Snapshot of upstream SQLite 3.45.3
[sqlcipher.git] / tool / lemon.c
blob7804837a0629a211bb4691fa7b2f6c6ad5af84f3
1 /*
2 ** This file contains all sources (including headers) to the LEMON
3 ** LALR(1) parser generator. The sources have been combined into a
4 ** single file to make it easy to include LEMON in the source tree
5 ** and Makefile of another program.
6 **
7 ** The author of this program disclaims copyright.
8 */
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <stdlib.h>
14 #include <assert.h>
16 #define ISSPACE(X) isspace((unsigned char)(X))
17 #define ISDIGIT(X) isdigit((unsigned char)(X))
18 #define ISALNUM(X) isalnum((unsigned char)(X))
19 #define ISALPHA(X) isalpha((unsigned char)(X))
20 #define ISUPPER(X) isupper((unsigned char)(X))
21 #define ISLOWER(X) islower((unsigned char)(X))
24 #ifndef __WIN32__
25 # if defined(_WIN32) || defined(WIN32)
26 # define __WIN32__
27 # endif
28 #endif
30 #ifdef __WIN32__
31 #ifdef __cplusplus
32 extern "C" {
33 #endif
34 extern int access(const char *path, int mode);
35 #ifdef __cplusplus
37 #endif
38 #else
39 #include <unistd.h>
40 #endif
42 /* #define PRIVATE static */
43 #define PRIVATE
45 #ifdef TEST
46 #define MAXRHS 5 /* Set low to exercise exception code */
47 #else
48 #define MAXRHS 1000
49 #endif
51 extern void memory_error();
52 static int showPrecedenceConflict = 0;
53 static char *msort(char*,char**,int(*)(const char*,const char*));
56 ** Compilers are getting increasingly pedantic about type conversions
57 ** as C evolves ever closer to Ada.... To work around the latest problems
58 ** we have to define the following variant of strlen().
60 #define lemonStrlen(X) ((int)strlen(X))
63 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
64 ** saying they are unsafe. So we define our own versions of those routines too.
66 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
67 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
68 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
69 ** buffer, making sure the buffer is always zero-terminated.
71 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
72 ** a few simply conversions:
74 ** %d
75 ** %s
76 ** %.*s
79 static void lemon_addtext(
80 char *zBuf, /* The buffer to which text is added */
81 int *pnUsed, /* Slots of the buffer used so far */
82 const char *zIn, /* Text to add */
83 int nIn, /* Bytes of text to add. -1 to use strlen() */
84 int iWidth /* Field width. Negative to left justify */
86 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
87 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
88 if( nIn==0 ) return;
89 memcpy(&zBuf[*pnUsed], zIn, nIn);
90 *pnUsed += nIn;
91 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
92 zBuf[*pnUsed] = 0;
94 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
95 int i, j, k, c;
96 int nUsed = 0;
97 const char *z;
98 char zTemp[50];
99 str[0] = 0;
100 for(i=j=0; (c = zFormat[i])!=0; i++){
101 if( c=='%' ){
102 int iWidth = 0;
103 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
104 c = zFormat[++i];
105 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
106 if( c=='-' ) i++;
107 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
108 if( c=='-' ) iWidth = -iWidth;
109 c = zFormat[i];
111 if( c=='d' ){
112 int v = va_arg(ap, int);
113 if( v<0 ){
114 lemon_addtext(str, &nUsed, "-", 1, iWidth);
115 v = -v;
116 }else if( v==0 ){
117 lemon_addtext(str, &nUsed, "0", 1, iWidth);
119 k = 0;
120 while( v>0 ){
121 k++;
122 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
123 v /= 10;
125 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
126 }else if( c=='s' ){
127 z = va_arg(ap, const char*);
128 lemon_addtext(str, &nUsed, z, -1, iWidth);
129 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
130 i += 2;
131 k = va_arg(ap, int);
132 z = va_arg(ap, const char*);
133 lemon_addtext(str, &nUsed, z, k, iWidth);
134 }else if( c=='%' ){
135 lemon_addtext(str, &nUsed, "%", 1, 0);
136 }else{
137 fprintf(stderr, "illegal format\n");
138 exit(1);
140 j = i+1;
143 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
144 return nUsed;
146 static int lemon_sprintf(char *str, const char *format, ...){
147 va_list ap;
148 int rc;
149 va_start(ap, format);
150 rc = lemon_vsprintf(str, format, ap);
151 va_end(ap);
152 return rc;
154 static void lemon_strcpy(char *dest, const char *src){
155 while( (*(dest++) = *(src++))!=0 ){}
157 static void lemon_strcat(char *dest, const char *src){
158 while( *dest ) dest++;
159 lemon_strcpy(dest, src);
163 /* a few forward declarations... */
164 struct rule;
165 struct lemon;
166 struct action;
168 static struct action *Action_new(void);
169 static struct action *Action_sort(struct action *);
171 /********** From the file "build.h" ************************************/
172 void FindRulePrecedences(struct lemon*);
173 void FindFirstSets(struct lemon*);
174 void FindStates(struct lemon*);
175 void FindLinks(struct lemon*);
176 void FindFollowSets(struct lemon*);
177 void FindActions(struct lemon*);
179 /********* From the file "configlist.h" *********************************/
180 void Configlist_init(void);
181 struct config *Configlist_add(struct rule *, int);
182 struct config *Configlist_addbasis(struct rule *, int);
183 void Configlist_closure(struct lemon *);
184 void Configlist_sort(void);
185 void Configlist_sortbasis(void);
186 struct config *Configlist_return(void);
187 struct config *Configlist_basis(void);
188 void Configlist_eat(struct config *);
189 void Configlist_reset(void);
191 /********* From the file "error.h" ***************************************/
192 void ErrorMsg(const char *, int,const char *, ...);
194 /****** From the file "option.h" ******************************************/
195 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
196 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
197 struct s_options {
198 enum option_type type;
199 const char *label;
200 char *arg;
201 const char *message;
203 int OptInit(char**,struct s_options*,FILE*);
204 int OptNArgs(void);
205 char *OptArg(int);
206 void OptErr(int);
207 void OptPrint(void);
209 /******** From the file "parse.h" *****************************************/
210 void Parse(struct lemon *lemp);
212 /********* From the file "plink.h" ***************************************/
213 struct plink *Plink_new(void);
214 void Plink_add(struct plink **, struct config *);
215 void Plink_copy(struct plink **, struct plink *);
216 void Plink_delete(struct plink *);
218 /********** From the file "report.h" *************************************/
219 void Reprint(struct lemon *);
220 void ReportOutput(struct lemon *);
221 void ReportTable(struct lemon *, int, int);
222 void ReportHeader(struct lemon *);
223 void CompressTables(struct lemon *);
224 void ResortStates(struct lemon *);
226 /********** From the file "set.h" ****************************************/
227 void SetSize(int); /* All sets will be of size N */
228 char *SetNew(void); /* A new set for element 0..N */
229 void SetFree(char*); /* Deallocate a set */
230 int SetAdd(char*,int); /* Add element to a set */
231 int SetUnion(char *,char *); /* A <- A U B, thru element N */
232 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
234 /********** From the file "struct.h" *************************************/
236 ** Principal data structures for the LEMON parser generator.
239 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
241 /* Symbols (terminals and nonterminals) of the grammar are stored
242 ** in the following: */
243 enum symbol_type {
244 TERMINAL,
245 NONTERMINAL,
246 MULTITERMINAL
248 enum e_assoc {
249 LEFT,
250 RIGHT,
251 NONE,
254 struct symbol {
255 const char *name; /* Name of the symbol */
256 int index; /* Index number for this symbol */
257 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
258 struct rule *rule; /* Linked list of rules of this (if an NT) */
259 struct symbol *fallback; /* fallback token in case this token doesn't parse */
260 int prec; /* Precedence if defined (-1 otherwise) */
261 enum e_assoc assoc; /* Associativity if precedence is defined */
262 char *firstset; /* First-set for all rules of this symbol */
263 Boolean lambda; /* True if NT and can generate an empty string */
264 int useCnt; /* Number of times used */
265 char *destructor; /* Code which executes whenever this symbol is
266 ** popped from the stack during error processing */
267 int destLineno; /* Line number for start of destructor. Set to
268 ** -1 for duplicate destructors. */
269 char *datatype; /* The data type of information held by this
270 ** object. Only used if type==NONTERMINAL */
271 int dtnum; /* The data type number. In the parser, the value
272 ** stack is a union. The .yy%d element of this
273 ** union is the correct data type for this object */
274 int bContent; /* True if this symbol ever carries content - if
275 ** it is ever more than just syntax */
276 /* The following fields are used by MULTITERMINALs only */
277 int nsubsym; /* Number of constituent symbols in the MULTI */
278 struct symbol **subsym; /* Array of constituent symbols */
281 /* Each production rule in the grammar is stored in the following
282 ** structure. */
283 struct rule {
284 struct symbol *lhs; /* Left-hand side of the rule */
285 const char *lhsalias; /* Alias for the LHS (NULL if none) */
286 int lhsStart; /* True if left-hand side is the start symbol */
287 int ruleline; /* Line number for the rule */
288 int nrhs; /* Number of RHS symbols */
289 struct symbol **rhs; /* The RHS symbols */
290 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
291 int line; /* Line number at which code begins */
292 const char *code; /* The code executed when this rule is reduced */
293 const char *codePrefix; /* Setup code before code[] above */
294 const char *codeSuffix; /* Breakdown code after code[] above */
295 struct symbol *precsym; /* Precedence symbol for this rule */
296 int index; /* An index number for this rule */
297 int iRule; /* Rule number as used in the generated tables */
298 Boolean noCode; /* True if this rule has no associated C code */
299 Boolean codeEmitted; /* True if the code has been emitted already */
300 Boolean canReduce; /* True if this rule is ever reduced */
301 Boolean doesReduce; /* Reduce actions occur after optimization */
302 Boolean neverReduce; /* Reduce is theoretically possible, but prevented
303 ** by actions or other outside implementation */
304 struct rule *nextlhs; /* Next rule with the same LHS */
305 struct rule *next; /* Next rule in the global list */
308 /* A configuration is a production rule of the grammar together with
309 ** a mark (dot) showing how much of that rule has been processed so far.
310 ** Configurations also contain a follow-set which is a list of terminal
311 ** symbols which are allowed to immediately follow the end of the rule.
312 ** Every configuration is recorded as an instance of the following: */
313 enum cfgstatus {
314 COMPLETE,
315 INCOMPLETE
317 struct config {
318 struct rule *rp; /* The rule upon which the configuration is based */
319 int dot; /* The parse point */
320 char *fws; /* Follow-set for this configuration only */
321 struct plink *fplp; /* Follow-set forward propagation links */
322 struct plink *bplp; /* Follow-set backwards propagation links */
323 struct state *stp; /* Pointer to state which contains this */
324 enum cfgstatus status; /* used during followset and shift computations */
325 struct config *next; /* Next configuration in the state */
326 struct config *bp; /* The next basis configuration */
329 enum e_action {
330 SHIFT,
331 ACCEPT,
332 REDUCE,
333 ERROR,
334 SSCONFLICT, /* A shift/shift conflict */
335 SRCONFLICT, /* Was a reduce, but part of a conflict */
336 RRCONFLICT, /* Was a reduce, but part of a conflict */
337 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
338 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
339 NOT_USED, /* Deleted by compression */
340 SHIFTREDUCE /* Shift first, then reduce */
343 /* Every shift or reduce operation is stored as one of the following */
344 struct action {
345 struct symbol *sp; /* The look-ahead symbol */
346 enum e_action type;
347 union {
348 struct state *stp; /* The new state, if a shift */
349 struct rule *rp; /* The rule, if a reduce */
350 } x;
351 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
352 struct action *next; /* Next action for this state */
353 struct action *collide; /* Next action with the same hash */
356 /* Each state of the generated parser's finite state machine
357 ** is encoded as an instance of the following structure. */
358 struct state {
359 struct config *bp; /* The basis configurations for this state */
360 struct config *cfp; /* All configurations in this set */
361 int statenum; /* Sequential number for this state */
362 struct action *ap; /* List of actions for this state */
363 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
364 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
365 int iDfltReduce; /* Default action is to REDUCE by this rule */
366 struct rule *pDfltReduce;/* The default REDUCE rule. */
367 int autoReduce; /* True if this is an auto-reduce state */
369 #define NO_OFFSET (-2147483647)
371 /* A followset propagation link indicates that the contents of one
372 ** configuration followset should be propagated to another whenever
373 ** the first changes. */
374 struct plink {
375 struct config *cfp; /* The configuration to which linked */
376 struct plink *next; /* The next propagate link */
379 /* The state vector for the entire parser generator is recorded as
380 ** follows. (LEMON uses no global variables and makes little use of
381 ** static variables. Fields in the following structure can be thought
382 ** of as begin global variables in the program.) */
383 struct lemon {
384 struct state **sorted; /* Table of states sorted by state number */
385 struct rule *rule; /* List of all rules */
386 struct rule *startRule; /* First rule */
387 int nstate; /* Number of states */
388 int nxstate; /* nstate with tail degenerate states removed */
389 int nrule; /* Number of rules */
390 int nruleWithAction; /* Number of rules with actions */
391 int nsymbol; /* Number of terminal and nonterminal symbols */
392 int nterminal; /* Number of terminal symbols */
393 int minShiftReduce; /* Minimum shift-reduce action value */
394 int errAction; /* Error action value */
395 int accAction; /* Accept action value */
396 int noAction; /* No-op action value */
397 int minReduce; /* Minimum reduce action */
398 int maxAction; /* Maximum action value of any kind */
399 struct symbol **symbols; /* Sorted array of pointers to symbols */
400 int errorcnt; /* Number of errors */
401 struct symbol *errsym; /* The error symbol */
402 struct symbol *wildcard; /* Token that matches anything */
403 char *name; /* Name of the generated parser */
404 char *arg; /* Declaration of the 3rd argument to parser */
405 char *ctx; /* Declaration of 2nd argument to constructor */
406 char *tokentype; /* Type of terminal symbols in the parser stack */
407 char *vartype; /* The default type of non-terminal symbols */
408 char *start; /* Name of the start symbol for the grammar */
409 char *stacksize; /* Size of the parser stack */
410 char *include; /* Code to put at the start of the C file */
411 char *error; /* Code to execute when an error is seen */
412 char *overflow; /* Code to execute on a stack overflow */
413 char *failure; /* Code to execute on parser failure */
414 char *accept; /* Code to execute when the parser excepts */
415 char *extracode; /* Code appended to the generated file */
416 char *tokendest; /* Code to execute to destroy token data */
417 char *vardest; /* Code for the default non-terminal destructor */
418 char *filename; /* Name of the input file */
419 char *outname; /* Name of the current output file */
420 char *tokenprefix; /* A prefix added to token names in the .h file */
421 int nconflict; /* Number of parsing conflicts */
422 int nactiontab; /* Number of entries in the yy_action[] table */
423 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
424 int tablesize; /* Total table size of all tables in bytes */
425 int basisflag; /* Print only basis configurations */
426 int printPreprocessed; /* Show preprocessor output on stdout */
427 int has_fallback; /* True if any %fallback is seen in the grammar */
428 int nolinenosflag; /* True if #line statements should not be printed */
429 int argc; /* Number of command-line arguments */
430 char **argv; /* Command-line arguments */
433 #define MemoryCheck(X) if((X)==0){ \
434 extern void memory_error(); \
435 memory_error(); \
438 /**************** From the file "table.h" *********************************/
440 ** All code in this file has been automatically generated
441 ** from a specification in the file
442 ** "table.q"
443 ** by the associative array code building program "aagen".
444 ** Do not edit this file! Instead, edit the specification
445 ** file, then rerun aagen.
448 ** Code for processing tables in the LEMON parser generator.
450 /* Routines for handling a strings */
452 const char *Strsafe(const char *);
454 void Strsafe_init(void);
455 int Strsafe_insert(const char *);
456 const char *Strsafe_find(const char *);
458 /* Routines for handling symbols of the grammar */
460 struct symbol *Symbol_new(const char *);
461 int Symbolcmpp(const void *, const void *);
462 void Symbol_init(void);
463 int Symbol_insert(struct symbol *, const char *);
464 struct symbol *Symbol_find(const char *);
465 struct symbol *Symbol_Nth(int);
466 int Symbol_count(void);
467 struct symbol **Symbol_arrayof(void);
469 /* Routines to manage the state table */
471 int Configcmp(const char *, const char *);
472 struct state *State_new(void);
473 void State_init(void);
474 int State_insert(struct state *, struct config *);
475 struct state *State_find(struct config *);
476 struct state **State_arrayof(void);
478 /* Routines used for efficiency in Configlist_add */
480 void Configtable_init(void);
481 int Configtable_insert(struct config *);
482 struct config *Configtable_find(struct config *);
483 void Configtable_clear(int(*)(struct config *));
485 /****************** From the file "action.c" *******************************/
487 ** Routines processing parser actions in the LEMON parser generator.
490 /* Allocate a new parser action */
491 static struct action *Action_new(void){
492 static struct action *actionfreelist = 0;
493 struct action *newaction;
495 if( actionfreelist==0 ){
496 int i;
497 int amt = 100;
498 actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
499 if( actionfreelist==0 ){
500 fprintf(stderr,"Unable to allocate memory for a new parser action.");
501 exit(1);
503 for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
504 actionfreelist[amt-1].next = 0;
506 newaction = actionfreelist;
507 actionfreelist = actionfreelist->next;
508 return newaction;
511 /* Compare two actions for sorting purposes. Return negative, zero, or
512 ** positive if the first action is less than, equal to, or greater than
513 ** the first
515 static int actioncmp(
516 struct action *ap1,
517 struct action *ap2
519 int rc;
520 rc = ap1->sp->index - ap2->sp->index;
521 if( rc==0 ){
522 rc = (int)ap1->type - (int)ap2->type;
524 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
525 rc = ap1->x.rp->index - ap2->x.rp->index;
527 if( rc==0 ){
528 rc = (int) (ap2 - ap1);
530 return rc;
533 /* Sort parser actions */
534 static struct action *Action_sort(
535 struct action *ap
537 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
538 (int(*)(const char*,const char*))actioncmp);
539 return ap;
542 void Action_add(
543 struct action **app,
544 enum e_action type,
545 struct symbol *sp,
546 char *arg
548 struct action *newaction;
549 newaction = Action_new();
550 newaction->next = *app;
551 *app = newaction;
552 newaction->type = type;
553 newaction->sp = sp;
554 newaction->spOpt = 0;
555 if( type==SHIFT ){
556 newaction->x.stp = (struct state *)arg;
557 }else{
558 newaction->x.rp = (struct rule *)arg;
561 /********************** New code to implement the "acttab" module ***********/
563 ** This module implements routines use to construct the yy_action[] table.
567 ** The state of the yy_action table under construction is an instance of
568 ** the following structure.
570 ** The yy_action table maps the pair (state_number, lookahead) into an
571 ** action_number. The table is an array of integers pairs. The state_number
572 ** determines an initial offset into the yy_action array. The lookahead
573 ** value is then added to this initial offset to get an index X into the
574 ** yy_action array. If the aAction[X].lookahead equals the value of the
575 ** of the lookahead input, then the value of the action_number output is
576 ** aAction[X].action. If the lookaheads do not match then the
577 ** default action for the state_number is returned.
579 ** All actions associated with a single state_number are first entered
580 ** into aLookahead[] using multiple calls to acttab_action(). Then the
581 ** actions for that single state_number are placed into the aAction[]
582 ** array with a single call to acttab_insert(). The acttab_insert() call
583 ** also resets the aLookahead[] array in preparation for the next
584 ** state number.
586 struct lookahead_action {
587 int lookahead; /* Value of the lookahead token */
588 int action; /* Action to take on the given lookahead */
590 typedef struct acttab acttab;
591 struct acttab {
592 int nAction; /* Number of used slots in aAction[] */
593 int nActionAlloc; /* Slots allocated for aAction[] */
594 struct lookahead_action
595 *aAction, /* The yy_action[] table under construction */
596 *aLookahead; /* A single new transaction set */
597 int mnLookahead; /* Minimum aLookahead[].lookahead */
598 int mnAction; /* Action associated with mnLookahead */
599 int mxLookahead; /* Maximum aLookahead[].lookahead */
600 int nLookahead; /* Used slots in aLookahead[] */
601 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
602 int nterminal; /* Number of terminal symbols */
603 int nsymbol; /* total number of symbols */
606 /* Return the number of entries in the yy_action table */
607 #define acttab_lookahead_size(X) ((X)->nAction)
609 /* The value for the N-th entry in yy_action */
610 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
612 /* The value for the N-th entry in yy_lookahead */
613 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
615 /* Free all memory associated with the given acttab */
616 void acttab_free(acttab *p){
617 free( p->aAction );
618 free( p->aLookahead );
619 free( p );
622 /* Allocate a new acttab structure */
623 acttab *acttab_alloc(int nsymbol, int nterminal){
624 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
625 if( p==0 ){
626 fprintf(stderr,"Unable to allocate memory for a new acttab.");
627 exit(1);
629 memset(p, 0, sizeof(*p));
630 p->nsymbol = nsymbol;
631 p->nterminal = nterminal;
632 return p;
635 /* Add a new action to the current transaction set.
637 ** This routine is called once for each lookahead for a particular
638 ** state.
640 void acttab_action(acttab *p, int lookahead, int action){
641 if( p->nLookahead>=p->nLookaheadAlloc ){
642 p->nLookaheadAlloc += 25;
643 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
644 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
645 if( p->aLookahead==0 ){
646 fprintf(stderr,"malloc failed\n");
647 exit(1);
650 if( p->nLookahead==0 ){
651 p->mxLookahead = lookahead;
652 p->mnLookahead = lookahead;
653 p->mnAction = action;
654 }else{
655 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
656 if( p->mnLookahead>lookahead ){
657 p->mnLookahead = lookahead;
658 p->mnAction = action;
661 p->aLookahead[p->nLookahead].lookahead = lookahead;
662 p->aLookahead[p->nLookahead].action = action;
663 p->nLookahead++;
667 ** Add the transaction set built up with prior calls to acttab_action()
668 ** into the current action table. Then reset the transaction set back
669 ** to an empty set in preparation for a new round of acttab_action() calls.
671 ** Return the offset into the action table of the new transaction.
673 ** If the makeItSafe parameter is true, then the offset is chosen so that
674 ** it is impossible to overread the yy_lookaside[] table regardless of
675 ** the lookaside token. This is done for the terminal symbols, as they
676 ** come from external inputs and can contain syntax errors. When makeItSafe
677 ** is false, there is more flexibility in selecting offsets, resulting in
678 ** a smaller table. For non-terminal symbols, which are never syntax errors,
679 ** makeItSafe can be false.
681 int acttab_insert(acttab *p, int makeItSafe){
682 int i, j, k, n, end;
683 assert( p->nLookahead>0 );
685 /* Make sure we have enough space to hold the expanded action table
686 ** in the worst case. The worst case occurs if the transaction set
687 ** must be appended to the current action table
689 n = p->nsymbol + 1;
690 if( p->nAction + n >= p->nActionAlloc ){
691 int oldAlloc = p->nActionAlloc;
692 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
693 p->aAction = (struct lookahead_action *) realloc( p->aAction,
694 sizeof(p->aAction[0])*p->nActionAlloc);
695 if( p->aAction==0 ){
696 fprintf(stderr,"malloc failed\n");
697 exit(1);
699 for(i=oldAlloc; i<p->nActionAlloc; i++){
700 p->aAction[i].lookahead = -1;
701 p->aAction[i].action = -1;
705 /* Scan the existing action table looking for an offset that is a
706 ** duplicate of the current transaction set. Fall out of the loop
707 ** if and when the duplicate is found.
709 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
711 end = makeItSafe ? p->mnLookahead : 0;
712 for(i=p->nAction-1; i>=end; i--){
713 if( p->aAction[i].lookahead==p->mnLookahead ){
714 /* All lookaheads and actions in the aLookahead[] transaction
715 ** must match against the candidate aAction[i] entry. */
716 if( p->aAction[i].action!=p->mnAction ) continue;
717 for(j=0; j<p->nLookahead; j++){
718 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
719 if( k<0 || k>=p->nAction ) break;
720 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
721 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
723 if( j<p->nLookahead ) continue;
725 /* No possible lookahead value that is not in the aLookahead[]
726 ** transaction is allowed to match aAction[i] */
727 n = 0;
728 for(j=0; j<p->nAction; j++){
729 if( p->aAction[j].lookahead<0 ) continue;
730 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
732 if( n==p->nLookahead ){
733 break; /* An exact match is found at offset i */
738 /* If no existing offsets exactly match the current transaction, find an
739 ** an empty offset in the aAction[] table in which we can add the
740 ** aLookahead[] transaction.
742 if( i<end ){
743 /* Look for holes in the aAction[] table that fit the current
744 ** aLookahead[] transaction. Leave i set to the offset of the hole.
745 ** If no holes are found, i is left at p->nAction, which means the
746 ** transaction will be appended. */
747 i = makeItSafe ? p->mnLookahead : 0;
748 for(; i<p->nActionAlloc - p->mxLookahead; i++){
749 if( p->aAction[i].lookahead<0 ){
750 for(j=0; j<p->nLookahead; j++){
751 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
752 if( k<0 ) break;
753 if( p->aAction[k].lookahead>=0 ) break;
755 if( j<p->nLookahead ) continue;
756 for(j=0; j<p->nAction; j++){
757 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
759 if( j==p->nAction ){
760 break; /* Fits in empty slots */
765 /* Insert transaction set at index i. */
766 #if 0
767 printf("Acttab:");
768 for(j=0; j<p->nLookahead; j++){
769 printf(" %d", p->aLookahead[j].lookahead);
771 printf(" inserted at %d\n", i);
772 #endif
773 for(j=0; j<p->nLookahead; j++){
774 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
775 p->aAction[k] = p->aLookahead[j];
776 if( k>=p->nAction ) p->nAction = k+1;
778 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
779 p->nLookahead = 0;
781 /* Return the offset that is added to the lookahead in order to get the
782 ** index into yy_action of the action */
783 return i - p->mnLookahead;
787 ** Return the size of the action table without the trailing syntax error
788 ** entries.
790 int acttab_action_size(acttab *p){
791 int n = p->nAction;
792 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
793 return n;
796 /********************** From the file "build.c" *****************************/
798 ** Routines to construction the finite state machine for the LEMON
799 ** parser generator.
802 /* Find a precedence symbol of every rule in the grammar.
804 ** Those rules which have a precedence symbol coded in the input
805 ** grammar using the "[symbol]" construct will already have the
806 ** rp->precsym field filled. Other rules take as their precedence
807 ** symbol the first RHS symbol with a defined precedence. If there
808 ** are not RHS symbols with a defined precedence, the precedence
809 ** symbol field is left blank.
811 void FindRulePrecedences(struct lemon *xp)
813 struct rule *rp;
814 for(rp=xp->rule; rp; rp=rp->next){
815 if( rp->precsym==0 ){
816 int i, j;
817 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
818 struct symbol *sp = rp->rhs[i];
819 if( sp->type==MULTITERMINAL ){
820 for(j=0; j<sp->nsubsym; j++){
821 if( sp->subsym[j]->prec>=0 ){
822 rp->precsym = sp->subsym[j];
823 break;
826 }else if( sp->prec>=0 ){
827 rp->precsym = rp->rhs[i];
832 return;
835 /* Find all nonterminals which will generate the empty string.
836 ** Then go back and compute the first sets of every nonterminal.
837 ** The first set is the set of all terminal symbols which can begin
838 ** a string generated by that nonterminal.
840 void FindFirstSets(struct lemon *lemp)
842 int i, j;
843 struct rule *rp;
844 int progress;
846 for(i=0; i<lemp->nsymbol; i++){
847 lemp->symbols[i]->lambda = LEMON_FALSE;
849 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
850 lemp->symbols[i]->firstset = SetNew();
853 /* First compute all lambdas */
855 progress = 0;
856 for(rp=lemp->rule; rp; rp=rp->next){
857 if( rp->lhs->lambda ) continue;
858 for(i=0; i<rp->nrhs; i++){
859 struct symbol *sp = rp->rhs[i];
860 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
861 if( sp->lambda==LEMON_FALSE ) break;
863 if( i==rp->nrhs ){
864 rp->lhs->lambda = LEMON_TRUE;
865 progress = 1;
868 }while( progress );
870 /* Now compute all first sets */
872 struct symbol *s1, *s2;
873 progress = 0;
874 for(rp=lemp->rule; rp; rp=rp->next){
875 s1 = rp->lhs;
876 for(i=0; i<rp->nrhs; i++){
877 s2 = rp->rhs[i];
878 if( s2->type==TERMINAL ){
879 progress += SetAdd(s1->firstset,s2->index);
880 break;
881 }else if( s2->type==MULTITERMINAL ){
882 for(j=0; j<s2->nsubsym; j++){
883 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
885 break;
886 }else if( s1==s2 ){
887 if( s1->lambda==LEMON_FALSE ) break;
888 }else{
889 progress += SetUnion(s1->firstset,s2->firstset);
890 if( s2->lambda==LEMON_FALSE ) break;
894 }while( progress );
895 return;
898 /* Compute all LR(0) states for the grammar. Links
899 ** are added to between some states so that the LR(1) follow sets
900 ** can be computed later.
902 PRIVATE struct state *getstate(struct lemon *); /* forward reference */
903 void FindStates(struct lemon *lemp)
905 struct symbol *sp;
906 struct rule *rp;
908 Configlist_init();
910 /* Find the start symbol */
911 if( lemp->start ){
912 sp = Symbol_find(lemp->start);
913 if( sp==0 ){
914 ErrorMsg(lemp->filename,0,
915 "The specified start symbol \"%s\" is not "
916 "in a nonterminal of the grammar. \"%s\" will be used as the start "
917 "symbol instead.",lemp->start,lemp->startRule->lhs->name);
918 lemp->errorcnt++;
919 sp = lemp->startRule->lhs;
921 }else if( lemp->startRule ){
922 sp = lemp->startRule->lhs;
923 }else{
924 ErrorMsg(lemp->filename,0,"Internal error - no start rule\n");
925 exit(1);
928 /* Make sure the start symbol doesn't occur on the right-hand side of
929 ** any rule. Report an error if it does. (YACC would generate a new
930 ** start symbol in this case.) */
931 for(rp=lemp->rule; rp; rp=rp->next){
932 int i;
933 for(i=0; i<rp->nrhs; i++){
934 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
935 ErrorMsg(lemp->filename,0,
936 "The start symbol \"%s\" occurs on the "
937 "right-hand side of a rule. This will result in a parser which "
938 "does not work properly.",sp->name);
939 lemp->errorcnt++;
944 /* The basis configuration set for the first state
945 ** is all rules which have the start symbol as their
946 ** left-hand side */
947 for(rp=sp->rule; rp; rp=rp->nextlhs){
948 struct config *newcfp;
949 rp->lhsStart = 1;
950 newcfp = Configlist_addbasis(rp,0);
951 SetAdd(newcfp->fws,0);
954 /* Compute the first state. All other states will be
955 ** computed automatically during the computation of the first one.
956 ** The returned pointer to the first state is not used. */
957 (void)getstate(lemp);
958 return;
961 /* Return a pointer to a state which is described by the configuration
962 ** list which has been built from calls to Configlist_add.
964 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
965 PRIVATE struct state *getstate(struct lemon *lemp)
967 struct config *cfp, *bp;
968 struct state *stp;
970 /* Extract the sorted basis of the new state. The basis was constructed
971 ** by prior calls to "Configlist_addbasis()". */
972 Configlist_sortbasis();
973 bp = Configlist_basis();
975 /* Get a state with the same basis */
976 stp = State_find(bp);
977 if( stp ){
978 /* A state with the same basis already exists! Copy all the follow-set
979 ** propagation links from the state under construction into the
980 ** preexisting state, then return a pointer to the preexisting state */
981 struct config *x, *y;
982 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
983 Plink_copy(&y->bplp,x->bplp);
984 Plink_delete(x->fplp);
985 x->fplp = x->bplp = 0;
987 cfp = Configlist_return();
988 Configlist_eat(cfp);
989 }else{
990 /* This really is a new state. Construct all the details */
991 Configlist_closure(lemp); /* Compute the configuration closure */
992 Configlist_sort(); /* Sort the configuration closure */
993 cfp = Configlist_return(); /* Get a pointer to the config list */
994 stp = State_new(); /* A new state structure */
995 MemoryCheck(stp);
996 stp->bp = bp; /* Remember the configuration basis */
997 stp->cfp = cfp; /* Remember the configuration closure */
998 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
999 stp->ap = 0; /* No actions, yet. */
1000 State_insert(stp,stp->bp); /* Add to the state table */
1001 buildshifts(lemp,stp); /* Recursively compute successor states */
1003 return stp;
1007 ** Return true if two symbols are the same.
1009 int same_symbol(struct symbol *a, struct symbol *b)
1011 int i;
1012 if( a==b ) return 1;
1013 if( a->type!=MULTITERMINAL ) return 0;
1014 if( b->type!=MULTITERMINAL ) return 0;
1015 if( a->nsubsym!=b->nsubsym ) return 0;
1016 for(i=0; i<a->nsubsym; i++){
1017 if( a->subsym[i]!=b->subsym[i] ) return 0;
1019 return 1;
1022 /* Construct all successor states to the given state. A "successor"
1023 ** state is any state which can be reached by a shift action.
1025 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
1027 struct config *cfp; /* For looping thru the config closure of "stp" */
1028 struct config *bcfp; /* For the inner loop on config closure of "stp" */
1029 struct config *newcfg; /* */
1030 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1031 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1032 struct state *newstp; /* A pointer to a successor state */
1034 /* Each configuration becomes complete after it contributes to a successor
1035 ** state. Initially, all configurations are incomplete */
1036 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1038 /* Loop through all configurations of the state "stp" */
1039 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1040 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1041 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1042 Configlist_reset(); /* Reset the new config set */
1043 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1045 /* For every configuration in the state "stp" which has the symbol "sp"
1046 ** following its dot, add the same configuration to the basis set under
1047 ** construction but with the dot shifted one symbol to the right. */
1048 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1049 if( bcfp->status==COMPLETE ) continue; /* Already used */
1050 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1051 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
1052 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
1053 bcfp->status = COMPLETE; /* Mark this config as used */
1054 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1055 Plink_add(&newcfg->bplp,bcfp);
1058 /* Get a pointer to the state described by the basis configuration set
1059 ** constructed in the preceding loop */
1060 newstp = getstate(lemp);
1062 /* The state "newstp" is reached from the state "stp" by a shift action
1063 ** on the symbol "sp" */
1064 if( sp->type==MULTITERMINAL ){
1065 int i;
1066 for(i=0; i<sp->nsubsym; i++){
1067 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1069 }else{
1070 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1076 ** Construct the propagation links
1078 void FindLinks(struct lemon *lemp)
1080 int i;
1081 struct config *cfp, *other;
1082 struct state *stp;
1083 struct plink *plp;
1085 /* Housekeeping detail:
1086 ** Add to every propagate link a pointer back to the state to
1087 ** which the link is attached. */
1088 for(i=0; i<lemp->nstate; i++){
1089 stp = lemp->sorted[i];
1090 for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
1091 cfp->stp = stp;
1095 /* Convert all backlinks into forward links. Only the forward
1096 ** links are used in the follow-set computation. */
1097 for(i=0; i<lemp->nstate; i++){
1098 stp = lemp->sorted[i];
1099 for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){
1100 for(plp=cfp->bplp; plp; plp=plp->next){
1101 other = plp->cfp;
1102 Plink_add(&other->fplp,cfp);
1108 /* Compute all followsets.
1110 ** A followset is the set of all symbols which can come immediately
1111 ** after a configuration.
1113 void FindFollowSets(struct lemon *lemp)
1115 int i;
1116 struct config *cfp;
1117 struct plink *plp;
1118 int progress;
1119 int change;
1121 for(i=0; i<lemp->nstate; i++){
1122 assert( lemp->sorted[i]!=0 );
1123 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1124 cfp->status = INCOMPLETE;
1129 progress = 0;
1130 for(i=0; i<lemp->nstate; i++){
1131 assert( lemp->sorted[i]!=0 );
1132 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1133 if( cfp->status==COMPLETE ) continue;
1134 for(plp=cfp->fplp; plp; plp=plp->next){
1135 change = SetUnion(plp->cfp->fws,cfp->fws);
1136 if( change ){
1137 plp->cfp->status = INCOMPLETE;
1138 progress = 1;
1141 cfp->status = COMPLETE;
1144 }while( progress );
1147 static int resolve_conflict(struct action *,struct action *);
1149 /* Compute the reduce actions, and resolve conflicts.
1151 void FindActions(struct lemon *lemp)
1153 int i,j;
1154 struct config *cfp;
1155 struct state *stp;
1156 struct symbol *sp;
1157 struct rule *rp;
1159 /* Add all of the reduce actions
1160 ** A reduce action is added for each element of the followset of
1161 ** a configuration which has its dot at the extreme right.
1163 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1164 stp = lemp->sorted[i];
1165 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1166 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1167 for(j=0; j<lemp->nterminal; j++){
1168 if( SetFind(cfp->fws,j) ){
1169 /* Add a reduce action to the state "stp" which will reduce by the
1170 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1171 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
1178 /* Add the accepting token */
1179 if( lemp->start ){
1180 sp = Symbol_find(lemp->start);
1181 if( sp==0 ){
1182 if( lemp->startRule==0 ){
1183 fprintf(stderr, "internal error on source line %d: no start rule\n",
1184 __LINE__);
1185 exit(1);
1187 sp = lemp->startRule->lhs;
1189 }else{
1190 sp = lemp->startRule->lhs;
1192 /* Add to the first state (which is always the starting state of the
1193 ** finite state machine) an action to ACCEPT if the lookahead is the
1194 ** start nonterminal. */
1195 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1197 /* Resolve conflicts */
1198 for(i=0; i<lemp->nstate; i++){
1199 struct action *ap, *nap;
1200 stp = lemp->sorted[i];
1201 /* assert( stp->ap ); */
1202 stp->ap = Action_sort(stp->ap);
1203 for(ap=stp->ap; ap && ap->next; ap=ap->next){
1204 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1205 /* The two actions "ap" and "nap" have the same lookahead.
1206 ** Figure out which one should be used */
1207 lemp->nconflict += resolve_conflict(ap,nap);
1212 /* Report an error for each rule that can never be reduced. */
1213 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
1214 for(i=0; i<lemp->nstate; i++){
1215 struct action *ap;
1216 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
1217 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
1220 for(rp=lemp->rule; rp; rp=rp->next){
1221 if( rp->canReduce ) continue;
1222 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1223 lemp->errorcnt++;
1227 /* Resolve a conflict between the two given actions. If the
1228 ** conflict can't be resolved, return non-zero.
1230 ** NO LONGER TRUE:
1231 ** To resolve a conflict, first look to see if either action
1232 ** is on an error rule. In that case, take the action which
1233 ** is not associated with the error rule. If neither or both
1234 ** actions are associated with an error rule, then try to
1235 ** use precedence to resolve the conflict.
1237 ** If either action is a SHIFT, then it must be apx. This
1238 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1240 static int resolve_conflict(
1241 struct action *apx,
1242 struct action *apy
1244 struct symbol *spx, *spy;
1245 int errcnt = 0;
1246 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1247 if( apx->type==SHIFT && apy->type==SHIFT ){
1248 apy->type = SSCONFLICT;
1249 errcnt++;
1251 if( apx->type==SHIFT && apy->type==REDUCE ){
1252 spx = apx->sp;
1253 spy = apy->x.rp->precsym;
1254 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1255 /* Not enough precedence information. */
1256 apy->type = SRCONFLICT;
1257 errcnt++;
1258 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
1259 apy->type = RD_RESOLVED;
1260 }else if( spx->prec<spy->prec ){
1261 apx->type = SH_RESOLVED;
1262 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1263 apy->type = RD_RESOLVED; /* associativity */
1264 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1265 apx->type = SH_RESOLVED;
1266 }else{
1267 assert( spx->prec==spy->prec && spx->assoc==NONE );
1268 apx->type = ERROR;
1270 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1271 spx = apx->x.rp->precsym;
1272 spy = apy->x.rp->precsym;
1273 if( spx==0 || spy==0 || spx->prec<0 ||
1274 spy->prec<0 || spx->prec==spy->prec ){
1275 apy->type = RRCONFLICT;
1276 errcnt++;
1277 }else if( spx->prec>spy->prec ){
1278 apy->type = RD_RESOLVED;
1279 }else if( spx->prec<spy->prec ){
1280 apx->type = RD_RESOLVED;
1282 }else{
1283 assert(
1284 apx->type==SH_RESOLVED ||
1285 apx->type==RD_RESOLVED ||
1286 apx->type==SSCONFLICT ||
1287 apx->type==SRCONFLICT ||
1288 apx->type==RRCONFLICT ||
1289 apy->type==SH_RESOLVED ||
1290 apy->type==RD_RESOLVED ||
1291 apy->type==SSCONFLICT ||
1292 apy->type==SRCONFLICT ||
1293 apy->type==RRCONFLICT
1295 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1296 ** REDUCEs on the list. If we reach this point it must be because
1297 ** the parser conflict had already been resolved. */
1299 return errcnt;
1301 /********************* From the file "configlist.c" *************************/
1303 ** Routines to processing a configuration list and building a state
1304 ** in the LEMON parser generator.
1307 static struct config *freelist = 0; /* List of free configurations */
1308 static struct config *current = 0; /* Top of list of configurations */
1309 static struct config **currentend = 0; /* Last on list of configs */
1310 static struct config *basis = 0; /* Top of list of basis configs */
1311 static struct config **basisend = 0; /* End of list of basis configs */
1313 /* Return a pointer to a new configuration */
1314 PRIVATE struct config *newconfig(void){
1315 return (struct config*)calloc(1, sizeof(struct config));
1318 /* The configuration "old" is no longer used */
1319 PRIVATE void deleteconfig(struct config *old)
1321 old->next = freelist;
1322 freelist = old;
1325 /* Initialized the configuration list builder */
1326 void Configlist_init(void){
1327 current = 0;
1328 currentend = &current;
1329 basis = 0;
1330 basisend = &basis;
1331 Configtable_init();
1332 return;
1335 /* Initialized the configuration list builder */
1336 void Configlist_reset(void){
1337 current = 0;
1338 currentend = &current;
1339 basis = 0;
1340 basisend = &basis;
1341 Configtable_clear(0);
1342 return;
1345 /* Add another configuration to the configuration list */
1346 struct config *Configlist_add(
1347 struct rule *rp, /* The rule */
1348 int dot /* Index into the RHS of the rule where the dot goes */
1350 struct config *cfp, model;
1352 assert( currentend!=0 );
1353 model.rp = rp;
1354 model.dot = dot;
1355 cfp = Configtable_find(&model);
1356 if( cfp==0 ){
1357 cfp = newconfig();
1358 cfp->rp = rp;
1359 cfp->dot = dot;
1360 cfp->fws = SetNew();
1361 cfp->stp = 0;
1362 cfp->fplp = cfp->bplp = 0;
1363 cfp->next = 0;
1364 cfp->bp = 0;
1365 *currentend = cfp;
1366 currentend = &cfp->next;
1367 Configtable_insert(cfp);
1369 return cfp;
1372 /* Add a basis configuration to the configuration list */
1373 struct config *Configlist_addbasis(struct rule *rp, int dot)
1375 struct config *cfp, model;
1377 assert( basisend!=0 );
1378 assert( currentend!=0 );
1379 model.rp = rp;
1380 model.dot = dot;
1381 cfp = Configtable_find(&model);
1382 if( cfp==0 ){
1383 cfp = newconfig();
1384 cfp->rp = rp;
1385 cfp->dot = dot;
1386 cfp->fws = SetNew();
1387 cfp->stp = 0;
1388 cfp->fplp = cfp->bplp = 0;
1389 cfp->next = 0;
1390 cfp->bp = 0;
1391 *currentend = cfp;
1392 currentend = &cfp->next;
1393 *basisend = cfp;
1394 basisend = &cfp->bp;
1395 Configtable_insert(cfp);
1397 return cfp;
1400 /* Compute the closure of the configuration list */
1401 void Configlist_closure(struct lemon *lemp)
1403 struct config *cfp, *newcfp;
1404 struct rule *rp, *newrp;
1405 struct symbol *sp, *xsp;
1406 int i, dot;
1408 assert( currentend!=0 );
1409 for(cfp=current; cfp; cfp=cfp->next){
1410 rp = cfp->rp;
1411 dot = cfp->dot;
1412 if( dot>=rp->nrhs ) continue;
1413 sp = rp->rhs[dot];
1414 if( sp->type==NONTERMINAL ){
1415 if( sp->rule==0 && sp!=lemp->errsym ){
1416 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1417 sp->name);
1418 lemp->errorcnt++;
1420 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1421 newcfp = Configlist_add(newrp,0);
1422 for(i=dot+1; i<rp->nrhs; i++){
1423 xsp = rp->rhs[i];
1424 if( xsp->type==TERMINAL ){
1425 SetAdd(newcfp->fws,xsp->index);
1426 break;
1427 }else if( xsp->type==MULTITERMINAL ){
1428 int k;
1429 for(k=0; k<xsp->nsubsym; k++){
1430 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1432 break;
1433 }else{
1434 SetUnion(newcfp->fws,xsp->firstset);
1435 if( xsp->lambda==LEMON_FALSE ) break;
1438 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1442 return;
1445 /* Sort the configuration list */
1446 void Configlist_sort(void){
1447 current = (struct config*)msort((char*)current,(char**)&(current->next),
1448 Configcmp);
1449 currentend = 0;
1450 return;
1453 /* Sort the basis configuration list */
1454 void Configlist_sortbasis(void){
1455 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1456 Configcmp);
1457 basisend = 0;
1458 return;
1461 /* Return a pointer to the head of the configuration list and
1462 ** reset the list */
1463 struct config *Configlist_return(void){
1464 struct config *old;
1465 old = current;
1466 current = 0;
1467 currentend = 0;
1468 return old;
1471 /* Return a pointer to the head of the configuration list and
1472 ** reset the list */
1473 struct config *Configlist_basis(void){
1474 struct config *old;
1475 old = basis;
1476 basis = 0;
1477 basisend = 0;
1478 return old;
1481 /* Free all elements of the given configuration list */
1482 void Configlist_eat(struct config *cfp)
1484 struct config *nextcfp;
1485 for(; cfp; cfp=nextcfp){
1486 nextcfp = cfp->next;
1487 assert( cfp->fplp==0 );
1488 assert( cfp->bplp==0 );
1489 if( cfp->fws ) SetFree(cfp->fws);
1490 deleteconfig(cfp);
1492 return;
1494 /***************** From the file "error.c" *********************************/
1496 ** Code for printing error message.
1499 void ErrorMsg(const char *filename, int lineno, const char *format, ...){
1500 va_list ap;
1501 fprintf(stderr, "%s:%d: ", filename, lineno);
1502 va_start(ap, format);
1503 vfprintf(stderr,format,ap);
1504 va_end(ap);
1505 fprintf(stderr, "\n");
1507 /**************** From the file "main.c" ************************************/
1509 ** Main program file for the LEMON parser generator.
1512 /* Report an out-of-memory condition and abort. This function
1513 ** is used mostly by the "MemoryCheck" macro in struct.h
1515 void memory_error(void){
1516 fprintf(stderr,"Out of memory. Aborting...\n");
1517 exit(1);
1520 static int nDefine = 0; /* Number of -D options on the command line */
1521 static int nDefineUsed = 0; /* Number of -D options actually used */
1522 static char **azDefine = 0; /* Name of the -D macros */
1523 static char *bDefineUsed = 0; /* True for every -D macro actually used */
1525 /* This routine is called with the argument to each -D command-line option.
1526 ** Add the macro defined to the azDefine array.
1528 static void handle_D_option(char *z){
1529 char **paz;
1530 nDefine++;
1531 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
1532 if( azDefine==0 ){
1533 fprintf(stderr,"out of memory\n");
1534 exit(1);
1536 bDefineUsed = (char*)realloc(bDefineUsed, nDefine);
1537 if( bDefineUsed==0 ){
1538 fprintf(stderr,"out of memory\n");
1539 exit(1);
1541 bDefineUsed[nDefine-1] = 0;
1542 paz = &azDefine[nDefine-1];
1543 *paz = (char *) malloc( lemonStrlen(z)+1 );
1544 if( *paz==0 ){
1545 fprintf(stderr,"out of memory\n");
1546 exit(1);
1548 lemon_strcpy(*paz, z);
1549 for(z=*paz; *z && *z!='='; z++){}
1550 *z = 0;
1553 /* Rember the name of the output directory
1555 static char *outputDir = NULL;
1556 static void handle_d_option(char *z){
1557 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1558 if( outputDir==0 ){
1559 fprintf(stderr,"out of memory\n");
1560 exit(1);
1562 lemon_strcpy(outputDir, z);
1565 static char *user_templatename = NULL;
1566 static void handle_T_option(char *z){
1567 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
1568 if( user_templatename==0 ){
1569 memory_error();
1571 lemon_strcpy(user_templatename, z);
1574 /* Merge together to lists of rules ordered by rule.iRule */
1575 static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1576 struct rule *pFirst = 0;
1577 struct rule **ppPrev = &pFirst;
1578 while( pA && pB ){
1579 if( pA->iRule<pB->iRule ){
1580 *ppPrev = pA;
1581 ppPrev = &pA->next;
1582 pA = pA->next;
1583 }else{
1584 *ppPrev = pB;
1585 ppPrev = &pB->next;
1586 pB = pB->next;
1589 if( pA ){
1590 *ppPrev = pA;
1591 }else{
1592 *ppPrev = pB;
1594 return pFirst;
1598 ** Sort a list of rules in order of increasing iRule value
1600 static struct rule *Rule_sort(struct rule *rp){
1601 unsigned int i;
1602 struct rule *pNext;
1603 struct rule *x[32];
1604 memset(x, 0, sizeof(x));
1605 while( rp ){
1606 pNext = rp->next;
1607 rp->next = 0;
1608 for(i=0; i<sizeof(x)/sizeof(x[0])-1 && x[i]; i++){
1609 rp = Rule_merge(x[i], rp);
1610 x[i] = 0;
1612 x[i] = rp;
1613 rp = pNext;
1615 rp = 0;
1616 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1617 rp = Rule_merge(x[i], rp);
1619 return rp;
1622 /* forward reference */
1623 static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1625 /* Print a single line of the "Parser Stats" output
1627 static void stats_line(const char *zLabel, int iValue){
1628 int nLabel = lemonStrlen(zLabel);
1629 printf(" %s%.*s %5d\n", zLabel,
1630 35-nLabel, "................................",
1631 iValue);
1634 /* The main program. Parse the command line and do it... */
1635 int main(int argc, char **argv){
1636 static int version = 0;
1637 static int rpflag = 0;
1638 static int basisflag = 0;
1639 static int compress = 0;
1640 static int quiet = 0;
1641 static int statistics = 0;
1642 static int mhflag = 0;
1643 static int nolinenosflag = 0;
1644 static int noResort = 0;
1645 static int sqlFlag = 0;
1646 static int printPP = 0;
1648 static struct s_options options[] = {
1649 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1650 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1651 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
1652 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
1653 {OPT_FLAG, "E", (char*)&printPP, "Print input file after preprocessing."},
1654 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1655 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1656 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1657 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1658 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
1659 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1660 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1661 "Show conflicts resolved by precedence rules"},
1662 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1663 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
1664 {OPT_FLAG, "s", (char*)&statistics,
1665 "Print parser stats to standard output."},
1666 {OPT_FLAG, "S", (char*)&sqlFlag,
1667 "Generate the *.sql file describing the parser tables."},
1668 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1669 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1670 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1671 {OPT_FLAG,0,0,0}
1673 int i;
1674 int exitcode;
1675 struct lemon lem;
1676 struct rule *rp;
1678 OptInit(argv,options,stderr);
1679 if( version ){
1680 printf("Lemon version 1.0\n");
1681 exit(0);
1683 if( OptNArgs()!=1 ){
1684 fprintf(stderr,"Exactly one filename argument is required.\n");
1685 exit(1);
1687 memset(&lem, 0, sizeof(lem));
1688 lem.errorcnt = 0;
1690 /* Initialize the machine */
1691 Strsafe_init();
1692 Symbol_init();
1693 State_init();
1694 lem.argv = argv;
1695 lem.argc = argc;
1696 lem.filename = OptArg(0);
1697 lem.basisflag = basisflag;
1698 lem.nolinenosflag = nolinenosflag;
1699 lem.printPreprocessed = printPP;
1700 Symbol_new("$");
1702 /* Parse the input file */
1703 Parse(&lem);
1704 if( lem.printPreprocessed || lem.errorcnt ) exit(lem.errorcnt);
1705 if( lem.nrule==0 ){
1706 fprintf(stderr,"Empty grammar.\n");
1707 exit(1);
1709 lem.errsym = Symbol_find("error");
1711 /* Count and index the symbols of the grammar */
1712 Symbol_new("{default}");
1713 lem.nsymbol = Symbol_count();
1714 lem.symbols = Symbol_arrayof();
1715 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1716 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1717 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1718 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1719 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1720 lem.nsymbol = i - 1;
1721 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
1722 lem.nterminal = i;
1724 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1725 ** reduce action C-code associated with them last, so that the switch()
1726 ** statement that selects reduction actions will have a smaller jump table.
1728 for(i=0, rp=lem.rule; rp; rp=rp->next){
1729 rp->iRule = rp->code ? i++ : -1;
1731 lem.nruleWithAction = i;
1732 for(rp=lem.rule; rp; rp=rp->next){
1733 if( rp->iRule<0 ) rp->iRule = i++;
1735 lem.startRule = lem.rule;
1736 lem.rule = Rule_sort(lem.rule);
1738 /* Generate a reprint of the grammar, if requested on the command line */
1739 if( rpflag ){
1740 Reprint(&lem);
1741 }else{
1742 /* Initialize the size for all follow and first sets */
1743 SetSize(lem.nterminal+1);
1745 /* Find the precedence for every production rule (that has one) */
1746 FindRulePrecedences(&lem);
1748 /* Compute the lambda-nonterminals and the first-sets for every
1749 ** nonterminal */
1750 FindFirstSets(&lem);
1752 /* Compute all LR(0) states. Also record follow-set propagation
1753 ** links so that the follow-set can be computed later */
1754 lem.nstate = 0;
1755 FindStates(&lem);
1756 lem.sorted = State_arrayof();
1758 /* Tie up loose ends on the propagation links */
1759 FindLinks(&lem);
1761 /* Compute the follow set of every reducible configuration */
1762 FindFollowSets(&lem);
1764 /* Compute the action tables */
1765 FindActions(&lem);
1767 /* Compress the action tables */
1768 if( compress==0 ) CompressTables(&lem);
1770 /* Reorder and renumber the states so that states with fewer choices
1771 ** occur at the end. This is an optimization that helps make the
1772 ** generated parser tables smaller. */
1773 if( noResort==0 ) ResortStates(&lem);
1775 /* Generate a report of the parser generated. (the "y.output" file) */
1776 if( !quiet ) ReportOutput(&lem);
1778 /* Generate the source code for the parser */
1779 ReportTable(&lem, mhflag, sqlFlag);
1781 /* Produce a header file for use by the scanner. (This step is
1782 ** omitted if the "-m" option is used because makeheaders will
1783 ** generate the file for us.) */
1784 if( !mhflag ) ReportHeader(&lem);
1786 if( statistics ){
1787 printf("Parser statistics:\n");
1788 stats_line("terminal symbols", lem.nterminal);
1789 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1790 stats_line("total symbols", lem.nsymbol);
1791 stats_line("rules", lem.nrule);
1792 stats_line("states", lem.nxstate);
1793 stats_line("conflicts", lem.nconflict);
1794 stats_line("action table entries", lem.nactiontab);
1795 stats_line("lookahead table entries", lem.nlookaheadtab);
1796 stats_line("total table size (bytes)", lem.tablesize);
1798 if( lem.nconflict > 0 ){
1799 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1802 /* return 0 on success, 1 on failure. */
1803 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
1804 exit(exitcode);
1805 return (exitcode);
1807 /******************** From the file "msort.c" *******************************/
1809 ** A generic merge-sort program.
1811 ** USAGE:
1812 ** Let "ptr" be a pointer to some structure which is at the head of
1813 ** a null-terminated list. Then to sort the list call:
1815 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1817 ** In the above, "cmpfnc" is a pointer to a function which compares
1818 ** two instances of the structure and returns an integer, as in
1819 ** strcmp. The second argument is a pointer to the pointer to the
1820 ** second element of the linked list. This address is used to compute
1821 ** the offset to the "next" field within the structure. The offset to
1822 ** the "next" field must be constant for all structures in the list.
1824 ** The function returns a new pointer which is the head of the list
1825 ** after sorting.
1827 ** ALGORITHM:
1828 ** Merge-sort.
1832 ** Return a pointer to the next structure in the linked list.
1834 #define NEXT(A) (*(char**)(((char*)A)+offset))
1837 ** Inputs:
1838 ** a: A sorted, null-terminated linked list. (May be null).
1839 ** b: A sorted, null-terminated linked list. (May be null).
1840 ** cmp: A pointer to the comparison function.
1841 ** offset: Offset in the structure to the "next" field.
1843 ** Return Value:
1844 ** A pointer to the head of a sorted list containing the elements
1845 ** of both a and b.
1847 ** Side effects:
1848 ** The "next" pointers for elements in the lists a and b are
1849 ** changed.
1851 static char *merge(
1852 char *a,
1853 char *b,
1854 int (*cmp)(const char*,const char*),
1855 int offset
1857 char *ptr, *head;
1859 if( a==0 ){
1860 head = b;
1861 }else if( b==0 ){
1862 head = a;
1863 }else{
1864 if( (*cmp)(a,b)<=0 ){
1865 ptr = a;
1866 a = NEXT(a);
1867 }else{
1868 ptr = b;
1869 b = NEXT(b);
1871 head = ptr;
1872 while( a && b ){
1873 if( (*cmp)(a,b)<=0 ){
1874 NEXT(ptr) = a;
1875 ptr = a;
1876 a = NEXT(a);
1877 }else{
1878 NEXT(ptr) = b;
1879 ptr = b;
1880 b = NEXT(b);
1883 if( a ) NEXT(ptr) = a;
1884 else NEXT(ptr) = b;
1886 return head;
1890 ** Inputs:
1891 ** list: Pointer to a singly-linked list of structures.
1892 ** next: Pointer to pointer to the second element of the list.
1893 ** cmp: A comparison function.
1895 ** Return Value:
1896 ** A pointer to the head of a sorted list containing the elements
1897 ** originally in list.
1899 ** Side effects:
1900 ** The "next" pointers for elements in list are changed.
1902 #define LISTSIZE 30
1903 static char *msort(
1904 char *list,
1905 char **next,
1906 int (*cmp)(const char*,const char*)
1908 unsigned long offset;
1909 char *ep;
1910 char *set[LISTSIZE];
1911 int i;
1912 offset = (unsigned long)((char*)next - (char*)list);
1913 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1914 while( list ){
1915 ep = list;
1916 list = NEXT(list);
1917 NEXT(ep) = 0;
1918 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1919 ep = merge(ep,set[i],cmp,offset);
1920 set[i] = 0;
1922 set[i] = ep;
1924 ep = 0;
1925 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
1926 return ep;
1928 /************************ From the file "option.c" **************************/
1929 static char **g_argv;
1930 static struct s_options *op;
1931 static FILE *errstream;
1933 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1936 ** Print the command line with a carrot pointing to the k-th character
1937 ** of the n-th field.
1939 static void errline(int n, int k, FILE *err)
1941 int spcnt, i;
1942 if( g_argv[0] ){
1943 fprintf(err,"%s",g_argv[0]);
1944 spcnt = lemonStrlen(g_argv[0]) + 1;
1945 }else{
1946 spcnt = 0;
1948 for(i=1; i<n && g_argv[i]; i++){
1949 fprintf(err," %s",g_argv[i]);
1950 spcnt += lemonStrlen(g_argv[i])+1;
1952 spcnt += k;
1953 for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
1954 if( spcnt<20 ){
1955 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1956 }else{
1957 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1962 ** Return the index of the N-th non-switch argument. Return -1
1963 ** if N is out of range.
1965 static int argindex(int n)
1967 int i;
1968 int dashdash = 0;
1969 if( g_argv!=0 && *g_argv!=0 ){
1970 for(i=1; g_argv[i]; i++){
1971 if( dashdash || !ISOPT(g_argv[i]) ){
1972 if( n==0 ) return i;
1973 n--;
1975 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
1978 return -1;
1981 static char emsg[] = "Command line syntax error: ";
1984 ** Process a flag command line argument.
1986 static int handleflags(int i, FILE *err)
1988 int v;
1989 int errcnt = 0;
1990 int j;
1991 for(j=0; op[j].label; j++){
1992 if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
1994 v = g_argv[i][0]=='-' ? 1 : 0;
1995 if( op[j].label==0 ){
1996 if( err ){
1997 fprintf(err,"%sundefined option.\n",emsg);
1998 errline(i,1,err);
2000 errcnt++;
2001 }else if( op[j].arg==0 ){
2002 /* Ignore this option */
2003 }else if( op[j].type==OPT_FLAG ){
2004 *((int*)op[j].arg) = v;
2005 }else if( op[j].type==OPT_FFLAG ){
2006 (*(void(*)(int))(op[j].arg))(v);
2007 }else if( op[j].type==OPT_FSTR ){
2008 (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
2009 }else{
2010 if( err ){
2011 fprintf(err,"%smissing argument on switch.\n",emsg);
2012 errline(i,1,err);
2014 errcnt++;
2016 return errcnt;
2020 ** Process a command line switch which has an argument.
2022 static int handleswitch(int i, FILE *err)
2024 int lv = 0;
2025 double dv = 0.0;
2026 char *sv = 0, *end;
2027 char *cp;
2028 int j;
2029 int errcnt = 0;
2030 cp = strchr(g_argv[i],'=');
2031 assert( cp!=0 );
2032 *cp = 0;
2033 for(j=0; op[j].label; j++){
2034 if( strcmp(g_argv[i],op[j].label)==0 ) break;
2036 *cp = '=';
2037 if( op[j].label==0 ){
2038 if( err ){
2039 fprintf(err,"%sundefined option.\n",emsg);
2040 errline(i,0,err);
2042 errcnt++;
2043 }else{
2044 cp++;
2045 switch( op[j].type ){
2046 case OPT_FLAG:
2047 case OPT_FFLAG:
2048 if( err ){
2049 fprintf(err,"%soption requires an argument.\n",emsg);
2050 errline(i,0,err);
2052 errcnt++;
2053 break;
2054 case OPT_DBL:
2055 case OPT_FDBL:
2056 dv = strtod(cp,&end);
2057 if( *end ){
2058 if( err ){
2059 fprintf(err,
2060 "%sillegal character in floating-point argument.\n",emsg);
2061 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
2063 errcnt++;
2065 break;
2066 case OPT_INT:
2067 case OPT_FINT:
2068 lv = strtol(cp,&end,0);
2069 if( *end ){
2070 if( err ){
2071 fprintf(err,"%sillegal character in integer argument.\n",emsg);
2072 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
2074 errcnt++;
2076 break;
2077 case OPT_STR:
2078 case OPT_FSTR:
2079 sv = cp;
2080 break;
2082 switch( op[j].type ){
2083 case OPT_FLAG:
2084 case OPT_FFLAG:
2085 break;
2086 case OPT_DBL:
2087 *(double*)(op[j].arg) = dv;
2088 break;
2089 case OPT_FDBL:
2090 (*(void(*)(double))(op[j].arg))(dv);
2091 break;
2092 case OPT_INT:
2093 *(int*)(op[j].arg) = lv;
2094 break;
2095 case OPT_FINT:
2096 (*(void(*)(int))(op[j].arg))((int)lv);
2097 break;
2098 case OPT_STR:
2099 *(char**)(op[j].arg) = sv;
2100 break;
2101 case OPT_FSTR:
2102 (*(void(*)(char *))(op[j].arg))(sv);
2103 break;
2106 return errcnt;
2109 int OptInit(char **a, struct s_options *o, FILE *err)
2111 int errcnt = 0;
2112 g_argv = a;
2113 op = o;
2114 errstream = err;
2115 if( g_argv && *g_argv && op ){
2116 int i;
2117 for(i=1; g_argv[i]; i++){
2118 if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
2119 errcnt += handleflags(i,err);
2120 }else if( strchr(g_argv[i],'=') ){
2121 errcnt += handleswitch(i,err);
2125 if( errcnt>0 ){
2126 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
2127 OptPrint();
2128 exit(1);
2130 return 0;
2133 int OptNArgs(void){
2134 int cnt = 0;
2135 int dashdash = 0;
2136 int i;
2137 if( g_argv!=0 && g_argv[0]!=0 ){
2138 for(i=1; g_argv[i]; i++){
2139 if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
2140 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
2143 return cnt;
2146 char *OptArg(int n)
2148 int i;
2149 i = argindex(n);
2150 return i>=0 ? g_argv[i] : 0;
2153 void OptErr(int n)
2155 int i;
2156 i = argindex(n);
2157 if( i>=0 ) errline(i,0,errstream);
2160 void OptPrint(void){
2161 int i;
2162 int max, len;
2163 max = 0;
2164 for(i=0; op[i].label; i++){
2165 len = lemonStrlen(op[i].label) + 1;
2166 switch( op[i].type ){
2167 case OPT_FLAG:
2168 case OPT_FFLAG:
2169 break;
2170 case OPT_INT:
2171 case OPT_FINT:
2172 len += 9; /* length of "<integer>" */
2173 break;
2174 case OPT_DBL:
2175 case OPT_FDBL:
2176 len += 6; /* length of "<real>" */
2177 break;
2178 case OPT_STR:
2179 case OPT_FSTR:
2180 len += 8; /* length of "<string>" */
2181 break;
2183 if( len>max ) max = len;
2185 for(i=0; op[i].label; i++){
2186 switch( op[i].type ){
2187 case OPT_FLAG:
2188 case OPT_FFLAG:
2189 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2190 break;
2191 case OPT_INT:
2192 case OPT_FINT:
2193 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
2194 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
2195 break;
2196 case OPT_DBL:
2197 case OPT_FDBL:
2198 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
2199 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
2200 break;
2201 case OPT_STR:
2202 case OPT_FSTR:
2203 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
2204 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
2205 break;
2209 /*********************** From the file "parse.c" ****************************/
2211 ** Input file parser for the LEMON parser generator.
2214 /* The state of the parser */
2215 enum e_state {
2216 INITIALIZE,
2217 WAITING_FOR_DECL_OR_RULE,
2218 WAITING_FOR_DECL_KEYWORD,
2219 WAITING_FOR_DECL_ARG,
2220 WAITING_FOR_PRECEDENCE_SYMBOL,
2221 WAITING_FOR_ARROW,
2222 IN_RHS,
2223 LHS_ALIAS_1,
2224 LHS_ALIAS_2,
2225 LHS_ALIAS_3,
2226 RHS_ALIAS_1,
2227 RHS_ALIAS_2,
2228 PRECEDENCE_MARK_1,
2229 PRECEDENCE_MARK_2,
2230 RESYNC_AFTER_RULE_ERROR,
2231 RESYNC_AFTER_DECL_ERROR,
2232 WAITING_FOR_DESTRUCTOR_SYMBOL,
2233 WAITING_FOR_DATATYPE_SYMBOL,
2234 WAITING_FOR_FALLBACK_ID,
2235 WAITING_FOR_WILDCARD_ID,
2236 WAITING_FOR_CLASS_ID,
2237 WAITING_FOR_CLASS_TOKEN,
2238 WAITING_FOR_TOKEN_NAME
2240 struct pstate {
2241 char *filename; /* Name of the input file */
2242 int tokenlineno; /* Linenumber at which current token starts */
2243 int errorcnt; /* Number of errors so far */
2244 char *tokenstart; /* Text of current token */
2245 struct lemon *gp; /* Global state vector */
2246 enum e_state state; /* The state of the parser */
2247 struct symbol *fallback; /* The fallback token */
2248 struct symbol *tkclass; /* Token class symbol */
2249 struct symbol *lhs; /* Left-hand side of current rule */
2250 const char *lhsalias; /* Alias for the LHS */
2251 int nrhs; /* Number of right-hand side symbols seen */
2252 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2253 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2254 struct rule *prevrule; /* Previous rule parsed */
2255 const char *declkeyword; /* Keyword of a declaration */
2256 char **declargslot; /* Where the declaration argument should be put */
2257 int insertLineMacro; /* Add #line before declaration insert */
2258 int *decllinenoslot; /* Where to write declaration line number */
2259 enum e_assoc declassoc; /* Assign this association to decl arguments */
2260 int preccounter; /* Assign this precedence to decl arguments */
2261 struct rule *firstrule; /* Pointer to first rule in the grammar */
2262 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2265 /* Parse a single token */
2266 static void parseonetoken(struct pstate *psp)
2268 const char *x;
2269 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2270 #if 0
2271 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2272 x,psp->state);
2273 #endif
2274 switch( psp->state ){
2275 case INITIALIZE:
2276 psp->prevrule = 0;
2277 psp->preccounter = 0;
2278 psp->firstrule = psp->lastrule = 0;
2279 psp->gp->nrule = 0;
2280 /* fall through */
2281 case WAITING_FOR_DECL_OR_RULE:
2282 if( x[0]=='%' ){
2283 psp->state = WAITING_FOR_DECL_KEYWORD;
2284 }else if( ISLOWER(x[0]) ){
2285 psp->lhs = Symbol_new(x);
2286 psp->nrhs = 0;
2287 psp->lhsalias = 0;
2288 psp->state = WAITING_FOR_ARROW;
2289 }else if( x[0]=='{' ){
2290 if( psp->prevrule==0 ){
2291 ErrorMsg(psp->filename,psp->tokenlineno,
2292 "There is no prior rule upon which to attach the code "
2293 "fragment which begins on this line.");
2294 psp->errorcnt++;
2295 }else if( psp->prevrule->code!=0 ){
2296 ErrorMsg(psp->filename,psp->tokenlineno,
2297 "Code fragment beginning on this line is not the first "
2298 "to follow the previous rule.");
2299 psp->errorcnt++;
2300 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
2301 psp->prevrule->neverReduce = 1;
2302 }else{
2303 psp->prevrule->line = psp->tokenlineno;
2304 psp->prevrule->code = &x[1];
2305 psp->prevrule->noCode = 0;
2307 }else if( x[0]=='[' ){
2308 psp->state = PRECEDENCE_MARK_1;
2309 }else{
2310 ErrorMsg(psp->filename,psp->tokenlineno,
2311 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2313 psp->errorcnt++;
2315 break;
2316 case PRECEDENCE_MARK_1:
2317 if( !ISUPPER(x[0]) ){
2318 ErrorMsg(psp->filename,psp->tokenlineno,
2319 "The precedence symbol must be a terminal.");
2320 psp->errorcnt++;
2321 }else if( psp->prevrule==0 ){
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "There is no prior rule to assign precedence \"[%s]\".",x);
2324 psp->errorcnt++;
2325 }else if( psp->prevrule->precsym!=0 ){
2326 ErrorMsg(psp->filename,psp->tokenlineno,
2327 "Precedence mark on this line is not the first "
2328 "to follow the previous rule.");
2329 psp->errorcnt++;
2330 }else{
2331 psp->prevrule->precsym = Symbol_new(x);
2333 psp->state = PRECEDENCE_MARK_2;
2334 break;
2335 case PRECEDENCE_MARK_2:
2336 if( x[0]!=']' ){
2337 ErrorMsg(psp->filename,psp->tokenlineno,
2338 "Missing \"]\" on precedence mark.");
2339 psp->errorcnt++;
2341 psp->state = WAITING_FOR_DECL_OR_RULE;
2342 break;
2343 case WAITING_FOR_ARROW:
2344 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2345 psp->state = IN_RHS;
2346 }else if( x[0]=='(' ){
2347 psp->state = LHS_ALIAS_1;
2348 }else{
2349 ErrorMsg(psp->filename,psp->tokenlineno,
2350 "Expected to see a \":\" following the LHS symbol \"%s\".",
2351 psp->lhs->name);
2352 psp->errorcnt++;
2353 psp->state = RESYNC_AFTER_RULE_ERROR;
2355 break;
2356 case LHS_ALIAS_1:
2357 if( ISALPHA(x[0]) ){
2358 psp->lhsalias = x;
2359 psp->state = LHS_ALIAS_2;
2360 }else{
2361 ErrorMsg(psp->filename,psp->tokenlineno,
2362 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2363 x,psp->lhs->name);
2364 psp->errorcnt++;
2365 psp->state = RESYNC_AFTER_RULE_ERROR;
2367 break;
2368 case LHS_ALIAS_2:
2369 if( x[0]==')' ){
2370 psp->state = LHS_ALIAS_3;
2371 }else{
2372 ErrorMsg(psp->filename,psp->tokenlineno,
2373 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2374 psp->errorcnt++;
2375 psp->state = RESYNC_AFTER_RULE_ERROR;
2377 break;
2378 case LHS_ALIAS_3:
2379 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2380 psp->state = IN_RHS;
2381 }else{
2382 ErrorMsg(psp->filename,psp->tokenlineno,
2383 "Missing \"->\" following: \"%s(%s)\".",
2384 psp->lhs->name,psp->lhsalias);
2385 psp->errorcnt++;
2386 psp->state = RESYNC_AFTER_RULE_ERROR;
2388 break;
2389 case IN_RHS:
2390 if( x[0]=='.' ){
2391 struct rule *rp;
2392 rp = (struct rule *)calloc( sizeof(struct rule) +
2393 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2394 if( rp==0 ){
2395 ErrorMsg(psp->filename,psp->tokenlineno,
2396 "Can't allocate enough memory for this rule.");
2397 psp->errorcnt++;
2398 psp->prevrule = 0;
2399 }else{
2400 int i;
2401 rp->ruleline = psp->tokenlineno;
2402 rp->rhs = (struct symbol**)&rp[1];
2403 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
2404 for(i=0; i<psp->nrhs; i++){
2405 rp->rhs[i] = psp->rhs[i];
2406 rp->rhsalias[i] = psp->alias[i];
2407 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
2409 rp->lhs = psp->lhs;
2410 rp->lhsalias = psp->lhsalias;
2411 rp->nrhs = psp->nrhs;
2412 rp->code = 0;
2413 rp->noCode = 1;
2414 rp->precsym = 0;
2415 rp->index = psp->gp->nrule++;
2416 rp->nextlhs = rp->lhs->rule;
2417 rp->lhs->rule = rp;
2418 rp->next = 0;
2419 if( psp->firstrule==0 ){
2420 psp->firstrule = psp->lastrule = rp;
2421 }else{
2422 psp->lastrule->next = rp;
2423 psp->lastrule = rp;
2425 psp->prevrule = rp;
2427 psp->state = WAITING_FOR_DECL_OR_RULE;
2428 }else if( ISALPHA(x[0]) ){
2429 if( psp->nrhs>=MAXRHS ){
2430 ErrorMsg(psp->filename,psp->tokenlineno,
2431 "Too many symbols on RHS of rule beginning at \"%s\".",
2433 psp->errorcnt++;
2434 psp->state = RESYNC_AFTER_RULE_ERROR;
2435 }else{
2436 psp->rhs[psp->nrhs] = Symbol_new(x);
2437 psp->alias[psp->nrhs] = 0;
2438 psp->nrhs++;
2440 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 && ISUPPER(x[1]) ){
2441 struct symbol *msp = psp->rhs[psp->nrhs-1];
2442 if( msp->type!=MULTITERMINAL ){
2443 struct symbol *origsp = msp;
2444 msp = (struct symbol *) calloc(1,sizeof(*msp));
2445 memset(msp, 0, sizeof(*msp));
2446 msp->type = MULTITERMINAL;
2447 msp->nsubsym = 1;
2448 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
2449 msp->subsym[0] = origsp;
2450 msp->name = origsp->name;
2451 psp->rhs[psp->nrhs-1] = msp;
2453 msp->nsubsym++;
2454 msp->subsym = (struct symbol **) realloc(msp->subsym,
2455 sizeof(struct symbol*)*msp->nsubsym);
2456 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2457 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
2458 ErrorMsg(psp->filename,psp->tokenlineno,
2459 "Cannot form a compound containing a non-terminal");
2460 psp->errorcnt++;
2462 }else if( x[0]=='(' && psp->nrhs>0 ){
2463 psp->state = RHS_ALIAS_1;
2464 }else{
2465 ErrorMsg(psp->filename,psp->tokenlineno,
2466 "Illegal character on RHS of rule: \"%s\".",x);
2467 psp->errorcnt++;
2468 psp->state = RESYNC_AFTER_RULE_ERROR;
2470 break;
2471 case RHS_ALIAS_1:
2472 if( ISALPHA(x[0]) ){
2473 psp->alias[psp->nrhs-1] = x;
2474 psp->state = RHS_ALIAS_2;
2475 }else{
2476 ErrorMsg(psp->filename,psp->tokenlineno,
2477 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2478 x,psp->rhs[psp->nrhs-1]->name);
2479 psp->errorcnt++;
2480 psp->state = RESYNC_AFTER_RULE_ERROR;
2482 break;
2483 case RHS_ALIAS_2:
2484 if( x[0]==')' ){
2485 psp->state = IN_RHS;
2486 }else{
2487 ErrorMsg(psp->filename,psp->tokenlineno,
2488 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2489 psp->errorcnt++;
2490 psp->state = RESYNC_AFTER_RULE_ERROR;
2492 break;
2493 case WAITING_FOR_DECL_KEYWORD:
2494 if( ISALPHA(x[0]) ){
2495 psp->declkeyword = x;
2496 psp->declargslot = 0;
2497 psp->decllinenoslot = 0;
2498 psp->insertLineMacro = 1;
2499 psp->state = WAITING_FOR_DECL_ARG;
2500 if( strcmp(x,"name")==0 ){
2501 psp->declargslot = &(psp->gp->name);
2502 psp->insertLineMacro = 0;
2503 }else if( strcmp(x,"include")==0 ){
2504 psp->declargslot = &(psp->gp->include);
2505 }else if( strcmp(x,"code")==0 ){
2506 psp->declargslot = &(psp->gp->extracode);
2507 }else if( strcmp(x,"token_destructor")==0 ){
2508 psp->declargslot = &psp->gp->tokendest;
2509 }else if( strcmp(x,"default_destructor")==0 ){
2510 psp->declargslot = &psp->gp->vardest;
2511 }else if( strcmp(x,"token_prefix")==0 ){
2512 psp->declargslot = &psp->gp->tokenprefix;
2513 psp->insertLineMacro = 0;
2514 }else if( strcmp(x,"syntax_error")==0 ){
2515 psp->declargslot = &(psp->gp->error);
2516 }else if( strcmp(x,"parse_accept")==0 ){
2517 psp->declargslot = &(psp->gp->accept);
2518 }else if( strcmp(x,"parse_failure")==0 ){
2519 psp->declargslot = &(psp->gp->failure);
2520 }else if( strcmp(x,"stack_overflow")==0 ){
2521 psp->declargslot = &(psp->gp->overflow);
2522 }else if( strcmp(x,"extra_argument")==0 ){
2523 psp->declargslot = &(psp->gp->arg);
2524 psp->insertLineMacro = 0;
2525 }else if( strcmp(x,"extra_context")==0 ){
2526 psp->declargslot = &(psp->gp->ctx);
2527 psp->insertLineMacro = 0;
2528 }else if( strcmp(x,"token_type")==0 ){
2529 psp->declargslot = &(psp->gp->tokentype);
2530 psp->insertLineMacro = 0;
2531 }else if( strcmp(x,"default_type")==0 ){
2532 psp->declargslot = &(psp->gp->vartype);
2533 psp->insertLineMacro = 0;
2534 }else if( strcmp(x,"stack_size")==0 ){
2535 psp->declargslot = &(psp->gp->stacksize);
2536 psp->insertLineMacro = 0;
2537 }else if( strcmp(x,"start_symbol")==0 ){
2538 psp->declargslot = &(psp->gp->start);
2539 psp->insertLineMacro = 0;
2540 }else if( strcmp(x,"left")==0 ){
2541 psp->preccounter++;
2542 psp->declassoc = LEFT;
2543 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2544 }else if( strcmp(x,"right")==0 ){
2545 psp->preccounter++;
2546 psp->declassoc = RIGHT;
2547 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2548 }else if( strcmp(x,"nonassoc")==0 ){
2549 psp->preccounter++;
2550 psp->declassoc = NONE;
2551 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2552 }else if( strcmp(x,"destructor")==0 ){
2553 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2554 }else if( strcmp(x,"type")==0 ){
2555 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2556 }else if( strcmp(x,"fallback")==0 ){
2557 psp->fallback = 0;
2558 psp->state = WAITING_FOR_FALLBACK_ID;
2559 }else if( strcmp(x,"token")==0 ){
2560 psp->state = WAITING_FOR_TOKEN_NAME;
2561 }else if( strcmp(x,"wildcard")==0 ){
2562 psp->state = WAITING_FOR_WILDCARD_ID;
2563 }else if( strcmp(x,"token_class")==0 ){
2564 psp->state = WAITING_FOR_CLASS_ID;
2565 }else{
2566 ErrorMsg(psp->filename,psp->tokenlineno,
2567 "Unknown declaration keyword: \"%%%s\".",x);
2568 psp->errorcnt++;
2569 psp->state = RESYNC_AFTER_DECL_ERROR;
2571 }else{
2572 ErrorMsg(psp->filename,psp->tokenlineno,
2573 "Illegal declaration keyword: \"%s\".",x);
2574 psp->errorcnt++;
2575 psp->state = RESYNC_AFTER_DECL_ERROR;
2577 break;
2578 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2579 if( !ISALPHA(x[0]) ){
2580 ErrorMsg(psp->filename,psp->tokenlineno,
2581 "Symbol name missing after %%destructor keyword");
2582 psp->errorcnt++;
2583 psp->state = RESYNC_AFTER_DECL_ERROR;
2584 }else{
2585 struct symbol *sp = Symbol_new(x);
2586 psp->declargslot = &sp->destructor;
2587 psp->decllinenoslot = &sp->destLineno;
2588 psp->insertLineMacro = 1;
2589 psp->state = WAITING_FOR_DECL_ARG;
2591 break;
2592 case WAITING_FOR_DATATYPE_SYMBOL:
2593 if( !ISALPHA(x[0]) ){
2594 ErrorMsg(psp->filename,psp->tokenlineno,
2595 "Symbol name missing after %%type keyword");
2596 psp->errorcnt++;
2597 psp->state = RESYNC_AFTER_DECL_ERROR;
2598 }else{
2599 struct symbol *sp = Symbol_find(x);
2600 if((sp) && (sp->datatype)){
2601 ErrorMsg(psp->filename,psp->tokenlineno,
2602 "Symbol %%type \"%s\" already defined", x);
2603 psp->errorcnt++;
2604 psp->state = RESYNC_AFTER_DECL_ERROR;
2605 }else{
2606 if (!sp){
2607 sp = Symbol_new(x);
2609 psp->declargslot = &sp->datatype;
2610 psp->insertLineMacro = 0;
2611 psp->state = WAITING_FOR_DECL_ARG;
2614 break;
2615 case WAITING_FOR_PRECEDENCE_SYMBOL:
2616 if( x[0]=='.' ){
2617 psp->state = WAITING_FOR_DECL_OR_RULE;
2618 }else if( ISUPPER(x[0]) ){
2619 struct symbol *sp;
2620 sp = Symbol_new(x);
2621 if( sp->prec>=0 ){
2622 ErrorMsg(psp->filename,psp->tokenlineno,
2623 "Symbol \"%s\" has already be given a precedence.",x);
2624 psp->errorcnt++;
2625 }else{
2626 sp->prec = psp->preccounter;
2627 sp->assoc = psp->declassoc;
2629 }else{
2630 ErrorMsg(psp->filename,psp->tokenlineno,
2631 "Can't assign a precedence to \"%s\".",x);
2632 psp->errorcnt++;
2634 break;
2635 case WAITING_FOR_DECL_ARG:
2636 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
2637 const char *zOld, *zNew;
2638 char *zBuf, *z;
2639 int nOld, n, nLine = 0, nNew, nBack;
2640 int addLineMacro;
2641 char zLine[50];
2642 zNew = x;
2643 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2644 nNew = lemonStrlen(zNew);
2645 if( *psp->declargslot ){
2646 zOld = *psp->declargslot;
2647 }else{
2648 zOld = "";
2650 nOld = lemonStrlen(zOld);
2651 n = nOld + nNew + 20;
2652 addLineMacro = !psp->gp->nolinenosflag
2653 && psp->insertLineMacro
2654 && psp->tokenlineno>1
2655 && (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2656 if( addLineMacro ){
2657 for(z=psp->filename, nBack=0; *z; z++){
2658 if( *z=='\\' ) nBack++;
2660 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
2661 nLine = lemonStrlen(zLine);
2662 n += nLine + lemonStrlen(psp->filename) + nBack;
2664 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2665 zBuf = *psp->declargslot + nOld;
2666 if( addLineMacro ){
2667 if( nOld && zBuf[-1]!='\n' ){
2668 *(zBuf++) = '\n';
2670 memcpy(zBuf, zLine, nLine);
2671 zBuf += nLine;
2672 *(zBuf++) = '"';
2673 for(z=psp->filename; *z; z++){
2674 if( *z=='\\' ){
2675 *(zBuf++) = '\\';
2677 *(zBuf++) = *z;
2679 *(zBuf++) = '"';
2680 *(zBuf++) = '\n';
2682 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2683 psp->decllinenoslot[0] = psp->tokenlineno;
2685 memcpy(zBuf, zNew, nNew);
2686 zBuf += nNew;
2687 *zBuf = 0;
2688 psp->state = WAITING_FOR_DECL_OR_RULE;
2689 }else{
2690 ErrorMsg(psp->filename,psp->tokenlineno,
2691 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2692 psp->errorcnt++;
2693 psp->state = RESYNC_AFTER_DECL_ERROR;
2695 break;
2696 case WAITING_FOR_FALLBACK_ID:
2697 if( x[0]=='.' ){
2698 psp->state = WAITING_FOR_DECL_OR_RULE;
2699 }else if( !ISUPPER(x[0]) ){
2700 ErrorMsg(psp->filename, psp->tokenlineno,
2701 "%%fallback argument \"%s\" should be a token", x);
2702 psp->errorcnt++;
2703 }else{
2704 struct symbol *sp = Symbol_new(x);
2705 if( psp->fallback==0 ){
2706 psp->fallback = sp;
2707 }else if( sp->fallback ){
2708 ErrorMsg(psp->filename, psp->tokenlineno,
2709 "More than one fallback assigned to token %s", x);
2710 psp->errorcnt++;
2711 }else{
2712 sp->fallback = psp->fallback;
2713 psp->gp->has_fallback = 1;
2716 break;
2717 case WAITING_FOR_TOKEN_NAME:
2718 /* Tokens do not have to be declared before use. But they can be
2719 ** in order to control their assigned integer number. The number for
2720 ** each token is assigned when it is first seen. So by including
2722 ** %token ONE TWO THREE.
2724 ** early in the grammar file, that assigns small consecutive values
2725 ** to each of the tokens ONE TWO and THREE.
2727 if( x[0]=='.' ){
2728 psp->state = WAITING_FOR_DECL_OR_RULE;
2729 }else if( !ISUPPER(x[0]) ){
2730 ErrorMsg(psp->filename, psp->tokenlineno,
2731 "%%token argument \"%s\" should be a token", x);
2732 psp->errorcnt++;
2733 }else{
2734 (void)Symbol_new(x);
2736 break;
2737 case WAITING_FOR_WILDCARD_ID:
2738 if( x[0]=='.' ){
2739 psp->state = WAITING_FOR_DECL_OR_RULE;
2740 }else if( !ISUPPER(x[0]) ){
2741 ErrorMsg(psp->filename, psp->tokenlineno,
2742 "%%wildcard argument \"%s\" should be a token", x);
2743 psp->errorcnt++;
2744 }else{
2745 struct symbol *sp = Symbol_new(x);
2746 if( psp->gp->wildcard==0 ){
2747 psp->gp->wildcard = sp;
2748 }else{
2749 ErrorMsg(psp->filename, psp->tokenlineno,
2750 "Extra wildcard to token: %s", x);
2751 psp->errorcnt++;
2754 break;
2755 case WAITING_FOR_CLASS_ID:
2756 if( !ISLOWER(x[0]) ){
2757 ErrorMsg(psp->filename, psp->tokenlineno,
2758 "%%token_class must be followed by an identifier: %s", x);
2759 psp->errorcnt++;
2760 psp->state = RESYNC_AFTER_DECL_ERROR;
2761 }else if( Symbol_find(x) ){
2762 ErrorMsg(psp->filename, psp->tokenlineno,
2763 "Symbol \"%s\" already used", x);
2764 psp->errorcnt++;
2765 psp->state = RESYNC_AFTER_DECL_ERROR;
2766 }else{
2767 psp->tkclass = Symbol_new(x);
2768 psp->tkclass->type = MULTITERMINAL;
2769 psp->state = WAITING_FOR_CLASS_TOKEN;
2771 break;
2772 case WAITING_FOR_CLASS_TOKEN:
2773 if( x[0]=='.' ){
2774 psp->state = WAITING_FOR_DECL_OR_RULE;
2775 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
2776 struct symbol *msp = psp->tkclass;
2777 msp->nsubsym++;
2778 msp->subsym = (struct symbol **) realloc(msp->subsym,
2779 sizeof(struct symbol*)*msp->nsubsym);
2780 if( !ISUPPER(x[0]) ) x++;
2781 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2782 }else{
2783 ErrorMsg(psp->filename, psp->tokenlineno,
2784 "%%token_class argument \"%s\" should be a token", x);
2785 psp->errorcnt++;
2786 psp->state = RESYNC_AFTER_DECL_ERROR;
2788 break;
2789 case RESYNC_AFTER_RULE_ERROR:
2790 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2791 ** break; */
2792 case RESYNC_AFTER_DECL_ERROR:
2793 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2794 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2795 break;
2799 /* The text in the input is part of the argument to an %ifdef or %ifndef.
2800 ** Evaluate the text as a boolean expression. Return true or false.
2802 static int eval_preprocessor_boolean(char *z, int lineno){
2803 int neg = 0;
2804 int res = 0;
2805 int okTerm = 1;
2806 int i;
2807 for(i=0; z[i]!=0; i++){
2808 if( ISSPACE(z[i]) ) continue;
2809 if( z[i]=='!' ){
2810 if( !okTerm ) goto pp_syntax_error;
2811 neg = !neg;
2812 continue;
2814 if( z[i]=='|' && z[i+1]=='|' ){
2815 if( okTerm ) goto pp_syntax_error;
2816 if( res ) return 1;
2817 i++;
2818 okTerm = 1;
2819 continue;
2821 if( z[i]=='&' && z[i+1]=='&' ){
2822 if( okTerm ) goto pp_syntax_error;
2823 if( !res ) return 0;
2824 i++;
2825 okTerm = 1;
2826 continue;
2828 if( z[i]=='(' ){
2829 int k;
2830 int n = 1;
2831 if( !okTerm ) goto pp_syntax_error;
2832 for(k=i+1; z[k]; k++){
2833 if( z[k]==')' ){
2834 n--;
2835 if( n==0 ){
2836 z[k] = 0;
2837 res = eval_preprocessor_boolean(&z[i+1], -1);
2838 z[k] = ')';
2839 if( res<0 ){
2840 i = i-res;
2841 goto pp_syntax_error;
2843 i = k;
2844 break;
2846 }else if( z[k]=='(' ){
2847 n++;
2848 }else if( z[k]==0 ){
2849 i = k;
2850 goto pp_syntax_error;
2853 if( neg ){
2854 res = !res;
2855 neg = 0;
2857 okTerm = 0;
2858 continue;
2860 if( ISALPHA(z[i]) ){
2861 int j, k, n;
2862 if( !okTerm ) goto pp_syntax_error;
2863 for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){}
2864 n = k - i;
2865 res = 0;
2866 for(j=0; j<nDefine; j++){
2867 if( strncmp(azDefine[j],&z[i],n)==0 && azDefine[j][n]==0 ){
2868 if( !bDefineUsed[j] ){
2869 bDefineUsed[j] = 1;
2870 nDefineUsed++;
2872 res = 1;
2873 break;
2876 i = k-1;
2877 if( neg ){
2878 res = !res;
2879 neg = 0;
2881 okTerm = 0;
2882 continue;
2884 goto pp_syntax_error;
2886 return res;
2888 pp_syntax_error:
2889 if( lineno>0 ){
2890 fprintf(stderr, "%%if syntax error on line %d.\n", lineno);
2891 fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z);
2892 exit(1);
2893 }else{
2894 return -(i+1);
2898 /* Run the preprocessor over the input file text. The global variables
2899 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2900 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2901 ** comments them out. Text in between is also commented out as appropriate.
2903 static void preprocess_input(char *z){
2904 int i, j, k;
2905 int exclude = 0;
2906 int start = 0;
2907 int lineno = 1;
2908 int start_lineno = 1;
2909 for(i=0; z[i]; i++){
2910 if( z[i]=='\n' ) lineno++;
2911 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2912 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
2913 if( exclude ){
2914 exclude--;
2915 if( exclude==0 ){
2916 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2919 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2920 }else if( strncmp(&z[i],"%else",5)==0 && ISSPACE(z[i+5]) ){
2921 if( exclude==1){
2922 exclude = 0;
2923 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2924 }else if( exclude==0 ){
2925 exclude = 1;
2926 start = i;
2927 start_lineno = lineno;
2929 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2930 }else if( strncmp(&z[i],"%ifdef ",7)==0
2931 || strncmp(&z[i],"%if ",4)==0
2932 || strncmp(&z[i],"%ifndef ",8)==0 ){
2933 if( exclude ){
2934 exclude++;
2935 }else{
2936 int isNot;
2937 int iBool;
2938 for(j=i; z[j] && !ISSPACE(z[j]); j++){}
2939 iBool = j;
2940 isNot = (j==i+7);
2941 while( z[j] && z[j]!='\n' ){ j++; }
2942 k = z[j];
2943 z[j] = 0;
2944 exclude = eval_preprocessor_boolean(&z[iBool], lineno);
2945 z[j] = k;
2946 if( !isNot ) exclude = !exclude;
2947 if( exclude ){
2948 start = i;
2949 start_lineno = lineno;
2952 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2955 if( exclude ){
2956 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2957 exit(1);
2961 /* In spite of its name, this function is really a scanner. It read
2962 ** in the entire input file (all at once) then tokenizes it. Each
2963 ** token is passed to the function "parseonetoken" which builds all
2964 ** the appropriate data structures in the global state vector "gp".
2966 void Parse(struct lemon *gp)
2968 struct pstate ps;
2969 FILE *fp;
2970 char *filebuf;
2971 unsigned int filesize;
2972 int lineno;
2973 int c;
2974 char *cp, *nextcp;
2975 int startline = 0;
2977 memset(&ps, '\0', sizeof(ps));
2978 ps.gp = gp;
2979 ps.filename = gp->filename;
2980 ps.errorcnt = 0;
2981 ps.state = INITIALIZE;
2983 /* Begin by reading the input file */
2984 fp = fopen(ps.filename,"rb");
2985 if( fp==0 ){
2986 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2987 gp->errorcnt++;
2988 return;
2990 fseek(fp,0,2);
2991 filesize = ftell(fp);
2992 rewind(fp);
2993 filebuf = (char *)malloc( filesize+1 );
2994 if( filesize>100000000 || filebuf==0 ){
2995 ErrorMsg(ps.filename,0,"Input file too large.");
2996 free(filebuf);
2997 gp->errorcnt++;
2998 fclose(fp);
2999 return;
3001 if( fread(filebuf,1,filesize,fp)!=filesize ){
3002 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
3003 filesize);
3004 free(filebuf);
3005 gp->errorcnt++;
3006 fclose(fp);
3007 return;
3009 fclose(fp);
3010 filebuf[filesize] = 0;
3012 /* Make an initial pass through the file to handle %ifdef and %ifndef */
3013 preprocess_input(filebuf);
3014 if( gp->printPreprocessed ){
3015 printf("%s\n", filebuf);
3016 return;
3019 /* Now scan the text of the input file */
3020 lineno = 1;
3021 for(cp=filebuf; (c= *cp)!=0; ){
3022 if( c=='\n' ) lineno++; /* Keep track of the line number */
3023 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
3024 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
3025 cp+=2;
3026 while( (c= *cp)!=0 && c!='\n' ) cp++;
3027 continue;
3029 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
3030 cp+=2;
3031 if( (*cp)=='/' ) cp++;
3032 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
3033 if( c=='\n' ) lineno++;
3034 cp++;
3036 if( c ) cp++;
3037 continue;
3039 ps.tokenstart = cp; /* Mark the beginning of the token */
3040 ps.tokenlineno = lineno; /* Linenumber on which token begins */
3041 if( c=='\"' ){ /* String literals */
3042 cp++;
3043 while( (c= *cp)!=0 && c!='\"' ){
3044 if( c=='\n' ) lineno++;
3045 cp++;
3047 if( c==0 ){
3048 ErrorMsg(ps.filename,startline,
3049 "String starting on this line is not terminated before "
3050 "the end of the file.");
3051 ps.errorcnt++;
3052 nextcp = cp;
3053 }else{
3054 nextcp = cp+1;
3056 }else if( c=='{' ){ /* A block of C code */
3057 int level;
3058 cp++;
3059 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
3060 if( c=='\n' ) lineno++;
3061 else if( c=='{' ) level++;
3062 else if( c=='}' ) level--;
3063 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
3064 int prevc;
3065 cp = &cp[2];
3066 prevc = 0;
3067 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
3068 if( c=='\n' ) lineno++;
3069 prevc = c;
3070 cp++;
3072 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
3073 cp = &cp[2];
3074 while( (c= *cp)!=0 && c!='\n' ) cp++;
3075 if( c ) lineno++;
3076 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
3077 int startchar, prevc;
3078 startchar = c;
3079 prevc = 0;
3080 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
3081 if( c=='\n' ) lineno++;
3082 if( prevc=='\\' ) prevc = 0;
3083 else prevc = c;
3087 if( c==0 ){
3088 ErrorMsg(ps.filename,ps.tokenlineno,
3089 "C code starting on this line is not terminated before "
3090 "the end of the file.");
3091 ps.errorcnt++;
3092 nextcp = cp;
3093 }else{
3094 nextcp = cp+1;
3096 }else if( ISALNUM(c) ){ /* Identifiers */
3097 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
3098 nextcp = cp;
3099 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
3100 cp += 3;
3101 nextcp = cp;
3102 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
3103 cp += 2;
3104 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
3105 nextcp = cp;
3106 }else{ /* All other (one character) operators */
3107 cp++;
3108 nextcp = cp;
3110 c = *cp;
3111 *cp = 0; /* Null terminate the token */
3112 parseonetoken(&ps); /* Parse the token */
3113 *cp = (char)c; /* Restore the buffer */
3114 cp = nextcp;
3116 free(filebuf); /* Release the buffer after parsing */
3117 gp->rule = ps.firstrule;
3118 gp->errorcnt = ps.errorcnt;
3120 /*************************** From the file "plink.c" *********************/
3122 ** Routines processing configuration follow-set propagation links
3123 ** in the LEMON parser generator.
3125 static struct plink *plink_freelist = 0;
3127 /* Allocate a new plink */
3128 struct plink *Plink_new(void){
3129 struct plink *newlink;
3131 if( plink_freelist==0 ){
3132 int i;
3133 int amt = 100;
3134 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
3135 if( plink_freelist==0 ){
3136 fprintf(stderr,
3137 "Unable to allocate memory for a new follow-set propagation link.\n");
3138 exit(1);
3140 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3141 plink_freelist[amt-1].next = 0;
3143 newlink = plink_freelist;
3144 plink_freelist = plink_freelist->next;
3145 return newlink;
3148 /* Add a plink to a plink list */
3149 void Plink_add(struct plink **plpp, struct config *cfp)
3151 struct plink *newlink;
3152 newlink = Plink_new();
3153 newlink->next = *plpp;
3154 *plpp = newlink;
3155 newlink->cfp = cfp;
3158 /* Transfer every plink on the list "from" to the list "to" */
3159 void Plink_copy(struct plink **to, struct plink *from)
3161 struct plink *nextpl;
3162 while( from ){
3163 nextpl = from->next;
3164 from->next = *to;
3165 *to = from;
3166 from = nextpl;
3170 /* Delete every plink on the list */
3171 void Plink_delete(struct plink *plp)
3173 struct plink *nextpl;
3175 while( plp ){
3176 nextpl = plp->next;
3177 plp->next = plink_freelist;
3178 plink_freelist = plp;
3179 plp = nextpl;
3182 /*********************** From the file "report.c" **************************/
3184 ** Procedures for generating reports and tables in the LEMON parser generator.
3187 /* Generate a filename with the given suffix. Space to hold the
3188 ** name comes from malloc() and must be freed by the calling
3189 ** function.
3191 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
3193 char *name;
3194 char *cp;
3195 char *filename = lemp->filename;
3196 int sz;
3198 if( outputDir ){
3199 cp = strrchr(filename, '/');
3200 if( cp ) filename = cp + 1;
3202 sz = lemonStrlen(filename);
3203 sz += lemonStrlen(suffix);
3204 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3205 sz += 5;
3206 name = (char*)malloc( sz );
3207 if( name==0 ){
3208 fprintf(stderr,"Can't allocate space for a filename.\n");
3209 exit(1);
3211 name[0] = 0;
3212 if( outputDir ){
3213 lemon_strcpy(name, outputDir);
3214 lemon_strcat(name, "/");
3216 lemon_strcat(name,filename);
3217 cp = strrchr(name,'.');
3218 if( cp ) *cp = 0;
3219 lemon_strcat(name,suffix);
3220 return name;
3223 /* Open a file with a name based on the name of the input file,
3224 ** but with a different (specified) suffix, and return a pointer
3225 ** to the stream */
3226 PRIVATE FILE *file_open(
3227 struct lemon *lemp,
3228 const char *suffix,
3229 const char *mode
3231 FILE *fp;
3233 if( lemp->outname ) free(lemp->outname);
3234 lemp->outname = file_makename(lemp, suffix);
3235 fp = fopen(lemp->outname,mode);
3236 if( fp==0 && *mode=='w' ){
3237 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3238 lemp->errorcnt++;
3239 return 0;
3241 return fp;
3244 /* Print the text of a rule
3246 void rule_print(FILE *out, struct rule *rp){
3247 int i, j;
3248 fprintf(out, "%s",rp->lhs->name);
3249 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3250 fprintf(out," ::=");
3251 for(i=0; i<rp->nrhs; i++){
3252 struct symbol *sp = rp->rhs[i];
3253 if( sp->type==MULTITERMINAL ){
3254 fprintf(out," %s", sp->subsym[0]->name);
3255 for(j=1; j<sp->nsubsym; j++){
3256 fprintf(out,"|%s", sp->subsym[j]->name);
3258 }else{
3259 fprintf(out," %s", sp->name);
3261 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3265 /* Duplicate the input file without comments and without actions
3266 ** on rules */
3267 void Reprint(struct lemon *lemp)
3269 struct rule *rp;
3270 struct symbol *sp;
3271 int i, j, maxlen, len, ncolumns, skip;
3272 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3273 maxlen = 10;
3274 for(i=0; i<lemp->nsymbol; i++){
3275 sp = lemp->symbols[i];
3276 len = lemonStrlen(sp->name);
3277 if( len>maxlen ) maxlen = len;
3279 ncolumns = 76/(maxlen+5);
3280 if( ncolumns<1 ) ncolumns = 1;
3281 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3282 for(i=0; i<skip; i++){
3283 printf("//");
3284 for(j=i; j<lemp->nsymbol; j+=skip){
3285 sp = lemp->symbols[j];
3286 assert( sp->index==j );
3287 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3289 printf("\n");
3291 for(rp=lemp->rule; rp; rp=rp->next){
3292 rule_print(stdout, rp);
3293 printf(".");
3294 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
3295 /* if( rp->code ) printf("\n %s",rp->code); */
3296 printf("\n");
3300 /* Print a single rule.
3302 void RulePrint(FILE *fp, struct rule *rp, int iCursor){
3303 struct symbol *sp;
3304 int i, j;
3305 fprintf(fp,"%s ::=",rp->lhs->name);
3306 for(i=0; i<=rp->nrhs; i++){
3307 if( i==iCursor ) fprintf(fp," *");
3308 if( i==rp->nrhs ) break;
3309 sp = rp->rhs[i];
3310 if( sp->type==MULTITERMINAL ){
3311 fprintf(fp," %s", sp->subsym[0]->name);
3312 for(j=1; j<sp->nsubsym; j++){
3313 fprintf(fp,"|%s",sp->subsym[j]->name);
3315 }else{
3316 fprintf(fp," %s", sp->name);
3321 /* Print the rule for a configuration.
3323 void ConfigPrint(FILE *fp, struct config *cfp){
3324 RulePrint(fp, cfp->rp, cfp->dot);
3327 /* #define TEST */
3328 #if 0
3329 /* Print a set */
3330 PRIVATE void SetPrint(out,set,lemp)
3331 FILE *out;
3332 char *set;
3333 struct lemon *lemp;
3335 int i;
3336 char *spacer;
3337 spacer = "";
3338 fprintf(out,"%12s[","");
3339 for(i=0; i<lemp->nterminal; i++){
3340 if( SetFind(set,i) ){
3341 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3342 spacer = " ";
3345 fprintf(out,"]\n");
3348 /* Print a plink chain */
3349 PRIVATE void PlinkPrint(out,plp,tag)
3350 FILE *out;
3351 struct plink *plp;
3352 char *tag;
3354 while( plp ){
3355 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
3356 ConfigPrint(out,plp->cfp);
3357 fprintf(out,"\n");
3358 plp = plp->next;
3361 #endif
3363 /* Print an action to the given file descriptor. Return FALSE if
3364 ** nothing was actually printed.
3366 int PrintAction(
3367 struct action *ap, /* The action to print */
3368 FILE *fp, /* Print the action here */
3369 int indent /* Indent by this amount */
3371 int result = 1;
3372 switch( ap->type ){
3373 case SHIFT: {
3374 struct state *stp = ap->x.stp;
3375 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
3376 break;
3378 case REDUCE: {
3379 struct rule *rp = ap->x.rp;
3380 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
3381 RulePrint(fp, rp, -1);
3382 break;
3384 case SHIFTREDUCE: {
3385 struct rule *rp = ap->x.rp;
3386 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
3387 RulePrint(fp, rp, -1);
3388 break;
3390 case ACCEPT:
3391 fprintf(fp,"%*s accept",indent,ap->sp->name);
3392 break;
3393 case ERROR:
3394 fprintf(fp,"%*s error",indent,ap->sp->name);
3395 break;
3396 case SRCONFLICT:
3397 case RRCONFLICT:
3398 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
3399 indent,ap->sp->name,ap->x.rp->iRule);
3400 break;
3401 case SSCONFLICT:
3402 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
3403 indent,ap->sp->name,ap->x.stp->statenum);
3404 break;
3405 case SH_RESOLVED:
3406 if( showPrecedenceConflict ){
3407 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
3408 indent,ap->sp->name,ap->x.stp->statenum);
3409 }else{
3410 result = 0;
3412 break;
3413 case RD_RESOLVED:
3414 if( showPrecedenceConflict ){
3415 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
3416 indent,ap->sp->name,ap->x.rp->iRule);
3417 }else{
3418 result = 0;
3420 break;
3421 case NOT_USED:
3422 result = 0;
3423 break;
3425 if( result && ap->spOpt ){
3426 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3428 return result;
3431 /* Generate the "*.out" log file */
3432 void ReportOutput(struct lemon *lemp)
3434 int i, n;
3435 struct state *stp;
3436 struct config *cfp;
3437 struct action *ap;
3438 struct rule *rp;
3439 FILE *fp;
3441 fp = file_open(lemp,".out","wb");
3442 if( fp==0 ) return;
3443 for(i=0; i<lemp->nxstate; i++){
3444 stp = lemp->sorted[i];
3445 fprintf(fp,"State %d:\n",stp->statenum);
3446 if( lemp->basisflag ) cfp=stp->bp;
3447 else cfp=stp->cfp;
3448 while( cfp ){
3449 char buf[20];
3450 if( cfp->dot==cfp->rp->nrhs ){
3451 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
3452 fprintf(fp," %5s ",buf);
3453 }else{
3454 fprintf(fp," ");
3456 ConfigPrint(fp,cfp);
3457 fprintf(fp,"\n");
3458 #if 0
3459 SetPrint(fp,cfp->fws,lemp);
3460 PlinkPrint(fp,cfp->fplp,"To ");
3461 PlinkPrint(fp,cfp->bplp,"From");
3462 #endif
3463 if( lemp->basisflag ) cfp=cfp->bp;
3464 else cfp=cfp->next;
3466 fprintf(fp,"\n");
3467 for(ap=stp->ap; ap; ap=ap->next){
3468 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3470 fprintf(fp,"\n");
3472 fprintf(fp, "----------------------------------------------------\n");
3473 fprintf(fp, "Symbols:\n");
3474 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
3475 for(i=0; i<lemp->nsymbol; i++){
3476 int j;
3477 struct symbol *sp;
3479 sp = lemp->symbols[i];
3480 fprintf(fp, " %3d: %s", i, sp->name);
3481 if( sp->type==NONTERMINAL ){
3482 fprintf(fp, ":");
3483 if( sp->lambda ){
3484 fprintf(fp, " <lambda>");
3486 for(j=0; j<lemp->nterminal; j++){
3487 if( sp->firstset && SetFind(sp->firstset, j) ){
3488 fprintf(fp, " %s", lemp->symbols[j]->name);
3492 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
3493 fprintf(fp, "\n");
3495 fprintf(fp, "----------------------------------------------------\n");
3496 fprintf(fp, "Syntax-only Symbols:\n");
3497 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3498 for(i=n=0; i<lemp->nsymbol; i++){
3499 int w;
3500 struct symbol *sp = lemp->symbols[i];
3501 if( sp->bContent ) continue;
3502 w = (int)strlen(sp->name);
3503 if( n>0 && n+w>75 ){
3504 fprintf(fp,"\n");
3505 n = 0;
3507 if( n>0 ){
3508 fprintf(fp, " ");
3509 n++;
3511 fprintf(fp, "%s", sp->name);
3512 n += w;
3514 if( n>0 ) fprintf(fp, "\n");
3515 fprintf(fp, "----------------------------------------------------\n");
3516 fprintf(fp, "Rules:\n");
3517 for(rp=lemp->rule; rp; rp=rp->next){
3518 fprintf(fp, "%4d: ", rp->iRule);
3519 rule_print(fp, rp);
3520 fprintf(fp,".");
3521 if( rp->precsym ){
3522 fprintf(fp," [%s precedence=%d]",
3523 rp->precsym->name, rp->precsym->prec);
3525 fprintf(fp,"\n");
3527 fclose(fp);
3528 return;
3531 /* Search for the file "name" which is in the same directory as
3532 ** the executable */
3533 PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
3535 const char *pathlist;
3536 char *pathbufptr = 0;
3537 char *pathbuf = 0;
3538 char *path,*cp;
3539 char c;
3541 #ifdef __WIN32__
3542 cp = strrchr(argv0,'\\');
3543 #else
3544 cp = strrchr(argv0,'/');
3545 #endif
3546 if( cp ){
3547 c = *cp;
3548 *cp = 0;
3549 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
3550 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
3551 *cp = c;
3552 }else{
3553 pathlist = getenv("PATH");
3554 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
3555 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
3556 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
3557 if( (pathbuf != 0) && (path!=0) ){
3558 pathbufptr = pathbuf;
3559 lemon_strcpy(pathbuf, pathlist);
3560 while( *pathbuf ){
3561 cp = strchr(pathbuf,':');
3562 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
3563 c = *cp;
3564 *cp = 0;
3565 lemon_sprintf(path,"%s/%s",pathbuf,name);
3566 *cp = c;
3567 if( c==0 ) pathbuf[0] = 0;
3568 else pathbuf = &cp[1];
3569 if( access(path,modemask)==0 ) break;
3572 free(pathbufptr);
3574 return path;
3577 /* Given an action, compute the integer value for that action
3578 ** which is to be put in the action table of the generated machine.
3579 ** Return negative if no action should be generated.
3581 PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
3583 int act;
3584 switch( ap->type ){
3585 case SHIFT: act = ap->x.stp->statenum; break;
3586 case SHIFTREDUCE: {
3587 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3588 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3589 ** REDUCE action: */
3590 if( ap->sp->index>=lemp->nterminal
3591 && (lemp->errsym==0 || ap->sp->index!=lemp->errsym->index)
3593 act = lemp->minReduce + ap->x.rp->iRule;
3594 }else{
3595 act = lemp->minShiftReduce + ap->x.rp->iRule;
3597 break;
3599 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3600 case ERROR: act = lemp->errAction; break;
3601 case ACCEPT: act = lemp->accAction; break;
3602 default: act = -1; break;
3604 return act;
3607 #define LINESIZE 1000
3608 /* The next cluster of routines are for reading the template file
3609 ** and writing the results to the generated parser */
3610 /* The first function transfers data from "in" to "out" until
3611 ** a line is seen which begins with "%%". The line number is
3612 ** tracked.
3614 ** if name!=0, then any word that begin with "Parse" is changed to
3615 ** begin with *name instead.
3617 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
3619 int i, iStart;
3620 char line[LINESIZE];
3621 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3622 (*lineno)++;
3623 iStart = 0;
3624 if( name ){
3625 for(i=0; line[i]; i++){
3626 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3627 && (i==0 || !ISALPHA(line[i-1]))
3629 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3630 fprintf(out,"%s",name);
3631 i += 4;
3632 iStart = i+1;
3636 fprintf(out,"%s",&line[iStart]);
3640 /* Skip forward past the header of the template file to the first "%%"
3642 PRIVATE void tplt_skip_header(FILE *in, int *lineno)
3644 char line[LINESIZE];
3645 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3646 (*lineno)++;
3650 /* The next function finds the template file and opens it, returning
3651 ** a pointer to the opened file. */
3652 PRIVATE FILE *tplt_open(struct lemon *lemp)
3654 static char templatename[] = "lempar.c";
3655 char buf[1000];
3656 FILE *in;
3657 char *tpltname;
3658 char *toFree = 0;
3659 char *cp;
3661 /* first, see if user specified a template filename on the command line. */
3662 if (user_templatename != 0) {
3663 if( access(user_templatename,004)==-1 ){
3664 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3665 user_templatename);
3666 lemp->errorcnt++;
3667 return 0;
3669 in = fopen(user_templatename,"rb");
3670 if( in==0 ){
3671 fprintf(stderr,"Can't open the template file \"%s\".\n",
3672 user_templatename);
3673 lemp->errorcnt++;
3674 return 0;
3676 return in;
3679 cp = strrchr(lemp->filename,'.');
3680 if( cp ){
3681 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3682 }else{
3683 lemon_sprintf(buf,"%s.lt",lemp->filename);
3685 if( access(buf,004)==0 ){
3686 tpltname = buf;
3687 }else if( access(templatename,004)==0 ){
3688 tpltname = templatename;
3689 }else{
3690 toFree = tpltname = pathsearch(lemp->argv[0],templatename,0);
3692 if( tpltname==0 ){
3693 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3694 templatename);
3695 lemp->errorcnt++;
3696 return 0;
3698 in = fopen(tpltname,"rb");
3699 if( in==0 ){
3700 fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname);
3701 lemp->errorcnt++;
3703 free(toFree);
3704 return in;
3707 /* Print a #line directive line to the output file. */
3708 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
3710 fprintf(out,"#line %d \"",lineno);
3711 while( *filename ){
3712 if( *filename == '\\' ) putc('\\',out);
3713 putc(*filename,out);
3714 filename++;
3716 fprintf(out,"\"\n");
3719 /* Print a string to the file and keep the linenumber up to date */
3720 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
3722 if( str==0 ) return;
3723 while( *str ){
3724 putc(*str,out);
3725 if( *str=='\n' ) (*lineno)++;
3726 str++;
3728 if( str[-1]!='\n' ){
3729 putc('\n',out);
3730 (*lineno)++;
3732 if (!lemp->nolinenosflag) {
3733 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3735 return;
3739 ** The following routine emits code for the destructor for the
3740 ** symbol sp
3742 void emit_destructor_code(
3743 FILE *out,
3744 struct symbol *sp,
3745 struct lemon *lemp,
3746 int *lineno
3748 char *cp = 0;
3750 if( sp->type==TERMINAL ){
3751 cp = lemp->tokendest;
3752 if( cp==0 ) return;
3753 fprintf(out,"{\n"); (*lineno)++;
3754 }else if( sp->destructor ){
3755 cp = sp->destructor;
3756 fprintf(out,"{\n"); (*lineno)++;
3757 if( !lemp->nolinenosflag ){
3758 (*lineno)++;
3759 tplt_linedir(out,sp->destLineno,lemp->filename);
3761 }else if( lemp->vardest ){
3762 cp = lemp->vardest;
3763 if( cp==0 ) return;
3764 fprintf(out,"{\n"); (*lineno)++;
3765 }else{
3766 assert( 0 ); /* Cannot happen */
3768 for(; *cp; cp++){
3769 if( *cp=='$' && cp[1]=='$' ){
3770 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3771 cp++;
3772 continue;
3774 if( *cp=='\n' ) (*lineno)++;
3775 fputc(*cp,out);
3777 fprintf(out,"\n"); (*lineno)++;
3778 if (!lemp->nolinenosflag) {
3779 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3781 fprintf(out,"}\n"); (*lineno)++;
3782 return;
3786 ** Return TRUE (non-zero) if the given symbol has a destructor.
3788 int has_destructor(struct symbol *sp, struct lemon *lemp)
3790 int ret;
3791 if( sp->type==TERMINAL ){
3792 ret = lemp->tokendest!=0;
3793 }else{
3794 ret = lemp->vardest!=0 || sp->destructor!=0;
3796 return ret;
3800 ** Append text to a dynamically allocated string. If zText is 0 then
3801 ** reset the string to be empty again. Always return the complete text
3802 ** of the string (which is overwritten with each call).
3804 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3805 ** \000 terminator is stored. zText can contain up to two instances of
3806 ** %d. The values of p1 and p2 are written into the first and second
3807 ** %d.
3809 ** If n==-1, then the previous character is overwritten.
3811 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3812 static char empty[1] = { 0 };
3813 static char *z = 0;
3814 static int alloced = 0;
3815 static int used = 0;
3816 int c;
3817 char zInt[40];
3818 if( zText==0 ){
3819 if( used==0 && z!=0 ) z[0] = 0;
3820 used = 0;
3821 return z;
3823 if( n<=0 ){
3824 if( n<0 ){
3825 used += n;
3826 assert( used>=0 );
3828 n = lemonStrlen(zText);
3830 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
3831 alloced = n + sizeof(zInt)*2 + used + 200;
3832 z = (char *) realloc(z, alloced);
3834 if( z==0 ) return empty;
3835 while( n-- > 0 ){
3836 c = *(zText++);
3837 if( c=='%' && n>0 && zText[0]=='d' ){
3838 lemon_sprintf(zInt, "%d", p1);
3839 p1 = p2;
3840 lemon_strcpy(&z[used], zInt);
3841 used += lemonStrlen(&z[used]);
3842 zText++;
3843 n--;
3844 }else{
3845 z[used++] = (char)c;
3848 z[used] = 0;
3849 return z;
3853 ** Write and transform the rp->code string so that symbols are expanded.
3854 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3856 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3857 ** to be defined.
3859 PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
3860 char *cp, *xp;
3861 int i;
3862 int rc = 0; /* True if yylhsminor is used */
3863 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
3864 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3865 char lhsused = 0; /* True if the LHS element has been used */
3866 char lhsdirect; /* True if LHS writes directly into stack */
3867 char used[MAXRHS]; /* True for each RHS element which is used */
3868 char zLhs[50]; /* Convert the LHS symbol into this string */
3869 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
3871 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3872 lhsused = 0;
3874 if( rp->code==0 ){
3875 static char newlinestr[2] = { '\n', '\0' };
3876 rp->code = newlinestr;
3877 rp->line = rp->ruleline;
3878 rp->noCode = 1;
3879 }else{
3880 rp->noCode = 0;
3884 if( rp->nrhs==0 ){
3885 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3886 lhsdirect = 1;
3887 }else if( rp->rhsalias[0]==0 ){
3888 /* The left-most RHS symbol has no value. LHS direct is ok. But
3889 ** we have to call the destructor on the RHS symbol first. */
3890 lhsdirect = 1;
3891 if( has_destructor(rp->rhs[0],lemp) ){
3892 append_str(0,0,0,0);
3893 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3894 rp->rhs[0]->index,1-rp->nrhs);
3895 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3896 rp->noCode = 0;
3898 }else if( rp->lhsalias==0 ){
3899 /* There is no LHS value symbol. */
3900 lhsdirect = 1;
3901 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3902 /* The LHS symbol and the left-most RHS symbol are the same, so
3903 ** direct writing is allowed */
3904 lhsdirect = 1;
3905 lhsused = 1;
3906 used[0] = 1;
3907 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3908 ErrorMsg(lemp->filename,rp->ruleline,
3909 "%s(%s) and %s(%s) share the same label but have "
3910 "different datatypes.",
3911 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3912 lemp->errorcnt++;
3914 }else{
3915 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3916 rp->lhsalias, rp->rhsalias[0]);
3917 zSkip = strstr(rp->code, zOvwrt);
3918 if( zSkip!=0 ){
3919 /* The code contains a special comment that indicates that it is safe
3920 ** for the LHS label to overwrite left-most RHS label. */
3921 lhsdirect = 1;
3922 }else{
3923 lhsdirect = 0;
3926 if( lhsdirect ){
3927 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3928 }else{
3929 rc = 1;
3930 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3933 append_str(0,0,0,0);
3935 /* This const cast is wrong but harmless, if we're careful. */
3936 for(cp=(char *)rp->code; *cp; cp++){
3937 if( cp==zSkip ){
3938 append_str(zOvwrt,0,0,0);
3939 cp += lemonStrlen(zOvwrt)-1;
3940 dontUseRhs0 = 1;
3941 continue;
3943 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
3944 char saved;
3945 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
3946 saved = *xp;
3947 *xp = 0;
3948 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3949 append_str(zLhs,0,0,0);
3950 cp = xp;
3951 lhsused = 1;
3952 }else{
3953 for(i=0; i<rp->nrhs; i++){
3954 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
3955 if( i==0 && dontUseRhs0 ){
3956 ErrorMsg(lemp->filename,rp->ruleline,
3957 "Label %s used after '%s'.",
3958 rp->rhsalias[0], zOvwrt);
3959 lemp->errorcnt++;
3960 }else if( cp!=rp->code && cp[-1]=='@' ){
3961 /* If the argument is of the form @X then substituted
3962 ** the token number of X, not the value of X */
3963 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3964 }else{
3965 struct symbol *sp = rp->rhs[i];
3966 int dtnum;
3967 if( sp->type==MULTITERMINAL ){
3968 dtnum = sp->subsym[0]->dtnum;
3969 }else{
3970 dtnum = sp->dtnum;
3972 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3974 cp = xp;
3975 used[i] = 1;
3976 break;
3980 *xp = saved;
3982 append_str(cp, 1, 0, 0);
3983 } /* End loop */
3985 /* Main code generation completed */
3986 cp = append_str(0,0,0,0);
3987 if( cp && cp[0] ) rp->code = Strsafe(cp);
3988 append_str(0,0,0,0);
3990 /* Check to make sure the LHS has been used */
3991 if( rp->lhsalias && !lhsused ){
3992 ErrorMsg(lemp->filename,rp->ruleline,
3993 "Label \"%s\" for \"%s(%s)\" is never used.",
3994 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3995 lemp->errorcnt++;
3998 /* Generate destructor code for RHS minor values which are not referenced.
3999 ** Generate error messages for unused labels and duplicate labels.
4001 for(i=0; i<rp->nrhs; i++){
4002 if( rp->rhsalias[i] ){
4003 if( i>0 ){
4004 int j;
4005 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
4006 ErrorMsg(lemp->filename,rp->ruleline,
4007 "%s(%s) has the same label as the LHS but is not the left-most "
4008 "symbol on the RHS.",
4009 rp->rhs[i]->name, rp->rhsalias[i]);
4010 lemp->errorcnt++;
4012 for(j=0; j<i; j++){
4013 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
4014 ErrorMsg(lemp->filename,rp->ruleline,
4015 "Label %s used for multiple symbols on the RHS of a rule.",
4016 rp->rhsalias[i]);
4017 lemp->errorcnt++;
4018 break;
4022 if( !used[i] ){
4023 ErrorMsg(lemp->filename,rp->ruleline,
4024 "Label %s for \"%s(%s)\" is never used.",
4025 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
4026 lemp->errorcnt++;
4028 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
4029 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
4030 rp->rhs[i]->index,i-rp->nrhs+1);
4034 /* If unable to write LHS values directly into the stack, write the
4035 ** saved LHS value now. */
4036 if( lhsdirect==0 ){
4037 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
4038 append_str(zLhs, 0, 0, 0);
4039 append_str(";\n", 0, 0, 0);
4042 /* Suffix code generation complete */
4043 cp = append_str(0,0,0,0);
4044 if( cp && cp[0] ){
4045 rp->codeSuffix = Strsafe(cp);
4046 rp->noCode = 0;
4049 return rc;
4053 ** Generate code which executes when the rule "rp" is reduced. Write
4054 ** the code to "out". Make sure lineno stays up-to-date.
4056 PRIVATE void emit_code(
4057 FILE *out,
4058 struct rule *rp,
4059 struct lemon *lemp,
4060 int *lineno
4062 const char *cp;
4064 /* Setup code prior to the #line directive */
4065 if( rp->codePrefix && rp->codePrefix[0] ){
4066 fprintf(out, "{%s", rp->codePrefix);
4067 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4070 /* Generate code to do the reduce action */
4071 if( rp->code ){
4072 if( !lemp->nolinenosflag ){
4073 (*lineno)++;
4074 tplt_linedir(out,rp->line,lemp->filename);
4076 fprintf(out,"{%s",rp->code);
4077 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4078 fprintf(out,"}\n"); (*lineno)++;
4079 if( !lemp->nolinenosflag ){
4080 (*lineno)++;
4081 tplt_linedir(out,*lineno,lemp->outname);
4085 /* Generate breakdown code that occurs after the #line directive */
4086 if( rp->codeSuffix && rp->codeSuffix[0] ){
4087 fprintf(out, "%s", rp->codeSuffix);
4088 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4091 if( rp->codePrefix ){
4092 fprintf(out, "}\n"); (*lineno)++;
4095 return;
4099 ** Print the definition of the union used for the parser's data stack.
4100 ** This union contains fields for every possible data type for tokens
4101 ** and nonterminals. In the process of computing and printing this
4102 ** union, also set the ".dtnum" field of every terminal and nonterminal
4103 ** symbol.
4105 void print_stack_union(
4106 FILE *out, /* The output stream */
4107 struct lemon *lemp, /* The main info structure for this parser */
4108 int *plineno, /* Pointer to the line number */
4109 int mhflag /* True if generating makeheaders output */
4111 int lineno; /* The line number of the output */
4112 char **types; /* A hash table of datatypes */
4113 int arraysize; /* Size of the "types" array */
4114 int maxdtlength; /* Maximum length of any ".datatype" field. */
4115 char *stddt; /* Standardized name for a datatype */
4116 int i,j; /* Loop counters */
4117 unsigned hash; /* For hashing the name of a type */
4118 const char *name; /* Name of the parser */
4120 /* Allocate and initialize types[] and allocate stddt[] */
4121 arraysize = lemp->nsymbol * 2;
4122 types = (char**)calloc( arraysize, sizeof(char*) );
4123 if( types==0 ){
4124 fprintf(stderr,"Out of memory.\n");
4125 exit(1);
4127 for(i=0; i<arraysize; i++) types[i] = 0;
4128 maxdtlength = 0;
4129 if( lemp->vartype ){
4130 maxdtlength = lemonStrlen(lemp->vartype);
4132 for(i=0; i<lemp->nsymbol; i++){
4133 int len;
4134 struct symbol *sp = lemp->symbols[i];
4135 if( sp->datatype==0 ) continue;
4136 len = lemonStrlen(sp->datatype);
4137 if( len>maxdtlength ) maxdtlength = len;
4139 stddt = (char*)malloc( maxdtlength*2 + 1 );
4140 if( stddt==0 ){
4141 fprintf(stderr,"Out of memory.\n");
4142 exit(1);
4145 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4146 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
4147 ** used for terminal symbols. If there is no %default_type defined then
4148 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4149 ** a datatype using the %type directive.
4151 for(i=0; i<lemp->nsymbol; i++){
4152 struct symbol *sp = lemp->symbols[i];
4153 char *cp;
4154 if( sp==lemp->errsym ){
4155 sp->dtnum = arraysize+1;
4156 continue;
4158 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
4159 sp->dtnum = 0;
4160 continue;
4162 cp = sp->datatype;
4163 if( cp==0 ) cp = lemp->vartype;
4164 j = 0;
4165 while( ISSPACE(*cp) ) cp++;
4166 while( *cp ) stddt[j++] = *cp++;
4167 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
4168 stddt[j] = 0;
4169 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
4170 sp->dtnum = 0;
4171 continue;
4173 hash = 0;
4174 for(j=0; stddt[j]; j++){
4175 hash = hash*53 + stddt[j];
4177 hash = (hash & 0x7fffffff)%arraysize;
4178 while( types[hash] ){
4179 if( strcmp(types[hash],stddt)==0 ){
4180 sp->dtnum = hash + 1;
4181 break;
4183 hash++;
4184 if( hash>=(unsigned)arraysize ) hash = 0;
4186 if( types[hash]==0 ){
4187 sp->dtnum = hash + 1;
4188 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
4189 if( types[hash]==0 ){
4190 fprintf(stderr,"Out of memory.\n");
4191 exit(1);
4193 lemon_strcpy(types[hash],stddt);
4197 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4198 name = lemp->name ? lemp->name : "Parse";
4199 lineno = *plineno;
4200 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4201 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4202 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4203 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4204 fprintf(out,"typedef union {\n"); lineno++;
4205 fprintf(out," int yyinit;\n"); lineno++;
4206 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4207 for(i=0; i<arraysize; i++){
4208 if( types[i]==0 ) continue;
4209 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4210 free(types[i]);
4212 if( lemp->errsym && lemp->errsym->useCnt ){
4213 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4215 free(stddt);
4216 free(types);
4217 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4218 *plineno = lineno;
4222 ** Return the name of a C datatype able to represent values between
4223 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4224 ** for that type (1, 2, or 4) into *pnByte.
4226 static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4227 const char *zType = "int";
4228 int nByte = 4;
4229 if( lwr>=0 ){
4230 if( upr<=255 ){
4231 zType = "unsigned char";
4232 nByte = 1;
4233 }else if( upr<65535 ){
4234 zType = "unsigned short int";
4235 nByte = 2;
4236 }else{
4237 zType = "unsigned int";
4238 nByte = 4;
4240 }else if( lwr>=-127 && upr<=127 ){
4241 zType = "signed char";
4242 nByte = 1;
4243 }else if( lwr>=-32767 && upr<32767 ){
4244 zType = "short";
4245 nByte = 2;
4247 if( pnByte ) *pnByte = nByte;
4248 return zType;
4252 ** Each state contains a set of token transaction and a set of
4253 ** nonterminal transactions. Each of these sets makes an instance
4254 ** of the following structure. An array of these structures is used
4255 ** to order the creation of entries in the yy_action[] table.
4257 struct axset {
4258 struct state *stp; /* A pointer to a state */
4259 int isTkn; /* True to use tokens. False for non-terminals */
4260 int nAction; /* Number of actions */
4261 int iOrder; /* Original order of action sets */
4265 ** Compare to axset structures for sorting purposes
4267 static int axset_compare(const void *a, const void *b){
4268 struct axset *p1 = (struct axset*)a;
4269 struct axset *p2 = (struct axset*)b;
4270 int c;
4271 c = p2->nAction - p1->nAction;
4272 if( c==0 ){
4273 c = p1->iOrder - p2->iOrder;
4275 assert( c!=0 || p1==p2 );
4276 return c;
4280 ** Write text on "out" that describes the rule "rp".
4282 static void writeRuleText(FILE *out, struct rule *rp){
4283 int j;
4284 fprintf(out,"%s ::=", rp->lhs->name);
4285 for(j=0; j<rp->nrhs; j++){
4286 struct symbol *sp = rp->rhs[j];
4287 if( sp->type!=MULTITERMINAL ){
4288 fprintf(out," %s", sp->name);
4289 }else{
4290 int k;
4291 fprintf(out," %s", sp->subsym[0]->name);
4292 for(k=1; k<sp->nsubsym; k++){
4293 fprintf(out,"|%s",sp->subsym[k]->name);
4300 /* Generate C source code for the parser */
4301 void ReportTable(
4302 struct lemon *lemp,
4303 int mhflag, /* Output in makeheaders format if true */
4304 int sqlFlag /* Generate the *.sql file too */
4306 FILE *out, *in, *sql;
4307 int lineno;
4308 struct state *stp;
4309 struct action *ap;
4310 struct rule *rp;
4311 struct acttab *pActtab;
4312 int i, j, n, sz;
4313 int nLookAhead;
4314 int szActionType; /* sizeof(YYACTIONTYPE) */
4315 int szCodeType; /* sizeof(YYCODETYPE) */
4316 const char *name;
4317 int mnTknOfst, mxTknOfst;
4318 int mnNtOfst, mxNtOfst;
4319 struct axset *ax;
4320 char *prefix;
4322 lemp->minShiftReduce = lemp->nstate;
4323 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4324 lemp->accAction = lemp->errAction + 1;
4325 lemp->noAction = lemp->accAction + 1;
4326 lemp->minReduce = lemp->noAction + 1;
4327 lemp->maxAction = lemp->minReduce + lemp->nrule;
4329 in = tplt_open(lemp);
4330 if( in==0 ) return;
4331 out = file_open(lemp,".c","wb");
4332 if( out==0 ){
4333 fclose(in);
4334 return;
4336 if( sqlFlag==0 ){
4337 sql = 0;
4338 }else{
4339 sql = file_open(lemp, ".sql", "wb");
4340 if( sql==0 ){
4341 fclose(in);
4342 fclose(out);
4343 return;
4345 fprintf(sql,
4346 "BEGIN;\n"
4347 "CREATE TABLE symbol(\n"
4348 " id INTEGER PRIMARY KEY,\n"
4349 " name TEXT NOT NULL,\n"
4350 " isTerminal BOOLEAN NOT NULL,\n"
4351 " fallback INTEGER REFERENCES symbol"
4352 " DEFERRABLE INITIALLY DEFERRED\n"
4353 ");\n"
4355 for(i=0; i<lemp->nsymbol; i++){
4356 fprintf(sql,
4357 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4358 "VALUES(%d,'%s',%s",
4359 i, lemp->symbols[i]->name,
4360 i<lemp->nterminal ? "TRUE" : "FALSE"
4362 if( lemp->symbols[i]->fallback ){
4363 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
4364 }else{
4365 fprintf(sql, ",NULL);\n");
4368 fprintf(sql,
4369 "CREATE TABLE rule(\n"
4370 " ruleid INTEGER PRIMARY KEY,\n"
4371 " lhs INTEGER REFERENCES symbol(id),\n"
4372 " txt TEXT\n"
4373 ");\n"
4374 "CREATE TABLE rulerhs(\n"
4375 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4376 " pos INTEGER,\n"
4377 " sym INTEGER REFERENCES symbol(id)\n"
4378 ");\n"
4380 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4381 assert( i==rp->iRule );
4382 fprintf(sql,
4383 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
4384 rp->iRule, rp->lhs->index
4386 writeRuleText(sql, rp);
4387 fprintf(sql,"');\n");
4388 for(j=0; j<rp->nrhs; j++){
4389 struct symbol *sp = rp->rhs[j];
4390 if( sp->type!=MULTITERMINAL ){
4391 fprintf(sql,
4392 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4393 i,j,sp->index
4395 }else{
4396 int k;
4397 for(k=0; k<sp->nsubsym; k++){
4398 fprintf(sql,
4399 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4400 i,j,sp->subsym[k]->index
4406 fprintf(sql, "COMMIT;\n");
4408 lineno = 1;
4410 fprintf(out,
4411 "/* This file is automatically generated by Lemon from input grammar\n"
4412 "** source file \"%s\"", lemp->filename); lineno++;
4413 if( nDefineUsed==0 ){
4414 fprintf(out, ".\n*/\n"); lineno += 2;
4415 }else{
4416 fprintf(out, " with these options:\n**\n"); lineno += 2;
4417 for(i=0; i<nDefine; i++){
4418 if( !bDefineUsed[i] ) continue;
4419 fprintf(out, "** -D%s\n", azDefine[i]); lineno++;
4421 fprintf(out, "*/\n"); lineno++;
4424 /* The first %include directive begins with a C-language comment,
4425 ** then skip over the header comment of the template file
4427 if( lemp->include==0 ) lemp->include = "";
4428 for(i=0; ISSPACE(lemp->include[i]); i++){
4429 if( lemp->include[i]=='\n' ){
4430 lemp->include += i+1;
4431 i = -1;
4434 if( lemp->include[0]=='/' ){
4435 tplt_skip_header(in,&lineno);
4436 }else{
4437 tplt_xfer(lemp->name,in,out,&lineno);
4440 /* Generate the include code, if any */
4441 tplt_print(out,lemp,lemp->include,&lineno);
4442 if( mhflag ){
4443 char *incName = file_makename(lemp, ".h");
4444 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4445 free(incName);
4447 tplt_xfer(lemp->name,in,out,&lineno);
4449 /* Generate #defines for all tokens */
4450 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4451 else prefix = "";
4452 if( mhflag ){
4453 fprintf(out,"#if INTERFACE\n"); lineno++;
4454 }else{
4455 fprintf(out,"#ifndef %s%s\n", prefix, lemp->symbols[1]->name);
4457 for(i=1; i<lemp->nterminal; i++){
4458 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4459 lineno++;
4461 fprintf(out,"#endif\n"); lineno++;
4462 tplt_xfer(lemp->name,in,out,&lineno);
4464 /* Generate the defines */
4465 fprintf(out,"#define YYCODETYPE %s\n",
4466 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4467 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
4468 fprintf(out,"#define YYACTIONTYPE %s\n",
4469 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
4470 if( lemp->wildcard ){
4471 fprintf(out,"#define YYWILDCARD %d\n",
4472 lemp->wildcard->index); lineno++;
4474 print_stack_union(out,lemp,&lineno,mhflag);
4475 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
4476 if( lemp->stacksize ){
4477 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4478 }else{
4479 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4481 fprintf(out, "#endif\n"); lineno++;
4482 if( mhflag ){
4483 fprintf(out,"#if INTERFACE\n"); lineno++;
4485 name = lemp->name ? lemp->name : "Parse";
4486 if( lemp->arg && lemp->arg[0] ){
4487 i = lemonStrlen(lemp->arg);
4488 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4489 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
4490 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4491 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4492 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4493 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
4494 name,lemp->arg,&lemp->arg[i]); lineno++;
4495 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
4496 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
4497 }else{
4498 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4499 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4500 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
4501 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4502 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
4504 if( lemp->ctx && lemp->ctx[0] ){
4505 i = lemonStrlen(lemp->ctx);
4506 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4507 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4508 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4509 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4510 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4511 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4512 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4513 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4514 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4515 }else{
4516 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4517 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4518 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4519 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4520 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4522 if( mhflag ){
4523 fprintf(out,"#endif\n"); lineno++;
4525 if( lemp->errsym && lemp->errsym->useCnt ){
4526 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4527 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
4529 if( lemp->has_fallback ){
4530 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4533 /* Compute the action table, but do not output it yet. The action
4534 ** table must be computed before generating the YYNSTATE macro because
4535 ** we need to know how many states can be eliminated.
4537 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
4538 if( ax==0 ){
4539 fprintf(stderr,"malloc failed\n");
4540 exit(1);
4542 for(i=0; i<lemp->nxstate; i++){
4543 stp = lemp->sorted[i];
4544 ax[i*2].stp = stp;
4545 ax[i*2].isTkn = 1;
4546 ax[i*2].nAction = stp->nTknAct;
4547 ax[i*2+1].stp = stp;
4548 ax[i*2+1].isTkn = 0;
4549 ax[i*2+1].nAction = stp->nNtAct;
4551 mxTknOfst = mnTknOfst = 0;
4552 mxNtOfst = mnNtOfst = 0;
4553 /* In an effort to minimize the action table size, use the heuristic
4554 ** of placing the largest action sets first */
4555 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4556 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
4557 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
4558 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
4559 stp = ax[i].stp;
4560 if( ax[i].isTkn ){
4561 for(ap=stp->ap; ap; ap=ap->next){
4562 int action;
4563 if( ap->sp->index>=lemp->nterminal ) continue;
4564 action = compute_action(lemp, ap);
4565 if( action<0 ) continue;
4566 acttab_action(pActtab, ap->sp->index, action);
4568 stp->iTknOfst = acttab_insert(pActtab, 1);
4569 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4570 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4571 }else{
4572 for(ap=stp->ap; ap; ap=ap->next){
4573 int action;
4574 if( ap->sp->index<lemp->nterminal ) continue;
4575 if( ap->sp->index==lemp->nsymbol ) continue;
4576 action = compute_action(lemp, ap);
4577 if( action<0 ) continue;
4578 acttab_action(pActtab, ap->sp->index, action);
4580 stp->iNtOfst = acttab_insert(pActtab, 0);
4581 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4582 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
4584 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4585 { int jj, nn;
4586 for(jj=nn=0; jj<pActtab->nAction; jj++){
4587 if( pActtab->aAction[jj].action<0 ) nn++;
4589 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4590 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4591 ax[i].nAction, pActtab->nAction, nn);
4593 #endif
4595 free(ax);
4597 /* Mark rules that are actually used for reduce actions after all
4598 ** optimizations have been applied
4600 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4601 for(i=0; i<lemp->nxstate; i++){
4602 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4603 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
4604 ap->x.rp->doesReduce = 1;
4609 /* Finish rendering the constants now that the action table has
4610 ** been computed */
4611 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4612 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
4613 fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
4614 lineno++;
4615 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
4616 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
4617 i = lemp->minShiftReduce;
4618 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4619 i += lemp->nrule;
4620 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4621 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4622 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4623 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4624 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4625 i = lemp->minReduce + lemp->nrule;
4626 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4627 tplt_xfer(lemp->name,in,out,&lineno);
4629 /* Now output the action table and its associates:
4631 ** yy_action[] A single table containing all actions.
4632 ** yy_lookahead[] A table containing the lookahead for each entry in
4633 ** yy_action. Used to detect hash collisions.
4634 ** yy_shift_ofst[] For each state, the offset into yy_action for
4635 ** shifting terminals.
4636 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4637 ** shifting non-terminals after a reduce.
4638 ** yy_default[] Default action for each state.
4641 /* Output the yy_action table */
4642 lemp->nactiontab = n = acttab_action_size(pActtab);
4643 lemp->tablesize += n*szActionType;
4644 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4645 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
4646 for(i=j=0; i<n; i++){
4647 int action = acttab_yyaction(pActtab, i);
4648 if( action<0 ) action = lemp->noAction;
4649 if( j==0 ) fprintf(out," /* %5d */ ", i);
4650 fprintf(out, " %4d,", action);
4651 if( j==9 || i==n-1 ){
4652 fprintf(out, "\n"); lineno++;
4653 j = 0;
4654 }else{
4655 j++;
4658 fprintf(out, "};\n"); lineno++;
4660 /* Output the yy_lookahead table */
4661 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
4662 lemp->tablesize += n*szCodeType;
4663 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
4664 for(i=j=0; i<n; i++){
4665 int la = acttab_yylookahead(pActtab, i);
4666 if( la<0 ) la = lemp->nsymbol;
4667 if( j==0 ) fprintf(out," /* %5d */ ", i);
4668 fprintf(out, " %4d,", la);
4669 if( j==9 ){
4670 fprintf(out, "\n"); lineno++;
4671 j = 0;
4672 }else{
4673 j++;
4676 /* Add extra entries to the end of the yy_lookahead[] table so that
4677 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4678 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4679 nLookAhead = lemp->nterminal + lemp->nactiontab;
4680 while( i<nLookAhead ){
4681 if( j==0 ) fprintf(out," /* %5d */ ", i);
4682 fprintf(out, " %4d,", lemp->nterminal);
4683 if( j==9 ){
4684 fprintf(out, "\n"); lineno++;
4685 j = 0;
4686 }else{
4687 j++;
4689 i++;
4691 if( j>0 ){ fprintf(out, "\n"); lineno++; }
4692 fprintf(out, "};\n"); lineno++;
4694 /* Output the yy_shift_ofst[] table */
4695 n = lemp->nxstate;
4696 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
4697 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4698 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4699 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
4700 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
4701 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4702 lineno++;
4703 lemp->tablesize += n*sz;
4704 for(i=j=0; i<n; i++){
4705 int ofst;
4706 stp = lemp->sorted[i];
4707 ofst = stp->iTknOfst;
4708 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
4709 if( j==0 ) fprintf(out," /* %5d */ ", i);
4710 fprintf(out, " %4d,", ofst);
4711 if( j==9 || i==n-1 ){
4712 fprintf(out, "\n"); lineno++;
4713 j = 0;
4714 }else{
4715 j++;
4718 fprintf(out, "};\n"); lineno++;
4720 /* Output the yy_reduce_ofst[] table */
4721 n = lemp->nxstate;
4722 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
4723 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4724 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4725 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
4726 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
4727 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4728 lemp->tablesize += n*sz;
4729 for(i=j=0; i<n; i++){
4730 int ofst;
4731 stp = lemp->sorted[i];
4732 ofst = stp->iNtOfst;
4733 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
4734 if( j==0 ) fprintf(out," /* %5d */ ", i);
4735 fprintf(out, " %4d,", ofst);
4736 if( j==9 || i==n-1 ){
4737 fprintf(out, "\n"); lineno++;
4738 j = 0;
4739 }else{
4740 j++;
4743 fprintf(out, "};\n"); lineno++;
4745 /* Output the default action table */
4746 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
4747 n = lemp->nxstate;
4748 lemp->tablesize += n*szActionType;
4749 for(i=j=0; i<n; i++){
4750 stp = lemp->sorted[i];
4751 if( j==0 ) fprintf(out," /* %5d */ ", i);
4752 if( stp->iDfltReduce<0 ){
4753 fprintf(out, " %4d,", lemp->errAction);
4754 }else{
4755 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4757 if( j==9 || i==n-1 ){
4758 fprintf(out, "\n"); lineno++;
4759 j = 0;
4760 }else{
4761 j++;
4764 fprintf(out, "};\n"); lineno++;
4765 tplt_xfer(lemp->name,in,out,&lineno);
4767 /* Generate the table of fallback tokens.
4769 if( lemp->has_fallback ){
4770 int mx = lemp->nterminal - 1;
4771 /* 2019-08-28: Generate fallback entries for every token to avoid
4772 ** having to do a range check on the index */
4773 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
4774 lemp->tablesize += (mx+1)*szCodeType;
4775 for(i=0; i<=mx; i++){
4776 struct symbol *p = lemp->symbols[i];
4777 if( p->fallback==0 ){
4778 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4779 }else{
4780 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4781 p->name, p->fallback->name);
4783 lineno++;
4786 tplt_xfer(lemp->name, in, out, &lineno);
4788 /* Generate a table containing the symbolic name of every symbol
4790 for(i=0; i<lemp->nsymbol; i++){
4791 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
4793 tplt_xfer(lemp->name,in,out,&lineno);
4795 /* Generate a table containing a text string that describes every
4796 ** rule in the rule set of the grammar. This information is used
4797 ** when tracing REDUCE actions.
4799 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4800 assert( rp->iRule==i );
4801 fprintf(out," /* %3d */ \"", i);
4802 writeRuleText(out, rp);
4803 fprintf(out,"\",\n"); lineno++;
4805 tplt_xfer(lemp->name,in,out,&lineno);
4807 /* Generate code which executes every time a symbol is popped from
4808 ** the stack while processing errors or while destroying the parser.
4809 ** (In other words, generate the %destructor actions)
4811 if( lemp->tokendest ){
4812 int once = 1;
4813 for(i=0; i<lemp->nsymbol; i++){
4814 struct symbol *sp = lemp->symbols[i];
4815 if( sp==0 || sp->type!=TERMINAL ) continue;
4816 if( once ){
4817 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4818 once = 0;
4820 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4822 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4823 if( i<lemp->nsymbol ){
4824 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4825 fprintf(out," break;\n"); lineno++;
4828 if( lemp->vardest ){
4829 struct symbol *dflt_sp = 0;
4830 int once = 1;
4831 for(i=0; i<lemp->nsymbol; i++){
4832 struct symbol *sp = lemp->symbols[i];
4833 if( sp==0 || sp->type==TERMINAL ||
4834 sp->index<=0 || sp->destructor!=0 ) continue;
4835 if( once ){
4836 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
4837 once = 0;
4839 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4840 dflt_sp = sp;
4842 if( dflt_sp!=0 ){
4843 emit_destructor_code(out,dflt_sp,lemp,&lineno);
4845 fprintf(out," break;\n"); lineno++;
4847 for(i=0; i<lemp->nsymbol; i++){
4848 struct symbol *sp = lemp->symbols[i];
4849 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
4850 if( sp->destLineno<0 ) continue; /* Already emitted */
4851 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
4853 /* Combine duplicate destructors into a single case */
4854 for(j=i+1; j<lemp->nsymbol; j++){
4855 struct symbol *sp2 = lemp->symbols[j];
4856 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4857 && sp2->dtnum==sp->dtnum
4858 && strcmp(sp->destructor,sp2->destructor)==0 ){
4859 fprintf(out," case %d: /* %s */\n",
4860 sp2->index, sp2->name); lineno++;
4861 sp2->destLineno = -1; /* Avoid emitting this destructor again */
4865 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4866 fprintf(out," break;\n"); lineno++;
4868 tplt_xfer(lemp->name,in,out,&lineno);
4870 /* Generate code which executes whenever the parser stack overflows */
4871 tplt_print(out,lemp,lemp->overflow,&lineno);
4872 tplt_xfer(lemp->name,in,out,&lineno);
4874 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4875 ** yyRuleInfoNRhs[].
4877 ** Note: This code depends on the fact that rules are number
4878 ** sequentially beginning with 0.
4880 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4881 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4882 rule_print(out, rp);
4883 fprintf(out," */\n"); lineno++;
4885 tplt_xfer(lemp->name,in,out,&lineno);
4886 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4887 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
4888 rule_print(out, rp);
4889 fprintf(out," */\n"); lineno++;
4891 tplt_xfer(lemp->name,in,out,&lineno);
4893 /* Generate code which execution during each REDUCE action */
4894 i = 0;
4895 for(rp=lemp->rule; rp; rp=rp->next){
4896 i += translate_code(lemp, rp);
4898 if( i ){
4899 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
4901 /* First output rules other than the default: rule */
4902 for(rp=lemp->rule; rp; rp=rp->next){
4903 struct rule *rp2; /* Other rules with the same action */
4904 if( rp->codeEmitted ) continue;
4905 if( rp->noCode ){
4906 /* No C code actions, so this will be part of the "default:" rule */
4907 continue;
4909 fprintf(out," case %d: /* ", rp->iRule);
4910 writeRuleText(out, rp);
4911 fprintf(out, " */\n"); lineno++;
4912 for(rp2=rp->next; rp2; rp2=rp2->next){
4913 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4914 && rp2->codeSuffix==rp->codeSuffix ){
4915 fprintf(out," case %d: /* ", rp2->iRule);
4916 writeRuleText(out, rp2);
4917 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
4918 rp2->codeEmitted = 1;
4921 emit_code(out,rp,lemp,&lineno);
4922 fprintf(out," break;\n"); lineno++;
4923 rp->codeEmitted = 1;
4925 /* Finally, output the default: rule. We choose as the default: all
4926 ** empty actions. */
4927 fprintf(out," default:\n"); lineno++;
4928 for(rp=lemp->rule; rp; rp=rp->next){
4929 if( rp->codeEmitted ) continue;
4930 assert( rp->noCode );
4931 fprintf(out," /* (%d) ", rp->iRule);
4932 writeRuleText(out, rp);
4933 if( rp->neverReduce ){
4934 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
4935 rp->iRule); lineno++;
4936 }else if( rp->doesReduce ){
4937 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4938 }else{
4939 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4940 rp->iRule); lineno++;
4943 fprintf(out," break;\n"); lineno++;
4944 tplt_xfer(lemp->name,in,out,&lineno);
4946 /* Generate code which executes if a parse fails */
4947 tplt_print(out,lemp,lemp->failure,&lineno);
4948 tplt_xfer(lemp->name,in,out,&lineno);
4950 /* Generate code which executes when a syntax error occurs */
4951 tplt_print(out,lemp,lemp->error,&lineno);
4952 tplt_xfer(lemp->name,in,out,&lineno);
4954 /* Generate code which executes when the parser accepts its input */
4955 tplt_print(out,lemp,lemp->accept,&lineno);
4956 tplt_xfer(lemp->name,in,out,&lineno);
4958 /* Append any addition code the user desires */
4959 tplt_print(out,lemp,lemp->extracode,&lineno);
4961 acttab_free(pActtab);
4962 fclose(in);
4963 fclose(out);
4964 if( sql ) fclose(sql);
4965 return;
4968 /* Generate a header file for the parser */
4969 void ReportHeader(struct lemon *lemp)
4971 FILE *out, *in;
4972 const char *prefix;
4973 char line[LINESIZE];
4974 char pattern[LINESIZE];
4975 int i;
4977 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4978 else prefix = "";
4979 in = file_open(lemp,".h","rb");
4980 if( in ){
4981 int nextChar;
4982 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4983 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4984 prefix,lemp->symbols[i]->name,i);
4985 if( strcmp(line,pattern) ) break;
4987 nextChar = fgetc(in);
4988 fclose(in);
4989 if( i==lemp->nterminal && nextChar==EOF ){
4990 /* No change in the file. Don't rewrite it. */
4991 return;
4994 out = file_open(lemp,".h","wb");
4995 if( out ){
4996 for(i=1; i<lemp->nterminal; i++){
4997 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
4999 fclose(out);
5001 return;
5004 /* Reduce the size of the action tables, if possible, by making use
5005 ** of defaults.
5007 ** In this version, we take the most frequent REDUCE action and make
5008 ** it the default. Except, there is no default if the wildcard token
5009 ** is a possible look-ahead.
5011 void CompressTables(struct lemon *lemp)
5013 struct state *stp;
5014 struct action *ap, *ap2, *nextap;
5015 struct rule *rp, *rp2, *rbest;
5016 int nbest, n;
5017 int i;
5018 int usesWildcard;
5020 for(i=0; i<lemp->nstate; i++){
5021 stp = lemp->sorted[i];
5022 nbest = 0;
5023 rbest = 0;
5024 usesWildcard = 0;
5026 for(ap=stp->ap; ap; ap=ap->next){
5027 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
5028 usesWildcard = 1;
5030 if( ap->type!=REDUCE ) continue;
5031 rp = ap->x.rp;
5032 if( rp->lhsStart ) continue;
5033 if( rp==rbest ) continue;
5034 n = 1;
5035 for(ap2=ap->next; ap2; ap2=ap2->next){
5036 if( ap2->type!=REDUCE ) continue;
5037 rp2 = ap2->x.rp;
5038 if( rp2==rbest ) continue;
5039 if( rp2==rp ) n++;
5041 if( n>nbest ){
5042 nbest = n;
5043 rbest = rp;
5047 /* Do not make a default if the number of rules to default
5048 ** is not at least 1 or if the wildcard token is a possible
5049 ** lookahead.
5051 if( nbest<1 || usesWildcard ) continue;
5054 /* Combine matching REDUCE actions into a single default */
5055 for(ap=stp->ap; ap; ap=ap->next){
5056 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
5058 assert( ap );
5059 ap->sp = Symbol_new("{default}");
5060 for(ap=ap->next; ap; ap=ap->next){
5061 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
5063 stp->ap = Action_sort(stp->ap);
5065 for(ap=stp->ap; ap; ap=ap->next){
5066 if( ap->type==SHIFT ) break;
5067 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
5069 if( ap==0 ){
5070 stp->autoReduce = 1;
5071 stp->pDfltReduce = rbest;
5075 /* Make a second pass over all states and actions. Convert
5076 ** every action that is a SHIFT to an autoReduce state into
5077 ** a SHIFTREDUCE action.
5079 for(i=0; i<lemp->nstate; i++){
5080 stp = lemp->sorted[i];
5081 for(ap=stp->ap; ap; ap=ap->next){
5082 struct state *pNextState;
5083 if( ap->type!=SHIFT ) continue;
5084 pNextState = ap->x.stp;
5085 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
5086 ap->type = SHIFTREDUCE;
5087 ap->x.rp = pNextState->pDfltReduce;
5092 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
5093 ** (meaning that the SHIFTREDUCE will land back in the state where it
5094 ** started) and if there is no C-code associated with the reduce action,
5095 ** then we can go ahead and convert the action to be the same as the
5096 ** action for the RHS of the rule.
5098 for(i=0; i<lemp->nstate; i++){
5099 stp = lemp->sorted[i];
5100 for(ap=stp->ap; ap; ap=nextap){
5101 nextap = ap->next;
5102 if( ap->type!=SHIFTREDUCE ) continue;
5103 rp = ap->x.rp;
5104 if( rp->noCode==0 ) continue;
5105 if( rp->nrhs!=1 ) continue;
5106 #if 1
5107 /* Only apply this optimization to non-terminals. It would be OK to
5108 ** apply it to terminal symbols too, but that makes the parser tables
5109 ** larger. */
5110 if( ap->sp->index<lemp->nterminal ) continue;
5111 #endif
5112 /* If we reach this point, it means the optimization can be applied */
5113 nextap = ap;
5114 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
5115 assert( ap2!=0 );
5116 ap->spOpt = ap2->sp;
5117 ap->type = ap2->type;
5118 ap->x = ap2->x;
5125 ** Compare two states for sorting purposes. The smaller state is the
5126 ** one with the most non-terminal actions. If they have the same number
5127 ** of non-terminal actions, then the smaller is the one with the most
5128 ** token actions.
5130 static int stateResortCompare(const void *a, const void *b){
5131 const struct state *pA = *(const struct state**)a;
5132 const struct state *pB = *(const struct state**)b;
5133 int n;
5135 n = pB->nNtAct - pA->nNtAct;
5136 if( n==0 ){
5137 n = pB->nTknAct - pA->nTknAct;
5138 if( n==0 ){
5139 n = pB->statenum - pA->statenum;
5142 assert( n!=0 );
5143 return n;
5148 ** Renumber and resort states so that states with fewer choices
5149 ** occur at the end. Except, keep state 0 as the first state.
5151 void ResortStates(struct lemon *lemp)
5153 int i;
5154 struct state *stp;
5155 struct action *ap;
5157 for(i=0; i<lemp->nstate; i++){
5158 stp = lemp->sorted[i];
5159 stp->nTknAct = stp->nNtAct = 0;
5160 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
5161 stp->iTknOfst = NO_OFFSET;
5162 stp->iNtOfst = NO_OFFSET;
5163 for(ap=stp->ap; ap; ap=ap->next){
5164 int iAction = compute_action(lemp,ap);
5165 if( iAction>=0 ){
5166 if( ap->sp->index<lemp->nterminal ){
5167 stp->nTknAct++;
5168 }else if( ap->sp->index<lemp->nsymbol ){
5169 stp->nNtAct++;
5170 }else{
5171 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
5172 stp->iDfltReduce = iAction;
5177 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
5178 stateResortCompare);
5179 for(i=0; i<lemp->nstate; i++){
5180 lemp->sorted[i]->statenum = i;
5182 lemp->nxstate = lemp->nstate;
5183 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
5184 lemp->nxstate--;
5189 /***************** From the file "set.c" ************************************/
5191 ** Set manipulation routines for the LEMON parser generator.
5194 static int size = 0;
5196 /* Set the set size */
5197 void SetSize(int n)
5199 size = n+1;
5202 /* Allocate a new set */
5203 char *SetNew(void){
5204 char *s;
5205 s = (char*)calloc( size, 1);
5206 if( s==0 ){
5207 memory_error();
5209 return s;
5212 /* Deallocate a set */
5213 void SetFree(char *s)
5215 free(s);
5218 /* Add a new element to the set. Return TRUE if the element was added
5219 ** and FALSE if it was already there. */
5220 int SetAdd(char *s, int e)
5222 int rv;
5223 assert( e>=0 && e<size );
5224 rv = s[e];
5225 s[e] = 1;
5226 return !rv;
5229 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
5230 int SetUnion(char *s1, char *s2)
5232 int i, progress;
5233 progress = 0;
5234 for(i=0; i<size; i++){
5235 if( s2[i]==0 ) continue;
5236 if( s1[i]==0 ){
5237 progress = 1;
5238 s1[i] = 1;
5241 return progress;
5243 /********************** From the file "table.c" ****************************/
5245 ** All code in this file has been automatically generated
5246 ** from a specification in the file
5247 ** "table.q"
5248 ** by the associative array code building program "aagen".
5249 ** Do not edit this file! Instead, edit the specification
5250 ** file, then rerun aagen.
5253 ** Code for processing tables in the LEMON parser generator.
5256 PRIVATE unsigned strhash(const char *x)
5258 unsigned h = 0;
5259 while( *x ) h = h*13 + *(x++);
5260 return h;
5263 /* Works like strdup, sort of. Save a string in malloced memory, but
5264 ** keep strings in a table so that the same string is not in more
5265 ** than one place.
5267 const char *Strsafe(const char *y)
5269 const char *z;
5270 char *cpy;
5272 if( y==0 ) return 0;
5273 z = Strsafe_find(y);
5274 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
5275 lemon_strcpy(cpy,y);
5276 z = cpy;
5277 Strsafe_insert(z);
5279 MemoryCheck(z);
5280 return z;
5283 /* There is one instance of the following structure for each
5284 ** associative array of type "x1".
5286 struct s_x1 {
5287 int size; /* The number of available slots. */
5288 /* Must be a power of 2 greater than or */
5289 /* equal to 1 */
5290 int count; /* Number of currently slots filled */
5291 struct s_x1node *tbl; /* The data stored here */
5292 struct s_x1node **ht; /* Hash table for lookups */
5295 /* There is one instance of this structure for every data element
5296 ** in an associative array of type "x1".
5298 typedef struct s_x1node {
5299 const char *data; /* The data */
5300 struct s_x1node *next; /* Next entry with the same hash */
5301 struct s_x1node **from; /* Previous link */
5302 } x1node;
5304 /* There is only one instance of the array, which is the following */
5305 static struct s_x1 *x1a;
5307 /* Allocate a new associative array */
5308 void Strsafe_init(void){
5309 if( x1a ) return;
5310 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5311 if( x1a ){
5312 x1a->size = 1024;
5313 x1a->count = 0;
5314 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
5315 if( x1a->tbl==0 ){
5316 free(x1a);
5317 x1a = 0;
5318 }else{
5319 int i;
5320 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5321 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5325 /* Insert a new record into the array. Return TRUE if successful.
5326 ** Prior data with the same key is NOT overwritten */
5327 int Strsafe_insert(const char *data)
5329 x1node *np;
5330 unsigned h;
5331 unsigned ph;
5333 if( x1a==0 ) return 0;
5334 ph = strhash(data);
5335 h = ph & (x1a->size-1);
5336 np = x1a->ht[h];
5337 while( np ){
5338 if( strcmp(np->data,data)==0 ){
5339 /* An existing entry with the same key is found. */
5340 /* Fail because overwrite is not allows. */
5341 return 0;
5343 np = np->next;
5345 if( x1a->count>=x1a->size ){
5346 /* Need to make the hash table bigger */
5347 int i,arrSize;
5348 struct s_x1 array;
5349 array.size = arrSize = x1a->size*2;
5350 array.count = x1a->count;
5351 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
5352 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5353 array.ht = (x1node**)&(array.tbl[arrSize]);
5354 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5355 for(i=0; i<x1a->count; i++){
5356 x1node *oldnp, *newnp;
5357 oldnp = &(x1a->tbl[i]);
5358 h = strhash(oldnp->data) & (arrSize-1);
5359 newnp = &(array.tbl[i]);
5360 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5361 newnp->next = array.ht[h];
5362 newnp->data = oldnp->data;
5363 newnp->from = &(array.ht[h]);
5364 array.ht[h] = newnp;
5366 /* free(x1a->tbl); // This program was originally for 16-bit machines.
5367 ** Don't worry about freeing memory on modern platforms. */
5368 *x1a = array;
5370 /* Insert the new data */
5371 h = ph & (x1a->size-1);
5372 np = &(x1a->tbl[x1a->count++]);
5373 np->data = data;
5374 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5375 np->next = x1a->ht[h];
5376 x1a->ht[h] = np;
5377 np->from = &(x1a->ht[h]);
5378 return 1;
5381 /* Return a pointer to data assigned to the given key. Return NULL
5382 ** if no such key. */
5383 const char *Strsafe_find(const char *key)
5385 unsigned h;
5386 x1node *np;
5388 if( x1a==0 ) return 0;
5389 h = strhash(key) & (x1a->size-1);
5390 np = x1a->ht[h];
5391 while( np ){
5392 if( strcmp(np->data,key)==0 ) break;
5393 np = np->next;
5395 return np ? np->data : 0;
5398 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5399 ** Create a new symbol if this is the first time "x" has been seen.
5401 struct symbol *Symbol_new(const char *x)
5403 struct symbol *sp;
5405 sp = Symbol_find(x);
5406 if( sp==0 ){
5407 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
5408 MemoryCheck(sp);
5409 sp->name = Strsafe(x);
5410 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
5411 sp->rule = 0;
5412 sp->fallback = 0;
5413 sp->prec = -1;
5414 sp->assoc = UNK;
5415 sp->firstset = 0;
5416 sp->lambda = LEMON_FALSE;
5417 sp->destructor = 0;
5418 sp->destLineno = 0;
5419 sp->datatype = 0;
5420 sp->useCnt = 0;
5421 Symbol_insert(sp,sp->name);
5423 sp->useCnt++;
5424 return sp;
5427 /* Compare two symbols for sorting purposes. Return negative,
5428 ** zero, or positive if a is less then, equal to, or greater
5429 ** than b.
5431 ** Symbols that begin with upper case letters (terminals or tokens)
5432 ** must sort before symbols that begin with lower case letters
5433 ** (non-terminals). And MULTITERMINAL symbols (created using the
5434 ** %token_class directive) must sort at the very end. Other than
5435 ** that, the order does not matter.
5437 ** We find experimentally that leaving the symbols in their original
5438 ** order (the order they appeared in the grammar file) gives the
5439 ** smallest parser tables in SQLite.
5441 int Symbolcmpp(const void *_a, const void *_b)
5443 const struct symbol *a = *(const struct symbol **) _a;
5444 const struct symbol *b = *(const struct symbol **) _b;
5445 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5446 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5447 return i1==i2 ? a->index - b->index : i1 - i2;
5450 /* There is one instance of the following structure for each
5451 ** associative array of type "x2".
5453 struct s_x2 {
5454 int size; /* The number of available slots. */
5455 /* Must be a power of 2 greater than or */
5456 /* equal to 1 */
5457 int count; /* Number of currently slots filled */
5458 struct s_x2node *tbl; /* The data stored here */
5459 struct s_x2node **ht; /* Hash table for lookups */
5462 /* There is one instance of this structure for every data element
5463 ** in an associative array of type "x2".
5465 typedef struct s_x2node {
5466 struct symbol *data; /* The data */
5467 const char *key; /* The key */
5468 struct s_x2node *next; /* Next entry with the same hash */
5469 struct s_x2node **from; /* Previous link */
5470 } x2node;
5472 /* There is only one instance of the array, which is the following */
5473 static struct s_x2 *x2a;
5475 /* Allocate a new associative array */
5476 void Symbol_init(void){
5477 if( x2a ) return;
5478 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5479 if( x2a ){
5480 x2a->size = 128;
5481 x2a->count = 0;
5482 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
5483 if( x2a->tbl==0 ){
5484 free(x2a);
5485 x2a = 0;
5486 }else{
5487 int i;
5488 x2a->ht = (x2node**)&(x2a->tbl[128]);
5489 for(i=0; i<128; i++) x2a->ht[i] = 0;
5493 /* Insert a new record into the array. Return TRUE if successful.
5494 ** Prior data with the same key is NOT overwritten */
5495 int Symbol_insert(struct symbol *data, const char *key)
5497 x2node *np;
5498 unsigned h;
5499 unsigned ph;
5501 if( x2a==0 ) return 0;
5502 ph = strhash(key);
5503 h = ph & (x2a->size-1);
5504 np = x2a->ht[h];
5505 while( np ){
5506 if( strcmp(np->key,key)==0 ){
5507 /* An existing entry with the same key is found. */
5508 /* Fail because overwrite is not allows. */
5509 return 0;
5511 np = np->next;
5513 if( x2a->count>=x2a->size ){
5514 /* Need to make the hash table bigger */
5515 int i,arrSize;
5516 struct s_x2 array;
5517 array.size = arrSize = x2a->size*2;
5518 array.count = x2a->count;
5519 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
5520 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5521 array.ht = (x2node**)&(array.tbl[arrSize]);
5522 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5523 for(i=0; i<x2a->count; i++){
5524 x2node *oldnp, *newnp;
5525 oldnp = &(x2a->tbl[i]);
5526 h = strhash(oldnp->key) & (arrSize-1);
5527 newnp = &(array.tbl[i]);
5528 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5529 newnp->next = array.ht[h];
5530 newnp->key = oldnp->key;
5531 newnp->data = oldnp->data;
5532 newnp->from = &(array.ht[h]);
5533 array.ht[h] = newnp;
5535 /* free(x2a->tbl); // This program was originally written for 16-bit
5536 ** machines. Don't worry about freeing this trivial amount of memory
5537 ** on modern platforms. Just leak it. */
5538 *x2a = array;
5540 /* Insert the new data */
5541 h = ph & (x2a->size-1);
5542 np = &(x2a->tbl[x2a->count++]);
5543 np->key = key;
5544 np->data = data;
5545 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5546 np->next = x2a->ht[h];
5547 x2a->ht[h] = np;
5548 np->from = &(x2a->ht[h]);
5549 return 1;
5552 /* Return a pointer to data assigned to the given key. Return NULL
5553 ** if no such key. */
5554 struct symbol *Symbol_find(const char *key)
5556 unsigned h;
5557 x2node *np;
5559 if( x2a==0 ) return 0;
5560 h = strhash(key) & (x2a->size-1);
5561 np = x2a->ht[h];
5562 while( np ){
5563 if( strcmp(np->key,key)==0 ) break;
5564 np = np->next;
5566 return np ? np->data : 0;
5569 /* Return the n-th data. Return NULL if n is out of range. */
5570 struct symbol *Symbol_Nth(int n)
5572 struct symbol *data;
5573 if( x2a && n>0 && n<=x2a->count ){
5574 data = x2a->tbl[n-1].data;
5575 }else{
5576 data = 0;
5578 return data;
5581 /* Return the size of the array */
5582 int Symbol_count()
5584 return x2a ? x2a->count : 0;
5587 /* Return an array of pointers to all data in the table.
5588 ** The array is obtained from malloc. Return NULL if memory allocation
5589 ** problems, or if the array is empty. */
5590 struct symbol **Symbol_arrayof()
5592 struct symbol **array;
5593 int i,arrSize;
5594 if( x2a==0 ) return 0;
5595 arrSize = x2a->count;
5596 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
5597 if( array ){
5598 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
5600 return array;
5603 /* Compare two configurations */
5604 int Configcmp(const char *_a,const char *_b)
5606 const struct config *a = (struct config *) _a;
5607 const struct config *b = (struct config *) _b;
5608 int x;
5609 x = a->rp->index - b->rp->index;
5610 if( x==0 ) x = a->dot - b->dot;
5611 return x;
5614 /* Compare two states */
5615 PRIVATE int statecmp(struct config *a, struct config *b)
5617 int rc;
5618 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5619 rc = a->rp->index - b->rp->index;
5620 if( rc==0 ) rc = a->dot - b->dot;
5622 if( rc==0 ){
5623 if( a ) rc = 1;
5624 if( b ) rc = -1;
5626 return rc;
5629 /* Hash a state */
5630 PRIVATE unsigned statehash(struct config *a)
5632 unsigned h=0;
5633 while( a ){
5634 h = h*571 + a->rp->index*37 + a->dot;
5635 a = a->bp;
5637 return h;
5640 /* Allocate a new state structure */
5641 struct state *State_new()
5643 struct state *newstate;
5644 newstate = (struct state *)calloc(1, sizeof(struct state) );
5645 MemoryCheck(newstate);
5646 return newstate;
5649 /* There is one instance of the following structure for each
5650 ** associative array of type "x3".
5652 struct s_x3 {
5653 int size; /* The number of available slots. */
5654 /* Must be a power of 2 greater than or */
5655 /* equal to 1 */
5656 int count; /* Number of currently slots filled */
5657 struct s_x3node *tbl; /* The data stored here */
5658 struct s_x3node **ht; /* Hash table for lookups */
5661 /* There is one instance of this structure for every data element
5662 ** in an associative array of type "x3".
5664 typedef struct s_x3node {
5665 struct state *data; /* The data */
5666 struct config *key; /* The key */
5667 struct s_x3node *next; /* Next entry with the same hash */
5668 struct s_x3node **from; /* Previous link */
5669 } x3node;
5671 /* There is only one instance of the array, which is the following */
5672 static struct s_x3 *x3a;
5674 /* Allocate a new associative array */
5675 void State_init(void){
5676 if( x3a ) return;
5677 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5678 if( x3a ){
5679 x3a->size = 128;
5680 x3a->count = 0;
5681 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
5682 if( x3a->tbl==0 ){
5683 free(x3a);
5684 x3a = 0;
5685 }else{
5686 int i;
5687 x3a->ht = (x3node**)&(x3a->tbl[128]);
5688 for(i=0; i<128; i++) x3a->ht[i] = 0;
5692 /* Insert a new record into the array. Return TRUE if successful.
5693 ** Prior data with the same key is NOT overwritten */
5694 int State_insert(struct state *data, struct config *key)
5696 x3node *np;
5697 unsigned h;
5698 unsigned ph;
5700 if( x3a==0 ) return 0;
5701 ph = statehash(key);
5702 h = ph & (x3a->size-1);
5703 np = x3a->ht[h];
5704 while( np ){
5705 if( statecmp(np->key,key)==0 ){
5706 /* An existing entry with the same key is found. */
5707 /* Fail because overwrite is not allows. */
5708 return 0;
5710 np = np->next;
5712 if( x3a->count>=x3a->size ){
5713 /* Need to make the hash table bigger */
5714 int i,arrSize;
5715 struct s_x3 array;
5716 array.size = arrSize = x3a->size*2;
5717 array.count = x3a->count;
5718 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
5719 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5720 array.ht = (x3node**)&(array.tbl[arrSize]);
5721 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5722 for(i=0; i<x3a->count; i++){
5723 x3node *oldnp, *newnp;
5724 oldnp = &(x3a->tbl[i]);
5725 h = statehash(oldnp->key) & (arrSize-1);
5726 newnp = &(array.tbl[i]);
5727 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5728 newnp->next = array.ht[h];
5729 newnp->key = oldnp->key;
5730 newnp->data = oldnp->data;
5731 newnp->from = &(array.ht[h]);
5732 array.ht[h] = newnp;
5734 free(x3a->tbl);
5735 *x3a = array;
5737 /* Insert the new data */
5738 h = ph & (x3a->size-1);
5739 np = &(x3a->tbl[x3a->count++]);
5740 np->key = key;
5741 np->data = data;
5742 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5743 np->next = x3a->ht[h];
5744 x3a->ht[h] = np;
5745 np->from = &(x3a->ht[h]);
5746 return 1;
5749 /* Return a pointer to data assigned to the given key. Return NULL
5750 ** if no such key. */
5751 struct state *State_find(struct config *key)
5753 unsigned h;
5754 x3node *np;
5756 if( x3a==0 ) return 0;
5757 h = statehash(key) & (x3a->size-1);
5758 np = x3a->ht[h];
5759 while( np ){
5760 if( statecmp(np->key,key)==0 ) break;
5761 np = np->next;
5763 return np ? np->data : 0;
5766 /* Return an array of pointers to all data in the table.
5767 ** The array is obtained from malloc. Return NULL if memory allocation
5768 ** problems, or if the array is empty. */
5769 struct state **State_arrayof(void)
5771 struct state **array;
5772 int i,arrSize;
5773 if( x3a==0 ) return 0;
5774 arrSize = x3a->count;
5775 array = (struct state **)calloc(arrSize, sizeof(struct state *));
5776 if( array ){
5777 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
5779 return array;
5782 /* Hash a configuration */
5783 PRIVATE unsigned confighash(struct config *a)
5785 unsigned h=0;
5786 h = h*571 + a->rp->index*37 + a->dot;
5787 return h;
5790 /* There is one instance of the following structure for each
5791 ** associative array of type "x4".
5793 struct s_x4 {
5794 int size; /* The number of available slots. */
5795 /* Must be a power of 2 greater than or */
5796 /* equal to 1 */
5797 int count; /* Number of currently slots filled */
5798 struct s_x4node *tbl; /* The data stored here */
5799 struct s_x4node **ht; /* Hash table for lookups */
5802 /* There is one instance of this structure for every data element
5803 ** in an associative array of type "x4".
5805 typedef struct s_x4node {
5806 struct config *data; /* The data */
5807 struct s_x4node *next; /* Next entry with the same hash */
5808 struct s_x4node **from; /* Previous link */
5809 } x4node;
5811 /* There is only one instance of the array, which is the following */
5812 static struct s_x4 *x4a;
5814 /* Allocate a new associative array */
5815 void Configtable_init(void){
5816 if( x4a ) return;
5817 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5818 if( x4a ){
5819 x4a->size = 64;
5820 x4a->count = 0;
5821 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
5822 if( x4a->tbl==0 ){
5823 free(x4a);
5824 x4a = 0;
5825 }else{
5826 int i;
5827 x4a->ht = (x4node**)&(x4a->tbl[64]);
5828 for(i=0; i<64; i++) x4a->ht[i] = 0;
5832 /* Insert a new record into the array. Return TRUE if successful.
5833 ** Prior data with the same key is NOT overwritten */
5834 int Configtable_insert(struct config *data)
5836 x4node *np;
5837 unsigned h;
5838 unsigned ph;
5840 if( x4a==0 ) return 0;
5841 ph = confighash(data);
5842 h = ph & (x4a->size-1);
5843 np = x4a->ht[h];
5844 while( np ){
5845 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
5846 /* An existing entry with the same key is found. */
5847 /* Fail because overwrite is not allows. */
5848 return 0;
5850 np = np->next;
5852 if( x4a->count>=x4a->size ){
5853 /* Need to make the hash table bigger */
5854 int i,arrSize;
5855 struct s_x4 array;
5856 array.size = arrSize = x4a->size*2;
5857 array.count = x4a->count;
5858 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
5859 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
5860 array.ht = (x4node**)&(array.tbl[arrSize]);
5861 for(i=0; i<arrSize; i++) array.ht[i] = 0;
5862 for(i=0; i<x4a->count; i++){
5863 x4node *oldnp, *newnp;
5864 oldnp = &(x4a->tbl[i]);
5865 h = confighash(oldnp->data) & (arrSize-1);
5866 newnp = &(array.tbl[i]);
5867 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5868 newnp->next = array.ht[h];
5869 newnp->data = oldnp->data;
5870 newnp->from = &(array.ht[h]);
5871 array.ht[h] = newnp;
5873 /* free(x4a->tbl); // This code was originall written for 16-bit machines.
5874 ** on modern machines, don't worry about freeing this trival amount of
5875 ** memory. */
5876 *x4a = array;
5878 /* Insert the new data */
5879 h = ph & (x4a->size-1);
5880 np = &(x4a->tbl[x4a->count++]);
5881 np->data = data;
5882 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5883 np->next = x4a->ht[h];
5884 x4a->ht[h] = np;
5885 np->from = &(x4a->ht[h]);
5886 return 1;
5889 /* Return a pointer to data assigned to the given key. Return NULL
5890 ** if no such key. */
5891 struct config *Configtable_find(struct config *key)
5893 int h;
5894 x4node *np;
5896 if( x4a==0 ) return 0;
5897 h = confighash(key) & (x4a->size-1);
5898 np = x4a->ht[h];
5899 while( np ){
5900 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
5901 np = np->next;
5903 return np ? np->data : 0;
5906 /* Remove all data from the table. Pass each data to the function "f"
5907 ** as it is removed. ("f" may be null to avoid this step.) */
5908 void Configtable_clear(int(*f)(struct config *))
5910 int i;
5911 if( x4a==0 || x4a->count==0 ) return;
5912 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5913 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5914 x4a->count = 0;
5915 return;