Fixes default log output to console for macOS
[sqlcipher.git] / tool / lemon.c
blob06b9109a1dbfc8796904281510b55ecc2e497b6d
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 ** Header on the linked list of memory allocations.
65 typedef struct MemChunk MemChunk;
66 struct MemChunk {
67 MemChunk *pNext;
68 size_t sz;
69 /* Actually memory follows */
70 };
73 ** Global linked list of all memory allocations.
75 static MemChunk *memChunkList = 0;
78 ** Wrappers around malloc(), calloc(), realloc() and free().
80 ** All memory allocations are kept on a doubly-linked list. The
81 ** lemon_free_all() function can be called prior to exit to clean
82 ** up any memory leaks.
84 ** This is not necessary. But compilers and getting increasingly
85 ** fussy about memory leaks, even in command-line programs like Lemon
86 ** where they do not matter. So this code is provided to hush the
87 ** warnings.
89 static void *lemon_malloc(size_t nByte){
90 MemChunk *p;
91 if( nByte<0 ) return 0;
92 p = malloc( nByte + sizeof(MemChunk) );
93 if( p==0 ){
94 fprintf(stderr, "Out of memory. Failed to allocate %lld bytes.\n",
95 (long long int)nByte);
96 exit(1);
98 p->pNext = memChunkList;
99 p->sz = nByte;
100 memChunkList = p;
101 return (void*)&p[1];
103 static void *lemon_calloc(size_t nElem, size_t sz){
104 void *p = lemon_malloc(nElem*sz);
105 memset(p, 0, nElem*sz);
106 return p;
108 static void lemon_free(void *pOld){
109 if( pOld ){
110 MemChunk *p = (MemChunk*)pOld;
111 p--;
112 memset(pOld, 0, p->sz);
115 static void *lemon_realloc(void *pOld, size_t nNew){
116 void *pNew;
117 MemChunk *p;
118 if( pOld==0 ) return lemon_malloc(nNew);
119 p = (MemChunk*)pOld;
120 p--;
121 if( p->sz>=nNew ) return pOld;
122 pNew = lemon_malloc( nNew );
123 memcpy(pNew, pOld, p->sz);
124 return pNew;
127 /* Free all outstanding memory allocations.
128 ** Do this right before exiting.
130 static void lemon_free_all(void){
131 while( memChunkList ){
132 MemChunk *pNext = memChunkList->pNext;
133 free( memChunkList );
134 memChunkList = pNext;
139 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
140 ** saying they are unsafe. So we define our own versions of those routines too.
142 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
143 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
144 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
145 ** buffer, making sure the buffer is always zero-terminated.
147 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
148 ** a few simply conversions:
150 ** %d
151 ** %s
152 ** %.*s
155 static void lemon_addtext(
156 char *zBuf, /* The buffer to which text is added */
157 int *pnUsed, /* Slots of the buffer used so far */
158 const char *zIn, /* Text to add */
159 int nIn, /* Bytes of text to add. -1 to use strlen() */
160 int iWidth /* Field width. Negative to left justify */
162 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
163 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
164 if( nIn==0 ) return;
165 memcpy(&zBuf[*pnUsed], zIn, nIn);
166 *pnUsed += nIn;
167 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
168 zBuf[*pnUsed] = 0;
170 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
171 int i, j, k, c;
172 int nUsed = 0;
173 const char *z;
174 char zTemp[50];
175 str[0] = 0;
176 for(i=j=0; (c = zFormat[i])!=0; i++){
177 if( c=='%' ){
178 int iWidth = 0;
179 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
180 c = zFormat[++i];
181 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
182 if( c=='-' ) i++;
183 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
184 if( c=='-' ) iWidth = -iWidth;
185 c = zFormat[i];
187 if( c=='d' ){
188 int v = va_arg(ap, int);
189 if( v<0 ){
190 lemon_addtext(str, &nUsed, "-", 1, iWidth);
191 v = -v;
192 }else if( v==0 ){
193 lemon_addtext(str, &nUsed, "0", 1, iWidth);
195 k = 0;
196 while( v>0 ){
197 k++;
198 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
199 v /= 10;
201 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
202 }else if( c=='s' ){
203 z = va_arg(ap, const char*);
204 lemon_addtext(str, &nUsed, z, -1, iWidth);
205 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
206 i += 2;
207 k = va_arg(ap, int);
208 z = va_arg(ap, const char*);
209 lemon_addtext(str, &nUsed, z, k, iWidth);
210 }else if( c=='%' ){
211 lemon_addtext(str, &nUsed, "%", 1, 0);
212 }else{
213 fprintf(stderr, "illegal format\n");
214 exit(1);
216 j = i+1;
219 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
220 return nUsed;
222 static int lemon_sprintf(char *str, const char *format, ...){
223 va_list ap;
224 int rc;
225 va_start(ap, format);
226 rc = lemon_vsprintf(str, format, ap);
227 va_end(ap);
228 return rc;
230 static void lemon_strcpy(char *dest, const char *src){
231 while( (*(dest++) = *(src++))!=0 ){}
233 static void lemon_strcat(char *dest, const char *src){
234 while( *dest ) dest++;
235 lemon_strcpy(dest, src);
239 /* a few forward declarations... */
240 struct rule;
241 struct lemon;
242 struct action;
244 static struct action *Action_new(void);
245 static struct action *Action_sort(struct action *);
247 /********** From the file "build.h" ************************************/
248 void FindRulePrecedences(struct lemon*);
249 void FindFirstSets(struct lemon*);
250 void FindStates(struct lemon*);
251 void FindLinks(struct lemon*);
252 void FindFollowSets(struct lemon*);
253 void FindActions(struct lemon*);
255 /********* From the file "configlist.h" *********************************/
256 void Configlist_init(void);
257 struct config *Configlist_add(struct rule *, int);
258 struct config *Configlist_addbasis(struct rule *, int);
259 void Configlist_closure(struct lemon *);
260 void Configlist_sort(void);
261 void Configlist_sortbasis(void);
262 struct config *Configlist_return(void);
263 struct config *Configlist_basis(void);
264 void Configlist_eat(struct config *);
265 void Configlist_reset(void);
267 /********* From the file "error.h" ***************************************/
268 void ErrorMsg(const char *, int,const char *, ...);
270 /****** From the file "option.h" ******************************************/
271 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
272 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
273 struct s_options {
274 enum option_type type;
275 const char *label;
276 char *arg;
277 const char *message;
279 int OptInit(char**,struct s_options*,FILE*);
280 int OptNArgs(void);
281 char *OptArg(int);
282 void OptErr(int);
283 void OptPrint(void);
285 /******** From the file "parse.h" *****************************************/
286 void Parse(struct lemon *lemp);
288 /********* From the file "plink.h" ***************************************/
289 struct plink *Plink_new(void);
290 void Plink_add(struct plink **, struct config *);
291 void Plink_copy(struct plink **, struct plink *);
292 void Plink_delete(struct plink *);
294 /********** From the file "report.h" *************************************/
295 void Reprint(struct lemon *);
296 void ReportOutput(struct lemon *);
297 void ReportTable(struct lemon *, int, int);
298 void ReportHeader(struct lemon *);
299 void CompressTables(struct lemon *);
300 void ResortStates(struct lemon *);
302 /********** From the file "set.h" ****************************************/
303 void SetSize(int); /* All sets will be of size N */
304 char *SetNew(void); /* A new set for element 0..N */
305 void SetFree(char*); /* Deallocate a set */
306 int SetAdd(char*,int); /* Add element to a set */
307 int SetUnion(char *,char *); /* A <- A U B, thru element N */
308 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
310 /********** From the file "struct.h" *************************************/
312 ** Principal data structures for the LEMON parser generator.
315 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
317 /* Symbols (terminals and nonterminals) of the grammar are stored
318 ** in the following: */
319 enum symbol_type {
320 TERMINAL,
321 NONTERMINAL,
322 MULTITERMINAL
324 enum e_assoc {
325 LEFT,
326 RIGHT,
327 NONE,
330 struct symbol {
331 const char *name; /* Name of the symbol */
332 int index; /* Index number for this symbol */
333 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
334 struct rule *rule; /* Linked list of rules of this (if an NT) */
335 struct symbol *fallback; /* fallback token in case this token doesn't parse */
336 int prec; /* Precedence if defined (-1 otherwise) */
337 enum e_assoc assoc; /* Associativity if precedence is defined */
338 char *firstset; /* First-set for all rules of this symbol */
339 Boolean lambda; /* True if NT and can generate an empty string */
340 int useCnt; /* Number of times used */
341 char *destructor; /* Code which executes whenever this symbol is
342 ** popped from the stack during error processing */
343 int destLineno; /* Line number for start of destructor. Set to
344 ** -1 for duplicate destructors. */
345 char *datatype; /* The data type of information held by this
346 ** object. Only used if type==NONTERMINAL */
347 int dtnum; /* The data type number. In the parser, the value
348 ** stack is a union. The .yy%d element of this
349 ** union is the correct data type for this object */
350 int bContent; /* True if this symbol ever carries content - if
351 ** it is ever more than just syntax */
352 /* The following fields are used by MULTITERMINALs only */
353 int nsubsym; /* Number of constituent symbols in the MULTI */
354 struct symbol **subsym; /* Array of constituent symbols */
357 /* Each production rule in the grammar is stored in the following
358 ** structure. */
359 struct rule {
360 struct symbol *lhs; /* Left-hand side of the rule */
361 const char *lhsalias; /* Alias for the LHS (NULL if none) */
362 int lhsStart; /* True if left-hand side is the start symbol */
363 int ruleline; /* Line number for the rule */
364 int nrhs; /* Number of RHS symbols */
365 struct symbol **rhs; /* The RHS symbols */
366 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
367 int line; /* Line number at which code begins */
368 const char *code; /* The code executed when this rule is reduced */
369 const char *codePrefix; /* Setup code before code[] above */
370 const char *codeSuffix; /* Breakdown code after code[] above */
371 struct symbol *precsym; /* Precedence symbol for this rule */
372 int index; /* An index number for this rule */
373 int iRule; /* Rule number as used in the generated tables */
374 Boolean noCode; /* True if this rule has no associated C code */
375 Boolean codeEmitted; /* True if the code has been emitted already */
376 Boolean canReduce; /* True if this rule is ever reduced */
377 Boolean doesReduce; /* Reduce actions occur after optimization */
378 Boolean neverReduce; /* Reduce is theoretically possible, but prevented
379 ** by actions or other outside implementation */
380 struct rule *nextlhs; /* Next rule with the same LHS */
381 struct rule *next; /* Next rule in the global list */
384 /* A configuration is a production rule of the grammar together with
385 ** a mark (dot) showing how much of that rule has been processed so far.
386 ** Configurations also contain a follow-set which is a list of terminal
387 ** symbols which are allowed to immediately follow the end of the rule.
388 ** Every configuration is recorded as an instance of the following: */
389 enum cfgstatus {
390 COMPLETE,
391 INCOMPLETE
393 struct config {
394 struct rule *rp; /* The rule upon which the configuration is based */
395 int dot; /* The parse point */
396 char *fws; /* Follow-set for this configuration only */
397 struct plink *fplp; /* Follow-set forward propagation links */
398 struct plink *bplp; /* Follow-set backwards propagation links */
399 struct state *stp; /* Pointer to state which contains this */
400 enum cfgstatus status; /* used during followset and shift computations */
401 struct config *next; /* Next configuration in the state */
402 struct config *bp; /* The next basis configuration */
405 enum e_action {
406 SHIFT,
407 ACCEPT,
408 REDUCE,
409 ERROR,
410 SSCONFLICT, /* A shift/shift conflict */
411 SRCONFLICT, /* Was a reduce, but part of a conflict */
412 RRCONFLICT, /* Was a reduce, but part of a conflict */
413 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
414 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
415 NOT_USED, /* Deleted by compression */
416 SHIFTREDUCE /* Shift first, then reduce */
419 /* Every shift or reduce operation is stored as one of the following */
420 struct action {
421 struct symbol *sp; /* The look-ahead symbol */
422 enum e_action type;
423 union {
424 struct state *stp; /* The new state, if a shift */
425 struct rule *rp; /* The rule, if a reduce */
426 } x;
427 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
428 struct action *next; /* Next action for this state */
429 struct action *collide; /* Next action with the same hash */
432 /* Each state of the generated parser's finite state machine
433 ** is encoded as an instance of the following structure. */
434 struct state {
435 struct config *bp; /* The basis configurations for this state */
436 struct config *cfp; /* All configurations in this set */
437 int statenum; /* Sequential number for this state */
438 struct action *ap; /* List of actions for this state */
439 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
440 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
441 int iDfltReduce; /* Default action is to REDUCE by this rule */
442 struct rule *pDfltReduce;/* The default REDUCE rule. */
443 int autoReduce; /* True if this is an auto-reduce state */
445 #define NO_OFFSET (-2147483647)
447 /* A followset propagation link indicates that the contents of one
448 ** configuration followset should be propagated to another whenever
449 ** the first changes. */
450 struct plink {
451 struct config *cfp; /* The configuration to which linked */
452 struct plink *next; /* The next propagate link */
455 /* The state vector for the entire parser generator is recorded as
456 ** follows. (LEMON uses no global variables and makes little use of
457 ** static variables. Fields in the following structure can be thought
458 ** of as begin global variables in the program.) */
459 struct lemon {
460 struct state **sorted; /* Table of states sorted by state number */
461 struct rule *rule; /* List of all rules */
462 struct rule *startRule; /* First rule */
463 int nstate; /* Number of states */
464 int nxstate; /* nstate with tail degenerate states removed */
465 int nrule; /* Number of rules */
466 int nruleWithAction; /* Number of rules with actions */
467 int nsymbol; /* Number of terminal and nonterminal symbols */
468 int nterminal; /* Number of terminal symbols */
469 int minShiftReduce; /* Minimum shift-reduce action value */
470 int errAction; /* Error action value */
471 int accAction; /* Accept action value */
472 int noAction; /* No-op action value */
473 int minReduce; /* Minimum reduce action */
474 int maxAction; /* Maximum action value of any kind */
475 struct symbol **symbols; /* Sorted array of pointers to symbols */
476 int errorcnt; /* Number of errors */
477 struct symbol *errsym; /* The error symbol */
478 struct symbol *wildcard; /* Token that matches anything */
479 char *name; /* Name of the generated parser */
480 char *arg; /* Declaration of the 3rd argument to parser */
481 char *ctx; /* Declaration of 2nd argument to constructor */
482 char *tokentype; /* Type of terminal symbols in the parser stack */
483 char *vartype; /* The default type of non-terminal symbols */
484 char *start; /* Name of the start symbol for the grammar */
485 char *stacksize; /* Size of the parser stack */
486 char *include; /* Code to put at the start of the C file */
487 char *error; /* Code to execute when an error is seen */
488 char *overflow; /* Code to execute on a stack overflow */
489 char *failure; /* Code to execute on parser failure */
490 char *accept; /* Code to execute when the parser excepts */
491 char *extracode; /* Code appended to the generated file */
492 char *tokendest; /* Code to execute to destroy token data */
493 char *vardest; /* Code for the default non-terminal destructor */
494 char *filename; /* Name of the input file */
495 char *outname; /* Name of the current output file */
496 char *tokenprefix; /* A prefix added to token names in the .h file */
497 char *reallocFunc; /* Function to use to allocate stack space */
498 char *freeFunc; /* Function to use to free stack space */
499 int nconflict; /* Number of parsing conflicts */
500 int nactiontab; /* Number of entries in the yy_action[] table */
501 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
502 int tablesize; /* Total table size of all tables in bytes */
503 int basisflag; /* Print only basis configurations */
504 int printPreprocessed; /* Show preprocessor output on stdout */
505 int has_fallback; /* True if any %fallback is seen in the grammar */
506 int nolinenosflag; /* True if #line statements should not be printed */
507 int argc; /* Number of command-line arguments */
508 char **argv; /* Command-line arguments */
511 #define MemoryCheck(X) if((X)==0){ \
512 extern void memory_error(); \
513 memory_error(); \
516 /**************** From the file "table.h" *********************************/
518 ** All code in this file has been automatically generated
519 ** from a specification in the file
520 ** "table.q"
521 ** by the associative array code building program "aagen".
522 ** Do not edit this file! Instead, edit the specification
523 ** file, then rerun aagen.
526 ** Code for processing tables in the LEMON parser generator.
528 /* Routines for handling a strings */
530 const char *Strsafe(const char *);
532 void Strsafe_init(void);
533 int Strsafe_insert(const char *);
534 const char *Strsafe_find(const char *);
536 /* Routines for handling symbols of the grammar */
538 struct symbol *Symbol_new(const char *);
539 int Symbolcmpp(const void *, const void *);
540 void Symbol_init(void);
541 int Symbol_insert(struct symbol *, const char *);
542 struct symbol *Symbol_find(const char *);
543 struct symbol *Symbol_Nth(int);
544 int Symbol_count(void);
545 struct symbol **Symbol_arrayof(void);
547 /* Routines to manage the state table */
549 int Configcmp(const char *, const char *);
550 struct state *State_new(void);
551 void State_init(void);
552 int State_insert(struct state *, struct config *);
553 struct state *State_find(struct config *);
554 struct state **State_arrayof(void);
556 /* Routines used for efficiency in Configlist_add */
558 void Configtable_init(void);
559 int Configtable_insert(struct config *);
560 struct config *Configtable_find(struct config *);
561 void Configtable_clear(int(*)(struct config *));
563 /****************** From the file "action.c" *******************************/
565 ** Routines processing parser actions in the LEMON parser generator.
568 /* Allocate a new parser action */
569 static struct action *Action_new(void){
570 static struct action *actionfreelist = 0;
571 struct action *newaction;
573 if( actionfreelist==0 ){
574 int i;
575 int amt = 100;
576 actionfreelist = (struct action *)lemon_calloc(amt, sizeof(struct action));
577 if( actionfreelist==0 ){
578 fprintf(stderr,"Unable to allocate memory for a new parser action.");
579 exit(1);
581 for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
582 actionfreelist[amt-1].next = 0;
584 newaction = actionfreelist;
585 actionfreelist = actionfreelist->next;
586 return newaction;
589 /* Compare two actions for sorting purposes. Return negative, zero, or
590 ** positive if the first action is less than, equal to, or greater than
591 ** the first
593 static int actioncmp(
594 struct action *ap1,
595 struct action *ap2
597 int rc;
598 rc = ap1->sp->index - ap2->sp->index;
599 if( rc==0 ){
600 rc = (int)ap1->type - (int)ap2->type;
602 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
603 rc = ap1->x.rp->index - ap2->x.rp->index;
605 if( rc==0 ){
606 rc = (int) (ap2 - ap1);
608 return rc;
611 /* Sort parser actions */
612 static struct action *Action_sort(
613 struct action *ap
615 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
616 (int(*)(const char*,const char*))actioncmp);
617 return ap;
620 void Action_add(
621 struct action **app,
622 enum e_action type,
623 struct symbol *sp,
624 char *arg
626 struct action *newaction;
627 newaction = Action_new();
628 newaction->next = *app;
629 *app = newaction;
630 newaction->type = type;
631 newaction->sp = sp;
632 newaction->spOpt = 0;
633 if( type==SHIFT ){
634 newaction->x.stp = (struct state *)arg;
635 }else{
636 newaction->x.rp = (struct rule *)arg;
639 /********************** New code to implement the "acttab" module ***********/
641 ** This module implements routines use to construct the yy_action[] table.
645 ** The state of the yy_action table under construction is an instance of
646 ** the following structure.
648 ** The yy_action table maps the pair (state_number, lookahead) into an
649 ** action_number. The table is an array of integers pairs. The state_number
650 ** determines an initial offset into the yy_action array. The lookahead
651 ** value is then added to this initial offset to get an index X into the
652 ** yy_action array. If the aAction[X].lookahead equals the value of the
653 ** of the lookahead input, then the value of the action_number output is
654 ** aAction[X].action. If the lookaheads do not match then the
655 ** default action for the state_number is returned.
657 ** All actions associated with a single state_number are first entered
658 ** into aLookahead[] using multiple calls to acttab_action(). Then the
659 ** actions for that single state_number are placed into the aAction[]
660 ** array with a single call to acttab_insert(). The acttab_insert() call
661 ** also resets the aLookahead[] array in preparation for the next
662 ** state number.
664 struct lookahead_action {
665 int lookahead; /* Value of the lookahead token */
666 int action; /* Action to take on the given lookahead */
668 typedef struct acttab acttab;
669 struct acttab {
670 int nAction; /* Number of used slots in aAction[] */
671 int nActionAlloc; /* Slots allocated for aAction[] */
672 struct lookahead_action
673 *aAction, /* The yy_action[] table under construction */
674 *aLookahead; /* A single new transaction set */
675 int mnLookahead; /* Minimum aLookahead[].lookahead */
676 int mnAction; /* Action associated with mnLookahead */
677 int mxLookahead; /* Maximum aLookahead[].lookahead */
678 int nLookahead; /* Used slots in aLookahead[] */
679 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
680 int nterminal; /* Number of terminal symbols */
681 int nsymbol; /* total number of symbols */
684 /* Return the number of entries in the yy_action table */
685 #define acttab_lookahead_size(X) ((X)->nAction)
687 /* The value for the N-th entry in yy_action */
688 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
690 /* The value for the N-th entry in yy_lookahead */
691 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
693 /* Free all memory associated with the given acttab */
694 void acttab_free(acttab *p){
695 lemon_free( p->aAction );
696 lemon_free( p->aLookahead );
697 lemon_free( p );
700 /* Allocate a new acttab structure */
701 acttab *acttab_alloc(int nsymbol, int nterminal){
702 acttab *p = (acttab *) lemon_calloc( 1, sizeof(*p) );
703 if( p==0 ){
704 fprintf(stderr,"Unable to allocate memory for a new acttab.");
705 exit(1);
707 memset(p, 0, sizeof(*p));
708 p->nsymbol = nsymbol;
709 p->nterminal = nterminal;
710 return p;
713 /* Add a new action to the current transaction set.
715 ** This routine is called once for each lookahead for a particular
716 ** state.
718 void acttab_action(acttab *p, int lookahead, int action){
719 if( p->nLookahead>=p->nLookaheadAlloc ){
720 p->nLookaheadAlloc += 25;
721 p->aLookahead = (struct lookahead_action *) lemon_realloc( p->aLookahead,
722 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
723 if( p->aLookahead==0 ){
724 fprintf(stderr,"malloc failed\n");
725 exit(1);
728 if( p->nLookahead==0 ){
729 p->mxLookahead = lookahead;
730 p->mnLookahead = lookahead;
731 p->mnAction = action;
732 }else{
733 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
734 if( p->mnLookahead>lookahead ){
735 p->mnLookahead = lookahead;
736 p->mnAction = action;
739 p->aLookahead[p->nLookahead].lookahead = lookahead;
740 p->aLookahead[p->nLookahead].action = action;
741 p->nLookahead++;
745 ** Add the transaction set built up with prior calls to acttab_action()
746 ** into the current action table. Then reset the transaction set back
747 ** to an empty set in preparation for a new round of acttab_action() calls.
749 ** Return the offset into the action table of the new transaction.
751 ** If the makeItSafe parameter is true, then the offset is chosen so that
752 ** it is impossible to overread the yy_lookaside[] table regardless of
753 ** the lookaside token. This is done for the terminal symbols, as they
754 ** come from external inputs and can contain syntax errors. When makeItSafe
755 ** is false, there is more flexibility in selecting offsets, resulting in
756 ** a smaller table. For non-terminal symbols, which are never syntax errors,
757 ** makeItSafe can be false.
759 int acttab_insert(acttab *p, int makeItSafe){
760 int i, j, k, n, end;
761 assert( p->nLookahead>0 );
763 /* Make sure we have enough space to hold the expanded action table
764 ** in the worst case. The worst case occurs if the transaction set
765 ** must be appended to the current action table
767 n = p->nsymbol + 1;
768 if( p->nAction + n >= p->nActionAlloc ){
769 int oldAlloc = p->nActionAlloc;
770 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
771 p->aAction = (struct lookahead_action *) lemon_realloc( p->aAction,
772 sizeof(p->aAction[0])*p->nActionAlloc);
773 if( p->aAction==0 ){
774 fprintf(stderr,"malloc failed\n");
775 exit(1);
777 for(i=oldAlloc; i<p->nActionAlloc; i++){
778 p->aAction[i].lookahead = -1;
779 p->aAction[i].action = -1;
783 /* Scan the existing action table looking for an offset that is a
784 ** duplicate of the current transaction set. Fall out of the loop
785 ** if and when the duplicate is found.
787 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
789 end = makeItSafe ? p->mnLookahead : 0;
790 for(i=p->nAction-1; i>=end; i--){
791 if( p->aAction[i].lookahead==p->mnLookahead ){
792 /* All lookaheads and actions in the aLookahead[] transaction
793 ** must match against the candidate aAction[i] entry. */
794 if( p->aAction[i].action!=p->mnAction ) continue;
795 for(j=0; j<p->nLookahead; j++){
796 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
797 if( k<0 || k>=p->nAction ) break;
798 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
799 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
801 if( j<p->nLookahead ) continue;
803 /* No possible lookahead value that is not in the aLookahead[]
804 ** transaction is allowed to match aAction[i] */
805 n = 0;
806 for(j=0; j<p->nAction; j++){
807 if( p->aAction[j].lookahead<0 ) continue;
808 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
810 if( n==p->nLookahead ){
811 break; /* An exact match is found at offset i */
816 /* If no existing offsets exactly match the current transaction, find an
817 ** an empty offset in the aAction[] table in which we can add the
818 ** aLookahead[] transaction.
820 if( i<end ){
821 /* Look for holes in the aAction[] table that fit the current
822 ** aLookahead[] transaction. Leave i set to the offset of the hole.
823 ** If no holes are found, i is left at p->nAction, which means the
824 ** transaction will be appended. */
825 i = makeItSafe ? p->mnLookahead : 0;
826 for(; i<p->nActionAlloc - p->mxLookahead; i++){
827 if( p->aAction[i].lookahead<0 ){
828 for(j=0; j<p->nLookahead; j++){
829 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
830 if( k<0 ) break;
831 if( p->aAction[k].lookahead>=0 ) break;
833 if( j<p->nLookahead ) continue;
834 for(j=0; j<p->nAction; j++){
835 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
837 if( j==p->nAction ){
838 break; /* Fits in empty slots */
843 /* Insert transaction set at index i. */
844 #if 0
845 printf("Acttab:");
846 for(j=0; j<p->nLookahead; j++){
847 printf(" %d", p->aLookahead[j].lookahead);
849 printf(" inserted at %d\n", i);
850 #endif
851 for(j=0; j<p->nLookahead; j++){
852 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
853 p->aAction[k] = p->aLookahead[j];
854 if( k>=p->nAction ) p->nAction = k+1;
856 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
857 p->nLookahead = 0;
859 /* Return the offset that is added to the lookahead in order to get the
860 ** index into yy_action of the action */
861 return i - p->mnLookahead;
865 ** Return the size of the action table without the trailing syntax error
866 ** entries.
868 int acttab_action_size(acttab *p){
869 int n = p->nAction;
870 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
871 return n;
874 /********************** From the file "build.c" *****************************/
876 ** Routines to construction the finite state machine for the LEMON
877 ** parser generator.
880 /* Find a precedence symbol of every rule in the grammar.
882 ** Those rules which have a precedence symbol coded in the input
883 ** grammar using the "[symbol]" construct will already have the
884 ** rp->precsym field filled. Other rules take as their precedence
885 ** symbol the first RHS symbol with a defined precedence. If there
886 ** are not RHS symbols with a defined precedence, the precedence
887 ** symbol field is left blank.
889 void FindRulePrecedences(struct lemon *xp)
891 struct rule *rp;
892 for(rp=xp->rule; rp; rp=rp->next){
893 if( rp->precsym==0 ){
894 int i, j;
895 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
896 struct symbol *sp = rp->rhs[i];
897 if( sp->type==MULTITERMINAL ){
898 for(j=0; j<sp->nsubsym; j++){
899 if( sp->subsym[j]->prec>=0 ){
900 rp->precsym = sp->subsym[j];
901 break;
904 }else if( sp->prec>=0 ){
905 rp->precsym = rp->rhs[i];
910 return;
913 /* Find all nonterminals which will generate the empty string.
914 ** Then go back and compute the first sets of every nonterminal.
915 ** The first set is the set of all terminal symbols which can begin
916 ** a string generated by that nonterminal.
918 void FindFirstSets(struct lemon *lemp)
920 int i, j;
921 struct rule *rp;
922 int progress;
924 for(i=0; i<lemp->nsymbol; i++){
925 lemp->symbols[i]->lambda = LEMON_FALSE;
927 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
928 lemp->symbols[i]->firstset = SetNew();
931 /* First compute all lambdas */
933 progress = 0;
934 for(rp=lemp->rule; rp; rp=rp->next){
935 if( rp->lhs->lambda ) continue;
936 for(i=0; i<rp->nrhs; i++){
937 struct symbol *sp = rp->rhs[i];
938 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
939 if( sp->lambda==LEMON_FALSE ) break;
941 if( i==rp->nrhs ){
942 rp->lhs->lambda = LEMON_TRUE;
943 progress = 1;
946 }while( progress );
948 /* Now compute all first sets */
950 struct symbol *s1, *s2;
951 progress = 0;
952 for(rp=lemp->rule; rp; rp=rp->next){
953 s1 = rp->lhs;
954 for(i=0; i<rp->nrhs; i++){
955 s2 = rp->rhs[i];
956 if( s2->type==TERMINAL ){
957 progress += SetAdd(s1->firstset,s2->index);
958 break;
959 }else if( s2->type==MULTITERMINAL ){
960 for(j=0; j<s2->nsubsym; j++){
961 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
963 break;
964 }else if( s1==s2 ){
965 if( s1->lambda==LEMON_FALSE ) break;
966 }else{
967 progress += SetUnion(s1->firstset,s2->firstset);
968 if( s2->lambda==LEMON_FALSE ) break;
972 }while( progress );
973 return;
976 /* Compute all LR(0) states for the grammar. Links
977 ** are added to between some states so that the LR(1) follow sets
978 ** can be computed later.
980 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
981 void FindStates(struct lemon *lemp)
983 struct symbol *sp;
984 struct rule *rp;
986 Configlist_init();
988 /* Find the start symbol */
989 if( lemp->start ){
990 sp = Symbol_find(lemp->start);
991 if( sp==0 ){
992 ErrorMsg(lemp->filename,0,
993 "The specified start symbol \"%s\" is not "
994 "in a nonterminal of the grammar. \"%s\" will be used as the start "
995 "symbol instead.",lemp->start,lemp->startRule->lhs->name);
996 lemp->errorcnt++;
997 sp = lemp->startRule->lhs;
999 }else if( lemp->startRule ){
1000 sp = lemp->startRule->lhs;
1001 }else{
1002 ErrorMsg(lemp->filename,0,"Internal error - no start rule\n");
1003 exit(1);
1006 /* Make sure the start symbol doesn't occur on the right-hand side of
1007 ** any rule. Report an error if it does. (YACC would generate a new
1008 ** start symbol in this case.) */
1009 for(rp=lemp->rule; rp; rp=rp->next){
1010 int i;
1011 for(i=0; i<rp->nrhs; i++){
1012 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
1013 ErrorMsg(lemp->filename,0,
1014 "The start symbol \"%s\" occurs on the "
1015 "right-hand side of a rule. This will result in a parser which "
1016 "does not work properly.",sp->name);
1017 lemp->errorcnt++;
1022 /* The basis configuration set for the first state
1023 ** is all rules which have the start symbol as their
1024 ** left-hand side */
1025 for(rp=sp->rule; rp; rp=rp->nextlhs){
1026 struct config *newcfp;
1027 rp->lhsStart = 1;
1028 newcfp = Configlist_addbasis(rp,0);
1029 SetAdd(newcfp->fws,0);
1032 /* Compute the first state. All other states will be
1033 ** computed automatically during the computation of the first one.
1034 ** The returned pointer to the first state is not used. */
1035 (void)getstate(lemp);
1036 return;
1039 /* Return a pointer to a state which is described by the configuration
1040 ** list which has been built from calls to Configlist_add.
1042 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
1043 PRIVATE struct state *getstate(struct lemon *lemp)
1045 struct config *cfp, *bp;
1046 struct state *stp;
1048 /* Extract the sorted basis of the new state. The basis was constructed
1049 ** by prior calls to "Configlist_addbasis()". */
1050 Configlist_sortbasis();
1051 bp = Configlist_basis();
1053 /* Get a state with the same basis */
1054 stp = State_find(bp);
1055 if( stp ){
1056 /* A state with the same basis already exists! Copy all the follow-set
1057 ** propagation links from the state under construction into the
1058 ** preexisting state, then return a pointer to the preexisting state */
1059 struct config *x, *y;
1060 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
1061 Plink_copy(&y->bplp,x->bplp);
1062 Plink_delete(x->fplp);
1063 x->fplp = x->bplp = 0;
1065 cfp = Configlist_return();
1066 Configlist_eat(cfp);
1067 }else{
1068 /* This really is a new state. Construct all the details */
1069 Configlist_closure(lemp); /* Compute the configuration closure */
1070 Configlist_sort(); /* Sort the configuration closure */
1071 cfp = Configlist_return(); /* Get a pointer to the config list */
1072 stp = State_new(); /* A new state structure */
1073 MemoryCheck(stp);
1074 stp->bp = bp; /* Remember the configuration basis */
1075 stp->cfp = cfp; /* Remember the configuration closure */
1076 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
1077 stp->ap = 0; /* No actions, yet. */
1078 State_insert(stp,stp->bp); /* Add to the state table */
1079 buildshifts(lemp,stp); /* Recursively compute successor states */
1081 return stp;
1085 ** Return true if two symbols are the same.
1087 int same_symbol(struct symbol *a, struct symbol *b)
1089 int i;
1090 if( a==b ) return 1;
1091 if( a->type!=MULTITERMINAL ) return 0;
1092 if( b->type!=MULTITERMINAL ) return 0;
1093 if( a->nsubsym!=b->nsubsym ) return 0;
1094 for(i=0; i<a->nsubsym; i++){
1095 if( a->subsym[i]!=b->subsym[i] ) return 0;
1097 return 1;
1100 /* Construct all successor states to the given state. A "successor"
1101 ** state is any state which can be reached by a shift action.
1103 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
1105 struct config *cfp; /* For looping thru the config closure of "stp" */
1106 struct config *bcfp; /* For the inner loop on config closure of "stp" */
1107 struct config *newcfg; /* */
1108 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1109 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1110 struct state *newstp; /* A pointer to a successor state */
1112 /* Each configuration becomes complete after it contributes to a successor
1113 ** state. Initially, all configurations are incomplete */
1114 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1116 /* Loop through all configurations of the state "stp" */
1117 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1118 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1119 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1120 Configlist_reset(); /* Reset the new config set */
1121 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1123 /* For every configuration in the state "stp" which has the symbol "sp"
1124 ** following its dot, add the same configuration to the basis set under
1125 ** construction but with the dot shifted one symbol to the right. */
1126 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1127 if( bcfp->status==COMPLETE ) continue; /* Already used */
1128 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1129 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
1130 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
1131 bcfp->status = COMPLETE; /* Mark this config as used */
1132 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1133 Plink_add(&newcfg->bplp,bcfp);
1136 /* Get a pointer to the state described by the basis configuration set
1137 ** constructed in the preceding loop */
1138 newstp = getstate(lemp);
1140 /* The state "newstp" is reached from the state "stp" by a shift action
1141 ** on the symbol "sp" */
1142 if( sp->type==MULTITERMINAL ){
1143 int i;
1144 for(i=0; i<sp->nsubsym; i++){
1145 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1147 }else{
1148 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1154 ** Construct the propagation links
1156 void FindLinks(struct lemon *lemp)
1158 int i;
1159 struct config *cfp, *other;
1160 struct state *stp;
1161 struct plink *plp;
1163 /* Housekeeping detail:
1164 ** Add to every propagate link a pointer back to the state to
1165 ** which the link is attached. */
1166 for(i=0; i<lemp->nstate; i++){
1167 stp = lemp->sorted[i];
1168 for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
1169 cfp->stp = stp;
1173 /* Convert all backlinks into forward links. Only the forward
1174 ** links are used in the follow-set computation. */
1175 for(i=0; i<lemp->nstate; i++){
1176 stp = lemp->sorted[i];
1177 for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
1178 for(plp=cfp->bplp; plp; plp=plp->next){
1179 other = plp->cfp;
1180 Plink_add(&other->fplp,cfp);
1186 /* Compute all followsets.
1188 ** A followset is the set of all symbols which can come immediately
1189 ** after a configuration.
1191 void FindFollowSets(struct lemon *lemp)
1193 int i;
1194 struct config *cfp;
1195 struct plink *plp;
1196 int progress;
1197 int change;
1199 for(i=0; i<lemp->nstate; i++){
1200 assert( lemp->sorted[i]!=0 );
1201 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1202 cfp->status = INCOMPLETE;
1207 progress = 0;
1208 for(i=0; i<lemp->nstate; i++){
1209 assert( lemp->sorted[i]!=0 );
1210 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1211 if( cfp->status==COMPLETE ) continue;
1212 for(plp=cfp->fplp; plp; plp=plp->next){
1213 change = SetUnion(plp->cfp->fws,cfp->fws);
1214 if( change ){
1215 plp->cfp->status = INCOMPLETE;
1216 progress = 1;
1219 cfp->status = COMPLETE;
1222 }while( progress );
1225 static int resolve_conflict(struct action *,struct action *);
1227 /* Compute the reduce actions, and resolve conflicts.
1229 void FindActions(struct lemon *lemp)
1231 int i,j;
1232 struct config *cfp;
1233 struct state *stp;
1234 struct symbol *sp;
1235 struct rule *rp;
1237 /* Add all of the reduce actions
1238 ** A reduce action is added for each element of the followset of
1239 ** a configuration which has its dot at the extreme right.
1241 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1242 stp = lemp->sorted[i];
1243 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1244 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1245 for(j=0; j<lemp->nterminal; j++){
1246 if( SetFind(cfp->fws,j) ){
1247 /* Add a reduce action to the state "stp" which will reduce by the
1248 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1249 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
1256 /* Add the accepting token */
1257 if( lemp->start ){
1258 sp = Symbol_find(lemp->start);
1259 if( sp==0 ){
1260 if( lemp->startRule==0 ){
1261 fprintf(stderr, "internal error on source line %d: no start rule\n",
1262 __LINE__);
1263 exit(1);
1265 sp = lemp->startRule->lhs;
1267 }else{
1268 sp = lemp->startRule->lhs;
1270 /* Add to the first state (which is always the starting state of the
1271 ** finite state machine) an action to ACCEPT if the lookahead is the
1272 ** start nonterminal. */
1273 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1275 /* Resolve conflicts */
1276 for(i=0; i<lemp->nstate; i++){
1277 struct action *ap, *nap;
1278 stp = lemp->sorted[i];
1279 /* assert( stp->ap ); */
1280 stp->ap = Action_sort(stp->ap);
1281 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1282 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1283 /* The two actions "ap" and "nap" have the same lookahead.
1284 ** Figure out which one should be used */
1285 lemp->nconflict += resolve_conflict(ap,nap);
1290 /* Report an error for each rule that can never be reduced. */
1291 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
1292 for(i=0; i<lemp->nstate; i++){
1293 struct action *ap;
1294 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1295 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
1298 for(rp=lemp->rule; rp; rp=rp->next){
1299 if( rp->canReduce ) continue;
1300 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1301 lemp->errorcnt++;
1305 /* Resolve a conflict between the two given actions. If the
1306 ** conflict can't be resolved, return non-zero.
1308 ** NO LONGER TRUE:
1309 ** To resolve a conflict, first look to see if either action
1310 ** is on an error rule. In that case, take the action which
1311 ** is not associated with the error rule. If neither or both
1312 ** actions are associated with an error rule, then try to
1313 ** use precedence to resolve the conflict.
1315 ** If either action is a SHIFT, then it must be apx. This
1316 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1318 static int resolve_conflict(
1319 struct action *apx,
1320 struct action *apy
1322 struct symbol *spx, *spy;
1323 int errcnt = 0;
1324 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1325 if( apx->type==SHIFT && apy->type==SHIFT ){
1326 apy->type = SSCONFLICT;
1327 errcnt++;
1329 if( apx->type==SHIFT && apy->type==REDUCE ){
1330 spx = apx->sp;
1331 spy = apy->x.rp->precsym;
1332 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1333 /* Not enough precedence information. */
1334 apy->type = SRCONFLICT;
1335 errcnt++;
1336 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
1337 apy->type = RD_RESOLVED;
1338 }else if( spx->prec<spy->prec ){
1339 apx->type = SH_RESOLVED;
1340 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1341 apy->type = RD_RESOLVED; /* associativity */
1342 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1343 apx->type = SH_RESOLVED;
1344 }else{
1345 assert( spx->prec==spy->prec && spx->assoc==NONE );
1346 apx->type = ERROR;
1348 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1349 spx = apx->x.rp->precsym;
1350 spy = apy->x.rp->precsym;
1351 if( spx==0 || spy==0 || spx->prec<0 ||
1352 spy->prec<0 || spx->prec==spy->prec ){
1353 apy->type = RRCONFLICT;
1354 errcnt++;
1355 }else if( spx->prec>spy->prec ){
1356 apy->type = RD_RESOLVED;
1357 }else if( spx->prec<spy->prec ){
1358 apx->type = RD_RESOLVED;
1360 }else{
1361 assert(
1362 apx->type==SH_RESOLVED ||
1363 apx->type==RD_RESOLVED ||
1364 apx->type==SSCONFLICT ||
1365 apx->type==SRCONFLICT ||
1366 apx->type==RRCONFLICT ||
1367 apy->type==SH_RESOLVED ||
1368 apy->type==RD_RESOLVED ||
1369 apy->type==SSCONFLICT ||
1370 apy->type==SRCONFLICT ||
1371 apy->type==RRCONFLICT
1373 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1374 ** REDUCEs on the list. If we reach this point it must be because
1375 ** the parser conflict had already been resolved. */
1377 return errcnt;
1379 /********************* From the file "configlist.c" *************************/
1381 ** Routines to processing a configuration list and building a state
1382 ** in the LEMON parser generator.
1385 static struct config *freelist = 0; /* List of free configurations */
1386 static struct config *current = 0; /* Top of list of configurations */
1387 static struct config **currentend = 0; /* Last on list of configs */
1388 static struct config *basis = 0; /* Top of list of basis configs */
1389 static struct config **basisend = 0; /* End of list of basis configs */
1391 /* Return a pointer to a new configuration */
1392 PRIVATE struct config *newconfig(void){
1393 return (struct config*)lemon_calloc(1, sizeof(struct config));
1396 /* The configuration "old" is no longer used */
1397 PRIVATE void deleteconfig(struct config *old)
1399 old->next = freelist;
1400 freelist = old;
1403 /* Initialized the configuration list builder */
1404 void Configlist_init(void){
1405 current = 0;
1406 currentend = &current;
1407 basis = 0;
1408 basisend = &basis;
1409 Configtable_init();
1410 return;
1413 /* Initialized the configuration list builder */
1414 void Configlist_reset(void){
1415 current = 0;
1416 currentend = &current;
1417 basis = 0;
1418 basisend = &basis;
1419 Configtable_clear(0);
1420 return;
1423 /* Add another configuration to the configuration list */
1424 struct config *Configlist_add(
1425 struct rule *rp, /* The rule */
1426 int dot /* Index into the RHS of the rule where the dot goes */
1428 struct config *cfp, model;
1430 assert( currentend!=0 );
1431 model.rp = rp;
1432 model.dot = dot;
1433 cfp = Configtable_find(&model);
1434 if( cfp==0 ){
1435 cfp = newconfig();
1436 cfp->rp = rp;
1437 cfp->dot = dot;
1438 cfp->fws = SetNew();
1439 cfp->stp = 0;
1440 cfp->fplp = cfp->bplp = 0;
1441 cfp->next = 0;
1442 cfp->bp = 0;
1443 *currentend = cfp;
1444 currentend = &cfp->next;
1445 Configtable_insert(cfp);
1447 return cfp;
1450 /* Add a basis configuration to the configuration list */
1451 struct config *Configlist_addbasis(struct rule *rp, int dot)
1453 struct config *cfp, model;
1455 assert( basisend!=0 );
1456 assert( currentend!=0 );
1457 model.rp = rp;
1458 model.dot = dot;
1459 cfp = Configtable_find(&model);
1460 if( cfp==0 ){
1461 cfp = newconfig();
1462 cfp->rp = rp;
1463 cfp->dot = dot;
1464 cfp->fws = SetNew();
1465 cfp->stp = 0;
1466 cfp->fplp = cfp->bplp = 0;
1467 cfp->next = 0;
1468 cfp->bp = 0;
1469 *currentend = cfp;
1470 currentend = &cfp->next;
1471 *basisend = cfp;
1472 basisend = &cfp->bp;
1473 Configtable_insert(cfp);
1475 return cfp;
1478 /* Compute the closure of the configuration list */
1479 void Configlist_closure(struct lemon *lemp)
1481 struct config *cfp, *newcfp;
1482 struct rule *rp, *newrp;
1483 struct symbol *sp, *xsp;
1484 int i, dot;
1486 assert( currentend!=0 );
1487 for(cfp=current; cfp; cfp=cfp->next){
1488 rp = cfp->rp;
1489 dot = cfp->dot;
1490 if( dot>=rp->nrhs ) continue;
1491 sp = rp->rhs[dot];
1492 if( sp->type==NONTERMINAL ){
1493 if( sp->rule==0 && sp!=lemp->errsym ){
1494 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1495 sp->name);
1496 lemp->errorcnt++;
1498 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1499 newcfp = Configlist_add(newrp,0);
1500 for(i=dot+1; i<rp->nrhs; i++){
1501 xsp = rp->rhs[i];
1502 if( xsp->type==TERMINAL ){
1503 SetAdd(newcfp->fws,xsp->index);
1504 break;
1505 }else if( xsp->type==MULTITERMINAL ){
1506 int k;
1507 for(k=0; k<xsp->nsubsym; k++){
1508 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1510 break;
1511 }else{
1512 SetUnion(newcfp->fws,xsp->firstset);
1513 if( xsp->lambda==LEMON_FALSE ) break;
1516 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1520 return;
1523 /* Sort the configuration list */
1524 void Configlist_sort(void){
1525 current = (struct config*)msort((char*)current,(char**)&(current->next),
1526 Configcmp);
1527 currentend = 0;
1528 return;
1531 /* Sort the basis configuration list */
1532 void Configlist_sortbasis(void){
1533 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1534 Configcmp);
1535 basisend = 0;
1536 return;
1539 /* Return a pointer to the head of the configuration list and
1540 ** reset the list */
1541 struct config *Configlist_return(void){
1542 struct config *old;
1543 old = current;
1544 current = 0;
1545 currentend = 0;
1546 return old;
1549 /* Return a pointer to the head of the configuration list and
1550 ** reset the list */
1551 struct config *Configlist_basis(void){
1552 struct config *old;
1553 old = basis;
1554 basis = 0;
1555 basisend = 0;
1556 return old;
1559 /* Free all elements of the given configuration list */
1560 void Configlist_eat(struct config *cfp)
1562 struct config *nextcfp;
1563 for(; cfp; cfp=nextcfp){
1564 nextcfp = cfp->next;
1565 assert( cfp->fplp==0 );
1566 assert( cfp->bplp==0 );
1567 if( cfp->fws ) SetFree(cfp->fws);
1568 deleteconfig(cfp);
1570 return;
1572 /***************** From the file "error.c" *********************************/
1574 ** Code for printing error message.
1577 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1578 va_list ap;
1579 fprintf(stderr, "%s:%d: ", filename, lineno);
1580 va_start(ap, format);
1581 vfprintf(stderr,format,ap);
1582 va_end(ap);
1583 fprintf(stderr, "\n");
1585 /**************** From the file "main.c" ************************************/
1587 ** Main program file for the LEMON parser generator.
1590 /* Report an out-of-memory condition and abort. This function
1591 ** is used mostly by the "MemoryCheck" macro in struct.h
1593 void memory_error(void){
1594 fprintf(stderr,"Out of memory. Aborting...\n");
1595 exit(1);
1598 static int nDefine = 0; /* Number of -D options on the command line */
1599 static int nDefineUsed = 0; /* Number of -D options actually used */
1600 static char **azDefine = 0; /* Name of the -D macros */
1601 static char *bDefineUsed = 0; /* True for every -D macro actually used */
1603 /* This routine is called with the argument to each -D command-line option.
1604 ** Add the macro defined to the azDefine array.
1606 static void handle_D_option(char *z){
1607 char **paz;
1608 nDefine++;
1609 azDefine = (char **) lemon_realloc(azDefine, sizeof(azDefine[0])*nDefine);
1610 if( azDefine==0 ){
1611 fprintf(stderr,"out of memory\n");
1612 exit(1);
1614 bDefineUsed = (char*)lemon_realloc(bDefineUsed, nDefine);
1615 if( bDefineUsed==0 ){
1616 fprintf(stderr,"out of memory\n");
1617 exit(1);
1619 bDefineUsed[nDefine-1] = 0;
1620 paz = &azDefine[nDefine-1];
1621 *paz = (char *) lemon_malloc( lemonStrlen(z)+1 );
1622 if( *paz==0 ){
1623 fprintf(stderr,"out of memory\n");
1624 exit(1);
1626 lemon_strcpy(*paz, z);
1627 for(z=*paz; *z && *z!='='; z++){}
1628 *z = 0;
1631 /* Rember the name of the output directory
1633 static char *outputDir = NULL;
1634 static void handle_d_option(char *z){
1635 outputDir = (char *) lemon_malloc( lemonStrlen(z)+1 );
1636 if( outputDir==0 ){
1637 fprintf(stderr,"out of memory\n");
1638 exit(1);
1640 lemon_strcpy(outputDir, z);
1643 static char *user_templatename = NULL;
1644 static void handle_T_option(char *z){
1645 user_templatename = (char *) lemon_malloc( lemonStrlen(z)+1 );
1646 if( user_templatename==0 ){
1647 memory_error();
1649 lemon_strcpy(user_templatename, z);
1652 /* Merge together to lists of rules ordered by rule.iRule */
1653 static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1654 struct rule *pFirst = 0;
1655 struct rule **ppPrev = &pFirst;
1656 while( pA && pB ){
1657 if( pA->iRule<pB->iRule ){
1658 *ppPrev = pA;
1659 ppPrev = &pA->next;
1660 pA = pA->next;
1661 }else{
1662 *ppPrev = pB;
1663 ppPrev = &pB->next;
1664 pB = pB->next;
1667 if( pA ){
1668 *ppPrev = pA;
1669 }else{
1670 *ppPrev = pB;
1672 return pFirst;
1676 ** Sort a list of rules in order of increasing iRule value
1678 static struct rule *Rule_sort(struct rule *rp){
1679 unsigned int i;
1680 struct rule *pNext;
1681 struct rule *x[32];
1682 memset(x, 0, sizeof(x));
1683 while( rp ){
1684 pNext = rp->next;
1685 rp->next = 0;
1686 for(i=0; i<sizeof(x)/sizeof(x[0])-1 && x[i]; i++){
1687 rp = Rule_merge(x[i], rp);
1688 x[i] = 0;
1690 x[i] = rp;
1691 rp = pNext;
1693 rp = 0;
1694 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1695 rp = Rule_merge(x[i], rp);
1697 return rp;
1700 /* forward reference */
1701 static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1703 /* Print a single line of the "Parser Stats" output
1705 static void stats_line(const char *zLabel, int iValue){
1706 int nLabel = lemonStrlen(zLabel);
1707 printf(" %s%.*s %5d\n", zLabel,
1708 35-nLabel, "................................",
1709 iValue);
1712 /* The main program. Parse the command line and do it... */
1713 int main(int argc, char **argv){
1714 static int version = 0;
1715 static int rpflag = 0;
1716 static int basisflag = 0;
1717 static int compress = 0;
1718 static int quiet = 0;
1719 static int statistics = 0;
1720 static int mhflag = 0;
1721 static int nolinenosflag = 0;
1722 static int noResort = 0;
1723 static int sqlFlag = 0;
1724 static int printPP = 0;
1726 static struct s_options options[] = {
1727 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1728 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1729 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
1730 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
1731 {OPT_FLAG, "E", (char*)&printPP, "Print input file after preprocessing."},
1732 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1733 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1734 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1735 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1736 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
1737 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1738 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1739 "Show conflicts resolved by precedence rules"},
1740 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1741 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
1742 {OPT_FLAG, "s", (char*)&statistics,
1743 "Print parser stats to standard output."},
1744 {OPT_FLAG, "S", (char*)&sqlFlag,
1745 "Generate the *.sql file describing the parser tables."},
1746 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1747 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1748 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1749 {OPT_FLAG,0,0,0}
1751 int i;
1752 int exitcode;
1753 struct lemon lem;
1754 struct rule *rp;
1756 OptInit(argv,options,stderr);
1757 if( version ){
1758 printf("Lemon version 1.0\n");
1759 exit(0);
1761 if( OptNArgs()!=1 ){
1762 fprintf(stderr,"Exactly one filename argument is required.\n");
1763 exit(1);
1765 memset(&lem, 0, sizeof(lem));
1766 lem.errorcnt = 0;
1768 /* Initialize the machine */
1769 Strsafe_init();
1770 Symbol_init();
1771 State_init();
1772 lem.argv = argv;
1773 lem.argc = argc;
1774 lem.filename = OptArg(0);
1775 lem.basisflag = basisflag;
1776 lem.nolinenosflag = nolinenosflag;
1777 lem.printPreprocessed = printPP;
1778 Symbol_new("$");
1780 /* Parse the input file */
1781 Parse(&lem);
1782 if( lem.printPreprocessed || lem.errorcnt ) exit(lem.errorcnt);
1783 if( lem.nrule==0 ){
1784 fprintf(stderr,"Empty grammar.\n");
1785 exit(1);
1787 lem.errsym = Symbol_find("error");
1789 /* Count and index the symbols of the grammar */
1790 Symbol_new("{default}");
1791 lem.nsymbol = Symbol_count();
1792 lem.symbols = Symbol_arrayof();
1793 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1794 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1795 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1796 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1797 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1798 lem.nsymbol = i - 1;
1799 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
1800 lem.nterminal = i;
1802 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1803 ** reduce action C-code associated with them last, so that the switch()
1804 ** statement that selects reduction actions will have a smaller jump table.
1806 for(i=0, rp=lem.rule; rp; rp=rp->next){
1807 rp->iRule = rp->code ? i++ : -1;
1809 lem.nruleWithAction = i;
1810 for(rp=lem.rule; rp; rp=rp->next){
1811 if( rp->iRule<0 ) rp->iRule = i++;
1813 lem.startRule = lem.rule;
1814 lem.rule = Rule_sort(lem.rule);
1816 /* Generate a reprint of the grammar, if requested on the command line */
1817 if( rpflag ){
1818 Reprint(&lem);
1819 }else{
1820 /* Initialize the size for all follow and first sets */
1821 SetSize(lem.nterminal+1);
1823 /* Find the precedence for every production rule (that has one) */
1824 FindRulePrecedences(&lem);
1826 /* Compute the lambda-nonterminals and the first-sets for every
1827 ** nonterminal */
1828 FindFirstSets(&lem);
1830 /* Compute all LR(0) states. Also record follow-set propagation
1831 ** links so that the follow-set can be computed later */
1832 lem.nstate = 0;
1833 FindStates(&lem);
1834 lem.sorted = State_arrayof();
1836 /* Tie up loose ends on the propagation links */
1837 FindLinks(&lem);
1839 /* Compute the follow set of every reducible configuration */
1840 FindFollowSets(&lem);
1842 /* Compute the action tables */
1843 FindActions(&lem);
1845 /* Compress the action tables */
1846 if( compress==0 ) CompressTables(&lem);
1848 /* Reorder and renumber the states so that states with fewer choices
1849 ** occur at the end. This is an optimization that helps make the
1850 ** generated parser tables smaller. */
1851 if( noResort==0 ) ResortStates(&lem);
1853 /* Generate a report of the parser generated. (the "y.output" file) */
1854 if( !quiet ) ReportOutput(&lem);
1856 /* Generate the source code for the parser */
1857 ReportTable(&lem, mhflag, sqlFlag);
1859 /* Produce a header file for use by the scanner. (This step is
1860 ** omitted if the "-m" option is used because makeheaders will
1861 ** generate the file for us.) */
1862 if( !mhflag ) ReportHeader(&lem);
1864 if( statistics ){
1865 printf("Parser statistics:\n");
1866 stats_line("terminal symbols", lem.nterminal);
1867 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1868 stats_line("total symbols", lem.nsymbol);
1869 stats_line("rules", lem.nrule);
1870 stats_line("states", lem.nxstate);
1871 stats_line("conflicts", lem.nconflict);
1872 stats_line("action table entries", lem.nactiontab);
1873 stats_line("lookahead table entries", lem.nlookaheadtab);
1874 stats_line("total table size (bytes)", lem.tablesize);
1876 if( lem.nconflict > 0 ){
1877 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1880 /* return 0 on success, 1 on failure. */
1881 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
1882 lemon_free_all();
1883 exit(exitcode);
1884 return (exitcode);
1886 /******************** From the file "msort.c" *******************************/
1888 ** A generic merge-sort program.
1890 ** USAGE:
1891 ** Let "ptr" be a pointer to some structure which is at the head of
1892 ** a null-terminated list. Then to sort the list call:
1894 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1896 ** In the above, "cmpfnc" is a pointer to a function which compares
1897 ** two instances of the structure and returns an integer, as in
1898 ** strcmp. The second argument is a pointer to the pointer to the
1899 ** second element of the linked list. This address is used to compute
1900 ** the offset to the "next" field within the structure. The offset to
1901 ** the "next" field must be constant for all structures in the list.
1903 ** The function returns a new pointer which is the head of the list
1904 ** after sorting.
1906 ** ALGORITHM:
1907 ** Merge-sort.
1911 ** Return a pointer to the next structure in the linked list.
1913 #define NEXT(A) (*(char**)(((char*)A)+offset))
1916 ** Inputs:
1917 ** a: A sorted, null-terminated linked list. (May be null).
1918 ** b: A sorted, null-terminated linked list. (May be null).
1919 ** cmp: A pointer to the comparison function.
1920 ** offset: Offset in the structure to the "next" field.
1922 ** Return Value:
1923 ** A pointer to the head of a sorted list containing the elements
1924 ** of both a and b.
1926 ** Side effects:
1927 ** The "next" pointers for elements in the lists a and b are
1928 ** changed.
1930 static char *merge(
1931 char *a,
1932 char *b,
1933 int (*cmp)(const char*,const char*),
1934 int offset
1936 char *ptr, *head;
1938 if( a==0 ){
1939 head = b;
1940 }else if( b==0 ){
1941 head = a;
1942 }else{
1943 if( (*cmp)(a,b)<=0 ){
1944 ptr = a;
1945 a = NEXT(a);
1946 }else{
1947 ptr = b;
1948 b = NEXT(b);
1950 head = ptr;
1951 while( a && b ){
1952 if( (*cmp)(a,b)<=0 ){
1953 NEXT(ptr) = a;
1954 ptr = a;
1955 a = NEXT(a);
1956 }else{
1957 NEXT(ptr) = b;
1958 ptr = b;
1959 b = NEXT(b);
1962 if( a ) NEXT(ptr) = a;
1963 else NEXT(ptr) = b;
1965 return head;
1969 ** Inputs:
1970 ** list: Pointer to a singly-linked list of structures.
1971 ** next: Pointer to pointer to the second element of the list.
1972 ** cmp: A comparison function.
1974 ** Return Value:
1975 ** A pointer to the head of a sorted list containing the elements
1976 ** originally in list.
1978 ** Side effects:
1979 ** The "next" pointers for elements in list are changed.
1981 #define LISTSIZE 30
1982 static char *msort(
1983 char *list,
1984 char **next,
1985 int (*cmp)(const char*,const char*)
1987 unsigned long offset;
1988 char *ep;
1989 char *set[LISTSIZE];
1990 int i;
1991 offset = (unsigned long)((char*)next - (char*)list);
1992 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1993 while( list ){
1994 ep = list;
1995 list = NEXT(list);
1996 NEXT(ep) = 0;
1997 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1998 ep = merge(ep,set[i],cmp,offset);
1999 set[i] = 0;
2001 set[i] = ep;
2003 ep = 0;
2004 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
2005 return ep;
2007 /************************ From the file "option.c" **************************/
2008 static char **g_argv;
2009 static struct s_options *op;
2010 static FILE *errstream;
2012 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
2015 ** Print the command line with a carrot pointing to the k-th character
2016 ** of the n-th field.
2018 static void errline(int n, int k, FILE *err)
2020 int spcnt, i;
2021 if( g_argv[0] ){
2022 fprintf(err,"%s",g_argv[0]);
2023 spcnt = lemonStrlen(g_argv[0]) + 1;
2024 }else{
2025 spcnt = 0;
2027 for(i=1; i<n && g_argv[i]; i++){
2028 fprintf(err," %s",g_argv[i]);
2029 spcnt += lemonStrlen(g_argv[i])+1;
2031 spcnt += k;
2032 for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
2033 if( spcnt<20 ){
2034 fprintf(err,"\n%*s^-- here\n",spcnt,"");
2035 }else{
2036 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
2041 ** Return the index of the N-th non-switch argument. Return -1
2042 ** if N is out of range.
2044 static int argindex(int n)
2046 int i;
2047 int dashdash = 0;
2048 if( g_argv!=0 && *g_argv!=0 ){
2049 for(i=1; g_argv[i]; i++){
2050 if( dashdash || !ISOPT(g_argv[i]) ){
2051 if( n==0 ) return i;
2052 n--;
2054 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
2057 return -1;
2060 static char emsg[] = "Command line syntax error: ";
2063 ** Process a flag command line argument.
2065 static int handleflags(int i, FILE *err)
2067 int v;
2068 int errcnt = 0;
2069 int j;
2070 for(j=0; op[j].label; j++){
2071 if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
2073 v = g_argv[i][0]=='-' ? 1 : 0;
2074 if( op[j].label==0 ){
2075 if( err ){
2076 fprintf(err,"%sundefined option.\n",emsg);
2077 errline(i,1,err);
2079 errcnt++;
2080 }else if( op[j].arg==0 ){
2081 /* Ignore this option */
2082 }else if( op[j].type==OPT_FLAG ){
2083 *((int*)op[j].arg) = v;
2084 }else if( op[j].type==OPT_FFLAG ){
2085 (*(void(*)(int))(op[j].arg))(v);
2086 }else if( op[j].type==OPT_FSTR ){
2087 (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
2088 }else{
2089 if( err ){
2090 fprintf(err,"%smissing argument on switch.\n",emsg);
2091 errline(i,1,err);
2093 errcnt++;
2095 return errcnt;
2099 ** Process a command line switch which has an argument.
2101 static int handleswitch(int i, FILE *err)
2103 int lv = 0;
2104 double dv = 0.0;
2105 char *sv = 0, *end;
2106 char *cp;
2107 int j;
2108 int errcnt = 0;
2109 cp = strchr(g_argv[i],'=');
2110 assert( cp!=0 );
2111 *cp = 0;
2112 for(j=0; op[j].label; j++){
2113 if( strcmp(g_argv[i],op[j].label)==0 ) break;
2115 *cp = '=';
2116 if( op[j].label==0 ){
2117 if( err ){
2118 fprintf(err,"%sundefined option.\n",emsg);
2119 errline(i,0,err);
2121 errcnt++;
2122 }else{
2123 cp++;
2124 switch( op[j].type ){
2125 case OPT_FLAG:
2126 case OPT_FFLAG:
2127 if( err ){
2128 fprintf(err,"%soption requires an argument.\n",emsg);
2129 errline(i,0,err);
2131 errcnt++;
2132 break;
2133 case OPT_DBL:
2134 case OPT_FDBL:
2135 dv = strtod(cp,&end);
2136 if( *end ){
2137 if( err ){
2138 fprintf(err,
2139 "%sillegal character in floating-point argument.\n",emsg);
2140 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
2142 errcnt++;
2144 break;
2145 case OPT_INT:
2146 case OPT_FINT:
2147 lv = strtol(cp,&end,0);
2148 if( *end ){
2149 if( err ){
2150 fprintf(err,"%sillegal character in integer argument.\n",emsg);
2151 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
2153 errcnt++;
2155 break;
2156 case OPT_STR:
2157 case OPT_FSTR:
2158 sv = cp;
2159 break;
2161 switch( op[j].type ){
2162 case OPT_FLAG:
2163 case OPT_FFLAG:
2164 break;
2165 case OPT_DBL:
2166 *(double*)(op[j].arg) = dv;
2167 break;
2168 case OPT_FDBL:
2169 (*(void(*)(double))(op[j].arg))(dv);
2170 break;
2171 case OPT_INT:
2172 *(int*)(op[j].arg) = lv;
2173 break;
2174 case OPT_FINT:
2175 (*(void(*)(int))(op[j].arg))((int)lv);
2176 break;
2177 case OPT_STR:
2178 *(char**)(op[j].arg) = sv;
2179 break;
2180 case OPT_FSTR:
2181 (*(void(*)(char *))(op[j].arg))(sv);
2182 break;
2185 return errcnt;
2188 int OptInit(char **a, struct s_options *o, FILE *err)
2190 int errcnt = 0;
2191 g_argv = a;
2192 op = o;
2193 errstream = err;
2194 if( g_argv && *g_argv && op ){
2195 int i;
2196 for(i=1; g_argv[i]; i++){
2197 if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
2198 errcnt += handleflags(i,err);
2199 }else if( strchr(g_argv[i],'=') ){
2200 errcnt += handleswitch(i,err);
2204 if( errcnt>0 ){
2205 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
2206 OptPrint();
2207 exit(1);
2209 return 0;
2212 int OptNArgs(void){
2213 int cnt = 0;
2214 int dashdash = 0;
2215 int i;
2216 if( g_argv!=0 && g_argv[0]!=0 ){
2217 for(i=1; g_argv[i]; i++){
2218 if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
2219 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
2222 return cnt;
2225 char *OptArg(int n)
2227 int i;
2228 i = argindex(n);
2229 return i>=0 ? g_argv[i] : 0;
2232 void OptErr(int n)
2234 int i;
2235 i = argindex(n);
2236 if( i>=0 ) errline(i,0,errstream);
2239 void OptPrint(void){
2240 int i;
2241 int max, len;
2242 max = 0;
2243 for(i=0; op[i].label; i++){
2244 len = lemonStrlen(op[i].label) + 1;
2245 switch( op[i].type ){
2246 case OPT_FLAG:
2247 case OPT_FFLAG:
2248 break;
2249 case OPT_INT:
2250 case OPT_FINT:
2251 len += 9; /* length of "<integer>" */
2252 break;
2253 case OPT_DBL:
2254 case OPT_FDBL:
2255 len += 6; /* length of "<real>" */
2256 break;
2257 case OPT_STR:
2258 case OPT_FSTR:
2259 len += 8; /* length of "<string>" */
2260 break;
2262 if( len>max ) max = len;
2264 for(i=0; op[i].label; i++){
2265 switch( op[i].type ){
2266 case OPT_FLAG:
2267 case OPT_FFLAG:
2268 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2269 break;
2270 case OPT_INT:
2271 case OPT_FINT:
2272 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
2273 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
2274 break;
2275 case OPT_DBL:
2276 case OPT_FDBL:
2277 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
2278 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
2279 break;
2280 case OPT_STR:
2281 case OPT_FSTR:
2282 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
2283 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
2284 break;
2288 /*********************** From the file "parse.c" ****************************/
2290 ** Input file parser for the LEMON parser generator.
2293 /* The state of the parser */
2294 enum e_state {
2295 INITIALIZE,
2296 WAITING_FOR_DECL_OR_RULE,
2297 WAITING_FOR_DECL_KEYWORD,
2298 WAITING_FOR_DECL_ARG,
2299 WAITING_FOR_PRECEDENCE_SYMBOL,
2300 WAITING_FOR_ARROW,
2301 IN_RHS,
2302 LHS_ALIAS_1,
2303 LHS_ALIAS_2,
2304 LHS_ALIAS_3,
2305 RHS_ALIAS_1,
2306 RHS_ALIAS_2,
2307 PRECEDENCE_MARK_1,
2308 PRECEDENCE_MARK_2,
2309 RESYNC_AFTER_RULE_ERROR,
2310 RESYNC_AFTER_DECL_ERROR,
2311 WAITING_FOR_DESTRUCTOR_SYMBOL,
2312 WAITING_FOR_DATATYPE_SYMBOL,
2313 WAITING_FOR_FALLBACK_ID,
2314 WAITING_FOR_WILDCARD_ID,
2315 WAITING_FOR_CLASS_ID,
2316 WAITING_FOR_CLASS_TOKEN,
2317 WAITING_FOR_TOKEN_NAME
2319 struct pstate {
2320 char *filename; /* Name of the input file */
2321 int tokenlineno; /* Linenumber at which current token starts */
2322 int errorcnt; /* Number of errors so far */
2323 char *tokenstart; /* Text of current token */
2324 struct lemon *gp; /* Global state vector */
2325 enum e_state state; /* The state of the parser */
2326 struct symbol *fallback; /* The fallback token */
2327 struct symbol *tkclass; /* Token class symbol */
2328 struct symbol *lhs; /* Left-hand side of current rule */
2329 const char *lhsalias; /* Alias for the LHS */
2330 int nrhs; /* Number of right-hand side symbols seen */
2331 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2332 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2333 struct rule *prevrule; /* Previous rule parsed */
2334 const char *declkeyword; /* Keyword of a declaration */
2335 char **declargslot; /* Where the declaration argument should be put */
2336 int insertLineMacro; /* Add #line before declaration insert */
2337 int *decllinenoslot; /* Where to write declaration line number */
2338 enum e_assoc declassoc; /* Assign this association to decl arguments */
2339 int preccounter; /* Assign this precedence to decl arguments */
2340 struct rule *firstrule; /* Pointer to first rule in the grammar */
2341 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2344 /* Parse a single token */
2345 static void parseonetoken(struct pstate *psp)
2347 const char *x;
2348 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2349 #if 0
2350 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2351 x,psp->state);
2352 #endif
2353 switch( psp->state ){
2354 case INITIALIZE:
2355 psp->prevrule = 0;
2356 psp->preccounter = 0;
2357 psp->firstrule = psp->lastrule = 0;
2358 psp->gp->nrule = 0;
2359 /* fall through */
2360 case WAITING_FOR_DECL_OR_RULE:
2361 if( x[0]=='%' ){
2362 psp->state = WAITING_FOR_DECL_KEYWORD;
2363 }else if( ISLOWER(x[0]) ){
2364 psp->lhs = Symbol_new(x);
2365 psp->nrhs = 0;
2366 psp->lhsalias = 0;
2367 psp->state = WAITING_FOR_ARROW;
2368 }else if( x[0]=='{' ){
2369 if( psp->prevrule==0 ){
2370 ErrorMsg(psp->filename,psp->tokenlineno,
2371 "There is no prior rule upon which to attach the code "
2372 "fragment which begins on this line.");
2373 psp->errorcnt++;
2374 }else if( psp->prevrule->code!=0 ){
2375 ErrorMsg(psp->filename,psp->tokenlineno,
2376 "Code fragment beginning on this line is not the first "
2377 "to follow the previous rule.");
2378 psp->errorcnt++;
2379 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
2380 psp->prevrule->neverReduce = 1;
2381 }else{
2382 psp->prevrule->line = psp->tokenlineno;
2383 psp->prevrule->code = &x[1];
2384 psp->prevrule->noCode = 0;
2386 }else if( x[0]=='[' ){
2387 psp->state = PRECEDENCE_MARK_1;
2388 }else{
2389 ErrorMsg(psp->filename,psp->tokenlineno,
2390 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2392 psp->errorcnt++;
2394 break;
2395 case PRECEDENCE_MARK_1:
2396 if( !ISUPPER(x[0]) ){
2397 ErrorMsg(psp->filename,psp->tokenlineno,
2398 "The precedence symbol must be a terminal.");
2399 psp->errorcnt++;
2400 }else if( psp->prevrule==0 ){
2401 ErrorMsg(psp->filename,psp->tokenlineno,
2402 "There is no prior rule to assign precedence \"[%s]\".",x);
2403 psp->errorcnt++;
2404 }else if( psp->prevrule->precsym!=0 ){
2405 ErrorMsg(psp->filename,psp->tokenlineno,
2406 "Precedence mark on this line is not the first "
2407 "to follow the previous rule.");
2408 psp->errorcnt++;
2409 }else{
2410 psp->prevrule->precsym = Symbol_new(x);
2412 psp->state = PRECEDENCE_MARK_2;
2413 break;
2414 case PRECEDENCE_MARK_2:
2415 if( x[0]!=']' ){
2416 ErrorMsg(psp->filename,psp->tokenlineno,
2417 "Missing \"]\" on precedence mark.");
2418 psp->errorcnt++;
2420 psp->state = WAITING_FOR_DECL_OR_RULE;
2421 break;
2422 case WAITING_FOR_ARROW:
2423 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2424 psp->state = IN_RHS;
2425 }else if( x[0]=='(' ){
2426 psp->state = LHS_ALIAS_1;
2427 }else{
2428 ErrorMsg(psp->filename,psp->tokenlineno,
2429 "Expected to see a \":\" following the LHS symbol \"%s\".",
2430 psp->lhs->name);
2431 psp->errorcnt++;
2432 psp->state = RESYNC_AFTER_RULE_ERROR;
2434 break;
2435 case LHS_ALIAS_1:
2436 if( ISALPHA(x[0]) ){
2437 psp->lhsalias = x;
2438 psp->state = LHS_ALIAS_2;
2439 }else{
2440 ErrorMsg(psp->filename,psp->tokenlineno,
2441 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2442 x,psp->lhs->name);
2443 psp->errorcnt++;
2444 psp->state = RESYNC_AFTER_RULE_ERROR;
2446 break;
2447 case LHS_ALIAS_2:
2448 if( x[0]==')' ){
2449 psp->state = LHS_ALIAS_3;
2450 }else{
2451 ErrorMsg(psp->filename,psp->tokenlineno,
2452 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2453 psp->errorcnt++;
2454 psp->state = RESYNC_AFTER_RULE_ERROR;
2456 break;
2457 case LHS_ALIAS_3:
2458 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2459 psp->state = IN_RHS;
2460 }else{
2461 ErrorMsg(psp->filename,psp->tokenlineno,
2462 "Missing \"->\" following: \"%s(%s)\".",
2463 psp->lhs->name,psp->lhsalias);
2464 psp->errorcnt++;
2465 psp->state = RESYNC_AFTER_RULE_ERROR;
2467 break;
2468 case IN_RHS:
2469 if( x[0]=='.' ){
2470 struct rule *rp;
2471 rp = (struct rule *)lemon_calloc( sizeof(struct rule) +
2472 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2473 if( rp==0 ){
2474 ErrorMsg(psp->filename,psp->tokenlineno,
2475 "Can't allocate enough memory for this rule.");
2476 psp->errorcnt++;
2477 psp->prevrule = 0;
2478 }else{
2479 int i;
2480 rp->ruleline = psp->tokenlineno;
2481 rp->rhs = (struct symbol**)&rp[1];
2482 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
2483 for(i=0; i<psp->nrhs; i++){
2484 rp->rhs[i] = psp->rhs[i];
2485 rp->rhsalias[i] = psp->alias[i];
2486 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
2488 rp->lhs = psp->lhs;
2489 rp->lhsalias = psp->lhsalias;
2490 rp->nrhs = psp->nrhs;
2491 rp->code = 0;
2492 rp->noCode = 1;
2493 rp->precsym = 0;
2494 rp->index = psp->gp->nrule++;
2495 rp->nextlhs = rp->lhs->rule;
2496 rp->lhs->rule = rp;
2497 rp->next = 0;
2498 if( psp->firstrule==0 ){
2499 psp->firstrule = psp->lastrule = rp;
2500 }else{
2501 psp->lastrule->next = rp;
2502 psp->lastrule = rp;
2504 psp->prevrule = rp;
2506 psp->state = WAITING_FOR_DECL_OR_RULE;
2507 }else if( ISALPHA(x[0]) ){
2508 if( psp->nrhs>=MAXRHS ){
2509 ErrorMsg(psp->filename,psp->tokenlineno,
2510 "Too many symbols on RHS of rule beginning at \"%s\".",
2512 psp->errorcnt++;
2513 psp->state = RESYNC_AFTER_RULE_ERROR;
2514 }else{
2515 psp->rhs[psp->nrhs] = Symbol_new(x);
2516 psp->alias[psp->nrhs] = 0;
2517 psp->nrhs++;
2519 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 && ISUPPER(x[1]) ){
2520 struct symbol *msp = psp->rhs[psp->nrhs-1];
2521 if( msp->type!=MULTITERMINAL ){
2522 struct symbol *origsp = msp;
2523 msp = (struct symbol *) lemon_calloc(1,sizeof(*msp));
2524 memset(msp, 0, sizeof(*msp));
2525 msp->type = MULTITERMINAL;
2526 msp->nsubsym = 1;
2527 msp->subsym = (struct symbol**)lemon_calloc(1,sizeof(struct symbol*));
2528 msp->subsym[0] = origsp;
2529 msp->name = origsp->name;
2530 psp->rhs[psp->nrhs-1] = msp;
2532 msp->nsubsym++;
2533 msp->subsym = (struct symbol **) lemon_realloc(msp->subsym,
2534 sizeof(struct symbol*)*msp->nsubsym);
2535 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2536 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
2537 ErrorMsg(psp->filename,psp->tokenlineno,
2538 "Cannot form a compound containing a non-terminal");
2539 psp->errorcnt++;
2541 }else if( x[0]=='(' && psp->nrhs>0 ){
2542 psp->state = RHS_ALIAS_1;
2543 }else{
2544 ErrorMsg(psp->filename,psp->tokenlineno,
2545 "Illegal character on RHS of rule: \"%s\".",x);
2546 psp->errorcnt++;
2547 psp->state = RESYNC_AFTER_RULE_ERROR;
2549 break;
2550 case RHS_ALIAS_1:
2551 if( ISALPHA(x[0]) ){
2552 psp->alias[psp->nrhs-1] = x;
2553 psp->state = RHS_ALIAS_2;
2554 }else{
2555 ErrorMsg(psp->filename,psp->tokenlineno,
2556 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2557 x,psp->rhs[psp->nrhs-1]->name);
2558 psp->errorcnt++;
2559 psp->state = RESYNC_AFTER_RULE_ERROR;
2561 break;
2562 case RHS_ALIAS_2:
2563 if( x[0]==')' ){
2564 psp->state = IN_RHS;
2565 }else{
2566 ErrorMsg(psp->filename,psp->tokenlineno,
2567 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2568 psp->errorcnt++;
2569 psp->state = RESYNC_AFTER_RULE_ERROR;
2571 break;
2572 case WAITING_FOR_DECL_KEYWORD:
2573 if( ISALPHA(x[0]) ){
2574 psp->declkeyword = x;
2575 psp->declargslot = 0;
2576 psp->decllinenoslot = 0;
2577 psp->insertLineMacro = 1;
2578 psp->state = WAITING_FOR_DECL_ARG;
2579 if( strcmp(x,"name")==0 ){
2580 psp->declargslot = &(psp->gp->name);
2581 psp->insertLineMacro = 0;
2582 }else if( strcmp(x,"include")==0 ){
2583 psp->declargslot = &(psp->gp->include);
2584 }else if( strcmp(x,"code")==0 ){
2585 psp->declargslot = &(psp->gp->extracode);
2586 }else if( strcmp(x,"token_destructor")==0 ){
2587 psp->declargslot = &psp->gp->tokendest;
2588 }else if( strcmp(x,"default_destructor")==0 ){
2589 psp->declargslot = &psp->gp->vardest;
2590 }else if( strcmp(x,"token_prefix")==0 ){
2591 psp->declargslot = &psp->gp->tokenprefix;
2592 psp->insertLineMacro = 0;
2593 }else if( strcmp(x,"syntax_error")==0 ){
2594 psp->declargslot = &(psp->gp->error);
2595 }else if( strcmp(x,"parse_accept")==0 ){
2596 psp->declargslot = &(psp->gp->accept);
2597 }else if( strcmp(x,"parse_failure")==0 ){
2598 psp->declargslot = &(psp->gp->failure);
2599 }else if( strcmp(x,"stack_overflow")==0 ){
2600 psp->declargslot = &(psp->gp->overflow);
2601 }else if( strcmp(x,"extra_argument")==0 ){
2602 psp->declargslot = &(psp->gp->arg);
2603 psp->insertLineMacro = 0;
2604 }else if( strcmp(x,"extra_context")==0 ){
2605 psp->declargslot = &(psp->gp->ctx);
2606 psp->insertLineMacro = 0;
2607 }else if( strcmp(x,"token_type")==0 ){
2608 psp->declargslot = &(psp->gp->tokentype);
2609 psp->insertLineMacro = 0;
2610 }else if( strcmp(x,"default_type")==0 ){
2611 psp->declargslot = &(psp->gp->vartype);
2612 psp->insertLineMacro = 0;
2613 }else if( strcmp(x,"realloc")==0 ){
2614 psp->declargslot = &(psp->gp->reallocFunc);
2615 psp->insertLineMacro = 0;
2616 }else if( strcmp(x,"free")==0 ){
2617 psp->declargslot = &(psp->gp->freeFunc);
2618 psp->insertLineMacro = 0;
2619 }else if( strcmp(x,"stack_size")==0 ){
2620 psp->declargslot = &(psp->gp->stacksize);
2621 psp->insertLineMacro = 0;
2622 }else if( strcmp(x,"start_symbol")==0 ){
2623 psp->declargslot = &(psp->gp->start);
2624 psp->insertLineMacro = 0;
2625 }else if( strcmp(x,"left")==0 ){
2626 psp->preccounter++;
2627 psp->declassoc = LEFT;
2628 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2629 }else if( strcmp(x,"right")==0 ){
2630 psp->preccounter++;
2631 psp->declassoc = RIGHT;
2632 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2633 }else if( strcmp(x,"nonassoc")==0 ){
2634 psp->preccounter++;
2635 psp->declassoc = NONE;
2636 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2637 }else if( strcmp(x,"destructor")==0 ){
2638 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2639 }else if( strcmp(x,"type")==0 ){
2640 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2641 }else if( strcmp(x,"fallback")==0 ){
2642 psp->fallback = 0;
2643 psp->state = WAITING_FOR_FALLBACK_ID;
2644 }else if( strcmp(x,"token")==0 ){
2645 psp->state = WAITING_FOR_TOKEN_NAME;
2646 }else if( strcmp(x,"wildcard")==0 ){
2647 psp->state = WAITING_FOR_WILDCARD_ID;
2648 }else if( strcmp(x,"token_class")==0 ){
2649 psp->state = WAITING_FOR_CLASS_ID;
2650 }else{
2651 ErrorMsg(psp->filename,psp->tokenlineno,
2652 "Unknown declaration keyword: \"%%%s\".",x);
2653 psp->errorcnt++;
2654 psp->state = RESYNC_AFTER_DECL_ERROR;
2656 }else{
2657 ErrorMsg(psp->filename,psp->tokenlineno,
2658 "Illegal declaration keyword: \"%s\".",x);
2659 psp->errorcnt++;
2660 psp->state = RESYNC_AFTER_DECL_ERROR;
2662 break;
2663 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2664 if( !ISALPHA(x[0]) ){
2665 ErrorMsg(psp->filename,psp->tokenlineno,
2666 "Symbol name missing after %%destructor keyword");
2667 psp->errorcnt++;
2668 psp->state = RESYNC_AFTER_DECL_ERROR;
2669 }else{
2670 struct symbol *sp = Symbol_new(x);
2671 psp->declargslot = &sp->destructor;
2672 psp->decllinenoslot = &sp->destLineno;
2673 psp->insertLineMacro = 1;
2674 psp->state = WAITING_FOR_DECL_ARG;
2676 break;
2677 case WAITING_FOR_DATATYPE_SYMBOL:
2678 if( !ISALPHA(x[0]) ){
2679 ErrorMsg(psp->filename,psp->tokenlineno,
2680 "Symbol name missing after %%type keyword");
2681 psp->errorcnt++;
2682 psp->state = RESYNC_AFTER_DECL_ERROR;
2683 }else{
2684 struct symbol *sp = Symbol_find(x);
2685 if((sp) && (sp->datatype)){
2686 ErrorMsg(psp->filename,psp->tokenlineno,
2687 "Symbol %%type \"%s\" already defined", x);
2688 psp->errorcnt++;
2689 psp->state = RESYNC_AFTER_DECL_ERROR;
2690 }else{
2691 if (!sp){
2692 sp = Symbol_new(x);
2694 psp->declargslot = &sp->datatype;
2695 psp->insertLineMacro = 0;
2696 psp->state = WAITING_FOR_DECL_ARG;
2699 break;
2700 case WAITING_FOR_PRECEDENCE_SYMBOL:
2701 if( x[0]=='.' ){
2702 psp->state = WAITING_FOR_DECL_OR_RULE;
2703 }else if( ISUPPER(x[0]) ){
2704 struct symbol *sp;
2705 sp = Symbol_new(x);
2706 if( sp->prec>=0 ){
2707 ErrorMsg(psp->filename,psp->tokenlineno,
2708 "Symbol \"%s\" has already be given a precedence.",x);
2709 psp->errorcnt++;
2710 }else{
2711 sp->prec = psp->preccounter;
2712 sp->assoc = psp->declassoc;
2714 }else{
2715 ErrorMsg(psp->filename,psp->tokenlineno,
2716 "Can't assign a precedence to \"%s\".",x);
2717 psp->errorcnt++;
2719 break;
2720 case WAITING_FOR_DECL_ARG:
2721 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
2722 const char *zOld, *zNew;
2723 char *zBuf, *z;
2724 int nOld, n, nLine = 0, nNew, nBack;
2725 int addLineMacro;
2726 char zLine[50];
2727 zNew = x;
2728 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2729 nNew = lemonStrlen(zNew);
2730 if( *psp->declargslot ){
2731 zOld = *psp->declargslot;
2732 }else{
2733 zOld = "";
2735 nOld = lemonStrlen(zOld);
2736 n = nOld + nNew + 20;
2737 addLineMacro = !psp->gp->nolinenosflag
2738 && psp->insertLineMacro
2739 && psp->tokenlineno>1
2740 && (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2741 if( addLineMacro ){
2742 for(z=psp->filename, nBack=0; *z; z++){
2743 if( *z=='\\' ) nBack++;
2745 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
2746 nLine = lemonStrlen(zLine);
2747 n += nLine + lemonStrlen(psp->filename) + nBack;
2749 *psp->declargslot = (char *) lemon_realloc(*psp->declargslot, n);
2750 zBuf = *psp->declargslot + nOld;
2751 if( addLineMacro ){
2752 if( nOld && zBuf[-1]!='\n' ){
2753 *(zBuf++) = '\n';
2755 memcpy(zBuf, zLine, nLine);
2756 zBuf += nLine;
2757 *(zBuf++) = '"';
2758 for(z=psp->filename; *z; z++){
2759 if( *z=='\\' ){
2760 *(zBuf++) = '\\';
2762 *(zBuf++) = *z;
2764 *(zBuf++) = '"';
2765 *(zBuf++) = '\n';
2767 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2768 psp->decllinenoslot[0] = psp->tokenlineno;
2770 memcpy(zBuf, zNew, nNew);
2771 zBuf += nNew;
2772 *zBuf = 0;
2773 psp->state = WAITING_FOR_DECL_OR_RULE;
2774 }else{
2775 ErrorMsg(psp->filename,psp->tokenlineno,
2776 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2777 psp->errorcnt++;
2778 psp->state = RESYNC_AFTER_DECL_ERROR;
2780 break;
2781 case WAITING_FOR_FALLBACK_ID:
2782 if( x[0]=='.' ){
2783 psp->state = WAITING_FOR_DECL_OR_RULE;
2784 }else if( !ISUPPER(x[0]) ){
2785 ErrorMsg(psp->filename, psp->tokenlineno,
2786 "%%fallback argument \"%s\" should be a token", x);
2787 psp->errorcnt++;
2788 }else{
2789 struct symbol *sp = Symbol_new(x);
2790 if( psp->fallback==0 ){
2791 psp->fallback = sp;
2792 }else if( sp->fallback ){
2793 ErrorMsg(psp->filename, psp->tokenlineno,
2794 "More than one fallback assigned to token %s", x);
2795 psp->errorcnt++;
2796 }else{
2797 sp->fallback = psp->fallback;
2798 psp->gp->has_fallback = 1;
2801 break;
2802 case WAITING_FOR_TOKEN_NAME:
2803 /* Tokens do not have to be declared before use. But they can be
2804 ** in order to control their assigned integer number. The number for
2805 ** each token is assigned when it is first seen. So by including
2807 ** %token ONE TWO THREE.
2809 ** early in the grammar file, that assigns small consecutive values
2810 ** to each of the tokens ONE TWO and THREE.
2812 if( x[0]=='.' ){
2813 psp->state = WAITING_FOR_DECL_OR_RULE;
2814 }else if( !ISUPPER(x[0]) ){
2815 ErrorMsg(psp->filename, psp->tokenlineno,
2816 "%%token argument \"%s\" should be a token", x);
2817 psp->errorcnt++;
2818 }else{
2819 (void)Symbol_new(x);
2821 break;
2822 case WAITING_FOR_WILDCARD_ID:
2823 if( x[0]=='.' ){
2824 psp->state = WAITING_FOR_DECL_OR_RULE;
2825 }else if( !ISUPPER(x[0]) ){
2826 ErrorMsg(psp->filename, psp->tokenlineno,
2827 "%%wildcard argument \"%s\" should be a token", x);
2828 psp->errorcnt++;
2829 }else{
2830 struct symbol *sp = Symbol_new(x);
2831 if( psp->gp->wildcard==0 ){
2832 psp->gp->wildcard = sp;
2833 }else{
2834 ErrorMsg(psp->filename, psp->tokenlineno,
2835 "Extra wildcard to token: %s", x);
2836 psp->errorcnt++;
2839 break;
2840 case WAITING_FOR_CLASS_ID:
2841 if( !ISLOWER(x[0]) ){
2842 ErrorMsg(psp->filename, psp->tokenlineno,
2843 "%%token_class must be followed by an identifier: %s", x);
2844 psp->errorcnt++;
2845 psp->state = RESYNC_AFTER_DECL_ERROR;
2846 }else if( Symbol_find(x) ){
2847 ErrorMsg(psp->filename, psp->tokenlineno,
2848 "Symbol \"%s\" already used", x);
2849 psp->errorcnt++;
2850 psp->state = RESYNC_AFTER_DECL_ERROR;
2851 }else{
2852 psp->tkclass = Symbol_new(x);
2853 psp->tkclass->type = MULTITERMINAL;
2854 psp->state = WAITING_FOR_CLASS_TOKEN;
2856 break;
2857 case WAITING_FOR_CLASS_TOKEN:
2858 if( x[0]=='.' ){
2859 psp->state = WAITING_FOR_DECL_OR_RULE;
2860 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
2861 struct symbol *msp = psp->tkclass;
2862 msp->nsubsym++;
2863 msp->subsym = (struct symbol **) lemon_realloc(msp->subsym,
2864 sizeof(struct symbol*)*msp->nsubsym);
2865 if( !ISUPPER(x[0]) ) x++;
2866 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2867 }else{
2868 ErrorMsg(psp->filename, psp->tokenlineno,
2869 "%%token_class argument \"%s\" should be a token", x);
2870 psp->errorcnt++;
2871 psp->state = RESYNC_AFTER_DECL_ERROR;
2873 break;
2874 case RESYNC_AFTER_RULE_ERROR:
2875 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2876 ** break; */
2877 case RESYNC_AFTER_DECL_ERROR:
2878 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2879 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2880 break;
2884 /* The text in the input is part of the argument to an %ifdef or %ifndef.
2885 ** Evaluate the text as a boolean expression. Return true or false.
2887 static int eval_preprocessor_boolean(char *z, int lineno){
2888 int neg = 0;
2889 int res = 0;
2890 int okTerm = 1;
2891 int i;
2892 for(i=0; z[i]!=0; i++){
2893 if( ISSPACE(z[i]) ) continue;
2894 if( z[i]=='!' ){
2895 if( !okTerm ) goto pp_syntax_error;
2896 neg = !neg;
2897 continue;
2899 if( z[i]=='|' && z[i+1]=='|' ){
2900 if( okTerm ) goto pp_syntax_error;
2901 if( res ) return 1;
2902 i++;
2903 okTerm = 1;
2904 continue;
2906 if( z[i]=='&' && z[i+1]=='&' ){
2907 if( okTerm ) goto pp_syntax_error;
2908 if( !res ) return 0;
2909 i++;
2910 okTerm = 1;
2911 continue;
2913 if( z[i]=='(' ){
2914 int k;
2915 int n = 1;
2916 if( !okTerm ) goto pp_syntax_error;
2917 for(k=i+1; z[k]; k++){
2918 if( z[k]==')' ){
2919 n--;
2920 if( n==0 ){
2921 z[k] = 0;
2922 res = eval_preprocessor_boolean(&z[i+1], -1);
2923 z[k] = ')';
2924 if( res<0 ){
2925 i = i-res;
2926 goto pp_syntax_error;
2928 i = k;
2929 break;
2931 }else if( z[k]=='(' ){
2932 n++;
2933 }else if( z[k]==0 ){
2934 i = k;
2935 goto pp_syntax_error;
2938 if( neg ){
2939 res = !res;
2940 neg = 0;
2942 okTerm = 0;
2943 continue;
2945 if( ISALPHA(z[i]) ){
2946 int j, k, n;
2947 if( !okTerm ) goto pp_syntax_error;
2948 for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){}
2949 n = k - i;
2950 res = 0;
2951 for(j=0; j<nDefine; j++){
2952 if( strncmp(azDefine[j],&z[i],n)==0 && azDefine[j][n]==0 ){
2953 if( !bDefineUsed[j] ){
2954 bDefineUsed[j] = 1;
2955 nDefineUsed++;
2957 res = 1;
2958 break;
2961 i = k-1;
2962 if( neg ){
2963 res = !res;
2964 neg = 0;
2966 okTerm = 0;
2967 continue;
2969 goto pp_syntax_error;
2971 return res;
2973 pp_syntax_error:
2974 if( lineno>0 ){
2975 fprintf(stderr, "%%if syntax error on line %d.\n", lineno);
2976 fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z);
2977 exit(1);
2978 }else{
2979 return -(i+1);
2983 /* Run the preprocessor over the input file text. The global variables
2984 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2985 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2986 ** comments them out. Text in between is also commented out as appropriate.
2988 static void preprocess_input(char *z){
2989 int i, j, k;
2990 int exclude = 0;
2991 int start = 0;
2992 int lineno = 1;
2993 int start_lineno = 1;
2994 for(i=0; z[i]; i++){
2995 if( z[i]=='\n' ) lineno++;
2996 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2997 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
2998 if( exclude ){
2999 exclude--;
3000 if( exclude==0 ){
3001 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
3004 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
3005 }else if( strncmp(&z[i],"%else",5)==0 && ISSPACE(z[i+5]) ){
3006 if( exclude==1){
3007 exclude = 0;
3008 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
3009 }else if( exclude==0 ){
3010 exclude = 1;
3011 start = i;
3012 start_lineno = lineno;
3014 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
3015 }else if( strncmp(&z[i],"%ifdef ",7)==0
3016 || strncmp(&z[i],"%if ",4)==0
3017 || strncmp(&z[i],"%ifndef ",8)==0 ){
3018 if( exclude ){
3019 exclude++;
3020 }else{
3021 int isNot;
3022 int iBool;
3023 for(j=i; z[j] && !ISSPACE(z[j]); j++){}
3024 iBool = j;
3025 isNot = (j==i+7);
3026 while( z[j] && z[j]!='\n' ){ j++; }
3027 k = z[j];
3028 z[j] = 0;
3029 exclude = eval_preprocessor_boolean(&z[iBool], lineno);
3030 z[j] = k;
3031 if( !isNot ) exclude = !exclude;
3032 if( exclude ){
3033 start = i;
3034 start_lineno = lineno;
3037 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
3040 if( exclude ){
3041 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
3042 exit(1);
3046 /* In spite of its name, this function is really a scanner. It read
3047 ** in the entire input file (all at once) then tokenizes it. Each
3048 ** token is passed to the function "parseonetoken" which builds all
3049 ** the appropriate data structures in the global state vector "gp".
3051 void Parse(struct lemon *gp)
3053 struct pstate ps;
3054 FILE *fp;
3055 char *filebuf;
3056 unsigned int filesize;
3057 int lineno;
3058 int c;
3059 char *cp, *nextcp;
3060 int startline = 0;
3062 memset(&ps, '\0', sizeof(ps));
3063 ps.gp = gp;
3064 ps.filename = gp->filename;
3065 ps.errorcnt = 0;
3066 ps.state = INITIALIZE;
3068 /* Begin by reading the input file */
3069 fp = fopen(ps.filename,"rb");
3070 if( fp==0 ){
3071 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
3072 gp->errorcnt++;
3073 return;
3075 fseek(fp,0,2);
3076 filesize = ftell(fp);
3077 rewind(fp);
3078 filebuf = (char *)lemon_malloc( filesize+1 );
3079 if( filesize>100000000 || filebuf==0 ){
3080 ErrorMsg(ps.filename,0,"Input file too large.");
3081 lemon_free(filebuf);
3082 gp->errorcnt++;
3083 fclose(fp);
3084 return;
3086 if( fread(filebuf,1,filesize,fp)!=filesize ){
3087 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
3088 filesize);
3089 lemon_free(filebuf);
3090 gp->errorcnt++;
3091 fclose(fp);
3092 return;
3094 fclose(fp);
3095 filebuf[filesize] = 0;
3097 /* Make an initial pass through the file to handle %ifdef and %ifndef */
3098 preprocess_input(filebuf);
3099 if( gp->printPreprocessed ){
3100 printf("%s\n", filebuf);
3101 return;
3104 /* Now scan the text of the input file */
3105 lineno = 1;
3106 for(cp=filebuf; (c= *cp)!=0; ){
3107 if( c=='\n' ) lineno++; /* Keep track of the line number */
3108 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
3109 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
3110 cp+=2;
3111 while( (c= *cp)!=0 && c!='\n' ) cp++;
3112 continue;
3114 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
3115 cp+=2;
3116 if( (*cp)=='/' ) cp++;
3117 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
3118 if( c=='\n' ) lineno++;
3119 cp++;
3121 if( c ) cp++;
3122 continue;
3124 ps.tokenstart = cp; /* Mark the beginning of the token */
3125 ps.tokenlineno = lineno; /* Linenumber on which token begins */
3126 if( c=='\"' ){ /* String literals */
3127 cp++;
3128 while( (c= *cp)!=0 && c!='\"' ){
3129 if( c=='\n' ) lineno++;
3130 cp++;
3132 if( c==0 ){
3133 ErrorMsg(ps.filename,startline,
3134 "String starting on this line is not terminated before "
3135 "the end of the file.");
3136 ps.errorcnt++;
3137 nextcp = cp;
3138 }else{
3139 nextcp = cp+1;
3141 }else if( c=='{' ){ /* A block of C code */
3142 int level;
3143 cp++;
3144 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
3145 if( c=='\n' ) lineno++;
3146 else if( c=='{' ) level++;
3147 else if( c=='}' ) level--;
3148 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
3149 int prevc;
3150 cp = &cp[2];
3151 prevc = 0;
3152 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
3153 if( c=='\n' ) lineno++;
3154 prevc = c;
3155 cp++;
3157 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
3158 cp = &cp[2];
3159 while( (c= *cp)!=0 && c!='\n' ) cp++;
3160 if( c ) lineno++;
3161 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
3162 int startchar, prevc;
3163 startchar = c;
3164 prevc = 0;
3165 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
3166 if( c=='\n' ) lineno++;
3167 if( prevc=='\\' ) prevc = 0;
3168 else prevc = c;
3172 if( c==0 ){
3173 ErrorMsg(ps.filename,ps.tokenlineno,
3174 "C code starting on this line is not terminated before "
3175 "the end of the file.");
3176 ps.errorcnt++;
3177 nextcp = cp;
3178 }else{
3179 nextcp = cp+1;
3181 }else if( ISALNUM(c) ){ /* Identifiers */
3182 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
3183 nextcp = cp;
3184 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
3185 cp += 3;
3186 nextcp = cp;
3187 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
3188 cp += 2;
3189 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
3190 nextcp = cp;
3191 }else{ /* All other (one character) operators */
3192 cp++;
3193 nextcp = cp;
3195 c = *cp;
3196 *cp = 0; /* Null terminate the token */
3197 parseonetoken(&ps); /* Parse the token */
3198 *cp = (char)c; /* Restore the buffer */
3199 cp = nextcp;
3201 lemon_free(filebuf); /* Release the buffer after parsing */
3202 gp->rule = ps.firstrule;
3203 gp->errorcnt = ps.errorcnt;
3205 /*************************** From the file "plink.c" *********************/
3207 ** Routines processing configuration follow-set propagation links
3208 ** in the LEMON parser generator.
3210 static struct plink *plink_freelist = 0;
3212 /* Allocate a new plink */
3213 struct plink *Plink_new(void){
3214 struct plink *newlink;
3216 if( plink_freelist==0 ){
3217 int i;
3218 int amt = 100;
3219 plink_freelist = (struct plink *)lemon_calloc( amt, sizeof(struct plink) );
3220 if( plink_freelist==0 ){
3221 fprintf(stderr,
3222 "Unable to allocate memory for a new follow-set propagation link.\n");
3223 exit(1);
3225 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3226 plink_freelist[amt-1].next = 0;
3228 newlink = plink_freelist;
3229 plink_freelist = plink_freelist->next;
3230 return newlink;
3233 /* Add a plink to a plink list */
3234 void Plink_add(struct plink **plpp, struct config *cfp)
3236 struct plink *newlink;
3237 newlink = Plink_new();
3238 newlink->next = *plpp;
3239 *plpp = newlink;
3240 newlink->cfp = cfp;
3243 /* Transfer every plink on the list "from" to the list "to" */
3244 void Plink_copy(struct plink **to, struct plink *from)
3246 struct plink *nextpl;
3247 while( from ){
3248 nextpl = from->next;
3249 from->next = *to;
3250 *to = from;
3251 from = nextpl;
3255 /* Delete every plink on the list */
3256 void Plink_delete(struct plink *plp)
3258 struct plink *nextpl;
3260 while( plp ){
3261 nextpl = plp->next;
3262 plp->next = plink_freelist;
3263 plink_freelist = plp;
3264 plp = nextpl;
3267 /*********************** From the file "report.c" **************************/
3269 ** Procedures for generating reports and tables in the LEMON parser generator.
3272 /* Generate a filename with the given suffix.
3274 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
3276 char *name;
3277 char *cp;
3278 char *filename = lemp->filename;
3279 int sz;
3281 if( outputDir ){
3282 cp = strrchr(filename, '/');
3283 if( cp ) filename = cp + 1;
3285 sz = lemonStrlen(filename);
3286 sz += lemonStrlen(suffix);
3287 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3288 sz += 5;
3289 name = (char*)lemon_malloc( sz );
3290 if( name==0 ){
3291 fprintf(stderr,"Can't allocate space for a filename.\n");
3292 exit(1);
3294 name[0] = 0;
3295 if( outputDir ){
3296 lemon_strcpy(name, outputDir);
3297 lemon_strcat(name, "/");
3299 lemon_strcat(name,filename);
3300 cp = strrchr(name,'.');
3301 if( cp ) *cp = 0;
3302 lemon_strcat(name,suffix);
3303 return name;
3306 /* Open a file with a name based on the name of the input file,
3307 ** but with a different (specified) suffix, and return a pointer
3308 ** to the stream */
3309 PRIVATE FILE *file_open(
3310 struct lemon *lemp,
3311 const char *suffix,
3312 const char *mode
3314 FILE *fp;
3316 if( lemp->outname ) lemon_free(lemp->outname);
3317 lemp->outname = file_makename(lemp, suffix);
3318 fp = fopen(lemp->outname,mode);
3319 if( fp==0 && *mode=='w' ){
3320 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3321 lemp->errorcnt++;
3322 return 0;
3324 return fp;
3327 /* Print the text of a rule
3329 void rule_print(FILE *out, struct rule *rp){
3330 int i, j;
3331 fprintf(out, "%s",rp->lhs->name);
3332 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3333 fprintf(out," ::=");
3334 for(i=0; i<rp->nrhs; i++){
3335 struct symbol *sp = rp->rhs[i];
3336 if( sp->type==MULTITERMINAL ){
3337 fprintf(out," %s", sp->subsym[0]->name);
3338 for(j=1; j<sp->nsubsym; j++){
3339 fprintf(out,"|%s", sp->subsym[j]->name);
3341 }else{
3342 fprintf(out," %s", sp->name);
3344 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3348 /* Duplicate the input file without comments and without actions
3349 ** on rules */
3350 void Reprint(struct lemon *lemp)
3352 struct rule *rp;
3353 struct symbol *sp;
3354 int i, j, maxlen, len, ncolumns, skip;
3355 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3356 maxlen = 10;
3357 for(i=0; i<lemp->nsymbol; i++){
3358 sp = lemp->symbols[i];
3359 len = lemonStrlen(sp->name);
3360 if( len>maxlen ) maxlen = len;
3362 ncolumns = 76/(maxlen+5);
3363 if( ncolumns<1 ) ncolumns = 1;
3364 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3365 for(i=0; i<skip; i++){
3366 printf("//");
3367 for(j=i; j<lemp->nsymbol; j+=skip){
3368 sp = lemp->symbols[j];
3369 assert( sp->index==j );
3370 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3372 printf("\n");
3374 for(rp=lemp->rule; rp; rp=rp->next){
3375 rule_print(stdout, rp);
3376 printf(".");
3377 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
3378 /* if( rp->code ) printf("\n %s",rp->code); */
3379 printf("\n");
3383 /* Print a single rule.
3385 void RulePrint(FILE *fp, struct rule *rp, int iCursor){
3386 struct symbol *sp;
3387 int i, j;
3388 fprintf(fp,"%s ::=",rp->lhs->name);
3389 for(i=0; i<=rp->nrhs; i++){
3390 if( i==iCursor ) fprintf(fp," *");
3391 if( i==rp->nrhs ) break;
3392 sp = rp->rhs[i];
3393 if( sp->type==MULTITERMINAL ){
3394 fprintf(fp," %s", sp->subsym[0]->name);
3395 for(j=1; j<sp->nsubsym; j++){
3396 fprintf(fp,"|%s",sp->subsym[j]->name);
3398 }else{
3399 fprintf(fp," %s", sp->name);
3404 /* Print the rule for a configuration.
3406 void ConfigPrint(FILE *fp, struct config *cfp){
3407 RulePrint(fp, cfp->rp, cfp->dot);
3410 /* #define TEST */
3411 #if 0
3412 /* Print a set */
3413 PRIVATE void SetPrint(out,set,lemp)
3414 FILE *out;
3415 char *set;
3416 struct lemon *lemp;
3418 int i;
3419 char *spacer;
3420 spacer = "";
3421 fprintf(out,"%12s[","");
3422 for(i=0; i<lemp->nterminal; i++){
3423 if( SetFind(set,i) ){
3424 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3425 spacer = " ";
3428 fprintf(out,"]\n");
3431 /* Print a plink chain */
3432 PRIVATE void PlinkPrint(out,plp,tag)
3433 FILE *out;
3434 struct plink *plp;
3435 char *tag;
3437 while( plp ){
3438 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
3439 ConfigPrint(out,plp->cfp);
3440 fprintf(out,"\n");
3441 plp = plp->next;
3444 #endif
3446 /* Print an action to the given file descriptor. Return FALSE if
3447 ** nothing was actually printed.
3449 int PrintAction(
3450 struct action *ap, /* The action to print */
3451 FILE *fp, /* Print the action here */
3452 int indent /* Indent by this amount */
3454 int result = 1;
3455 switch( ap->type ){
3456 case SHIFT: {
3457 struct state *stp = ap->x.stp;
3458 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
3459 break;
3461 case REDUCE: {
3462 struct rule *rp = ap->x.rp;
3463 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
3464 RulePrint(fp, rp, -1);
3465 break;
3467 case SHIFTREDUCE: {
3468 struct rule *rp = ap->x.rp;
3469 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
3470 RulePrint(fp, rp, -1);
3471 break;
3473 case ACCEPT:
3474 fprintf(fp,"%*s accept",indent,ap->sp->name);
3475 break;
3476 case ERROR:
3477 fprintf(fp,"%*s error",indent,ap->sp->name);
3478 break;
3479 case SRCONFLICT:
3480 case RRCONFLICT:
3481 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
3482 indent,ap->sp->name,ap->x.rp->iRule);
3483 break;
3484 case SSCONFLICT:
3485 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
3486 indent,ap->sp->name,ap->x.stp->statenum);
3487 break;
3488 case SH_RESOLVED:
3489 if( showPrecedenceConflict ){
3490 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
3491 indent,ap->sp->name,ap->x.stp->statenum);
3492 }else{
3493 result = 0;
3495 break;
3496 case RD_RESOLVED:
3497 if( showPrecedenceConflict ){
3498 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
3499 indent,ap->sp->name,ap->x.rp->iRule);
3500 }else{
3501 result = 0;
3503 break;
3504 case NOT_USED:
3505 result = 0;
3506 break;
3508 if( result && ap->spOpt ){
3509 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3511 return result;
3514 /* Generate the "*.out" log file */
3515 void ReportOutput(struct lemon *lemp)
3517 int i, n;
3518 struct state *stp;
3519 struct config *cfp;
3520 struct action *ap;
3521 struct rule *rp;
3522 FILE *fp;
3524 fp = file_open(lemp,".out","wb");
3525 if( fp==0 ) return;
3526 for(i=0; i<lemp->nxstate; i++){
3527 stp = lemp->sorted[i];
3528 fprintf(fp,"State %d:\n",stp->statenum);
3529 if( lemp->basisflag ) cfp=stp->bp;
3530 else cfp=stp->cfp;
3531 while( cfp ){
3532 char buf[20];
3533 if( cfp->dot==cfp->rp->nrhs ){
3534 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
3535 fprintf(fp," %5s ",buf);
3536 }else{
3537 fprintf(fp," ");
3539 ConfigPrint(fp,cfp);
3540 fprintf(fp,"\n");
3541 #if 0
3542 SetPrint(fp,cfp->fws,lemp);
3543 PlinkPrint(fp,cfp->fplp,"To ");
3544 PlinkPrint(fp,cfp->bplp,"From");
3545 #endif
3546 if( lemp->basisflag ) cfp=cfp->bp;
3547 else cfp=cfp->next;
3549 fprintf(fp,"\n");
3550 for(ap=stp->ap; ap; ap=ap->next){
3551 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3553 fprintf(fp,"\n");
3555 fprintf(fp, "----------------------------------------------------\n");
3556 fprintf(fp, "Symbols:\n");
3557 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
3558 for(i=0; i<lemp->nsymbol; i++){
3559 int j;
3560 struct symbol *sp;
3562 sp = lemp->symbols[i];
3563 fprintf(fp, " %3d: %s", i, sp->name);
3564 if( sp->type==NONTERMINAL ){
3565 fprintf(fp, ":");
3566 if( sp->lambda ){
3567 fprintf(fp, " <lambda>");
3569 for(j=0; j<lemp->nterminal; j++){
3570 if( sp->firstset && SetFind(sp->firstset, j) ){
3571 fprintf(fp, " %s", lemp->symbols[j]->name);
3575 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
3576 fprintf(fp, "\n");
3578 fprintf(fp, "----------------------------------------------------\n");
3579 fprintf(fp, "Syntax-only Symbols:\n");
3580 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3581 for(i=n=0; i<lemp->nsymbol; i++){
3582 int w;
3583 struct symbol *sp = lemp->symbols[i];
3584 if( sp->bContent ) continue;
3585 w = (int)strlen(sp->name);
3586 if( n>0 && n+w>75 ){
3587 fprintf(fp,"\n");
3588 n = 0;
3590 if( n>0 ){
3591 fprintf(fp, " ");
3592 n++;
3594 fprintf(fp, "%s", sp->name);
3595 n += w;
3597 if( n>0 ) fprintf(fp, "\n");
3598 fprintf(fp, "----------------------------------------------------\n");
3599 fprintf(fp, "Rules:\n");
3600 for(rp=lemp->rule; rp; rp=rp->next){
3601 fprintf(fp, "%4d: ", rp->iRule);
3602 rule_print(fp, rp);
3603 fprintf(fp,".");
3604 if( rp->precsym ){
3605 fprintf(fp," [%s precedence=%d]",
3606 rp->precsym->name, rp->precsym->prec);
3608 fprintf(fp,"\n");
3610 fclose(fp);
3611 return;
3614 /* Search for the file "name" which is in the same directory as
3615 ** the executable */
3616 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
3618 const char *pathlist;
3619 char *pathbufptr = 0;
3620 char *pathbuf = 0;
3621 char *path,*cp;
3622 char c;
3624 #ifdef __WIN32__
3625 cp = strrchr(argv0,'\\');
3626 #else
3627 cp = strrchr(argv0,'/');
3628 #endif
3629 if( cp ){
3630 c = *cp;
3631 *cp = 0;
3632 path = (char *)lemon_malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
3633 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
3634 *cp = c;
3635 }else{
3636 pathlist = getenv("PATH");
3637 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
3638 pathbuf = (char *) lemon_malloc( lemonStrlen(pathlist) + 1 );
3639 path = (char *)lemon_malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
3640 if( (pathbuf != 0) && (path!=0) ){
3641 pathbufptr = pathbuf;
3642 lemon_strcpy(pathbuf, pathlist);
3643 while( *pathbuf ){
3644 cp = strchr(pathbuf,':');
3645 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
3646 c = *cp;
3647 *cp = 0;
3648 lemon_sprintf(path,"%s/%s",pathbuf,name);
3649 *cp = c;
3650 if( c==0 ) pathbuf[0] = 0;
3651 else pathbuf = &cp[1];
3652 if( access(path,modemask)==0 ) break;
3655 lemon_free(pathbufptr);
3657 return path;
3660 /* Given an action, compute the integer value for that action
3661 ** which is to be put in the action table of the generated machine.
3662 ** Return negative if no action should be generated.
3664 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
3666 int act;
3667 switch( ap->type ){
3668 case SHIFT: act = ap->x.stp->statenum; break;
3669 case SHIFTREDUCE: {
3670 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3671 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3672 ** REDUCE action: */
3673 if( ap->sp->index>=lemp->nterminal
3674 && (lemp->errsym==0 || ap->sp->index!=lemp->errsym->index)
3676 act = lemp->minReduce + ap->x.rp->iRule;
3677 }else{
3678 act = lemp->minShiftReduce + ap->x.rp->iRule;
3680 break;
3682 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3683 case ERROR: act = lemp->errAction; break;
3684 case ACCEPT: act = lemp->accAction; break;
3685 default: act = -1; break;
3687 return act;
3690 #define LINESIZE 1000
3691 /* The next cluster of routines are for reading the template file
3692 ** and writing the results to the generated parser */
3693 /* The first function transfers data from "in" to "out" until
3694 ** a line is seen which begins with "%%". The line number is
3695 ** tracked.
3697 ** if name!=0, then any word that begin with "Parse" is changed to
3698 ** begin with *name instead.
3700 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
3702 int i, iStart;
3703 char line[LINESIZE];
3704 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3705 (*lineno)++;
3706 iStart = 0;
3707 if( name ){
3708 for(i=0; line[i]; i++){
3709 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3710 && (i==0 || !ISALPHA(line[i-1]))
3712 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3713 fprintf(out,"%s",name);
3714 i += 4;
3715 iStart = i+1;
3719 fprintf(out,"%s",&line[iStart]);
3723 /* Skip forward past the header of the template file to the first "%%"
3725 PRIVATE void tplt_skip_header(FILE *in, int *lineno)
3727 char line[LINESIZE];
3728 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3729 (*lineno)++;
3733 /* The next function finds the template file and opens it, returning
3734 ** a pointer to the opened file. */
3735 PRIVATE FILE *tplt_open(struct lemon *lemp)
3737 static char templatename[] = "lempar.c";
3738 char buf[1000];
3739 FILE *in;
3740 char *tpltname;
3741 char *toFree = 0;
3742 char *cp;
3744 /* first, see if user specified a template filename on the command line. */
3745 if (user_templatename != 0) {
3746 if( access(user_templatename,004)==-1 ){
3747 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3748 user_templatename);
3749 lemp->errorcnt++;
3750 return 0;
3752 in = fopen(user_templatename,"rb");
3753 if( in==0 ){
3754 fprintf(stderr,"Can't open the template file \"%s\".\n",
3755 user_templatename);
3756 lemp->errorcnt++;
3757 return 0;
3759 return in;
3762 cp = strrchr(lemp->filename,'.');
3763 if( cp ){
3764 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3765 }else{
3766 lemon_sprintf(buf,"%s.lt",lemp->filename);
3768 if( access(buf,004)==0 ){
3769 tpltname = buf;
3770 }else if( access(templatename,004)==0 ){
3771 tpltname = templatename;
3772 }else{
3773 toFree = tpltname = pathsearch(lemp->argv[0],templatename,0);
3775 if( tpltname==0 ){
3776 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3777 templatename);
3778 lemp->errorcnt++;
3779 return 0;
3781 in = fopen(tpltname,"rb");
3782 if( in==0 ){
3783 fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
3784 lemp->errorcnt++;
3786 lemon_free(toFree);
3787 return in;
3790 /* Print a #line directive line to the output file. */
3791 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
3793 fprintf(out,"#line %d \"",lineno);
3794 while( *filename ){
3795 if( *filename == '\\' ) putc('\\',out);
3796 putc(*filename,out);
3797 filename++;
3799 fprintf(out,"\"\n");
3802 /* Print a string to the file and keep the linenumber up to date */
3803 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
3805 if( str==0 ) return;
3806 while( *str ){
3807 putc(*str,out);
3808 if( *str=='\n' ) (*lineno)++;
3809 str++;
3811 if( str[-1]!='\n' ){
3812 putc('\n',out);
3813 (*lineno)++;
3815 if (!lemp->nolinenosflag) {
3816 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3818 return;
3822 ** The following routine emits code for the destructor for the
3823 ** symbol sp
3825 void emit_destructor_code(
3826 FILE *out,
3827 struct symbol *sp,
3828 struct lemon *lemp,
3829 int *lineno
3831 char *cp = 0;
3833 if( sp->type==TERMINAL ){
3834 cp = lemp->tokendest;
3835 if( cp==0 ) return;
3836 fprintf(out,"{\n"); (*lineno)++;
3837 }else if( sp->destructor ){
3838 cp = sp->destructor;
3839 fprintf(out,"{\n"); (*lineno)++;
3840 if( !lemp->nolinenosflag ){
3841 (*lineno)++;
3842 tplt_linedir(out,sp->destLineno,lemp->filename);
3844 }else if( lemp->vardest ){
3845 cp = lemp->vardest;
3846 if( cp==0 ) return;
3847 fprintf(out,"{\n"); (*lineno)++;
3848 }else{
3849 assert( 0 ); /* Cannot happen */
3851 for(; *cp; cp++){
3852 if( *cp=='$' && cp[1]=='$' ){
3853 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3854 cp++;
3855 continue;
3857 if( *cp=='\n' ) (*lineno)++;
3858 fputc(*cp,out);
3860 fprintf(out,"\n"); (*lineno)++;
3861 if (!lemp->nolinenosflag) {
3862 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3864 fprintf(out,"}\n"); (*lineno)++;
3865 return;
3869 ** Return TRUE (non-zero) if the given symbol has a destructor.
3871 int has_destructor(struct symbol *sp, struct lemon *lemp)
3873 int ret;
3874 if( sp->type==TERMINAL ){
3875 ret = lemp->tokendest!=0;
3876 }else{
3877 ret = lemp->vardest!=0 || sp->destructor!=0;
3879 return ret;
3883 ** Append text to a dynamically allocated string. If zText is 0 then
3884 ** reset the string to be empty again. Always return the complete text
3885 ** of the string (which is overwritten with each call).
3887 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3888 ** \000 terminator is stored. zText can contain up to two instances of
3889 ** %d. The values of p1 and p2 are written into the first and second
3890 ** %d.
3892 ** If n==-1, then the previous character is overwritten.
3894 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3895 static char empty[1] = { 0 };
3896 static char *z = 0;
3897 static int alloced = 0;
3898 static int used = 0;
3899 int c;
3900 char zInt[40];
3901 if( zText==0 ){
3902 if( used==0 && z!=0 ) z[0] = 0;
3903 used = 0;
3904 return z;
3906 if( n<=0 ){
3907 if( n<0 ){
3908 used += n;
3909 assert( used>=0 );
3911 n = lemonStrlen(zText);
3913 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
3914 alloced = n + sizeof(zInt)*2 + used + 200;
3915 z = (char *) lemon_realloc(z, alloced);
3917 if( z==0 ) return empty;
3918 while( n-- > 0 ){
3919 c = *(zText++);
3920 if( c=='%' && n>0 && zText[0]=='d' ){
3921 lemon_sprintf(zInt, "%d", p1);
3922 p1 = p2;
3923 lemon_strcpy(&z[used], zInt);
3924 used += lemonStrlen(&z[used]);
3925 zText++;
3926 n--;
3927 }else{
3928 z[used++] = (char)c;
3931 z[used] = 0;
3932 return z;
3936 ** Write and transform the rp->code string so that symbols are expanded.
3937 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3939 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3940 ** to be defined.
3942 PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
3943 char *cp, *xp;
3944 int i;
3945 int rc = 0; /* True if yylhsminor is used */
3946 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
3947 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3948 char lhsused = 0; /* True if the LHS element has been used */
3949 char lhsdirect; /* True if LHS writes directly into stack */
3950 char used[MAXRHS]; /* True for each RHS element which is used */
3951 char zLhs[50]; /* Convert the LHS symbol into this string */
3952 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
3954 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3955 lhsused = 0;
3957 if( rp->code==0 ){
3958 static char newlinestr[2] = { '\n', '\0' };
3959 rp->code = newlinestr;
3960 rp->line = rp->ruleline;
3961 rp->noCode = 1;
3962 }else{
3963 rp->noCode = 0;
3967 if( rp->nrhs==0 ){
3968 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3969 lhsdirect = 1;
3970 }else if( rp->rhsalias[0]==0 ){
3971 /* The left-most RHS symbol has no value. LHS direct is ok. But
3972 ** we have to call the destructor on the RHS symbol first. */
3973 lhsdirect = 1;
3974 if( has_destructor(rp->rhs[0],lemp) ){
3975 append_str(0,0,0,0);
3976 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3977 rp->rhs[0]->index,1-rp->nrhs);
3978 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3979 rp->noCode = 0;
3981 }else if( rp->lhsalias==0 ){
3982 /* There is no LHS value symbol. */
3983 lhsdirect = 1;
3984 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3985 /* The LHS symbol and the left-most RHS symbol are the same, so
3986 ** direct writing is allowed */
3987 lhsdirect = 1;
3988 lhsused = 1;
3989 used[0] = 1;
3990 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3991 ErrorMsg(lemp->filename,rp->ruleline,
3992 "%s(%s) and %s(%s) share the same label but have "
3993 "different datatypes.",
3994 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3995 lemp->errorcnt++;
3997 }else{
3998 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3999 rp->lhsalias, rp->rhsalias[0]);
4000 zSkip = strstr(rp->code, zOvwrt);
4001 if( zSkip!=0 ){
4002 /* The code contains a special comment that indicates that it is safe
4003 ** for the LHS label to overwrite left-most RHS label. */
4004 lhsdirect = 1;
4005 }else{
4006 lhsdirect = 0;
4009 if( lhsdirect ){
4010 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
4011 }else{
4012 rc = 1;
4013 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
4016 append_str(0,0,0,0);
4018 /* This const cast is wrong but harmless, if we're careful. */
4019 for(cp=(char *)rp->code; *cp; cp++){
4020 if( cp==zSkip ){
4021 append_str(zOvwrt,0,0,0);
4022 cp += lemonStrlen(zOvwrt)-1;
4023 dontUseRhs0 = 1;
4024 continue;
4026 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
4027 char saved;
4028 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
4029 saved = *xp;
4030 *xp = 0;
4031 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
4032 append_str(zLhs,0,0,0);
4033 cp = xp;
4034 lhsused = 1;
4035 }else{
4036 for(i=0; i<rp->nrhs; i++){
4037 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
4038 if( i==0 && dontUseRhs0 ){
4039 ErrorMsg(lemp->filename,rp->ruleline,
4040 "Label %s used after '%s'.",
4041 rp->rhsalias[0], zOvwrt);
4042 lemp->errorcnt++;
4043 }else if( cp!=rp->code && cp[-1]=='@' ){
4044 /* If the argument is of the form @X then substituted
4045 ** the token number of X, not the value of X */
4046 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
4047 }else{
4048 struct symbol *sp = rp->rhs[i];
4049 int dtnum;
4050 if( sp->type==MULTITERMINAL ){
4051 dtnum = sp->subsym[0]->dtnum;
4052 }else{
4053 dtnum = sp->dtnum;
4055 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
4057 cp = xp;
4058 used[i] = 1;
4059 break;
4063 *xp = saved;
4065 append_str(cp, 1, 0, 0);
4066 } /* End loop */
4068 /* Main code generation completed */
4069 cp = append_str(0,0,0,0);
4070 if( cp && cp[0] ) rp->code = Strsafe(cp);
4071 append_str(0,0,0,0);
4073 /* Check to make sure the LHS has been used */
4074 if( rp->lhsalias && !lhsused ){
4075 ErrorMsg(lemp->filename,rp->ruleline,
4076 "Label \"%s\" for \"%s(%s)\" is never used.",
4077 rp->lhsalias,rp->lhs->name,rp->lhsalias);
4078 lemp->errorcnt++;
4081 /* Generate destructor code for RHS minor values which are not referenced.
4082 ** Generate error messages for unused labels and duplicate labels.
4084 for(i=0; i<rp->nrhs; i++){
4085 if( rp->rhsalias[i] ){
4086 if( i>0 ){
4087 int j;
4088 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
4089 ErrorMsg(lemp->filename,rp->ruleline,
4090 "%s(%s) has the same label as the LHS but is not the left-most "
4091 "symbol on the RHS.",
4092 rp->rhs[i]->name, rp->rhsalias[i]);
4093 lemp->errorcnt++;
4095 for(j=0; j<i; j++){
4096 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
4097 ErrorMsg(lemp->filename,rp->ruleline,
4098 "Label %s used for multiple symbols on the RHS of a rule.",
4099 rp->rhsalias[i]);
4100 lemp->errorcnt++;
4101 break;
4105 if( !used[i] ){
4106 ErrorMsg(lemp->filename,rp->ruleline,
4107 "Label %s for \"%s(%s)\" is never used.",
4108 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
4109 lemp->errorcnt++;
4111 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
4112 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
4113 rp->rhs[i]->index,i-rp->nrhs+1);
4117 /* If unable to write LHS values directly into the stack, write the
4118 ** saved LHS value now. */
4119 if( lhsdirect==0 ){
4120 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
4121 append_str(zLhs, 0, 0, 0);
4122 append_str(";\n", 0, 0, 0);
4125 /* Suffix code generation complete */
4126 cp = append_str(0,0,0,0);
4127 if( cp && cp[0] ){
4128 rp->codeSuffix = Strsafe(cp);
4129 rp->noCode = 0;
4132 return rc;
4136 ** Generate code which executes when the rule "rp" is reduced. Write
4137 ** the code to "out". Make sure lineno stays up-to-date.
4139 PRIVATE void emit_code(
4140 FILE *out,
4141 struct rule *rp,
4142 struct lemon *lemp,
4143 int *lineno
4145 const char *cp;
4147 /* Setup code prior to the #line directive */
4148 if( rp->codePrefix && rp->codePrefix[0] ){
4149 fprintf(out, "{%s", rp->codePrefix);
4150 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4153 /* Generate code to do the reduce action */
4154 if( rp->code ){
4155 if( !lemp->nolinenosflag ){
4156 (*lineno)++;
4157 tplt_linedir(out,rp->line,lemp->filename);
4159 fprintf(out,"{%s",rp->code);
4160 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4161 fprintf(out,"}\n"); (*lineno)++;
4162 if( !lemp->nolinenosflag ){
4163 (*lineno)++;
4164 tplt_linedir(out,*lineno,lemp->outname);
4168 /* Generate breakdown code that occurs after the #line directive */
4169 if( rp->codeSuffix && rp->codeSuffix[0] ){
4170 fprintf(out, "%s", rp->codeSuffix);
4171 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4174 if( rp->codePrefix ){
4175 fprintf(out, "}\n"); (*lineno)++;
4178 return;
4182 ** Print the definition of the union used for the parser's data stack.
4183 ** This union contains fields for every possible data type for tokens
4184 ** and nonterminals. In the process of computing and printing this
4185 ** union, also set the ".dtnum" field of every terminal and nonterminal
4186 ** symbol.
4188 void print_stack_union(
4189 FILE *out, /* The output stream */
4190 struct lemon *lemp, /* The main info structure for this parser */
4191 int *plineno, /* Pointer to the line number */
4192 int mhflag /* True if generating makeheaders output */
4194 int lineno; /* The line number of the output */
4195 char **types; /* A hash table of datatypes */
4196 int arraysize; /* Size of the "types" array */
4197 int maxdtlength; /* Maximum length of any ".datatype" field. */
4198 char *stddt; /* Standardized name for a datatype */
4199 int i,j; /* Loop counters */
4200 unsigned hash; /* For hashing the name of a type */
4201 const char *name; /* Name of the parser */
4203 /* Allocate and initialize types[] and allocate stddt[] */
4204 arraysize = lemp->nsymbol * 2;
4205 types = (char**)lemon_calloc( arraysize, sizeof(char*) );
4206 if( types==0 ){
4207 fprintf(stderr,"Out of memory.\n");
4208 exit(1);
4210 for(i=0; i<arraysize; i++) types[i] = 0;
4211 maxdtlength = 0;
4212 if( lemp->vartype ){
4213 maxdtlength = lemonStrlen(lemp->vartype);
4215 for(i=0; i<lemp->nsymbol; i++){
4216 int len;
4217 struct symbol *sp = lemp->symbols[i];
4218 if( sp->datatype==0 ) continue;
4219 len = lemonStrlen(sp->datatype);
4220 if( len>maxdtlength ) maxdtlength = len;
4222 stddt = (char*)lemon_malloc( maxdtlength*2 + 1 );
4223 if( stddt==0 ){
4224 fprintf(stderr,"Out of memory.\n");
4225 exit(1);
4228 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4229 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
4230 ** used for terminal symbols. If there is no %default_type defined then
4231 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4232 ** a datatype using the %type directive.
4234 for(i=0; i<lemp->nsymbol; i++){
4235 struct symbol *sp = lemp->symbols[i];
4236 char *cp;
4237 if( sp==lemp->errsym ){
4238 sp->dtnum = arraysize+1;
4239 continue;
4241 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
4242 sp->dtnum = 0;
4243 continue;
4245 cp = sp->datatype;
4246 if( cp==0 ) cp = lemp->vartype;
4247 j = 0;
4248 while( ISSPACE(*cp) ) cp++;
4249 while( *cp ) stddt[j++] = *cp++;
4250 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
4251 stddt[j] = 0;
4252 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
4253 sp->dtnum = 0;
4254 continue;
4256 hash = 0;
4257 for(j=0; stddt[j]; j++){
4258 hash = hash*53 + stddt[j];
4260 hash = (hash & 0x7fffffff)%arraysize;
4261 while( types[hash] ){
4262 if( strcmp(types[hash],stddt)==0 ){
4263 sp->dtnum = hash + 1;
4264 break;
4266 hash++;
4267 if( hash>=(unsigned)arraysize ) hash = 0;
4269 if( types[hash]==0 ){
4270 sp->dtnum = hash + 1;
4271 types[hash] = (char*)lemon_malloc( lemonStrlen(stddt)+1 );
4272 if( types[hash]==0 ){
4273 fprintf(stderr,"Out of memory.\n");
4274 exit(1);
4276 lemon_strcpy(types[hash],stddt);
4280 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4281 name = lemp->name ? lemp->name : "Parse";
4282 lineno = *plineno;
4283 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4284 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4285 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4286 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4287 fprintf(out,"typedef union {\n"); lineno++;
4288 fprintf(out," int yyinit;\n"); lineno++;
4289 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4290 for(i=0; i<arraysize; i++){
4291 if( types[i]==0 ) continue;
4292 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4293 lemon_free(types[i]);
4295 if( lemp->errsym && lemp->errsym->useCnt ){
4296 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4298 lemon_free(stddt);
4299 lemon_free(types);
4300 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4301 *plineno = lineno;
4305 ** Return the name of a C datatype able to represent values between
4306 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4307 ** for that type (1, 2, or 4) into *pnByte.
4309 static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4310 const char *zType = "int";
4311 int nByte = 4;
4312 if( lwr>=0 ){
4313 if( upr<=255 ){
4314 zType = "unsigned char";
4315 nByte = 1;
4316 }else if( upr<65535 ){
4317 zType = "unsigned short int";
4318 nByte = 2;
4319 }else{
4320 zType = "unsigned int";
4321 nByte = 4;
4323 }else if( lwr>=-127 && upr<=127 ){
4324 zType = "signed char";
4325 nByte = 1;
4326 }else if( lwr>=-32767 && upr<32767 ){
4327 zType = "short";
4328 nByte = 2;
4330 if( pnByte ) *pnByte = nByte;
4331 return zType;
4335 ** Each state contains a set of token transaction and a set of
4336 ** nonterminal transactions. Each of these sets makes an instance
4337 ** of the following structure. An array of these structures is used
4338 ** to order the creation of entries in the yy_action[] table.
4340 struct axset {
4341 struct state *stp; /* A pointer to a state */
4342 int isTkn; /* True to use tokens. False for non-terminals */
4343 int nAction; /* Number of actions */
4344 int iOrder; /* Original order of action sets */
4348 ** Compare to axset structures for sorting purposes
4350 static int axset_compare(const void *a, const void *b){
4351 struct axset *p1 = (struct axset*)a;
4352 struct axset *p2 = (struct axset*)b;
4353 int c;
4354 c = p2->nAction - p1->nAction;
4355 if( c==0 ){
4356 c = p1->iOrder - p2->iOrder;
4358 assert( c!=0 || p1==p2 );
4359 return c;
4363 ** Write text on "out" that describes the rule "rp".
4365 static void writeRuleText(FILE *out, struct rule *rp){
4366 int j;
4367 fprintf(out,"%s ::=", rp->lhs->name);
4368 for(j=0; j<rp->nrhs; j++){
4369 struct symbol *sp = rp->rhs[j];
4370 if( sp->type!=MULTITERMINAL ){
4371 fprintf(out," %s", sp->name);
4372 }else{
4373 int k;
4374 fprintf(out," %s", sp->subsym[0]->name);
4375 for(k=1; k<sp->nsubsym; k++){
4376 fprintf(out,"|%s",sp->subsym[k]->name);
4383 /* Generate C source code for the parser */
4384 void ReportTable(
4385 struct lemon *lemp,
4386 int mhflag, /* Output in makeheaders format if true */
4387 int sqlFlag /* Generate the *.sql file too */
4389 FILE *out, *in, *sql;
4390 int lineno;
4391 struct state *stp;
4392 struct action *ap;
4393 struct rule *rp;
4394 struct acttab *pActtab;
4395 int i, j, n, sz, mn, mx;
4396 int nLookAhead;
4397 int szActionType; /* sizeof(YYACTIONTYPE) */
4398 int szCodeType; /* sizeof(YYCODETYPE) */
4399 const char *name;
4400 int mnTknOfst, mxTknOfst;
4401 int mnNtOfst, mxNtOfst;
4402 struct axset *ax;
4403 char *prefix;
4405 lemp->minShiftReduce = lemp->nstate;
4406 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4407 lemp->accAction = lemp->errAction + 1;
4408 lemp->noAction = lemp->accAction + 1;
4409 lemp->minReduce = lemp->noAction + 1;
4410 lemp->maxAction = lemp->minReduce + lemp->nrule;
4412 in = tplt_open(lemp);
4413 if( in==0 ) return;
4414 out = file_open(lemp,".c","wb");
4415 if( out==0 ){
4416 fclose(in);
4417 return;
4419 if( sqlFlag==0 ){
4420 sql = 0;
4421 }else{
4422 sql = file_open(lemp, ".sql", "wb");
4423 if( sql==0 ){
4424 fclose(in);
4425 fclose(out);
4426 return;
4428 fprintf(sql,
4429 "BEGIN;\n"
4430 "CREATE TABLE symbol(\n"
4431 " id INTEGER PRIMARY KEY,\n"
4432 " name TEXT NOT NULL,\n"
4433 " isTerminal BOOLEAN NOT NULL,\n"
4434 " fallback INTEGER REFERENCES symbol"
4435 " DEFERRABLE INITIALLY DEFERRED\n"
4436 ");\n"
4438 for(i=0; i<lemp->nsymbol; i++){
4439 fprintf(sql,
4440 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4441 "VALUES(%d,'%s',%s",
4442 i, lemp->symbols[i]->name,
4443 i<lemp->nterminal ? "TRUE" : "FALSE"
4445 if( lemp->symbols[i]->fallback ){
4446 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
4447 }else{
4448 fprintf(sql, ",NULL);\n");
4451 fprintf(sql,
4452 "CREATE TABLE rule(\n"
4453 " ruleid INTEGER PRIMARY KEY,\n"
4454 " lhs INTEGER REFERENCES symbol(id),\n"
4455 " txt TEXT\n"
4456 ");\n"
4457 "CREATE TABLE rulerhs(\n"
4458 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4459 " pos INTEGER,\n"
4460 " sym INTEGER REFERENCES symbol(id)\n"
4461 ");\n"
4463 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4464 assert( i==rp->iRule );
4465 fprintf(sql,
4466 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
4467 rp->iRule, rp->lhs->index
4469 writeRuleText(sql, rp);
4470 fprintf(sql,"');\n");
4471 for(j=0; j<rp->nrhs; j++){
4472 struct symbol *sp = rp->rhs[j];
4473 if( sp->type!=MULTITERMINAL ){
4474 fprintf(sql,
4475 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4476 i,j,sp->index
4478 }else{
4479 int k;
4480 for(k=0; k<sp->nsubsym; k++){
4481 fprintf(sql,
4482 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4483 i,j,sp->subsym[k]->index
4489 fprintf(sql, "COMMIT;\n");
4491 lineno = 1;
4493 fprintf(out,
4494 "/* This file is automatically generated by Lemon from input grammar\n"
4495 "** source file \"%s\"", lemp->filename); lineno++;
4496 if( nDefineUsed==0 ){
4497 fprintf(out, ".\n*/\n"); lineno += 2;
4498 }else{
4499 fprintf(out, " with these options:\n**\n"); lineno += 2;
4500 for(i=0; i<nDefine; i++){
4501 if( !bDefineUsed[i] ) continue;
4502 fprintf(out, "** -D%s\n", azDefine[i]); lineno++;
4504 fprintf(out, "*/\n"); lineno++;
4507 /* The first %include directive begins with a C-language comment,
4508 ** then skip over the header comment of the template file
4510 if( lemp->include==0 ) lemp->include = "";
4511 for(i=0; ISSPACE(lemp->include[i]); i++){
4512 if( lemp->include[i]=='\n' ){
4513 lemp->include += i+1;
4514 i = -1;
4517 if( lemp->include[0]=='/' ){
4518 tplt_skip_header(in,&lineno);
4519 }else{
4520 tplt_xfer(lemp->name,in,out,&lineno);
4523 /* Generate the include code, if any */
4524 tplt_print(out,lemp,lemp->include,&lineno);
4525 if( mhflag ){
4526 char *incName = file_makename(lemp, ".h");
4527 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4528 lemon_free(incName);
4530 tplt_xfer(lemp->name,in,out,&lineno);
4532 /* Generate #defines for all tokens */
4533 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4534 else prefix = "";
4535 if( mhflag ){
4536 fprintf(out,"#if INTERFACE\n"); lineno++;
4537 }else{
4538 fprintf(out,"#ifndef %s%s\n", prefix, lemp->symbols[1]->name);
4540 for(i=1; i<lemp->nterminal; i++){
4541 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4542 lineno++;
4544 fprintf(out,"#endif\n"); lineno++;
4545 tplt_xfer(lemp->name,in,out,&lineno);
4547 /* Generate the defines */
4548 fprintf(out,"#define YYCODETYPE %s\n",
4549 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4550 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
4551 fprintf(out,"#define YYACTIONTYPE %s\n",
4552 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
4553 if( lemp->wildcard ){
4554 fprintf(out,"#define YYWILDCARD %d\n",
4555 lemp->wildcard->index); lineno++;
4557 print_stack_union(out,lemp,&lineno,mhflag);
4558 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
4559 if( lemp->stacksize ){
4560 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4561 }else{
4562 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4564 fprintf(out, "#endif\n"); lineno++;
4565 if( mhflag ){
4566 fprintf(out,"#if INTERFACE\n"); lineno++;
4568 name = lemp->name ? lemp->name : "Parse";
4569 if( lemp->arg && lemp->arg[0] ){
4570 i = lemonStrlen(lemp->arg);
4571 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4572 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
4573 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4574 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4575 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4576 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
4577 name,lemp->arg,&lemp->arg[i]); lineno++;
4578 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
4579 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
4580 }else{
4581 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4582 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4583 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
4584 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4585 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
4587 if( lemp->reallocFunc ){
4588 fprintf(out,"#define YYREALLOC %s\n", lemp->reallocFunc); lineno++;
4589 }else{
4590 fprintf(out,"#define YYREALLOC realloc\n"); lineno++;
4592 if( lemp->freeFunc ){
4593 fprintf(out,"#define YYFREE %s\n", lemp->freeFunc); lineno++;
4594 }else{
4595 fprintf(out,"#define YYFREE free\n"); lineno++;
4597 if( lemp->reallocFunc && lemp->freeFunc ){
4598 fprintf(out,"#define YYDYNSTACK 1\n"); lineno++;
4599 }else{
4600 fprintf(out,"#define YYDYNSTACK 0\n"); lineno++;
4602 if( lemp->ctx && lemp->ctx[0] ){
4603 i = lemonStrlen(lemp->ctx);
4604 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4605 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4606 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4607 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4608 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4609 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4610 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4611 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4612 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4613 }else{
4614 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4615 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4616 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4617 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4618 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4620 if( mhflag ){
4621 fprintf(out,"#endif\n"); lineno++;
4623 if( lemp->errsym && lemp->errsym->useCnt ){
4624 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4625 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
4627 if( lemp->has_fallback ){
4628 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4631 /* Compute the action table, but do not output it yet. The action
4632 ** table must be computed before generating the YYNSTATE macro because
4633 ** we need to know how many states can be eliminated.
4635 ax = (struct axset *) lemon_calloc(lemp->nxstate*2, sizeof(ax[0]));
4636 if( ax==0 ){
4637 fprintf(stderr,"malloc failed\n");
4638 exit(1);
4640 for(i=0; i<lemp->nxstate; i++){
4641 stp = lemp->sorted[i];
4642 ax[i*2].stp = stp;
4643 ax[i*2].isTkn = 1;
4644 ax[i*2].nAction = stp->nTknAct;
4645 ax[i*2+1].stp = stp;
4646 ax[i*2+1].isTkn = 0;
4647 ax[i*2+1].nAction = stp->nNtAct;
4649 mxTknOfst = mnTknOfst = 0;
4650 mxNtOfst = mnNtOfst = 0;
4651 /* In an effort to minimize the action table size, use the heuristic
4652 ** of placing the largest action sets first */
4653 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4654 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
4655 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
4656 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
4657 stp = ax[i].stp;
4658 if( ax[i].isTkn ){
4659 for(ap=stp->ap; ap; ap=ap->next){
4660 int action;
4661 if( ap->sp->index>=lemp->nterminal ) continue;
4662 action = compute_action(lemp, ap);
4663 if( action<0 ) continue;
4664 acttab_action(pActtab, ap->sp->index, action);
4666 stp->iTknOfst = acttab_insert(pActtab, 1);
4667 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4668 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4669 }else{
4670 for(ap=stp->ap; ap; ap=ap->next){
4671 int action;
4672 if( ap->sp->index<lemp->nterminal ) continue;
4673 if( ap->sp->index==lemp->nsymbol ) continue;
4674 action = compute_action(lemp, ap);
4675 if( action<0 ) continue;
4676 acttab_action(pActtab, ap->sp->index, action);
4678 stp->iNtOfst = acttab_insert(pActtab, 0);
4679 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4680 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
4682 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4683 { int jj, nn;
4684 for(jj=nn=0; jj<pActtab->nAction; jj++){
4685 if( pActtab->aAction[jj].action<0 ) nn++;
4687 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4688 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4689 ax[i].nAction, pActtab->nAction, nn);
4691 #endif
4693 lemon_free(ax);
4695 /* Mark rules that are actually used for reduce actions after all
4696 ** optimizations have been applied
4698 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4699 for(i=0; i<lemp->nxstate; i++){
4700 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4701 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
4702 ap->x.rp->doesReduce = 1;
4707 /* Finish rendering the constants now that the action table has
4708 ** been computed */
4709 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4710 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
4711 fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
4712 lineno++;
4713 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
4714 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
4715 i = lemp->minShiftReduce;
4716 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4717 i += lemp->nrule;
4718 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4719 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4720 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4721 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4722 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4723 i = lemp->minReduce + lemp->nrule;
4724 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4726 /* Minimum and maximum token values that have a destructor */
4727 mn = mx = 0;
4728 for(i=0; i<lemp->nsymbol; i++){
4729 struct symbol *sp = lemp->symbols[i];
4731 if( sp && sp->type!=TERMINAL && sp->destructor ){
4732 if( mn==0 || sp->index<mn ) mn = sp->index;
4733 if( sp->index>mx ) mx = sp->index;
4736 if( lemp->tokendest ) mn = 0;
4737 if( lemp->vardest ) mx = lemp->nsymbol-1;
4738 fprintf(out,"#define YY_MIN_DSTRCTR %d\n", mn); lineno++;
4739 fprintf(out,"#define YY_MAX_DSTRCTR %d\n", mx); lineno++;
4741 tplt_xfer(lemp->name,in,out,&lineno);
4743 /* Now output the action table and its associates:
4745 ** yy_action[] A single table containing all actions.
4746 ** yy_lookahead[] A table containing the lookahead for each entry in
4747 ** yy_action. Used to detect hash collisions.
4748 ** yy_shift_ofst[] For each state, the offset into yy_action for
4749 ** shifting terminals.
4750 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4751 ** shifting non-terminals after a reduce.
4752 ** yy_default[] Default action for each state.
4755 /* Output the yy_action table */
4756 lemp->nactiontab = n = acttab_action_size(pActtab);
4757 lemp->tablesize += n*szActionType;
4758 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4759 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
4760 for(i=j=0; i<n; i++){
4761 int action = acttab_yyaction(pActtab, i);
4762 if( action<0 ) action = lemp->noAction;
4763 if( j==0 ) fprintf(out," /* %5d */ ", i);
4764 fprintf(out, " %4d,", action);
4765 if( j==9 || i==n-1 ){
4766 fprintf(out, "\n"); lineno++;
4767 j = 0;
4768 }else{
4769 j++;
4772 fprintf(out, "};\n"); lineno++;
4774 /* Output the yy_lookahead table */
4775 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
4776 lemp->tablesize += n*szCodeType;
4777 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
4778 for(i=j=0; i<n; i++){
4779 int la = acttab_yylookahead(pActtab, i);
4780 if( la<0 ) la = lemp->nsymbol;
4781 if( j==0 ) fprintf(out," /* %5d */ ", i);
4782 fprintf(out, " %4d,", la);
4783 if( j==9 ){
4784 fprintf(out, "\n"); lineno++;
4785 j = 0;
4786 }else{
4787 j++;
4790 /* Add extra entries to the end of the yy_lookahead[] table so that
4791 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4792 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4793 nLookAhead = lemp->nterminal + lemp->nactiontab;
4794 while( i<nLookAhead ){
4795 if( j==0 ) fprintf(out," /* %5d */ ", i);
4796 fprintf(out, " %4d,", lemp->nterminal);
4797 if( j==9 ){
4798 fprintf(out, "\n"); lineno++;
4799 j = 0;
4800 }else{
4801 j++;
4803 i++;
4805 if( j>0 ){ fprintf(out, "\n"); lineno++; }
4806 fprintf(out, "};\n"); lineno++;
4808 /* Output the yy_shift_ofst[] table */
4809 n = lemp->nxstate;
4810 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
4811 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4812 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4813 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
4814 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
4815 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4816 lineno++;
4817 lemp->tablesize += n*sz;
4818 for(i=j=0; i<n; i++){
4819 int ofst;
4820 stp = lemp->sorted[i];
4821 ofst = stp->iTknOfst;
4822 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
4823 if( j==0 ) fprintf(out," /* %5d */ ", i);
4824 fprintf(out, " %4d,", ofst);
4825 if( j==9 || i==n-1 ){
4826 fprintf(out, "\n"); lineno++;
4827 j = 0;
4828 }else{
4829 j++;
4832 fprintf(out, "};\n"); lineno++;
4834 /* Output the yy_reduce_ofst[] table */
4835 n = lemp->nxstate;
4836 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
4837 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4838 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4839 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
4840 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
4841 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4842 lemp->tablesize += n*sz;
4843 for(i=j=0; i<n; i++){
4844 int ofst;
4845 stp = lemp->sorted[i];
4846 ofst = stp->iNtOfst;
4847 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
4848 if( j==0 ) fprintf(out," /* %5d */ ", i);
4849 fprintf(out, " %4d,", ofst);
4850 if( j==9 || i==n-1 ){
4851 fprintf(out, "\n"); lineno++;
4852 j = 0;
4853 }else{
4854 j++;
4857 fprintf(out, "};\n"); lineno++;
4859 /* Output the default action table */
4860 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
4861 n = lemp->nxstate;
4862 lemp->tablesize += n*szActionType;
4863 for(i=j=0; i<n; i++){
4864 stp = lemp->sorted[i];
4865 if( j==0 ) fprintf(out," /* %5d */ ", i);
4866 if( stp->iDfltReduce<0 ){
4867 fprintf(out, " %4d,", lemp->errAction);
4868 }else{
4869 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4871 if( j==9 || i==n-1 ){
4872 fprintf(out, "\n"); lineno++;
4873 j = 0;
4874 }else{
4875 j++;
4878 fprintf(out, "};\n"); lineno++;
4879 tplt_xfer(lemp->name,in,out,&lineno);
4881 /* Generate the table of fallback tokens.
4883 if( lemp->has_fallback ){
4884 mx = lemp->nterminal - 1;
4885 /* 2019-08-28: Generate fallback entries for every token to avoid
4886 ** having to do a range check on the index */
4887 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
4888 lemp->tablesize += (mx+1)*szCodeType;
4889 for(i=0; i<=mx; i++){
4890 struct symbol *p = lemp->symbols[i];
4891 if( p->fallback==0 ){
4892 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4893 }else{
4894 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4895 p->name, p->fallback->name);
4897 lineno++;
4900 tplt_xfer(lemp->name, in, out, &lineno);
4902 /* Generate a table containing the symbolic name of every symbol
4904 for(i=0; i<lemp->nsymbol; i++){
4905 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
4907 tplt_xfer(lemp->name,in,out,&lineno);
4909 /* Generate a table containing a text string that describes every
4910 ** rule in the rule set of the grammar. This information is used
4911 ** when tracing REDUCE actions.
4913 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4914 assert( rp->iRule==i );
4915 fprintf(out," /* %3d */ \"", i);
4916 writeRuleText(out, rp);
4917 fprintf(out,"\",\n"); lineno++;
4919 tplt_xfer(lemp->name,in,out,&lineno);
4921 /* Generate code which executes every time a symbol is popped from
4922 ** the stack while processing errors or while destroying the parser.
4923 ** (In other words, generate the %destructor actions)
4925 if( lemp->tokendest ){
4926 int once = 1;
4927 for(i=0; i<lemp->nsymbol; i++){
4928 struct symbol *sp = lemp->symbols[i];
4929 if( sp==0 || sp->type!=TERMINAL ) continue;
4930 if( once ){
4931 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4932 once = 0;
4934 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4936 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4937 if( i<lemp->nsymbol ){
4938 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4939 fprintf(out," break;\n"); lineno++;
4942 if( lemp->vardest ){
4943 struct symbol *dflt_sp = 0;
4944 int once = 1;
4945 for(i=0; i<lemp->nsymbol; i++){
4946 struct symbol *sp = lemp->symbols[i];
4947 if( sp==0 || sp->type==TERMINAL ||
4948 sp->index<=0 || sp->destructor!=0 ) continue;
4949 if( once ){
4950 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
4951 once = 0;
4953 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4954 dflt_sp = sp;
4956 if( dflt_sp!=0 ){
4957 emit_destructor_code(out,dflt_sp,lemp,&lineno);
4959 fprintf(out," break;\n"); lineno++;
4961 for(i=0; i<lemp->nsymbol; i++){
4962 struct symbol *sp = lemp->symbols[i];
4963 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
4964 if( sp->destLineno<0 ) continue; /* Already emitted */
4965 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4967 /* Combine duplicate destructors into a single case */
4968 for(j=i+1; j<lemp->nsymbol; j++){
4969 struct symbol *sp2 = lemp->symbols[j];
4970 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4971 && sp2->dtnum==sp->dtnum
4972 && strcmp(sp->destructor,sp2->destructor)==0 ){
4973 fprintf(out," case %d: /* %s */\n",
4974 sp2->index, sp2->name); lineno++;
4975 sp2->destLineno = -1; /* Avoid emitting this destructor again */
4979 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4980 fprintf(out," break;\n"); lineno++;
4982 tplt_xfer(lemp->name,in,out,&lineno);
4984 /* Generate code which executes whenever the parser stack overflows */
4985 tplt_print(out,lemp,lemp->overflow,&lineno);
4986 tplt_xfer(lemp->name,in,out,&lineno);
4988 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4989 ** yyRuleInfoNRhs[].
4991 ** Note: This code depends on the fact that rules are number
4992 ** sequentially beginning with 0.
4994 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4995 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4996 rule_print(out, rp);
4997 fprintf(out," */\n"); lineno++;
4999 tplt_xfer(lemp->name,in,out,&lineno);
5000 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
5001 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
5002 rule_print(out, rp);
5003 fprintf(out," */\n"); lineno++;
5005 tplt_xfer(lemp->name,in,out,&lineno);
5007 /* Generate code which execution during each REDUCE action */
5008 i = 0;
5009 for(rp=lemp->rule; rp; rp=rp->next){
5010 i += translate_code(lemp, rp);
5012 if( i ){
5013 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
5015 /* First output rules other than the default: rule */
5016 for(rp=lemp->rule; rp; rp=rp->next){
5017 struct rule *rp2; /* Other rules with the same action */
5018 if( rp->codeEmitted ) continue;
5019 if( rp->noCode ){
5020 /* No C code actions, so this will be part of the "default:" rule */
5021 continue;
5023 fprintf(out," case %d: /* ", rp->iRule);
5024 writeRuleText(out, rp);
5025 fprintf(out, " */\n"); lineno++;
5026 for(rp2=rp->next; rp2; rp2=rp2->next){
5027 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
5028 && rp2->codeSuffix==rp->codeSuffix ){
5029 fprintf(out," case %d: /* ", rp2->iRule);
5030 writeRuleText(out, rp2);
5031 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
5032 rp2->codeEmitted = 1;
5035 emit_code(out,rp,lemp,&lineno);
5036 fprintf(out," break;\n"); lineno++;
5037 rp->codeEmitted = 1;
5039 /* Finally, output the default: rule. We choose as the default: all
5040 ** empty actions. */
5041 fprintf(out," default:\n"); lineno++;
5042 for(rp=lemp->rule; rp; rp=rp->next){
5043 if( rp->codeEmitted ) continue;
5044 assert( rp->noCode );
5045 fprintf(out," /* (%d) ", rp->iRule);
5046 writeRuleText(out, rp);
5047 if( rp->neverReduce ){
5048 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
5049 rp->iRule); lineno++;
5050 }else if( rp->doesReduce ){
5051 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
5052 }else{
5053 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
5054 rp->iRule); lineno++;
5057 fprintf(out," break;\n"); lineno++;
5058 tplt_xfer(lemp->name,in,out,&lineno);
5060 /* Generate code which executes if a parse fails */
5061 tplt_print(out,lemp,lemp->failure,&lineno);
5062 tplt_xfer(lemp->name,in,out,&lineno);
5064 /* Generate code which executes when a syntax error occurs */
5065 tplt_print(out,lemp,lemp->error,&lineno);
5066 tplt_xfer(lemp->name,in,out,&lineno);
5068 /* Generate code which executes when the parser accepts its input */
5069 tplt_print(out,lemp,lemp->accept,&lineno);
5070 tplt_xfer(lemp->name,in,out,&lineno);
5072 /* Append any addition code the user desires */
5073 tplt_print(out,lemp,lemp->extracode,&lineno);
5075 acttab_free(pActtab);
5076 fclose(in);
5077 fclose(out);
5078 if( sql ) fclose(sql);
5079 return;
5082 /* Generate a header file for the parser */
5083 void ReportHeader(struct lemon *lemp)
5085 FILE *out, *in;
5086 const char *prefix;
5087 char line[LINESIZE];
5088 char pattern[LINESIZE];
5089 int i;
5091 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
5092 else prefix = "";
5093 in = file_open(lemp,".h","rb");
5094 if( in ){
5095 int nextChar;
5096 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
5097 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
5098 prefix,lemp->symbols[i]->name,i);
5099 if( strcmp(line,pattern) ) break;
5101 nextChar = fgetc(in);
5102 fclose(in);
5103 if( i==lemp->nterminal && nextChar==EOF ){
5104 /* No change in the file. Don't rewrite it. */
5105 return;
5108 out = file_open(lemp,".h","wb");
5109 if( out ){
5110 for(i=1; i<lemp->nterminal; i++){
5111 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
5113 fclose(out);
5115 return;
5118 /* Reduce the size of the action tables, if possible, by making use
5119 ** of defaults.
5121 ** In this version, we take the most frequent REDUCE action and make
5122 ** it the default. Except, there is no default if the wildcard token
5123 ** is a possible look-ahead.
5125 void CompressTables(struct lemon *lemp)
5127 struct state *stp;
5128 struct action *ap, *ap2, *nextap;
5129 struct rule *rp, *rp2, *rbest;
5130 int nbest, n;
5131 int i;
5132 int usesWildcard;
5134 for(i=0; i<lemp->nstate; i++){
5135 stp = lemp->sorted[i];
5136 nbest = 0;
5137 rbest = 0;
5138 usesWildcard = 0;
5140 for(ap=stp->ap; ap; ap=ap->next){
5141 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
5142 usesWildcard = 1;
5144 if( ap->type!=REDUCE ) continue;
5145 rp = ap->x.rp;
5146 if( rp->lhsStart ) continue;
5147 if( rp==rbest ) continue;
5148 n = 1;
5149 for(ap2=ap->next; ap2; ap2=ap2->next){
5150 if( ap2->type!=REDUCE ) continue;
5151 rp2 = ap2->x.rp;
5152 if( rp2==rbest ) continue;
5153 if( rp2==rp ) n++;
5155 if( n>nbest ){
5156 nbest = n;
5157 rbest = rp;
5161 /* Do not make a default if the number of rules to default
5162 ** is not at least 1 or if the wildcard token is a possible
5163 ** lookahead.
5165 if( nbest<1 || usesWildcard ) continue;
5168 /* Combine matching REDUCE actions into a single default */
5169 for(ap=stp->ap; ap; ap=ap->next){
5170 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
5172 assert( ap );
5173 ap->sp = Symbol_new("{default}");
5174 for(ap=ap->next; ap; ap=ap->next){
5175 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
5177 stp->ap = Action_sort(stp->ap);
5179 for(ap=stp->ap; ap; ap=ap->next){
5180 if( ap->type==SHIFT ) break;
5181 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
5183 if( ap==0 ){
5184 stp->autoReduce = 1;
5185 stp->pDfltReduce = rbest;
5189 /* Make a second pass over all states and actions. Convert
5190 ** every action that is a SHIFT to an autoReduce state into
5191 ** a SHIFTREDUCE action.
5193 for(i=0; i<lemp->nstate; i++){
5194 stp = lemp->sorted[i];
5195 for(ap=stp->ap; ap; ap=ap->next){
5196 struct state *pNextState;
5197 if( ap->type!=SHIFT ) continue;
5198 pNextState = ap->x.stp;
5199 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
5200 ap->type = SHIFTREDUCE;
5201 ap->x.rp = pNextState->pDfltReduce;
5206 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
5207 ** (meaning that the SHIFTREDUCE will land back in the state where it
5208 ** started) and if there is no C-code associated with the reduce action,
5209 ** then we can go ahead and convert the action to be the same as the
5210 ** action for the RHS of the rule.
5212 for(i=0; i<lemp->nstate; i++){
5213 stp = lemp->sorted[i];
5214 for(ap=stp->ap; ap; ap=nextap){
5215 nextap = ap->next;
5216 if( ap->type!=SHIFTREDUCE ) continue;
5217 rp = ap->x.rp;
5218 if( rp->noCode==0 ) continue;
5219 if( rp->nrhs!=1 ) continue;
5220 #if 1
5221 /* Only apply this optimization to non-terminals. It would be OK to
5222 ** apply it to terminal symbols too, but that makes the parser tables
5223 ** larger. */
5224 if( ap->sp->index<lemp->nterminal ) continue;
5225 #endif
5226 /* If we reach this point, it means the optimization can be applied */
5227 nextap = ap;
5228 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
5229 assert( ap2!=0 );
5230 ap->spOpt = ap2->sp;
5231 ap->type = ap2->type;
5232 ap->x = ap2->x;
5239 ** Compare two states for sorting purposes. The smaller state is the
5240 ** one with the most non-terminal actions. If they have the same number
5241 ** of non-terminal actions, then the smaller is the one with the most
5242 ** token actions.
5244 static int stateResortCompare(const void *a, const void *b){
5245 const struct state *pA = *(const struct state**)a;
5246 const struct state *pB = *(const struct state**)b;
5247 int n;
5249 n = pB->nNtAct - pA->nNtAct;
5250 if( n==0 ){
5251 n = pB->nTknAct - pA->nTknAct;
5252 if( n==0 ){
5253 n = pB->statenum - pA->statenum;
5256 assert( n!=0 );
5257 return n;
5262 ** Renumber and resort states so that states with fewer choices
5263 ** occur at the end. Except, keep state 0 as the first state.
5265 void ResortStates(struct lemon *lemp)
5267 int i;
5268 struct state *stp;
5269 struct action *ap;
5271 for(i=0; i<lemp->nstate; i++){
5272 stp = lemp->sorted[i];
5273 stp->nTknAct = stp->nNtAct = 0;
5274 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
5275 stp->iTknOfst = NO_OFFSET;
5276 stp->iNtOfst = NO_OFFSET;
5277 for(ap=stp->ap; ap; ap=ap->next){
5278 int iAction = compute_action(lemp,ap);
5279 if( iAction>=0 ){
5280 if( ap->sp->index<lemp->nterminal ){
5281 stp->nTknAct++;
5282 }else if( ap->sp->index<lemp->nsymbol ){
5283 stp->nNtAct++;
5284 }else{
5285 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
5286 stp->iDfltReduce = iAction;
5291 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
5292 stateResortCompare);
5293 for(i=0; i<lemp->nstate; i++){
5294 lemp->sorted[i]->statenum = i;
5296 lemp->nxstate = lemp->nstate;
5297 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
5298 lemp->nxstate--;
5303 /***************** From the file "set.c" ************************************/
5305 ** Set manipulation routines for the LEMON parser generator.
5308 static int size = 0;
5310 /* Set the set size */
5311 void SetSize(int n)
5313 size = n+1;
5316 /* Allocate a new set */
5317 char *SetNew(void){
5318 char *s;
5319 s = (char*)lemon_calloc( size, 1);
5320 if( s==0 ){
5321 memory_error();
5323 return s;
5326 /* Deallocate a set */
5327 void SetFree(char *s)
5329 lemon_free(s);
5332 /* Add a new element to the set. Return TRUE if the element was added
5333 ** and FALSE if it was already there. */
5334 int SetAdd(char *s, int e)
5336 int rv;
5337 assert( e>=0 && e<size );
5338 rv = s[e];
5339 s[e] = 1;
5340 return !rv;
5343 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
5344 int SetUnion(char *s1, char *s2)
5346 int i, progress;
5347 progress = 0;
5348 for(i=0; i<size; i++){
5349 if( s2[i]==0 ) continue;
5350 if( s1[i]==0 ){
5351 progress = 1;
5352 s1[i] = 1;
5355 return progress;
5357 /********************** From the file "table.c" ****************************/
5359 ** All code in this file has been automatically generated
5360 ** from a specification in the file
5361 ** "table.q"
5362 ** by the associative array code building program "aagen".
5363 ** Do not edit this file! Instead, edit the specification
5364 ** file, then rerun aagen.
5367 ** Code for processing tables in the LEMON parser generator.
5370 PRIVATE unsigned strhash(const char *x)
5372 unsigned h = 0;
5373 while( *x ) h = h*13 + *(x++);
5374 return h;
5377 /* Works like strdup, sort of. Save a string in malloced memory, but
5378 ** keep strings in a table so that the same string is not in more
5379 ** than one place.
5381 const char *Strsafe(const char *y)
5383 const char *z;
5384 char *cpy;
5386 if( y==0 ) return 0;
5387 z = Strsafe_find(y);
5388 if( z==0 && (cpy=(char *)lemon_malloc( lemonStrlen(y)+1 ))!=0 ){
5389 lemon_strcpy(cpy,y);
5390 z = cpy;
5391 Strsafe_insert(z);
5393 MemoryCheck(z);
5394 return z;
5397 /* There is one instance of the following structure for each
5398 ** associative array of type "x1".
5400 struct s_x1 {
5401 int size; /* The number of available slots. */
5402 /* Must be a power of 2 greater than or */
5403 /* equal to 1 */
5404 int count; /* Number of currently slots filled */
5405 struct s_x1node *tbl; /* The data stored here */
5406 struct s_x1node **ht; /* Hash table for lookups */
5409 /* There is one instance of this structure for every data element
5410 ** in an associative array of type "x1".
5412 typedef struct s_x1node {
5413 const char *data; /* The data */
5414 struct s_x1node *next; /* Next entry with the same hash */
5415 struct s_x1node **from; /* Previous link */
5416 } x1node;
5418 /* There is only one instance of the array, which is the following */
5419 static struct s_x1 *x1a;
5421 /* Allocate a new associative array */
5422 void Strsafe_init(void){
5423 if( x1a ) return;
5424 x1a = (struct s_x1*)lemon_malloc( sizeof(struct s_x1) );
5425 if( x1a ){
5426 x1a->size = 1024;
5427 x1a->count = 0;
5428 x1a->tbl = (x1node*)lemon_calloc(1024, sizeof(x1node) + sizeof(x1node*));
5429 if( x1a->tbl==0 ){
5430 lemon_free(x1a);
5431 x1a = 0;
5432 }else{
5433 int i;
5434 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5435 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5439 /* Insert a new record into the array. Return TRUE if successful.
5440 ** Prior data with the same key is NOT overwritten */
5441 int Strsafe_insert(const char *data)
5443 x1node *np;
5444 unsigned h;
5445 unsigned ph;
5447 if( x1a==0 ) return 0;
5448 ph = strhash(data);
5449 h = ph & (x1a->size-1);
5450 np = x1a->ht[h];
5451 while( np ){
5452 if( strcmp(np->data,data)==0 ){
5453 /* An existing entry with the same key is found. */
5454 /* Fail because overwrite is not allows. */
5455 return 0;
5457 np = np->next;
5459 if( x1a->count>=x1a->size ){
5460 /* Need to make the hash table bigger */
5461 int i,arrSize;
5462 struct s_x1 array;
5463 array.size = arrSize = x1a->size*2;
5464 array.count = x1a->count;
5465 array.tbl = (x1node*)lemon_calloc(arrSize, sizeof(x1node)+sizeof(x1node*));
5466 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5467 array.ht = (x1node**)&(array.tbl[arrSize]);
5468 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5469 for(i=0; i<x1a->count; i++){
5470 x1node *oldnp, *newnp;
5471 oldnp = &(x1a->tbl[i]);
5472 h = strhash(oldnp->data) & (arrSize-1);
5473 newnp = &(array.tbl[i]);
5474 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5475 newnp->next = array.ht[h];
5476 newnp->data = oldnp->data;
5477 newnp->from = &(array.ht[h]);
5478 array.ht[h] = newnp;
5480 /* lemon_free(x1a->tbl); // This program was originally for 16-bit machines.
5481 ** Don't worry about freeing memory on modern platforms. */
5482 *x1a = array;
5484 /* Insert the new data */
5485 h = ph & (x1a->size-1);
5486 np = &(x1a->tbl[x1a->count++]);
5487 np->data = data;
5488 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5489 np->next = x1a->ht[h];
5490 x1a->ht[h] = np;
5491 np->from = &(x1a->ht[h]);
5492 return 1;
5495 /* Return a pointer to data assigned to the given key. Return NULL
5496 ** if no such key. */
5497 const char *Strsafe_find(const char *key)
5499 unsigned h;
5500 x1node *np;
5502 if( x1a==0 ) return 0;
5503 h = strhash(key) & (x1a->size-1);
5504 np = x1a->ht[h];
5505 while( np ){
5506 if( strcmp(np->data,key)==0 ) break;
5507 np = np->next;
5509 return np ? np->data : 0;
5512 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5513 ** Create a new symbol if this is the first time "x" has been seen.
5515 struct symbol *Symbol_new(const char *x)
5517 struct symbol *sp;
5519 sp = Symbol_find(x);
5520 if( sp==0 ){
5521 sp = (struct symbol *)lemon_calloc(1, sizeof(struct symbol) );
5522 MemoryCheck(sp);
5523 sp->name = Strsafe(x);
5524 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
5525 sp->rule = 0;
5526 sp->fallback = 0;
5527 sp->prec = -1;
5528 sp->assoc = UNK;
5529 sp->firstset = 0;
5530 sp->lambda = LEMON_FALSE;
5531 sp->destructor = 0;
5532 sp->destLineno = 0;
5533 sp->datatype = 0;
5534 sp->useCnt = 0;
5535 Symbol_insert(sp,sp->name);
5537 sp->useCnt++;
5538 return sp;
5541 /* Compare two symbols for sorting purposes. Return negative,
5542 ** zero, or positive if a is less then, equal to, or greater
5543 ** than b.
5545 ** Symbols that begin with upper case letters (terminals or tokens)
5546 ** must sort before symbols that begin with lower case letters
5547 ** (non-terminals). And MULTITERMINAL symbols (created using the
5548 ** %token_class directive) must sort at the very end. Other than
5549 ** that, the order does not matter.
5551 ** We find experimentally that leaving the symbols in their original
5552 ** order (the order they appeared in the grammar file) gives the
5553 ** smallest parser tables in SQLite.
5555 int Symbolcmpp(const void *_a, const void *_b)
5557 const struct symbol *a = *(const struct symbol **) _a;
5558 const struct symbol *b = *(const struct symbol **) _b;
5559 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5560 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5561 return i1==i2 ? a->index - b->index : i1 - i2;
5564 /* There is one instance of the following structure for each
5565 ** associative array of type "x2".
5567 struct s_x2 {
5568 int size; /* The number of available slots. */
5569 /* Must be a power of 2 greater than or */
5570 /* equal to 1 */
5571 int count; /* Number of currently slots filled */
5572 struct s_x2node *tbl; /* The data stored here */
5573 struct s_x2node **ht; /* Hash table for lookups */
5576 /* There is one instance of this structure for every data element
5577 ** in an associative array of type "x2".
5579 typedef struct s_x2node {
5580 struct symbol *data; /* The data */
5581 const char *key; /* The key */
5582 struct s_x2node *next; /* Next entry with the same hash */
5583 struct s_x2node **from; /* Previous link */
5584 } x2node;
5586 /* There is only one instance of the array, which is the following */
5587 static struct s_x2 *x2a;
5589 /* Allocate a new associative array */
5590 void Symbol_init(void){
5591 if( x2a ) return;
5592 x2a = (struct s_x2*)lemon_malloc( sizeof(struct s_x2) );
5593 if( x2a ){
5594 x2a->size = 128;
5595 x2a->count = 0;
5596 x2a->tbl = (x2node*)lemon_calloc(128, sizeof(x2node) + sizeof(x2node*));
5597 if( x2a->tbl==0 ){
5598 lemon_free(x2a);
5599 x2a = 0;
5600 }else{
5601 int i;
5602 x2a->ht = (x2node**)&(x2a->tbl[128]);
5603 for(i=0; i<128; i++) x2a->ht[i] = 0;
5607 /* Insert a new record into the array. Return TRUE if successful.
5608 ** Prior data with the same key is NOT overwritten */
5609 int Symbol_insert(struct symbol *data, const char *key)
5611 x2node *np;
5612 unsigned h;
5613 unsigned ph;
5615 if( x2a==0 ) return 0;
5616 ph = strhash(key);
5617 h = ph & (x2a->size-1);
5618 np = x2a->ht[h];
5619 while( np ){
5620 if( strcmp(np->key,key)==0 ){
5621 /* An existing entry with the same key is found. */
5622 /* Fail because overwrite is not allows. */
5623 return 0;
5625 np = np->next;
5627 if( x2a->count>=x2a->size ){
5628 /* Need to make the hash table bigger */
5629 int i,arrSize;
5630 struct s_x2 array;
5631 array.size = arrSize = x2a->size*2;
5632 array.count = x2a->count;
5633 array.tbl = (x2node*)lemon_calloc(arrSize, sizeof(x2node)+sizeof(x2node*));
5634 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5635 array.ht = (x2node**)&(array.tbl[arrSize]);
5636 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5637 for(i=0; i<x2a->count; i++){
5638 x2node *oldnp, *newnp;
5639 oldnp = &(x2a->tbl[i]);
5640 h = strhash(oldnp->key) & (arrSize-1);
5641 newnp = &(array.tbl[i]);
5642 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5643 newnp->next = array.ht[h];
5644 newnp->key = oldnp->key;
5645 newnp->data = oldnp->data;
5646 newnp->from = &(array.ht[h]);
5647 array.ht[h] = newnp;
5649 /* lemon_free(x2a->tbl); // This program was originally written for 16-bit
5650 ** machines. Don't worry about freeing this trivial amount of memory
5651 ** on modern platforms. Just leak it. */
5652 *x2a = array;
5654 /* Insert the new data */
5655 h = ph & (x2a->size-1);
5656 np = &(x2a->tbl[x2a->count++]);
5657 np->key = key;
5658 np->data = data;
5659 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5660 np->next = x2a->ht[h];
5661 x2a->ht[h] = np;
5662 np->from = &(x2a->ht[h]);
5663 return 1;
5666 /* Return a pointer to data assigned to the given key. Return NULL
5667 ** if no such key. */
5668 struct symbol *Symbol_find(const char *key)
5670 unsigned h;
5671 x2node *np;
5673 if( x2a==0 ) return 0;
5674 h = strhash(key) & (x2a->size-1);
5675 np = x2a->ht[h];
5676 while( np ){
5677 if( strcmp(np->key,key)==0 ) break;
5678 np = np->next;
5680 return np ? np->data : 0;
5683 /* Return the n-th data. Return NULL if n is out of range. */
5684 struct symbol *Symbol_Nth(int n)
5686 struct symbol *data;
5687 if( x2a && n>0 && n<=x2a->count ){
5688 data = x2a->tbl[n-1].data;
5689 }else{
5690 data = 0;
5692 return data;
5695 /* Return the size of the array */
5696 int Symbol_count()
5698 return x2a ? x2a->count : 0;
5701 /* Return an array of pointers to all data in the table.
5702 ** The array is obtained from malloc. Return NULL if memory allocation
5703 ** problems, or if the array is empty. */
5704 struct symbol **Symbol_arrayof()
5706 struct symbol **array;
5707 int i,arrSize;
5708 if( x2a==0 ) return 0;
5709 arrSize = x2a->count;
5710 array = (struct symbol **)lemon_calloc(arrSize, sizeof(struct symbol *));
5711 if( array ){
5712 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
5714 return array;
5717 /* Compare two configurations */
5718 int Configcmp(const char *_a,const char *_b)
5720 const struct config *a = (struct config *) _a;
5721 const struct config *b = (struct config *) _b;
5722 int x;
5723 x = a->rp->index - b->rp->index;
5724 if( x==0 ) x = a->dot - b->dot;
5725 return x;
5728 /* Compare two states */
5729 PRIVATE int statecmp(struct config *a, struct config *b)
5731 int rc;
5732 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5733 rc = a->rp->index - b->rp->index;
5734 if( rc==0 ) rc = a->dot - b->dot;
5736 if( rc==0 ){
5737 if( a ) rc = 1;
5738 if( b ) rc = -1;
5740 return rc;
5743 /* Hash a state */
5744 PRIVATE unsigned statehash(struct config *a)
5746 unsigned h=0;
5747 while( a ){
5748 h = h*571 + a->rp->index*37 + a->dot;
5749 a = a->bp;
5751 return h;
5754 /* Allocate a new state structure */
5755 struct state *State_new()
5757 struct state *newstate;
5758 newstate = (struct state *)lemon_calloc(1, sizeof(struct state) );
5759 MemoryCheck(newstate);
5760 return newstate;
5763 /* There is one instance of the following structure for each
5764 ** associative array of type "x3".
5766 struct s_x3 {
5767 int size; /* The number of available slots. */
5768 /* Must be a power of 2 greater than or */
5769 /* equal to 1 */
5770 int count; /* Number of currently slots filled */
5771 struct s_x3node *tbl; /* The data stored here */
5772 struct s_x3node **ht; /* Hash table for lookups */
5775 /* There is one instance of this structure for every data element
5776 ** in an associative array of type "x3".
5778 typedef struct s_x3node {
5779 struct state *data; /* The data */
5780 struct config *key; /* The key */
5781 struct s_x3node *next; /* Next entry with the same hash */
5782 struct s_x3node **from; /* Previous link */
5783 } x3node;
5785 /* There is only one instance of the array, which is the following */
5786 static struct s_x3 *x3a;
5788 /* Allocate a new associative array */
5789 void State_init(void){
5790 if( x3a ) return;
5791 x3a = (struct s_x3*)lemon_malloc( sizeof(struct s_x3) );
5792 if( x3a ){
5793 x3a->size = 128;
5794 x3a->count = 0;
5795 x3a->tbl = (x3node*)lemon_calloc(128, sizeof(x3node) + sizeof(x3node*));
5796 if( x3a->tbl==0 ){
5797 lemon_free(x3a);
5798 x3a = 0;
5799 }else{
5800 int i;
5801 x3a->ht = (x3node**)&(x3a->tbl[128]);
5802 for(i=0; i<128; i++) x3a->ht[i] = 0;
5806 /* Insert a new record into the array. Return TRUE if successful.
5807 ** Prior data with the same key is NOT overwritten */
5808 int State_insert(struct state *data, struct config *key)
5810 x3node *np;
5811 unsigned h;
5812 unsigned ph;
5814 if( x3a==0 ) return 0;
5815 ph = statehash(key);
5816 h = ph & (x3a->size-1);
5817 np = x3a->ht[h];
5818 while( np ){
5819 if( statecmp(np->key,key)==0 ){
5820 /* An existing entry with the same key is found. */
5821 /* Fail because overwrite is not allows. */
5822 return 0;
5824 np = np->next;
5826 if( x3a->count>=x3a->size ){
5827 /* Need to make the hash table bigger */
5828 int i,arrSize;
5829 struct s_x3 array;
5830 array.size = arrSize = x3a->size*2;
5831 array.count = x3a->count;
5832 array.tbl = (x3node*)lemon_calloc(arrSize, sizeof(x3node)+sizeof(x3node*));
5833 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5834 array.ht = (x3node**)&(array.tbl[arrSize]);
5835 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5836 for(i=0; i<x3a->count; i++){
5837 x3node *oldnp, *newnp;
5838 oldnp = &(x3a->tbl[i]);
5839 h = statehash(oldnp->key) & (arrSize-1);
5840 newnp = &(array.tbl[i]);
5841 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5842 newnp->next = array.ht[h];
5843 newnp->key = oldnp->key;
5844 newnp->data = oldnp->data;
5845 newnp->from = &(array.ht[h]);
5846 array.ht[h] = newnp;
5848 lemon_free(x3a->tbl);
5849 *x3a = array;
5851 /* Insert the new data */
5852 h = ph & (x3a->size-1);
5853 np = &(x3a->tbl[x3a->count++]);
5854 np->key = key;
5855 np->data = data;
5856 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5857 np->next = x3a->ht[h];
5858 x3a->ht[h] = np;
5859 np->from = &(x3a->ht[h]);
5860 return 1;
5863 /* Return a pointer to data assigned to the given key. Return NULL
5864 ** if no such key. */
5865 struct state *State_find(struct config *key)
5867 unsigned h;
5868 x3node *np;
5870 if( x3a==0 ) return 0;
5871 h = statehash(key) & (x3a->size-1);
5872 np = x3a->ht[h];
5873 while( np ){
5874 if( statecmp(np->key,key)==0 ) break;
5875 np = np->next;
5877 return np ? np->data : 0;
5880 /* Return an array of pointers to all data in the table.
5881 ** The array is obtained from malloc. Return NULL if memory allocation
5882 ** problems, or if the array is empty. */
5883 struct state **State_arrayof(void)
5885 struct state **array;
5886 int i,arrSize;
5887 if( x3a==0 ) return 0;
5888 arrSize = x3a->count;
5889 array = (struct state **)lemon_calloc(arrSize, sizeof(struct state *));
5890 if( array ){
5891 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
5893 return array;
5896 /* Hash a configuration */
5897 PRIVATE unsigned confighash(struct config *a)
5899 unsigned h=0;
5900 h = h*571 + a->rp->index*37 + a->dot;
5901 return h;
5904 /* There is one instance of the following structure for each
5905 ** associative array of type "x4".
5907 struct s_x4 {
5908 int size; /* The number of available slots. */
5909 /* Must be a power of 2 greater than or */
5910 /* equal to 1 */
5911 int count; /* Number of currently slots filled */
5912 struct s_x4node *tbl; /* The data stored here */
5913 struct s_x4node **ht; /* Hash table for lookups */
5916 /* There is one instance of this structure for every data element
5917 ** in an associative array of type "x4".
5919 typedef struct s_x4node {
5920 struct config *data; /* The data */
5921 struct s_x4node *next; /* Next entry with the same hash */
5922 struct s_x4node **from; /* Previous link */
5923 } x4node;
5925 /* There is only one instance of the array, which is the following */
5926 static struct s_x4 *x4a;
5928 /* Allocate a new associative array */
5929 void Configtable_init(void){
5930 if( x4a ) return;
5931 x4a = (struct s_x4*)lemon_malloc( sizeof(struct s_x4) );
5932 if( x4a ){
5933 x4a->size = 64;
5934 x4a->count = 0;
5935 x4a->tbl = (x4node*)lemon_calloc(64, sizeof(x4node) + sizeof(x4node*));
5936 if( x4a->tbl==0 ){
5937 lemon_free(x4a);
5938 x4a = 0;
5939 }else{
5940 int i;
5941 x4a->ht = (x4node**)&(x4a->tbl[64]);
5942 for(i=0; i<64; i++) x4a->ht[i] = 0;
5946 /* Insert a new record into the array. Return TRUE if successful.
5947 ** Prior data with the same key is NOT overwritten */
5948 int Configtable_insert(struct config *data)
5950 x4node *np;
5951 unsigned h;
5952 unsigned ph;
5954 if( x4a==0 ) return 0;
5955 ph = confighash(data);
5956 h = ph & (x4a->size-1);
5957 np = x4a->ht[h];
5958 while( np ){
5959 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
5960 /* An existing entry with the same key is found. */
5961 /* Fail because overwrite is not allows. */
5962 return 0;
5964 np = np->next;
5966 if( x4a->count>=x4a->size ){
5967 /* Need to make the hash table bigger */
5968 int i,arrSize;
5969 struct s_x4 array;
5970 array.size = arrSize = x4a->size*2;
5971 array.count = x4a->count;
5972 array.tbl = (x4node*)lemon_calloc(arrSize,
5973 sizeof(x4node) + sizeof(x4node*));
5974 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5975 array.ht = (x4node**)&(array.tbl[arrSize]);
5976 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5977 for(i=0; i<x4a->count; i++){
5978 x4node *oldnp, *newnp;
5979 oldnp = &(x4a->tbl[i]);
5980 h = confighash(oldnp->data) & (arrSize-1);
5981 newnp = &(array.tbl[i]);
5982 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5983 newnp->next = array.ht[h];
5984 newnp->data = oldnp->data;
5985 newnp->from = &(array.ht[h]);
5986 array.ht[h] = newnp;
5988 *x4a = array;
5990 /* Insert the new data */
5991 h = ph & (x4a->size-1);
5992 np = &(x4a->tbl[x4a->count++]);
5993 np->data = data;
5994 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5995 np->next = x4a->ht[h];
5996 x4a->ht[h] = np;
5997 np->from = &(x4a->ht[h]);
5998 return 1;
6001 /* Return a pointer to data assigned to the given key. Return NULL
6002 ** if no such key. */
6003 struct config *Configtable_find(struct config *key)
6005 int h;
6006 x4node *np;
6008 if( x4a==0 ) return 0;
6009 h = confighash(key) & (x4a->size-1);
6010 np = x4a->ht[h];
6011 while( np ){
6012 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
6013 np = np->next;
6015 return np ? np->data : 0;
6018 /* Remove all data from the table. Pass each data to the function "f"
6019 ** as it is removed. ("f" may be null to avoid this step.) */
6020 void Configtable_clear(int(*f)(struct config *))
6022 int i;
6023 if( x4a==0 || x4a->count==0 ) return;
6024 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
6025 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
6026 x4a->count = 0;
6027 return;