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.
7 ** The author of this program disclaims copyright.
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))
25 # if defined(_WIN32) || defined(WIN32)
34 extern int access(const char *path
, int mode
);
42 /* #define PRIVATE static */
46 #define MAXRHS 5 /* Set low to exercise exception code */
51 extern void memory_error();
52 static int showPrecedenceConflict
= 0;
53 static char *msort(char*,char**,int(*)(const char*,const char*));
56 ** Compilers are getting increasingly pedantic about type conversions
57 ** as C evolves ever closer to Ada.... To work around the latest problems
58 ** we have to define the following variant of strlen().
60 #define lemonStrlen(X) ((int)strlen(X))
63 ** Header on the linked list of memory allocations.
65 typedef struct MemChunk MemChunk
;
69 /* Actually memory follows */
73 ** Global linked list of all memory allocations.
75 static MemChunk
*memChunkList
= 0;
78 ** Wrappers around malloc(), calloc(), realloc() and free().
80 ** All memory allocations are kept on a doubly-linked list. The
81 ** lemon_free_all() function can be called prior to exit to clean
82 ** up any memory leaks.
84 ** This is not necessary. But compilers and getting increasingly
85 ** fussy about memory leaks, even in command-line programs like Lemon
86 ** where they do not matter. So this code is provided to hush the
89 static void *lemon_malloc(size_t nByte
){
91 if( nByte
<0 ) return 0;
92 p
= malloc( nByte
+ sizeof(MemChunk
) );
94 fprintf(stderr
, "Out of memory. Failed to allocate %lld bytes.\n",
95 (long long int)nByte
);
98 p
->pNext
= memChunkList
;
103 static void *lemon_calloc(size_t nElem
, size_t sz
){
104 void *p
= lemon_malloc(nElem
*sz
);
105 memset(p
, 0, nElem
*sz
);
108 static void lemon_free(void *pOld
){
110 MemChunk
*p
= (MemChunk
*)pOld
;
112 memset(pOld
, 0, p
->sz
);
115 static void *lemon_realloc(void *pOld
, size_t nNew
){
118 if( pOld
==0 ) return lemon_malloc(nNew
);
121 if( p
->sz
>=nNew
) return pOld
;
122 pNew
= lemon_malloc( nNew
);
123 memcpy(pNew
, pOld
, p
->sz
);
127 /* Free all outstanding memory allocations.
128 ** Do this right before exiting.
130 static void lemon_free_all(void){
131 while( memChunkList
){
132 MemChunk
*pNext
= memChunkList
->pNext
;
133 free( memChunkList
);
134 memChunkList
= pNext
;
139 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
140 ** saying they are unsafe. So we define our own versions of those routines too.
142 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
143 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
144 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
145 ** buffer, making sure the buffer is always zero-terminated.
147 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
148 ** a few simply conversions:
155 static void lemon_addtext(
156 char *zBuf
, /* The buffer to which text is added */
157 int *pnUsed
, /* Slots of the buffer used so far */
158 const char *zIn
, /* Text to add */
159 int nIn
, /* Bytes of text to add. -1 to use strlen() */
160 int iWidth
/* Field width. Negative to left justify */
162 if( nIn
<0 ) for(nIn
=0; zIn
[nIn
]; nIn
++){}
163 while( iWidth
>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
--; }
165 memcpy(&zBuf
[*pnUsed
], zIn
, nIn
);
167 while( (-iWidth
)>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
++; }
170 static int lemon_vsprintf(char *str
, const char *zFormat
, va_list ap
){
176 for(i
=j
=0; (c
= zFormat
[i
])!=0; i
++){
179 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
181 if( ISDIGIT(c
) || (c
=='-' && ISDIGIT(zFormat
[i
+1])) ){
183 while( ISDIGIT(zFormat
[i
]) ) iWidth
= iWidth
*10 + zFormat
[i
++] - '0';
184 if( c
=='-' ) iWidth
= -iWidth
;
188 int v
= va_arg(ap
, int);
190 lemon_addtext(str
, &nUsed
, "-", 1, iWidth
);
193 lemon_addtext(str
, &nUsed
, "0", 1, iWidth
);
198 zTemp
[sizeof(zTemp
)-k
] = (v
%10) + '0';
201 lemon_addtext(str
, &nUsed
, &zTemp
[sizeof(zTemp
)-k
], k
, iWidth
);
203 z
= va_arg(ap
, const char*);
204 lemon_addtext(str
, &nUsed
, z
, -1, iWidth
);
205 }else if( c
=='.' && memcmp(&zFormat
[i
], ".*s", 3)==0 ){
208 z
= va_arg(ap
, const char*);
209 lemon_addtext(str
, &nUsed
, z
, k
, iWidth
);
211 lemon_addtext(str
, &nUsed
, "%", 1, 0);
213 fprintf(stderr
, "illegal format\n");
219 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
222 static int lemon_sprintf(char *str
, const char *format
, ...){
225 va_start(ap
, format
);
226 rc
= lemon_vsprintf(str
, format
, ap
);
230 static void lemon_strcpy(char *dest
, const char *src
){
231 while( (*(dest
++) = *(src
++))!=0 ){}
233 static void lemon_strcat(char *dest
, const char *src
){
234 while( *dest
) dest
++;
235 lemon_strcpy(dest
, src
);
239 /* a few forward declarations... */
244 static struct action
*Action_new(void);
245 static struct action
*Action_sort(struct action
*);
247 /********** From the file "build.h" ************************************/
248 void FindRulePrecedences(struct lemon
*);
249 void FindFirstSets(struct lemon
*);
250 void FindStates(struct lemon
*);
251 void FindLinks(struct lemon
*);
252 void FindFollowSets(struct lemon
*);
253 void FindActions(struct lemon
*);
255 /********* From the file "configlist.h" *********************************/
256 void Configlist_init(void);
257 struct config
*Configlist_add(struct rule
*, int);
258 struct config
*Configlist_addbasis(struct rule
*, int);
259 void Configlist_closure(struct lemon
*);
260 void Configlist_sort(void);
261 void Configlist_sortbasis(void);
262 struct config
*Configlist_return(void);
263 struct config
*Configlist_basis(void);
264 void Configlist_eat(struct config
*);
265 void Configlist_reset(void);
267 /********* From the file "error.h" ***************************************/
268 void ErrorMsg(const char *, int,const char *, ...);
270 /****** From the file "option.h" ******************************************/
271 enum option_type
{ OPT_FLAG
=1, OPT_INT
, OPT_DBL
, OPT_STR
,
272 OPT_FFLAG
, OPT_FINT
, OPT_FDBL
, OPT_FSTR
};
274 enum option_type type
;
279 int OptInit(char**,struct s_options
*,FILE*);
285 /******** From the file "parse.h" *****************************************/
286 void Parse(struct lemon
*lemp
);
288 /********* From the file "plink.h" ***************************************/
289 struct plink
*Plink_new(void);
290 void Plink_add(struct plink
**, struct config
*);
291 void Plink_copy(struct plink
**, struct plink
*);
292 void Plink_delete(struct plink
*);
294 /********** From the file "report.h" *************************************/
295 void Reprint(struct lemon
*);
296 void ReportOutput(struct lemon
*);
297 void ReportTable(struct lemon
*, int, int);
298 void ReportHeader(struct lemon
*);
299 void CompressTables(struct lemon
*);
300 void ResortStates(struct lemon
*);
302 /********** From the file "set.h" ****************************************/
303 void SetSize(int); /* All sets will be of size N */
304 char *SetNew(void); /* A new set for element 0..N */
305 void SetFree(char*); /* Deallocate a set */
306 int SetAdd(char*,int); /* Add element to a set */
307 int SetUnion(char *,char *); /* A <- A U B, thru element N */
308 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
310 /********** From the file "struct.h" *************************************/
312 ** Principal data structures for the LEMON parser generator.
315 typedef enum {LEMON_FALSE
=0, LEMON_TRUE
} Boolean
;
317 /* Symbols (terminals and nonterminals) of the grammar are stored
318 ** in the following: */
331 const char *name
; /* Name of the symbol */
332 int index
; /* Index number for this symbol */
333 enum symbol_type type
; /* Symbols are all either TERMINALS or NTs */
334 struct rule
*rule
; /* Linked list of rules of this (if an NT) */
335 struct symbol
*fallback
; /* fallback token in case this token doesn't parse */
336 int prec
; /* Precedence if defined (-1 otherwise) */
337 enum e_assoc assoc
; /* Associativity if precedence is defined */
338 char *firstset
; /* First-set for all rules of this symbol */
339 Boolean lambda
; /* True if NT and can generate an empty string */
340 int useCnt
; /* Number of times used */
341 char *destructor
; /* Code which executes whenever this symbol is
342 ** popped from the stack during error processing */
343 int destLineno
; /* Line number for start of destructor. Set to
344 ** -1 for duplicate destructors. */
345 char *datatype
; /* The data type of information held by this
346 ** object. Only used if type==NONTERMINAL */
347 int dtnum
; /* The data type number. In the parser, the value
348 ** stack is a union. The .yy%d element of this
349 ** union is the correct data type for this object */
350 int bContent
; /* True if this symbol ever carries content - if
351 ** it is ever more than just syntax */
352 /* The following fields are used by MULTITERMINALs only */
353 int nsubsym
; /* Number of constituent symbols in the MULTI */
354 struct symbol
**subsym
; /* Array of constituent symbols */
357 /* Each production rule in the grammar is stored in the following
360 struct symbol
*lhs
; /* Left-hand side of the rule */
361 const char *lhsalias
; /* Alias for the LHS (NULL if none) */
362 int lhsStart
; /* True if left-hand side is the start symbol */
363 int ruleline
; /* Line number for the rule */
364 int nrhs
; /* Number of RHS symbols */
365 struct symbol
**rhs
; /* The RHS symbols */
366 const char **rhsalias
; /* An alias for each RHS symbol (NULL if none) */
367 int line
; /* Line number at which code begins */
368 const char *code
; /* The code executed when this rule is reduced */
369 const char *codePrefix
; /* Setup code before code[] above */
370 const char *codeSuffix
; /* Breakdown code after code[] above */
371 struct symbol
*precsym
; /* Precedence symbol for this rule */
372 int index
; /* An index number for this rule */
373 int iRule
; /* Rule number as used in the generated tables */
374 Boolean noCode
; /* True if this rule has no associated C code */
375 Boolean codeEmitted
; /* True if the code has been emitted already */
376 Boolean canReduce
; /* True if this rule is ever reduced */
377 Boolean doesReduce
; /* Reduce actions occur after optimization */
378 Boolean neverReduce
; /* Reduce is theoretically possible, but prevented
379 ** by actions or other outside implementation */
380 struct rule
*nextlhs
; /* Next rule with the same LHS */
381 struct rule
*next
; /* Next rule in the global list */
384 /* A configuration is a production rule of the grammar together with
385 ** a mark (dot) showing how much of that rule has been processed so far.
386 ** Configurations also contain a follow-set which is a list of terminal
387 ** symbols which are allowed to immediately follow the end of the rule.
388 ** Every configuration is recorded as an instance of the following: */
394 struct rule
*rp
; /* The rule upon which the configuration is based */
395 int dot
; /* The parse point */
396 char *fws
; /* Follow-set for this configuration only */
397 struct plink
*fplp
; /* Follow-set forward propagation links */
398 struct plink
*bplp
; /* Follow-set backwards propagation links */
399 struct state
*stp
; /* Pointer to state which contains this */
400 enum cfgstatus status
; /* used during followset and shift computations */
401 struct config
*next
; /* Next configuration in the state */
402 struct config
*bp
; /* The next basis configuration */
410 SSCONFLICT
, /* A shift/shift conflict */
411 SRCONFLICT
, /* Was a reduce, but part of a conflict */
412 RRCONFLICT
, /* Was a reduce, but part of a conflict */
413 SH_RESOLVED
, /* Was a shift. Precedence resolved conflict */
414 RD_RESOLVED
, /* Was reduce. Precedence resolved conflict */
415 NOT_USED
, /* Deleted by compression */
416 SHIFTREDUCE
/* Shift first, then reduce */
419 /* Every shift or reduce operation is stored as one of the following */
421 struct symbol
*sp
; /* The look-ahead symbol */
424 struct state
*stp
; /* The new state, if a shift */
425 struct rule
*rp
; /* The rule, if a reduce */
427 struct symbol
*spOpt
; /* SHIFTREDUCE optimization to this symbol */
428 struct action
*next
; /* Next action for this state */
429 struct action
*collide
; /* Next action with the same hash */
432 /* Each state of the generated parser's finite state machine
433 ** is encoded as an instance of the following structure. */
435 struct config
*bp
; /* The basis configurations for this state */
436 struct config
*cfp
; /* All configurations in this set */
437 int statenum
; /* Sequential number for this state */
438 struct action
*ap
; /* List of actions for this state */
439 int nTknAct
, nNtAct
; /* Number of actions on terminals and nonterminals */
440 int iTknOfst
, iNtOfst
; /* yy_action[] offset for terminals and nonterms */
441 int iDfltReduce
; /* Default action is to REDUCE by this rule */
442 struct rule
*pDfltReduce
;/* The default REDUCE rule. */
443 int autoReduce
; /* True if this is an auto-reduce state */
445 #define NO_OFFSET (-2147483647)
447 /* A followset propagation link indicates that the contents of one
448 ** configuration followset should be propagated to another whenever
449 ** the first changes. */
451 struct config
*cfp
; /* The configuration to which linked */
452 struct plink
*next
; /* The next propagate link */
455 /* The state vector for the entire parser generator is recorded as
456 ** follows. (LEMON uses no global variables and makes little use of
457 ** static variables. Fields in the following structure can be thought
458 ** of as begin global variables in the program.) */
460 struct state
**sorted
; /* Table of states sorted by state number */
461 struct rule
*rule
; /* List of all rules */
462 struct rule
*startRule
; /* First rule */
463 int nstate
; /* Number of states */
464 int nxstate
; /* nstate with tail degenerate states removed */
465 int nrule
; /* Number of rules */
466 int nruleWithAction
; /* Number of rules with actions */
467 int nsymbol
; /* Number of terminal and nonterminal symbols */
468 int nterminal
; /* Number of terminal symbols */
469 int minShiftReduce
; /* Minimum shift-reduce action value */
470 int errAction
; /* Error action value */
471 int accAction
; /* Accept action value */
472 int noAction
; /* No-op action value */
473 int minReduce
; /* Minimum reduce action */
474 int maxAction
; /* Maximum action value of any kind */
475 struct symbol
**symbols
; /* Sorted array of pointers to symbols */
476 int errorcnt
; /* Number of errors */
477 struct symbol
*errsym
; /* The error symbol */
478 struct symbol
*wildcard
; /* Token that matches anything */
479 char *name
; /* Name of the generated parser */
480 char *arg
; /* Declaration of the 3rd argument to parser */
481 char *ctx
; /* Declaration of 2nd argument to constructor */
482 char *tokentype
; /* Type of terminal symbols in the parser stack */
483 char *vartype
; /* The default type of non-terminal symbols */
484 char *start
; /* Name of the start symbol for the grammar */
485 char *stacksize
; /* Size of the parser stack */
486 char *include
; /* Code to put at the start of the C file */
487 char *error
; /* Code to execute when an error is seen */
488 char *overflow
; /* Code to execute on a stack overflow */
489 char *failure
; /* Code to execute on parser failure */
490 char *accept
; /* Code to execute when the parser excepts */
491 char *extracode
; /* Code appended to the generated file */
492 char *tokendest
; /* Code to execute to destroy token data */
493 char *vardest
; /* Code for the default non-terminal destructor */
494 char *filename
; /* Name of the input file */
495 char *outname
; /* Name of the current output file */
496 char *tokenprefix
; /* A prefix added to token names in the .h file */
497 char *reallocFunc
; /* Function to use to allocate stack space */
498 char *freeFunc
; /* Function to use to free stack space */
499 int nconflict
; /* Number of parsing conflicts */
500 int nactiontab
; /* Number of entries in the yy_action[] table */
501 int nlookaheadtab
; /* Number of entries in yy_lookahead[] */
502 int tablesize
; /* Total table size of all tables in bytes */
503 int basisflag
; /* Print only basis configurations */
504 int printPreprocessed
; /* Show preprocessor output on stdout */
505 int has_fallback
; /* True if any %fallback is seen in the grammar */
506 int nolinenosflag
; /* True if #line statements should not be printed */
507 int argc
; /* Number of command-line arguments */
508 char **argv
; /* Command-line arguments */
511 #define MemoryCheck(X) if((X)==0){ \
512 extern void memory_error(); \
516 /**************** From the file "table.h" *********************************/
518 ** All code in this file has been automatically generated
519 ** from a specification in the file
521 ** by the associative array code building program "aagen".
522 ** Do not edit this file! Instead, edit the specification
523 ** file, then rerun aagen.
526 ** Code for processing tables in the LEMON parser generator.
528 /* Routines for handling a strings */
530 const char *Strsafe(const char *);
532 void Strsafe_init(void);
533 int Strsafe_insert(const char *);
534 const char *Strsafe_find(const char *);
536 /* Routines for handling symbols of the grammar */
538 struct symbol
*Symbol_new(const char *);
539 int Symbolcmpp(const void *, const void *);
540 void Symbol_init(void);
541 int Symbol_insert(struct symbol
*, const char *);
542 struct symbol
*Symbol_find(const char *);
543 struct symbol
*Symbol_Nth(int);
544 int Symbol_count(void);
545 struct symbol
**Symbol_arrayof(void);
547 /* Routines to manage the state table */
549 int Configcmp(const char *, const char *);
550 struct state
*State_new(void);
551 void State_init(void);
552 int State_insert(struct state
*, struct config
*);
553 struct state
*State_find(struct config
*);
554 struct state
**State_arrayof(void);
556 /* Routines used for efficiency in Configlist_add */
558 void Configtable_init(void);
559 int Configtable_insert(struct config
*);
560 struct config
*Configtable_find(struct config
*);
561 void Configtable_clear(int(*)(struct config
*));
563 /****************** From the file "action.c" *******************************/
565 ** Routines processing parser actions in the LEMON parser generator.
568 /* Allocate a new parser action */
569 static struct action
*Action_new(void){
570 static struct action
*actionfreelist
= 0;
571 struct action
*newaction
;
573 if( actionfreelist
==0 ){
576 actionfreelist
= (struct action
*)lemon_calloc(amt
, sizeof(struct action
));
577 if( actionfreelist
==0 ){
578 fprintf(stderr
,"Unable to allocate memory for a new parser action.");
581 for(i
=0; i
<amt
-1; i
++) actionfreelist
[i
].next
= &actionfreelist
[i
+1];
582 actionfreelist
[amt
-1].next
= 0;
584 newaction
= actionfreelist
;
585 actionfreelist
= actionfreelist
->next
;
589 /* Compare two actions for sorting purposes. Return negative, zero, or
590 ** positive if the first action is less than, equal to, or greater than
593 static int actioncmp(
598 rc
= ap1
->sp
->index
- ap2
->sp
->index
;
600 rc
= (int)ap1
->type
- (int)ap2
->type
;
602 if( rc
==0 && (ap1
->type
==REDUCE
|| ap1
->type
==SHIFTREDUCE
) ){
603 rc
= ap1
->x
.rp
->index
- ap2
->x
.rp
->index
;
606 rc
= (int) (ap2
- ap1
);
611 /* Sort parser actions */
612 static struct action
*Action_sort(
615 ap
= (struct action
*)msort((char *)ap
,(char **)&ap
->next
,
616 (int(*)(const char*,const char*))actioncmp
);
626 struct action
*newaction
;
627 newaction
= Action_new();
628 newaction
->next
= *app
;
630 newaction
->type
= type
;
632 newaction
->spOpt
= 0;
634 newaction
->x
.stp
= (struct state
*)arg
;
636 newaction
->x
.rp
= (struct rule
*)arg
;
639 /********************** New code to implement the "acttab" module ***********/
641 ** This module implements routines use to construct the yy_action[] table.
645 ** The state of the yy_action table under construction is an instance of
646 ** the following structure.
648 ** The yy_action table maps the pair (state_number, lookahead) into an
649 ** action_number. The table is an array of integers pairs. The state_number
650 ** determines an initial offset into the yy_action array. The lookahead
651 ** value is then added to this initial offset to get an index X into the
652 ** yy_action array. If the aAction[X].lookahead equals the value of the
653 ** of the lookahead input, then the value of the action_number output is
654 ** aAction[X].action. If the lookaheads do not match then the
655 ** default action for the state_number is returned.
657 ** All actions associated with a single state_number are first entered
658 ** into aLookahead[] using multiple calls to acttab_action(). Then the
659 ** actions for that single state_number are placed into the aAction[]
660 ** array with a single call to acttab_insert(). The acttab_insert() call
661 ** also resets the aLookahead[] array in preparation for the next
664 struct lookahead_action
{
665 int lookahead
; /* Value of the lookahead token */
666 int action
; /* Action to take on the given lookahead */
668 typedef struct acttab acttab
;
670 int nAction
; /* Number of used slots in aAction[] */
671 int nActionAlloc
; /* Slots allocated for aAction[] */
672 struct lookahead_action
673 *aAction
, /* The yy_action[] table under construction */
674 *aLookahead
; /* A single new transaction set */
675 int mnLookahead
; /* Minimum aLookahead[].lookahead */
676 int mnAction
; /* Action associated with mnLookahead */
677 int mxLookahead
; /* Maximum aLookahead[].lookahead */
678 int nLookahead
; /* Used slots in aLookahead[] */
679 int nLookaheadAlloc
; /* Slots allocated in aLookahead[] */
680 int nterminal
; /* Number of terminal symbols */
681 int nsymbol
; /* total number of symbols */
684 /* Return the number of entries in the yy_action table */
685 #define acttab_lookahead_size(X) ((X)->nAction)
687 /* The value for the N-th entry in yy_action */
688 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
690 /* The value for the N-th entry in yy_lookahead */
691 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
693 /* Free all memory associated with the given acttab */
694 void acttab_free(acttab
*p
){
695 lemon_free( p
->aAction
);
696 lemon_free( p
->aLookahead
);
700 /* Allocate a new acttab structure */
701 acttab
*acttab_alloc(int nsymbol
, int nterminal
){
702 acttab
*p
= (acttab
*) lemon_calloc( 1, sizeof(*p
) );
704 fprintf(stderr
,"Unable to allocate memory for a new acttab.");
707 memset(p
, 0, sizeof(*p
));
708 p
->nsymbol
= nsymbol
;
709 p
->nterminal
= nterminal
;
713 /* Add a new action to the current transaction set.
715 ** This routine is called once for each lookahead for a particular
718 void acttab_action(acttab
*p
, int lookahead
, int action
){
719 if( p
->nLookahead
>=p
->nLookaheadAlloc
){
720 p
->nLookaheadAlloc
+= 25;
721 p
->aLookahead
= (struct lookahead_action
*) lemon_realloc( p
->aLookahead
,
722 sizeof(p
->aLookahead
[0])*p
->nLookaheadAlloc
);
723 if( p
->aLookahead
==0 ){
724 fprintf(stderr
,"malloc failed\n");
728 if( p
->nLookahead
==0 ){
729 p
->mxLookahead
= lookahead
;
730 p
->mnLookahead
= lookahead
;
731 p
->mnAction
= action
;
733 if( p
->mxLookahead
<lookahead
) p
->mxLookahead
= lookahead
;
734 if( p
->mnLookahead
>lookahead
){
735 p
->mnLookahead
= lookahead
;
736 p
->mnAction
= action
;
739 p
->aLookahead
[p
->nLookahead
].lookahead
= lookahead
;
740 p
->aLookahead
[p
->nLookahead
].action
= action
;
745 ** Add the transaction set built up with prior calls to acttab_action()
746 ** into the current action table. Then reset the transaction set back
747 ** to an empty set in preparation for a new round of acttab_action() calls.
749 ** Return the offset into the action table of the new transaction.
751 ** If the makeItSafe parameter is true, then the offset is chosen so that
752 ** it is impossible to overread the yy_lookaside[] table regardless of
753 ** the lookaside token. This is done for the terminal symbols, as they
754 ** come from external inputs and can contain syntax errors. When makeItSafe
755 ** is false, there is more flexibility in selecting offsets, resulting in
756 ** a smaller table. For non-terminal symbols, which are never syntax errors,
757 ** makeItSafe can be false.
759 int acttab_insert(acttab
*p
, int makeItSafe
){
761 assert( p
->nLookahead
>0 );
763 /* Make sure we have enough space to hold the expanded action table
764 ** in the worst case. The worst case occurs if the transaction set
765 ** must be appended to the current action table
768 if( p
->nAction
+ n
>= p
->nActionAlloc
){
769 int oldAlloc
= p
->nActionAlloc
;
770 p
->nActionAlloc
= p
->nAction
+ n
+ p
->nActionAlloc
+ 20;
771 p
->aAction
= (struct lookahead_action
*) lemon_realloc( p
->aAction
,
772 sizeof(p
->aAction
[0])*p
->nActionAlloc
);
774 fprintf(stderr
,"malloc failed\n");
777 for(i
=oldAlloc
; i
<p
->nActionAlloc
; i
++){
778 p
->aAction
[i
].lookahead
= -1;
779 p
->aAction
[i
].action
= -1;
783 /* Scan the existing action table looking for an offset that is a
784 ** duplicate of the current transaction set. Fall out of the loop
785 ** if and when the duplicate is found.
787 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
789 end
= makeItSafe
? p
->mnLookahead
: 0;
790 for(i
=p
->nAction
-1; i
>=end
; i
--){
791 if( p
->aAction
[i
].lookahead
==p
->mnLookahead
){
792 /* All lookaheads and actions in the aLookahead[] transaction
793 ** must match against the candidate aAction[i] entry. */
794 if( p
->aAction
[i
].action
!=p
->mnAction
) continue;
795 for(j
=0; j
<p
->nLookahead
; j
++){
796 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
797 if( k
<0 || k
>=p
->nAction
) break;
798 if( p
->aLookahead
[j
].lookahead
!=p
->aAction
[k
].lookahead
) break;
799 if( p
->aLookahead
[j
].action
!=p
->aAction
[k
].action
) break;
801 if( j
<p
->nLookahead
) continue;
803 /* No possible lookahead value that is not in the aLookahead[]
804 ** transaction is allowed to match aAction[i] */
806 for(j
=0; j
<p
->nAction
; j
++){
807 if( p
->aAction
[j
].lookahead
<0 ) continue;
808 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) n
++;
810 if( n
==p
->nLookahead
){
811 break; /* An exact match is found at offset i */
816 /* If no existing offsets exactly match the current transaction, find an
817 ** an empty offset in the aAction[] table in which we can add the
818 ** aLookahead[] transaction.
821 /* Look for holes in the aAction[] table that fit the current
822 ** aLookahead[] transaction. Leave i set to the offset of the hole.
823 ** If no holes are found, i is left at p->nAction, which means the
824 ** transaction will be appended. */
825 i
= makeItSafe
? p
->mnLookahead
: 0;
826 for(; i
<p
->nActionAlloc
- p
->mxLookahead
; i
++){
827 if( p
->aAction
[i
].lookahead
<0 ){
828 for(j
=0; j
<p
->nLookahead
; j
++){
829 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
831 if( p
->aAction
[k
].lookahead
>=0 ) break;
833 if( j
<p
->nLookahead
) continue;
834 for(j
=0; j
<p
->nAction
; j
++){
835 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) break;
838 break; /* Fits in empty slots */
843 /* Insert transaction set at index i. */
846 for(j
=0; j
<p
->nLookahead
; j
++){
847 printf(" %d", p
->aLookahead
[j
].lookahead
);
849 printf(" inserted at %d\n", i
);
851 for(j
=0; j
<p
->nLookahead
; j
++){
852 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
853 p
->aAction
[k
] = p
->aLookahead
[j
];
854 if( k
>=p
->nAction
) p
->nAction
= k
+1;
856 if( makeItSafe
&& i
+p
->nterminal
>=p
->nAction
) p
->nAction
= i
+p
->nterminal
+1;
859 /* Return the offset that is added to the lookahead in order to get the
860 ** index into yy_action of the action */
861 return i
- p
->mnLookahead
;
865 ** Return the size of the action table without the trailing syntax error
868 int acttab_action_size(acttab
*p
){
870 while( n
>0 && p
->aAction
[n
-1].lookahead
<0 ){ n
--; }
874 /********************** From the file "build.c" *****************************/
876 ** Routines to construction the finite state machine for the LEMON
880 /* Find a precedence symbol of every rule in the grammar.
882 ** Those rules which have a precedence symbol coded in the input
883 ** grammar using the "[symbol]" construct will already have the
884 ** rp->precsym field filled. Other rules take as their precedence
885 ** symbol the first RHS symbol with a defined precedence. If there
886 ** are not RHS symbols with a defined precedence, the precedence
887 ** symbol field is left blank.
889 void FindRulePrecedences(struct lemon
*xp
)
892 for(rp
=xp
->rule
; rp
; rp
=rp
->next
){
893 if( rp
->precsym
==0 ){
895 for(i
=0; i
<rp
->nrhs
&& rp
->precsym
==0; i
++){
896 struct symbol
*sp
= rp
->rhs
[i
];
897 if( sp
->type
==MULTITERMINAL
){
898 for(j
=0; j
<sp
->nsubsym
; j
++){
899 if( sp
->subsym
[j
]->prec
>=0 ){
900 rp
->precsym
= sp
->subsym
[j
];
904 }else if( sp
->prec
>=0 ){
905 rp
->precsym
= rp
->rhs
[i
];
913 /* Find all nonterminals which will generate the empty string.
914 ** Then go back and compute the first sets of every nonterminal.
915 ** The first set is the set of all terminal symbols which can begin
916 ** a string generated by that nonterminal.
918 void FindFirstSets(struct lemon
*lemp
)
924 for(i
=0; i
<lemp
->nsymbol
; i
++){
925 lemp
->symbols
[i
]->lambda
= LEMON_FALSE
;
927 for(i
=lemp
->nterminal
; i
<lemp
->nsymbol
; i
++){
928 lemp
->symbols
[i
]->firstset
= SetNew();
931 /* First compute all lambdas */
934 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
935 if( rp
->lhs
->lambda
) continue;
936 for(i
=0; i
<rp
->nrhs
; i
++){
937 struct symbol
*sp
= rp
->rhs
[i
];
938 assert( sp
->type
==NONTERMINAL
|| sp
->lambda
==LEMON_FALSE
);
939 if( sp
->lambda
==LEMON_FALSE
) break;
942 rp
->lhs
->lambda
= LEMON_TRUE
;
948 /* Now compute all first sets */
950 struct symbol
*s1
, *s2
;
952 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
954 for(i
=0; i
<rp
->nrhs
; i
++){
956 if( s2
->type
==TERMINAL
){
957 progress
+= SetAdd(s1
->firstset
,s2
->index
);
959 }else if( s2
->type
==MULTITERMINAL
){
960 for(j
=0; j
<s2
->nsubsym
; j
++){
961 progress
+= SetAdd(s1
->firstset
,s2
->subsym
[j
]->index
);
965 if( s1
->lambda
==LEMON_FALSE
) break;
967 progress
+= SetUnion(s1
->firstset
,s2
->firstset
);
968 if( s2
->lambda
==LEMON_FALSE
) break;
976 /* Compute all LR(0) states for the grammar. Links
977 ** are added to between some states so that the LR(1) follow sets
978 ** can be computed later.
980 PRIVATE
struct state
*getstate(struct lemon
*); /* forward reference */
981 void FindStates(struct lemon
*lemp
)
988 /* Find the start symbol */
990 sp
= Symbol_find(lemp
->start
);
992 ErrorMsg(lemp
->filename
,0,
993 "The specified start symbol \"%s\" is not "
994 "in a nonterminal of the grammar. \"%s\" will be used as the start "
995 "symbol instead.",lemp
->start
,lemp
->startRule
->lhs
->name
);
997 sp
= lemp
->startRule
->lhs
;
999 }else if( lemp
->startRule
){
1000 sp
= lemp
->startRule
->lhs
;
1002 ErrorMsg(lemp
->filename
,0,"Internal error - no start rule\n");
1006 /* Make sure the start symbol doesn't occur on the right-hand side of
1007 ** any rule. Report an error if it does. (YACC would generate a new
1008 ** start symbol in this case.) */
1009 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
1011 for(i
=0; i
<rp
->nrhs
; i
++){
1012 if( rp
->rhs
[i
]==sp
){ /* FIX ME: Deal with multiterminals */
1013 ErrorMsg(lemp
->filename
,0,
1014 "The start symbol \"%s\" occurs on the "
1015 "right-hand side of a rule. This will result in a parser which "
1016 "does not work properly.",sp
->name
);
1022 /* The basis configuration set for the first state
1023 ** is all rules which have the start symbol as their
1024 ** left-hand side */
1025 for(rp
=sp
->rule
; rp
; rp
=rp
->nextlhs
){
1026 struct config
*newcfp
;
1028 newcfp
= Configlist_addbasis(rp
,0);
1029 SetAdd(newcfp
->fws
,0);
1032 /* Compute the first state. All other states will be
1033 ** computed automatically during the computation of the first one.
1034 ** The returned pointer to the first state is not used. */
1035 (void)getstate(lemp
);
1039 /* Return a pointer to a state which is described by the configuration
1040 ** list which has been built from calls to Configlist_add.
1042 PRIVATE
void buildshifts(struct lemon
*, struct state
*); /* Forwd ref */
1043 PRIVATE
struct state
*getstate(struct lemon
*lemp
)
1045 struct config
*cfp
, *bp
;
1048 /* Extract the sorted basis of the new state. The basis was constructed
1049 ** by prior calls to "Configlist_addbasis()". */
1050 Configlist_sortbasis();
1051 bp
= Configlist_basis();
1053 /* Get a state with the same basis */
1054 stp
= State_find(bp
);
1056 /* A state with the same basis already exists! Copy all the follow-set
1057 ** propagation links from the state under construction into the
1058 ** preexisting state, then return a pointer to the preexisting state */
1059 struct config
*x
, *y
;
1060 for(x
=bp
, y
=stp
->bp
; x
&& y
; x
=x
->bp
, y
=y
->bp
){
1061 Plink_copy(&y
->bplp
,x
->bplp
);
1062 Plink_delete(x
->fplp
);
1063 x
->fplp
= x
->bplp
= 0;
1065 cfp
= Configlist_return();
1066 Configlist_eat(cfp
);
1068 /* This really is a new state. Construct all the details */
1069 Configlist_closure(lemp
); /* Compute the configuration closure */
1070 Configlist_sort(); /* Sort the configuration closure */
1071 cfp
= Configlist_return(); /* Get a pointer to the config list */
1072 stp
= State_new(); /* A new state structure */
1074 stp
->bp
= bp
; /* Remember the configuration basis */
1075 stp
->cfp
= cfp
; /* Remember the configuration closure */
1076 stp
->statenum
= lemp
->nstate
++; /* Every state gets a sequence number */
1077 stp
->ap
= 0; /* No actions, yet. */
1078 State_insert(stp
,stp
->bp
); /* Add to the state table */
1079 buildshifts(lemp
,stp
); /* Recursively compute successor states */
1085 ** Return true if two symbols are the same.
1087 int same_symbol(struct symbol
*a
, struct symbol
*b
)
1090 if( a
==b
) return 1;
1091 if( a
->type
!=MULTITERMINAL
) return 0;
1092 if( b
->type
!=MULTITERMINAL
) return 0;
1093 if( a
->nsubsym
!=b
->nsubsym
) return 0;
1094 for(i
=0; i
<a
->nsubsym
; i
++){
1095 if( a
->subsym
[i
]!=b
->subsym
[i
] ) return 0;
1100 /* Construct all successor states to the given state. A "successor"
1101 ** state is any state which can be reached by a shift action.
1103 PRIVATE
void buildshifts(struct lemon
*lemp
, struct state
*stp
)
1105 struct config
*cfp
; /* For looping thru the config closure of "stp" */
1106 struct config
*bcfp
; /* For the inner loop on config closure of "stp" */
1107 struct config
*newcfg
; /* */
1108 struct symbol
*sp
; /* Symbol following the dot in configuration "cfp" */
1109 struct symbol
*bsp
; /* Symbol following the dot in configuration "bcfp" */
1110 struct state
*newstp
; /* A pointer to a successor state */
1112 /* Each configuration becomes complete after it contributes to a successor
1113 ** state. Initially, all configurations are incomplete */
1114 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
) cfp
->status
= INCOMPLETE
;
1116 /* Loop through all configurations of the state "stp" */
1117 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1118 if( cfp
->status
==COMPLETE
) continue; /* Already used by inner loop */
1119 if( cfp
->dot
>=cfp
->rp
->nrhs
) continue; /* Can't shift this config */
1120 Configlist_reset(); /* Reset the new config set */
1121 sp
= cfp
->rp
->rhs
[cfp
->dot
]; /* Symbol after the dot */
1123 /* For every configuration in the state "stp" which has the symbol "sp"
1124 ** following its dot, add the same configuration to the basis set under
1125 ** construction but with the dot shifted one symbol to the right. */
1126 for(bcfp
=cfp
; bcfp
; bcfp
=bcfp
->next
){
1127 if( bcfp
->status
==COMPLETE
) continue; /* Already used */
1128 if( bcfp
->dot
>=bcfp
->rp
->nrhs
) continue; /* Can't shift this one */
1129 bsp
= bcfp
->rp
->rhs
[bcfp
->dot
]; /* Get symbol after dot */
1130 if( !same_symbol(bsp
,sp
) ) continue; /* Must be same as for "cfp" */
1131 bcfp
->status
= COMPLETE
; /* Mark this config as used */
1132 newcfg
= Configlist_addbasis(bcfp
->rp
,bcfp
->dot
+1);
1133 Plink_add(&newcfg
->bplp
,bcfp
);
1136 /* Get a pointer to the state described by the basis configuration set
1137 ** constructed in the preceding loop */
1138 newstp
= getstate(lemp
);
1140 /* The state "newstp" is reached from the state "stp" by a shift action
1141 ** on the symbol "sp" */
1142 if( sp
->type
==MULTITERMINAL
){
1144 for(i
=0; i
<sp
->nsubsym
; i
++){
1145 Action_add(&stp
->ap
,SHIFT
,sp
->subsym
[i
],(char*)newstp
);
1148 Action_add(&stp
->ap
,SHIFT
,sp
,(char *)newstp
);
1154 ** Construct the propagation links
1156 void FindLinks(struct lemon
*lemp
)
1159 struct config
*cfp
, *other
;
1163 /* Housekeeping detail:
1164 ** Add to every propagate link a pointer back to the state to
1165 ** which the link is attached. */
1166 for(i
=0; i
<lemp
->nstate
; i
++){
1167 stp
= lemp
->sorted
[i
];
1168 for(cfp
=stp
?stp
->cfp
:0; cfp
; cfp
=cfp
->next
){
1173 /* Convert all backlinks into forward links. Only the forward
1174 ** links are used in the follow-set computation. */
1175 for(i
=0; i
<lemp
->nstate
; i
++){
1176 stp
= lemp
->sorted
[i
];
1177 for(cfp
=stp
?stp
->cfp
:0; cfp
; cfp
=cfp
->next
){
1178 for(plp
=cfp
->bplp
; plp
; plp
=plp
->next
){
1180 Plink_add(&other
->fplp
,cfp
);
1186 /* Compute all followsets.
1188 ** A followset is the set of all symbols which can come immediately
1189 ** after a configuration.
1191 void FindFollowSets(struct lemon
*lemp
)
1199 for(i
=0; i
<lemp
->nstate
; i
++){
1200 assert( lemp
->sorted
[i
]!=0 );
1201 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1202 cfp
->status
= INCOMPLETE
;
1208 for(i
=0; i
<lemp
->nstate
; i
++){
1209 assert( lemp
->sorted
[i
]!=0 );
1210 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1211 if( cfp
->status
==COMPLETE
) continue;
1212 for(plp
=cfp
->fplp
; plp
; plp
=plp
->next
){
1213 change
= SetUnion(plp
->cfp
->fws
,cfp
->fws
);
1215 plp
->cfp
->status
= INCOMPLETE
;
1219 cfp
->status
= COMPLETE
;
1225 static int resolve_conflict(struct action
*,struct action
*);
1227 /* Compute the reduce actions, and resolve conflicts.
1229 void FindActions(struct lemon
*lemp
)
1237 /* Add all of the reduce actions
1238 ** A reduce action is added for each element of the followset of
1239 ** a configuration which has its dot at the extreme right.
1241 for(i
=0; i
<lemp
->nstate
; i
++){ /* Loop over all states */
1242 stp
= lemp
->sorted
[i
];
1243 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){ /* Loop over all configurations */
1244 if( cfp
->rp
->nrhs
==cfp
->dot
){ /* Is dot at extreme right? */
1245 for(j
=0; j
<lemp
->nterminal
; j
++){
1246 if( SetFind(cfp
->fws
,j
) ){
1247 /* Add a reduce action to the state "stp" which will reduce by the
1248 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1249 Action_add(&stp
->ap
,REDUCE
,lemp
->symbols
[j
],(char *)cfp
->rp
);
1256 /* Add the accepting token */
1258 sp
= Symbol_find(lemp
->start
);
1260 if( lemp
->startRule
==0 ){
1261 fprintf(stderr
, "internal error on source line %d: no start rule\n",
1265 sp
= lemp
->startRule
->lhs
;
1268 sp
= lemp
->startRule
->lhs
;
1270 /* Add to the first state (which is always the starting state of the
1271 ** finite state machine) an action to ACCEPT if the lookahead is the
1272 ** start nonterminal. */
1273 Action_add(&lemp
->sorted
[0]->ap
,ACCEPT
,sp
,0);
1275 /* Resolve conflicts */
1276 for(i
=0; i
<lemp
->nstate
; i
++){
1277 struct action
*ap
, *nap
;
1278 stp
= lemp
->sorted
[i
];
1279 /* assert( stp->ap ); */
1280 stp
->ap
= Action_sort(stp
->ap
);
1281 for(ap
=stp
->ap
; ap
&& ap
->next
; ap
=ap
->next
){
1282 for(nap
=ap
->next
; nap
&& nap
->sp
==ap
->sp
; nap
=nap
->next
){
1283 /* The two actions "ap" and "nap" have the same lookahead.
1284 ** Figure out which one should be used */
1285 lemp
->nconflict
+= resolve_conflict(ap
,nap
);
1290 /* Report an error for each rule that can never be reduced. */
1291 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->canReduce
= LEMON_FALSE
;
1292 for(i
=0; i
<lemp
->nstate
; i
++){
1294 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
1295 if( ap
->type
==REDUCE
) ap
->x
.rp
->canReduce
= LEMON_TRUE
;
1298 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
1299 if( rp
->canReduce
) continue;
1300 ErrorMsg(lemp
->filename
,rp
->ruleline
,"This rule can not be reduced.\n");
1305 /* Resolve a conflict between the two given actions. If the
1306 ** conflict can't be resolved, return non-zero.
1309 ** To resolve a conflict, first look to see if either action
1310 ** is on an error rule. In that case, take the action which
1311 ** is not associated with the error rule. If neither or both
1312 ** actions are associated with an error rule, then try to
1313 ** use precedence to resolve the conflict.
1315 ** If either action is a SHIFT, then it must be apx. This
1316 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1318 static int resolve_conflict(
1322 struct symbol
*spx
, *spy
;
1324 assert( apx
->sp
==apy
->sp
); /* Otherwise there would be no conflict */
1325 if( apx
->type
==SHIFT
&& apy
->type
==SHIFT
){
1326 apy
->type
= SSCONFLICT
;
1329 if( apx
->type
==SHIFT
&& apy
->type
==REDUCE
){
1331 spy
= apy
->x
.rp
->precsym
;
1332 if( spy
==0 || spx
->prec
<0 || spy
->prec
<0 ){
1333 /* Not enough precedence information. */
1334 apy
->type
= SRCONFLICT
;
1336 }else if( spx
->prec
>spy
->prec
){ /* higher precedence wins */
1337 apy
->type
= RD_RESOLVED
;
1338 }else if( spx
->prec
<spy
->prec
){
1339 apx
->type
= SH_RESOLVED
;
1340 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==RIGHT
){ /* Use operator */
1341 apy
->type
= RD_RESOLVED
; /* associativity */
1342 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==LEFT
){ /* to break tie */
1343 apx
->type
= SH_RESOLVED
;
1345 assert( spx
->prec
==spy
->prec
&& spx
->assoc
==NONE
);
1348 }else if( apx
->type
==REDUCE
&& apy
->type
==REDUCE
){
1349 spx
= apx
->x
.rp
->precsym
;
1350 spy
= apy
->x
.rp
->precsym
;
1351 if( spx
==0 || spy
==0 || spx
->prec
<0 ||
1352 spy
->prec
<0 || spx
->prec
==spy
->prec
){
1353 apy
->type
= RRCONFLICT
;
1355 }else if( spx
->prec
>spy
->prec
){
1356 apy
->type
= RD_RESOLVED
;
1357 }else if( spx
->prec
<spy
->prec
){
1358 apx
->type
= RD_RESOLVED
;
1362 apx
->type
==SH_RESOLVED
||
1363 apx
->type
==RD_RESOLVED
||
1364 apx
->type
==SSCONFLICT
||
1365 apx
->type
==SRCONFLICT
||
1366 apx
->type
==RRCONFLICT
||
1367 apy
->type
==SH_RESOLVED
||
1368 apy
->type
==RD_RESOLVED
||
1369 apy
->type
==SSCONFLICT
||
1370 apy
->type
==SRCONFLICT
||
1371 apy
->type
==RRCONFLICT
1373 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1374 ** REDUCEs on the list. If we reach this point it must be because
1375 ** the parser conflict had already been resolved. */
1379 /********************* From the file "configlist.c" *************************/
1381 ** Routines to processing a configuration list and building a state
1382 ** in the LEMON parser generator.
1385 static struct config
*freelist
= 0; /* List of free configurations */
1386 static struct config
*current
= 0; /* Top of list of configurations */
1387 static struct config
**currentend
= 0; /* Last on list of configs */
1388 static struct config
*basis
= 0; /* Top of list of basis configs */
1389 static struct config
**basisend
= 0; /* End of list of basis configs */
1391 /* Return a pointer to a new configuration */
1392 PRIVATE
struct config
*newconfig(void){
1393 return (struct config
*)lemon_calloc(1, sizeof(struct config
));
1396 /* The configuration "old" is no longer used */
1397 PRIVATE
void deleteconfig(struct config
*old
)
1399 old
->next
= freelist
;
1403 /* Initialized the configuration list builder */
1404 void Configlist_init(void){
1406 currentend
= ¤t
;
1413 /* Initialized the configuration list builder */
1414 void Configlist_reset(void){
1416 currentend
= ¤t
;
1419 Configtable_clear(0);
1423 /* Add another configuration to the configuration list */
1424 struct config
*Configlist_add(
1425 struct rule
*rp
, /* The rule */
1426 int dot
/* Index into the RHS of the rule where the dot goes */
1428 struct config
*cfp
, model
;
1430 assert( currentend
!=0 );
1433 cfp
= Configtable_find(&model
);
1438 cfp
->fws
= SetNew();
1440 cfp
->fplp
= cfp
->bplp
= 0;
1444 currentend
= &cfp
->next
;
1445 Configtable_insert(cfp
);
1450 /* Add a basis configuration to the configuration list */
1451 struct config
*Configlist_addbasis(struct rule
*rp
, int dot
)
1453 struct config
*cfp
, model
;
1455 assert( basisend
!=0 );
1456 assert( currentend
!=0 );
1459 cfp
= Configtable_find(&model
);
1464 cfp
->fws
= SetNew();
1466 cfp
->fplp
= cfp
->bplp
= 0;
1470 currentend
= &cfp
->next
;
1472 basisend
= &cfp
->bp
;
1473 Configtable_insert(cfp
);
1478 /* Compute the closure of the configuration list */
1479 void Configlist_closure(struct lemon
*lemp
)
1481 struct config
*cfp
, *newcfp
;
1482 struct rule
*rp
, *newrp
;
1483 struct symbol
*sp
, *xsp
;
1486 assert( currentend
!=0 );
1487 for(cfp
=current
; cfp
; cfp
=cfp
->next
){
1490 if( dot
>=rp
->nrhs
) continue;
1492 if( sp
->type
==NONTERMINAL
){
1493 if( sp
->rule
==0 && sp
!=lemp
->errsym
){
1494 ErrorMsg(lemp
->filename
,rp
->line
,"Nonterminal \"%s\" has no rules.",
1498 for(newrp
=sp
->rule
; newrp
; newrp
=newrp
->nextlhs
){
1499 newcfp
= Configlist_add(newrp
,0);
1500 for(i
=dot
+1; i
<rp
->nrhs
; i
++){
1502 if( xsp
->type
==TERMINAL
){
1503 SetAdd(newcfp
->fws
,xsp
->index
);
1505 }else if( xsp
->type
==MULTITERMINAL
){
1507 for(k
=0; k
<xsp
->nsubsym
; k
++){
1508 SetAdd(newcfp
->fws
, xsp
->subsym
[k
]->index
);
1512 SetUnion(newcfp
->fws
,xsp
->firstset
);
1513 if( xsp
->lambda
==LEMON_FALSE
) break;
1516 if( i
==rp
->nrhs
) Plink_add(&cfp
->fplp
,newcfp
);
1523 /* Sort the configuration list */
1524 void Configlist_sort(void){
1525 current
= (struct config
*)msort((char*)current
,(char**)&(current
->next
),
1531 /* Sort the basis configuration list */
1532 void Configlist_sortbasis(void){
1533 basis
= (struct config
*)msort((char*)current
,(char**)&(current
->bp
),
1539 /* Return a pointer to the head of the configuration list and
1540 ** reset the list */
1541 struct config
*Configlist_return(void){
1549 /* Return a pointer to the head of the configuration list and
1550 ** reset the list */
1551 struct config
*Configlist_basis(void){
1559 /* Free all elements of the given configuration list */
1560 void Configlist_eat(struct config
*cfp
)
1562 struct config
*nextcfp
;
1563 for(; cfp
; cfp
=nextcfp
){
1564 nextcfp
= cfp
->next
;
1565 assert( cfp
->fplp
==0 );
1566 assert( cfp
->bplp
==0 );
1567 if( cfp
->fws
) SetFree(cfp
->fws
);
1572 /***************** From the file "error.c" *********************************/
1574 ** Code for printing error message.
1577 void ErrorMsg(const char *filename
, int lineno
, const char *format
, ...){
1579 fprintf(stderr
, "%s:%d: ", filename
, lineno
);
1580 va_start(ap
, format
);
1581 vfprintf(stderr
,format
,ap
);
1583 fprintf(stderr
, "\n");
1585 /**************** From the file "main.c" ************************************/
1587 ** Main program file for the LEMON parser generator.
1590 /* Report an out-of-memory condition and abort. This function
1591 ** is used mostly by the "MemoryCheck" macro in struct.h
1593 void memory_error(void){
1594 fprintf(stderr
,"Out of memory. Aborting...\n");
1598 static int nDefine
= 0; /* Number of -D options on the command line */
1599 static int nDefineUsed
= 0; /* Number of -D options actually used */
1600 static char **azDefine
= 0; /* Name of the -D macros */
1601 static char *bDefineUsed
= 0; /* True for every -D macro actually used */
1603 /* This routine is called with the argument to each -D command-line option.
1604 ** Add the macro defined to the azDefine array.
1606 static void handle_D_option(char *z
){
1609 azDefine
= (char **) lemon_realloc(azDefine
, sizeof(azDefine
[0])*nDefine
);
1611 fprintf(stderr
,"out of memory\n");
1614 bDefineUsed
= (char*)lemon_realloc(bDefineUsed
, nDefine
);
1615 if( bDefineUsed
==0 ){
1616 fprintf(stderr
,"out of memory\n");
1619 bDefineUsed
[nDefine
-1] = 0;
1620 paz
= &azDefine
[nDefine
-1];
1621 *paz
= (char *) lemon_malloc( lemonStrlen(z
)+1 );
1623 fprintf(stderr
,"out of memory\n");
1626 lemon_strcpy(*paz
, z
);
1627 for(z
=*paz
; *z
&& *z
!='='; z
++){}
1631 /* Rember the name of the output directory
1633 static char *outputDir
= NULL
;
1634 static void handle_d_option(char *z
){
1635 outputDir
= (char *) lemon_malloc( lemonStrlen(z
)+1 );
1637 fprintf(stderr
,"out of memory\n");
1640 lemon_strcpy(outputDir
, z
);
1643 static char *user_templatename
= NULL
;
1644 static void handle_T_option(char *z
){
1645 user_templatename
= (char *) lemon_malloc( lemonStrlen(z
)+1 );
1646 if( user_templatename
==0 ){
1649 lemon_strcpy(user_templatename
, z
);
1652 /* Merge together to lists of rules ordered by rule.iRule */
1653 static struct rule
*Rule_merge(struct rule
*pA
, struct rule
*pB
){
1654 struct rule
*pFirst
= 0;
1655 struct rule
**ppPrev
= &pFirst
;
1657 if( pA
->iRule
<pB
->iRule
){
1676 ** Sort a list of rules in order of increasing iRule value
1678 static struct rule
*Rule_sort(struct rule
*rp
){
1682 memset(x
, 0, sizeof(x
));
1686 for(i
=0; i
<sizeof(x
)/sizeof(x
[0])-1 && x
[i
]; i
++){
1687 rp
= Rule_merge(x
[i
], rp
);
1694 for(i
=0; i
<sizeof(x
)/sizeof(x
[0]); i
++){
1695 rp
= Rule_merge(x
[i
], rp
);
1700 /* forward reference */
1701 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
);
1703 /* Print a single line of the "Parser Stats" output
1705 static void stats_line(const char *zLabel
, int iValue
){
1706 int nLabel
= lemonStrlen(zLabel
);
1707 printf(" %s%.*s %5d\n", zLabel
,
1708 35-nLabel
, "................................",
1712 /* The main program. Parse the command line and do it... */
1713 int main(int argc
, char **argv
){
1714 static int version
= 0;
1715 static int rpflag
= 0;
1716 static int basisflag
= 0;
1717 static int compress
= 0;
1718 static int quiet
= 0;
1719 static int statistics
= 0;
1720 static int mhflag
= 0;
1721 static int nolinenosflag
= 0;
1722 static int noResort
= 0;
1723 static int sqlFlag
= 0;
1724 static int printPP
= 0;
1726 static struct s_options options
[] = {
1727 {OPT_FLAG
, "b", (char*)&basisflag
, "Print only the basis in report."},
1728 {OPT_FLAG
, "c", (char*)&compress
, "Don't compress the action table."},
1729 {OPT_FSTR
, "d", (char*)&handle_d_option
, "Output directory. Default '.'"},
1730 {OPT_FSTR
, "D", (char*)handle_D_option
, "Define an %ifdef macro."},
1731 {OPT_FLAG
, "E", (char*)&printPP
, "Print input file after preprocessing."},
1732 {OPT_FSTR
, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1733 {OPT_FLAG
, "g", (char*)&rpflag
, "Print grammar without actions."},
1734 {OPT_FSTR
, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1735 {OPT_FLAG
, "m", (char*)&mhflag
, "Output a makeheaders compatible file."},
1736 {OPT_FLAG
, "l", (char*)&nolinenosflag
, "Do not print #line statements."},
1737 {OPT_FSTR
, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1738 {OPT_FLAG
, "p", (char*)&showPrecedenceConflict
,
1739 "Show conflicts resolved by precedence rules"},
1740 {OPT_FLAG
, "q", (char*)&quiet
, "(Quiet) Don't print the report file."},
1741 {OPT_FLAG
, "r", (char*)&noResort
, "Do not sort or renumber states"},
1742 {OPT_FLAG
, "s", (char*)&statistics
,
1743 "Print parser stats to standard output."},
1744 {OPT_FLAG
, "S", (char*)&sqlFlag
,
1745 "Generate the *.sql file describing the parser tables."},
1746 {OPT_FLAG
, "x", (char*)&version
, "Print the version number."},
1747 {OPT_FSTR
, "T", (char*)handle_T_option
, "Specify a template file."},
1748 {OPT_FSTR
, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1756 OptInit(argv
,options
,stderr
);
1758 printf("Lemon version 1.0\n");
1761 if( OptNArgs()!=1 ){
1762 fprintf(stderr
,"Exactly one filename argument is required.\n");
1765 memset(&lem
, 0, sizeof(lem
));
1768 /* Initialize the machine */
1774 lem
.filename
= OptArg(0);
1775 lem
.basisflag
= basisflag
;
1776 lem
.nolinenosflag
= nolinenosflag
;
1777 lem
.printPreprocessed
= printPP
;
1780 /* Parse the input file */
1782 if( lem
.printPreprocessed
|| lem
.errorcnt
) exit(lem
.errorcnt
);
1784 fprintf(stderr
,"Empty grammar.\n");
1787 lem
.errsym
= Symbol_find("error");
1789 /* Count and index the symbols of the grammar */
1790 Symbol_new("{default}");
1791 lem
.nsymbol
= Symbol_count();
1792 lem
.symbols
= Symbol_arrayof();
1793 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1794 qsort(lem
.symbols
,lem
.nsymbol
,sizeof(struct symbol
*), Symbolcmpp
);
1795 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1796 while( lem
.symbols
[i
-1]->type
==MULTITERMINAL
){ i
--; }
1797 assert( strcmp(lem
.symbols
[i
-1]->name
,"{default}")==0 );
1798 lem
.nsymbol
= i
- 1;
1799 for(i
=1; ISUPPER(lem
.symbols
[i
]->name
[0]); i
++);
1802 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1803 ** reduce action C-code associated with them last, so that the switch()
1804 ** statement that selects reduction actions will have a smaller jump table.
1806 for(i
=0, rp
=lem
.rule
; rp
; rp
=rp
->next
){
1807 rp
->iRule
= rp
->code
? i
++ : -1;
1809 lem
.nruleWithAction
= i
;
1810 for(rp
=lem
.rule
; rp
; rp
=rp
->next
){
1811 if( rp
->iRule
<0 ) rp
->iRule
= i
++;
1813 lem
.startRule
= lem
.rule
;
1814 lem
.rule
= Rule_sort(lem
.rule
);
1816 /* Generate a reprint of the grammar, if requested on the command line */
1820 /* Initialize the size for all follow and first sets */
1821 SetSize(lem
.nterminal
+1);
1823 /* Find the precedence for every production rule (that has one) */
1824 FindRulePrecedences(&lem
);
1826 /* Compute the lambda-nonterminals and the first-sets for every
1828 FindFirstSets(&lem
);
1830 /* Compute all LR(0) states. Also record follow-set propagation
1831 ** links so that the follow-set can be computed later */
1834 lem
.sorted
= State_arrayof();
1836 /* Tie up loose ends on the propagation links */
1839 /* Compute the follow set of every reducible configuration */
1840 FindFollowSets(&lem
);
1842 /* Compute the action tables */
1845 /* Compress the action tables */
1846 if( compress
==0 ) CompressTables(&lem
);
1848 /* Reorder and renumber the states so that states with fewer choices
1849 ** occur at the end. This is an optimization that helps make the
1850 ** generated parser tables smaller. */
1851 if( noResort
==0 ) ResortStates(&lem
);
1853 /* Generate a report of the parser generated. (the "y.output" file) */
1854 if( !quiet
) ReportOutput(&lem
);
1856 /* Generate the source code for the parser */
1857 ReportTable(&lem
, mhflag
, sqlFlag
);
1859 /* Produce a header file for use by the scanner. (This step is
1860 ** omitted if the "-m" option is used because makeheaders will
1861 ** generate the file for us.) */
1862 if( !mhflag
) ReportHeader(&lem
);
1865 printf("Parser statistics:\n");
1866 stats_line("terminal symbols", lem
.nterminal
);
1867 stats_line("non-terminal symbols", lem
.nsymbol
- lem
.nterminal
);
1868 stats_line("total symbols", lem
.nsymbol
);
1869 stats_line("rules", lem
.nrule
);
1870 stats_line("states", lem
.nxstate
);
1871 stats_line("conflicts", lem
.nconflict
);
1872 stats_line("action table entries", lem
.nactiontab
);
1873 stats_line("lookahead table entries", lem
.nlookaheadtab
);
1874 stats_line("total table size (bytes)", lem
.tablesize
);
1876 if( lem
.nconflict
> 0 ){
1877 fprintf(stderr
,"%d parsing conflicts.\n",lem
.nconflict
);
1880 /* return 0 on success, 1 on failure. */
1881 exitcode
= ((lem
.errorcnt
> 0) || (lem
.nconflict
> 0)) ? 1 : 0;
1886 /******************** From the file "msort.c" *******************************/
1888 ** A generic merge-sort program.
1891 ** Let "ptr" be a pointer to some structure which is at the head of
1892 ** a null-terminated list. Then to sort the list call:
1894 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1896 ** In the above, "cmpfnc" is a pointer to a function which compares
1897 ** two instances of the structure and returns an integer, as in
1898 ** strcmp. The second argument is a pointer to the pointer to the
1899 ** second element of the linked list. This address is used to compute
1900 ** the offset to the "next" field within the structure. The offset to
1901 ** the "next" field must be constant for all structures in the list.
1903 ** The function returns a new pointer which is the head of the list
1911 ** Return a pointer to the next structure in the linked list.
1913 #define NEXT(A) (*(char**)(((char*)A)+offset))
1917 ** a: A sorted, null-terminated linked list. (May be null).
1918 ** b: A sorted, null-terminated linked list. (May be null).
1919 ** cmp: A pointer to the comparison function.
1920 ** offset: Offset in the structure to the "next" field.
1923 ** A pointer to the head of a sorted list containing the elements
1927 ** The "next" pointers for elements in the lists a and b are
1933 int (*cmp
)(const char*,const char*),
1943 if( (*cmp
)(a
,b
)<=0 ){
1952 if( (*cmp
)(a
,b
)<=0 ){
1962 if( a
) NEXT(ptr
) = a
;
1970 ** list: Pointer to a singly-linked list of structures.
1971 ** next: Pointer to pointer to the second element of the list.
1972 ** cmp: A comparison function.
1975 ** A pointer to the head of a sorted list containing the elements
1976 ** originally in list.
1979 ** The "next" pointers for elements in list are changed.
1985 int (*cmp
)(const char*,const char*)
1987 unsigned long offset
;
1989 char *set
[LISTSIZE
];
1991 offset
= (unsigned long)((char*)next
- (char*)list
);
1992 for(i
=0; i
<LISTSIZE
; i
++) set
[i
] = 0;
1997 for(i
=0; i
<LISTSIZE
-1 && set
[i
]!=0; i
++){
1998 ep
= merge(ep
,set
[i
],cmp
,offset
);
2004 for(i
=0; i
<LISTSIZE
; i
++) if( set
[i
] ) ep
= merge(set
[i
],ep
,cmp
,offset
);
2007 /************************ From the file "option.c" **************************/
2008 static char **g_argv
;
2009 static struct s_options
*op
;
2010 static FILE *errstream
;
2012 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
2015 ** Print the command line with a carrot pointing to the k-th character
2016 ** of the n-th field.
2018 static void errline(int n
, int k
, FILE *err
)
2022 fprintf(err
,"%s",g_argv
[0]);
2023 spcnt
= lemonStrlen(g_argv
[0]) + 1;
2027 for(i
=1; i
<n
&& g_argv
[i
]; i
++){
2028 fprintf(err
," %s",g_argv
[i
]);
2029 spcnt
+= lemonStrlen(g_argv
[i
])+1;
2032 for(; g_argv
[i
]; i
++) fprintf(err
," %s",g_argv
[i
]);
2034 fprintf(err
,"\n%*s^-- here\n",spcnt
,"");
2036 fprintf(err
,"\n%*shere --^\n",spcnt
-7,"");
2041 ** Return the index of the N-th non-switch argument. Return -1
2042 ** if N is out of range.
2044 static int argindex(int n
)
2048 if( g_argv
!=0 && *g_argv
!=0 ){
2049 for(i
=1; g_argv
[i
]; i
++){
2050 if( dashdash
|| !ISOPT(g_argv
[i
]) ){
2051 if( n
==0 ) return i
;
2054 if( strcmp(g_argv
[i
],"--")==0 ) dashdash
= 1;
2060 static char emsg
[] = "Command line syntax error: ";
2063 ** Process a flag command line argument.
2065 static int handleflags(int i
, FILE *err
)
2070 for(j
=0; op
[j
].label
; j
++){
2071 if( strncmp(&g_argv
[i
][1],op
[j
].label
,lemonStrlen(op
[j
].label
))==0 ) break;
2073 v
= g_argv
[i
][0]=='-' ? 1 : 0;
2074 if( op
[j
].label
==0 ){
2076 fprintf(err
,"%sundefined option.\n",emsg
);
2080 }else if( op
[j
].arg
==0 ){
2081 /* Ignore this option */
2082 }else if( op
[j
].type
==OPT_FLAG
){
2083 *((int*)op
[j
].arg
) = v
;
2084 }else if( op
[j
].type
==OPT_FFLAG
){
2085 (*(void(*)(int))(op
[j
].arg
))(v
);
2086 }else if( op
[j
].type
==OPT_FSTR
){
2087 (*(void(*)(char *))(op
[j
].arg
))(&g_argv
[i
][2]);
2090 fprintf(err
,"%smissing argument on switch.\n",emsg
);
2099 ** Process a command line switch which has an argument.
2101 static int handleswitch(int i
, FILE *err
)
2109 cp
= strchr(g_argv
[i
],'=');
2112 for(j
=0; op
[j
].label
; j
++){
2113 if( strcmp(g_argv
[i
],op
[j
].label
)==0 ) break;
2116 if( op
[j
].label
==0 ){
2118 fprintf(err
,"%sundefined option.\n",emsg
);
2124 switch( op
[j
].type
){
2128 fprintf(err
,"%soption requires an argument.\n",emsg
);
2135 dv
= strtod(cp
,&end
);
2139 "%sillegal character in floating-point argument.\n",emsg
);
2140 errline(i
,(int)((char*)end
-(char*)g_argv
[i
]),err
);
2147 lv
= strtol(cp
,&end
,0);
2150 fprintf(err
,"%sillegal character in integer argument.\n",emsg
);
2151 errline(i
,(int)((char*)end
-(char*)g_argv
[i
]),err
);
2161 switch( op
[j
].type
){
2166 *(double*)(op
[j
].arg
) = dv
;
2169 (*(void(*)(double))(op
[j
].arg
))(dv
);
2172 *(int*)(op
[j
].arg
) = lv
;
2175 (*(void(*)(int))(op
[j
].arg
))((int)lv
);
2178 *(char**)(op
[j
].arg
) = sv
;
2181 (*(void(*)(char *))(op
[j
].arg
))(sv
);
2188 int OptInit(char **a
, struct s_options
*o
, FILE *err
)
2194 if( g_argv
&& *g_argv
&& op
){
2196 for(i
=1; g_argv
[i
]; i
++){
2197 if( g_argv
[i
][0]=='+' || g_argv
[i
][0]=='-' ){
2198 errcnt
+= handleflags(i
,err
);
2199 }else if( strchr(g_argv
[i
],'=') ){
2200 errcnt
+= handleswitch(i
,err
);
2205 fprintf(err
,"Valid command line options for \"%s\" are:\n",*a
);
2216 if( g_argv
!=0 && g_argv
[0]!=0 ){
2217 for(i
=1; g_argv
[i
]; i
++){
2218 if( dashdash
|| !ISOPT(g_argv
[i
]) ) cnt
++;
2219 if( strcmp(g_argv
[i
],"--")==0 ) dashdash
= 1;
2229 return i
>=0 ? g_argv
[i
] : 0;
2236 if( i
>=0 ) errline(i
,0,errstream
);
2239 void OptPrint(void){
2243 for(i
=0; op
[i
].label
; i
++){
2244 len
= lemonStrlen(op
[i
].label
) + 1;
2245 switch( op
[i
].type
){
2251 len
+= 9; /* length of "<integer>" */
2255 len
+= 6; /* length of "<real>" */
2259 len
+= 8; /* length of "<string>" */
2262 if( len
>max
) max
= len
;
2264 for(i
=0; op
[i
].label
; i
++){
2265 switch( op
[i
].type
){
2268 fprintf(errstream
," -%-*s %s\n",max
,op
[i
].label
,op
[i
].message
);
2272 fprintf(errstream
," -%s<integer>%*s %s\n",op
[i
].label
,
2273 (int)(max
-lemonStrlen(op
[i
].label
)-9),"",op
[i
].message
);
2277 fprintf(errstream
," -%s<real>%*s %s\n",op
[i
].label
,
2278 (int)(max
-lemonStrlen(op
[i
].label
)-6),"",op
[i
].message
);
2282 fprintf(errstream
," -%s<string>%*s %s\n",op
[i
].label
,
2283 (int)(max
-lemonStrlen(op
[i
].label
)-8),"",op
[i
].message
);
2288 /*********************** From the file "parse.c" ****************************/
2290 ** Input file parser for the LEMON parser generator.
2293 /* The state of the parser */
2296 WAITING_FOR_DECL_OR_RULE
,
2297 WAITING_FOR_DECL_KEYWORD
,
2298 WAITING_FOR_DECL_ARG
,
2299 WAITING_FOR_PRECEDENCE_SYMBOL
,
2309 RESYNC_AFTER_RULE_ERROR
,
2310 RESYNC_AFTER_DECL_ERROR
,
2311 WAITING_FOR_DESTRUCTOR_SYMBOL
,
2312 WAITING_FOR_DATATYPE_SYMBOL
,
2313 WAITING_FOR_FALLBACK_ID
,
2314 WAITING_FOR_WILDCARD_ID
,
2315 WAITING_FOR_CLASS_ID
,
2316 WAITING_FOR_CLASS_TOKEN
,
2317 WAITING_FOR_TOKEN_NAME
2320 char *filename
; /* Name of the input file */
2321 int tokenlineno
; /* Linenumber at which current token starts */
2322 int errorcnt
; /* Number of errors so far */
2323 char *tokenstart
; /* Text of current token */
2324 struct lemon
*gp
; /* Global state vector */
2325 enum e_state state
; /* The state of the parser */
2326 struct symbol
*fallback
; /* The fallback token */
2327 struct symbol
*tkclass
; /* Token class symbol */
2328 struct symbol
*lhs
; /* Left-hand side of current rule */
2329 const char *lhsalias
; /* Alias for the LHS */
2330 int nrhs
; /* Number of right-hand side symbols seen */
2331 struct symbol
*rhs
[MAXRHS
]; /* RHS symbols */
2332 const char *alias
[MAXRHS
]; /* Aliases for each RHS symbol (or NULL) */
2333 struct rule
*prevrule
; /* Previous rule parsed */
2334 const char *declkeyword
; /* Keyword of a declaration */
2335 char **declargslot
; /* Where the declaration argument should be put */
2336 int insertLineMacro
; /* Add #line before declaration insert */
2337 int *decllinenoslot
; /* Where to write declaration line number */
2338 enum e_assoc declassoc
; /* Assign this association to decl arguments */
2339 int preccounter
; /* Assign this precedence to decl arguments */
2340 struct rule
*firstrule
; /* Pointer to first rule in the grammar */
2341 struct rule
*lastrule
; /* Pointer to the most recently parsed rule */
2344 /* Parse a single token */
2345 static void parseonetoken(struct pstate
*psp
)
2348 x
= Strsafe(psp
->tokenstart
); /* Save the token permanently */
2350 printf("%s:%d: Token=[%s] state=%d\n",psp
->filename
,psp
->tokenlineno
,
2353 switch( psp
->state
){
2356 psp
->preccounter
= 0;
2357 psp
->firstrule
= psp
->lastrule
= 0;
2360 case WAITING_FOR_DECL_OR_RULE
:
2362 psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2363 }else if( ISLOWER(x
[0]) ){
2364 psp
->lhs
= Symbol_new(x
);
2367 psp
->state
= WAITING_FOR_ARROW
;
2368 }else if( x
[0]=='{' ){
2369 if( psp
->prevrule
==0 ){
2370 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2371 "There is no prior rule upon which to attach the code "
2372 "fragment which begins on this line.");
2374 }else if( psp
->prevrule
->code
!=0 ){
2375 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2376 "Code fragment beginning on this line is not the first "
2377 "to follow the previous rule.");
2379 }else if( strcmp(x
, "{NEVER-REDUCE")==0 ){
2380 psp
->prevrule
->neverReduce
= 1;
2382 psp
->prevrule
->line
= psp
->tokenlineno
;
2383 psp
->prevrule
->code
= &x
[1];
2384 psp
->prevrule
->noCode
= 0;
2386 }else if( x
[0]=='[' ){
2387 psp
->state
= PRECEDENCE_MARK_1
;
2389 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2390 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2395 case PRECEDENCE_MARK_1
:
2396 if( !ISUPPER(x
[0]) ){
2397 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2398 "The precedence symbol must be a terminal.");
2400 }else if( psp
->prevrule
==0 ){
2401 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2402 "There is no prior rule to assign precedence \"[%s]\".",x
);
2404 }else if( psp
->prevrule
->precsym
!=0 ){
2405 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2406 "Precedence mark on this line is not the first "
2407 "to follow the previous rule.");
2410 psp
->prevrule
->precsym
= Symbol_new(x
);
2412 psp
->state
= PRECEDENCE_MARK_2
;
2414 case PRECEDENCE_MARK_2
:
2416 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2417 "Missing \"]\" on precedence mark.");
2420 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2422 case WAITING_FOR_ARROW
:
2423 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2424 psp
->state
= IN_RHS
;
2425 }else if( x
[0]=='(' ){
2426 psp
->state
= LHS_ALIAS_1
;
2428 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2429 "Expected to see a \":\" following the LHS symbol \"%s\".",
2432 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2436 if( ISALPHA(x
[0]) ){
2438 psp
->state
= LHS_ALIAS_2
;
2440 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2441 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2444 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2449 psp
->state
= LHS_ALIAS_3
;
2451 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2452 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2454 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2458 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2459 psp
->state
= IN_RHS
;
2461 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2462 "Missing \"->\" following: \"%s(%s)\".",
2463 psp
->lhs
->name
,psp
->lhsalias
);
2465 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2471 rp
= (struct rule
*)lemon_calloc( sizeof(struct rule
) +
2472 sizeof(struct symbol
*)*psp
->nrhs
+ sizeof(char*)*psp
->nrhs
, 1);
2474 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2475 "Can't allocate enough memory for this rule.");
2480 rp
->ruleline
= psp
->tokenlineno
;
2481 rp
->rhs
= (struct symbol
**)&rp
[1];
2482 rp
->rhsalias
= (const char**)&(rp
->rhs
[psp
->nrhs
]);
2483 for(i
=0; i
<psp
->nrhs
; i
++){
2484 rp
->rhs
[i
] = psp
->rhs
[i
];
2485 rp
->rhsalias
[i
] = psp
->alias
[i
];
2486 if( rp
->rhsalias
[i
]!=0 ){ rp
->rhs
[i
]->bContent
= 1; }
2489 rp
->lhsalias
= psp
->lhsalias
;
2490 rp
->nrhs
= psp
->nrhs
;
2494 rp
->index
= psp
->gp
->nrule
++;
2495 rp
->nextlhs
= rp
->lhs
->rule
;
2498 if( psp
->firstrule
==0 ){
2499 psp
->firstrule
= psp
->lastrule
= rp
;
2501 psp
->lastrule
->next
= rp
;
2506 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2507 }else if( ISALPHA(x
[0]) ){
2508 if( psp
->nrhs
>=MAXRHS
){
2509 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2510 "Too many symbols on RHS of rule beginning at \"%s\".",
2513 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2515 psp
->rhs
[psp
->nrhs
] = Symbol_new(x
);
2516 psp
->alias
[psp
->nrhs
] = 0;
2519 }else if( (x
[0]=='|' || x
[0]=='/') && psp
->nrhs
>0 && ISUPPER(x
[1]) ){
2520 struct symbol
*msp
= psp
->rhs
[psp
->nrhs
-1];
2521 if( msp
->type
!=MULTITERMINAL
){
2522 struct symbol
*origsp
= msp
;
2523 msp
= (struct symbol
*) lemon_calloc(1,sizeof(*msp
));
2524 memset(msp
, 0, sizeof(*msp
));
2525 msp
->type
= MULTITERMINAL
;
2527 msp
->subsym
= (struct symbol
**)lemon_calloc(1,sizeof(struct symbol
*));
2528 msp
->subsym
[0] = origsp
;
2529 msp
->name
= origsp
->name
;
2530 psp
->rhs
[psp
->nrhs
-1] = msp
;
2533 msp
->subsym
= (struct symbol
**) lemon_realloc(msp
->subsym
,
2534 sizeof(struct symbol
*)*msp
->nsubsym
);
2535 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(&x
[1]);
2536 if( ISLOWER(x
[1]) || ISLOWER(msp
->subsym
[0]->name
[0]) ){
2537 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2538 "Cannot form a compound containing a non-terminal");
2541 }else if( x
[0]=='(' && psp
->nrhs
>0 ){
2542 psp
->state
= RHS_ALIAS_1
;
2544 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2545 "Illegal character on RHS of rule: \"%s\".",x
);
2547 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2551 if( ISALPHA(x
[0]) ){
2552 psp
->alias
[psp
->nrhs
-1] = x
;
2553 psp
->state
= RHS_ALIAS_2
;
2555 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2556 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2557 x
,psp
->rhs
[psp
->nrhs
-1]->name
);
2559 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2564 psp
->state
= IN_RHS
;
2566 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2567 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2569 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2572 case WAITING_FOR_DECL_KEYWORD
:
2573 if( ISALPHA(x
[0]) ){
2574 psp
->declkeyword
= x
;
2575 psp
->declargslot
= 0;
2576 psp
->decllinenoslot
= 0;
2577 psp
->insertLineMacro
= 1;
2578 psp
->state
= WAITING_FOR_DECL_ARG
;
2579 if( strcmp(x
,"name")==0 ){
2580 psp
->declargslot
= &(psp
->gp
->name
);
2581 psp
->insertLineMacro
= 0;
2582 }else if( strcmp(x
,"include")==0 ){
2583 psp
->declargslot
= &(psp
->gp
->include
);
2584 }else if( strcmp(x
,"code")==0 ){
2585 psp
->declargslot
= &(psp
->gp
->extracode
);
2586 }else if( strcmp(x
,"token_destructor")==0 ){
2587 psp
->declargslot
= &psp
->gp
->tokendest
;
2588 }else if( strcmp(x
,"default_destructor")==0 ){
2589 psp
->declargslot
= &psp
->gp
->vardest
;
2590 }else if( strcmp(x
,"token_prefix")==0 ){
2591 psp
->declargslot
= &psp
->gp
->tokenprefix
;
2592 psp
->insertLineMacro
= 0;
2593 }else if( strcmp(x
,"syntax_error")==0 ){
2594 psp
->declargslot
= &(psp
->gp
->error
);
2595 }else if( strcmp(x
,"parse_accept")==0 ){
2596 psp
->declargslot
= &(psp
->gp
->accept
);
2597 }else if( strcmp(x
,"parse_failure")==0 ){
2598 psp
->declargslot
= &(psp
->gp
->failure
);
2599 }else if( strcmp(x
,"stack_overflow")==0 ){
2600 psp
->declargslot
= &(psp
->gp
->overflow
);
2601 }else if( strcmp(x
,"extra_argument")==0 ){
2602 psp
->declargslot
= &(psp
->gp
->arg
);
2603 psp
->insertLineMacro
= 0;
2604 }else if( strcmp(x
,"extra_context")==0 ){
2605 psp
->declargslot
= &(psp
->gp
->ctx
);
2606 psp
->insertLineMacro
= 0;
2607 }else if( strcmp(x
,"token_type")==0 ){
2608 psp
->declargslot
= &(psp
->gp
->tokentype
);
2609 psp
->insertLineMacro
= 0;
2610 }else if( strcmp(x
,"default_type")==0 ){
2611 psp
->declargslot
= &(psp
->gp
->vartype
);
2612 psp
->insertLineMacro
= 0;
2613 }else if( strcmp(x
,"realloc")==0 ){
2614 psp
->declargslot
= &(psp
->gp
->reallocFunc
);
2615 psp
->insertLineMacro
= 0;
2616 }else if( strcmp(x
,"free")==0 ){
2617 psp
->declargslot
= &(psp
->gp
->freeFunc
);
2618 psp
->insertLineMacro
= 0;
2619 }else if( strcmp(x
,"stack_size")==0 ){
2620 psp
->declargslot
= &(psp
->gp
->stacksize
);
2621 psp
->insertLineMacro
= 0;
2622 }else if( strcmp(x
,"start_symbol")==0 ){
2623 psp
->declargslot
= &(psp
->gp
->start
);
2624 psp
->insertLineMacro
= 0;
2625 }else if( strcmp(x
,"left")==0 ){
2627 psp
->declassoc
= LEFT
;
2628 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2629 }else if( strcmp(x
,"right")==0 ){
2631 psp
->declassoc
= RIGHT
;
2632 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2633 }else if( strcmp(x
,"nonassoc")==0 ){
2635 psp
->declassoc
= NONE
;
2636 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2637 }else if( strcmp(x
,"destructor")==0 ){
2638 psp
->state
= WAITING_FOR_DESTRUCTOR_SYMBOL
;
2639 }else if( strcmp(x
,"type")==0 ){
2640 psp
->state
= WAITING_FOR_DATATYPE_SYMBOL
;
2641 }else if( strcmp(x
,"fallback")==0 ){
2643 psp
->state
= WAITING_FOR_FALLBACK_ID
;
2644 }else if( strcmp(x
,"token")==0 ){
2645 psp
->state
= WAITING_FOR_TOKEN_NAME
;
2646 }else if( strcmp(x
,"wildcard")==0 ){
2647 psp
->state
= WAITING_FOR_WILDCARD_ID
;
2648 }else if( strcmp(x
,"token_class")==0 ){
2649 psp
->state
= WAITING_FOR_CLASS_ID
;
2651 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2652 "Unknown declaration keyword: \"%%%s\".",x
);
2654 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2657 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2658 "Illegal declaration keyword: \"%s\".",x
);
2660 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2663 case WAITING_FOR_DESTRUCTOR_SYMBOL
:
2664 if( !ISALPHA(x
[0]) ){
2665 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2666 "Symbol name missing after %%destructor keyword");
2668 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2670 struct symbol
*sp
= Symbol_new(x
);
2671 psp
->declargslot
= &sp
->destructor
;
2672 psp
->decllinenoslot
= &sp
->destLineno
;
2673 psp
->insertLineMacro
= 1;
2674 psp
->state
= WAITING_FOR_DECL_ARG
;
2677 case WAITING_FOR_DATATYPE_SYMBOL
:
2678 if( !ISALPHA(x
[0]) ){
2679 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2680 "Symbol name missing after %%type keyword");
2682 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2684 struct symbol
*sp
= Symbol_find(x
);
2685 if((sp
) && (sp
->datatype
)){
2686 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2687 "Symbol %%type \"%s\" already defined", x
);
2689 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2694 psp
->declargslot
= &sp
->datatype
;
2695 psp
->insertLineMacro
= 0;
2696 psp
->state
= WAITING_FOR_DECL_ARG
;
2700 case WAITING_FOR_PRECEDENCE_SYMBOL
:
2702 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2703 }else if( ISUPPER(x
[0]) ){
2707 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2708 "Symbol \"%s\" has already be given a precedence.",x
);
2711 sp
->prec
= psp
->preccounter
;
2712 sp
->assoc
= psp
->declassoc
;
2715 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2716 "Can't assign a precedence to \"%s\".",x
);
2720 case WAITING_FOR_DECL_ARG
:
2721 if( x
[0]=='{' || x
[0]=='\"' || ISALNUM(x
[0]) ){
2722 const char *zOld
, *zNew
;
2724 int nOld
, n
, nLine
= 0, nNew
, nBack
;
2728 if( zNew
[0]=='"' || zNew
[0]=='{' ) zNew
++;
2729 nNew
= lemonStrlen(zNew
);
2730 if( *psp
->declargslot
){
2731 zOld
= *psp
->declargslot
;
2735 nOld
= lemonStrlen(zOld
);
2736 n
= nOld
+ nNew
+ 20;
2737 addLineMacro
= !psp
->gp
->nolinenosflag
2738 && psp
->insertLineMacro
2739 && psp
->tokenlineno
>1
2740 && (psp
->decllinenoslot
==0 || psp
->decllinenoslot
[0]!=0);
2742 for(z
=psp
->filename
, nBack
=0; *z
; z
++){
2743 if( *z
=='\\' ) nBack
++;
2745 lemon_sprintf(zLine
, "#line %d ", psp
->tokenlineno
);
2746 nLine
= lemonStrlen(zLine
);
2747 n
+= nLine
+ lemonStrlen(psp
->filename
) + nBack
;
2749 *psp
->declargslot
= (char *) lemon_realloc(*psp
->declargslot
, n
);
2750 zBuf
= *psp
->declargslot
+ nOld
;
2752 if( nOld
&& zBuf
[-1]!='\n' ){
2755 memcpy(zBuf
, zLine
, nLine
);
2758 for(z
=psp
->filename
; *z
; z
++){
2767 if( psp
->decllinenoslot
&& psp
->decllinenoslot
[0]==0 ){
2768 psp
->decllinenoslot
[0] = psp
->tokenlineno
;
2770 memcpy(zBuf
, zNew
, nNew
);
2773 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2775 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2776 "Illegal argument to %%%s: %s",psp
->declkeyword
,x
);
2778 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2781 case WAITING_FOR_FALLBACK_ID
:
2783 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2784 }else if( !ISUPPER(x
[0]) ){
2785 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2786 "%%fallback argument \"%s\" should be a token", x
);
2789 struct symbol
*sp
= Symbol_new(x
);
2790 if( psp
->fallback
==0 ){
2792 }else if( sp
->fallback
){
2793 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2794 "More than one fallback assigned to token %s", x
);
2797 sp
->fallback
= psp
->fallback
;
2798 psp
->gp
->has_fallback
= 1;
2802 case WAITING_FOR_TOKEN_NAME
:
2803 /* Tokens do not have to be declared before use. But they can be
2804 ** in order to control their assigned integer number. The number for
2805 ** each token is assigned when it is first seen. So by including
2807 ** %token ONE TWO THREE.
2809 ** early in the grammar file, that assigns small consecutive values
2810 ** to each of the tokens ONE TWO and THREE.
2813 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2814 }else if( !ISUPPER(x
[0]) ){
2815 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2816 "%%token argument \"%s\" should be a token", x
);
2819 (void)Symbol_new(x
);
2822 case WAITING_FOR_WILDCARD_ID
:
2824 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2825 }else if( !ISUPPER(x
[0]) ){
2826 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2827 "%%wildcard argument \"%s\" should be a token", x
);
2830 struct symbol
*sp
= Symbol_new(x
);
2831 if( psp
->gp
->wildcard
==0 ){
2832 psp
->gp
->wildcard
= sp
;
2834 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2835 "Extra wildcard to token: %s", x
);
2840 case WAITING_FOR_CLASS_ID
:
2841 if( !ISLOWER(x
[0]) ){
2842 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2843 "%%token_class must be followed by an identifier: %s", x
);
2845 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2846 }else if( Symbol_find(x
) ){
2847 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2848 "Symbol \"%s\" already used", x
);
2850 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2852 psp
->tkclass
= Symbol_new(x
);
2853 psp
->tkclass
->type
= MULTITERMINAL
;
2854 psp
->state
= WAITING_FOR_CLASS_TOKEN
;
2857 case WAITING_FOR_CLASS_TOKEN
:
2859 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2860 }else if( ISUPPER(x
[0]) || ((x
[0]=='|' || x
[0]=='/') && ISUPPER(x
[1])) ){
2861 struct symbol
*msp
= psp
->tkclass
;
2863 msp
->subsym
= (struct symbol
**) lemon_realloc(msp
->subsym
,
2864 sizeof(struct symbol
*)*msp
->nsubsym
);
2865 if( !ISUPPER(x
[0]) ) x
++;
2866 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(x
);
2868 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2869 "%%token_class argument \"%s\" should be a token", x
);
2871 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2874 case RESYNC_AFTER_RULE_ERROR
:
2875 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2877 case RESYNC_AFTER_DECL_ERROR
:
2878 if( x
[0]=='.' ) psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2879 if( x
[0]=='%' ) psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2884 /* The text in the input is part of the argument to an %ifdef or %ifndef.
2885 ** Evaluate the text as a boolean expression. Return true or false.
2887 static int eval_preprocessor_boolean(char *z
, int lineno
){
2892 for(i
=0; z
[i
]!=0; i
++){
2893 if( ISSPACE(z
[i
]) ) continue;
2895 if( !okTerm
) goto pp_syntax_error
;
2899 if( z
[i
]=='|' && z
[i
+1]=='|' ){
2900 if( okTerm
) goto pp_syntax_error
;
2906 if( z
[i
]=='&' && z
[i
+1]=='&' ){
2907 if( okTerm
) goto pp_syntax_error
;
2908 if( !res
) return 0;
2916 if( !okTerm
) goto pp_syntax_error
;
2917 for(k
=i
+1; z
[k
]; k
++){
2922 res
= eval_preprocessor_boolean(&z
[i
+1], -1);
2926 goto pp_syntax_error
;
2931 }else if( z
[k
]=='(' ){
2933 }else if( z
[k
]==0 ){
2935 goto pp_syntax_error
;
2945 if( ISALPHA(z
[i
]) ){
2947 if( !okTerm
) goto pp_syntax_error
;
2948 for(k
=i
+1; ISALNUM(z
[k
]) || z
[k
]=='_'; k
++){}
2951 for(j
=0; j
<nDefine
; j
++){
2952 if( strncmp(azDefine
[j
],&z
[i
],n
)==0 && azDefine
[j
][n
]==0 ){
2953 if( !bDefineUsed
[j
] ){
2969 goto pp_syntax_error
;
2975 fprintf(stderr
, "%%if syntax error on line %d.\n", lineno
);
2976 fprintf(stderr
, " %.*s <-- syntax error here\n", i
+1, z
);
2983 /* Run the preprocessor over the input file text. The global variables
2984 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2985 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2986 ** comments them out. Text in between is also commented out as appropriate.
2988 static void preprocess_input(char *z
){
2993 int start_lineno
= 1;
2994 for(i
=0; z
[i
]; i
++){
2995 if( z
[i
]=='\n' ) lineno
++;
2996 if( z
[i
]!='%' || (i
>0 && z
[i
-1]!='\n') ) continue;
2997 if( strncmp(&z
[i
],"%endif",6)==0 && ISSPACE(z
[i
+6]) ){
3001 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
3004 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
3005 }else if( strncmp(&z
[i
],"%else",5)==0 && ISSPACE(z
[i
+5]) ){
3008 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
3009 }else if( exclude
==0 ){
3012 start_lineno
= lineno
;
3014 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
3015 }else if( strncmp(&z
[i
],"%ifdef ",7)==0
3016 || strncmp(&z
[i
],"%if ",4)==0
3017 || strncmp(&z
[i
],"%ifndef ",8)==0 ){
3023 for(j
=i
; z
[j
] && !ISSPACE(z
[j
]); j
++){}
3026 while( z
[j
] && z
[j
]!='\n' ){ j
++; }
3029 exclude
= eval_preprocessor_boolean(&z
[iBool
], lineno
);
3031 if( !isNot
) exclude
= !exclude
;
3034 start_lineno
= lineno
;
3037 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
3041 fprintf(stderr
,"unterminated %%ifdef starting on line %d\n", start_lineno
);
3046 /* In spite of its name, this function is really a scanner. It read
3047 ** in the entire input file (all at once) then tokenizes it. Each
3048 ** token is passed to the function "parseonetoken" which builds all
3049 ** the appropriate data structures in the global state vector "gp".
3051 void Parse(struct lemon
*gp
)
3056 unsigned int filesize
;
3062 memset(&ps
, '\0', sizeof(ps
));
3064 ps
.filename
= gp
->filename
;
3066 ps
.state
= INITIALIZE
;
3068 /* Begin by reading the input file */
3069 fp
= fopen(ps
.filename
,"rb");
3071 ErrorMsg(ps
.filename
,0,"Can't open this file for reading.");
3076 filesize
= ftell(fp
);
3078 filebuf
= (char *)lemon_malloc( filesize
+1 );
3079 if( filesize
>100000000 || filebuf
==0 ){
3080 ErrorMsg(ps
.filename
,0,"Input file too large.");
3081 lemon_free(filebuf
);
3086 if( fread(filebuf
,1,filesize
,fp
)!=filesize
){
3087 ErrorMsg(ps
.filename
,0,"Can't read in all %d bytes of this file.",
3089 lemon_free(filebuf
);
3095 filebuf
[filesize
] = 0;
3097 /* Make an initial pass through the file to handle %ifdef and %ifndef */
3098 preprocess_input(filebuf
);
3099 if( gp
->printPreprocessed
){
3100 printf("%s\n", filebuf
);
3104 /* Now scan the text of the input file */
3106 for(cp
=filebuf
; (c
= *cp
)!=0; ){
3107 if( c
=='\n' ) lineno
++; /* Keep track of the line number */
3108 if( ISSPACE(c
) ){ cp
++; continue; } /* Skip all white space */
3109 if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments */
3111 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
3114 if( c
=='/' && cp
[1]=='*' ){ /* Skip C style comments */
3116 if( (*cp
)=='/' ) cp
++;
3117 while( (c
= *cp
)!=0 && (c
!='/' || cp
[-1]!='*') ){
3118 if( c
=='\n' ) lineno
++;
3124 ps
.tokenstart
= cp
; /* Mark the beginning of the token */
3125 ps
.tokenlineno
= lineno
; /* Linenumber on which token begins */
3126 if( c
=='\"' ){ /* String literals */
3128 while( (c
= *cp
)!=0 && c
!='\"' ){
3129 if( c
=='\n' ) lineno
++;
3133 ErrorMsg(ps
.filename
,startline
,
3134 "String starting on this line is not terminated before "
3135 "the end of the file.");
3141 }else if( c
=='{' ){ /* A block of C code */
3144 for(level
=1; (c
= *cp
)!=0 && (level
>1 || c
!='}'); cp
++){
3145 if( c
=='\n' ) lineno
++;
3146 else if( c
=='{' ) level
++;
3147 else if( c
=='}' ) level
--;
3148 else if( c
=='/' && cp
[1]=='*' ){ /* Skip comments */
3152 while( (c
= *cp
)!=0 && (c
!='/' || prevc
!='*') ){
3153 if( c
=='\n' ) lineno
++;
3157 }else if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments too */
3159 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
3161 }else if( c
=='\'' || c
=='\"' ){ /* String a character literals */
3162 int startchar
, prevc
;
3165 for(cp
++; (c
= *cp
)!=0 && (c
!=startchar
|| prevc
=='\\'); cp
++){
3166 if( c
=='\n' ) lineno
++;
3167 if( prevc
=='\\' ) prevc
= 0;
3173 ErrorMsg(ps
.filename
,ps
.tokenlineno
,
3174 "C code starting on this line is not terminated before "
3175 "the end of the file.");
3181 }else if( ISALNUM(c
) ){ /* Identifiers */
3182 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
3184 }else if( c
==':' && cp
[1]==':' && cp
[2]=='=' ){ /* The operator "::=" */
3187 }else if( (c
=='/' || c
=='|') && ISALPHA(cp
[1]) ){
3189 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
3191 }else{ /* All other (one character) operators */
3196 *cp
= 0; /* Null terminate the token */
3197 parseonetoken(&ps
); /* Parse the token */
3198 *cp
= (char)c
; /* Restore the buffer */
3201 lemon_free(filebuf
); /* Release the buffer after parsing */
3202 gp
->rule
= ps
.firstrule
;
3203 gp
->errorcnt
= ps
.errorcnt
;
3205 /*************************** From the file "plink.c" *********************/
3207 ** Routines processing configuration follow-set propagation links
3208 ** in the LEMON parser generator.
3210 static struct plink
*plink_freelist
= 0;
3212 /* Allocate a new plink */
3213 struct plink
*Plink_new(void){
3214 struct plink
*newlink
;
3216 if( plink_freelist
==0 ){
3219 plink_freelist
= (struct plink
*)lemon_calloc( amt
, sizeof(struct plink
) );
3220 if( plink_freelist
==0 ){
3222 "Unable to allocate memory for a new follow-set propagation link.\n");
3225 for(i
=0; i
<amt
-1; i
++) plink_freelist
[i
].next
= &plink_freelist
[i
+1];
3226 plink_freelist
[amt
-1].next
= 0;
3228 newlink
= plink_freelist
;
3229 plink_freelist
= plink_freelist
->next
;
3233 /* Add a plink to a plink list */
3234 void Plink_add(struct plink
**plpp
, struct config
*cfp
)
3236 struct plink
*newlink
;
3237 newlink
= Plink_new();
3238 newlink
->next
= *plpp
;
3243 /* Transfer every plink on the list "from" to the list "to" */
3244 void Plink_copy(struct plink
**to
, struct plink
*from
)
3246 struct plink
*nextpl
;
3248 nextpl
= from
->next
;
3255 /* Delete every plink on the list */
3256 void Plink_delete(struct plink
*plp
)
3258 struct plink
*nextpl
;
3262 plp
->next
= plink_freelist
;
3263 plink_freelist
= plp
;
3267 /*********************** From the file "report.c" **************************/
3269 ** Procedures for generating reports and tables in the LEMON parser generator.
3272 /* Generate a filename with the given suffix.
3274 PRIVATE
char *file_makename(struct lemon
*lemp
, const char *suffix
)
3278 char *filename
= lemp
->filename
;
3282 cp
= strrchr(filename
, '/');
3283 if( cp
) filename
= cp
+ 1;
3285 sz
= lemonStrlen(filename
);
3286 sz
+= lemonStrlen(suffix
);
3287 if( outputDir
) sz
+= lemonStrlen(outputDir
) + 1;
3289 name
= (char*)lemon_malloc( sz
);
3291 fprintf(stderr
,"Can't allocate space for a filename.\n");
3296 lemon_strcpy(name
, outputDir
);
3297 lemon_strcat(name
, "/");
3299 lemon_strcat(name
,filename
);
3300 cp
= strrchr(name
,'.');
3302 lemon_strcat(name
,suffix
);
3306 /* Open a file with a name based on the name of the input file,
3307 ** but with a different (specified) suffix, and return a pointer
3309 PRIVATE
FILE *file_open(
3316 if( lemp
->outname
) lemon_free(lemp
->outname
);
3317 lemp
->outname
= file_makename(lemp
, suffix
);
3318 fp
= fopen(lemp
->outname
,mode
);
3319 if( fp
==0 && *mode
=='w' ){
3320 fprintf(stderr
,"Can't open file \"%s\".\n",lemp
->outname
);
3327 /* Print the text of a rule
3329 void rule_print(FILE *out
, struct rule
*rp
){
3331 fprintf(out
, "%s",rp
->lhs
->name
);
3332 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3333 fprintf(out
," ::=");
3334 for(i
=0; i
<rp
->nrhs
; i
++){
3335 struct symbol
*sp
= rp
->rhs
[i
];
3336 if( sp
->type
==MULTITERMINAL
){
3337 fprintf(out
," %s", sp
->subsym
[0]->name
);
3338 for(j
=1; j
<sp
->nsubsym
; j
++){
3339 fprintf(out
,"|%s", sp
->subsym
[j
]->name
);
3342 fprintf(out
," %s", sp
->name
);
3344 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3348 /* Duplicate the input file without comments and without actions
3350 void Reprint(struct lemon
*lemp
)
3354 int i
, j
, maxlen
, len
, ncolumns
, skip
;
3355 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp
->filename
);
3357 for(i
=0; i
<lemp
->nsymbol
; i
++){
3358 sp
= lemp
->symbols
[i
];
3359 len
= lemonStrlen(sp
->name
);
3360 if( len
>maxlen
) maxlen
= len
;
3362 ncolumns
= 76/(maxlen
+5);
3363 if( ncolumns
<1 ) ncolumns
= 1;
3364 skip
= (lemp
->nsymbol
+ ncolumns
- 1)/ncolumns
;
3365 for(i
=0; i
<skip
; i
++){
3367 for(j
=i
; j
<lemp
->nsymbol
; j
+=skip
){
3368 sp
= lemp
->symbols
[j
];
3369 assert( sp
->index
==j
);
3370 printf(" %3d %-*.*s",j
,maxlen
,maxlen
,sp
->name
);
3374 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3375 rule_print(stdout
, rp
);
3377 if( rp
->precsym
) printf(" [%s]",rp
->precsym
->name
);
3378 /* if( rp->code ) printf("\n %s",rp->code); */
3383 /* Print a single rule.
3385 void RulePrint(FILE *fp
, struct rule
*rp
, int iCursor
){
3388 fprintf(fp
,"%s ::=",rp
->lhs
->name
);
3389 for(i
=0; i
<=rp
->nrhs
; i
++){
3390 if( i
==iCursor
) fprintf(fp
," *");
3391 if( i
==rp
->nrhs
) break;
3393 if( sp
->type
==MULTITERMINAL
){
3394 fprintf(fp
," %s", sp
->subsym
[0]->name
);
3395 for(j
=1; j
<sp
->nsubsym
; j
++){
3396 fprintf(fp
,"|%s",sp
->subsym
[j
]->name
);
3399 fprintf(fp
," %s", sp
->name
);
3404 /* Print the rule for a configuration.
3406 void ConfigPrint(FILE *fp
, struct config
*cfp
){
3407 RulePrint(fp
, cfp
->rp
, cfp
->dot
);
3413 PRIVATE
void SetPrint(out
,set
,lemp
)
3421 fprintf(out
,"%12s[","");
3422 for(i
=0; i
<lemp
->nterminal
; i
++){
3423 if( SetFind(set
,i
) ){
3424 fprintf(out
,"%s%s",spacer
,lemp
->symbols
[i
]->name
);
3431 /* Print a plink chain */
3432 PRIVATE
void PlinkPrint(out
,plp
,tag
)
3438 fprintf(out
,"%12s%s (state %2d) ","",tag
,plp
->cfp
->stp
->statenum
);
3439 ConfigPrint(out
,plp
->cfp
);
3446 /* Print an action to the given file descriptor. Return FALSE if
3447 ** nothing was actually printed.
3450 struct action
*ap
, /* The action to print */
3451 FILE *fp
, /* Print the action here */
3452 int indent
/* Indent by this amount */
3457 struct state
*stp
= ap
->x
.stp
;
3458 fprintf(fp
,"%*s shift %-7d",indent
,ap
->sp
->name
,stp
->statenum
);
3462 struct rule
*rp
= ap
->x
.rp
;
3463 fprintf(fp
,"%*s reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3464 RulePrint(fp
, rp
, -1);
3468 struct rule
*rp
= ap
->x
.rp
;
3469 fprintf(fp
,"%*s shift-reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3470 RulePrint(fp
, rp
, -1);
3474 fprintf(fp
,"%*s accept",indent
,ap
->sp
->name
);
3477 fprintf(fp
,"%*s error",indent
,ap
->sp
->name
);
3481 fprintf(fp
,"%*s reduce %-7d ** Parsing conflict **",
3482 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3485 fprintf(fp
,"%*s shift %-7d ** Parsing conflict **",
3486 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3489 if( showPrecedenceConflict
){
3490 fprintf(fp
,"%*s shift %-7d -- dropped by precedence",
3491 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3497 if( showPrecedenceConflict
){
3498 fprintf(fp
,"%*s reduce %-7d -- dropped by precedence",
3499 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3508 if( result
&& ap
->spOpt
){
3509 fprintf(fp
," /* because %s==%s */", ap
->sp
->name
, ap
->spOpt
->name
);
3514 /* Generate the "*.out" log file */
3515 void ReportOutput(struct lemon
*lemp
)
3524 fp
= file_open(lemp
,".out","wb");
3526 for(i
=0; i
<lemp
->nxstate
; i
++){
3527 stp
= lemp
->sorted
[i
];
3528 fprintf(fp
,"State %d:\n",stp
->statenum
);
3529 if( lemp
->basisflag
) cfp
=stp
->bp
;
3533 if( cfp
->dot
==cfp
->rp
->nrhs
){
3534 lemon_sprintf(buf
,"(%d)",cfp
->rp
->iRule
);
3535 fprintf(fp
," %5s ",buf
);
3539 ConfigPrint(fp
,cfp
);
3542 SetPrint(fp
,cfp
->fws
,lemp
);
3543 PlinkPrint(fp
,cfp
->fplp
,"To ");
3544 PlinkPrint(fp
,cfp
->bplp
,"From");
3546 if( lemp
->basisflag
) cfp
=cfp
->bp
;
3550 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3551 if( PrintAction(ap
,fp
,30) ) fprintf(fp
,"\n");
3555 fprintf(fp
, "----------------------------------------------------\n");
3556 fprintf(fp
, "Symbols:\n");
3557 fprintf(fp
, "The first-set of non-terminals is shown after the name.\n\n");
3558 for(i
=0; i
<lemp
->nsymbol
; i
++){
3562 sp
= lemp
->symbols
[i
];
3563 fprintf(fp
, " %3d: %s", i
, sp
->name
);
3564 if( sp
->type
==NONTERMINAL
){
3567 fprintf(fp
, " <lambda>");
3569 for(j
=0; j
<lemp
->nterminal
; j
++){
3570 if( sp
->firstset
&& SetFind(sp
->firstset
, j
) ){
3571 fprintf(fp
, " %s", lemp
->symbols
[j
]->name
);
3575 if( sp
->prec
>=0 ) fprintf(fp
," (precedence=%d)", sp
->prec
);
3578 fprintf(fp
, "----------------------------------------------------\n");
3579 fprintf(fp
, "Syntax-only Symbols:\n");
3580 fprintf(fp
, "The following symbols never carry semantic content.\n\n");
3581 for(i
=n
=0; i
<lemp
->nsymbol
; i
++){
3583 struct symbol
*sp
= lemp
->symbols
[i
];
3584 if( sp
->bContent
) continue;
3585 w
= (int)strlen(sp
->name
);
3586 if( n
>0 && n
+w
>75 ){
3594 fprintf(fp
, "%s", sp
->name
);
3597 if( n
>0 ) fprintf(fp
, "\n");
3598 fprintf(fp
, "----------------------------------------------------\n");
3599 fprintf(fp
, "Rules:\n");
3600 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3601 fprintf(fp
, "%4d: ", rp
->iRule
);
3605 fprintf(fp
," [%s precedence=%d]",
3606 rp
->precsym
->name
, rp
->precsym
->prec
);
3614 /* Search for the file "name" which is in the same directory as
3615 ** the executable */
3616 PRIVATE
char *pathsearch(char *argv0
, char *name
, int modemask
)
3618 const char *pathlist
;
3619 char *pathbufptr
= 0;
3625 cp
= strrchr(argv0
,'\\');
3627 cp
= strrchr(argv0
,'/');
3632 path
= (char *)lemon_malloc( lemonStrlen(argv0
) + lemonStrlen(name
) + 2 );
3633 if( path
) lemon_sprintf(path
,"%s/%s",argv0
,name
);
3636 pathlist
= getenv("PATH");
3637 if( pathlist
==0 ) pathlist
= ".:/bin:/usr/bin";
3638 pathbuf
= (char *) lemon_malloc( lemonStrlen(pathlist
) + 1 );
3639 path
= (char *)lemon_malloc( lemonStrlen(pathlist
)+lemonStrlen(name
)+2 );
3640 if( (pathbuf
!= 0) && (path
!=0) ){
3641 pathbufptr
= pathbuf
;
3642 lemon_strcpy(pathbuf
, pathlist
);
3644 cp
= strchr(pathbuf
,':');
3645 if( cp
==0 ) cp
= &pathbuf
[lemonStrlen(pathbuf
)];
3648 lemon_sprintf(path
,"%s/%s",pathbuf
,name
);
3650 if( c
==0 ) pathbuf
[0] = 0;
3651 else pathbuf
= &cp
[1];
3652 if( access(path
,modemask
)==0 ) break;
3655 lemon_free(pathbufptr
);
3660 /* Given an action, compute the integer value for that action
3661 ** which is to be put in the action table of the generated machine.
3662 ** Return negative if no action should be generated.
3664 PRIVATE
int compute_action(struct lemon
*lemp
, struct action
*ap
)
3668 case SHIFT
: act
= ap
->x
.stp
->statenum
; break;
3670 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3671 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3672 ** REDUCE action: */
3673 if( ap
->sp
->index
>=lemp
->nterminal
3674 && (lemp
->errsym
==0 || ap
->sp
->index
!=lemp
->errsym
->index
)
3676 act
= lemp
->minReduce
+ ap
->x
.rp
->iRule
;
3678 act
= lemp
->minShiftReduce
+ ap
->x
.rp
->iRule
;
3682 case REDUCE
: act
= lemp
->minReduce
+ ap
->x
.rp
->iRule
; break;
3683 case ERROR
: act
= lemp
->errAction
; break;
3684 case ACCEPT
: act
= lemp
->accAction
; break;
3685 default: act
= -1; break;
3690 #define LINESIZE 1000
3691 /* The next cluster of routines are for reading the template file
3692 ** and writing the results to the generated parser */
3693 /* The first function transfers data from "in" to "out" until
3694 ** a line is seen which begins with "%%". The line number is
3697 ** if name!=0, then any word that begin with "Parse" is changed to
3698 ** begin with *name instead.
3700 PRIVATE
void tplt_xfer(char *name
, FILE *in
, FILE *out
, int *lineno
)
3703 char line
[LINESIZE
];
3704 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3708 for(i
=0; line
[i
]; i
++){
3709 if( line
[i
]=='P' && strncmp(&line
[i
],"Parse",5)==0
3710 && (i
==0 || !ISALPHA(line
[i
-1]))
3712 if( i
>iStart
) fprintf(out
,"%.*s",i
-iStart
,&line
[iStart
]);
3713 fprintf(out
,"%s",name
);
3719 fprintf(out
,"%s",&line
[iStart
]);
3723 /* Skip forward past the header of the template file to the first "%%"
3725 PRIVATE
void tplt_skip_header(FILE *in
, int *lineno
)
3727 char line
[LINESIZE
];
3728 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3733 /* The next function finds the template file and opens it, returning
3734 ** a pointer to the opened file. */
3735 PRIVATE
FILE *tplt_open(struct lemon
*lemp
)
3737 static char templatename
[] = "lempar.c";
3744 /* first, see if user specified a template filename on the command line. */
3745 if (user_templatename
!= 0) {
3746 if( access(user_templatename
,004)==-1 ){
3747 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3752 in
= fopen(user_templatename
,"rb");
3754 fprintf(stderr
,"Can't open the template file \"%s\".\n",
3762 cp
= strrchr(lemp
->filename
,'.');
3764 lemon_sprintf(buf
,"%.*s.lt",(int)(cp
-lemp
->filename
),lemp
->filename
);
3766 lemon_sprintf(buf
,"%s.lt",lemp
->filename
);
3768 if( access(buf
,004)==0 ){
3770 }else if( access(templatename
,004)==0 ){
3771 tpltname
= templatename
;
3773 toFree
= tpltname
= pathsearch(lemp
->argv
[0],templatename
,0);
3776 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3781 in
= fopen(tpltname
,"rb");
3783 fprintf(stderr
,"Can't open the template file \"%s\".\n",tpltname
);
3790 /* Print a #line directive line to the output file. */
3791 PRIVATE
void tplt_linedir(FILE *out
, int lineno
, char *filename
)
3793 fprintf(out
,"#line %d \"",lineno
);
3795 if( *filename
== '\\' ) putc('\\',out
);
3796 putc(*filename
,out
);
3799 fprintf(out
,"\"\n");
3802 /* Print a string to the file and keep the linenumber up to date */
3803 PRIVATE
void tplt_print(FILE *out
, struct lemon
*lemp
, char *str
, int *lineno
)
3805 if( str
==0 ) return;
3808 if( *str
=='\n' ) (*lineno
)++;
3811 if( str
[-1]!='\n' ){
3815 if (!lemp
->nolinenosflag
) {
3816 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3822 ** The following routine emits code for the destructor for the
3825 void emit_destructor_code(
3833 if( sp
->type
==TERMINAL
){
3834 cp
= lemp
->tokendest
;
3836 fprintf(out
,"{\n"); (*lineno
)++;
3837 }else if( sp
->destructor
){
3838 cp
= sp
->destructor
;
3839 fprintf(out
,"{\n"); (*lineno
)++;
3840 if( !lemp
->nolinenosflag
){
3842 tplt_linedir(out
,sp
->destLineno
,lemp
->filename
);
3844 }else if( lemp
->vardest
){
3847 fprintf(out
,"{\n"); (*lineno
)++;
3849 assert( 0 ); /* Cannot happen */
3852 if( *cp
=='$' && cp
[1]=='$' ){
3853 fprintf(out
,"(yypminor->yy%d)",sp
->dtnum
);
3857 if( *cp
=='\n' ) (*lineno
)++;
3860 fprintf(out
,"\n"); (*lineno
)++;
3861 if (!lemp
->nolinenosflag
) {
3862 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3864 fprintf(out
,"}\n"); (*lineno
)++;
3869 ** Return TRUE (non-zero) if the given symbol has a destructor.
3871 int has_destructor(struct symbol
*sp
, struct lemon
*lemp
)
3874 if( sp
->type
==TERMINAL
){
3875 ret
= lemp
->tokendest
!=0;
3877 ret
= lemp
->vardest
!=0 || sp
->destructor
!=0;
3883 ** Append text to a dynamically allocated string. If zText is 0 then
3884 ** reset the string to be empty again. Always return the complete text
3885 ** of the string (which is overwritten with each call).
3887 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3888 ** \000 terminator is stored. zText can contain up to two instances of
3889 ** %d. The values of p1 and p2 are written into the first and second
3892 ** If n==-1, then the previous character is overwritten.
3894 PRIVATE
char *append_str(const char *zText
, int n
, int p1
, int p2
){
3895 static char empty
[1] = { 0 };
3897 static int alloced
= 0;
3898 static int used
= 0;
3902 if( used
==0 && z
!=0 ) z
[0] = 0;
3911 n
= lemonStrlen(zText
);
3913 if( (int) (n
+sizeof(zInt
)*2+used
) >= alloced
){
3914 alloced
= n
+ sizeof(zInt
)*2 + used
+ 200;
3915 z
= (char *) lemon_realloc(z
, alloced
);
3917 if( z
==0 ) return empty
;
3920 if( c
=='%' && n
>0 && zText
[0]=='d' ){
3921 lemon_sprintf(zInt
, "%d", p1
);
3923 lemon_strcpy(&z
[used
], zInt
);
3924 used
+= lemonStrlen(&z
[used
]);
3928 z
[used
++] = (char)c
;
3936 ** Write and transform the rp->code string so that symbols are expanded.
3937 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3939 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3942 PRIVATE
int translate_code(struct lemon
*lemp
, struct rule
*rp
){
3945 int rc
= 0; /* True if yylhsminor is used */
3946 int dontUseRhs0
= 0; /* If true, use of left-most RHS label is illegal */
3947 const char *zSkip
= 0; /* The zOvwrt comment within rp->code, or NULL */
3948 char lhsused
= 0; /* True if the LHS element has been used */
3949 char lhsdirect
; /* True if LHS writes directly into stack */
3950 char used
[MAXRHS
]; /* True for each RHS element which is used */
3951 char zLhs
[50]; /* Convert the LHS symbol into this string */
3952 char zOvwrt
[900]; /* Comment that to allow LHS to overwrite RHS */
3954 for(i
=0; i
<rp
->nrhs
; i
++) used
[i
] = 0;
3958 static char newlinestr
[2] = { '\n', '\0' };
3959 rp
->code
= newlinestr
;
3960 rp
->line
= rp
->ruleline
;
3968 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3970 }else if( rp
->rhsalias
[0]==0 ){
3971 /* The left-most RHS symbol has no value. LHS direct is ok. But
3972 ** we have to call the destructor on the RHS symbol first. */
3974 if( has_destructor(rp
->rhs
[0],lemp
) ){
3975 append_str(0,0,0,0);
3976 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3977 rp
->rhs
[0]->index
,1-rp
->nrhs
);
3978 rp
->codePrefix
= Strsafe(append_str(0,0,0,0));
3981 }else if( rp
->lhsalias
==0 ){
3982 /* There is no LHS value symbol. */
3984 }else if( strcmp(rp
->lhsalias
,rp
->rhsalias
[0])==0 ){
3985 /* The LHS symbol and the left-most RHS symbol are the same, so
3986 ** direct writing is allowed */
3990 if( rp
->lhs
->dtnum
!=rp
->rhs
[0]->dtnum
){
3991 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3992 "%s(%s) and %s(%s) share the same label but have "
3993 "different datatypes.",
3994 rp
->lhs
->name
, rp
->lhsalias
, rp
->rhs
[0]->name
, rp
->rhsalias
[0]);
3998 lemon_sprintf(zOvwrt
, "/*%s-overwrites-%s*/",
3999 rp
->lhsalias
, rp
->rhsalias
[0]);
4000 zSkip
= strstr(rp
->code
, zOvwrt
);
4002 /* The code contains a special comment that indicates that it is safe
4003 ** for the LHS label to overwrite left-most RHS label. */
4010 sprintf(zLhs
, "yymsp[%d].minor.yy%d",1-rp
->nrhs
,rp
->lhs
->dtnum
);
4013 sprintf(zLhs
, "yylhsminor.yy%d",rp
->lhs
->dtnum
);
4016 append_str(0,0,0,0);
4018 /* This const cast is wrong but harmless, if we're careful. */
4019 for(cp
=(char *)rp
->code
; *cp
; cp
++){
4021 append_str(zOvwrt
,0,0,0);
4022 cp
+= lemonStrlen(zOvwrt
)-1;
4026 if( ISALPHA(*cp
) && (cp
==rp
->code
|| (!ISALNUM(cp
[-1]) && cp
[-1]!='_')) ){
4028 for(xp
= &cp
[1]; ISALNUM(*xp
) || *xp
=='_'; xp
++);
4031 if( rp
->lhsalias
&& strcmp(cp
,rp
->lhsalias
)==0 ){
4032 append_str(zLhs
,0,0,0);
4036 for(i
=0; i
<rp
->nrhs
; i
++){
4037 if( rp
->rhsalias
[i
] && strcmp(cp
,rp
->rhsalias
[i
])==0 ){
4038 if( i
==0 && dontUseRhs0
){
4039 ErrorMsg(lemp
->filename
,rp
->ruleline
,
4040 "Label %s used after '%s'.",
4041 rp
->rhsalias
[0], zOvwrt
);
4043 }else if( cp
!=rp
->code
&& cp
[-1]=='@' ){
4044 /* If the argument is of the form @X then substituted
4045 ** the token number of X, not the value of X */
4046 append_str("yymsp[%d].major",-1,i
-rp
->nrhs
+1,0);
4048 struct symbol
*sp
= rp
->rhs
[i
];
4050 if( sp
->type
==MULTITERMINAL
){
4051 dtnum
= sp
->subsym
[0]->dtnum
;
4055 append_str("yymsp[%d].minor.yy%d",0,i
-rp
->nrhs
+1, dtnum
);
4065 append_str(cp
, 1, 0, 0);
4068 /* Main code generation completed */
4069 cp
= append_str(0,0,0,0);
4070 if( cp
&& cp
[0] ) rp
->code
= Strsafe(cp
);
4071 append_str(0,0,0,0);
4073 /* Check to make sure the LHS has been used */
4074 if( rp
->lhsalias
&& !lhsused
){
4075 ErrorMsg(lemp
->filename
,rp
->ruleline
,
4076 "Label \"%s\" for \"%s(%s)\" is never used.",
4077 rp
->lhsalias
,rp
->lhs
->name
,rp
->lhsalias
);
4081 /* Generate destructor code for RHS minor values which are not referenced.
4082 ** Generate error messages for unused labels and duplicate labels.
4084 for(i
=0; i
<rp
->nrhs
; i
++){
4085 if( rp
->rhsalias
[i
] ){
4088 if( rp
->lhsalias
&& strcmp(rp
->lhsalias
,rp
->rhsalias
[i
])==0 ){
4089 ErrorMsg(lemp
->filename
,rp
->ruleline
,
4090 "%s(%s) has the same label as the LHS but is not the left-most "
4091 "symbol on the RHS.",
4092 rp
->rhs
[i
]->name
, rp
->rhsalias
[i
]);
4096 if( rp
->rhsalias
[j
] && strcmp(rp
->rhsalias
[j
],rp
->rhsalias
[i
])==0 ){
4097 ErrorMsg(lemp
->filename
,rp
->ruleline
,
4098 "Label %s used for multiple symbols on the RHS of a rule.",
4106 ErrorMsg(lemp
->filename
,rp
->ruleline
,
4107 "Label %s for \"%s(%s)\" is never used.",
4108 rp
->rhsalias
[i
],rp
->rhs
[i
]->name
,rp
->rhsalias
[i
]);
4111 }else if( i
>0 && has_destructor(rp
->rhs
[i
],lemp
) ){
4112 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
4113 rp
->rhs
[i
]->index
,i
-rp
->nrhs
+1);
4117 /* If unable to write LHS values directly into the stack, write the
4118 ** saved LHS value now. */
4120 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp
->nrhs
, rp
->lhs
->dtnum
);
4121 append_str(zLhs
, 0, 0, 0);
4122 append_str(";\n", 0, 0, 0);
4125 /* Suffix code generation complete */
4126 cp
= append_str(0,0,0,0);
4128 rp
->codeSuffix
= Strsafe(cp
);
4136 ** Generate code which executes when the rule "rp" is reduced. Write
4137 ** the code to "out". Make sure lineno stays up-to-date.
4139 PRIVATE
void emit_code(
4147 /* Setup code prior to the #line directive */
4148 if( rp
->codePrefix
&& rp
->codePrefix
[0] ){
4149 fprintf(out
, "{%s", rp
->codePrefix
);
4150 for(cp
=rp
->codePrefix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
4153 /* Generate code to do the reduce action */
4155 if( !lemp
->nolinenosflag
){
4157 tplt_linedir(out
,rp
->line
,lemp
->filename
);
4159 fprintf(out
,"{%s",rp
->code
);
4160 for(cp
=rp
->code
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
4161 fprintf(out
,"}\n"); (*lineno
)++;
4162 if( !lemp
->nolinenosflag
){
4164 tplt_linedir(out
,*lineno
,lemp
->outname
);
4168 /* Generate breakdown code that occurs after the #line directive */
4169 if( rp
->codeSuffix
&& rp
->codeSuffix
[0] ){
4170 fprintf(out
, "%s", rp
->codeSuffix
);
4171 for(cp
=rp
->codeSuffix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
4174 if( rp
->codePrefix
){
4175 fprintf(out
, "}\n"); (*lineno
)++;
4182 ** Print the definition of the union used for the parser's data stack.
4183 ** This union contains fields for every possible data type for tokens
4184 ** and nonterminals. In the process of computing and printing this
4185 ** union, also set the ".dtnum" field of every terminal and nonterminal
4188 void print_stack_union(
4189 FILE *out
, /* The output stream */
4190 struct lemon
*lemp
, /* The main info structure for this parser */
4191 int *plineno
, /* Pointer to the line number */
4192 int mhflag
/* True if generating makeheaders output */
4194 int lineno
; /* The line number of the output */
4195 char **types
; /* A hash table of datatypes */
4196 int arraysize
; /* Size of the "types" array */
4197 int maxdtlength
; /* Maximum length of any ".datatype" field. */
4198 char *stddt
; /* Standardized name for a datatype */
4199 int i
,j
; /* Loop counters */
4200 unsigned hash
; /* For hashing the name of a type */
4201 const char *name
; /* Name of the parser */
4203 /* Allocate and initialize types[] and allocate stddt[] */
4204 arraysize
= lemp
->nsymbol
* 2;
4205 types
= (char**)lemon_calloc( arraysize
, sizeof(char*) );
4207 fprintf(stderr
,"Out of memory.\n");
4210 for(i
=0; i
<arraysize
; i
++) types
[i
] = 0;
4212 if( lemp
->vartype
){
4213 maxdtlength
= lemonStrlen(lemp
->vartype
);
4215 for(i
=0; i
<lemp
->nsymbol
; i
++){
4217 struct symbol
*sp
= lemp
->symbols
[i
];
4218 if( sp
->datatype
==0 ) continue;
4219 len
= lemonStrlen(sp
->datatype
);
4220 if( len
>maxdtlength
) maxdtlength
= len
;
4222 stddt
= (char*)lemon_malloc( maxdtlength
*2 + 1 );
4224 fprintf(stderr
,"Out of memory.\n");
4228 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4229 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
4230 ** used for terminal symbols. If there is no %default_type defined then
4231 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4232 ** a datatype using the %type directive.
4234 for(i
=0; i
<lemp
->nsymbol
; i
++){
4235 struct symbol
*sp
= lemp
->symbols
[i
];
4237 if( sp
==lemp
->errsym
){
4238 sp
->dtnum
= arraysize
+1;
4241 if( sp
->type
!=NONTERMINAL
|| (sp
->datatype
==0 && lemp
->vartype
==0) ){
4246 if( cp
==0 ) cp
= lemp
->vartype
;
4248 while( ISSPACE(*cp
) ) cp
++;
4249 while( *cp
) stddt
[j
++] = *cp
++;
4250 while( j
>0 && ISSPACE(stddt
[j
-1]) ) j
--;
4252 if( lemp
->tokentype
&& strcmp(stddt
, lemp
->tokentype
)==0 ){
4257 for(j
=0; stddt
[j
]; j
++){
4258 hash
= hash
*53 + stddt
[j
];
4260 hash
= (hash
& 0x7fffffff)%arraysize
;
4261 while( types
[hash
] ){
4262 if( strcmp(types
[hash
],stddt
)==0 ){
4263 sp
->dtnum
= hash
+ 1;
4267 if( hash
>=(unsigned)arraysize
) hash
= 0;
4269 if( types
[hash
]==0 ){
4270 sp
->dtnum
= hash
+ 1;
4271 types
[hash
] = (char*)lemon_malloc( lemonStrlen(stddt
)+1 );
4272 if( types
[hash
]==0 ){
4273 fprintf(stderr
,"Out of memory.\n");
4276 lemon_strcpy(types
[hash
],stddt
);
4280 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4281 name
= lemp
->name
? lemp
->name
: "Parse";
4283 if( mhflag
){ fprintf(out
,"#if INTERFACE\n"); lineno
++; }
4284 fprintf(out
,"#define %sTOKENTYPE %s\n",name
,
4285 lemp
->tokentype
?lemp
->tokentype
:"void*"); lineno
++;
4286 if( mhflag
){ fprintf(out
,"#endif\n"); lineno
++; }
4287 fprintf(out
,"typedef union {\n"); lineno
++;
4288 fprintf(out
," int yyinit;\n"); lineno
++;
4289 fprintf(out
," %sTOKENTYPE yy0;\n",name
); lineno
++;
4290 for(i
=0; i
<arraysize
; i
++){
4291 if( types
[i
]==0 ) continue;
4292 fprintf(out
," %s yy%d;\n",types
[i
],i
+1); lineno
++;
4293 lemon_free(types
[i
]);
4295 if( lemp
->errsym
&& lemp
->errsym
->useCnt
){
4296 fprintf(out
," int yy%d;\n",lemp
->errsym
->dtnum
); lineno
++;
4300 fprintf(out
,"} YYMINORTYPE;\n"); lineno
++;
4305 ** Return the name of a C datatype able to represent values between
4306 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4307 ** for that type (1, 2, or 4) into *pnByte.
4309 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
){
4310 const char *zType
= "int";
4314 zType
= "unsigned char";
4316 }else if( upr
<65535 ){
4317 zType
= "unsigned short int";
4320 zType
= "unsigned int";
4323 }else if( lwr
>=-127 && upr
<=127 ){
4324 zType
= "signed char";
4326 }else if( lwr
>=-32767 && upr
<32767 ){
4330 if( pnByte
) *pnByte
= nByte
;
4335 ** Each state contains a set of token transaction and a set of
4336 ** nonterminal transactions. Each of these sets makes an instance
4337 ** of the following structure. An array of these structures is used
4338 ** to order the creation of entries in the yy_action[] table.
4341 struct state
*stp
; /* A pointer to a state */
4342 int isTkn
; /* True to use tokens. False for non-terminals */
4343 int nAction
; /* Number of actions */
4344 int iOrder
; /* Original order of action sets */
4348 ** Compare to axset structures for sorting purposes
4350 static int axset_compare(const void *a
, const void *b
){
4351 struct axset
*p1
= (struct axset
*)a
;
4352 struct axset
*p2
= (struct axset
*)b
;
4354 c
= p2
->nAction
- p1
->nAction
;
4356 c
= p1
->iOrder
- p2
->iOrder
;
4358 assert( c
!=0 || p1
==p2
);
4363 ** Write text on "out" that describes the rule "rp".
4365 static void writeRuleText(FILE *out
, struct rule
*rp
){
4367 fprintf(out
,"%s ::=", rp
->lhs
->name
);
4368 for(j
=0; j
<rp
->nrhs
; j
++){
4369 struct symbol
*sp
= rp
->rhs
[j
];
4370 if( sp
->type
!=MULTITERMINAL
){
4371 fprintf(out
," %s", sp
->name
);
4374 fprintf(out
," %s", sp
->subsym
[0]->name
);
4375 for(k
=1; k
<sp
->nsubsym
; k
++){
4376 fprintf(out
,"|%s",sp
->subsym
[k
]->name
);
4383 /* Generate C source code for the parser */
4386 int mhflag
, /* Output in makeheaders format if true */
4387 int sqlFlag
/* Generate the *.sql file too */
4389 FILE *out
, *in
, *sql
;
4394 struct acttab
*pActtab
;
4395 int i
, j
, n
, sz
, mn
, mx
;
4397 int szActionType
; /* sizeof(YYACTIONTYPE) */
4398 int szCodeType
; /* sizeof(YYCODETYPE) */
4400 int mnTknOfst
, mxTknOfst
;
4401 int mnNtOfst
, mxNtOfst
;
4405 lemp
->minShiftReduce
= lemp
->nstate
;
4406 lemp
->errAction
= lemp
->minShiftReduce
+ lemp
->nrule
;
4407 lemp
->accAction
= lemp
->errAction
+ 1;
4408 lemp
->noAction
= lemp
->accAction
+ 1;
4409 lemp
->minReduce
= lemp
->noAction
+ 1;
4410 lemp
->maxAction
= lemp
->minReduce
+ lemp
->nrule
;
4412 in
= tplt_open(lemp
);
4414 out
= file_open(lemp
,".c","wb");
4422 sql
= file_open(lemp
, ".sql", "wb");
4430 "CREATE TABLE symbol(\n"
4431 " id INTEGER PRIMARY KEY,\n"
4432 " name TEXT NOT NULL,\n"
4433 " isTerminal BOOLEAN NOT NULL,\n"
4434 " fallback INTEGER REFERENCES symbol"
4435 " DEFERRABLE INITIALLY DEFERRED\n"
4438 for(i
=0; i
<lemp
->nsymbol
; i
++){
4440 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4441 "VALUES(%d,'%s',%s",
4442 i
, lemp
->symbols
[i
]->name
,
4443 i
<lemp
->nterminal
? "TRUE" : "FALSE"
4445 if( lemp
->symbols
[i
]->fallback
){
4446 fprintf(sql
, ",%d);\n", lemp
->symbols
[i
]->fallback
->index
);
4448 fprintf(sql
, ",NULL);\n");
4452 "CREATE TABLE rule(\n"
4453 " ruleid INTEGER PRIMARY KEY,\n"
4454 " lhs INTEGER REFERENCES symbol(id),\n"
4457 "CREATE TABLE rulerhs(\n"
4458 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4460 " sym INTEGER REFERENCES symbol(id)\n"
4463 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4464 assert( i
==rp
->iRule
);
4466 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
4467 rp
->iRule
, rp
->lhs
->index
4469 writeRuleText(sql
, rp
);
4470 fprintf(sql
,"');\n");
4471 for(j
=0; j
<rp
->nrhs
; j
++){
4472 struct symbol
*sp
= rp
->rhs
[j
];
4473 if( sp
->type
!=MULTITERMINAL
){
4475 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4480 for(k
=0; k
<sp
->nsubsym
; k
++){
4482 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4483 i
,j
,sp
->subsym
[k
]->index
4489 fprintf(sql
, "COMMIT;\n");
4494 "/* This file is automatically generated by Lemon from input grammar\n"
4495 "** source file \"%s\"", lemp
->filename
); lineno
++;
4496 if( nDefineUsed
==0 ){
4497 fprintf(out
, ".\n*/\n"); lineno
+= 2;
4499 fprintf(out
, " with these options:\n**\n"); lineno
+= 2;
4500 for(i
=0; i
<nDefine
; i
++){
4501 if( !bDefineUsed
[i
] ) continue;
4502 fprintf(out
, "** -D%s\n", azDefine
[i
]); lineno
++;
4504 fprintf(out
, "*/\n"); lineno
++;
4507 /* The first %include directive begins with a C-language comment,
4508 ** then skip over the header comment of the template file
4510 if( lemp
->include
==0 ) lemp
->include
= "";
4511 for(i
=0; ISSPACE(lemp
->include
[i
]); i
++){
4512 if( lemp
->include
[i
]=='\n' ){
4513 lemp
->include
+= i
+1;
4517 if( lemp
->include
[0]=='/' ){
4518 tplt_skip_header(in
,&lineno
);
4520 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4523 /* Generate the include code, if any */
4524 tplt_print(out
,lemp
,lemp
->include
,&lineno
);
4526 char *incName
= file_makename(lemp
, ".h");
4527 fprintf(out
,"#include \"%s\"\n", incName
); lineno
++;
4528 lemon_free(incName
);
4530 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4532 /* Generate #defines for all tokens */
4533 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4536 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4538 fprintf(out
,"#ifndef %s%s\n", prefix
, lemp
->symbols
[1]->name
);
4540 for(i
=1; i
<lemp
->nterminal
; i
++){
4541 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4544 fprintf(out
,"#endif\n"); lineno
++;
4545 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4547 /* Generate the defines */
4548 fprintf(out
,"#define YYCODETYPE %s\n",
4549 minimum_size_type(0, lemp
->nsymbol
, &szCodeType
)); lineno
++;
4550 fprintf(out
,"#define YYNOCODE %d\n",lemp
->nsymbol
); lineno
++;
4551 fprintf(out
,"#define YYACTIONTYPE %s\n",
4552 minimum_size_type(0,lemp
->maxAction
,&szActionType
)); lineno
++;
4553 if( lemp
->wildcard
){
4554 fprintf(out
,"#define YYWILDCARD %d\n",
4555 lemp
->wildcard
->index
); lineno
++;
4557 print_stack_union(out
,lemp
,&lineno
,mhflag
);
4558 fprintf(out
, "#ifndef YYSTACKDEPTH\n"); lineno
++;
4559 if( lemp
->stacksize
){
4560 fprintf(out
,"#define YYSTACKDEPTH %s\n",lemp
->stacksize
); lineno
++;
4562 fprintf(out
,"#define YYSTACKDEPTH 100\n"); lineno
++;
4564 fprintf(out
, "#endif\n"); lineno
++;
4566 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4568 name
= lemp
->name
? lemp
->name
: "Parse";
4569 if( lemp
->arg
&& lemp
->arg
[0] ){
4570 i
= lemonStrlen(lemp
->arg
);
4571 while( i
>=1 && ISSPACE(lemp
->arg
[i
-1]) ) i
--;
4572 while( i
>=1 && (ISALNUM(lemp
->arg
[i
-1]) || lemp
->arg
[i
-1]=='_') ) i
--;
4573 fprintf(out
,"#define %sARG_SDECL %s;\n",name
,lemp
->arg
); lineno
++;
4574 fprintf(out
,"#define %sARG_PDECL ,%s\n",name
,lemp
->arg
); lineno
++;
4575 fprintf(out
,"#define %sARG_PARAM ,%s\n",name
,&lemp
->arg
[i
]); lineno
++;
4576 fprintf(out
,"#define %sARG_FETCH %s=yypParser->%s;\n",
4577 name
,lemp
->arg
,&lemp
->arg
[i
]); lineno
++;
4578 fprintf(out
,"#define %sARG_STORE yypParser->%s=%s;\n",
4579 name
,&lemp
->arg
[i
],&lemp
->arg
[i
]); lineno
++;
4581 fprintf(out
,"#define %sARG_SDECL\n",name
); lineno
++;
4582 fprintf(out
,"#define %sARG_PDECL\n",name
); lineno
++;
4583 fprintf(out
,"#define %sARG_PARAM\n",name
); lineno
++;
4584 fprintf(out
,"#define %sARG_FETCH\n",name
); lineno
++;
4585 fprintf(out
,"#define %sARG_STORE\n",name
); lineno
++;
4587 if( lemp
->reallocFunc
){
4588 fprintf(out
,"#define YYREALLOC %s\n", lemp
->reallocFunc
); lineno
++;
4590 fprintf(out
,"#define YYREALLOC realloc\n"); lineno
++;
4592 if( lemp
->freeFunc
){
4593 fprintf(out
,"#define YYFREE %s\n", lemp
->freeFunc
); lineno
++;
4595 fprintf(out
,"#define YYFREE free\n"); lineno
++;
4597 if( lemp
->reallocFunc
&& lemp
->freeFunc
){
4598 fprintf(out
,"#define YYDYNSTACK 1\n"); lineno
++;
4600 fprintf(out
,"#define YYDYNSTACK 0\n"); lineno
++;
4602 if( lemp
->ctx
&& lemp
->ctx
[0] ){
4603 i
= lemonStrlen(lemp
->ctx
);
4604 while( i
>=1 && ISSPACE(lemp
->ctx
[i
-1]) ) i
--;
4605 while( i
>=1 && (ISALNUM(lemp
->ctx
[i
-1]) || lemp
->ctx
[i
-1]=='_') ) i
--;
4606 fprintf(out
,"#define %sCTX_SDECL %s;\n",name
,lemp
->ctx
); lineno
++;
4607 fprintf(out
,"#define %sCTX_PDECL ,%s\n",name
,lemp
->ctx
); lineno
++;
4608 fprintf(out
,"#define %sCTX_PARAM ,%s\n",name
,&lemp
->ctx
[i
]); lineno
++;
4609 fprintf(out
,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4610 name
,lemp
->ctx
,&lemp
->ctx
[i
]); lineno
++;
4611 fprintf(out
,"#define %sCTX_STORE yypParser->%s=%s;\n",
4612 name
,&lemp
->ctx
[i
],&lemp
->ctx
[i
]); lineno
++;
4614 fprintf(out
,"#define %sCTX_SDECL\n",name
); lineno
++;
4615 fprintf(out
,"#define %sCTX_PDECL\n",name
); lineno
++;
4616 fprintf(out
,"#define %sCTX_PARAM\n",name
); lineno
++;
4617 fprintf(out
,"#define %sCTX_FETCH\n",name
); lineno
++;
4618 fprintf(out
,"#define %sCTX_STORE\n",name
); lineno
++;
4621 fprintf(out
,"#endif\n"); lineno
++;
4623 if( lemp
->errsym
&& lemp
->errsym
->useCnt
){
4624 fprintf(out
,"#define YYERRORSYMBOL %d\n",lemp
->errsym
->index
); lineno
++;
4625 fprintf(out
,"#define YYERRSYMDT yy%d\n",lemp
->errsym
->dtnum
); lineno
++;
4627 if( lemp
->has_fallback
){
4628 fprintf(out
,"#define YYFALLBACK 1\n"); lineno
++;
4631 /* Compute the action table, but do not output it yet. The action
4632 ** table must be computed before generating the YYNSTATE macro because
4633 ** we need to know how many states can be eliminated.
4635 ax
= (struct axset
*) lemon_calloc(lemp
->nxstate
*2, sizeof(ax
[0]));
4637 fprintf(stderr
,"malloc failed\n");
4640 for(i
=0; i
<lemp
->nxstate
; i
++){
4641 stp
= lemp
->sorted
[i
];
4644 ax
[i
*2].nAction
= stp
->nTknAct
;
4645 ax
[i
*2+1].stp
= stp
;
4646 ax
[i
*2+1].isTkn
= 0;
4647 ax
[i
*2+1].nAction
= stp
->nNtAct
;
4649 mxTknOfst
= mnTknOfst
= 0;
4650 mxNtOfst
= mnNtOfst
= 0;
4651 /* In an effort to minimize the action table size, use the heuristic
4652 ** of placing the largest action sets first */
4653 for(i
=0; i
<lemp
->nxstate
*2; i
++) ax
[i
].iOrder
= i
;
4654 qsort(ax
, lemp
->nxstate
*2, sizeof(ax
[0]), axset_compare
);
4655 pActtab
= acttab_alloc(lemp
->nsymbol
, lemp
->nterminal
);
4656 for(i
=0; i
<lemp
->nxstate
*2 && ax
[i
].nAction
>0; i
++){
4659 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4661 if( ap
->sp
->index
>=lemp
->nterminal
) continue;
4662 action
= compute_action(lemp
, ap
);
4663 if( action
<0 ) continue;
4664 acttab_action(pActtab
, ap
->sp
->index
, action
);
4666 stp
->iTknOfst
= acttab_insert(pActtab
, 1);
4667 if( stp
->iTknOfst
<mnTknOfst
) mnTknOfst
= stp
->iTknOfst
;
4668 if( stp
->iTknOfst
>mxTknOfst
) mxTknOfst
= stp
->iTknOfst
;
4670 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4672 if( ap
->sp
->index
<lemp
->nterminal
) continue;
4673 if( ap
->sp
->index
==lemp
->nsymbol
) continue;
4674 action
= compute_action(lemp
, ap
);
4675 if( action
<0 ) continue;
4676 acttab_action(pActtab
, ap
->sp
->index
, action
);
4678 stp
->iNtOfst
= acttab_insert(pActtab
, 0);
4679 if( stp
->iNtOfst
<mnNtOfst
) mnNtOfst
= stp
->iNtOfst
;
4680 if( stp
->iNtOfst
>mxNtOfst
) mxNtOfst
= stp
->iNtOfst
;
4682 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4684 for(jj
=nn
=0; jj
<pActtab
->nAction
; jj
++){
4685 if( pActtab
->aAction
[jj
].action
<0 ) nn
++;
4687 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4688 i
, stp
->statenum
, ax
[i
].isTkn
? "Token" : "Var ",
4689 ax
[i
].nAction
, pActtab
->nAction
, nn
);
4695 /* Mark rules that are actually used for reduce actions after all
4696 ** optimizations have been applied
4698 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->doesReduce
= LEMON_FALSE
;
4699 for(i
=0; i
<lemp
->nxstate
; i
++){
4700 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
4701 if( ap
->type
==REDUCE
|| ap
->type
==SHIFTREDUCE
){
4702 ap
->x
.rp
->doesReduce
= 1;
4707 /* Finish rendering the constants now that the action table has
4709 fprintf(out
,"#define YYNSTATE %d\n",lemp
->nxstate
); lineno
++;
4710 fprintf(out
,"#define YYNRULE %d\n",lemp
->nrule
); lineno
++;
4711 fprintf(out
,"#define YYNRULE_WITH_ACTION %d\n",lemp
->nruleWithAction
);
4713 fprintf(out
,"#define YYNTOKEN %d\n",lemp
->nterminal
); lineno
++;
4714 fprintf(out
,"#define YY_MAX_SHIFT %d\n",lemp
->nxstate
-1); lineno
++;
4715 i
= lemp
->minShiftReduce
;
4716 fprintf(out
,"#define YY_MIN_SHIFTREDUCE %d\n",i
); lineno
++;
4718 fprintf(out
,"#define YY_MAX_SHIFTREDUCE %d\n", i
-1); lineno
++;
4719 fprintf(out
,"#define YY_ERROR_ACTION %d\n", lemp
->errAction
); lineno
++;
4720 fprintf(out
,"#define YY_ACCEPT_ACTION %d\n", lemp
->accAction
); lineno
++;
4721 fprintf(out
,"#define YY_NO_ACTION %d\n", lemp
->noAction
); lineno
++;
4722 fprintf(out
,"#define YY_MIN_REDUCE %d\n", lemp
->minReduce
); lineno
++;
4723 i
= lemp
->minReduce
+ lemp
->nrule
;
4724 fprintf(out
,"#define YY_MAX_REDUCE %d\n", i
-1); lineno
++;
4726 /* Minimum and maximum token values that have a destructor */
4728 for(i
=0; i
<lemp
->nsymbol
; i
++){
4729 struct symbol
*sp
= lemp
->symbols
[i
];
4731 if( sp
&& sp
->type
!=TERMINAL
&& sp
->destructor
){
4732 if( mn
==0 || sp
->index
<mn
) mn
= sp
->index
;
4733 if( sp
->index
>mx
) mx
= sp
->index
;
4736 if( lemp
->tokendest
) mn
= 0;
4737 if( lemp
->vardest
) mx
= lemp
->nsymbol
-1;
4738 fprintf(out
,"#define YY_MIN_DSTRCTR %d\n", mn
); lineno
++;
4739 fprintf(out
,"#define YY_MAX_DSTRCTR %d\n", mx
); lineno
++;
4741 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4743 /* Now output the action table and its associates:
4745 ** yy_action[] A single table containing all actions.
4746 ** yy_lookahead[] A table containing the lookahead for each entry in
4747 ** yy_action. Used to detect hash collisions.
4748 ** yy_shift_ofst[] For each state, the offset into yy_action for
4749 ** shifting terminals.
4750 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4751 ** shifting non-terminals after a reduce.
4752 ** yy_default[] Default action for each state.
4755 /* Output the yy_action table */
4756 lemp
->nactiontab
= n
= acttab_action_size(pActtab
);
4757 lemp
->tablesize
+= n
*szActionType
;
4758 fprintf(out
,"#define YY_ACTTAB_COUNT (%d)\n", n
); lineno
++;
4759 fprintf(out
,"static const YYACTIONTYPE yy_action[] = {\n"); lineno
++;
4760 for(i
=j
=0; i
<n
; i
++){
4761 int action
= acttab_yyaction(pActtab
, i
);
4762 if( action
<0 ) action
= lemp
->noAction
;
4763 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4764 fprintf(out
, " %4d,", action
);
4765 if( j
==9 || i
==n
-1 ){
4766 fprintf(out
, "\n"); lineno
++;
4772 fprintf(out
, "};\n"); lineno
++;
4774 /* Output the yy_lookahead table */
4775 lemp
->nlookaheadtab
= n
= acttab_lookahead_size(pActtab
);
4776 lemp
->tablesize
+= n
*szCodeType
;
4777 fprintf(out
,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno
++;
4778 for(i
=j
=0; i
<n
; i
++){
4779 int la
= acttab_yylookahead(pActtab
, i
);
4780 if( la
<0 ) la
= lemp
->nsymbol
;
4781 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4782 fprintf(out
, " %4d,", la
);
4784 fprintf(out
, "\n"); lineno
++;
4790 /* Add extra entries to the end of the yy_lookahead[] table so that
4791 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4792 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4793 nLookAhead
= lemp
->nterminal
+ lemp
->nactiontab
;
4794 while( i
<nLookAhead
){
4795 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4796 fprintf(out
, " %4d,", lemp
->nterminal
);
4798 fprintf(out
, "\n"); lineno
++;
4805 if( j
>0 ){ fprintf(out
, "\n"); lineno
++; }
4806 fprintf(out
, "};\n"); lineno
++;
4808 /* Output the yy_shift_ofst[] table */
4810 while( n
>0 && lemp
->sorted
[n
-1]->iTknOfst
==NO_OFFSET
) n
--;
4811 fprintf(out
, "#define YY_SHIFT_COUNT (%d)\n", n
-1); lineno
++;
4812 fprintf(out
, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst
); lineno
++;
4813 fprintf(out
, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst
); lineno
++;
4814 fprintf(out
, "static const %s yy_shift_ofst[] = {\n",
4815 minimum_size_type(mnTknOfst
, lemp
->nterminal
+lemp
->nactiontab
, &sz
));
4817 lemp
->tablesize
+= n
*sz
;
4818 for(i
=j
=0; i
<n
; i
++){
4820 stp
= lemp
->sorted
[i
];
4821 ofst
= stp
->iTknOfst
;
4822 if( ofst
==NO_OFFSET
) ofst
= lemp
->nactiontab
;
4823 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4824 fprintf(out
, " %4d,", ofst
);
4825 if( j
==9 || i
==n
-1 ){
4826 fprintf(out
, "\n"); lineno
++;
4832 fprintf(out
, "};\n"); lineno
++;
4834 /* Output the yy_reduce_ofst[] table */
4836 while( n
>0 && lemp
->sorted
[n
-1]->iNtOfst
==NO_OFFSET
) n
--;
4837 fprintf(out
, "#define YY_REDUCE_COUNT (%d)\n", n
-1); lineno
++;
4838 fprintf(out
, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst
); lineno
++;
4839 fprintf(out
, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst
); lineno
++;
4840 fprintf(out
, "static const %s yy_reduce_ofst[] = {\n",
4841 minimum_size_type(mnNtOfst
-1, mxNtOfst
, &sz
)); lineno
++;
4842 lemp
->tablesize
+= n
*sz
;
4843 for(i
=j
=0; i
<n
; i
++){
4845 stp
= lemp
->sorted
[i
];
4846 ofst
= stp
->iNtOfst
;
4847 if( ofst
==NO_OFFSET
) ofst
= mnNtOfst
- 1;
4848 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4849 fprintf(out
, " %4d,", ofst
);
4850 if( j
==9 || i
==n
-1 ){
4851 fprintf(out
, "\n"); lineno
++;
4857 fprintf(out
, "};\n"); lineno
++;
4859 /* Output the default action table */
4860 fprintf(out
, "static const YYACTIONTYPE yy_default[] = {\n"); lineno
++;
4862 lemp
->tablesize
+= n
*szActionType
;
4863 for(i
=j
=0; i
<n
; i
++){
4864 stp
= lemp
->sorted
[i
];
4865 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4866 if( stp
->iDfltReduce
<0 ){
4867 fprintf(out
, " %4d,", lemp
->errAction
);
4869 fprintf(out
, " %4d,", stp
->iDfltReduce
+ lemp
->minReduce
);
4871 if( j
==9 || i
==n
-1 ){
4872 fprintf(out
, "\n"); lineno
++;
4878 fprintf(out
, "};\n"); lineno
++;
4879 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4881 /* Generate the table of fallback tokens.
4883 if( lemp
->has_fallback
){
4884 mx
= lemp
->nterminal
- 1;
4885 /* 2019-08-28: Generate fallback entries for every token to avoid
4886 ** having to do a range check on the index */
4887 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
4888 lemp
->tablesize
+= (mx
+1)*szCodeType
;
4889 for(i
=0; i
<=mx
; i
++){
4890 struct symbol
*p
= lemp
->symbols
[i
];
4891 if( p
->fallback
==0 ){
4892 fprintf(out
, " 0, /* %10s => nothing */\n", p
->name
);
4894 fprintf(out
, " %3d, /* %10s => %s */\n", p
->fallback
->index
,
4895 p
->name
, p
->fallback
->name
);
4900 tplt_xfer(lemp
->name
, in
, out
, &lineno
);
4902 /* Generate a table containing the symbolic name of every symbol
4904 for(i
=0; i
<lemp
->nsymbol
; i
++){
4905 fprintf(out
," /* %4d */ \"%s\",\n",i
, lemp
->symbols
[i
]->name
); lineno
++;
4907 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4909 /* Generate a table containing a text string that describes every
4910 ** rule in the rule set of the grammar. This information is used
4911 ** when tracing REDUCE actions.
4913 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4914 assert( rp
->iRule
==i
);
4915 fprintf(out
," /* %3d */ \"", i
);
4916 writeRuleText(out
, rp
);
4917 fprintf(out
,"\",\n"); lineno
++;
4919 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4921 /* Generate code which executes every time a symbol is popped from
4922 ** the stack while processing errors or while destroying the parser.
4923 ** (In other words, generate the %destructor actions)
4925 if( lemp
->tokendest
){
4927 for(i
=0; i
<lemp
->nsymbol
; i
++){
4928 struct symbol
*sp
= lemp
->symbols
[i
];
4929 if( sp
==0 || sp
->type
!=TERMINAL
) continue;
4931 fprintf(out
, " /* TERMINAL Destructor */\n"); lineno
++;
4934 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4936 for(i
=0; i
<lemp
->nsymbol
&& lemp
->symbols
[i
]->type
!=TERMINAL
; i
++);
4937 if( i
<lemp
->nsymbol
){
4938 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4939 fprintf(out
," break;\n"); lineno
++;
4942 if( lemp
->vardest
){
4943 struct symbol
*dflt_sp
= 0;
4945 for(i
=0; i
<lemp
->nsymbol
; i
++){
4946 struct symbol
*sp
= lemp
->symbols
[i
];
4947 if( sp
==0 || sp
->type
==TERMINAL
||
4948 sp
->index
<=0 || sp
->destructor
!=0 ) continue;
4950 fprintf(out
, " /* Default NON-TERMINAL Destructor */\n");lineno
++;
4953 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4957 emit_destructor_code(out
,dflt_sp
,lemp
,&lineno
);
4959 fprintf(out
," break;\n"); lineno
++;
4961 for(i
=0; i
<lemp
->nsymbol
; i
++){
4962 struct symbol
*sp
= lemp
->symbols
[i
];
4963 if( sp
==0 || sp
->type
==TERMINAL
|| sp
->destructor
==0 ) continue;
4964 if( sp
->destLineno
<0 ) continue; /* Already emitted */
4965 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4967 /* Combine duplicate destructors into a single case */
4968 for(j
=i
+1; j
<lemp
->nsymbol
; j
++){
4969 struct symbol
*sp2
= lemp
->symbols
[j
];
4970 if( sp2
&& sp2
->type
!=TERMINAL
&& sp2
->destructor
4971 && sp2
->dtnum
==sp
->dtnum
4972 && strcmp(sp
->destructor
,sp2
->destructor
)==0 ){
4973 fprintf(out
," case %d: /* %s */\n",
4974 sp2
->index
, sp2
->name
); lineno
++;
4975 sp2
->destLineno
= -1; /* Avoid emitting this destructor again */
4979 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4980 fprintf(out
," break;\n"); lineno
++;
4982 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4984 /* Generate code which executes whenever the parser stack overflows */
4985 tplt_print(out
,lemp
,lemp
->overflow
,&lineno
);
4986 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4988 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4989 ** yyRuleInfoNRhs[].
4991 ** Note: This code depends on the fact that rules are number
4992 ** sequentially beginning with 0.
4994 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4995 fprintf(out
," %4d, /* (%d) ", rp
->lhs
->index
, i
);
4996 rule_print(out
, rp
);
4997 fprintf(out
," */\n"); lineno
++;
4999 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
5000 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
5001 fprintf(out
," %3d, /* (%d) ", -rp
->nrhs
, i
);
5002 rule_print(out
, rp
);
5003 fprintf(out
," */\n"); lineno
++;
5005 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
5007 /* Generate code which execution during each REDUCE action */
5009 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
5010 i
+= translate_code(lemp
, rp
);
5013 fprintf(out
," YYMINORTYPE yylhsminor;\n"); lineno
++;
5015 /* First output rules other than the default: rule */
5016 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
5017 struct rule
*rp2
; /* Other rules with the same action */
5018 if( rp
->codeEmitted
) continue;
5020 /* No C code actions, so this will be part of the "default:" rule */
5023 fprintf(out
," case %d: /* ", rp
->iRule
);
5024 writeRuleText(out
, rp
);
5025 fprintf(out
, " */\n"); lineno
++;
5026 for(rp2
=rp
->next
; rp2
; rp2
=rp2
->next
){
5027 if( rp2
->code
==rp
->code
&& rp2
->codePrefix
==rp
->codePrefix
5028 && rp2
->codeSuffix
==rp
->codeSuffix
){
5029 fprintf(out
," case %d: /* ", rp2
->iRule
);
5030 writeRuleText(out
, rp2
);
5031 fprintf(out
," */ yytestcase(yyruleno==%d);\n", rp2
->iRule
); lineno
++;
5032 rp2
->codeEmitted
= 1;
5035 emit_code(out
,rp
,lemp
,&lineno
);
5036 fprintf(out
," break;\n"); lineno
++;
5037 rp
->codeEmitted
= 1;
5039 /* Finally, output the default: rule. We choose as the default: all
5040 ** empty actions. */
5041 fprintf(out
," default:\n"); lineno
++;
5042 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
5043 if( rp
->codeEmitted
) continue;
5044 assert( rp
->noCode
);
5045 fprintf(out
," /* (%d) ", rp
->iRule
);
5046 writeRuleText(out
, rp
);
5047 if( rp
->neverReduce
){
5048 fprintf(out
, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
5049 rp
->iRule
); lineno
++;
5050 }else if( rp
->doesReduce
){
5051 fprintf(out
, " */ yytestcase(yyruleno==%d);\n", rp
->iRule
); lineno
++;
5053 fprintf(out
, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
5054 rp
->iRule
); lineno
++;
5057 fprintf(out
," break;\n"); lineno
++;
5058 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
5060 /* Generate code which executes if a parse fails */
5061 tplt_print(out
,lemp
,lemp
->failure
,&lineno
);
5062 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
5064 /* Generate code which executes when a syntax error occurs */
5065 tplt_print(out
,lemp
,lemp
->error
,&lineno
);
5066 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
5068 /* Generate code which executes when the parser accepts its input */
5069 tplt_print(out
,lemp
,lemp
->accept
,&lineno
);
5070 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
5072 /* Append any addition code the user desires */
5073 tplt_print(out
,lemp
,lemp
->extracode
,&lineno
);
5075 acttab_free(pActtab
);
5078 if( sql
) fclose(sql
);
5082 /* Generate a header file for the parser */
5083 void ReportHeader(struct lemon
*lemp
)
5087 char line
[LINESIZE
];
5088 char pattern
[LINESIZE
];
5091 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
5093 in
= file_open(lemp
,".h","rb");
5096 for(i
=1; i
<lemp
->nterminal
&& fgets(line
,LINESIZE
,in
); i
++){
5097 lemon_sprintf(pattern
,"#define %s%-30s %3d\n",
5098 prefix
,lemp
->symbols
[i
]->name
,i
);
5099 if( strcmp(line
,pattern
) ) break;
5101 nextChar
= fgetc(in
);
5103 if( i
==lemp
->nterminal
&& nextChar
==EOF
){
5104 /* No change in the file. Don't rewrite it. */
5108 out
= file_open(lemp
,".h","wb");
5110 for(i
=1; i
<lemp
->nterminal
; i
++){
5111 fprintf(out
,"#define %s%-30s %3d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
5118 /* Reduce the size of the action tables, if possible, by making use
5121 ** In this version, we take the most frequent REDUCE action and make
5122 ** it the default. Except, there is no default if the wildcard token
5123 ** is a possible look-ahead.
5125 void CompressTables(struct lemon
*lemp
)
5128 struct action
*ap
, *ap2
, *nextap
;
5129 struct rule
*rp
, *rp2
, *rbest
;
5134 for(i
=0; i
<lemp
->nstate
; i
++){
5135 stp
= lemp
->sorted
[i
];
5140 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5141 if( ap
->type
==SHIFT
&& ap
->sp
==lemp
->wildcard
){
5144 if( ap
->type
!=REDUCE
) continue;
5146 if( rp
->lhsStart
) continue;
5147 if( rp
==rbest
) continue;
5149 for(ap2
=ap
->next
; ap2
; ap2
=ap2
->next
){
5150 if( ap2
->type
!=REDUCE
) continue;
5152 if( rp2
==rbest
) continue;
5161 /* Do not make a default if the number of rules to default
5162 ** is not at least 1 or if the wildcard token is a possible
5165 if( nbest
<1 || usesWildcard
) continue;
5168 /* Combine matching REDUCE actions into a single default */
5169 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5170 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) break;
5173 ap
->sp
= Symbol_new("{default}");
5174 for(ap
=ap
->next
; ap
; ap
=ap
->next
){
5175 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) ap
->type
= NOT_USED
;
5177 stp
->ap
= Action_sort(stp
->ap
);
5179 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5180 if( ap
->type
==SHIFT
) break;
5181 if( ap
->type
==REDUCE
&& ap
->x
.rp
!=rbest
) break;
5184 stp
->autoReduce
= 1;
5185 stp
->pDfltReduce
= rbest
;
5189 /* Make a second pass over all states and actions. Convert
5190 ** every action that is a SHIFT to an autoReduce state into
5191 ** a SHIFTREDUCE action.
5193 for(i
=0; i
<lemp
->nstate
; i
++){
5194 stp
= lemp
->sorted
[i
];
5195 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5196 struct state
*pNextState
;
5197 if( ap
->type
!=SHIFT
) continue;
5198 pNextState
= ap
->x
.stp
;
5199 if( pNextState
->autoReduce
&& pNextState
->pDfltReduce
!=0 ){
5200 ap
->type
= SHIFTREDUCE
;
5201 ap
->x
.rp
= pNextState
->pDfltReduce
;
5206 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
5207 ** (meaning that the SHIFTREDUCE will land back in the state where it
5208 ** started) and if there is no C-code associated with the reduce action,
5209 ** then we can go ahead and convert the action to be the same as the
5210 ** action for the RHS of the rule.
5212 for(i
=0; i
<lemp
->nstate
; i
++){
5213 stp
= lemp
->sorted
[i
];
5214 for(ap
=stp
->ap
; ap
; ap
=nextap
){
5216 if( ap
->type
!=SHIFTREDUCE
) continue;
5218 if( rp
->noCode
==0 ) continue;
5219 if( rp
->nrhs
!=1 ) continue;
5221 /* Only apply this optimization to non-terminals. It would be OK to
5222 ** apply it to terminal symbols too, but that makes the parser tables
5224 if( ap
->sp
->index
<lemp
->nterminal
) continue;
5226 /* If we reach this point, it means the optimization can be applied */
5228 for(ap2
=stp
->ap
; ap2
&& (ap2
==ap
|| ap2
->sp
!=rp
->lhs
); ap2
=ap2
->next
){}
5230 ap
->spOpt
= ap2
->sp
;
5231 ap
->type
= ap2
->type
;
5239 ** Compare two states for sorting purposes. The smaller state is the
5240 ** one with the most non-terminal actions. If they have the same number
5241 ** of non-terminal actions, then the smaller is the one with the most
5244 static int stateResortCompare(const void *a
, const void *b
){
5245 const struct state
*pA
= *(const struct state
**)a
;
5246 const struct state
*pB
= *(const struct state
**)b
;
5249 n
= pB
->nNtAct
- pA
->nNtAct
;
5251 n
= pB
->nTknAct
- pA
->nTknAct
;
5253 n
= pB
->statenum
- pA
->statenum
;
5262 ** Renumber and resort states so that states with fewer choices
5263 ** occur at the end. Except, keep state 0 as the first state.
5265 void ResortStates(struct lemon
*lemp
)
5271 for(i
=0; i
<lemp
->nstate
; i
++){
5272 stp
= lemp
->sorted
[i
];
5273 stp
->nTknAct
= stp
->nNtAct
= 0;
5274 stp
->iDfltReduce
= -1; /* Init dflt action to "syntax error" */
5275 stp
->iTknOfst
= NO_OFFSET
;
5276 stp
->iNtOfst
= NO_OFFSET
;
5277 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5278 int iAction
= compute_action(lemp
,ap
);
5280 if( ap
->sp
->index
<lemp
->nterminal
){
5282 }else if( ap
->sp
->index
<lemp
->nsymbol
){
5285 assert( stp
->autoReduce
==0 || stp
->pDfltReduce
==ap
->x
.rp
);
5286 stp
->iDfltReduce
= iAction
;
5291 qsort(&lemp
->sorted
[1], lemp
->nstate
-1, sizeof(lemp
->sorted
[0]),
5292 stateResortCompare
);
5293 for(i
=0; i
<lemp
->nstate
; i
++){
5294 lemp
->sorted
[i
]->statenum
= i
;
5296 lemp
->nxstate
= lemp
->nstate
;
5297 while( lemp
->nxstate
>1 && lemp
->sorted
[lemp
->nxstate
-1]->autoReduce
){
5303 /***************** From the file "set.c" ************************************/
5305 ** Set manipulation routines for the LEMON parser generator.
5308 static int size
= 0;
5310 /* Set the set size */
5316 /* Allocate a new set */
5319 s
= (char*)lemon_calloc( size
, 1);
5326 /* Deallocate a set */
5327 void SetFree(char *s
)
5332 /* Add a new element to the set. Return TRUE if the element was added
5333 ** and FALSE if it was already there. */
5334 int SetAdd(char *s
, int e
)
5337 assert( e
>=0 && e
<size
);
5343 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
5344 int SetUnion(char *s1
, char *s2
)
5348 for(i
=0; i
<size
; i
++){
5349 if( s2
[i
]==0 ) continue;
5357 /********************** From the file "table.c" ****************************/
5359 ** All code in this file has been automatically generated
5360 ** from a specification in the file
5362 ** by the associative array code building program "aagen".
5363 ** Do not edit this file! Instead, edit the specification
5364 ** file, then rerun aagen.
5367 ** Code for processing tables in the LEMON parser generator.
5370 PRIVATE
unsigned strhash(const char *x
)
5373 while( *x
) h
= h
*13 + *(x
++);
5377 /* Works like strdup, sort of. Save a string in malloced memory, but
5378 ** keep strings in a table so that the same string is not in more
5381 const char *Strsafe(const char *y
)
5386 if( y
==0 ) return 0;
5387 z
= Strsafe_find(y
);
5388 if( z
==0 && (cpy
=(char *)lemon_malloc( lemonStrlen(y
)+1 ))!=0 ){
5389 lemon_strcpy(cpy
,y
);
5397 /* There is one instance of the following structure for each
5398 ** associative array of type "x1".
5401 int size
; /* The number of available slots. */
5402 /* Must be a power of 2 greater than or */
5404 int count
; /* Number of currently slots filled */
5405 struct s_x1node
*tbl
; /* The data stored here */
5406 struct s_x1node
**ht
; /* Hash table for lookups */
5409 /* There is one instance of this structure for every data element
5410 ** in an associative array of type "x1".
5412 typedef struct s_x1node
{
5413 const char *data
; /* The data */
5414 struct s_x1node
*next
; /* Next entry with the same hash */
5415 struct s_x1node
**from
; /* Previous link */
5418 /* There is only one instance of the array, which is the following */
5419 static struct s_x1
*x1a
;
5421 /* Allocate a new associative array */
5422 void Strsafe_init(void){
5424 x1a
= (struct s_x1
*)lemon_malloc( sizeof(struct s_x1
) );
5428 x1a
->tbl
= (x1node
*)lemon_calloc(1024, sizeof(x1node
) + sizeof(x1node
*));
5434 x1a
->ht
= (x1node
**)&(x1a
->tbl
[1024]);
5435 for(i
=0; i
<1024; i
++) x1a
->ht
[i
] = 0;
5439 /* Insert a new record into the array. Return TRUE if successful.
5440 ** Prior data with the same key is NOT overwritten */
5441 int Strsafe_insert(const char *data
)
5447 if( x1a
==0 ) return 0;
5449 h
= ph
& (x1a
->size
-1);
5452 if( strcmp(np
->data
,data
)==0 ){
5453 /* An existing entry with the same key is found. */
5454 /* Fail because overwrite is not allows. */
5459 if( x1a
->count
>=x1a
->size
){
5460 /* Need to make the hash table bigger */
5463 array
.size
= arrSize
= x1a
->size
*2;
5464 array
.count
= x1a
->count
;
5465 array
.tbl
= (x1node
*)lemon_calloc(arrSize
, sizeof(x1node
)+sizeof(x1node
*));
5466 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5467 array
.ht
= (x1node
**)&(array
.tbl
[arrSize
]);
5468 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5469 for(i
=0; i
<x1a
->count
; i
++){
5470 x1node
*oldnp
, *newnp
;
5471 oldnp
= &(x1a
->tbl
[i
]);
5472 h
= strhash(oldnp
->data
) & (arrSize
-1);
5473 newnp
= &(array
.tbl
[i
]);
5474 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5475 newnp
->next
= array
.ht
[h
];
5476 newnp
->data
= oldnp
->data
;
5477 newnp
->from
= &(array
.ht
[h
]);
5478 array
.ht
[h
] = newnp
;
5480 /* lemon_free(x1a->tbl); // This program was originally for 16-bit machines.
5481 ** Don't worry about freeing memory on modern platforms. */
5484 /* Insert the new data */
5485 h
= ph
& (x1a
->size
-1);
5486 np
= &(x1a
->tbl
[x1a
->count
++]);
5488 if( x1a
->ht
[h
] ) x1a
->ht
[h
]->from
= &(np
->next
);
5489 np
->next
= x1a
->ht
[h
];
5491 np
->from
= &(x1a
->ht
[h
]);
5495 /* Return a pointer to data assigned to the given key. Return NULL
5496 ** if no such key. */
5497 const char *Strsafe_find(const char *key
)
5502 if( x1a
==0 ) return 0;
5503 h
= strhash(key
) & (x1a
->size
-1);
5506 if( strcmp(np
->data
,key
)==0 ) break;
5509 return np
? np
->data
: 0;
5512 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5513 ** Create a new symbol if this is the first time "x" has been seen.
5515 struct symbol
*Symbol_new(const char *x
)
5519 sp
= Symbol_find(x
);
5521 sp
= (struct symbol
*)lemon_calloc(1, sizeof(struct symbol
) );
5523 sp
->name
= Strsafe(x
);
5524 sp
->type
= ISUPPER(*x
) ? TERMINAL
: NONTERMINAL
;
5530 sp
->lambda
= LEMON_FALSE
;
5535 Symbol_insert(sp
,sp
->name
);
5541 /* Compare two symbols for sorting purposes. Return negative,
5542 ** zero, or positive if a is less then, equal to, or greater
5545 ** Symbols that begin with upper case letters (terminals or tokens)
5546 ** must sort before symbols that begin with lower case letters
5547 ** (non-terminals). And MULTITERMINAL symbols (created using the
5548 ** %token_class directive) must sort at the very end. Other than
5549 ** that, the order does not matter.
5551 ** We find experimentally that leaving the symbols in their original
5552 ** order (the order they appeared in the grammar file) gives the
5553 ** smallest parser tables in SQLite.
5555 int Symbolcmpp(const void *_a
, const void *_b
)
5557 const struct symbol
*a
= *(const struct symbol
**) _a
;
5558 const struct symbol
*b
= *(const struct symbol
**) _b
;
5559 int i1
= a
->type
==MULTITERMINAL
? 3 : a
->name
[0]>'Z' ? 2 : 1;
5560 int i2
= b
->type
==MULTITERMINAL
? 3 : b
->name
[0]>'Z' ? 2 : 1;
5561 return i1
==i2
? a
->index
- b
->index
: i1
- i2
;
5564 /* There is one instance of the following structure for each
5565 ** associative array of type "x2".
5568 int size
; /* The number of available slots. */
5569 /* Must be a power of 2 greater than or */
5571 int count
; /* Number of currently slots filled */
5572 struct s_x2node
*tbl
; /* The data stored here */
5573 struct s_x2node
**ht
; /* Hash table for lookups */
5576 /* There is one instance of this structure for every data element
5577 ** in an associative array of type "x2".
5579 typedef struct s_x2node
{
5580 struct symbol
*data
; /* The data */
5581 const char *key
; /* The key */
5582 struct s_x2node
*next
; /* Next entry with the same hash */
5583 struct s_x2node
**from
; /* Previous link */
5586 /* There is only one instance of the array, which is the following */
5587 static struct s_x2
*x2a
;
5589 /* Allocate a new associative array */
5590 void Symbol_init(void){
5592 x2a
= (struct s_x2
*)lemon_malloc( sizeof(struct s_x2
) );
5596 x2a
->tbl
= (x2node
*)lemon_calloc(128, sizeof(x2node
) + sizeof(x2node
*));
5602 x2a
->ht
= (x2node
**)&(x2a
->tbl
[128]);
5603 for(i
=0; i
<128; i
++) x2a
->ht
[i
] = 0;
5607 /* Insert a new record into the array. Return TRUE if successful.
5608 ** Prior data with the same key is NOT overwritten */
5609 int Symbol_insert(struct symbol
*data
, const char *key
)
5615 if( x2a
==0 ) return 0;
5617 h
= ph
& (x2a
->size
-1);
5620 if( strcmp(np
->key
,key
)==0 ){
5621 /* An existing entry with the same key is found. */
5622 /* Fail because overwrite is not allows. */
5627 if( x2a
->count
>=x2a
->size
){
5628 /* Need to make the hash table bigger */
5631 array
.size
= arrSize
= x2a
->size
*2;
5632 array
.count
= x2a
->count
;
5633 array
.tbl
= (x2node
*)lemon_calloc(arrSize
, sizeof(x2node
)+sizeof(x2node
*));
5634 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5635 array
.ht
= (x2node
**)&(array
.tbl
[arrSize
]);
5636 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5637 for(i
=0; i
<x2a
->count
; i
++){
5638 x2node
*oldnp
, *newnp
;
5639 oldnp
= &(x2a
->tbl
[i
]);
5640 h
= strhash(oldnp
->key
) & (arrSize
-1);
5641 newnp
= &(array
.tbl
[i
]);
5642 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5643 newnp
->next
= array
.ht
[h
];
5644 newnp
->key
= oldnp
->key
;
5645 newnp
->data
= oldnp
->data
;
5646 newnp
->from
= &(array
.ht
[h
]);
5647 array
.ht
[h
] = newnp
;
5649 /* lemon_free(x2a->tbl); // This program was originally written for 16-bit
5650 ** machines. Don't worry about freeing this trivial amount of memory
5651 ** on modern platforms. Just leak it. */
5654 /* Insert the new data */
5655 h
= ph
& (x2a
->size
-1);
5656 np
= &(x2a
->tbl
[x2a
->count
++]);
5659 if( x2a
->ht
[h
] ) x2a
->ht
[h
]->from
= &(np
->next
);
5660 np
->next
= x2a
->ht
[h
];
5662 np
->from
= &(x2a
->ht
[h
]);
5666 /* Return a pointer to data assigned to the given key. Return NULL
5667 ** if no such key. */
5668 struct symbol
*Symbol_find(const char *key
)
5673 if( x2a
==0 ) return 0;
5674 h
= strhash(key
) & (x2a
->size
-1);
5677 if( strcmp(np
->key
,key
)==0 ) break;
5680 return np
? np
->data
: 0;
5683 /* Return the n-th data. Return NULL if n is out of range. */
5684 struct symbol
*Symbol_Nth(int n
)
5686 struct symbol
*data
;
5687 if( x2a
&& n
>0 && n
<=x2a
->count
){
5688 data
= x2a
->tbl
[n
-1].data
;
5695 /* Return the size of the array */
5698 return x2a
? x2a
->count
: 0;
5701 /* Return an array of pointers to all data in the table.
5702 ** The array is obtained from malloc. Return NULL if memory allocation
5703 ** problems, or if the array is empty. */
5704 struct symbol
**Symbol_arrayof()
5706 struct symbol
**array
;
5708 if( x2a
==0 ) return 0;
5709 arrSize
= x2a
->count
;
5710 array
= (struct symbol
**)lemon_calloc(arrSize
, sizeof(struct symbol
*));
5712 for(i
=0; i
<arrSize
; i
++) array
[i
] = x2a
->tbl
[i
].data
;
5717 /* Compare two configurations */
5718 int Configcmp(const char *_a
,const char *_b
)
5720 const struct config
*a
= (struct config
*) _a
;
5721 const struct config
*b
= (struct config
*) _b
;
5723 x
= a
->rp
->index
- b
->rp
->index
;
5724 if( x
==0 ) x
= a
->dot
- b
->dot
;
5728 /* Compare two states */
5729 PRIVATE
int statecmp(struct config
*a
, struct config
*b
)
5732 for(rc
=0; rc
==0 && a
&& b
; a
=a
->bp
, b
=b
->bp
){
5733 rc
= a
->rp
->index
- b
->rp
->index
;
5734 if( rc
==0 ) rc
= a
->dot
- b
->dot
;
5744 PRIVATE
unsigned statehash(struct config
*a
)
5748 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5754 /* Allocate a new state structure */
5755 struct state
*State_new()
5757 struct state
*newstate
;
5758 newstate
= (struct state
*)lemon_calloc(1, sizeof(struct state
) );
5759 MemoryCheck(newstate
);
5763 /* There is one instance of the following structure for each
5764 ** associative array of type "x3".
5767 int size
; /* The number of available slots. */
5768 /* Must be a power of 2 greater than or */
5770 int count
; /* Number of currently slots filled */
5771 struct s_x3node
*tbl
; /* The data stored here */
5772 struct s_x3node
**ht
; /* Hash table for lookups */
5775 /* There is one instance of this structure for every data element
5776 ** in an associative array of type "x3".
5778 typedef struct s_x3node
{
5779 struct state
*data
; /* The data */
5780 struct config
*key
; /* The key */
5781 struct s_x3node
*next
; /* Next entry with the same hash */
5782 struct s_x3node
**from
; /* Previous link */
5785 /* There is only one instance of the array, which is the following */
5786 static struct s_x3
*x3a
;
5788 /* Allocate a new associative array */
5789 void State_init(void){
5791 x3a
= (struct s_x3
*)lemon_malloc( sizeof(struct s_x3
) );
5795 x3a
->tbl
= (x3node
*)lemon_calloc(128, sizeof(x3node
) + sizeof(x3node
*));
5801 x3a
->ht
= (x3node
**)&(x3a
->tbl
[128]);
5802 for(i
=0; i
<128; i
++) x3a
->ht
[i
] = 0;
5806 /* Insert a new record into the array. Return TRUE if successful.
5807 ** Prior data with the same key is NOT overwritten */
5808 int State_insert(struct state
*data
, struct config
*key
)
5814 if( x3a
==0 ) return 0;
5815 ph
= statehash(key
);
5816 h
= ph
& (x3a
->size
-1);
5819 if( statecmp(np
->key
,key
)==0 ){
5820 /* An existing entry with the same key is found. */
5821 /* Fail because overwrite is not allows. */
5826 if( x3a
->count
>=x3a
->size
){
5827 /* Need to make the hash table bigger */
5830 array
.size
= arrSize
= x3a
->size
*2;
5831 array
.count
= x3a
->count
;
5832 array
.tbl
= (x3node
*)lemon_calloc(arrSize
, sizeof(x3node
)+sizeof(x3node
*));
5833 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5834 array
.ht
= (x3node
**)&(array
.tbl
[arrSize
]);
5835 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5836 for(i
=0; i
<x3a
->count
; i
++){
5837 x3node
*oldnp
, *newnp
;
5838 oldnp
= &(x3a
->tbl
[i
]);
5839 h
= statehash(oldnp
->key
) & (arrSize
-1);
5840 newnp
= &(array
.tbl
[i
]);
5841 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5842 newnp
->next
= array
.ht
[h
];
5843 newnp
->key
= oldnp
->key
;
5844 newnp
->data
= oldnp
->data
;
5845 newnp
->from
= &(array
.ht
[h
]);
5846 array
.ht
[h
] = newnp
;
5848 lemon_free(x3a
->tbl
);
5851 /* Insert the new data */
5852 h
= ph
& (x3a
->size
-1);
5853 np
= &(x3a
->tbl
[x3a
->count
++]);
5856 if( x3a
->ht
[h
] ) x3a
->ht
[h
]->from
= &(np
->next
);
5857 np
->next
= x3a
->ht
[h
];
5859 np
->from
= &(x3a
->ht
[h
]);
5863 /* Return a pointer to data assigned to the given key. Return NULL
5864 ** if no such key. */
5865 struct state
*State_find(struct config
*key
)
5870 if( x3a
==0 ) return 0;
5871 h
= statehash(key
) & (x3a
->size
-1);
5874 if( statecmp(np
->key
,key
)==0 ) break;
5877 return np
? np
->data
: 0;
5880 /* Return an array of pointers to all data in the table.
5881 ** The array is obtained from malloc. Return NULL if memory allocation
5882 ** problems, or if the array is empty. */
5883 struct state
**State_arrayof(void)
5885 struct state
**array
;
5887 if( x3a
==0 ) return 0;
5888 arrSize
= x3a
->count
;
5889 array
= (struct state
**)lemon_calloc(arrSize
, sizeof(struct state
*));
5891 for(i
=0; i
<arrSize
; i
++) array
[i
] = x3a
->tbl
[i
].data
;
5896 /* Hash a configuration */
5897 PRIVATE
unsigned confighash(struct config
*a
)
5900 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5904 /* There is one instance of the following structure for each
5905 ** associative array of type "x4".
5908 int size
; /* The number of available slots. */
5909 /* Must be a power of 2 greater than or */
5911 int count
; /* Number of currently slots filled */
5912 struct s_x4node
*tbl
; /* The data stored here */
5913 struct s_x4node
**ht
; /* Hash table for lookups */
5916 /* There is one instance of this structure for every data element
5917 ** in an associative array of type "x4".
5919 typedef struct s_x4node
{
5920 struct config
*data
; /* The data */
5921 struct s_x4node
*next
; /* Next entry with the same hash */
5922 struct s_x4node
**from
; /* Previous link */
5925 /* There is only one instance of the array, which is the following */
5926 static struct s_x4
*x4a
;
5928 /* Allocate a new associative array */
5929 void Configtable_init(void){
5931 x4a
= (struct s_x4
*)lemon_malloc( sizeof(struct s_x4
) );
5935 x4a
->tbl
= (x4node
*)lemon_calloc(64, sizeof(x4node
) + sizeof(x4node
*));
5941 x4a
->ht
= (x4node
**)&(x4a
->tbl
[64]);
5942 for(i
=0; i
<64; i
++) x4a
->ht
[i
] = 0;
5946 /* Insert a new record into the array. Return TRUE if successful.
5947 ** Prior data with the same key is NOT overwritten */
5948 int Configtable_insert(struct config
*data
)
5954 if( x4a
==0 ) return 0;
5955 ph
= confighash(data
);
5956 h
= ph
& (x4a
->size
-1);
5959 if( Configcmp((const char *) np
->data
,(const char *) data
)==0 ){
5960 /* An existing entry with the same key is found. */
5961 /* Fail because overwrite is not allows. */
5966 if( x4a
->count
>=x4a
->size
){
5967 /* Need to make the hash table bigger */
5970 array
.size
= arrSize
= x4a
->size
*2;
5971 array
.count
= x4a
->count
;
5972 array
.tbl
= (x4node
*)lemon_calloc(arrSize
,
5973 sizeof(x4node
) + sizeof(x4node
*));
5974 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5975 array
.ht
= (x4node
**)&(array
.tbl
[arrSize
]);
5976 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5977 for(i
=0; i
<x4a
->count
; i
++){
5978 x4node
*oldnp
, *newnp
;
5979 oldnp
= &(x4a
->tbl
[i
]);
5980 h
= confighash(oldnp
->data
) & (arrSize
-1);
5981 newnp
= &(array
.tbl
[i
]);
5982 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5983 newnp
->next
= array
.ht
[h
];
5984 newnp
->data
= oldnp
->data
;
5985 newnp
->from
= &(array
.ht
[h
]);
5986 array
.ht
[h
] = newnp
;
5990 /* Insert the new data */
5991 h
= ph
& (x4a
->size
-1);
5992 np
= &(x4a
->tbl
[x4a
->count
++]);
5994 if( x4a
->ht
[h
] ) x4a
->ht
[h
]->from
= &(np
->next
);
5995 np
->next
= x4a
->ht
[h
];
5997 np
->from
= &(x4a
->ht
[h
]);
6001 /* Return a pointer to data assigned to the given key. Return NULL
6002 ** if no such key. */
6003 struct config
*Configtable_find(struct config
*key
)
6008 if( x4a
==0 ) return 0;
6009 h
= confighash(key
) & (x4a
->size
-1);
6012 if( Configcmp((const char *) np
->data
,(const char *) key
)==0 ) break;
6015 return np
? np
->data
: 0;
6018 /* Remove all data from the table. Pass each data to the function "f"
6019 ** as it is removed. ("f" may be null to avoid this step.) */
6020 void Configtable_clear(int(*f
)(struct config
*))
6023 if( x4a
==0 || x4a
->count
==0 ) return;
6024 if( f
) for(i
=0; i
<x4a
->count
; i
++) (*f
)(x4a
->tbl
[i
].data
);
6025 for(i
=0; i
<x4a
->size
; i
++) x4a
->ht
[i
] = 0;