Snapshot of upstream SQLite check-in 5a877221
[sqlcipher.git] / tool / lemon.c
blob8dcf65179fd03ddeda74a5601d2ecc148a45a98f
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 author of this program disclaims copyright.
8 */
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <stdlib.h>
14 #include <assert.h>
16 #define ISSPACE(X) isspace((unsigned char)(X))
17 #define ISDIGIT(X) isdigit((unsigned char)(X))
18 #define ISALNUM(X) isalnum((unsigned char)(X))
19 #define ISALPHA(X) isalpha((unsigned char)(X))
20 #define ISUPPER(X) isupper((unsigned char)(X))
21 #define ISLOWER(X) islower((unsigned char)(X))
24 #ifndef __WIN32__
25 # if defined(_WIN32) || defined(WIN32)
26 # define __WIN32__
27 # endif
28 #endif
30 #ifdef __WIN32__
31 #ifdef __cplusplus
32 extern "C" {
33 #endif
34 extern int access(const char *path, int mode);
35 #ifdef __cplusplus
37 #endif
38 #else
39 #include <unistd.h>
40 #endif
42 /* #define PRIVATE static */
43 #define PRIVATE
45 #ifdef TEST
46 #define MAXRHS 5 /* Set low to exercise exception code */
47 #else
48 #define MAXRHS 1000
49 #endif
51 extern void memory_error();
52 static int showPrecedenceConflict = 0;
53 static char *msort(char*,char**,int(*)(const char*,const char*));
56 ** Compilers are getting increasingly pedantic about type conversions
57 ** as C evolves ever closer to Ada.... To work around the latest problems
58 ** we have to define the following variant of strlen().
60 #define lemonStrlen(X) ((int)strlen(X))
63 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
64 ** saying they are unsafe. So we define our own versions of those routines too.
66 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
67 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
68 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
69 ** buffer, making sure the buffer is always zero-terminated.
71 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
72 ** a few simply conversions:
74 ** %d
75 ** %s
76 ** %.*s
79 static void lemon_addtext(
80 char *zBuf, /* The buffer to which text is added */
81 int *pnUsed, /* Slots of the buffer used so far */
82 const char *zIn, /* Text to add */
83 int nIn, /* Bytes of text to add. -1 to use strlen() */
84 int iWidth /* Field width. Negative to left justify */
86 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
87 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
88 if( nIn==0 ) return;
89 memcpy(&zBuf[*pnUsed], zIn, nIn);
90 *pnUsed += nIn;
91 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
92 zBuf[*pnUsed] = 0;
94 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
95 int i, j, k, c;
96 int nUsed = 0;
97 const char *z;
98 char zTemp[50];
99 str[0] = 0;
100 for(i=j=0; (c = zFormat[i])!=0; i++){
101 if( c=='%' ){
102 int iWidth = 0;
103 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
104 c = zFormat[++i];
105 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
106 if( c=='-' ) i++;
107 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
108 if( c=='-' ) iWidth = -iWidth;
109 c = zFormat[i];
111 if( c=='d' ){
112 int v = va_arg(ap, int);
113 if( v<0 ){
114 lemon_addtext(str, &nUsed, "-", 1, iWidth);
115 v = -v;
116 }else if( v==0 ){
117 lemon_addtext(str, &nUsed, "0", 1, iWidth);
119 k = 0;
120 while( v>0 ){
121 k++;
122 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
123 v /= 10;
125 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
126 }else if( c=='s' ){
127 z = va_arg(ap, const char*);
128 lemon_addtext(str, &nUsed, z, -1, iWidth);
129 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
130 i += 2;
131 k = va_arg(ap, int);
132 z = va_arg(ap, const char*);
133 lemon_addtext(str, &nUsed, z, k, iWidth);
134 }else if( c=='%' ){
135 lemon_addtext(str, &nUsed, "%", 1, 0);
136 }else{
137 fprintf(stderr, "illegal format\n");
138 exit(1);
140 j = i+1;
143 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
144 return nUsed;
146 static int lemon_sprintf(char *str, const char *format, ...){
147 va_list ap;
148 int rc;
149 va_start(ap, format);
150 rc = lemon_vsprintf(str, format, ap);
151 va_end(ap);
152 return rc;
154 static void lemon_strcpy(char *dest, const char *src){
155 while( (*(dest++) = *(src++))!=0 ){}
157 static void lemon_strcat(char *dest, const char *src){
158 while( *dest ) dest++;
159 lemon_strcpy(dest, src);
163 /* a few forward declarations... */
164 struct rule;
165 struct lemon;
166 struct action;
168 static struct action *Action_new(void);
169 static struct action *Action_sort(struct action *);
171 /********** From the file "build.h" ************************************/
172 void FindRulePrecedences(struct lemon*);
173 void FindFirstSets(struct lemon*);
174 void FindStates(struct lemon*);
175 void FindLinks(struct lemon*);
176 void FindFollowSets(struct lemon*);
177 void FindActions(struct lemon*);
179 /********* From the file "configlist.h" *********************************/
180 void Configlist_init(void);
181 struct config *Configlist_add(struct rule *, int);
182 struct config *Configlist_addbasis(struct rule *, int);
183 void Configlist_closure(struct lemon *);
184 void Configlist_sort(void);
185 void Configlist_sortbasis(void);
186 struct config *Configlist_return(void);
187 struct config *Configlist_basis(void);
188 void Configlist_eat(struct config *);
189 void Configlist_reset(void);
191 /********* From the file "error.h" ***************************************/
192 void ErrorMsg(const char *, int,const char *, ...);
194 /****** From the file "option.h" ******************************************/
195 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
196 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
197 struct s_options {
198 enum option_type type;
199 const char *label;
200 char *arg;
201 const char *message;
203 int OptInit(char**,struct s_options*,FILE*);
204 int OptNArgs(void);
205 char *OptArg(int);
206 void OptErr(int);
207 void OptPrint(void);
209 /******** From the file "parse.h" *****************************************/
210 void Parse(struct lemon *lemp);
212 /********* From the file "plink.h" ***************************************/
213 struct plink *Plink_new(void);
214 void Plink_add(struct plink **, struct config *);
215 void Plink_copy(struct plink **, struct plink *);
216 void Plink_delete(struct plink *);
218 /********** From the file "report.h" *************************************/
219 void Reprint(struct lemon *);
220 void ReportOutput(struct lemon *);
221 void ReportTable(struct lemon *, int, int);
222 void ReportHeader(struct lemon *);
223 void CompressTables(struct lemon *);
224 void ResortStates(struct lemon *);
226 /********** From the file "set.h" ****************************************/
227 void SetSize(int); /* All sets will be of size N */
228 char *SetNew(void); /* A new set for element 0..N */
229 void SetFree(char*); /* Deallocate a set */
230 int SetAdd(char*,int); /* Add element to a set */
231 int SetUnion(char *,char *); /* A <- A U B, thru element N */
232 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
234 /********** From the file "struct.h" *************************************/
236 ** Principal data structures for the LEMON parser generator.
239 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
241 /* Symbols (terminals and nonterminals) of the grammar are stored
242 ** in the following: */
243 enum symbol_type {
244 TERMINAL,
245 NONTERMINAL,
246 MULTITERMINAL
248 enum e_assoc {
249 LEFT,
250 RIGHT,
251 NONE,
254 struct symbol {
255 const char *name; /* Name of the symbol */
256 int index; /* Index number for this symbol */
257 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
258 struct rule *rule; /* Linked list of rules of this (if an NT) */
259 struct symbol *fallback; /* fallback token in case this token doesn't parse */
260 int prec; /* Precedence if defined (-1 otherwise) */
261 enum e_assoc assoc; /* Associativity if precedence is defined */
262 char *firstset; /* First-set for all rules of this symbol */
263 Boolean lambda; /* True if NT and can generate an empty string */
264 int useCnt; /* Number of times used */
265 char *destructor; /* Code which executes whenever this symbol is
266 ** popped from the stack during error processing */
267 int destLineno; /* Line number for start of destructor. Set to
268 ** -1 for duplicate destructors. */
269 char *datatype; /* The data type of information held by this
270 ** object. Only used if type==NONTERMINAL */
271 int dtnum; /* The data type number. In the parser, the value
272 ** stack is a union. The .yy%d element of this
273 ** union is the correct data type for this object */
274 int bContent; /* True if this symbol ever carries content - if
275 ** it is ever more than just syntax */
276 /* The following fields are used by MULTITERMINALs only */
277 int nsubsym; /* Number of constituent symbols in the MULTI */
278 struct symbol **subsym; /* Array of constituent symbols */
281 /* Each production rule in the grammar is stored in the following
282 ** structure. */
283 struct rule {
284 struct symbol *lhs; /* Left-hand side of the rule */
285 const char *lhsalias; /* Alias for the LHS (NULL if none) */
286 int lhsStart; /* True if left-hand side is the start symbol */
287 int ruleline; /* Line number for the rule */
288 int nrhs; /* Number of RHS symbols */
289 struct symbol **rhs; /* The RHS symbols */
290 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
291 int line; /* Line number at which code begins */
292 const char *code; /* The code executed when this rule is reduced */
293 const char *codePrefix; /* Setup code before code[] above */
294 const char *codeSuffix; /* Breakdown code after code[] above */
295 struct symbol *precsym; /* Precedence symbol for this rule */
296 int index; /* An index number for this rule */
297 int iRule; /* Rule number as used in the generated tables */
298 Boolean noCode; /* True if this rule has no associated C code */
299 Boolean codeEmitted; /* True if the code has been emitted already */
300 Boolean canReduce; /* True if this rule is ever reduced */
301 Boolean doesReduce; /* Reduce actions occur after optimization */
302 Boolean neverReduce; /* Reduce is theoretically possible, but prevented
303 ** by actions or other outside implementation */
304 struct rule *nextlhs; /* Next rule with the same LHS */
305 struct rule *next; /* Next rule in the global list */
308 /* A configuration is a production rule of the grammar together with
309 ** a mark (dot) showing how much of that rule has been processed so far.
310 ** Configurations also contain a follow-set which is a list of terminal
311 ** symbols which are allowed to immediately follow the end of the rule.
312 ** Every configuration is recorded as an instance of the following: */
313 enum cfgstatus {
314 COMPLETE,
315 INCOMPLETE
317 struct config {
318 struct rule *rp; /* The rule upon which the configuration is based */
319 int dot; /* The parse point */
320 char *fws; /* Follow-set for this configuration only */
321 struct plink *fplp; /* Follow-set forward propagation links */
322 struct plink *bplp; /* Follow-set backwards propagation links */
323 struct state *stp; /* Pointer to state which contains this */
324 enum cfgstatus status; /* used during followset and shift computations */
325 struct config *next; /* Next configuration in the state */
326 struct config *bp; /* The next basis configuration */
329 enum e_action {
330 SHIFT,
331 ACCEPT,
332 REDUCE,
333 ERROR,
334 SSCONFLICT, /* A shift/shift conflict */
335 SRCONFLICT, /* Was a reduce, but part of a conflict */
336 RRCONFLICT, /* Was a reduce, but part of a conflict */
337 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
338 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
339 NOT_USED, /* Deleted by compression */
340 SHIFTREDUCE /* Shift first, then reduce */
343 /* Every shift or reduce operation is stored as one of the following */
344 struct action {
345 struct symbol *sp; /* The look-ahead symbol */
346 enum e_action type;
347 union {
348 struct state *stp; /* The new state, if a shift */
349 struct rule *rp; /* The rule, if a reduce */
350 } x;
351 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
352 struct action *next; /* Next action for this state */
353 struct action *collide; /* Next action with the same hash */
356 /* Each state of the generated parser's finite state machine
357 ** is encoded as an instance of the following structure. */
358 struct state {
359 struct config *bp; /* The basis configurations for this state */
360 struct config *cfp; /* All configurations in this set */
361 int statenum; /* Sequential number for this state */
362 struct action *ap; /* List of actions for this state */
363 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
364 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
365 int iDfltReduce; /* Default action is to REDUCE by this rule */
366 struct rule *pDfltReduce;/* The default REDUCE rule. */
367 int autoReduce; /* True if this is an auto-reduce state */
369 #define NO_OFFSET (-2147483647)
371 /* A followset propagation link indicates that the contents of one
372 ** configuration followset should be propagated to another whenever
373 ** the first changes. */
374 struct plink {
375 struct config *cfp; /* The configuration to which linked */
376 struct plink *next; /* The next propagate link */
379 /* The state vector for the entire parser generator is recorded as
380 ** follows. (LEMON uses no global variables and makes little use of
381 ** static variables. Fields in the following structure can be thought
382 ** of as begin global variables in the program.) */
383 struct lemon {
384 struct state **sorted; /* Table of states sorted by state number */
385 struct rule *rule; /* List of all rules */
386 struct rule *startRule; /* First rule */
387 int nstate; /* Number of states */
388 int nxstate; /* nstate with tail degenerate states removed */
389 int nrule; /* Number of rules */
390 int nruleWithAction; /* Number of rules with actions */
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 *ctx; /* Declaration of 2nd argument to constructor */
406 char *tokentype; /* Type of terminal symbols in the parser stack */
407 char *vartype; /* The default type of non-terminal symbols */
408 char *start; /* Name of the start symbol for the grammar */
409 char *stacksize; /* Size of the parser stack */
410 char *include; /* Code to put at the start of the C file */
411 char *error; /* Code to execute when an error is seen */
412 char *overflow; /* Code to execute on a stack overflow */
413 char *failure; /* Code to execute on parser failure */
414 char *accept; /* Code to execute when the parser excepts */
415 char *extracode; /* Code appended to the generated file */
416 char *tokendest; /* Code to execute to destroy token data */
417 char *vardest; /* Code for the default non-terminal destructor */
418 char *filename; /* Name of the input file */
419 char *outname; /* Name of the current output file */
420 char *tokenprefix; /* A prefix added to token names in the .h file */
421 int nconflict; /* Number of parsing conflicts */
422 int nactiontab; /* Number of entries in the yy_action[] table */
423 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
424 int tablesize; /* Total table size of all tables in bytes */
425 int basisflag; /* Print only basis configurations */
426 int has_fallback; /* True if any %fallback is seen in the grammar */
427 int nolinenosflag; /* True if #line statements should not be printed */
428 char *argv0; /* Name of the program */
431 #define MemoryCheck(X) if((X)==0){ \
432 extern void memory_error(); \
433 memory_error(); \
436 /**************** From the file "table.h" *********************************/
438 ** All code in this file has been automatically generated
439 ** from a specification in the file
440 ** "table.q"
441 ** by the associative array code building program "aagen".
442 ** Do not edit this file! Instead, edit the specification
443 ** file, then rerun aagen.
446 ** Code for processing tables in the LEMON parser generator.
448 /* Routines for handling a strings */
450 const char *Strsafe(const char *);
452 void Strsafe_init(void);
453 int Strsafe_insert(const char *);
454 const char *Strsafe_find(const char *);
456 /* Routines for handling symbols of the grammar */
458 struct symbol *Symbol_new(const char *);
459 int Symbolcmpp(const void *, const void *);
460 void Symbol_init(void);
461 int Symbol_insert(struct symbol *, const char *);
462 struct symbol *Symbol_find(const char *);
463 struct symbol *Symbol_Nth(int);
464 int Symbol_count(void);
465 struct symbol **Symbol_arrayof(void);
467 /* Routines to manage the state table */
469 int Configcmp(const char *, const char *);
470 struct state *State_new(void);
471 void State_init(void);
472 int State_insert(struct state *, struct config *);
473 struct state *State_find(struct config *);
474 struct state **State_arrayof(void);
476 /* Routines used for efficiency in Configlist_add */
478 void Configtable_init(void);
479 int Configtable_insert(struct config *);
480 struct config *Configtable_find(struct config *);
481 void Configtable_clear(int(*)(struct config *));
483 /****************** From the file "action.c" *******************************/
485 ** Routines processing parser actions in the LEMON parser generator.
488 /* Allocate a new parser action */
489 static struct action *Action_new(void){
490 static struct action *actionfreelist = 0;
491 struct action *newaction;
493 if( actionfreelist==0 ){
494 int i;
495 int amt = 100;
496 actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
497 if( actionfreelist==0 ){
498 fprintf(stderr,"Unable to allocate memory for a new parser action.");
499 exit(1);
501 for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
502 actionfreelist[amt-1].next = 0;
504 newaction = actionfreelist;
505 actionfreelist = actionfreelist->next;
506 return newaction;
509 /* Compare two actions for sorting purposes. Return negative, zero, or
510 ** positive if the first action is less than, equal to, or greater than
511 ** the first
513 static int actioncmp(
514 struct action *ap1,
515 struct action *ap2
517 int rc;
518 rc = ap1->sp->index - ap2->sp->index;
519 if( rc==0 ){
520 rc = (int)ap1->type - (int)ap2->type;
522 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
523 rc = ap1->x.rp->index - ap2->x.rp->index;
525 if( rc==0 ){
526 rc = (int) (ap2 - ap1);
528 return rc;
531 /* Sort parser actions */
532 static struct action *Action_sort(
533 struct action *ap
535 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
536 (int(*)(const char*,const char*))actioncmp);
537 return ap;
540 void Action_add(
541 struct action **app,
542 enum e_action type,
543 struct symbol *sp,
544 char *arg
546 struct action *newaction;
547 newaction = Action_new();
548 newaction->next = *app;
549 *app = newaction;
550 newaction->type = type;
551 newaction->sp = sp;
552 newaction->spOpt = 0;
553 if( type==SHIFT ){
554 newaction->x.stp = (struct state *)arg;
555 }else{
556 newaction->x.rp = (struct rule *)arg;
559 /********************** New code to implement the "acttab" module ***********/
561 ** This module implements routines use to construct the yy_action[] table.
565 ** The state of the yy_action table under construction is an instance of
566 ** the following structure.
568 ** The yy_action table maps the pair (state_number, lookahead) into an
569 ** action_number. The table is an array of integers pairs. The state_number
570 ** determines an initial offset into the yy_action array. The lookahead
571 ** value is then added to this initial offset to get an index X into the
572 ** yy_action array. If the aAction[X].lookahead equals the value of the
573 ** of the lookahead input, then the value of the action_number output is
574 ** aAction[X].action. If the lookaheads do not match then the
575 ** default action for the state_number is returned.
577 ** All actions associated with a single state_number are first entered
578 ** into aLookahead[] using multiple calls to acttab_action(). Then the
579 ** actions for that single state_number are placed into the aAction[]
580 ** array with a single call to acttab_insert(). The acttab_insert() call
581 ** also resets the aLookahead[] array in preparation for the next
582 ** state number.
584 struct lookahead_action {
585 int lookahead; /* Value of the lookahead token */
586 int action; /* Action to take on the given lookahead */
588 typedef struct acttab acttab;
589 struct acttab {
590 int nAction; /* Number of used slots in aAction[] */
591 int nActionAlloc; /* Slots allocated for aAction[] */
592 struct lookahead_action
593 *aAction, /* The yy_action[] table under construction */
594 *aLookahead; /* A single new transaction set */
595 int mnLookahead; /* Minimum aLookahead[].lookahead */
596 int mnAction; /* Action associated with mnLookahead */
597 int mxLookahead; /* Maximum aLookahead[].lookahead */
598 int nLookahead; /* Used slots in aLookahead[] */
599 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
600 int nterminal; /* Number of terminal symbols */
601 int nsymbol; /* total number of symbols */
604 /* Return the number of entries in the yy_action table */
605 #define acttab_lookahead_size(X) ((X)->nAction)
607 /* The value for the N-th entry in yy_action */
608 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
610 /* The value for the N-th entry in yy_lookahead */
611 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
613 /* Free all memory associated with the given acttab */
614 void acttab_free(acttab *p){
615 free( p->aAction );
616 free( p->aLookahead );
617 free( p );
620 /* Allocate a new acttab structure */
621 acttab *acttab_alloc(int nsymbol, int nterminal){
622 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
623 if( p==0 ){
624 fprintf(stderr,"Unable to allocate memory for a new acttab.");
625 exit(1);
627 memset(p, 0, sizeof(*p));
628 p->nsymbol = nsymbol;
629 p->nterminal = nterminal;
630 return p;
633 /* Add a new action to the current transaction set.
635 ** This routine is called once for each lookahead for a particular
636 ** state.
638 void acttab_action(acttab *p, int lookahead, int action){
639 if( p->nLookahead>=p->nLookaheadAlloc ){
640 p->nLookaheadAlloc += 25;
641 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
642 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
643 if( p->aLookahead==0 ){
644 fprintf(stderr,"malloc failed\n");
645 exit(1);
648 if( p->nLookahead==0 ){
649 p->mxLookahead = lookahead;
650 p->mnLookahead = lookahead;
651 p->mnAction = action;
652 }else{
653 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
654 if( p->mnLookahead>lookahead ){
655 p->mnLookahead = lookahead;
656 p->mnAction = action;
659 p->aLookahead[p->nLookahead].lookahead = lookahead;
660 p->aLookahead[p->nLookahead].action = action;
661 p->nLookahead++;
665 ** Add the transaction set built up with prior calls to acttab_action()
666 ** into the current action table. Then reset the transaction set back
667 ** to an empty set in preparation for a new round of acttab_action() calls.
669 ** Return the offset into the action table of the new transaction.
671 ** If the makeItSafe parameter is true, then the offset is chosen so that
672 ** it is impossible to overread the yy_lookaside[] table regardless of
673 ** the lookaside token. This is done for the terminal symbols, as they
674 ** come from external inputs and can contain syntax errors. When makeItSafe
675 ** is false, there is more flexibility in selecting offsets, resulting in
676 ** a smaller table. For non-terminal symbols, which are never syntax errors,
677 ** makeItSafe can be false.
679 int acttab_insert(acttab *p, int makeItSafe){
680 int i, j, k, n, end;
681 assert( p->nLookahead>0 );
683 /* Make sure we have enough space to hold the expanded action table
684 ** in the worst case. The worst case occurs if the transaction set
685 ** must be appended to the current action table
687 n = p->nsymbol + 1;
688 if( p->nAction + n >= p->nActionAlloc ){
689 int oldAlloc = p->nActionAlloc;
690 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
691 p->aAction = (struct lookahead_action *) realloc( p->aAction,
692 sizeof(p->aAction[0])*p->nActionAlloc);
693 if( p->aAction==0 ){
694 fprintf(stderr,"malloc failed\n");
695 exit(1);
697 for(i=oldAlloc; i<p->nActionAlloc; i++){
698 p->aAction[i].lookahead = -1;
699 p->aAction[i].action = -1;
703 /* Scan the existing action table looking for an offset that is a
704 ** duplicate of the current transaction set. Fall out of the loop
705 ** if and when the duplicate is found.
707 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
709 end = makeItSafe ? p->mnLookahead : 0;
710 for(i=p->nAction-1; i>=end; i--){
711 if( p->aAction[i].lookahead==p->mnLookahead ){
712 /* All lookaheads and actions in the aLookahead[] transaction
713 ** must match against the candidate aAction[i] entry. */
714 if( p->aAction[i].action!=p->mnAction ) continue;
715 for(j=0; j<p->nLookahead; j++){
716 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
717 if( k<0 || k>=p->nAction ) break;
718 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
719 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
721 if( j<p->nLookahead ) continue;
723 /* No possible lookahead value that is not in the aLookahead[]
724 ** transaction is allowed to match aAction[i] */
725 n = 0;
726 for(j=0; j<p->nAction; j++){
727 if( p->aAction[j].lookahead<0 ) continue;
728 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
730 if( n==p->nLookahead ){
731 break; /* An exact match is found at offset i */
736 /* If no existing offsets exactly match the current transaction, find an
737 ** an empty offset in the aAction[] table in which we can add the
738 ** aLookahead[] transaction.
740 if( i<end ){
741 /* Look for holes in the aAction[] table that fit the current
742 ** aLookahead[] transaction. Leave i set to the offset of the hole.
743 ** If no holes are found, i is left at p->nAction, which means the
744 ** transaction will be appended. */
745 i = makeItSafe ? p->mnLookahead : 0;
746 for(; i<p->nActionAlloc - p->mxLookahead; i++){
747 if( p->aAction[i].lookahead<0 ){
748 for(j=0; j<p->nLookahead; j++){
749 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
750 if( k<0 ) break;
751 if( p->aAction[k].lookahead>=0 ) break;
753 if( j<p->nLookahead ) continue;
754 for(j=0; j<p->nAction; j++){
755 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
757 if( j==p->nAction ){
758 break; /* Fits in empty slots */
763 /* Insert transaction set at index i. */
764 #if 0
765 printf("Acttab:");
766 for(j=0; j<p->nLookahead; j++){
767 printf(" %d", p->aLookahead[j].lookahead);
769 printf(" inserted at %d\n", i);
770 #endif
771 for(j=0; j<p->nLookahead; j++){
772 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
773 p->aAction[k] = p->aLookahead[j];
774 if( k>=p->nAction ) p->nAction = k+1;
776 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
777 p->nLookahead = 0;
779 /* Return the offset that is added to the lookahead in order to get the
780 ** index into yy_action of the action */
781 return i - p->mnLookahead;
785 ** Return the size of the action table without the trailing syntax error
786 ** entries.
788 int acttab_action_size(acttab *p){
789 int n = p->nAction;
790 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
791 return n;
794 /********************** From the file "build.c" *****************************/
796 ** Routines to construction the finite state machine for the LEMON
797 ** parser generator.
800 /* Find a precedence symbol of every rule in the grammar.
802 ** Those rules which have a precedence symbol coded in the input
803 ** grammar using the "[symbol]" construct will already have the
804 ** rp->precsym field filled. Other rules take as their precedence
805 ** symbol the first RHS symbol with a defined precedence. If there
806 ** are not RHS symbols with a defined precedence, the precedence
807 ** symbol field is left blank.
809 void FindRulePrecedences(struct lemon *xp)
811 struct rule *rp;
812 for(rp=xp->rule; rp; rp=rp->next){
813 if( rp->precsym==0 ){
814 int i, j;
815 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
816 struct symbol *sp = rp->rhs[i];
817 if( sp->type==MULTITERMINAL ){
818 for(j=0; j<sp->nsubsym; j++){
819 if( sp->subsym[j]->prec>=0 ){
820 rp->precsym = sp->subsym[j];
821 break;
824 }else if( sp->prec>=0 ){
825 rp->precsym = rp->rhs[i];
830 return;
833 /* Find all nonterminals which will generate the empty string.
834 ** Then go back and compute the first sets of every nonterminal.
835 ** The first set is the set of all terminal symbols which can begin
836 ** a string generated by that nonterminal.
838 void FindFirstSets(struct lemon *lemp)
840 int i, j;
841 struct rule *rp;
842 int progress;
844 for(i=0; i<lemp->nsymbol; i++){
845 lemp->symbols[i]->lambda = LEMON_FALSE;
847 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
848 lemp->symbols[i]->firstset = SetNew();
851 /* First compute all lambdas */
853 progress = 0;
854 for(rp=lemp->rule; rp; rp=rp->next){
855 if( rp->lhs->lambda ) continue;
856 for(i=0; i<rp->nrhs; i++){
857 struct symbol *sp = rp->rhs[i];
858 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
859 if( sp->lambda==LEMON_FALSE ) break;
861 if( i==rp->nrhs ){
862 rp->lhs->lambda = LEMON_TRUE;
863 progress = 1;
866 }while( progress );
868 /* Now compute all first sets */
870 struct symbol *s1, *s2;
871 progress = 0;
872 for(rp=lemp->rule; rp; rp=rp->next){
873 s1 = rp->lhs;
874 for(i=0; i<rp->nrhs; i++){
875 s2 = rp->rhs[i];
876 if( s2->type==TERMINAL ){
877 progress += SetAdd(s1->firstset,s2->index);
878 break;
879 }else if( s2->type==MULTITERMINAL ){
880 for(j=0; j<s2->nsubsym; j++){
881 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
883 break;
884 }else if( s1==s2 ){
885 if( s1->lambda==LEMON_FALSE ) break;
886 }else{
887 progress += SetUnion(s1->firstset,s2->firstset);
888 if( s2->lambda==LEMON_FALSE ) break;
892 }while( progress );
893 return;
896 /* Compute all LR(0) states for the grammar. Links
897 ** are added to between some states so that the LR(1) follow sets
898 ** can be computed later.
900 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
901 void FindStates(struct lemon *lemp)
903 struct symbol *sp;
904 struct rule *rp;
906 Configlist_init();
908 /* Find the start symbol */
909 if( lemp->start ){
910 sp = Symbol_find(lemp->start);
911 if( sp==0 ){
912 ErrorMsg(lemp->filename,0,
913 "The specified start symbol \"%s\" is not "
914 "in a nonterminal of the grammar. \"%s\" will be used as the start "
915 "symbol instead.",lemp->start,lemp->startRule->lhs->name);
916 lemp->errorcnt++;
917 sp = lemp->startRule->lhs;
919 }else{
920 sp = lemp->startRule->lhs;
923 /* Make sure the start symbol doesn't occur on the right-hand side of
924 ** any rule. Report an error if it does. (YACC would generate a new
925 ** start symbol in this case.) */
926 for(rp=lemp->rule; rp; rp=rp->next){
927 int i;
928 for(i=0; i<rp->nrhs; i++){
929 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
930 ErrorMsg(lemp->filename,0,
931 "The start symbol \"%s\" occurs on the "
932 "right-hand side of a rule. This will result in a parser which "
933 "does not work properly.",sp->name);
934 lemp->errorcnt++;
939 /* The basis configuration set for the first state
940 ** is all rules which have the start symbol as their
941 ** left-hand side */
942 for(rp=sp->rule; rp; rp=rp->nextlhs){
943 struct config *newcfp;
944 rp->lhsStart = 1;
945 newcfp = Configlist_addbasis(rp,0);
946 SetAdd(newcfp->fws,0);
949 /* Compute the first state. All other states will be
950 ** computed automatically during the computation of the first one.
951 ** The returned pointer to the first state is not used. */
952 (void)getstate(lemp);
953 return;
956 /* Return a pointer to a state which is described by the configuration
957 ** list which has been built from calls to Configlist_add.
959 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
960 PRIVATE struct state *getstate(struct lemon *lemp)
962 struct config *cfp, *bp;
963 struct state *stp;
965 /* Extract the sorted basis of the new state. The basis was constructed
966 ** by prior calls to "Configlist_addbasis()". */
967 Configlist_sortbasis();
968 bp = Configlist_basis();
970 /* Get a state with the same basis */
971 stp = State_find(bp);
972 if( stp ){
973 /* A state with the same basis already exists! Copy all the follow-set
974 ** propagation links from the state under construction into the
975 ** preexisting state, then return a pointer to the preexisting state */
976 struct config *x, *y;
977 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
978 Plink_copy(&y->bplp,x->bplp);
979 Plink_delete(x->fplp);
980 x->fplp = x->bplp = 0;
982 cfp = Configlist_return();
983 Configlist_eat(cfp);
984 }else{
985 /* This really is a new state. Construct all the details */
986 Configlist_closure(lemp); /* Compute the configuration closure */
987 Configlist_sort(); /* Sort the configuration closure */
988 cfp = Configlist_return(); /* Get a pointer to the config list */
989 stp = State_new(); /* A new state structure */
990 MemoryCheck(stp);
991 stp->bp = bp; /* Remember the configuration basis */
992 stp->cfp = cfp; /* Remember the configuration closure */
993 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
994 stp->ap = 0; /* No actions, yet. */
995 State_insert(stp,stp->bp); /* Add to the state table */
996 buildshifts(lemp,stp); /* Recursively compute successor states */
998 return stp;
1002 ** Return true if two symbols are the same.
1004 int same_symbol(struct symbol *a, struct symbol *b)
1006 int i;
1007 if( a==b ) return 1;
1008 if( a->type!=MULTITERMINAL ) return 0;
1009 if( b->type!=MULTITERMINAL ) return 0;
1010 if( a->nsubsym!=b->nsubsym ) return 0;
1011 for(i=0; i<a->nsubsym; i++){
1012 if( a->subsym[i]!=b->subsym[i] ) return 0;
1014 return 1;
1017 /* Construct all successor states to the given state. A "successor"
1018 ** state is any state which can be reached by a shift action.
1020 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
1022 struct config *cfp; /* For looping thru the config closure of "stp" */
1023 struct config *bcfp; /* For the inner loop on config closure of "stp" */
1024 struct config *newcfg; /* */
1025 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1026 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1027 struct state *newstp; /* A pointer to a successor state */
1029 /* Each configuration becomes complete after it contibutes to a successor
1030 ** state. Initially, all configurations are incomplete */
1031 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1033 /* Loop through all configurations of the state "stp" */
1034 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1035 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1036 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1037 Configlist_reset(); /* Reset the new config set */
1038 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1040 /* For every configuration in the state "stp" which has the symbol "sp"
1041 ** following its dot, add the same configuration to the basis set under
1042 ** construction but with the dot shifted one symbol to the right. */
1043 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1044 if( bcfp->status==COMPLETE ) continue; /* Already used */
1045 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1046 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
1047 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
1048 bcfp->status = COMPLETE; /* Mark this config as used */
1049 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1050 Plink_add(&newcfg->bplp,bcfp);
1053 /* Get a pointer to the state described by the basis configuration set
1054 ** constructed in the preceding loop */
1055 newstp = getstate(lemp);
1057 /* The state "newstp" is reached from the state "stp" by a shift action
1058 ** on the symbol "sp" */
1059 if( sp->type==MULTITERMINAL ){
1060 int i;
1061 for(i=0; i<sp->nsubsym; i++){
1062 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1064 }else{
1065 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1071 ** Construct the propagation links
1073 void FindLinks(struct lemon *lemp)
1075 int i;
1076 struct config *cfp, *other;
1077 struct state *stp;
1078 struct plink *plp;
1080 /* Housekeeping detail:
1081 ** Add to every propagate link a pointer back to the state to
1082 ** which the link is attached. */
1083 for(i=0; i<lemp->nstate; i++){
1084 stp = lemp->sorted[i];
1085 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1086 cfp->stp = stp;
1090 /* Convert all backlinks into forward links. Only the forward
1091 ** links are used in the follow-set computation. */
1092 for(i=0; i<lemp->nstate; i++){
1093 stp = lemp->sorted[i];
1094 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1095 for(plp=cfp->bplp; plp; plp=plp->next){
1096 other = plp->cfp;
1097 Plink_add(&other->fplp,cfp);
1103 /* Compute all followsets.
1105 ** A followset is the set of all symbols which can come immediately
1106 ** after a configuration.
1108 void FindFollowSets(struct lemon *lemp)
1110 int i;
1111 struct config *cfp;
1112 struct plink *plp;
1113 int progress;
1114 int change;
1116 for(i=0; i<lemp->nstate; i++){
1117 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1118 cfp->status = INCOMPLETE;
1123 progress = 0;
1124 for(i=0; i<lemp->nstate; i++){
1125 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1126 if( cfp->status==COMPLETE ) continue;
1127 for(plp=cfp->fplp; plp; plp=plp->next){
1128 change = SetUnion(plp->cfp->fws,cfp->fws);
1129 if( change ){
1130 plp->cfp->status = INCOMPLETE;
1131 progress = 1;
1134 cfp->status = COMPLETE;
1137 }while( progress );
1140 static int resolve_conflict(struct action *,struct action *);
1142 /* Compute the reduce actions, and resolve conflicts.
1144 void FindActions(struct lemon *lemp)
1146 int i,j;
1147 struct config *cfp;
1148 struct state *stp;
1149 struct symbol *sp;
1150 struct rule *rp;
1152 /* Add all of the reduce actions
1153 ** A reduce action is added for each element of the followset of
1154 ** a configuration which has its dot at the extreme right.
1156 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1157 stp = lemp->sorted[i];
1158 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1159 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1160 for(j=0; j<lemp->nterminal; j++){
1161 if( SetFind(cfp->fws,j) ){
1162 /* Add a reduce action to the state "stp" which will reduce by the
1163 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1164 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
1171 /* Add the accepting token */
1172 if( lemp->start ){
1173 sp = Symbol_find(lemp->start);
1174 if( sp==0 ) sp = lemp->startRule->lhs;
1175 }else{
1176 sp = lemp->startRule->lhs;
1178 /* Add to the first state (which is always the starting state of the
1179 ** finite state machine) an action to ACCEPT if the lookahead is the
1180 ** start nonterminal. */
1181 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1183 /* Resolve conflicts */
1184 for(i=0; i<lemp->nstate; i++){
1185 struct action *ap, *nap;
1186 stp = lemp->sorted[i];
1187 /* assert( stp->ap ); */
1188 stp->ap = Action_sort(stp->ap);
1189 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1190 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1191 /* The two actions "ap" and "nap" have the same lookahead.
1192 ** Figure out which one should be used */
1193 lemp->nconflict += resolve_conflict(ap,nap);
1198 /* Report an error for each rule that can never be reduced. */
1199 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
1200 for(i=0; i<lemp->nstate; i++){
1201 struct action *ap;
1202 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1203 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
1206 for(rp=lemp->rule; rp; rp=rp->next){
1207 if( rp->canReduce ) continue;
1208 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1209 lemp->errorcnt++;
1213 /* Resolve a conflict between the two given actions. If the
1214 ** conflict can't be resolved, return non-zero.
1216 ** NO LONGER TRUE:
1217 ** To resolve a conflict, first look to see if either action
1218 ** is on an error rule. In that case, take the action which
1219 ** is not associated with the error rule. If neither or both
1220 ** actions are associated with an error rule, then try to
1221 ** use precedence to resolve the conflict.
1223 ** If either action is a SHIFT, then it must be apx. This
1224 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1226 static int resolve_conflict(
1227 struct action *apx,
1228 struct action *apy
1230 struct symbol *spx, *spy;
1231 int errcnt = 0;
1232 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1233 if( apx->type==SHIFT && apy->type==SHIFT ){
1234 apy->type = SSCONFLICT;
1235 errcnt++;
1237 if( apx->type==SHIFT && apy->type==REDUCE ){
1238 spx = apx->sp;
1239 spy = apy->x.rp->precsym;
1240 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1241 /* Not enough precedence information. */
1242 apy->type = SRCONFLICT;
1243 errcnt++;
1244 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
1245 apy->type = RD_RESOLVED;
1246 }else if( spx->prec<spy->prec ){
1247 apx->type = SH_RESOLVED;
1248 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1249 apy->type = RD_RESOLVED; /* associativity */
1250 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1251 apx->type = SH_RESOLVED;
1252 }else{
1253 assert( spx->prec==spy->prec && spx->assoc==NONE );
1254 apx->type = ERROR;
1256 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1257 spx = apx->x.rp->precsym;
1258 spy = apy->x.rp->precsym;
1259 if( spx==0 || spy==0 || spx->prec<0 ||
1260 spy->prec<0 || spx->prec==spy->prec ){
1261 apy->type = RRCONFLICT;
1262 errcnt++;
1263 }else if( spx->prec>spy->prec ){
1264 apy->type = RD_RESOLVED;
1265 }else if( spx->prec<spy->prec ){
1266 apx->type = RD_RESOLVED;
1268 }else{
1269 assert(
1270 apx->type==SH_RESOLVED ||
1271 apx->type==RD_RESOLVED ||
1272 apx->type==SSCONFLICT ||
1273 apx->type==SRCONFLICT ||
1274 apx->type==RRCONFLICT ||
1275 apy->type==SH_RESOLVED ||
1276 apy->type==RD_RESOLVED ||
1277 apy->type==SSCONFLICT ||
1278 apy->type==SRCONFLICT ||
1279 apy->type==RRCONFLICT
1281 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1282 ** REDUCEs on the list. If we reach this point it must be because
1283 ** the parser conflict had already been resolved. */
1285 return errcnt;
1287 /********************* From the file "configlist.c" *************************/
1289 ** Routines to processing a configuration list and building a state
1290 ** in the LEMON parser generator.
1293 static struct config *freelist = 0; /* List of free configurations */
1294 static struct config *current = 0; /* Top of list of configurations */
1295 static struct config **currentend = 0; /* Last on list of configs */
1296 static struct config *basis = 0; /* Top of list of basis configs */
1297 static struct config **basisend = 0; /* End of list of basis configs */
1299 /* Return a pointer to a new configuration */
1300 PRIVATE struct config *newconfig(void){
1301 struct config *newcfg;
1302 if( freelist==0 ){
1303 int i;
1304 int amt = 3;
1305 freelist = (struct config *)calloc( amt, sizeof(struct config) );
1306 if( freelist==0 ){
1307 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1308 exit(1);
1310 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1311 freelist[amt-1].next = 0;
1313 newcfg = freelist;
1314 freelist = freelist->next;
1315 return newcfg;
1318 /* The configuration "old" is no longer used */
1319 PRIVATE void deleteconfig(struct config *old)
1321 old->next = freelist;
1322 freelist = old;
1325 /* Initialized the configuration list builder */
1326 void Configlist_init(void){
1327 current = 0;
1328 currentend = &current;
1329 basis = 0;
1330 basisend = &basis;
1331 Configtable_init();
1332 return;
1335 /* Initialized the configuration list builder */
1336 void Configlist_reset(void){
1337 current = 0;
1338 currentend = &current;
1339 basis = 0;
1340 basisend = &basis;
1341 Configtable_clear(0);
1342 return;
1345 /* Add another configuration to the configuration list */
1346 struct config *Configlist_add(
1347 struct rule *rp, /* The rule */
1348 int dot /* Index into the RHS of the rule where the dot goes */
1350 struct config *cfp, model;
1352 assert( currentend!=0 );
1353 model.rp = rp;
1354 model.dot = dot;
1355 cfp = Configtable_find(&model);
1356 if( cfp==0 ){
1357 cfp = newconfig();
1358 cfp->rp = rp;
1359 cfp->dot = dot;
1360 cfp->fws = SetNew();
1361 cfp->stp = 0;
1362 cfp->fplp = cfp->bplp = 0;
1363 cfp->next = 0;
1364 cfp->bp = 0;
1365 *currentend = cfp;
1366 currentend = &cfp->next;
1367 Configtable_insert(cfp);
1369 return cfp;
1372 /* Add a basis configuration to the configuration list */
1373 struct config *Configlist_addbasis(struct rule *rp, int dot)
1375 struct config *cfp, model;
1377 assert( basisend!=0 );
1378 assert( currentend!=0 );
1379 model.rp = rp;
1380 model.dot = dot;
1381 cfp = Configtable_find(&model);
1382 if( cfp==0 ){
1383 cfp = newconfig();
1384 cfp->rp = rp;
1385 cfp->dot = dot;
1386 cfp->fws = SetNew();
1387 cfp->stp = 0;
1388 cfp->fplp = cfp->bplp = 0;
1389 cfp->next = 0;
1390 cfp->bp = 0;
1391 *currentend = cfp;
1392 currentend = &cfp->next;
1393 *basisend = cfp;
1394 basisend = &cfp->bp;
1395 Configtable_insert(cfp);
1397 return cfp;
1400 /* Compute the closure of the configuration list */
1401 void Configlist_closure(struct lemon *lemp)
1403 struct config *cfp, *newcfp;
1404 struct rule *rp, *newrp;
1405 struct symbol *sp, *xsp;
1406 int i, dot;
1408 assert( currentend!=0 );
1409 for(cfp=current; cfp; cfp=cfp->next){
1410 rp = cfp->rp;
1411 dot = cfp->dot;
1412 if( dot>=rp->nrhs ) continue;
1413 sp = rp->rhs[dot];
1414 if( sp->type==NONTERMINAL ){
1415 if( sp->rule==0 && sp!=lemp->errsym ){
1416 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1417 sp->name);
1418 lemp->errorcnt++;
1420 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1421 newcfp = Configlist_add(newrp,0);
1422 for(i=dot+1; i<rp->nrhs; i++){
1423 xsp = rp->rhs[i];
1424 if( xsp->type==TERMINAL ){
1425 SetAdd(newcfp->fws,xsp->index);
1426 break;
1427 }else if( xsp->type==MULTITERMINAL ){
1428 int k;
1429 for(k=0; k<xsp->nsubsym; k++){
1430 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1432 break;
1433 }else{
1434 SetUnion(newcfp->fws,xsp->firstset);
1435 if( xsp->lambda==LEMON_FALSE ) break;
1438 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1442 return;
1445 /* Sort the configuration list */
1446 void Configlist_sort(void){
1447 current = (struct config*)msort((char*)current,(char**)&(current->next),
1448 Configcmp);
1449 currentend = 0;
1450 return;
1453 /* Sort the basis configuration list */
1454 void Configlist_sortbasis(void){
1455 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1456 Configcmp);
1457 basisend = 0;
1458 return;
1461 /* Return a pointer to the head of the configuration list and
1462 ** reset the list */
1463 struct config *Configlist_return(void){
1464 struct config *old;
1465 old = current;
1466 current = 0;
1467 currentend = 0;
1468 return old;
1471 /* Return a pointer to the head of the configuration list and
1472 ** reset the list */
1473 struct config *Configlist_basis(void){
1474 struct config *old;
1475 old = basis;
1476 basis = 0;
1477 basisend = 0;
1478 return old;
1481 /* Free all elements of the given configuration list */
1482 void Configlist_eat(struct config *cfp)
1484 struct config *nextcfp;
1485 for(; cfp; cfp=nextcfp){
1486 nextcfp = cfp->next;
1487 assert( cfp->fplp==0 );
1488 assert( cfp->bplp==0 );
1489 if( cfp->fws ) SetFree(cfp->fws);
1490 deleteconfig(cfp);
1492 return;
1494 /***************** From the file "error.c" *********************************/
1496 ** Code for printing error message.
1499 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1500 va_list ap;
1501 fprintf(stderr, "%s:%d: ", filename, lineno);
1502 va_start(ap, format);
1503 vfprintf(stderr,format,ap);
1504 va_end(ap);
1505 fprintf(stderr, "\n");
1507 /**************** From the file "main.c" ************************************/
1509 ** Main program file for the LEMON parser generator.
1512 /* Report an out-of-memory condition and abort. This function
1513 ** is used mostly by the "MemoryCheck" macro in struct.h
1515 void memory_error(void){
1516 fprintf(stderr,"Out of memory. Aborting...\n");
1517 exit(1);
1520 static int nDefine = 0; /* Number of -D options on the command line */
1521 static char **azDefine = 0; /* Name of the -D macros */
1523 /* This routine is called with the argument to each -D command-line option.
1524 ** Add the macro defined to the azDefine array.
1526 static void handle_D_option(char *z){
1527 char **paz;
1528 nDefine++;
1529 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
1530 if( azDefine==0 ){
1531 fprintf(stderr,"out of memory\n");
1532 exit(1);
1534 paz = &azDefine[nDefine-1];
1535 *paz = (char *) malloc( lemonStrlen(z)+1 );
1536 if( *paz==0 ){
1537 fprintf(stderr,"out of memory\n");
1538 exit(1);
1540 lemon_strcpy(*paz, z);
1541 for(z=*paz; *z && *z!='='; z++){}
1542 *z = 0;
1545 /* Rember the name of the output directory
1547 static char *outputDir = NULL;
1548 static void handle_d_option(char *z){
1549 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1550 if( outputDir==0 ){
1551 fprintf(stderr,"out of memory\n");
1552 exit(1);
1554 lemon_strcpy(outputDir, z);
1557 static char *user_templatename = NULL;
1558 static void handle_T_option(char *z){
1559 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
1560 if( user_templatename==0 ){
1561 memory_error();
1563 lemon_strcpy(user_templatename, z);
1566 /* Merge together to lists of rules ordered by rule.iRule */
1567 static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1568 struct rule *pFirst = 0;
1569 struct rule **ppPrev = &pFirst;
1570 while( pA && pB ){
1571 if( pA->iRule<pB->iRule ){
1572 *ppPrev = pA;
1573 ppPrev = &pA->next;
1574 pA = pA->next;
1575 }else{
1576 *ppPrev = pB;
1577 ppPrev = &pB->next;
1578 pB = pB->next;
1581 if( pA ){
1582 *ppPrev = pA;
1583 }else{
1584 *ppPrev = pB;
1586 return pFirst;
1590 ** Sort a list of rules in order of increasing iRule value
1592 static struct rule *Rule_sort(struct rule *rp){
1593 int i;
1594 struct rule *pNext;
1595 struct rule *x[32];
1596 memset(x, 0, sizeof(x));
1597 while( rp ){
1598 pNext = rp->next;
1599 rp->next = 0;
1600 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1601 rp = Rule_merge(x[i], rp);
1602 x[i] = 0;
1604 x[i] = rp;
1605 rp = pNext;
1607 rp = 0;
1608 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1609 rp = Rule_merge(x[i], rp);
1611 return rp;
1614 /* forward reference */
1615 static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1617 /* Print a single line of the "Parser Stats" output
1619 static void stats_line(const char *zLabel, int iValue){
1620 int nLabel = lemonStrlen(zLabel);
1621 printf(" %s%.*s %5d\n", zLabel,
1622 35-nLabel, "................................",
1623 iValue);
1626 /* The main program. Parse the command line and do it... */
1627 int main(int argc, char **argv)
1629 static int version = 0;
1630 static int rpflag = 0;
1631 static int basisflag = 0;
1632 static int compress = 0;
1633 static int quiet = 0;
1634 static int statistics = 0;
1635 static int mhflag = 0;
1636 static int nolinenosflag = 0;
1637 static int noResort = 0;
1638 static int sqlFlag = 0;
1640 static struct s_options options[] = {
1641 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1642 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1643 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
1644 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
1645 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1646 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1647 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1648 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1649 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
1650 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1651 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1652 "Show conflicts resolved by precedence rules"},
1653 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1654 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
1655 {OPT_FLAG, "s", (char*)&statistics,
1656 "Print parser stats to standard output."},
1657 {OPT_FLAG, "S", (char*)&sqlFlag,
1658 "Generate the *.sql file describing the parser tables."},
1659 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1660 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1661 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1662 {OPT_FLAG,0,0,0}
1664 int i;
1665 int exitcode;
1666 struct lemon lem;
1667 struct rule *rp;
1669 OptInit(argv,options,stderr);
1670 if( version ){
1671 printf("Lemon version 1.0\n");
1672 exit(0);
1674 if( OptNArgs()!=1 ){
1675 fprintf(stderr,"Exactly one filename argument is required.\n");
1676 exit(1);
1678 memset(&lem, 0, sizeof(lem));
1679 lem.errorcnt = 0;
1681 /* Initialize the machine */
1682 Strsafe_init();
1683 Symbol_init();
1684 State_init();
1685 lem.argv0 = argv[0];
1686 lem.filename = OptArg(0);
1687 lem.basisflag = basisflag;
1688 lem.nolinenosflag = nolinenosflag;
1689 Symbol_new("$");
1691 /* Parse the input file */
1692 Parse(&lem);
1693 if( lem.errorcnt ) exit(lem.errorcnt);
1694 if( lem.nrule==0 ){
1695 fprintf(stderr,"Empty grammar.\n");
1696 exit(1);
1698 lem.errsym = Symbol_find("error");
1700 /* Count and index the symbols of the grammar */
1701 Symbol_new("{default}");
1702 lem.nsymbol = Symbol_count();
1703 lem.symbols = Symbol_arrayof();
1704 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1705 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1706 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1707 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1708 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1709 lem.nsymbol = i - 1;
1710 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
1711 lem.nterminal = i;
1713 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1714 ** reduce action C-code associated with them last, so that the switch()
1715 ** statement that selects reduction actions will have a smaller jump table.
1717 for(i=0, rp=lem.rule; rp; rp=rp->next){
1718 rp->iRule = rp->code ? i++ : -1;
1720 lem.nruleWithAction = i;
1721 for(rp=lem.rule; rp; rp=rp->next){
1722 if( rp->iRule<0 ) rp->iRule = i++;
1724 lem.startRule = lem.rule;
1725 lem.rule = Rule_sort(lem.rule);
1727 /* Generate a reprint of the grammar, if requested on the command line */
1728 if( rpflag ){
1729 Reprint(&lem);
1730 }else{
1731 /* Initialize the size for all follow and first sets */
1732 SetSize(lem.nterminal+1);
1734 /* Find the precedence for every production rule (that has one) */
1735 FindRulePrecedences(&lem);
1737 /* Compute the lambda-nonterminals and the first-sets for every
1738 ** nonterminal */
1739 FindFirstSets(&lem);
1741 /* Compute all LR(0) states. Also record follow-set propagation
1742 ** links so that the follow-set can be computed later */
1743 lem.nstate = 0;
1744 FindStates(&lem);
1745 lem.sorted = State_arrayof();
1747 /* Tie up loose ends on the propagation links */
1748 FindLinks(&lem);
1750 /* Compute the follow set of every reducible configuration */
1751 FindFollowSets(&lem);
1753 /* Compute the action tables */
1754 FindActions(&lem);
1756 /* Compress the action tables */
1757 if( compress==0 ) CompressTables(&lem);
1759 /* Reorder and renumber the states so that states with fewer choices
1760 ** occur at the end. This is an optimization that helps make the
1761 ** generated parser tables smaller. */
1762 if( noResort==0 ) ResortStates(&lem);
1764 /* Generate a report of the parser generated. (the "y.output" file) */
1765 if( !quiet ) ReportOutput(&lem);
1767 /* Generate the source code for the parser */
1768 ReportTable(&lem, mhflag, sqlFlag);
1770 /* Produce a header file for use by the scanner. (This step is
1771 ** omitted if the "-m" option is used because makeheaders will
1772 ** generate the file for us.) */
1773 if( !mhflag ) ReportHeader(&lem);
1775 if( statistics ){
1776 printf("Parser statistics:\n");
1777 stats_line("terminal symbols", lem.nterminal);
1778 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1779 stats_line("total symbols", lem.nsymbol);
1780 stats_line("rules", lem.nrule);
1781 stats_line("states", lem.nxstate);
1782 stats_line("conflicts", lem.nconflict);
1783 stats_line("action table entries", lem.nactiontab);
1784 stats_line("lookahead table entries", lem.nlookaheadtab);
1785 stats_line("total table size (bytes)", lem.tablesize);
1787 if( lem.nconflict > 0 ){
1788 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1791 /* return 0 on success, 1 on failure. */
1792 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
1793 exit(exitcode);
1794 return (exitcode);
1796 /******************** From the file "msort.c" *******************************/
1798 ** A generic merge-sort program.
1800 ** USAGE:
1801 ** Let "ptr" be a pointer to some structure which is at the head of
1802 ** a null-terminated list. Then to sort the list call:
1804 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1806 ** In the above, "cmpfnc" is a pointer to a function which compares
1807 ** two instances of the structure and returns an integer, as in
1808 ** strcmp. The second argument is a pointer to the pointer to the
1809 ** second element of the linked list. This address is used to compute
1810 ** the offset to the "next" field within the structure. The offset to
1811 ** the "next" field must be constant for all structures in the list.
1813 ** The function returns a new pointer which is the head of the list
1814 ** after sorting.
1816 ** ALGORITHM:
1817 ** Merge-sort.
1821 ** Return a pointer to the next structure in the linked list.
1823 #define NEXT(A) (*(char**)(((char*)A)+offset))
1826 ** Inputs:
1827 ** a: A sorted, null-terminated linked list. (May be null).
1828 ** b: A sorted, null-terminated linked list. (May be null).
1829 ** cmp: A pointer to the comparison function.
1830 ** offset: Offset in the structure to the "next" field.
1832 ** Return Value:
1833 ** A pointer to the head of a sorted list containing the elements
1834 ** of both a and b.
1836 ** Side effects:
1837 ** The "next" pointers for elements in the lists a and b are
1838 ** changed.
1840 static char *merge(
1841 char *a,
1842 char *b,
1843 int (*cmp)(const char*,const char*),
1844 int offset
1846 char *ptr, *head;
1848 if( a==0 ){
1849 head = b;
1850 }else if( b==0 ){
1851 head = a;
1852 }else{
1853 if( (*cmp)(a,b)<=0 ){
1854 ptr = a;
1855 a = NEXT(a);
1856 }else{
1857 ptr = b;
1858 b = NEXT(b);
1860 head = ptr;
1861 while( a && b ){
1862 if( (*cmp)(a,b)<=0 ){
1863 NEXT(ptr) = a;
1864 ptr = a;
1865 a = NEXT(a);
1866 }else{
1867 NEXT(ptr) = b;
1868 ptr = b;
1869 b = NEXT(b);
1872 if( a ) NEXT(ptr) = a;
1873 else NEXT(ptr) = b;
1875 return head;
1879 ** Inputs:
1880 ** list: Pointer to a singly-linked list of structures.
1881 ** next: Pointer to pointer to the second element of the list.
1882 ** cmp: A comparison function.
1884 ** Return Value:
1885 ** A pointer to the head of a sorted list containing the elements
1886 ** orginally in list.
1888 ** Side effects:
1889 ** The "next" pointers for elements in list are changed.
1891 #define LISTSIZE 30
1892 static char *msort(
1893 char *list,
1894 char **next,
1895 int (*cmp)(const char*,const char*)
1897 unsigned long offset;
1898 char *ep;
1899 char *set[LISTSIZE];
1900 int i;
1901 offset = (unsigned long)((char*)next - (char*)list);
1902 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1903 while( list ){
1904 ep = list;
1905 list = NEXT(list);
1906 NEXT(ep) = 0;
1907 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1908 ep = merge(ep,set[i],cmp,offset);
1909 set[i] = 0;
1911 set[i] = ep;
1913 ep = 0;
1914 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
1915 return ep;
1917 /************************ From the file "option.c" **************************/
1918 static char **g_argv;
1919 static struct s_options *op;
1920 static FILE *errstream;
1922 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1925 ** Print the command line with a carrot pointing to the k-th character
1926 ** of the n-th field.
1928 static void errline(int n, int k, FILE *err)
1930 int spcnt, i;
1931 if( g_argv[0] ) fprintf(err,"%s",g_argv[0]);
1932 spcnt = lemonStrlen(g_argv[0]) + 1;
1933 for(i=1; i<n && g_argv[i]; i++){
1934 fprintf(err," %s",g_argv[i]);
1935 spcnt += lemonStrlen(g_argv[i])+1;
1937 spcnt += k;
1938 for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
1939 if( spcnt<20 ){
1940 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1941 }else{
1942 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1947 ** Return the index of the N-th non-switch argument. Return -1
1948 ** if N is out of range.
1950 static int argindex(int n)
1952 int i;
1953 int dashdash = 0;
1954 if( g_argv!=0 && *g_argv!=0 ){
1955 for(i=1; g_argv[i]; i++){
1956 if( dashdash || !ISOPT(g_argv[i]) ){
1957 if( n==0 ) return i;
1958 n--;
1960 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
1963 return -1;
1966 static char emsg[] = "Command line syntax error: ";
1969 ** Process a flag command line argument.
1971 static int handleflags(int i, FILE *err)
1973 int v;
1974 int errcnt = 0;
1975 int j;
1976 for(j=0; op[j].label; j++){
1977 if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
1979 v = g_argv[i][0]=='-' ? 1 : 0;
1980 if( op[j].label==0 ){
1981 if( err ){
1982 fprintf(err,"%sundefined option.\n",emsg);
1983 errline(i,1,err);
1985 errcnt++;
1986 }else if( op[j].arg==0 ){
1987 /* Ignore this option */
1988 }else if( op[j].type==OPT_FLAG ){
1989 *((int*)op[j].arg) = v;
1990 }else if( op[j].type==OPT_FFLAG ){
1991 (*(void(*)(int))(op[j].arg))(v);
1992 }else if( op[j].type==OPT_FSTR ){
1993 (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
1994 }else{
1995 if( err ){
1996 fprintf(err,"%smissing argument on switch.\n",emsg);
1997 errline(i,1,err);
1999 errcnt++;
2001 return errcnt;
2005 ** Process a command line switch which has an argument.
2007 static int handleswitch(int i, FILE *err)
2009 int lv = 0;
2010 double dv = 0.0;
2011 char *sv = 0, *end;
2012 char *cp;
2013 int j;
2014 int errcnt = 0;
2015 cp = strchr(g_argv[i],'=');
2016 assert( cp!=0 );
2017 *cp = 0;
2018 for(j=0; op[j].label; j++){
2019 if( strcmp(g_argv[i],op[j].label)==0 ) break;
2021 *cp = '=';
2022 if( op[j].label==0 ){
2023 if( err ){
2024 fprintf(err,"%sundefined option.\n",emsg);
2025 errline(i,0,err);
2027 errcnt++;
2028 }else{
2029 cp++;
2030 switch( op[j].type ){
2031 case OPT_FLAG:
2032 case OPT_FFLAG:
2033 if( err ){
2034 fprintf(err,"%soption requires an argument.\n",emsg);
2035 errline(i,0,err);
2037 errcnt++;
2038 break;
2039 case OPT_DBL:
2040 case OPT_FDBL:
2041 dv = strtod(cp,&end);
2042 if( *end ){
2043 if( err ){
2044 fprintf(err,
2045 "%sillegal character in floating-point argument.\n",emsg);
2046 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
2048 errcnt++;
2050 break;
2051 case OPT_INT:
2052 case OPT_FINT:
2053 lv = strtol(cp,&end,0);
2054 if( *end ){
2055 if( err ){
2056 fprintf(err,"%sillegal character in integer argument.\n",emsg);
2057 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
2059 errcnt++;
2061 break;
2062 case OPT_STR:
2063 case OPT_FSTR:
2064 sv = cp;
2065 break;
2067 switch( op[j].type ){
2068 case OPT_FLAG:
2069 case OPT_FFLAG:
2070 break;
2071 case OPT_DBL:
2072 *(double*)(op[j].arg) = dv;
2073 break;
2074 case OPT_FDBL:
2075 (*(void(*)(double))(op[j].arg))(dv);
2076 break;
2077 case OPT_INT:
2078 *(int*)(op[j].arg) = lv;
2079 break;
2080 case OPT_FINT:
2081 (*(void(*)(int))(op[j].arg))((int)lv);
2082 break;
2083 case OPT_STR:
2084 *(char**)(op[j].arg) = sv;
2085 break;
2086 case OPT_FSTR:
2087 (*(void(*)(char *))(op[j].arg))(sv);
2088 break;
2091 return errcnt;
2094 int OptInit(char **a, struct s_options *o, FILE *err)
2096 int errcnt = 0;
2097 g_argv = a;
2098 op = o;
2099 errstream = err;
2100 if( g_argv && *g_argv && op ){
2101 int i;
2102 for(i=1; g_argv[i]; i++){
2103 if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
2104 errcnt += handleflags(i,err);
2105 }else if( strchr(g_argv[i],'=') ){
2106 errcnt += handleswitch(i,err);
2110 if( errcnt>0 ){
2111 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
2112 OptPrint();
2113 exit(1);
2115 return 0;
2118 int OptNArgs(void){
2119 int cnt = 0;
2120 int dashdash = 0;
2121 int i;
2122 if( g_argv!=0 && g_argv[0]!=0 ){
2123 for(i=1; g_argv[i]; i++){
2124 if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
2125 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
2128 return cnt;
2131 char *OptArg(int n)
2133 int i;
2134 i = argindex(n);
2135 return i>=0 ? g_argv[i] : 0;
2138 void OptErr(int n)
2140 int i;
2141 i = argindex(n);
2142 if( i>=0 ) errline(i,0,errstream);
2145 void OptPrint(void){
2146 int i;
2147 int max, len;
2148 max = 0;
2149 for(i=0; op[i].label; i++){
2150 len = lemonStrlen(op[i].label) + 1;
2151 switch( op[i].type ){
2152 case OPT_FLAG:
2153 case OPT_FFLAG:
2154 break;
2155 case OPT_INT:
2156 case OPT_FINT:
2157 len += 9; /* length of "<integer>" */
2158 break;
2159 case OPT_DBL:
2160 case OPT_FDBL:
2161 len += 6; /* length of "<real>" */
2162 break;
2163 case OPT_STR:
2164 case OPT_FSTR:
2165 len += 8; /* length of "<string>" */
2166 break;
2168 if( len>max ) max = len;
2170 for(i=0; op[i].label; i++){
2171 switch( op[i].type ){
2172 case OPT_FLAG:
2173 case OPT_FFLAG:
2174 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2175 break;
2176 case OPT_INT:
2177 case OPT_FINT:
2178 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
2179 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
2180 break;
2181 case OPT_DBL:
2182 case OPT_FDBL:
2183 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
2184 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
2185 break;
2186 case OPT_STR:
2187 case OPT_FSTR:
2188 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
2189 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
2190 break;
2194 /*********************** From the file "parse.c" ****************************/
2196 ** Input file parser for the LEMON parser generator.
2199 /* The state of the parser */
2200 enum e_state {
2201 INITIALIZE,
2202 WAITING_FOR_DECL_OR_RULE,
2203 WAITING_FOR_DECL_KEYWORD,
2204 WAITING_FOR_DECL_ARG,
2205 WAITING_FOR_PRECEDENCE_SYMBOL,
2206 WAITING_FOR_ARROW,
2207 IN_RHS,
2208 LHS_ALIAS_1,
2209 LHS_ALIAS_2,
2210 LHS_ALIAS_3,
2211 RHS_ALIAS_1,
2212 RHS_ALIAS_2,
2213 PRECEDENCE_MARK_1,
2214 PRECEDENCE_MARK_2,
2215 RESYNC_AFTER_RULE_ERROR,
2216 RESYNC_AFTER_DECL_ERROR,
2217 WAITING_FOR_DESTRUCTOR_SYMBOL,
2218 WAITING_FOR_DATATYPE_SYMBOL,
2219 WAITING_FOR_FALLBACK_ID,
2220 WAITING_FOR_WILDCARD_ID,
2221 WAITING_FOR_CLASS_ID,
2222 WAITING_FOR_CLASS_TOKEN,
2223 WAITING_FOR_TOKEN_NAME
2225 struct pstate {
2226 char *filename; /* Name of the input file */
2227 int tokenlineno; /* Linenumber at which current token starts */
2228 int errorcnt; /* Number of errors so far */
2229 char *tokenstart; /* Text of current token */
2230 struct lemon *gp; /* Global state vector */
2231 enum e_state state; /* The state of the parser */
2232 struct symbol *fallback; /* The fallback token */
2233 struct symbol *tkclass; /* Token class symbol */
2234 struct symbol *lhs; /* Left-hand side of current rule */
2235 const char *lhsalias; /* Alias for the LHS */
2236 int nrhs; /* Number of right-hand side symbols seen */
2237 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2238 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2239 struct rule *prevrule; /* Previous rule parsed */
2240 const char *declkeyword; /* Keyword of a declaration */
2241 char **declargslot; /* Where the declaration argument should be put */
2242 int insertLineMacro; /* Add #line before declaration insert */
2243 int *decllinenoslot; /* Where to write declaration line number */
2244 enum e_assoc declassoc; /* Assign this association to decl arguments */
2245 int preccounter; /* Assign this precedence to decl arguments */
2246 struct rule *firstrule; /* Pointer to first rule in the grammar */
2247 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2250 /* Parse a single token */
2251 static void parseonetoken(struct pstate *psp)
2253 const char *x;
2254 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2255 #if 0
2256 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2257 x,psp->state);
2258 #endif
2259 switch( psp->state ){
2260 case INITIALIZE:
2261 psp->prevrule = 0;
2262 psp->preccounter = 0;
2263 psp->firstrule = psp->lastrule = 0;
2264 psp->gp->nrule = 0;
2265 /* Fall thru to next case */
2266 case WAITING_FOR_DECL_OR_RULE:
2267 if( x[0]=='%' ){
2268 psp->state = WAITING_FOR_DECL_KEYWORD;
2269 }else if( ISLOWER(x[0]) ){
2270 psp->lhs = Symbol_new(x);
2271 psp->nrhs = 0;
2272 psp->lhsalias = 0;
2273 psp->state = WAITING_FOR_ARROW;
2274 }else if( x[0]=='{' ){
2275 if( psp->prevrule==0 ){
2276 ErrorMsg(psp->filename,psp->tokenlineno,
2277 "There is no prior rule upon which to attach the code "
2278 "fragment which begins on this line.");
2279 psp->errorcnt++;
2280 }else if( psp->prevrule->code!=0 ){
2281 ErrorMsg(psp->filename,psp->tokenlineno,
2282 "Code fragment beginning on this line is not the first "
2283 "to follow the previous rule.");
2284 psp->errorcnt++;
2285 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
2286 psp->prevrule->neverReduce = 1;
2287 }else{
2288 psp->prevrule->line = psp->tokenlineno;
2289 psp->prevrule->code = &x[1];
2290 psp->prevrule->noCode = 0;
2292 }else if( x[0]=='[' ){
2293 psp->state = PRECEDENCE_MARK_1;
2294 }else{
2295 ErrorMsg(psp->filename,psp->tokenlineno,
2296 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2298 psp->errorcnt++;
2300 break;
2301 case PRECEDENCE_MARK_1:
2302 if( !ISUPPER(x[0]) ){
2303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "The precedence symbol must be a terminal.");
2305 psp->errorcnt++;
2306 }else if( psp->prevrule==0 ){
2307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "There is no prior rule to assign precedence \"[%s]\".",x);
2309 psp->errorcnt++;
2310 }else if( psp->prevrule->precsym!=0 ){
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "Precedence mark on this line is not the first "
2313 "to follow the previous rule.");
2314 psp->errorcnt++;
2315 }else{
2316 psp->prevrule->precsym = Symbol_new(x);
2318 psp->state = PRECEDENCE_MARK_2;
2319 break;
2320 case PRECEDENCE_MARK_2:
2321 if( x[0]!=']' ){
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "Missing \"]\" on precedence mark.");
2324 psp->errorcnt++;
2326 psp->state = WAITING_FOR_DECL_OR_RULE;
2327 break;
2328 case WAITING_FOR_ARROW:
2329 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2330 psp->state = IN_RHS;
2331 }else if( x[0]=='(' ){
2332 psp->state = LHS_ALIAS_1;
2333 }else{
2334 ErrorMsg(psp->filename,psp->tokenlineno,
2335 "Expected to see a \":\" following the LHS symbol \"%s\".",
2336 psp->lhs->name);
2337 psp->errorcnt++;
2338 psp->state = RESYNC_AFTER_RULE_ERROR;
2340 break;
2341 case LHS_ALIAS_1:
2342 if( ISALPHA(x[0]) ){
2343 psp->lhsalias = x;
2344 psp->state = LHS_ALIAS_2;
2345 }else{
2346 ErrorMsg(psp->filename,psp->tokenlineno,
2347 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2348 x,psp->lhs->name);
2349 psp->errorcnt++;
2350 psp->state = RESYNC_AFTER_RULE_ERROR;
2352 break;
2353 case LHS_ALIAS_2:
2354 if( x[0]==')' ){
2355 psp->state = LHS_ALIAS_3;
2356 }else{
2357 ErrorMsg(psp->filename,psp->tokenlineno,
2358 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2359 psp->errorcnt++;
2360 psp->state = RESYNC_AFTER_RULE_ERROR;
2362 break;
2363 case LHS_ALIAS_3:
2364 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2365 psp->state = IN_RHS;
2366 }else{
2367 ErrorMsg(psp->filename,psp->tokenlineno,
2368 "Missing \"->\" following: \"%s(%s)\".",
2369 psp->lhs->name,psp->lhsalias);
2370 psp->errorcnt++;
2371 psp->state = RESYNC_AFTER_RULE_ERROR;
2373 break;
2374 case IN_RHS:
2375 if( x[0]=='.' ){
2376 struct rule *rp;
2377 rp = (struct rule *)calloc( sizeof(struct rule) +
2378 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2379 if( rp==0 ){
2380 ErrorMsg(psp->filename,psp->tokenlineno,
2381 "Can't allocate enough memory for this rule.");
2382 psp->errorcnt++;
2383 psp->prevrule = 0;
2384 }else{
2385 int i;
2386 rp->ruleline = psp->tokenlineno;
2387 rp->rhs = (struct symbol**)&rp[1];
2388 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
2389 for(i=0; i<psp->nrhs; i++){
2390 rp->rhs[i] = psp->rhs[i];
2391 rp->rhsalias[i] = psp->alias[i];
2392 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
2394 rp->lhs = psp->lhs;
2395 rp->lhsalias = psp->lhsalias;
2396 rp->nrhs = psp->nrhs;
2397 rp->code = 0;
2398 rp->noCode = 1;
2399 rp->precsym = 0;
2400 rp->index = psp->gp->nrule++;
2401 rp->nextlhs = rp->lhs->rule;
2402 rp->lhs->rule = rp;
2403 rp->next = 0;
2404 if( psp->firstrule==0 ){
2405 psp->firstrule = psp->lastrule = rp;
2406 }else{
2407 psp->lastrule->next = rp;
2408 psp->lastrule = rp;
2410 psp->prevrule = rp;
2412 psp->state = WAITING_FOR_DECL_OR_RULE;
2413 }else if( ISALPHA(x[0]) ){
2414 if( psp->nrhs>=MAXRHS ){
2415 ErrorMsg(psp->filename,psp->tokenlineno,
2416 "Too many symbols on RHS of rule beginning at \"%s\".",
2418 psp->errorcnt++;
2419 psp->state = RESYNC_AFTER_RULE_ERROR;
2420 }else{
2421 psp->rhs[psp->nrhs] = Symbol_new(x);
2422 psp->alias[psp->nrhs] = 0;
2423 psp->nrhs++;
2425 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2426 struct symbol *msp = psp->rhs[psp->nrhs-1];
2427 if( msp->type!=MULTITERMINAL ){
2428 struct symbol *origsp = msp;
2429 msp = (struct symbol *) calloc(1,sizeof(*msp));
2430 memset(msp, 0, sizeof(*msp));
2431 msp->type = MULTITERMINAL;
2432 msp->nsubsym = 1;
2433 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
2434 msp->subsym[0] = origsp;
2435 msp->name = origsp->name;
2436 psp->rhs[psp->nrhs-1] = msp;
2438 msp->nsubsym++;
2439 msp->subsym = (struct symbol **) realloc(msp->subsym,
2440 sizeof(struct symbol*)*msp->nsubsym);
2441 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2442 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
2443 ErrorMsg(psp->filename,psp->tokenlineno,
2444 "Cannot form a compound containing a non-terminal");
2445 psp->errorcnt++;
2447 }else if( x[0]=='(' && psp->nrhs>0 ){
2448 psp->state = RHS_ALIAS_1;
2449 }else{
2450 ErrorMsg(psp->filename,psp->tokenlineno,
2451 "Illegal character on RHS of rule: \"%s\".",x);
2452 psp->errorcnt++;
2453 psp->state = RESYNC_AFTER_RULE_ERROR;
2455 break;
2456 case RHS_ALIAS_1:
2457 if( ISALPHA(x[0]) ){
2458 psp->alias[psp->nrhs-1] = x;
2459 psp->state = RHS_ALIAS_2;
2460 }else{
2461 ErrorMsg(psp->filename,psp->tokenlineno,
2462 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2463 x,psp->rhs[psp->nrhs-1]->name);
2464 psp->errorcnt++;
2465 psp->state = RESYNC_AFTER_RULE_ERROR;
2467 break;
2468 case RHS_ALIAS_2:
2469 if( x[0]==')' ){
2470 psp->state = IN_RHS;
2471 }else{
2472 ErrorMsg(psp->filename,psp->tokenlineno,
2473 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2474 psp->errorcnt++;
2475 psp->state = RESYNC_AFTER_RULE_ERROR;
2477 break;
2478 case WAITING_FOR_DECL_KEYWORD:
2479 if( ISALPHA(x[0]) ){
2480 psp->declkeyword = x;
2481 psp->declargslot = 0;
2482 psp->decllinenoslot = 0;
2483 psp->insertLineMacro = 1;
2484 psp->state = WAITING_FOR_DECL_ARG;
2485 if( strcmp(x,"name")==0 ){
2486 psp->declargslot = &(psp->gp->name);
2487 psp->insertLineMacro = 0;
2488 }else if( strcmp(x,"include")==0 ){
2489 psp->declargslot = &(psp->gp->include);
2490 }else if( strcmp(x,"code")==0 ){
2491 psp->declargslot = &(psp->gp->extracode);
2492 }else if( strcmp(x,"token_destructor")==0 ){
2493 psp->declargslot = &psp->gp->tokendest;
2494 }else if( strcmp(x,"default_destructor")==0 ){
2495 psp->declargslot = &psp->gp->vardest;
2496 }else if( strcmp(x,"token_prefix")==0 ){
2497 psp->declargslot = &psp->gp->tokenprefix;
2498 psp->insertLineMacro = 0;
2499 }else if( strcmp(x,"syntax_error")==0 ){
2500 psp->declargslot = &(psp->gp->error);
2501 }else if( strcmp(x,"parse_accept")==0 ){
2502 psp->declargslot = &(psp->gp->accept);
2503 }else if( strcmp(x,"parse_failure")==0 ){
2504 psp->declargslot = &(psp->gp->failure);
2505 }else if( strcmp(x,"stack_overflow")==0 ){
2506 psp->declargslot = &(psp->gp->overflow);
2507 }else if( strcmp(x,"extra_argument")==0 ){
2508 psp->declargslot = &(psp->gp->arg);
2509 psp->insertLineMacro = 0;
2510 }else if( strcmp(x,"extra_context")==0 ){
2511 psp->declargslot = &(psp->gp->ctx);
2512 psp->insertLineMacro = 0;
2513 }else if( strcmp(x,"token_type")==0 ){
2514 psp->declargslot = &(psp->gp->tokentype);
2515 psp->insertLineMacro = 0;
2516 }else if( strcmp(x,"default_type")==0 ){
2517 psp->declargslot = &(psp->gp->vartype);
2518 psp->insertLineMacro = 0;
2519 }else if( strcmp(x,"stack_size")==0 ){
2520 psp->declargslot = &(psp->gp->stacksize);
2521 psp->insertLineMacro = 0;
2522 }else if( strcmp(x,"start_symbol")==0 ){
2523 psp->declargslot = &(psp->gp->start);
2524 psp->insertLineMacro = 0;
2525 }else if( strcmp(x,"left")==0 ){
2526 psp->preccounter++;
2527 psp->declassoc = LEFT;
2528 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2529 }else if( strcmp(x,"right")==0 ){
2530 psp->preccounter++;
2531 psp->declassoc = RIGHT;
2532 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2533 }else if( strcmp(x,"nonassoc")==0 ){
2534 psp->preccounter++;
2535 psp->declassoc = NONE;
2536 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2537 }else if( strcmp(x,"destructor")==0 ){
2538 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2539 }else if( strcmp(x,"type")==0 ){
2540 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2541 }else if( strcmp(x,"fallback")==0 ){
2542 psp->fallback = 0;
2543 psp->state = WAITING_FOR_FALLBACK_ID;
2544 }else if( strcmp(x,"token")==0 ){
2545 psp->state = WAITING_FOR_TOKEN_NAME;
2546 }else if( strcmp(x,"wildcard")==0 ){
2547 psp->state = WAITING_FOR_WILDCARD_ID;
2548 }else if( strcmp(x,"token_class")==0 ){
2549 psp->state = WAITING_FOR_CLASS_ID;
2550 }else{
2551 ErrorMsg(psp->filename,psp->tokenlineno,
2552 "Unknown declaration keyword: \"%%%s\".",x);
2553 psp->errorcnt++;
2554 psp->state = RESYNC_AFTER_DECL_ERROR;
2556 }else{
2557 ErrorMsg(psp->filename,psp->tokenlineno,
2558 "Illegal declaration keyword: \"%s\".",x);
2559 psp->errorcnt++;
2560 psp->state = RESYNC_AFTER_DECL_ERROR;
2562 break;
2563 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2564 if( !ISALPHA(x[0]) ){
2565 ErrorMsg(psp->filename,psp->tokenlineno,
2566 "Symbol name missing after %%destructor keyword");
2567 psp->errorcnt++;
2568 psp->state = RESYNC_AFTER_DECL_ERROR;
2569 }else{
2570 struct symbol *sp = Symbol_new(x);
2571 psp->declargslot = &sp->destructor;
2572 psp->decllinenoslot = &sp->destLineno;
2573 psp->insertLineMacro = 1;
2574 psp->state = WAITING_FOR_DECL_ARG;
2576 break;
2577 case WAITING_FOR_DATATYPE_SYMBOL:
2578 if( !ISALPHA(x[0]) ){
2579 ErrorMsg(psp->filename,psp->tokenlineno,
2580 "Symbol name missing after %%type keyword");
2581 psp->errorcnt++;
2582 psp->state = RESYNC_AFTER_DECL_ERROR;
2583 }else{
2584 struct symbol *sp = Symbol_find(x);
2585 if((sp) && (sp->datatype)){
2586 ErrorMsg(psp->filename,psp->tokenlineno,
2587 "Symbol %%type \"%s\" already defined", x);
2588 psp->errorcnt++;
2589 psp->state = RESYNC_AFTER_DECL_ERROR;
2590 }else{
2591 if (!sp){
2592 sp = Symbol_new(x);
2594 psp->declargslot = &sp->datatype;
2595 psp->insertLineMacro = 0;
2596 psp->state = WAITING_FOR_DECL_ARG;
2599 break;
2600 case WAITING_FOR_PRECEDENCE_SYMBOL:
2601 if( x[0]=='.' ){
2602 psp->state = WAITING_FOR_DECL_OR_RULE;
2603 }else if( ISUPPER(x[0]) ){
2604 struct symbol *sp;
2605 sp = Symbol_new(x);
2606 if( sp->prec>=0 ){
2607 ErrorMsg(psp->filename,psp->tokenlineno,
2608 "Symbol \"%s\" has already be given a precedence.",x);
2609 psp->errorcnt++;
2610 }else{
2611 sp->prec = psp->preccounter;
2612 sp->assoc = psp->declassoc;
2614 }else{
2615 ErrorMsg(psp->filename,psp->tokenlineno,
2616 "Can't assign a precedence to \"%s\".",x);
2617 psp->errorcnt++;
2619 break;
2620 case WAITING_FOR_DECL_ARG:
2621 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
2622 const char *zOld, *zNew;
2623 char *zBuf, *z;
2624 int nOld, n, nLine = 0, nNew, nBack;
2625 int addLineMacro;
2626 char zLine[50];
2627 zNew = x;
2628 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2629 nNew = lemonStrlen(zNew);
2630 if( *psp->declargslot ){
2631 zOld = *psp->declargslot;
2632 }else{
2633 zOld = "";
2635 nOld = lemonStrlen(zOld);
2636 n = nOld + nNew + 20;
2637 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
2638 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2639 if( addLineMacro ){
2640 for(z=psp->filename, nBack=0; *z; z++){
2641 if( *z=='\\' ) nBack++;
2643 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
2644 nLine = lemonStrlen(zLine);
2645 n += nLine + lemonStrlen(psp->filename) + nBack;
2647 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2648 zBuf = *psp->declargslot + nOld;
2649 if( addLineMacro ){
2650 if( nOld && zBuf[-1]!='\n' ){
2651 *(zBuf++) = '\n';
2653 memcpy(zBuf, zLine, nLine);
2654 zBuf += nLine;
2655 *(zBuf++) = '"';
2656 for(z=psp->filename; *z; z++){
2657 if( *z=='\\' ){
2658 *(zBuf++) = '\\';
2660 *(zBuf++) = *z;
2662 *(zBuf++) = '"';
2663 *(zBuf++) = '\n';
2665 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2666 psp->decllinenoslot[0] = psp->tokenlineno;
2668 memcpy(zBuf, zNew, nNew);
2669 zBuf += nNew;
2670 *zBuf = 0;
2671 psp->state = WAITING_FOR_DECL_OR_RULE;
2672 }else{
2673 ErrorMsg(psp->filename,psp->tokenlineno,
2674 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2675 psp->errorcnt++;
2676 psp->state = RESYNC_AFTER_DECL_ERROR;
2678 break;
2679 case WAITING_FOR_FALLBACK_ID:
2680 if( x[0]=='.' ){
2681 psp->state = WAITING_FOR_DECL_OR_RULE;
2682 }else if( !ISUPPER(x[0]) ){
2683 ErrorMsg(psp->filename, psp->tokenlineno,
2684 "%%fallback argument \"%s\" should be a token", x);
2685 psp->errorcnt++;
2686 }else{
2687 struct symbol *sp = Symbol_new(x);
2688 if( psp->fallback==0 ){
2689 psp->fallback = sp;
2690 }else if( sp->fallback ){
2691 ErrorMsg(psp->filename, psp->tokenlineno,
2692 "More than one fallback assigned to token %s", x);
2693 psp->errorcnt++;
2694 }else{
2695 sp->fallback = psp->fallback;
2696 psp->gp->has_fallback = 1;
2699 break;
2700 case WAITING_FOR_TOKEN_NAME:
2701 /* Tokens do not have to be declared before use. But they can be
2702 ** in order to control their assigned integer number. The number for
2703 ** each token is assigned when it is first seen. So by including
2705 ** %token ONE TWO THREE
2707 ** early in the grammar file, that assigns small consecutive values
2708 ** to each of the tokens ONE TWO and THREE.
2710 if( x[0]=='.' ){
2711 psp->state = WAITING_FOR_DECL_OR_RULE;
2712 }else if( !ISUPPER(x[0]) ){
2713 ErrorMsg(psp->filename, psp->tokenlineno,
2714 "%%token argument \"%s\" should be a token", x);
2715 psp->errorcnt++;
2716 }else{
2717 (void)Symbol_new(x);
2719 break;
2720 case WAITING_FOR_WILDCARD_ID:
2721 if( x[0]=='.' ){
2722 psp->state = WAITING_FOR_DECL_OR_RULE;
2723 }else if( !ISUPPER(x[0]) ){
2724 ErrorMsg(psp->filename, psp->tokenlineno,
2725 "%%wildcard argument \"%s\" should be a token", x);
2726 psp->errorcnt++;
2727 }else{
2728 struct symbol *sp = Symbol_new(x);
2729 if( psp->gp->wildcard==0 ){
2730 psp->gp->wildcard = sp;
2731 }else{
2732 ErrorMsg(psp->filename, psp->tokenlineno,
2733 "Extra wildcard to token: %s", x);
2734 psp->errorcnt++;
2737 break;
2738 case WAITING_FOR_CLASS_ID:
2739 if( !ISLOWER(x[0]) ){
2740 ErrorMsg(psp->filename, psp->tokenlineno,
2741 "%%token_class must be followed by an identifier: %s", x);
2742 psp->errorcnt++;
2743 psp->state = RESYNC_AFTER_DECL_ERROR;
2744 }else if( Symbol_find(x) ){
2745 ErrorMsg(psp->filename, psp->tokenlineno,
2746 "Symbol \"%s\" already used", x);
2747 psp->errorcnt++;
2748 psp->state = RESYNC_AFTER_DECL_ERROR;
2749 }else{
2750 psp->tkclass = Symbol_new(x);
2751 psp->tkclass->type = MULTITERMINAL;
2752 psp->state = WAITING_FOR_CLASS_TOKEN;
2754 break;
2755 case WAITING_FOR_CLASS_TOKEN:
2756 if( x[0]=='.' ){
2757 psp->state = WAITING_FOR_DECL_OR_RULE;
2758 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
2759 struct symbol *msp = psp->tkclass;
2760 msp->nsubsym++;
2761 msp->subsym = (struct symbol **) realloc(msp->subsym,
2762 sizeof(struct symbol*)*msp->nsubsym);
2763 if( !ISUPPER(x[0]) ) x++;
2764 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2765 }else{
2766 ErrorMsg(psp->filename, psp->tokenlineno,
2767 "%%token_class argument \"%s\" should be a token", x);
2768 psp->errorcnt++;
2769 psp->state = RESYNC_AFTER_DECL_ERROR;
2771 break;
2772 case RESYNC_AFTER_RULE_ERROR:
2773 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2774 ** break; */
2775 case RESYNC_AFTER_DECL_ERROR:
2776 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2777 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2778 break;
2782 /* Run the preprocessor over the input file text. The global variables
2783 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2784 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2785 ** comments them out. Text in between is also commented out as appropriate.
2787 static void preprocess_input(char *z){
2788 int i, j, k, n;
2789 int exclude = 0;
2790 int start = 0;
2791 int lineno = 1;
2792 int start_lineno = 1;
2793 for(i=0; z[i]; i++){
2794 if( z[i]=='\n' ) lineno++;
2795 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2796 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
2797 if( exclude ){
2798 exclude--;
2799 if( exclude==0 ){
2800 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2803 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2804 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2805 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
2806 if( exclude ){
2807 exclude++;
2808 }else{
2809 for(j=i+7; ISSPACE(z[j]); j++){}
2810 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
2811 exclude = 1;
2812 for(k=0; k<nDefine; k++){
2813 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
2814 exclude = 0;
2815 break;
2818 if( z[i+3]=='n' ) exclude = !exclude;
2819 if( exclude ){
2820 start = i;
2821 start_lineno = lineno;
2824 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2827 if( exclude ){
2828 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2829 exit(1);
2833 /* In spite of its name, this function is really a scanner. It read
2834 ** in the entire input file (all at once) then tokenizes it. Each
2835 ** token is passed to the function "parseonetoken" which builds all
2836 ** the appropriate data structures in the global state vector "gp".
2838 void Parse(struct lemon *gp)
2840 struct pstate ps;
2841 FILE *fp;
2842 char *filebuf;
2843 unsigned int filesize;
2844 int lineno;
2845 int c;
2846 char *cp, *nextcp;
2847 int startline = 0;
2849 memset(&ps, '\0', sizeof(ps));
2850 ps.gp = gp;
2851 ps.filename = gp->filename;
2852 ps.errorcnt = 0;
2853 ps.state = INITIALIZE;
2855 /* Begin by reading the input file */
2856 fp = fopen(ps.filename,"rb");
2857 if( fp==0 ){
2858 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2859 gp->errorcnt++;
2860 return;
2862 fseek(fp,0,2);
2863 filesize = ftell(fp);
2864 rewind(fp);
2865 filebuf = (char *)malloc( filesize+1 );
2866 if( filesize>100000000 || filebuf==0 ){
2867 ErrorMsg(ps.filename,0,"Input file too large.");
2868 free(filebuf);
2869 gp->errorcnt++;
2870 fclose(fp);
2871 return;
2873 if( fread(filebuf,1,filesize,fp)!=filesize ){
2874 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2875 filesize);
2876 free(filebuf);
2877 gp->errorcnt++;
2878 fclose(fp);
2879 return;
2881 fclose(fp);
2882 filebuf[filesize] = 0;
2884 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2885 preprocess_input(filebuf);
2887 /* Now scan the text of the input file */
2888 lineno = 1;
2889 for(cp=filebuf; (c= *cp)!=0; ){
2890 if( c=='\n' ) lineno++; /* Keep track of the line number */
2891 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
2892 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2893 cp+=2;
2894 while( (c= *cp)!=0 && c!='\n' ) cp++;
2895 continue;
2897 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2898 cp+=2;
2899 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2900 if( c=='\n' ) lineno++;
2901 cp++;
2903 if( c ) cp++;
2904 continue;
2906 ps.tokenstart = cp; /* Mark the beginning of the token */
2907 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2908 if( c=='\"' ){ /* String literals */
2909 cp++;
2910 while( (c= *cp)!=0 && c!='\"' ){
2911 if( c=='\n' ) lineno++;
2912 cp++;
2914 if( c==0 ){
2915 ErrorMsg(ps.filename,startline,
2916 "String starting on this line is not terminated before "
2917 "the end of the file.");
2918 ps.errorcnt++;
2919 nextcp = cp;
2920 }else{
2921 nextcp = cp+1;
2923 }else if( c=='{' ){ /* A block of C code */
2924 int level;
2925 cp++;
2926 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2927 if( c=='\n' ) lineno++;
2928 else if( c=='{' ) level++;
2929 else if( c=='}' ) level--;
2930 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2931 int prevc;
2932 cp = &cp[2];
2933 prevc = 0;
2934 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2935 if( c=='\n' ) lineno++;
2936 prevc = c;
2937 cp++;
2939 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2940 cp = &cp[2];
2941 while( (c= *cp)!=0 && c!='\n' ) cp++;
2942 if( c ) lineno++;
2943 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2944 int startchar, prevc;
2945 startchar = c;
2946 prevc = 0;
2947 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2948 if( c=='\n' ) lineno++;
2949 if( prevc=='\\' ) prevc = 0;
2950 else prevc = c;
2954 if( c==0 ){
2955 ErrorMsg(ps.filename,ps.tokenlineno,
2956 "C code starting on this line is not terminated before "
2957 "the end of the file.");
2958 ps.errorcnt++;
2959 nextcp = cp;
2960 }else{
2961 nextcp = cp+1;
2963 }else if( ISALNUM(c) ){ /* Identifiers */
2964 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
2965 nextcp = cp;
2966 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2967 cp += 3;
2968 nextcp = cp;
2969 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
2970 cp += 2;
2971 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
2972 nextcp = cp;
2973 }else{ /* All other (one character) operators */
2974 cp++;
2975 nextcp = cp;
2977 c = *cp;
2978 *cp = 0; /* Null terminate the token */
2979 parseonetoken(&ps); /* Parse the token */
2980 *cp = (char)c; /* Restore the buffer */
2981 cp = nextcp;
2983 free(filebuf); /* Release the buffer after parsing */
2984 gp->rule = ps.firstrule;
2985 gp->errorcnt = ps.errorcnt;
2987 /*************************** From the file "plink.c" *********************/
2989 ** Routines processing configuration follow-set propagation links
2990 ** in the LEMON parser generator.
2992 static struct plink *plink_freelist = 0;
2994 /* Allocate a new plink */
2995 struct plink *Plink_new(void){
2996 struct plink *newlink;
2998 if( plink_freelist==0 ){
2999 int i;
3000 int amt = 100;
3001 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
3002 if( plink_freelist==0 ){
3003 fprintf(stderr,
3004 "Unable to allocate memory for a new follow-set propagation link.\n");
3005 exit(1);
3007 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3008 plink_freelist[amt-1].next = 0;
3010 newlink = plink_freelist;
3011 plink_freelist = plink_freelist->next;
3012 return newlink;
3015 /* Add a plink to a plink list */
3016 void Plink_add(struct plink **plpp, struct config *cfp)
3018 struct plink *newlink;
3019 newlink = Plink_new();
3020 newlink->next = *plpp;
3021 *plpp = newlink;
3022 newlink->cfp = cfp;
3025 /* Transfer every plink on the list "from" to the list "to" */
3026 void Plink_copy(struct plink **to, struct plink *from)
3028 struct plink *nextpl;
3029 while( from ){
3030 nextpl = from->next;
3031 from->next = *to;
3032 *to = from;
3033 from = nextpl;
3037 /* Delete every plink on the list */
3038 void Plink_delete(struct plink *plp)
3040 struct plink *nextpl;
3042 while( plp ){
3043 nextpl = plp->next;
3044 plp->next = plink_freelist;
3045 plink_freelist = plp;
3046 plp = nextpl;
3049 /*********************** From the file "report.c" **************************/
3051 ** Procedures for generating reports and tables in the LEMON parser generator.
3054 /* Generate a filename with the given suffix. Space to hold the
3055 ** name comes from malloc() and must be freed by the calling
3056 ** function.
3058 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
3060 char *name;
3061 char *cp;
3062 char *filename = lemp->filename;
3063 int sz;
3065 if( outputDir ){
3066 cp = strrchr(filename, '/');
3067 if( cp ) filename = cp + 1;
3069 sz = lemonStrlen(filename);
3070 sz += lemonStrlen(suffix);
3071 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3072 sz += 5;
3073 name = (char*)malloc( sz );
3074 if( name==0 ){
3075 fprintf(stderr,"Can't allocate space for a filename.\n");
3076 exit(1);
3078 name[0] = 0;
3079 if( outputDir ){
3080 lemon_strcpy(name, outputDir);
3081 lemon_strcat(name, "/");
3083 lemon_strcat(name,filename);
3084 cp = strrchr(name,'.');
3085 if( cp ) *cp = 0;
3086 lemon_strcat(name,suffix);
3087 return name;
3090 /* Open a file with a name based on the name of the input file,
3091 ** but with a different (specified) suffix, and return a pointer
3092 ** to the stream */
3093 PRIVATE FILE *file_open(
3094 struct lemon *lemp,
3095 const char *suffix,
3096 const char *mode
3098 FILE *fp;
3100 if( lemp->outname ) free(lemp->outname);
3101 lemp->outname = file_makename(lemp, suffix);
3102 fp = fopen(lemp->outname,mode);
3103 if( fp==0 && *mode=='w' ){
3104 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3105 lemp->errorcnt++;
3106 return 0;
3108 return fp;
3111 /* Print the text of a rule
3113 void rule_print(FILE *out, struct rule *rp){
3114 int i, j;
3115 fprintf(out, "%s",rp->lhs->name);
3116 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3117 fprintf(out," ::=");
3118 for(i=0; i<rp->nrhs; i++){
3119 struct symbol *sp = rp->rhs[i];
3120 if( sp->type==MULTITERMINAL ){
3121 fprintf(out," %s", sp->subsym[0]->name);
3122 for(j=1; j<sp->nsubsym; j++){
3123 fprintf(out,"|%s", sp->subsym[j]->name);
3125 }else{
3126 fprintf(out," %s", sp->name);
3128 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3132 /* Duplicate the input file without comments and without actions
3133 ** on rules */
3134 void Reprint(struct lemon *lemp)
3136 struct rule *rp;
3137 struct symbol *sp;
3138 int i, j, maxlen, len, ncolumns, skip;
3139 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3140 maxlen = 10;
3141 for(i=0; i<lemp->nsymbol; i++){
3142 sp = lemp->symbols[i];
3143 len = lemonStrlen(sp->name);
3144 if( len>maxlen ) maxlen = len;
3146 ncolumns = 76/(maxlen+5);
3147 if( ncolumns<1 ) ncolumns = 1;
3148 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3149 for(i=0; i<skip; i++){
3150 printf("//");
3151 for(j=i; j<lemp->nsymbol; j+=skip){
3152 sp = lemp->symbols[j];
3153 assert( sp->index==j );
3154 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3156 printf("\n");
3158 for(rp=lemp->rule; rp; rp=rp->next){
3159 rule_print(stdout, rp);
3160 printf(".");
3161 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
3162 /* if( rp->code ) printf("\n %s",rp->code); */
3163 printf("\n");
3167 /* Print a single rule.
3169 void RulePrint(FILE *fp, struct rule *rp, int iCursor){
3170 struct symbol *sp;
3171 int i, j;
3172 fprintf(fp,"%s ::=",rp->lhs->name);
3173 for(i=0; i<=rp->nrhs; i++){
3174 if( i==iCursor ) fprintf(fp," *");
3175 if( i==rp->nrhs ) break;
3176 sp = rp->rhs[i];
3177 if( sp->type==MULTITERMINAL ){
3178 fprintf(fp," %s", sp->subsym[0]->name);
3179 for(j=1; j<sp->nsubsym; j++){
3180 fprintf(fp,"|%s",sp->subsym[j]->name);
3182 }else{
3183 fprintf(fp," %s", sp->name);
3188 /* Print the rule for a configuration.
3190 void ConfigPrint(FILE *fp, struct config *cfp){
3191 RulePrint(fp, cfp->rp, cfp->dot);
3194 /* #define TEST */
3195 #if 0
3196 /* Print a set */
3197 PRIVATE void SetPrint(out,set,lemp)
3198 FILE *out;
3199 char *set;
3200 struct lemon *lemp;
3202 int i;
3203 char *spacer;
3204 spacer = "";
3205 fprintf(out,"%12s[","");
3206 for(i=0; i<lemp->nterminal; i++){
3207 if( SetFind(set,i) ){
3208 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3209 spacer = " ";
3212 fprintf(out,"]\n");
3215 /* Print a plink chain */
3216 PRIVATE void PlinkPrint(out,plp,tag)
3217 FILE *out;
3218 struct plink *plp;
3219 char *tag;
3221 while( plp ){
3222 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
3223 ConfigPrint(out,plp->cfp);
3224 fprintf(out,"\n");
3225 plp = plp->next;
3228 #endif
3230 /* Print an action to the given file descriptor. Return FALSE if
3231 ** nothing was actually printed.
3233 int PrintAction(
3234 struct action *ap, /* The action to print */
3235 FILE *fp, /* Print the action here */
3236 int indent /* Indent by this amount */
3238 int result = 1;
3239 switch( ap->type ){
3240 case SHIFT: {
3241 struct state *stp = ap->x.stp;
3242 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
3243 break;
3245 case REDUCE: {
3246 struct rule *rp = ap->x.rp;
3247 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
3248 RulePrint(fp, rp, -1);
3249 break;
3251 case SHIFTREDUCE: {
3252 struct rule *rp = ap->x.rp;
3253 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
3254 RulePrint(fp, rp, -1);
3255 break;
3257 case ACCEPT:
3258 fprintf(fp,"%*s accept",indent,ap->sp->name);
3259 break;
3260 case ERROR:
3261 fprintf(fp,"%*s error",indent,ap->sp->name);
3262 break;
3263 case SRCONFLICT:
3264 case RRCONFLICT:
3265 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
3266 indent,ap->sp->name,ap->x.rp->iRule);
3267 break;
3268 case SSCONFLICT:
3269 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
3270 indent,ap->sp->name,ap->x.stp->statenum);
3271 break;
3272 case SH_RESOLVED:
3273 if( showPrecedenceConflict ){
3274 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
3275 indent,ap->sp->name,ap->x.stp->statenum);
3276 }else{
3277 result = 0;
3279 break;
3280 case RD_RESOLVED:
3281 if( showPrecedenceConflict ){
3282 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
3283 indent,ap->sp->name,ap->x.rp->iRule);
3284 }else{
3285 result = 0;
3287 break;
3288 case NOT_USED:
3289 result = 0;
3290 break;
3292 if( result && ap->spOpt ){
3293 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3295 return result;
3298 /* Generate the "*.out" log file */
3299 void ReportOutput(struct lemon *lemp)
3301 int i, n;
3302 struct state *stp;
3303 struct config *cfp;
3304 struct action *ap;
3305 struct rule *rp;
3306 FILE *fp;
3308 fp = file_open(lemp,".out","wb");
3309 if( fp==0 ) return;
3310 for(i=0; i<lemp->nxstate; i++){
3311 stp = lemp->sorted[i];
3312 fprintf(fp,"State %d:\n",stp->statenum);
3313 if( lemp->basisflag ) cfp=stp->bp;
3314 else cfp=stp->cfp;
3315 while( cfp ){
3316 char buf[20];
3317 if( cfp->dot==cfp->rp->nrhs ){
3318 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
3319 fprintf(fp," %5s ",buf);
3320 }else{
3321 fprintf(fp," ");
3323 ConfigPrint(fp,cfp);
3324 fprintf(fp,"\n");
3325 #if 0
3326 SetPrint(fp,cfp->fws,lemp);
3327 PlinkPrint(fp,cfp->fplp,"To ");
3328 PlinkPrint(fp,cfp->bplp,"From");
3329 #endif
3330 if( lemp->basisflag ) cfp=cfp->bp;
3331 else cfp=cfp->next;
3333 fprintf(fp,"\n");
3334 for(ap=stp->ap; ap; ap=ap->next){
3335 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3337 fprintf(fp,"\n");
3339 fprintf(fp, "----------------------------------------------------\n");
3340 fprintf(fp, "Symbols:\n");
3341 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
3342 for(i=0; i<lemp->nsymbol; i++){
3343 int j;
3344 struct symbol *sp;
3346 sp = lemp->symbols[i];
3347 fprintf(fp, " %3d: %s", i, sp->name);
3348 if( sp->type==NONTERMINAL ){
3349 fprintf(fp, ":");
3350 if( sp->lambda ){
3351 fprintf(fp, " <lambda>");
3353 for(j=0; j<lemp->nterminal; j++){
3354 if( sp->firstset && SetFind(sp->firstset, j) ){
3355 fprintf(fp, " %s", lemp->symbols[j]->name);
3359 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
3360 fprintf(fp, "\n");
3362 fprintf(fp, "----------------------------------------------------\n");
3363 fprintf(fp, "Syntax-only Symbols:\n");
3364 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3365 for(i=n=0; i<lemp->nsymbol; i++){
3366 int w;
3367 struct symbol *sp = lemp->symbols[i];
3368 if( sp->bContent ) continue;
3369 w = (int)strlen(sp->name);
3370 if( n>0 && n+w>75 ){
3371 fprintf(fp,"\n");
3372 n = 0;
3374 if( n>0 ){
3375 fprintf(fp, " ");
3376 n++;
3378 fprintf(fp, "%s", sp->name);
3379 n += w;
3381 if( n>0 ) fprintf(fp, "\n");
3382 fprintf(fp, "----------------------------------------------------\n");
3383 fprintf(fp, "Rules:\n");
3384 for(rp=lemp->rule; rp; rp=rp->next){
3385 fprintf(fp, "%4d: ", rp->iRule);
3386 rule_print(fp, rp);
3387 fprintf(fp,".");
3388 if( rp->precsym ){
3389 fprintf(fp," [%s precedence=%d]",
3390 rp->precsym->name, rp->precsym->prec);
3392 fprintf(fp,"\n");
3394 fclose(fp);
3395 return;
3398 /* Search for the file "name" which is in the same directory as
3399 ** the exacutable */
3400 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
3402 const char *pathlist;
3403 char *pathbufptr;
3404 char *pathbuf;
3405 char *path,*cp;
3406 char c;
3408 #ifdef __WIN32__
3409 cp = strrchr(argv0,'\\');
3410 #else
3411 cp = strrchr(argv0,'/');
3412 #endif
3413 if( cp ){
3414 c = *cp;
3415 *cp = 0;
3416 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
3417 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
3418 *cp = c;
3419 }else{
3420 pathlist = getenv("PATH");
3421 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
3422 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
3423 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
3424 if( (pathbuf != 0) && (path!=0) ){
3425 pathbufptr = pathbuf;
3426 lemon_strcpy(pathbuf, pathlist);
3427 while( *pathbuf ){
3428 cp = strchr(pathbuf,':');
3429 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
3430 c = *cp;
3431 *cp = 0;
3432 lemon_sprintf(path,"%s/%s",pathbuf,name);
3433 *cp = c;
3434 if( c==0 ) pathbuf[0] = 0;
3435 else pathbuf = &cp[1];
3436 if( access(path,modemask)==0 ) break;
3438 free(pathbufptr);
3441 return path;
3444 /* Given an action, compute the integer value for that action
3445 ** which is to be put in the action table of the generated machine.
3446 ** Return negative if no action should be generated.
3448 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
3450 int act;
3451 switch( ap->type ){
3452 case SHIFT: act = ap->x.stp->statenum; break;
3453 case SHIFTREDUCE: {
3454 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3455 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3456 ** REDUCE action: */
3457 if( ap->sp->index>=lemp->nterminal ){
3458 act = lemp->minReduce + ap->x.rp->iRule;
3459 }else{
3460 act = lemp->minShiftReduce + ap->x.rp->iRule;
3462 break;
3464 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3465 case ERROR: act = lemp->errAction; break;
3466 case ACCEPT: act = lemp->accAction; break;
3467 default: act = -1; break;
3469 return act;
3472 #define LINESIZE 1000
3473 /* The next cluster of routines are for reading the template file
3474 ** and writing the results to the generated parser */
3475 /* The first function transfers data from "in" to "out" until
3476 ** a line is seen which begins with "%%". The line number is
3477 ** tracked.
3479 ** if name!=0, then any word that begin with "Parse" is changed to
3480 ** begin with *name instead.
3482 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
3484 int i, iStart;
3485 char line[LINESIZE];
3486 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3487 (*lineno)++;
3488 iStart = 0;
3489 if( name ){
3490 for(i=0; line[i]; i++){
3491 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3492 && (i==0 || !ISALPHA(line[i-1]))
3494 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3495 fprintf(out,"%s",name);
3496 i += 4;
3497 iStart = i+1;
3501 fprintf(out,"%s",&line[iStart]);
3505 /* The next function finds the template file and opens it, returning
3506 ** a pointer to the opened file. */
3507 PRIVATE FILE *tplt_open(struct lemon *lemp)
3509 static char templatename[] = "lempar.c";
3510 char buf[1000];
3511 FILE *in;
3512 char *tpltname;
3513 char *cp;
3515 /* first, see if user specified a template filename on the command line. */
3516 if (user_templatename != 0) {
3517 if( access(user_templatename,004)==-1 ){
3518 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3519 user_templatename);
3520 lemp->errorcnt++;
3521 return 0;
3523 in = fopen(user_templatename,"rb");
3524 if( in==0 ){
3525 fprintf(stderr,"Can't open the template file \"%s\".\n",
3526 user_templatename);
3527 lemp->errorcnt++;
3528 return 0;
3530 return in;
3533 cp = strrchr(lemp->filename,'.');
3534 if( cp ){
3535 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3536 }else{
3537 lemon_sprintf(buf,"%s.lt",lemp->filename);
3539 if( access(buf,004)==0 ){
3540 tpltname = buf;
3541 }else if( access(templatename,004)==0 ){
3542 tpltname = templatename;
3543 }else{
3544 tpltname = pathsearch(lemp->argv0,templatename,0);
3546 if( tpltname==0 ){
3547 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3548 templatename);
3549 lemp->errorcnt++;
3550 return 0;
3552 in = fopen(tpltname,"rb");
3553 if( in==0 ){
3554 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3555 lemp->errorcnt++;
3556 return 0;
3558 return in;
3561 /* Print a #line directive line to the output file. */
3562 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
3564 fprintf(out,"#line %d \"",lineno);
3565 while( *filename ){
3566 if( *filename == '\\' ) putc('\\',out);
3567 putc(*filename,out);
3568 filename++;
3570 fprintf(out,"\"\n");
3573 /* Print a string to the file and keep the linenumber up to date */
3574 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
3576 if( str==0 ) return;
3577 while( *str ){
3578 putc(*str,out);
3579 if( *str=='\n' ) (*lineno)++;
3580 str++;
3582 if( str[-1]!='\n' ){
3583 putc('\n',out);
3584 (*lineno)++;
3586 if (!lemp->nolinenosflag) {
3587 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3589 return;
3593 ** The following routine emits code for the destructor for the
3594 ** symbol sp
3596 void emit_destructor_code(
3597 FILE *out,
3598 struct symbol *sp,
3599 struct lemon *lemp,
3600 int *lineno
3602 char *cp = 0;
3604 if( sp->type==TERMINAL ){
3605 cp = lemp->tokendest;
3606 if( cp==0 ) return;
3607 fprintf(out,"{\n"); (*lineno)++;
3608 }else if( sp->destructor ){
3609 cp = sp->destructor;
3610 fprintf(out,"{\n"); (*lineno)++;
3611 if( !lemp->nolinenosflag ){
3612 (*lineno)++;
3613 tplt_linedir(out,sp->destLineno,lemp->filename);
3615 }else if( lemp->vardest ){
3616 cp = lemp->vardest;
3617 if( cp==0 ) return;
3618 fprintf(out,"{\n"); (*lineno)++;
3619 }else{
3620 assert( 0 ); /* Cannot happen */
3622 for(; *cp; cp++){
3623 if( *cp=='$' && cp[1]=='$' ){
3624 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3625 cp++;
3626 continue;
3628 if( *cp=='\n' ) (*lineno)++;
3629 fputc(*cp,out);
3631 fprintf(out,"\n"); (*lineno)++;
3632 if (!lemp->nolinenosflag) {
3633 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3635 fprintf(out,"}\n"); (*lineno)++;
3636 return;
3640 ** Return TRUE (non-zero) if the given symbol has a destructor.
3642 int has_destructor(struct symbol *sp, struct lemon *lemp)
3644 int ret;
3645 if( sp->type==TERMINAL ){
3646 ret = lemp->tokendest!=0;
3647 }else{
3648 ret = lemp->vardest!=0 || sp->destructor!=0;
3650 return ret;
3654 ** Append text to a dynamically allocated string. If zText is 0 then
3655 ** reset the string to be empty again. Always return the complete text
3656 ** of the string (which is overwritten with each call).
3658 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3659 ** \000 terminator is stored. zText can contain up to two instances of
3660 ** %d. The values of p1 and p2 are written into the first and second
3661 ** %d.
3663 ** If n==-1, then the previous character is overwritten.
3665 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3666 static char empty[1] = { 0 };
3667 static char *z = 0;
3668 static int alloced = 0;
3669 static int used = 0;
3670 int c;
3671 char zInt[40];
3672 if( zText==0 ){
3673 if( used==0 && z!=0 ) z[0] = 0;
3674 used = 0;
3675 return z;
3677 if( n<=0 ){
3678 if( n<0 ){
3679 used += n;
3680 assert( used>=0 );
3682 n = lemonStrlen(zText);
3684 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
3685 alloced = n + sizeof(zInt)*2 + used + 200;
3686 z = (char *) realloc(z, alloced);
3688 if( z==0 ) return empty;
3689 while( n-- > 0 ){
3690 c = *(zText++);
3691 if( c=='%' && n>0 && zText[0]=='d' ){
3692 lemon_sprintf(zInt, "%d", p1);
3693 p1 = p2;
3694 lemon_strcpy(&z[used], zInt);
3695 used += lemonStrlen(&z[used]);
3696 zText++;
3697 n--;
3698 }else{
3699 z[used++] = (char)c;
3702 z[used] = 0;
3703 return z;
3707 ** Write and transform the rp->code string so that symbols are expanded.
3708 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3710 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3711 ** to be defined.
3713 PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
3714 char *cp, *xp;
3715 int i;
3716 int rc = 0; /* True if yylhsminor is used */
3717 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
3718 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3719 char lhsused = 0; /* True if the LHS element has been used */
3720 char lhsdirect; /* True if LHS writes directly into stack */
3721 char used[MAXRHS]; /* True for each RHS element which is used */
3722 char zLhs[50]; /* Convert the LHS symbol into this string */
3723 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
3725 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3726 lhsused = 0;
3728 if( rp->code==0 ){
3729 static char newlinestr[2] = { '\n', '\0' };
3730 rp->code = newlinestr;
3731 rp->line = rp->ruleline;
3732 rp->noCode = 1;
3733 }else{
3734 rp->noCode = 0;
3738 if( rp->nrhs==0 ){
3739 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3740 lhsdirect = 1;
3741 }else if( rp->rhsalias[0]==0 ){
3742 /* The left-most RHS symbol has no value. LHS direct is ok. But
3743 ** we have to call the distructor on the RHS symbol first. */
3744 lhsdirect = 1;
3745 if( has_destructor(rp->rhs[0],lemp) ){
3746 append_str(0,0,0,0);
3747 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3748 rp->rhs[0]->index,1-rp->nrhs);
3749 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3750 rp->noCode = 0;
3752 }else if( rp->lhsalias==0 ){
3753 /* There is no LHS value symbol. */
3754 lhsdirect = 1;
3755 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3756 /* The LHS symbol and the left-most RHS symbol are the same, so
3757 ** direct writing is allowed */
3758 lhsdirect = 1;
3759 lhsused = 1;
3760 used[0] = 1;
3761 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3762 ErrorMsg(lemp->filename,rp->ruleline,
3763 "%s(%s) and %s(%s) share the same label but have "
3764 "different datatypes.",
3765 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3766 lemp->errorcnt++;
3768 }else{
3769 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3770 rp->lhsalias, rp->rhsalias[0]);
3771 zSkip = strstr(rp->code, zOvwrt);
3772 if( zSkip!=0 ){
3773 /* The code contains a special comment that indicates that it is safe
3774 ** for the LHS label to overwrite left-most RHS label. */
3775 lhsdirect = 1;
3776 }else{
3777 lhsdirect = 0;
3780 if( lhsdirect ){
3781 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3782 }else{
3783 rc = 1;
3784 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3787 append_str(0,0,0,0);
3789 /* This const cast is wrong but harmless, if we're careful. */
3790 for(cp=(char *)rp->code; *cp; cp++){
3791 if( cp==zSkip ){
3792 append_str(zOvwrt,0,0,0);
3793 cp += lemonStrlen(zOvwrt)-1;
3794 dontUseRhs0 = 1;
3795 continue;
3797 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
3798 char saved;
3799 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
3800 saved = *xp;
3801 *xp = 0;
3802 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3803 append_str(zLhs,0,0,0);
3804 cp = xp;
3805 lhsused = 1;
3806 }else{
3807 for(i=0; i<rp->nrhs; i++){
3808 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3809 if( i==0 && dontUseRhs0 ){
3810 ErrorMsg(lemp->filename,rp->ruleline,
3811 "Label %s used after '%s'.",
3812 rp->rhsalias[0], zOvwrt);
3813 lemp->errorcnt++;
3814 }else if( cp!=rp->code && cp[-1]=='@' ){
3815 /* If the argument is of the form @X then substituted
3816 ** the token number of X, not the value of X */
3817 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3818 }else{
3819 struct symbol *sp = rp->rhs[i];
3820 int dtnum;
3821 if( sp->type==MULTITERMINAL ){
3822 dtnum = sp->subsym[0]->dtnum;
3823 }else{
3824 dtnum = sp->dtnum;
3826 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3828 cp = xp;
3829 used[i] = 1;
3830 break;
3834 *xp = saved;
3836 append_str(cp, 1, 0, 0);
3837 } /* End loop */
3839 /* Main code generation completed */
3840 cp = append_str(0,0,0,0);
3841 if( cp && cp[0] ) rp->code = Strsafe(cp);
3842 append_str(0,0,0,0);
3844 /* Check to make sure the LHS has been used */
3845 if( rp->lhsalias && !lhsused ){
3846 ErrorMsg(lemp->filename,rp->ruleline,
3847 "Label \"%s\" for \"%s(%s)\" is never used.",
3848 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3849 lemp->errorcnt++;
3852 /* Generate destructor code for RHS minor values which are not referenced.
3853 ** Generate error messages for unused labels and duplicate labels.
3855 for(i=0; i<rp->nrhs; i++){
3856 if( rp->rhsalias[i] ){
3857 if( i>0 ){
3858 int j;
3859 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3860 ErrorMsg(lemp->filename,rp->ruleline,
3861 "%s(%s) has the same label as the LHS but is not the left-most "
3862 "symbol on the RHS.",
3863 rp->rhs[i]->name, rp->rhsalias[i]);
3864 lemp->errorcnt++;
3866 for(j=0; j<i; j++){
3867 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3868 ErrorMsg(lemp->filename,rp->ruleline,
3869 "Label %s used for multiple symbols on the RHS of a rule.",
3870 rp->rhsalias[i]);
3871 lemp->errorcnt++;
3872 break;
3876 if( !used[i] ){
3877 ErrorMsg(lemp->filename,rp->ruleline,
3878 "Label %s for \"%s(%s)\" is never used.",
3879 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3880 lemp->errorcnt++;
3882 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3883 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3884 rp->rhs[i]->index,i-rp->nrhs+1);
3888 /* If unable to write LHS values directly into the stack, write the
3889 ** saved LHS value now. */
3890 if( lhsdirect==0 ){
3891 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3892 append_str(zLhs, 0, 0, 0);
3893 append_str(";\n", 0, 0, 0);
3896 /* Suffix code generation complete */
3897 cp = append_str(0,0,0,0);
3898 if( cp && cp[0] ){
3899 rp->codeSuffix = Strsafe(cp);
3900 rp->noCode = 0;
3903 return rc;
3907 ** Generate code which executes when the rule "rp" is reduced. Write
3908 ** the code to "out". Make sure lineno stays up-to-date.
3910 PRIVATE void emit_code(
3911 FILE *out,
3912 struct rule *rp,
3913 struct lemon *lemp,
3914 int *lineno
3916 const char *cp;
3918 /* Setup code prior to the #line directive */
3919 if( rp->codePrefix && rp->codePrefix[0] ){
3920 fprintf(out, "{%s", rp->codePrefix);
3921 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3924 /* Generate code to do the reduce action */
3925 if( rp->code ){
3926 if( !lemp->nolinenosflag ){
3927 (*lineno)++;
3928 tplt_linedir(out,rp->line,lemp->filename);
3930 fprintf(out,"{%s",rp->code);
3931 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3932 fprintf(out,"}\n"); (*lineno)++;
3933 if( !lemp->nolinenosflag ){
3934 (*lineno)++;
3935 tplt_linedir(out,*lineno,lemp->outname);
3939 /* Generate breakdown code that occurs after the #line directive */
3940 if( rp->codeSuffix && rp->codeSuffix[0] ){
3941 fprintf(out, "%s", rp->codeSuffix);
3942 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3945 if( rp->codePrefix ){
3946 fprintf(out, "}\n"); (*lineno)++;
3949 return;
3953 ** Print the definition of the union used for the parser's data stack.
3954 ** This union contains fields for every possible data type for tokens
3955 ** and nonterminals. In the process of computing and printing this
3956 ** union, also set the ".dtnum" field of every terminal and nonterminal
3957 ** symbol.
3959 void print_stack_union(
3960 FILE *out, /* The output stream */
3961 struct lemon *lemp, /* The main info structure for this parser */
3962 int *plineno, /* Pointer to the line number */
3963 int mhflag /* True if generating makeheaders output */
3965 int lineno = *plineno; /* The line number of the output */
3966 char **types; /* A hash table of datatypes */
3967 int arraysize; /* Size of the "types" array */
3968 int maxdtlength; /* Maximum length of any ".datatype" field. */
3969 char *stddt; /* Standardized name for a datatype */
3970 int i,j; /* Loop counters */
3971 unsigned hash; /* For hashing the name of a type */
3972 const char *name; /* Name of the parser */
3974 /* Allocate and initialize types[] and allocate stddt[] */
3975 arraysize = lemp->nsymbol * 2;
3976 types = (char**)calloc( arraysize, sizeof(char*) );
3977 if( types==0 ){
3978 fprintf(stderr,"Out of memory.\n");
3979 exit(1);
3981 for(i=0; i<arraysize; i++) types[i] = 0;
3982 maxdtlength = 0;
3983 if( lemp->vartype ){
3984 maxdtlength = lemonStrlen(lemp->vartype);
3986 for(i=0; i<lemp->nsymbol; i++){
3987 int len;
3988 struct symbol *sp = lemp->symbols[i];
3989 if( sp->datatype==0 ) continue;
3990 len = lemonStrlen(sp->datatype);
3991 if( len>maxdtlength ) maxdtlength = len;
3993 stddt = (char*)malloc( maxdtlength*2 + 1 );
3994 if( stddt==0 ){
3995 fprintf(stderr,"Out of memory.\n");
3996 exit(1);
3999 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4000 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
4001 ** used for terminal symbols. If there is no %default_type defined then
4002 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4003 ** a datatype using the %type directive.
4005 for(i=0; i<lemp->nsymbol; i++){
4006 struct symbol *sp = lemp->symbols[i];
4007 char *cp;
4008 if( sp==lemp->errsym ){
4009 sp->dtnum = arraysize+1;
4010 continue;
4012 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
4013 sp->dtnum = 0;
4014 continue;
4016 cp = sp->datatype;
4017 if( cp==0 ) cp = lemp->vartype;
4018 j = 0;
4019 while( ISSPACE(*cp) ) cp++;
4020 while( *cp ) stddt[j++] = *cp++;
4021 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
4022 stddt[j] = 0;
4023 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
4024 sp->dtnum = 0;
4025 continue;
4027 hash = 0;
4028 for(j=0; stddt[j]; j++){
4029 hash = hash*53 + stddt[j];
4031 hash = (hash & 0x7fffffff)%arraysize;
4032 while( types[hash] ){
4033 if( strcmp(types[hash],stddt)==0 ){
4034 sp->dtnum = hash + 1;
4035 break;
4037 hash++;
4038 if( hash>=(unsigned)arraysize ) hash = 0;
4040 if( types[hash]==0 ){
4041 sp->dtnum = hash + 1;
4042 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
4043 if( types[hash]==0 ){
4044 fprintf(stderr,"Out of memory.\n");
4045 exit(1);
4047 lemon_strcpy(types[hash],stddt);
4051 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4052 name = lemp->name ? lemp->name : "Parse";
4053 lineno = *plineno;
4054 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4055 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4056 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4057 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4058 fprintf(out,"typedef union {\n"); lineno++;
4059 fprintf(out," int yyinit;\n"); lineno++;
4060 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4061 for(i=0; i<arraysize; i++){
4062 if( types[i]==0 ) continue;
4063 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4064 free(types[i]);
4066 if( lemp->errsym && lemp->errsym->useCnt ){
4067 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4069 free(stddt);
4070 free(types);
4071 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4072 *plineno = lineno;
4076 ** Return the name of a C datatype able to represent values between
4077 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4078 ** for that type (1, 2, or 4) into *pnByte.
4080 static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4081 const char *zType = "int";
4082 int nByte = 4;
4083 if( lwr>=0 ){
4084 if( upr<=255 ){
4085 zType = "unsigned char";
4086 nByte = 1;
4087 }else if( upr<65535 ){
4088 zType = "unsigned short int";
4089 nByte = 2;
4090 }else{
4091 zType = "unsigned int";
4092 nByte = 4;
4094 }else if( lwr>=-127 && upr<=127 ){
4095 zType = "signed char";
4096 nByte = 1;
4097 }else if( lwr>=-32767 && upr<32767 ){
4098 zType = "short";
4099 nByte = 2;
4101 if( pnByte ) *pnByte = nByte;
4102 return zType;
4106 ** Each state contains a set of token transaction and a set of
4107 ** nonterminal transactions. Each of these sets makes an instance
4108 ** of the following structure. An array of these structures is used
4109 ** to order the creation of entries in the yy_action[] table.
4111 struct axset {
4112 struct state *stp; /* A pointer to a state */
4113 int isTkn; /* True to use tokens. False for non-terminals */
4114 int nAction; /* Number of actions */
4115 int iOrder; /* Original order of action sets */
4119 ** Compare to axset structures for sorting purposes
4121 static int axset_compare(const void *a, const void *b){
4122 struct axset *p1 = (struct axset*)a;
4123 struct axset *p2 = (struct axset*)b;
4124 int c;
4125 c = p2->nAction - p1->nAction;
4126 if( c==0 ){
4127 c = p1->iOrder - p2->iOrder;
4129 assert( c!=0 || p1==p2 );
4130 return c;
4134 ** Write text on "out" that describes the rule "rp".
4136 static void writeRuleText(FILE *out, struct rule *rp){
4137 int j;
4138 fprintf(out,"%s ::=", rp->lhs->name);
4139 for(j=0; j<rp->nrhs; j++){
4140 struct symbol *sp = rp->rhs[j];
4141 if( sp->type!=MULTITERMINAL ){
4142 fprintf(out," %s", sp->name);
4143 }else{
4144 int k;
4145 fprintf(out," %s", sp->subsym[0]->name);
4146 for(k=1; k<sp->nsubsym; k++){
4147 fprintf(out,"|%s",sp->subsym[k]->name);
4154 /* Generate C source code for the parser */
4155 void ReportTable(
4156 struct lemon *lemp,
4157 int mhflag, /* Output in makeheaders format if true */
4158 int sqlFlag /* Generate the *.sql file too */
4160 FILE *out, *in, *sql;
4161 char line[LINESIZE];
4162 int lineno;
4163 struct state *stp;
4164 struct action *ap;
4165 struct rule *rp;
4166 struct acttab *pActtab;
4167 int i, j, n, sz;
4168 int nLookAhead;
4169 int szActionType; /* sizeof(YYACTIONTYPE) */
4170 int szCodeType; /* sizeof(YYCODETYPE) */
4171 const char *name;
4172 int mnTknOfst, mxTknOfst;
4173 int mnNtOfst, mxNtOfst;
4174 struct axset *ax;
4176 lemp->minShiftReduce = lemp->nstate;
4177 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4178 lemp->accAction = lemp->errAction + 1;
4179 lemp->noAction = lemp->accAction + 1;
4180 lemp->minReduce = lemp->noAction + 1;
4181 lemp->maxAction = lemp->minReduce + lemp->nrule;
4183 in = tplt_open(lemp);
4184 if( in==0 ) return;
4185 out = file_open(lemp,".c","wb");
4186 if( out==0 ){
4187 fclose(in);
4188 return;
4190 if( sqlFlag==0 ){
4191 sql = 0;
4192 }else{
4193 sql = file_open(lemp, ".sql", "wb");
4194 if( sql==0 ){
4195 fclose(in);
4196 fclose(out);
4197 return;
4199 fprintf(sql,
4200 "BEGIN;\n"
4201 "CREATE TABLE symbol(\n"
4202 " id INTEGER PRIMARY KEY,\n"
4203 " name TEXT NOT NULL,\n"
4204 " isTerminal BOOLEAN NOT NULL,\n"
4205 " fallback INTEGER REFERENCES symbol"
4206 " DEFERRABLE INITIALLY DEFERRED\n"
4207 ");\n"
4209 for(i=0; i<lemp->nsymbol; i++){
4210 fprintf(sql,
4211 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4212 "VALUES(%d,'%s',%s",
4213 i, lemp->symbols[i]->name,
4214 i<lemp->nterminal ? "TRUE" : "FALSE"
4216 if( lemp->symbols[i]->fallback ){
4217 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
4218 }else{
4219 fprintf(sql, ",NULL);\n");
4222 fprintf(sql,
4223 "CREATE TABLE rule(\n"
4224 " ruleid INTEGER PRIMARY KEY,\n"
4225 " lhs INTEGER REFERENCES symbol(id),\n"
4226 " txt TEXT\n"
4227 ");\n"
4228 "CREATE TABLE rulerhs(\n"
4229 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4230 " pos INTEGER,\n"
4231 " sym INTEGER REFERENCES symbol(id)\n"
4232 ");\n"
4234 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4235 assert( i==rp->iRule );
4236 fprintf(sql,
4237 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
4238 rp->iRule, rp->lhs->index
4240 writeRuleText(sql, rp);
4241 fprintf(sql,"');\n");
4242 for(j=0; j<rp->nrhs; j++){
4243 struct symbol *sp = rp->rhs[j];
4244 if( sp->type!=MULTITERMINAL ){
4245 fprintf(sql,
4246 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4247 i,j,sp->index
4249 }else{
4250 int k;
4251 for(k=0; k<sp->nsubsym; k++){
4252 fprintf(sql,
4253 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4254 i,j,sp->subsym[k]->index
4260 fprintf(sql, "COMMIT;\n");
4262 lineno = 1;
4263 tplt_xfer(lemp->name,in,out,&lineno);
4265 /* Generate the include code, if any */
4266 tplt_print(out,lemp,lemp->include,&lineno);
4267 if( mhflag ){
4268 char *incName = file_makename(lemp, ".h");
4269 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4270 free(incName);
4272 tplt_xfer(lemp->name,in,out,&lineno);
4274 /* Generate #defines for all tokens */
4275 if( mhflag ){
4276 const char *prefix;
4277 fprintf(out,"#if INTERFACE\n"); lineno++;
4278 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4279 else prefix = "";
4280 for(i=1; i<lemp->nterminal; i++){
4281 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4282 lineno++;
4284 fprintf(out,"#endif\n"); lineno++;
4286 tplt_xfer(lemp->name,in,out,&lineno);
4288 /* Generate the defines */
4289 fprintf(out,"#define YYCODETYPE %s\n",
4290 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4291 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
4292 fprintf(out,"#define YYACTIONTYPE %s\n",
4293 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
4294 if( lemp->wildcard ){
4295 fprintf(out,"#define YYWILDCARD %d\n",
4296 lemp->wildcard->index); lineno++;
4298 print_stack_union(out,lemp,&lineno,mhflag);
4299 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
4300 if( lemp->stacksize ){
4301 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4302 }else{
4303 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4305 fprintf(out, "#endif\n"); lineno++;
4306 if( mhflag ){
4307 fprintf(out,"#if INTERFACE\n"); lineno++;
4309 name = lemp->name ? lemp->name : "Parse";
4310 if( lemp->arg && lemp->arg[0] ){
4311 i = lemonStrlen(lemp->arg);
4312 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4313 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
4314 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4315 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4316 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4317 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
4318 name,lemp->arg,&lemp->arg[i]); lineno++;
4319 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
4320 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
4321 }else{
4322 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4323 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4324 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
4325 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4326 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
4328 if( lemp->ctx && lemp->ctx[0] ){
4329 i = lemonStrlen(lemp->ctx);
4330 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4331 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4332 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4333 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4334 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4335 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4336 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4337 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4338 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4339 }else{
4340 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4341 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4342 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4343 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4344 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4346 if( mhflag ){
4347 fprintf(out,"#endif\n"); lineno++;
4349 if( lemp->errsym && lemp->errsym->useCnt ){
4350 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4351 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
4353 if( lemp->has_fallback ){
4354 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4357 /* Compute the action table, but do not output it yet. The action
4358 ** table must be computed before generating the YYNSTATE macro because
4359 ** we need to know how many states can be eliminated.
4361 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
4362 if( ax==0 ){
4363 fprintf(stderr,"malloc failed\n");
4364 exit(1);
4366 for(i=0; i<lemp->nxstate; i++){
4367 stp = lemp->sorted[i];
4368 ax[i*2].stp = stp;
4369 ax[i*2].isTkn = 1;
4370 ax[i*2].nAction = stp->nTknAct;
4371 ax[i*2+1].stp = stp;
4372 ax[i*2+1].isTkn = 0;
4373 ax[i*2+1].nAction = stp->nNtAct;
4375 mxTknOfst = mnTknOfst = 0;
4376 mxNtOfst = mnNtOfst = 0;
4377 /* In an effort to minimize the action table size, use the heuristic
4378 ** of placing the largest action sets first */
4379 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4380 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
4381 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
4382 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
4383 stp = ax[i].stp;
4384 if( ax[i].isTkn ){
4385 for(ap=stp->ap; ap; ap=ap->next){
4386 int action;
4387 if( ap->sp->index>=lemp->nterminal ) continue;
4388 action = compute_action(lemp, ap);
4389 if( action<0 ) continue;
4390 acttab_action(pActtab, ap->sp->index, action);
4392 stp->iTknOfst = acttab_insert(pActtab, 1);
4393 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4394 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4395 }else{
4396 for(ap=stp->ap; ap; ap=ap->next){
4397 int action;
4398 if( ap->sp->index<lemp->nterminal ) continue;
4399 if( ap->sp->index==lemp->nsymbol ) continue;
4400 action = compute_action(lemp, ap);
4401 if( action<0 ) continue;
4402 acttab_action(pActtab, ap->sp->index, action);
4404 stp->iNtOfst = acttab_insert(pActtab, 0);
4405 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4406 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
4408 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4409 { int jj, nn;
4410 for(jj=nn=0; jj<pActtab->nAction; jj++){
4411 if( pActtab->aAction[jj].action<0 ) nn++;
4413 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4414 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4415 ax[i].nAction, pActtab->nAction, nn);
4417 #endif
4419 free(ax);
4421 /* Mark rules that are actually used for reduce actions after all
4422 ** optimizations have been applied
4424 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4425 for(i=0; i<lemp->nxstate; i++){
4426 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4427 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
4428 ap->x.rp->doesReduce = 1;
4433 /* Finish rendering the constants now that the action table has
4434 ** been computed */
4435 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4436 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
4437 fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
4438 lineno++;
4439 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
4440 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
4441 i = lemp->minShiftReduce;
4442 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4443 i += lemp->nrule;
4444 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4445 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4446 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4447 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4448 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4449 i = lemp->minReduce + lemp->nrule;
4450 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4451 tplt_xfer(lemp->name,in,out,&lineno);
4453 /* Now output the action table and its associates:
4455 ** yy_action[] A single table containing all actions.
4456 ** yy_lookahead[] A table containing the lookahead for each entry in
4457 ** yy_action. Used to detect hash collisions.
4458 ** yy_shift_ofst[] For each state, the offset into yy_action for
4459 ** shifting terminals.
4460 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4461 ** shifting non-terminals after a reduce.
4462 ** yy_default[] Default action for each state.
4465 /* Output the yy_action table */
4466 lemp->nactiontab = n = acttab_action_size(pActtab);
4467 lemp->tablesize += n*szActionType;
4468 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4469 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
4470 for(i=j=0; i<n; i++){
4471 int action = acttab_yyaction(pActtab, i);
4472 if( action<0 ) action = lemp->noAction;
4473 if( j==0 ) fprintf(out," /* %5d */ ", i);
4474 fprintf(out, " %4d,", action);
4475 if( j==9 || i==n-1 ){
4476 fprintf(out, "\n"); lineno++;
4477 j = 0;
4478 }else{
4479 j++;
4482 fprintf(out, "};\n"); lineno++;
4484 /* Output the yy_lookahead table */
4485 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
4486 lemp->tablesize += n*szCodeType;
4487 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
4488 for(i=j=0; i<n; i++){
4489 int la = acttab_yylookahead(pActtab, i);
4490 if( la<0 ) la = lemp->nsymbol;
4491 if( j==0 ) fprintf(out," /* %5d */ ", i);
4492 fprintf(out, " %4d,", la);
4493 if( j==9 ){
4494 fprintf(out, "\n"); lineno++;
4495 j = 0;
4496 }else{
4497 j++;
4500 /* Add extra entries to the end of the yy_lookahead[] table so that
4501 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4502 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4503 nLookAhead = lemp->nterminal + lemp->nactiontab;
4504 while( i<nLookAhead ){
4505 if( j==0 ) fprintf(out," /* %5d */ ", i);
4506 fprintf(out, " %4d,", lemp->nterminal);
4507 if( j==9 ){
4508 fprintf(out, "\n"); lineno++;
4509 j = 0;
4510 }else{
4511 j++;
4513 i++;
4515 if( j>0 ){ fprintf(out, "\n"); lineno++; }
4516 fprintf(out, "};\n"); lineno++;
4518 /* Output the yy_shift_ofst[] table */
4519 n = lemp->nxstate;
4520 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
4521 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4522 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4523 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
4524 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
4525 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4526 lineno++;
4527 lemp->tablesize += n*sz;
4528 for(i=j=0; i<n; i++){
4529 int ofst;
4530 stp = lemp->sorted[i];
4531 ofst = stp->iTknOfst;
4532 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
4533 if( j==0 ) fprintf(out," /* %5d */ ", i);
4534 fprintf(out, " %4d,", ofst);
4535 if( j==9 || i==n-1 ){
4536 fprintf(out, "\n"); lineno++;
4537 j = 0;
4538 }else{
4539 j++;
4542 fprintf(out, "};\n"); lineno++;
4544 /* Output the yy_reduce_ofst[] table */
4545 n = lemp->nxstate;
4546 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
4547 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4548 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4549 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
4550 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
4551 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4552 lemp->tablesize += n*sz;
4553 for(i=j=0; i<n; i++){
4554 int ofst;
4555 stp = lemp->sorted[i];
4556 ofst = stp->iNtOfst;
4557 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
4558 if( j==0 ) fprintf(out," /* %5d */ ", i);
4559 fprintf(out, " %4d,", ofst);
4560 if( j==9 || i==n-1 ){
4561 fprintf(out, "\n"); lineno++;
4562 j = 0;
4563 }else{
4564 j++;
4567 fprintf(out, "};\n"); lineno++;
4569 /* Output the default action table */
4570 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
4571 n = lemp->nxstate;
4572 lemp->tablesize += n*szActionType;
4573 for(i=j=0; i<n; i++){
4574 stp = lemp->sorted[i];
4575 if( j==0 ) fprintf(out," /* %5d */ ", i);
4576 if( stp->iDfltReduce<0 ){
4577 fprintf(out, " %4d,", lemp->errAction);
4578 }else{
4579 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4581 if( j==9 || i==n-1 ){
4582 fprintf(out, "\n"); lineno++;
4583 j = 0;
4584 }else{
4585 j++;
4588 fprintf(out, "};\n"); lineno++;
4589 tplt_xfer(lemp->name,in,out,&lineno);
4591 /* Generate the table of fallback tokens.
4593 if( lemp->has_fallback ){
4594 int mx = lemp->nterminal - 1;
4595 /* 2019-08-28: Generate fallback entries for every token to avoid
4596 ** having to do a range check on the index */
4597 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
4598 lemp->tablesize += (mx+1)*szCodeType;
4599 for(i=0; i<=mx; i++){
4600 struct symbol *p = lemp->symbols[i];
4601 if( p->fallback==0 ){
4602 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4603 }else{
4604 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4605 p->name, p->fallback->name);
4607 lineno++;
4610 tplt_xfer(lemp->name, in, out, &lineno);
4612 /* Generate a table containing the symbolic name of every symbol
4614 for(i=0; i<lemp->nsymbol; i++){
4615 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
4616 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
4618 tplt_xfer(lemp->name,in,out,&lineno);
4620 /* Generate a table containing a text string that describes every
4621 ** rule in the rule set of the grammar. This information is used
4622 ** when tracing REDUCE actions.
4624 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4625 assert( rp->iRule==i );
4626 fprintf(out," /* %3d */ \"", i);
4627 writeRuleText(out, rp);
4628 fprintf(out,"\",\n"); lineno++;
4630 tplt_xfer(lemp->name,in,out,&lineno);
4632 /* Generate code which executes every time a symbol is popped from
4633 ** the stack while processing errors or while destroying the parser.
4634 ** (In other words, generate the %destructor actions)
4636 if( lemp->tokendest ){
4637 int once = 1;
4638 for(i=0; i<lemp->nsymbol; i++){
4639 struct symbol *sp = lemp->symbols[i];
4640 if( sp==0 || sp->type!=TERMINAL ) continue;
4641 if( once ){
4642 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4643 once = 0;
4645 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4647 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4648 if( i<lemp->nsymbol ){
4649 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4650 fprintf(out," break;\n"); lineno++;
4653 if( lemp->vardest ){
4654 struct symbol *dflt_sp = 0;
4655 int once = 1;
4656 for(i=0; i<lemp->nsymbol; i++){
4657 struct symbol *sp = lemp->symbols[i];
4658 if( sp==0 || sp->type==TERMINAL ||
4659 sp->index<=0 || sp->destructor!=0 ) continue;
4660 if( once ){
4661 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
4662 once = 0;
4664 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4665 dflt_sp = sp;
4667 if( dflt_sp!=0 ){
4668 emit_destructor_code(out,dflt_sp,lemp,&lineno);
4670 fprintf(out," break;\n"); lineno++;
4672 for(i=0; i<lemp->nsymbol; i++){
4673 struct symbol *sp = lemp->symbols[i];
4674 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
4675 if( sp->destLineno<0 ) continue; /* Already emitted */
4676 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4678 /* Combine duplicate destructors into a single case */
4679 for(j=i+1; j<lemp->nsymbol; j++){
4680 struct symbol *sp2 = lemp->symbols[j];
4681 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4682 && sp2->dtnum==sp->dtnum
4683 && strcmp(sp->destructor,sp2->destructor)==0 ){
4684 fprintf(out," case %d: /* %s */\n",
4685 sp2->index, sp2->name); lineno++;
4686 sp2->destLineno = -1; /* Avoid emitting this destructor again */
4690 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4691 fprintf(out," break;\n"); lineno++;
4693 tplt_xfer(lemp->name,in,out,&lineno);
4695 /* Generate code which executes whenever the parser stack overflows */
4696 tplt_print(out,lemp,lemp->overflow,&lineno);
4697 tplt_xfer(lemp->name,in,out,&lineno);
4699 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4700 ** yyRuleInfoNRhs[].
4702 ** Note: This code depends on the fact that rules are number
4703 ** sequentually beginning with 0.
4705 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4706 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4707 rule_print(out, rp);
4708 fprintf(out," */\n"); lineno++;
4710 tplt_xfer(lemp->name,in,out,&lineno);
4711 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4712 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
4713 rule_print(out, rp);
4714 fprintf(out," */\n"); lineno++;
4716 tplt_xfer(lemp->name,in,out,&lineno);
4718 /* Generate code which execution during each REDUCE action */
4719 i = 0;
4720 for(rp=lemp->rule; rp; rp=rp->next){
4721 i += translate_code(lemp, rp);
4723 if( i ){
4724 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
4726 /* First output rules other than the default: rule */
4727 for(rp=lemp->rule; rp; rp=rp->next){
4728 struct rule *rp2; /* Other rules with the same action */
4729 if( rp->codeEmitted ) continue;
4730 if( rp->noCode ){
4731 /* No C code actions, so this will be part of the "default:" rule */
4732 continue;
4734 fprintf(out," case %d: /* ", rp->iRule);
4735 writeRuleText(out, rp);
4736 fprintf(out, " */\n"); lineno++;
4737 for(rp2=rp->next; rp2; rp2=rp2->next){
4738 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4739 && rp2->codeSuffix==rp->codeSuffix ){
4740 fprintf(out," case %d: /* ", rp2->iRule);
4741 writeRuleText(out, rp2);
4742 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
4743 rp2->codeEmitted = 1;
4746 emit_code(out,rp,lemp,&lineno);
4747 fprintf(out," break;\n"); lineno++;
4748 rp->codeEmitted = 1;
4750 /* Finally, output the default: rule. We choose as the default: all
4751 ** empty actions. */
4752 fprintf(out," default:\n"); lineno++;
4753 for(rp=lemp->rule; rp; rp=rp->next){
4754 if( rp->codeEmitted ) continue;
4755 assert( rp->noCode );
4756 fprintf(out," /* (%d) ", rp->iRule);
4757 writeRuleText(out, rp);
4758 if( rp->neverReduce ){
4759 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
4760 rp->iRule); lineno++;
4761 }else if( rp->doesReduce ){
4762 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4763 }else{
4764 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4765 rp->iRule); lineno++;
4768 fprintf(out," break;\n"); lineno++;
4769 tplt_xfer(lemp->name,in,out,&lineno);
4771 /* Generate code which executes if a parse fails */
4772 tplt_print(out,lemp,lemp->failure,&lineno);
4773 tplt_xfer(lemp->name,in,out,&lineno);
4775 /* Generate code which executes when a syntax error occurs */
4776 tplt_print(out,lemp,lemp->error,&lineno);
4777 tplt_xfer(lemp->name,in,out,&lineno);
4779 /* Generate code which executes when the parser accepts its input */
4780 tplt_print(out,lemp,lemp->accept,&lineno);
4781 tplt_xfer(lemp->name,in,out,&lineno);
4783 /* Append any addition code the user desires */
4784 tplt_print(out,lemp,lemp->extracode,&lineno);
4786 acttab_free(pActtab);
4787 fclose(in);
4788 fclose(out);
4789 if( sql ) fclose(sql);
4790 return;
4793 /* Generate a header file for the parser */
4794 void ReportHeader(struct lemon *lemp)
4796 FILE *out, *in;
4797 const char *prefix;
4798 char line[LINESIZE];
4799 char pattern[LINESIZE];
4800 int i;
4802 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4803 else prefix = "";
4804 in = file_open(lemp,".h","rb");
4805 if( in ){
4806 int nextChar;
4807 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4808 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4809 prefix,lemp->symbols[i]->name,i);
4810 if( strcmp(line,pattern) ) break;
4812 nextChar = fgetc(in);
4813 fclose(in);
4814 if( i==lemp->nterminal && nextChar==EOF ){
4815 /* No change in the file. Don't rewrite it. */
4816 return;
4819 out = file_open(lemp,".h","wb");
4820 if( out ){
4821 for(i=1; i<lemp->nterminal; i++){
4822 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
4824 fclose(out);
4826 return;
4829 /* Reduce the size of the action tables, if possible, by making use
4830 ** of defaults.
4832 ** In this version, we take the most frequent REDUCE action and make
4833 ** it the default. Except, there is no default if the wildcard token
4834 ** is a possible look-ahead.
4836 void CompressTables(struct lemon *lemp)
4838 struct state *stp;
4839 struct action *ap, *ap2, *nextap;
4840 struct rule *rp, *rp2, *rbest;
4841 int nbest, n;
4842 int i;
4843 int usesWildcard;
4845 for(i=0; i<lemp->nstate; i++){
4846 stp = lemp->sorted[i];
4847 nbest = 0;
4848 rbest = 0;
4849 usesWildcard = 0;
4851 for(ap=stp->ap; ap; ap=ap->next){
4852 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4853 usesWildcard = 1;
4855 if( ap->type!=REDUCE ) continue;
4856 rp = ap->x.rp;
4857 if( rp->lhsStart ) continue;
4858 if( rp==rbest ) continue;
4859 n = 1;
4860 for(ap2=ap->next; ap2; ap2=ap2->next){
4861 if( ap2->type!=REDUCE ) continue;
4862 rp2 = ap2->x.rp;
4863 if( rp2==rbest ) continue;
4864 if( rp2==rp ) n++;
4866 if( n>nbest ){
4867 nbest = n;
4868 rbest = rp;
4872 /* Do not make a default if the number of rules to default
4873 ** is not at least 1 or if the wildcard token is a possible
4874 ** lookahead.
4876 if( nbest<1 || usesWildcard ) continue;
4879 /* Combine matching REDUCE actions into a single default */
4880 for(ap=stp->ap; ap; ap=ap->next){
4881 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4883 assert( ap );
4884 ap->sp = Symbol_new("{default}");
4885 for(ap=ap->next; ap; ap=ap->next){
4886 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
4888 stp->ap = Action_sort(stp->ap);
4890 for(ap=stp->ap; ap; ap=ap->next){
4891 if( ap->type==SHIFT ) break;
4892 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4894 if( ap==0 ){
4895 stp->autoReduce = 1;
4896 stp->pDfltReduce = rbest;
4900 /* Make a second pass over all states and actions. Convert
4901 ** every action that is a SHIFT to an autoReduce state into
4902 ** a SHIFTREDUCE action.
4904 for(i=0; i<lemp->nstate; i++){
4905 stp = lemp->sorted[i];
4906 for(ap=stp->ap; ap; ap=ap->next){
4907 struct state *pNextState;
4908 if( ap->type!=SHIFT ) continue;
4909 pNextState = ap->x.stp;
4910 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4911 ap->type = SHIFTREDUCE;
4912 ap->x.rp = pNextState->pDfltReduce;
4917 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4918 ** (meaning that the SHIFTREDUCE will land back in the state where it
4919 ** started) and if there is no C-code associated with the reduce action,
4920 ** then we can go ahead and convert the action to be the same as the
4921 ** action for the RHS of the rule.
4923 for(i=0; i<lemp->nstate; i++){
4924 stp = lemp->sorted[i];
4925 for(ap=stp->ap; ap; ap=nextap){
4926 nextap = ap->next;
4927 if( ap->type!=SHIFTREDUCE ) continue;
4928 rp = ap->x.rp;
4929 if( rp->noCode==0 ) continue;
4930 if( rp->nrhs!=1 ) continue;
4931 #if 1
4932 /* Only apply this optimization to non-terminals. It would be OK to
4933 ** apply it to terminal symbols too, but that makes the parser tables
4934 ** larger. */
4935 if( ap->sp->index<lemp->nterminal ) continue;
4936 #endif
4937 /* If we reach this point, it means the optimization can be applied */
4938 nextap = ap;
4939 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4940 assert( ap2!=0 );
4941 ap->spOpt = ap2->sp;
4942 ap->type = ap2->type;
4943 ap->x = ap2->x;
4950 ** Compare two states for sorting purposes. The smaller state is the
4951 ** one with the most non-terminal actions. If they have the same number
4952 ** of non-terminal actions, then the smaller is the one with the most
4953 ** token actions.
4955 static int stateResortCompare(const void *a, const void *b){
4956 const struct state *pA = *(const struct state**)a;
4957 const struct state *pB = *(const struct state**)b;
4958 int n;
4960 n = pB->nNtAct - pA->nNtAct;
4961 if( n==0 ){
4962 n = pB->nTknAct - pA->nTknAct;
4963 if( n==0 ){
4964 n = pB->statenum - pA->statenum;
4967 assert( n!=0 );
4968 return n;
4973 ** Renumber and resort states so that states with fewer choices
4974 ** occur at the end. Except, keep state 0 as the first state.
4976 void ResortStates(struct lemon *lemp)
4978 int i;
4979 struct state *stp;
4980 struct action *ap;
4982 for(i=0; i<lemp->nstate; i++){
4983 stp = lemp->sorted[i];
4984 stp->nTknAct = stp->nNtAct = 0;
4985 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
4986 stp->iTknOfst = NO_OFFSET;
4987 stp->iNtOfst = NO_OFFSET;
4988 for(ap=stp->ap; ap; ap=ap->next){
4989 int iAction = compute_action(lemp,ap);
4990 if( iAction>=0 ){
4991 if( ap->sp->index<lemp->nterminal ){
4992 stp->nTknAct++;
4993 }else if( ap->sp->index<lemp->nsymbol ){
4994 stp->nNtAct++;
4995 }else{
4996 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4997 stp->iDfltReduce = iAction;
5002 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
5003 stateResortCompare);
5004 for(i=0; i<lemp->nstate; i++){
5005 lemp->sorted[i]->statenum = i;
5007 lemp->nxstate = lemp->nstate;
5008 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
5009 lemp->nxstate--;
5014 /***************** From the file "set.c" ************************************/
5016 ** Set manipulation routines for the LEMON parser generator.
5019 static int size = 0;
5021 /* Set the set size */
5022 void SetSize(int n)
5024 size = n+1;
5027 /* Allocate a new set */
5028 char *SetNew(void){
5029 char *s;
5030 s = (char*)calloc( size, 1);
5031 if( s==0 ){
5032 memory_error();
5034 return s;
5037 /* Deallocate a set */
5038 void SetFree(char *s)
5040 free(s);
5043 /* Add a new element to the set. Return TRUE if the element was added
5044 ** and FALSE if it was already there. */
5045 int SetAdd(char *s, int e)
5047 int rv;
5048 assert( e>=0 && e<size );
5049 rv = s[e];
5050 s[e] = 1;
5051 return !rv;
5054 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
5055 int SetUnion(char *s1, char *s2)
5057 int i, progress;
5058 progress = 0;
5059 for(i=0; i<size; i++){
5060 if( s2[i]==0 ) continue;
5061 if( s1[i]==0 ){
5062 progress = 1;
5063 s1[i] = 1;
5066 return progress;
5068 /********************** From the file "table.c" ****************************/
5070 ** All code in this file has been automatically generated
5071 ** from a specification in the file
5072 ** "table.q"
5073 ** by the associative array code building program "aagen".
5074 ** Do not edit this file! Instead, edit the specification
5075 ** file, then rerun aagen.
5078 ** Code for processing tables in the LEMON parser generator.
5081 PRIVATE unsigned strhash(const char *x)
5083 unsigned h = 0;
5084 while( *x ) h = h*13 + *(x++);
5085 return h;
5088 /* Works like strdup, sort of. Save a string in malloced memory, but
5089 ** keep strings in a table so that the same string is not in more
5090 ** than one place.
5092 const char *Strsafe(const char *y)
5094 const char *z;
5095 char *cpy;
5097 if( y==0 ) return 0;
5098 z = Strsafe_find(y);
5099 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
5100 lemon_strcpy(cpy,y);
5101 z = cpy;
5102 Strsafe_insert(z);
5104 MemoryCheck(z);
5105 return z;
5108 /* There is one instance of the following structure for each
5109 ** associative array of type "x1".
5111 struct s_x1 {
5112 int size; /* The number of available slots. */
5113 /* Must be a power of 2 greater than or */
5114 /* equal to 1 */
5115 int count; /* Number of currently slots filled */
5116 struct s_x1node *tbl; /* The data stored here */
5117 struct s_x1node **ht; /* Hash table for lookups */
5120 /* There is one instance of this structure for every data element
5121 ** in an associative array of type "x1".
5123 typedef struct s_x1node {
5124 const char *data; /* The data */
5125 struct s_x1node *next; /* Next entry with the same hash */
5126 struct s_x1node **from; /* Previous link */
5127 } x1node;
5129 /* There is only one instance of the array, which is the following */
5130 static struct s_x1 *x1a;
5132 /* Allocate a new associative array */
5133 void Strsafe_init(void){
5134 if( x1a ) return;
5135 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5136 if( x1a ){
5137 x1a->size = 1024;
5138 x1a->count = 0;
5139 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
5140 if( x1a->tbl==0 ){
5141 free(x1a);
5142 x1a = 0;
5143 }else{
5144 int i;
5145 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5146 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5150 /* Insert a new record into the array. Return TRUE if successful.
5151 ** Prior data with the same key is NOT overwritten */
5152 int Strsafe_insert(const char *data)
5154 x1node *np;
5155 unsigned h;
5156 unsigned ph;
5158 if( x1a==0 ) return 0;
5159 ph = strhash(data);
5160 h = ph & (x1a->size-1);
5161 np = x1a->ht[h];
5162 while( np ){
5163 if( strcmp(np->data,data)==0 ){
5164 /* An existing entry with the same key is found. */
5165 /* Fail because overwrite is not allows. */
5166 return 0;
5168 np = np->next;
5170 if( x1a->count>=x1a->size ){
5171 /* Need to make the hash table bigger */
5172 int i,arrSize;
5173 struct s_x1 array;
5174 array.size = arrSize = x1a->size*2;
5175 array.count = x1a->count;
5176 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
5177 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5178 array.ht = (x1node**)&(array.tbl[arrSize]);
5179 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5180 for(i=0; i<x1a->count; i++){
5181 x1node *oldnp, *newnp;
5182 oldnp = &(x1a->tbl[i]);
5183 h = strhash(oldnp->data) & (arrSize-1);
5184 newnp = &(array.tbl[i]);
5185 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5186 newnp->next = array.ht[h];
5187 newnp->data = oldnp->data;
5188 newnp->from = &(array.ht[h]);
5189 array.ht[h] = newnp;
5191 free(x1a->tbl);
5192 *x1a = array;
5194 /* Insert the new data */
5195 h = ph & (x1a->size-1);
5196 np = &(x1a->tbl[x1a->count++]);
5197 np->data = data;
5198 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5199 np->next = x1a->ht[h];
5200 x1a->ht[h] = np;
5201 np->from = &(x1a->ht[h]);
5202 return 1;
5205 /* Return a pointer to data assigned to the given key. Return NULL
5206 ** if no such key. */
5207 const char *Strsafe_find(const char *key)
5209 unsigned h;
5210 x1node *np;
5212 if( x1a==0 ) return 0;
5213 h = strhash(key) & (x1a->size-1);
5214 np = x1a->ht[h];
5215 while( np ){
5216 if( strcmp(np->data,key)==0 ) break;
5217 np = np->next;
5219 return np ? np->data : 0;
5222 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5223 ** Create a new symbol if this is the first time "x" has been seen.
5225 struct symbol *Symbol_new(const char *x)
5227 struct symbol *sp;
5229 sp = Symbol_find(x);
5230 if( sp==0 ){
5231 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
5232 MemoryCheck(sp);
5233 sp->name = Strsafe(x);
5234 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
5235 sp->rule = 0;
5236 sp->fallback = 0;
5237 sp->prec = -1;
5238 sp->assoc = UNK;
5239 sp->firstset = 0;
5240 sp->lambda = LEMON_FALSE;
5241 sp->destructor = 0;
5242 sp->destLineno = 0;
5243 sp->datatype = 0;
5244 sp->useCnt = 0;
5245 Symbol_insert(sp,sp->name);
5247 sp->useCnt++;
5248 return sp;
5251 /* Compare two symbols for sorting purposes. Return negative,
5252 ** zero, or positive if a is less then, equal to, or greater
5253 ** than b.
5255 ** Symbols that begin with upper case letters (terminals or tokens)
5256 ** must sort before symbols that begin with lower case letters
5257 ** (non-terminals). And MULTITERMINAL symbols (created using the
5258 ** %token_class directive) must sort at the very end. Other than
5259 ** that, the order does not matter.
5261 ** We find experimentally that leaving the symbols in their original
5262 ** order (the order they appeared in the grammar file) gives the
5263 ** smallest parser tables in SQLite.
5265 int Symbolcmpp(const void *_a, const void *_b)
5267 const struct symbol *a = *(const struct symbol **) _a;
5268 const struct symbol *b = *(const struct symbol **) _b;
5269 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5270 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5271 return i1==i2 ? a->index - b->index : i1 - i2;
5274 /* There is one instance of the following structure for each
5275 ** associative array of type "x2".
5277 struct s_x2 {
5278 int size; /* The number of available slots. */
5279 /* Must be a power of 2 greater than or */
5280 /* equal to 1 */
5281 int count; /* Number of currently slots filled */
5282 struct s_x2node *tbl; /* The data stored here */
5283 struct s_x2node **ht; /* Hash table for lookups */
5286 /* There is one instance of this structure for every data element
5287 ** in an associative array of type "x2".
5289 typedef struct s_x2node {
5290 struct symbol *data; /* The data */
5291 const char *key; /* The key */
5292 struct s_x2node *next; /* Next entry with the same hash */
5293 struct s_x2node **from; /* Previous link */
5294 } x2node;
5296 /* There is only one instance of the array, which is the following */
5297 static struct s_x2 *x2a;
5299 /* Allocate a new associative array */
5300 void Symbol_init(void){
5301 if( x2a ) return;
5302 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5303 if( x2a ){
5304 x2a->size = 128;
5305 x2a->count = 0;
5306 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
5307 if( x2a->tbl==0 ){
5308 free(x2a);
5309 x2a = 0;
5310 }else{
5311 int i;
5312 x2a->ht = (x2node**)&(x2a->tbl[128]);
5313 for(i=0; i<128; i++) x2a->ht[i] = 0;
5317 /* Insert a new record into the array. Return TRUE if successful.
5318 ** Prior data with the same key is NOT overwritten */
5319 int Symbol_insert(struct symbol *data, const char *key)
5321 x2node *np;
5322 unsigned h;
5323 unsigned ph;
5325 if( x2a==0 ) return 0;
5326 ph = strhash(key);
5327 h = ph & (x2a->size-1);
5328 np = x2a->ht[h];
5329 while( np ){
5330 if( strcmp(np->key,key)==0 ){
5331 /* An existing entry with the same key is found. */
5332 /* Fail because overwrite is not allows. */
5333 return 0;
5335 np = np->next;
5337 if( x2a->count>=x2a->size ){
5338 /* Need to make the hash table bigger */
5339 int i,arrSize;
5340 struct s_x2 array;
5341 array.size = arrSize = x2a->size*2;
5342 array.count = x2a->count;
5343 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
5344 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5345 array.ht = (x2node**)&(array.tbl[arrSize]);
5346 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5347 for(i=0; i<x2a->count; i++){
5348 x2node *oldnp, *newnp;
5349 oldnp = &(x2a->tbl[i]);
5350 h = strhash(oldnp->key) & (arrSize-1);
5351 newnp = &(array.tbl[i]);
5352 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5353 newnp->next = array.ht[h];
5354 newnp->key = oldnp->key;
5355 newnp->data = oldnp->data;
5356 newnp->from = &(array.ht[h]);
5357 array.ht[h] = newnp;
5359 free(x2a->tbl);
5360 *x2a = array;
5362 /* Insert the new data */
5363 h = ph & (x2a->size-1);
5364 np = &(x2a->tbl[x2a->count++]);
5365 np->key = key;
5366 np->data = data;
5367 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5368 np->next = x2a->ht[h];
5369 x2a->ht[h] = np;
5370 np->from = &(x2a->ht[h]);
5371 return 1;
5374 /* Return a pointer to data assigned to the given key. Return NULL
5375 ** if no such key. */
5376 struct symbol *Symbol_find(const char *key)
5378 unsigned h;
5379 x2node *np;
5381 if( x2a==0 ) return 0;
5382 h = strhash(key) & (x2a->size-1);
5383 np = x2a->ht[h];
5384 while( np ){
5385 if( strcmp(np->key,key)==0 ) break;
5386 np = np->next;
5388 return np ? np->data : 0;
5391 /* Return the n-th data. Return NULL if n is out of range. */
5392 struct symbol *Symbol_Nth(int n)
5394 struct symbol *data;
5395 if( x2a && n>0 && n<=x2a->count ){
5396 data = x2a->tbl[n-1].data;
5397 }else{
5398 data = 0;
5400 return data;
5403 /* Return the size of the array */
5404 int Symbol_count()
5406 return x2a ? x2a->count : 0;
5409 /* Return an array of pointers to all data in the table.
5410 ** The array is obtained from malloc. Return NULL if memory allocation
5411 ** problems, or if the array is empty. */
5412 struct symbol **Symbol_arrayof()
5414 struct symbol **array;
5415 int i,arrSize;
5416 if( x2a==0 ) return 0;
5417 arrSize = x2a->count;
5418 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
5419 if( array ){
5420 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
5422 return array;
5425 /* Compare two configurations */
5426 int Configcmp(const char *_a,const char *_b)
5428 const struct config *a = (struct config *) _a;
5429 const struct config *b = (struct config *) _b;
5430 int x;
5431 x = a->rp->index - b->rp->index;
5432 if( x==0 ) x = a->dot - b->dot;
5433 return x;
5436 /* Compare two states */
5437 PRIVATE int statecmp(struct config *a, struct config *b)
5439 int rc;
5440 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5441 rc = a->rp->index - b->rp->index;
5442 if( rc==0 ) rc = a->dot - b->dot;
5444 if( rc==0 ){
5445 if( a ) rc = 1;
5446 if( b ) rc = -1;
5448 return rc;
5451 /* Hash a state */
5452 PRIVATE unsigned statehash(struct config *a)
5454 unsigned h=0;
5455 while( a ){
5456 h = h*571 + a->rp->index*37 + a->dot;
5457 a = a->bp;
5459 return h;
5462 /* Allocate a new state structure */
5463 struct state *State_new()
5465 struct state *newstate;
5466 newstate = (struct state *)calloc(1, sizeof(struct state) );
5467 MemoryCheck(newstate);
5468 return newstate;
5471 /* There is one instance of the following structure for each
5472 ** associative array of type "x3".
5474 struct s_x3 {
5475 int size; /* The number of available slots. */
5476 /* Must be a power of 2 greater than or */
5477 /* equal to 1 */
5478 int count; /* Number of currently slots filled */
5479 struct s_x3node *tbl; /* The data stored here */
5480 struct s_x3node **ht; /* Hash table for lookups */
5483 /* There is one instance of this structure for every data element
5484 ** in an associative array of type "x3".
5486 typedef struct s_x3node {
5487 struct state *data; /* The data */
5488 struct config *key; /* The key */
5489 struct s_x3node *next; /* Next entry with the same hash */
5490 struct s_x3node **from; /* Previous link */
5491 } x3node;
5493 /* There is only one instance of the array, which is the following */
5494 static struct s_x3 *x3a;
5496 /* Allocate a new associative array */
5497 void State_init(void){
5498 if( x3a ) return;
5499 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5500 if( x3a ){
5501 x3a->size = 128;
5502 x3a->count = 0;
5503 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
5504 if( x3a->tbl==0 ){
5505 free(x3a);
5506 x3a = 0;
5507 }else{
5508 int i;
5509 x3a->ht = (x3node**)&(x3a->tbl[128]);
5510 for(i=0; i<128; i++) x3a->ht[i] = 0;
5514 /* Insert a new record into the array. Return TRUE if successful.
5515 ** Prior data with the same key is NOT overwritten */
5516 int State_insert(struct state *data, struct config *key)
5518 x3node *np;
5519 unsigned h;
5520 unsigned ph;
5522 if( x3a==0 ) return 0;
5523 ph = statehash(key);
5524 h = ph & (x3a->size-1);
5525 np = x3a->ht[h];
5526 while( np ){
5527 if( statecmp(np->key,key)==0 ){
5528 /* An existing entry with the same key is found. */
5529 /* Fail because overwrite is not allows. */
5530 return 0;
5532 np = np->next;
5534 if( x3a->count>=x3a->size ){
5535 /* Need to make the hash table bigger */
5536 int i,arrSize;
5537 struct s_x3 array;
5538 array.size = arrSize = x3a->size*2;
5539 array.count = x3a->count;
5540 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
5541 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5542 array.ht = (x3node**)&(array.tbl[arrSize]);
5543 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5544 for(i=0; i<x3a->count; i++){
5545 x3node *oldnp, *newnp;
5546 oldnp = &(x3a->tbl[i]);
5547 h = statehash(oldnp->key) & (arrSize-1);
5548 newnp = &(array.tbl[i]);
5549 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5550 newnp->next = array.ht[h];
5551 newnp->key = oldnp->key;
5552 newnp->data = oldnp->data;
5553 newnp->from = &(array.ht[h]);
5554 array.ht[h] = newnp;
5556 free(x3a->tbl);
5557 *x3a = array;
5559 /* Insert the new data */
5560 h = ph & (x3a->size-1);
5561 np = &(x3a->tbl[x3a->count++]);
5562 np->key = key;
5563 np->data = data;
5564 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5565 np->next = x3a->ht[h];
5566 x3a->ht[h] = np;
5567 np->from = &(x3a->ht[h]);
5568 return 1;
5571 /* Return a pointer to data assigned to the given key. Return NULL
5572 ** if no such key. */
5573 struct state *State_find(struct config *key)
5575 unsigned h;
5576 x3node *np;
5578 if( x3a==0 ) return 0;
5579 h = statehash(key) & (x3a->size-1);
5580 np = x3a->ht[h];
5581 while( np ){
5582 if( statecmp(np->key,key)==0 ) break;
5583 np = np->next;
5585 return np ? np->data : 0;
5588 /* Return an array of pointers to all data in the table.
5589 ** The array is obtained from malloc. Return NULL if memory allocation
5590 ** problems, or if the array is empty. */
5591 struct state **State_arrayof(void)
5593 struct state **array;
5594 int i,arrSize;
5595 if( x3a==0 ) return 0;
5596 arrSize = x3a->count;
5597 array = (struct state **)calloc(arrSize, sizeof(struct state *));
5598 if( array ){
5599 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
5601 return array;
5604 /* Hash a configuration */
5605 PRIVATE unsigned confighash(struct config *a)
5607 unsigned h=0;
5608 h = h*571 + a->rp->index*37 + a->dot;
5609 return h;
5612 /* There is one instance of the following structure for each
5613 ** associative array of type "x4".
5615 struct s_x4 {
5616 int size; /* The number of available slots. */
5617 /* Must be a power of 2 greater than or */
5618 /* equal to 1 */
5619 int count; /* Number of currently slots filled */
5620 struct s_x4node *tbl; /* The data stored here */
5621 struct s_x4node **ht; /* Hash table for lookups */
5624 /* There is one instance of this structure for every data element
5625 ** in an associative array of type "x4".
5627 typedef struct s_x4node {
5628 struct config *data; /* The data */
5629 struct s_x4node *next; /* Next entry with the same hash */
5630 struct s_x4node **from; /* Previous link */
5631 } x4node;
5633 /* There is only one instance of the array, which is the following */
5634 static struct s_x4 *x4a;
5636 /* Allocate a new associative array */
5637 void Configtable_init(void){
5638 if( x4a ) return;
5639 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5640 if( x4a ){
5641 x4a->size = 64;
5642 x4a->count = 0;
5643 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
5644 if( x4a->tbl==0 ){
5645 free(x4a);
5646 x4a = 0;
5647 }else{
5648 int i;
5649 x4a->ht = (x4node**)&(x4a->tbl[64]);
5650 for(i=0; i<64; i++) x4a->ht[i] = 0;
5654 /* Insert a new record into the array. Return TRUE if successful.
5655 ** Prior data with the same key is NOT overwritten */
5656 int Configtable_insert(struct config *data)
5658 x4node *np;
5659 unsigned h;
5660 unsigned ph;
5662 if( x4a==0 ) return 0;
5663 ph = confighash(data);
5664 h = ph & (x4a->size-1);
5665 np = x4a->ht[h];
5666 while( np ){
5667 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
5668 /* An existing entry with the same key is found. */
5669 /* Fail because overwrite is not allows. */
5670 return 0;
5672 np = np->next;
5674 if( x4a->count>=x4a->size ){
5675 /* Need to make the hash table bigger */
5676 int i,arrSize;
5677 struct s_x4 array;
5678 array.size = arrSize = x4a->size*2;
5679 array.count = x4a->count;
5680 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
5681 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5682 array.ht = (x4node**)&(array.tbl[arrSize]);
5683 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5684 for(i=0; i<x4a->count; i++){
5685 x4node *oldnp, *newnp;
5686 oldnp = &(x4a->tbl[i]);
5687 h = confighash(oldnp->data) & (arrSize-1);
5688 newnp = &(array.tbl[i]);
5689 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5690 newnp->next = array.ht[h];
5691 newnp->data = oldnp->data;
5692 newnp->from = &(array.ht[h]);
5693 array.ht[h] = newnp;
5695 free(x4a->tbl);
5696 *x4a = array;
5698 /* Insert the new data */
5699 h = ph & (x4a->size-1);
5700 np = &(x4a->tbl[x4a->count++]);
5701 np->data = data;
5702 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5703 np->next = x4a->ht[h];
5704 x4a->ht[h] = np;
5705 np->from = &(x4a->ht[h]);
5706 return 1;
5709 /* Return a pointer to data assigned to the given key. Return NULL
5710 ** if no such key. */
5711 struct config *Configtable_find(struct config *key)
5713 int h;
5714 x4node *np;
5716 if( x4a==0 ) return 0;
5717 h = confighash(key) & (x4a->size-1);
5718 np = x4a->ht[h];
5719 while( np ){
5720 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
5721 np = np->next;
5723 return np ? np->data : 0;
5726 /* Remove all data from the table. Pass each data to the function "f"
5727 ** as it is removed. ("f" may be null to avoid this step.) */
5728 void Configtable_clear(int(*f)(struct config *))
5730 int i;
5731 if( x4a==0 || x4a->count==0 ) return;
5732 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5733 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5734 x4a->count = 0;
5735 return;