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 static int showPrecedenceConflict
= 0;
52 static char *msort(char*,char**,int(*)(const char*,const char*));
55 ** Compilers are getting increasingly pedantic about type conversions
56 ** as C evolves ever closer to Ada.... To work around the latest problems
57 ** we have to define the following variant of strlen().
59 #define lemonStrlen(X) ((int)strlen(X))
62 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
63 ** saying they are unsafe. So we define our own versions of those routines too.
65 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
66 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
67 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
68 ** buffer, making sure the buffer is always zero-terminated.
70 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
71 ** a few simply conversions:
78 static void lemon_addtext(
79 char *zBuf
, /* The buffer to which text is added */
80 int *pnUsed
, /* Slots of the buffer used so far */
81 const char *zIn
, /* Text to add */
82 int nIn
, /* Bytes of text to add. -1 to use strlen() */
83 int iWidth
/* Field width. Negative to left justify */
85 if( nIn
<0 ) for(nIn
=0; zIn
[nIn
]; nIn
++){}
86 while( iWidth
>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
--; }
88 memcpy(&zBuf
[*pnUsed
], zIn
, nIn
);
90 while( (-iWidth
)>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
++; }
93 static int lemon_vsprintf(char *str
, const char *zFormat
, va_list ap
){
99 for(i
=j
=0; (c
= zFormat
[i
])!=0; i
++){
102 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
104 if( ISDIGIT(c
) || (c
=='-' && ISDIGIT(zFormat
[i
+1])) ){
106 while( ISDIGIT(zFormat
[i
]) ) iWidth
= iWidth
*10 + zFormat
[i
++] - '0';
107 if( c
=='-' ) iWidth
= -iWidth
;
111 int v
= va_arg(ap
, int);
113 lemon_addtext(str
, &nUsed
, "-", 1, iWidth
);
116 lemon_addtext(str
, &nUsed
, "0", 1, iWidth
);
121 zTemp
[sizeof(zTemp
)-k
] = (v
%10) + '0';
124 lemon_addtext(str
, &nUsed
, &zTemp
[sizeof(zTemp
)-k
], k
, iWidth
);
126 z
= va_arg(ap
, const char*);
127 lemon_addtext(str
, &nUsed
, z
, -1, iWidth
);
128 }else if( c
=='.' && memcmp(&zFormat
[i
], ".*s", 3)==0 ){
131 z
= va_arg(ap
, const char*);
132 lemon_addtext(str
, &nUsed
, z
, k
, iWidth
);
134 lemon_addtext(str
, &nUsed
, "%", 1, 0);
136 fprintf(stderr
, "illegal format\n");
142 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
145 static int lemon_sprintf(char *str
, const char *format
, ...){
148 va_start(ap
, format
);
149 rc
= lemon_vsprintf(str
, format
, ap
);
153 static void lemon_strcpy(char *dest
, const char *src
){
154 while( (*(dest
++) = *(src
++))!=0 ){}
156 static void lemon_strcat(char *dest
, const char *src
){
157 while( *dest
) dest
++;
158 lemon_strcpy(dest
, src
);
162 /* a few forward declarations... */
167 static struct action
*Action_new(void);
168 static struct action
*Action_sort(struct action
*);
170 /********** From the file "build.h" ************************************/
171 void FindRulePrecedences(struct lemon
*);
172 void FindFirstSets(struct lemon
*);
173 void FindStates(struct lemon
*);
174 void FindLinks(struct lemon
*);
175 void FindFollowSets(struct lemon
*);
176 void FindActions(struct lemon
*);
178 /********* From the file "configlist.h" *********************************/
179 void Configlist_init(void);
180 struct config
*Configlist_add(struct rule
*, int);
181 struct config
*Configlist_addbasis(struct rule
*, int);
182 void Configlist_closure(struct lemon
*);
183 void Configlist_sort(void);
184 void Configlist_sortbasis(void);
185 struct config
*Configlist_return(void);
186 struct config
*Configlist_basis(void);
187 void Configlist_eat(struct config
*);
188 void Configlist_reset(void);
190 /********* From the file "error.h" ***************************************/
191 void ErrorMsg(const char *, int,const char *, ...);
193 /****** From the file "option.h" ******************************************/
194 enum option_type
{ OPT_FLAG
=1, OPT_INT
, OPT_DBL
, OPT_STR
,
195 OPT_FFLAG
, OPT_FINT
, OPT_FDBL
, OPT_FSTR
};
197 enum option_type type
;
202 int OptInit(char**,struct s_options
*,FILE*);
208 /******** From the file "parse.h" *****************************************/
209 void Parse(struct lemon
*lemp
);
211 /********* From the file "plink.h" ***************************************/
212 struct plink
*Plink_new(void);
213 void Plink_add(struct plink
**, struct config
*);
214 void Plink_copy(struct plink
**, struct plink
*);
215 void Plink_delete(struct plink
*);
217 /********** From the file "report.h" *************************************/
218 void Reprint(struct lemon
*);
219 void ReportOutput(struct lemon
*);
220 void ReportTable(struct lemon
*, int);
221 void ReportHeader(struct lemon
*);
222 void CompressTables(struct lemon
*);
223 void ResortStates(struct lemon
*);
225 /********** From the file "set.h" ****************************************/
226 void SetSize(int); /* All sets will be of size N */
227 char *SetNew(void); /* A new set for element 0..N */
228 void SetFree(char*); /* Deallocate a set */
229 int SetAdd(char*,int); /* Add element to a set */
230 int SetUnion(char *,char *); /* A <- A U B, thru element N */
231 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
233 /********** From the file "struct.h" *************************************/
235 ** Principal data structures for the LEMON parser generator.
238 typedef enum {LEMON_FALSE
=0, LEMON_TRUE
} Boolean
;
240 /* Symbols (terminals and nonterminals) of the grammar are stored
241 ** in the following: */
254 const char *name
; /* Name of the symbol */
255 int index
; /* Index number for this symbol */
256 enum symbol_type type
; /* Symbols are all either TERMINALS or NTs */
257 struct rule
*rule
; /* Linked list of rules of this (if an NT) */
258 struct symbol
*fallback
; /* fallback token in case this token doesn't parse */
259 int prec
; /* Precedence if defined (-1 otherwise) */
260 enum e_assoc assoc
; /* Associativity if precedence is defined */
261 char *firstset
; /* First-set for all rules of this symbol */
262 Boolean lambda
; /* True if NT and can generate an empty string */
263 int useCnt
; /* Number of times used */
264 char *destructor
; /* Code which executes whenever this symbol is
265 ** popped from the stack during error processing */
266 int destLineno
; /* Line number for start of destructor. Set to
267 ** -1 for duplicate destructors. */
268 char *datatype
; /* The data type of information held by this
269 ** object. Only used if type==NONTERMINAL */
270 int dtnum
; /* The data type number. In the parser, the value
271 ** stack is a union. The .yy%d element of this
272 ** union is the correct data type for this object */
273 int bContent
; /* True if this symbol ever carries content - if
274 ** it is ever more than just syntax */
275 /* The following fields are used by MULTITERMINALs only */
276 int nsubsym
; /* Number of constituent symbols in the MULTI */
277 struct symbol
**subsym
; /* Array of constituent symbols */
280 /* Each production rule in the grammar is stored in the following
283 struct symbol
*lhs
; /* Left-hand side of the rule */
284 const char *lhsalias
; /* Alias for the LHS (NULL if none) */
285 int lhsStart
; /* True if left-hand side is the start symbol */
286 int ruleline
; /* Line number for the rule */
287 int nrhs
; /* Number of RHS symbols */
288 struct symbol
**rhs
; /* The RHS symbols */
289 const char **rhsalias
; /* An alias for each RHS symbol (NULL if none) */
290 int line
; /* Line number at which code begins */
291 const char *code
; /* The code executed when this rule is reduced */
292 const char *codePrefix
; /* Setup code before code[] above */
293 const char *codeSuffix
; /* Breakdown code after code[] above */
294 int noCode
; /* True if this rule has no associated C code */
295 int codeEmitted
; /* True if the code has been emitted already */
296 struct symbol
*precsym
; /* Precedence symbol for this rule */
297 int index
; /* An index number for this rule */
298 int iRule
; /* Rule number as used in the generated tables */
299 Boolean canReduce
; /* True if this rule is ever reduced */
300 Boolean doesReduce
; /* Reduce actions occur after optimization */
301 struct rule
*nextlhs
; /* Next rule with the same LHS */
302 struct rule
*next
; /* Next rule in the global list */
305 /* A configuration is a production rule of the grammar together with
306 ** a mark (dot) showing how much of that rule has been processed so far.
307 ** Configurations also contain a follow-set which is a list of terminal
308 ** symbols which are allowed to immediately follow the end of the rule.
309 ** Every configuration is recorded as an instance of the following: */
315 struct rule
*rp
; /* The rule upon which the configuration is based */
316 int dot
; /* The parse point */
317 char *fws
; /* Follow-set for this configuration only */
318 struct plink
*fplp
; /* Follow-set forward propagation links */
319 struct plink
*bplp
; /* Follow-set backwards propagation links */
320 struct state
*stp
; /* Pointer to state which contains this */
321 enum cfgstatus status
; /* used during followset and shift computations */
322 struct config
*next
; /* Next configuration in the state */
323 struct config
*bp
; /* The next basis configuration */
331 SSCONFLICT
, /* A shift/shift conflict */
332 SRCONFLICT
, /* Was a reduce, but part of a conflict */
333 RRCONFLICT
, /* Was a reduce, but part of a conflict */
334 SH_RESOLVED
, /* Was a shift. Precedence resolved conflict */
335 RD_RESOLVED
, /* Was reduce. Precedence resolved conflict */
336 NOT_USED
, /* Deleted by compression */
337 SHIFTREDUCE
/* Shift first, then reduce */
340 /* Every shift or reduce operation is stored as one of the following */
342 struct symbol
*sp
; /* The look-ahead symbol */
345 struct state
*stp
; /* The new state, if a shift */
346 struct rule
*rp
; /* The rule, if a reduce */
348 struct symbol
*spOpt
; /* SHIFTREDUCE optimization to this symbol */
349 struct action
*next
; /* Next action for this state */
350 struct action
*collide
; /* Next action with the same hash */
353 /* Each state of the generated parser's finite state machine
354 ** is encoded as an instance of the following structure. */
356 struct config
*bp
; /* The basis configurations for this state */
357 struct config
*cfp
; /* All configurations in this set */
358 int statenum
; /* Sequential number for this state */
359 struct action
*ap
; /* List of actions for this state */
360 int nTknAct
, nNtAct
; /* Number of actions on terminals and nonterminals */
361 int iTknOfst
, iNtOfst
; /* yy_action[] offset for terminals and nonterms */
362 int iDfltReduce
; /* Default action is to REDUCE by this rule */
363 struct rule
*pDfltReduce
;/* The default REDUCE rule. */
364 int autoReduce
; /* True if this is an auto-reduce state */
366 #define NO_OFFSET (-2147483647)
368 /* A followset propagation link indicates that the contents of one
369 ** configuration followset should be propagated to another whenever
370 ** the first changes. */
372 struct config
*cfp
; /* The configuration to which linked */
373 struct plink
*next
; /* The next propagate link */
376 /* The state vector for the entire parser generator is recorded as
377 ** follows. (LEMON uses no global variables and makes little use of
378 ** static variables. Fields in the following structure can be thought
379 ** of as begin global variables in the program.) */
381 struct state
**sorted
; /* Table of states sorted by state number */
382 struct rule
*rule
; /* List of all rules */
383 struct rule
*startRule
; /* First rule */
384 int nstate
; /* Number of states */
385 int nxstate
; /* nstate with tail degenerate states removed */
386 int nrule
; /* Number of rules */
387 int nsymbol
; /* Number of terminal and nonterminal symbols */
388 int nterminal
; /* Number of terminal symbols */
389 int minShiftReduce
; /* Minimum shift-reduce action value */
390 int errAction
; /* Error action value */
391 int accAction
; /* Accept action value */
392 int noAction
; /* No-op action value */
393 int minReduce
; /* Minimum reduce action */
394 int maxAction
; /* Maximum action value of any kind */
395 struct symbol
**symbols
; /* Sorted array of pointers to symbols */
396 int errorcnt
; /* Number of errors */
397 struct symbol
*errsym
; /* The error symbol */
398 struct symbol
*wildcard
; /* Token that matches anything */
399 char *name
; /* Name of the generated parser */
400 char *arg
; /* Declaration of the 3th argument to parser */
401 char *ctx
; /* Declaration of 2nd argument to constructor */
402 char *tokentype
; /* Type of terminal symbols in the parser stack */
403 char *vartype
; /* The default type of non-terminal symbols */
404 char *start
; /* Name of the start symbol for the grammar */
405 char *stacksize
; /* Size of the parser stack */
406 char *include
; /* Code to put at the start of the C file */
407 char *error
; /* Code to execute when an error is seen */
408 char *overflow
; /* Code to execute on a stack overflow */
409 char *failure
; /* Code to execute on parser failure */
410 char *accept
; /* Code to execute when the parser excepts */
411 char *extracode
; /* Code appended to the generated file */
412 char *tokendest
; /* Code to execute to destroy token data */
413 char *vardest
; /* Code for the default non-terminal destructor */
414 char *filename
; /* Name of the input file */
415 char *outname
; /* Name of the current output file */
416 char *tokenprefix
; /* A prefix added to token names in the .h file */
417 int nconflict
; /* Number of parsing conflicts */
418 int nactiontab
; /* Number of entries in the yy_action[] table */
419 int nlookaheadtab
; /* Number of entries in yy_lookahead[] */
420 int tablesize
; /* Total table size of all tables in bytes */
421 int basisflag
; /* Print only basis configurations */
422 int has_fallback
; /* True if any %fallback is seen in the grammar */
423 int nolinenosflag
; /* True if #line statements should not be printed */
424 char *argv0
; /* Name of the program */
427 #define MemoryCheck(X) if((X)==0){ \
428 extern void memory_error(); \
432 /**************** From the file "table.h" *********************************/
434 ** All code in this file has been automatically generated
435 ** from a specification in the file
437 ** by the associative array code building program "aagen".
438 ** Do not edit this file! Instead, edit the specification
439 ** file, then rerun aagen.
442 ** Code for processing tables in the LEMON parser generator.
444 /* Routines for handling a strings */
446 const char *Strsafe(const char *);
448 void Strsafe_init(void);
449 int Strsafe_insert(const char *);
450 const char *Strsafe_find(const char *);
452 /* Routines for handling symbols of the grammar */
454 struct symbol
*Symbol_new(const char *);
455 int Symbolcmpp(const void *, const void *);
456 void Symbol_init(void);
457 int Symbol_insert(struct symbol
*, const char *);
458 struct symbol
*Symbol_find(const char *);
459 struct symbol
*Symbol_Nth(int);
460 int Symbol_count(void);
461 struct symbol
**Symbol_arrayof(void);
463 /* Routines to manage the state table */
465 int Configcmp(const char *, const char *);
466 struct state
*State_new(void);
467 void State_init(void);
468 int State_insert(struct state
*, struct config
*);
469 struct state
*State_find(struct config
*);
470 struct state
**State_arrayof(void);
472 /* Routines used for efficiency in Configlist_add */
474 void Configtable_init(void);
475 int Configtable_insert(struct config
*);
476 struct config
*Configtable_find(struct config
*);
477 void Configtable_clear(int(*)(struct config
*));
479 /****************** From the file "action.c" *******************************/
481 ** Routines processing parser actions in the LEMON parser generator.
484 /* Allocate a new parser action */
485 static struct action
*Action_new(void){
486 static struct action
*freelist
= 0;
487 struct action
*newaction
;
492 freelist
= (struct action
*)calloc(amt
, sizeof(struct action
));
494 fprintf(stderr
,"Unable to allocate memory for a new parser action.");
497 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
498 freelist
[amt
-1].next
= 0;
500 newaction
= freelist
;
501 freelist
= freelist
->next
;
505 /* Compare two actions for sorting purposes. Return negative, zero, or
506 ** positive if the first action is less than, equal to, or greater than
509 static int actioncmp(
514 rc
= ap1
->sp
->index
- ap2
->sp
->index
;
516 rc
= (int)ap1
->type
- (int)ap2
->type
;
518 if( rc
==0 && (ap1
->type
==REDUCE
|| ap1
->type
==SHIFTREDUCE
) ){
519 rc
= ap1
->x
.rp
->index
- ap2
->x
.rp
->index
;
522 rc
= (int) (ap2
- ap1
);
527 /* Sort parser actions */
528 static struct action
*Action_sort(
531 ap
= (struct action
*)msort((char *)ap
,(char **)&ap
->next
,
532 (int(*)(const char*,const char*))actioncmp
);
542 struct action
*newaction
;
543 newaction
= Action_new();
544 newaction
->next
= *app
;
546 newaction
->type
= type
;
548 newaction
->spOpt
= 0;
550 newaction
->x
.stp
= (struct state
*)arg
;
552 newaction
->x
.rp
= (struct rule
*)arg
;
555 /********************** New code to implement the "acttab" module ***********/
557 ** This module implements routines use to construct the yy_action[] table.
561 ** The state of the yy_action table under construction is an instance of
562 ** the following structure.
564 ** The yy_action table maps the pair (state_number, lookahead) into an
565 ** action_number. The table is an array of integers pairs. The state_number
566 ** determines an initial offset into the yy_action array. The lookahead
567 ** value is then added to this initial offset to get an index X into the
568 ** yy_action array. If the aAction[X].lookahead equals the value of the
569 ** of the lookahead input, then the value of the action_number output is
570 ** aAction[X].action. If the lookaheads do not match then the
571 ** default action for the state_number is returned.
573 ** All actions associated with a single state_number are first entered
574 ** into aLookahead[] using multiple calls to acttab_action(). Then the
575 ** actions for that single state_number are placed into the aAction[]
576 ** array with a single call to acttab_insert(). The acttab_insert() call
577 ** also resets the aLookahead[] array in preparation for the next
580 struct lookahead_action
{
581 int lookahead
; /* Value of the lookahead token */
582 int action
; /* Action to take on the given lookahead */
584 typedef struct acttab acttab
;
586 int nAction
; /* Number of used slots in aAction[] */
587 int nActionAlloc
; /* Slots allocated for aAction[] */
588 struct lookahead_action
589 *aAction
, /* The yy_action[] table under construction */
590 *aLookahead
; /* A single new transaction set */
591 int mnLookahead
; /* Minimum aLookahead[].lookahead */
592 int mnAction
; /* Action associated with mnLookahead */
593 int mxLookahead
; /* Maximum aLookahead[].lookahead */
594 int nLookahead
; /* Used slots in aLookahead[] */
595 int nLookaheadAlloc
; /* Slots allocated in aLookahead[] */
596 int nterminal
; /* Number of terminal symbols */
597 int nsymbol
; /* total number of symbols */
600 /* Return the number of entries in the yy_action table */
601 #define acttab_lookahead_size(X) ((X)->nAction)
603 /* The value for the N-th entry in yy_action */
604 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
606 /* The value for the N-th entry in yy_lookahead */
607 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
609 /* Free all memory associated with the given acttab */
610 void acttab_free(acttab
*p
){
612 free( p
->aLookahead
);
616 /* Allocate a new acttab structure */
617 acttab
*acttab_alloc(int nsymbol
, int nterminal
){
618 acttab
*p
= (acttab
*) calloc( 1, sizeof(*p
) );
620 fprintf(stderr
,"Unable to allocate memory for a new acttab.");
623 memset(p
, 0, sizeof(*p
));
624 p
->nsymbol
= nsymbol
;
625 p
->nterminal
= nterminal
;
629 /* Add a new action to the current transaction set.
631 ** This routine is called once for each lookahead for a particular
634 void acttab_action(acttab
*p
, int lookahead
, int action
){
635 if( p
->nLookahead
>=p
->nLookaheadAlloc
){
636 p
->nLookaheadAlloc
+= 25;
637 p
->aLookahead
= (struct lookahead_action
*) realloc( p
->aLookahead
,
638 sizeof(p
->aLookahead
[0])*p
->nLookaheadAlloc
);
639 if( p
->aLookahead
==0 ){
640 fprintf(stderr
,"malloc failed\n");
644 if( p
->nLookahead
==0 ){
645 p
->mxLookahead
= lookahead
;
646 p
->mnLookahead
= lookahead
;
647 p
->mnAction
= action
;
649 if( p
->mxLookahead
<lookahead
) p
->mxLookahead
= lookahead
;
650 if( p
->mnLookahead
>lookahead
){
651 p
->mnLookahead
= lookahead
;
652 p
->mnAction
= action
;
655 p
->aLookahead
[p
->nLookahead
].lookahead
= lookahead
;
656 p
->aLookahead
[p
->nLookahead
].action
= action
;
661 ** Add the transaction set built up with prior calls to acttab_action()
662 ** into the current action table. Then reset the transaction set back
663 ** to an empty set in preparation for a new round of acttab_action() calls.
665 ** Return the offset into the action table of the new transaction.
667 ** If the makeItSafe parameter is true, then the offset is chosen so that
668 ** it is impossible to overread the yy_lookaside[] table regardless of
669 ** the lookaside token. This is done for the terminal symbols, as they
670 ** come from external inputs and can contain syntax errors. When makeItSafe
671 ** is false, there is more flexibility in selecting offsets, resulting in
672 ** a smaller table. For non-terminal symbols, which are never syntax errors,
673 ** makeItSafe can be false.
675 int acttab_insert(acttab
*p
, int makeItSafe
){
677 assert( p
->nLookahead
>0 );
679 /* Make sure we have enough space to hold the expanded action table
680 ** in the worst case. The worst case occurs if the transaction set
681 ** must be appended to the current action table
684 if( p
->nAction
+ n
>= p
->nActionAlloc
){
685 int oldAlloc
= p
->nActionAlloc
;
686 p
->nActionAlloc
= p
->nAction
+ n
+ p
->nActionAlloc
+ 20;
687 p
->aAction
= (struct lookahead_action
*) realloc( p
->aAction
,
688 sizeof(p
->aAction
[0])*p
->nActionAlloc
);
690 fprintf(stderr
,"malloc failed\n");
693 for(i
=oldAlloc
; i
<p
->nActionAlloc
; i
++){
694 p
->aAction
[i
].lookahead
= -1;
695 p
->aAction
[i
].action
= -1;
699 /* Scan the existing action table looking for an offset that is a
700 ** duplicate of the current transaction set. Fall out of the loop
701 ** if and when the duplicate is found.
703 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
705 end
= makeItSafe
? p
->mnLookahead
: 0;
706 for(i
=p
->nAction
-1; i
>=end
; i
--){
707 if( p
->aAction
[i
].lookahead
==p
->mnLookahead
){
708 /* All lookaheads and actions in the aLookahead[] transaction
709 ** must match against the candidate aAction[i] entry. */
710 if( p
->aAction
[i
].action
!=p
->mnAction
) continue;
711 for(j
=0; j
<p
->nLookahead
; j
++){
712 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
713 if( k
<0 || k
>=p
->nAction
) break;
714 if( p
->aLookahead
[j
].lookahead
!=p
->aAction
[k
].lookahead
) break;
715 if( p
->aLookahead
[j
].action
!=p
->aAction
[k
].action
) break;
717 if( j
<p
->nLookahead
) continue;
719 /* No possible lookahead value that is not in the aLookahead[]
720 ** transaction is allowed to match aAction[i] */
722 for(j
=0; j
<p
->nAction
; j
++){
723 if( p
->aAction
[j
].lookahead
<0 ) continue;
724 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) n
++;
726 if( n
==p
->nLookahead
){
727 break; /* An exact match is found at offset i */
732 /* If no existing offsets exactly match the current transaction, find an
733 ** an empty offset in the aAction[] table in which we can add the
734 ** aLookahead[] transaction.
737 /* Look for holes in the aAction[] table that fit the current
738 ** aLookahead[] transaction. Leave i set to the offset of the hole.
739 ** If no holes are found, i is left at p->nAction, which means the
740 ** transaction will be appended. */
741 i
= makeItSafe
? p
->mnLookahead
: 0;
742 for(; i
<p
->nActionAlloc
- p
->mxLookahead
; i
++){
743 if( p
->aAction
[i
].lookahead
<0 ){
744 for(j
=0; j
<p
->nLookahead
; j
++){
745 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
747 if( p
->aAction
[k
].lookahead
>=0 ) break;
749 if( j
<p
->nLookahead
) continue;
750 for(j
=0; j
<p
->nAction
; j
++){
751 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) break;
754 break; /* Fits in empty slots */
759 /* Insert transaction set at index i. */
762 for(j
=0; j
<p
->nLookahead
; j
++){
763 printf(" %d", p
->aLookahead
[j
].lookahead
);
765 printf(" inserted at %d\n", i
);
767 for(j
=0; j
<p
->nLookahead
; j
++){
768 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
769 p
->aAction
[k
] = p
->aLookahead
[j
];
770 if( k
>=p
->nAction
) p
->nAction
= k
+1;
772 if( makeItSafe
&& i
+p
->nterminal
>=p
->nAction
) p
->nAction
= i
+p
->nterminal
+1;
775 /* Return the offset that is added to the lookahead in order to get the
776 ** index into yy_action of the action */
777 return i
- p
->mnLookahead
;
781 ** Return the size of the action table without the trailing syntax error
784 int acttab_action_size(acttab
*p
){
786 while( n
>0 && p
->aAction
[n
-1].lookahead
<0 ){ n
--; }
790 /********************** From the file "build.c" *****************************/
792 ** Routines to construction the finite state machine for the LEMON
796 /* Find a precedence symbol of every rule in the grammar.
798 ** Those rules which have a precedence symbol coded in the input
799 ** grammar using the "[symbol]" construct will already have the
800 ** rp->precsym field filled. Other rules take as their precedence
801 ** symbol the first RHS symbol with a defined precedence. If there
802 ** are not RHS symbols with a defined precedence, the precedence
803 ** symbol field is left blank.
805 void FindRulePrecedences(struct lemon
*xp
)
808 for(rp
=xp
->rule
; rp
; rp
=rp
->next
){
809 if( rp
->precsym
==0 ){
811 for(i
=0; i
<rp
->nrhs
&& rp
->precsym
==0; i
++){
812 struct symbol
*sp
= rp
->rhs
[i
];
813 if( sp
->type
==MULTITERMINAL
){
814 for(j
=0; j
<sp
->nsubsym
; j
++){
815 if( sp
->subsym
[j
]->prec
>=0 ){
816 rp
->precsym
= sp
->subsym
[j
];
820 }else if( sp
->prec
>=0 ){
821 rp
->precsym
= rp
->rhs
[i
];
829 /* Find all nonterminals which will generate the empty string.
830 ** Then go back and compute the first sets of every nonterminal.
831 ** The first set is the set of all terminal symbols which can begin
832 ** a string generated by that nonterminal.
834 void FindFirstSets(struct lemon
*lemp
)
840 for(i
=0; i
<lemp
->nsymbol
; i
++){
841 lemp
->symbols
[i
]->lambda
= LEMON_FALSE
;
843 for(i
=lemp
->nterminal
; i
<lemp
->nsymbol
; i
++){
844 lemp
->symbols
[i
]->firstset
= SetNew();
847 /* First compute all lambdas */
850 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
851 if( rp
->lhs
->lambda
) continue;
852 for(i
=0; i
<rp
->nrhs
; i
++){
853 struct symbol
*sp
= rp
->rhs
[i
];
854 assert( sp
->type
==NONTERMINAL
|| sp
->lambda
==LEMON_FALSE
);
855 if( sp
->lambda
==LEMON_FALSE
) break;
858 rp
->lhs
->lambda
= LEMON_TRUE
;
864 /* Now compute all first sets */
866 struct symbol
*s1
, *s2
;
868 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
870 for(i
=0; i
<rp
->nrhs
; i
++){
872 if( s2
->type
==TERMINAL
){
873 progress
+= SetAdd(s1
->firstset
,s2
->index
);
875 }else if( s2
->type
==MULTITERMINAL
){
876 for(j
=0; j
<s2
->nsubsym
; j
++){
877 progress
+= SetAdd(s1
->firstset
,s2
->subsym
[j
]->index
);
881 if( s1
->lambda
==LEMON_FALSE
) break;
883 progress
+= SetUnion(s1
->firstset
,s2
->firstset
);
884 if( s2
->lambda
==LEMON_FALSE
) break;
892 /* Compute all LR(0) states for the grammar. Links
893 ** are added to between some states so that the LR(1) follow sets
894 ** can be computed later.
896 PRIVATE
struct state
*getstate(struct lemon
*); /* forward reference */
897 void FindStates(struct lemon
*lemp
)
904 /* Find the start symbol */
906 sp
= Symbol_find(lemp
->start
);
908 ErrorMsg(lemp
->filename
,0,
909 "The specified start symbol \"%s\" is not \
910 in a nonterminal of the grammar. \"%s\" will be used as the start \
911 symbol instead.",lemp
->start
,lemp
->startRule
->lhs
->name
);
913 sp
= lemp
->startRule
->lhs
;
916 sp
= lemp
->startRule
->lhs
;
919 /* Make sure the start symbol doesn't occur on the right-hand side of
920 ** any rule. Report an error if it does. (YACC would generate a new
921 ** start symbol in this case.) */
922 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
924 for(i
=0; i
<rp
->nrhs
; i
++){
925 if( rp
->rhs
[i
]==sp
){ /* FIX ME: Deal with multiterminals */
926 ErrorMsg(lemp
->filename
,0,
927 "The start symbol \"%s\" occurs on the \
928 right-hand side of a rule. This will result in a parser which \
929 does not work properly.",sp
->name
);
935 /* The basis configuration set for the first state
936 ** is all rules which have the start symbol as their
938 for(rp
=sp
->rule
; rp
; rp
=rp
->nextlhs
){
939 struct config
*newcfp
;
941 newcfp
= Configlist_addbasis(rp
,0);
942 SetAdd(newcfp
->fws
,0);
945 /* Compute the first state. All other states will be
946 ** computed automatically during the computation of the first one.
947 ** The returned pointer to the first state is not used. */
948 (void)getstate(lemp
);
952 /* Return a pointer to a state which is described by the configuration
953 ** list which has been built from calls to Configlist_add.
955 PRIVATE
void buildshifts(struct lemon
*, struct state
*); /* Forwd ref */
956 PRIVATE
struct state
*getstate(struct lemon
*lemp
)
958 struct config
*cfp
, *bp
;
961 /* Extract the sorted basis of the new state. The basis was constructed
962 ** by prior calls to "Configlist_addbasis()". */
963 Configlist_sortbasis();
964 bp
= Configlist_basis();
966 /* Get a state with the same basis */
967 stp
= State_find(bp
);
969 /* A state with the same basis already exists! Copy all the follow-set
970 ** propagation links from the state under construction into the
971 ** preexisting state, then return a pointer to the preexisting state */
972 struct config
*x
, *y
;
973 for(x
=bp
, y
=stp
->bp
; x
&& y
; x
=x
->bp
, y
=y
->bp
){
974 Plink_copy(&y
->bplp
,x
->bplp
);
975 Plink_delete(x
->fplp
);
976 x
->fplp
= x
->bplp
= 0;
978 cfp
= Configlist_return();
981 /* This really is a new state. Construct all the details */
982 Configlist_closure(lemp
); /* Compute the configuration closure */
983 Configlist_sort(); /* Sort the configuration closure */
984 cfp
= Configlist_return(); /* Get a pointer to the config list */
985 stp
= State_new(); /* A new state structure */
987 stp
->bp
= bp
; /* Remember the configuration basis */
988 stp
->cfp
= cfp
; /* Remember the configuration closure */
989 stp
->statenum
= lemp
->nstate
++; /* Every state gets a sequence number */
990 stp
->ap
= 0; /* No actions, yet. */
991 State_insert(stp
,stp
->bp
); /* Add to the state table */
992 buildshifts(lemp
,stp
); /* Recursively compute successor states */
998 ** Return true if two symbols are the same.
1000 int same_symbol(struct symbol
*a
, struct symbol
*b
)
1003 if( a
==b
) return 1;
1004 if( a
->type
!=MULTITERMINAL
) return 0;
1005 if( b
->type
!=MULTITERMINAL
) return 0;
1006 if( a
->nsubsym
!=b
->nsubsym
) return 0;
1007 for(i
=0; i
<a
->nsubsym
; i
++){
1008 if( a
->subsym
[i
]!=b
->subsym
[i
] ) return 0;
1013 /* Construct all successor states to the given state. A "successor"
1014 ** state is any state which can be reached by a shift action.
1016 PRIVATE
void buildshifts(struct lemon
*lemp
, struct state
*stp
)
1018 struct config
*cfp
; /* For looping thru the config closure of "stp" */
1019 struct config
*bcfp
; /* For the inner loop on config closure of "stp" */
1020 struct config
*newcfg
; /* */
1021 struct symbol
*sp
; /* Symbol following the dot in configuration "cfp" */
1022 struct symbol
*bsp
; /* Symbol following the dot in configuration "bcfp" */
1023 struct state
*newstp
; /* A pointer to a successor state */
1025 /* Each configuration becomes complete after it contibutes to a successor
1026 ** state. Initially, all configurations are incomplete */
1027 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
) cfp
->status
= INCOMPLETE
;
1029 /* Loop through all configurations of the state "stp" */
1030 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1031 if( cfp
->status
==COMPLETE
) continue; /* Already used by inner loop */
1032 if( cfp
->dot
>=cfp
->rp
->nrhs
) continue; /* Can't shift this config */
1033 Configlist_reset(); /* Reset the new config set */
1034 sp
= cfp
->rp
->rhs
[cfp
->dot
]; /* Symbol after the dot */
1036 /* For every configuration in the state "stp" which has the symbol "sp"
1037 ** following its dot, add the same configuration to the basis set under
1038 ** construction but with the dot shifted one symbol to the right. */
1039 for(bcfp
=cfp
; bcfp
; bcfp
=bcfp
->next
){
1040 if( bcfp
->status
==COMPLETE
) continue; /* Already used */
1041 if( bcfp
->dot
>=bcfp
->rp
->nrhs
) continue; /* Can't shift this one */
1042 bsp
= bcfp
->rp
->rhs
[bcfp
->dot
]; /* Get symbol after dot */
1043 if( !same_symbol(bsp
,sp
) ) continue; /* Must be same as for "cfp" */
1044 bcfp
->status
= COMPLETE
; /* Mark this config as used */
1045 newcfg
= Configlist_addbasis(bcfp
->rp
,bcfp
->dot
+1);
1046 Plink_add(&newcfg
->bplp
,bcfp
);
1049 /* Get a pointer to the state described by the basis configuration set
1050 ** constructed in the preceding loop */
1051 newstp
= getstate(lemp
);
1053 /* The state "newstp" is reached from the state "stp" by a shift action
1054 ** on the symbol "sp" */
1055 if( sp
->type
==MULTITERMINAL
){
1057 for(i
=0; i
<sp
->nsubsym
; i
++){
1058 Action_add(&stp
->ap
,SHIFT
,sp
->subsym
[i
],(char*)newstp
);
1061 Action_add(&stp
->ap
,SHIFT
,sp
,(char *)newstp
);
1067 ** Construct the propagation links
1069 void FindLinks(struct lemon
*lemp
)
1072 struct config
*cfp
, *other
;
1076 /* Housekeeping detail:
1077 ** Add to every propagate link a pointer back to the state to
1078 ** which the link is attached. */
1079 for(i
=0; i
<lemp
->nstate
; i
++){
1080 stp
= lemp
->sorted
[i
];
1081 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1086 /* Convert all backlinks into forward links. Only the forward
1087 ** links are used in the follow-set computation. */
1088 for(i
=0; i
<lemp
->nstate
; i
++){
1089 stp
= lemp
->sorted
[i
];
1090 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1091 for(plp
=cfp
->bplp
; plp
; plp
=plp
->next
){
1093 Plink_add(&other
->fplp
,cfp
);
1099 /* Compute all followsets.
1101 ** A followset is the set of all symbols which can come immediately
1102 ** after a configuration.
1104 void FindFollowSets(struct lemon
*lemp
)
1112 for(i
=0; i
<lemp
->nstate
; i
++){
1113 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1114 cfp
->status
= INCOMPLETE
;
1120 for(i
=0; i
<lemp
->nstate
; i
++){
1121 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1122 if( cfp
->status
==COMPLETE
) continue;
1123 for(plp
=cfp
->fplp
; plp
; plp
=plp
->next
){
1124 change
= SetUnion(plp
->cfp
->fws
,cfp
->fws
);
1126 plp
->cfp
->status
= INCOMPLETE
;
1130 cfp
->status
= COMPLETE
;
1136 static int resolve_conflict(struct action
*,struct action
*);
1138 /* Compute the reduce actions, and resolve conflicts.
1140 void FindActions(struct lemon
*lemp
)
1148 /* Add all of the reduce actions
1149 ** A reduce action is added for each element of the followset of
1150 ** a configuration which has its dot at the extreme right.
1152 for(i
=0; i
<lemp
->nstate
; i
++){ /* Loop over all states */
1153 stp
= lemp
->sorted
[i
];
1154 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){ /* Loop over all configurations */
1155 if( cfp
->rp
->nrhs
==cfp
->dot
){ /* Is dot at extreme right? */
1156 for(j
=0; j
<lemp
->nterminal
; j
++){
1157 if( SetFind(cfp
->fws
,j
) ){
1158 /* Add a reduce action to the state "stp" which will reduce by the
1159 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1160 Action_add(&stp
->ap
,REDUCE
,lemp
->symbols
[j
],(char *)cfp
->rp
);
1167 /* Add the accepting token */
1169 sp
= Symbol_find(lemp
->start
);
1170 if( sp
==0 ) sp
= lemp
->startRule
->lhs
;
1172 sp
= lemp
->startRule
->lhs
;
1174 /* Add to the first state (which is always the starting state of the
1175 ** finite state machine) an action to ACCEPT if the lookahead is the
1176 ** start nonterminal. */
1177 Action_add(&lemp
->sorted
[0]->ap
,ACCEPT
,sp
,0);
1179 /* Resolve conflicts */
1180 for(i
=0; i
<lemp
->nstate
; i
++){
1181 struct action
*ap
, *nap
;
1182 stp
= lemp
->sorted
[i
];
1183 /* assert( stp->ap ); */
1184 stp
->ap
= Action_sort(stp
->ap
);
1185 for(ap
=stp
->ap
; ap
&& ap
->next
; ap
=ap
->next
){
1186 for(nap
=ap
->next
; nap
&& nap
->sp
==ap
->sp
; nap
=nap
->next
){
1187 /* The two actions "ap" and "nap" have the same lookahead.
1188 ** Figure out which one should be used */
1189 lemp
->nconflict
+= resolve_conflict(ap
,nap
);
1194 /* Report an error for each rule that can never be reduced. */
1195 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->canReduce
= LEMON_FALSE
;
1196 for(i
=0; i
<lemp
->nstate
; i
++){
1198 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
1199 if( ap
->type
==REDUCE
) ap
->x
.rp
->canReduce
= LEMON_TRUE
;
1202 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
1203 if( rp
->canReduce
) continue;
1204 ErrorMsg(lemp
->filename
,rp
->ruleline
,"This rule can not be reduced.\n");
1209 /* Resolve a conflict between the two given actions. If the
1210 ** conflict can't be resolved, return non-zero.
1213 ** To resolve a conflict, first look to see if either action
1214 ** is on an error rule. In that case, take the action which
1215 ** is not associated with the error rule. If neither or both
1216 ** actions are associated with an error rule, then try to
1217 ** use precedence to resolve the conflict.
1219 ** If either action is a SHIFT, then it must be apx. This
1220 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1222 static int resolve_conflict(
1226 struct symbol
*spx
, *spy
;
1228 assert( apx
->sp
==apy
->sp
); /* Otherwise there would be no conflict */
1229 if( apx
->type
==SHIFT
&& apy
->type
==SHIFT
){
1230 apy
->type
= SSCONFLICT
;
1233 if( apx
->type
==SHIFT
&& apy
->type
==REDUCE
){
1235 spy
= apy
->x
.rp
->precsym
;
1236 if( spy
==0 || spx
->prec
<0 || spy
->prec
<0 ){
1237 /* Not enough precedence information. */
1238 apy
->type
= SRCONFLICT
;
1240 }else if( spx
->prec
>spy
->prec
){ /* higher precedence wins */
1241 apy
->type
= RD_RESOLVED
;
1242 }else if( spx
->prec
<spy
->prec
){
1243 apx
->type
= SH_RESOLVED
;
1244 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==RIGHT
){ /* Use operator */
1245 apy
->type
= RD_RESOLVED
; /* associativity */
1246 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==LEFT
){ /* to break tie */
1247 apx
->type
= SH_RESOLVED
;
1249 assert( spx
->prec
==spy
->prec
&& spx
->assoc
==NONE
);
1252 }else if( apx
->type
==REDUCE
&& apy
->type
==REDUCE
){
1253 spx
= apx
->x
.rp
->precsym
;
1254 spy
= apy
->x
.rp
->precsym
;
1255 if( spx
==0 || spy
==0 || spx
->prec
<0 ||
1256 spy
->prec
<0 || spx
->prec
==spy
->prec
){
1257 apy
->type
= RRCONFLICT
;
1259 }else if( spx
->prec
>spy
->prec
){
1260 apy
->type
= RD_RESOLVED
;
1261 }else if( spx
->prec
<spy
->prec
){
1262 apx
->type
= RD_RESOLVED
;
1266 apx
->type
==SH_RESOLVED
||
1267 apx
->type
==RD_RESOLVED
||
1268 apx
->type
==SSCONFLICT
||
1269 apx
->type
==SRCONFLICT
||
1270 apx
->type
==RRCONFLICT
||
1271 apy
->type
==SH_RESOLVED
||
1272 apy
->type
==RD_RESOLVED
||
1273 apy
->type
==SSCONFLICT
||
1274 apy
->type
==SRCONFLICT
||
1275 apy
->type
==RRCONFLICT
1277 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1278 ** REDUCEs on the list. If we reach this point it must be because
1279 ** the parser conflict had already been resolved. */
1283 /********************* From the file "configlist.c" *************************/
1285 ** Routines to processing a configuration list and building a state
1286 ** in the LEMON parser generator.
1289 static struct config
*freelist
= 0; /* List of free configurations */
1290 static struct config
*current
= 0; /* Top of list of configurations */
1291 static struct config
**currentend
= 0; /* Last on list of configs */
1292 static struct config
*basis
= 0; /* Top of list of basis configs */
1293 static struct config
**basisend
= 0; /* End of list of basis configs */
1295 /* Return a pointer to a new configuration */
1296 PRIVATE
struct config
*newconfig(void){
1297 struct config
*newcfg
;
1301 freelist
= (struct config
*)calloc( amt
, sizeof(struct config
) );
1303 fprintf(stderr
,"Unable to allocate memory for a new configuration.");
1306 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
1307 freelist
[amt
-1].next
= 0;
1310 freelist
= freelist
->next
;
1314 /* The configuration "old" is no longer used */
1315 PRIVATE
void deleteconfig(struct config
*old
)
1317 old
->next
= freelist
;
1321 /* Initialized the configuration list builder */
1322 void Configlist_init(void){
1324 currentend
= ¤t
;
1331 /* Initialized the configuration list builder */
1332 void Configlist_reset(void){
1334 currentend
= ¤t
;
1337 Configtable_clear(0);
1341 /* Add another configuration to the configuration list */
1342 struct config
*Configlist_add(
1343 struct rule
*rp
, /* The rule */
1344 int dot
/* Index into the RHS of the rule where the dot goes */
1346 struct config
*cfp
, model
;
1348 assert( currentend
!=0 );
1351 cfp
= Configtable_find(&model
);
1356 cfp
->fws
= SetNew();
1358 cfp
->fplp
= cfp
->bplp
= 0;
1362 currentend
= &cfp
->next
;
1363 Configtable_insert(cfp
);
1368 /* Add a basis configuration to the configuration list */
1369 struct config
*Configlist_addbasis(struct rule
*rp
, int dot
)
1371 struct config
*cfp
, model
;
1373 assert( basisend
!=0 );
1374 assert( currentend
!=0 );
1377 cfp
= Configtable_find(&model
);
1382 cfp
->fws
= SetNew();
1384 cfp
->fplp
= cfp
->bplp
= 0;
1388 currentend
= &cfp
->next
;
1390 basisend
= &cfp
->bp
;
1391 Configtable_insert(cfp
);
1396 /* Compute the closure of the configuration list */
1397 void Configlist_closure(struct lemon
*lemp
)
1399 struct config
*cfp
, *newcfp
;
1400 struct rule
*rp
, *newrp
;
1401 struct symbol
*sp
, *xsp
;
1404 assert( currentend
!=0 );
1405 for(cfp
=current
; cfp
; cfp
=cfp
->next
){
1408 if( dot
>=rp
->nrhs
) continue;
1410 if( sp
->type
==NONTERMINAL
){
1411 if( sp
->rule
==0 && sp
!=lemp
->errsym
){
1412 ErrorMsg(lemp
->filename
,rp
->line
,"Nonterminal \"%s\" has no rules.",
1416 for(newrp
=sp
->rule
; newrp
; newrp
=newrp
->nextlhs
){
1417 newcfp
= Configlist_add(newrp
,0);
1418 for(i
=dot
+1; i
<rp
->nrhs
; i
++){
1420 if( xsp
->type
==TERMINAL
){
1421 SetAdd(newcfp
->fws
,xsp
->index
);
1423 }else if( xsp
->type
==MULTITERMINAL
){
1425 for(k
=0; k
<xsp
->nsubsym
; k
++){
1426 SetAdd(newcfp
->fws
, xsp
->subsym
[k
]->index
);
1430 SetUnion(newcfp
->fws
,xsp
->firstset
);
1431 if( xsp
->lambda
==LEMON_FALSE
) break;
1434 if( i
==rp
->nrhs
) Plink_add(&cfp
->fplp
,newcfp
);
1441 /* Sort the configuration list */
1442 void Configlist_sort(void){
1443 current
= (struct config
*)msort((char*)current
,(char**)&(current
->next
),
1449 /* Sort the basis configuration list */
1450 void Configlist_sortbasis(void){
1451 basis
= (struct config
*)msort((char*)current
,(char**)&(current
->bp
),
1457 /* Return a pointer to the head of the configuration list and
1458 ** reset the list */
1459 struct config
*Configlist_return(void){
1467 /* Return a pointer to the head of the configuration list and
1468 ** reset the list */
1469 struct config
*Configlist_basis(void){
1477 /* Free all elements of the given configuration list */
1478 void Configlist_eat(struct config
*cfp
)
1480 struct config
*nextcfp
;
1481 for(; cfp
; cfp
=nextcfp
){
1482 nextcfp
= cfp
->next
;
1483 assert( cfp
->fplp
==0 );
1484 assert( cfp
->bplp
==0 );
1485 if( cfp
->fws
) SetFree(cfp
->fws
);
1490 /***************** From the file "error.c" *********************************/
1492 ** Code for printing error message.
1495 void ErrorMsg(const char *filename
, int lineno
, const char *format
, ...){
1497 fprintf(stderr
, "%s:%d: ", filename
, lineno
);
1498 va_start(ap
, format
);
1499 vfprintf(stderr
,format
,ap
);
1501 fprintf(stderr
, "\n");
1503 /**************** From the file "main.c" ************************************/
1505 ** Main program file for the LEMON parser generator.
1508 /* Report an out-of-memory condition and abort. This function
1509 ** is used mostly by the "MemoryCheck" macro in struct.h
1511 void memory_error(void){
1512 fprintf(stderr
,"Out of memory. Aborting...\n");
1516 static int nDefine
= 0; /* Number of -D options on the command line */
1517 static char **azDefine
= 0; /* Name of the -D macros */
1519 /* This routine is called with the argument to each -D command-line option.
1520 ** Add the macro defined to the azDefine array.
1522 static void handle_D_option(char *z
){
1525 azDefine
= (char **) realloc(azDefine
, sizeof(azDefine
[0])*nDefine
);
1527 fprintf(stderr
,"out of memory\n");
1530 paz
= &azDefine
[nDefine
-1];
1531 *paz
= (char *) malloc( lemonStrlen(z
)+1 );
1533 fprintf(stderr
,"out of memory\n");
1536 lemon_strcpy(*paz
, z
);
1537 for(z
=*paz
; *z
&& *z
!='='; z
++){}
1541 /* Rember the name of the output directory
1543 static char *outputDir
= NULL
;
1544 static void handle_d_option(char *z
){
1545 outputDir
= (char *) malloc( lemonStrlen(z
)+1 );
1547 fprintf(stderr
,"out of memory\n");
1550 lemon_strcpy(outputDir
, z
);
1553 static char *user_templatename
= NULL
;
1554 static void handle_T_option(char *z
){
1555 user_templatename
= (char *) malloc( lemonStrlen(z
)+1 );
1556 if( user_templatename
==0 ){
1559 lemon_strcpy(user_templatename
, z
);
1562 /* Merge together to lists of rules ordered by rule.iRule */
1563 static struct rule
*Rule_merge(struct rule
*pA
, struct rule
*pB
){
1564 struct rule
*pFirst
= 0;
1565 struct rule
**ppPrev
= &pFirst
;
1567 if( pA
->iRule
<pB
->iRule
){
1586 ** Sort a list of rules in order of increasing iRule value
1588 static struct rule
*Rule_sort(struct rule
*rp
){
1592 memset(x
, 0, sizeof(x
));
1596 for(i
=0; i
<sizeof(x
)/sizeof(x
[0]) && x
[i
]; i
++){
1597 rp
= Rule_merge(x
[i
], rp
);
1604 for(i
=0; i
<sizeof(x
)/sizeof(x
[0]); i
++){
1605 rp
= Rule_merge(x
[i
], rp
);
1610 /* forward reference */
1611 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
);
1613 /* Print a single line of the "Parser Stats" output
1615 static void stats_line(const char *zLabel
, int iValue
){
1616 int nLabel
= lemonStrlen(zLabel
);
1617 printf(" %s%.*s %5d\n", zLabel
,
1618 35-nLabel
, "................................",
1622 /* The main program. Parse the command line and do it... */
1623 int main(int argc
, char **argv
)
1625 static int version
= 0;
1626 static int rpflag
= 0;
1627 static int basisflag
= 0;
1628 static int compress
= 0;
1629 static int quiet
= 0;
1630 static int statistics
= 0;
1631 static int mhflag
= 0;
1632 static int nolinenosflag
= 0;
1633 static int noResort
= 0;
1635 static struct s_options options
[] = {
1636 {OPT_FLAG
, "b", (char*)&basisflag
, "Print only the basis in report."},
1637 {OPT_FLAG
, "c", (char*)&compress
, "Don't compress the action table."},
1638 {OPT_FSTR
, "d", (char*)&handle_d_option
, "Output directory. Default '.'"},
1639 {OPT_FSTR
, "D", (char*)handle_D_option
, "Define an %ifdef macro."},
1640 {OPT_FSTR
, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1641 {OPT_FLAG
, "g", (char*)&rpflag
, "Print grammar without actions."},
1642 {OPT_FSTR
, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1643 {OPT_FLAG
, "m", (char*)&mhflag
, "Output a makeheaders compatible file."},
1644 {OPT_FLAG
, "l", (char*)&nolinenosflag
, "Do not print #line statements."},
1645 {OPT_FSTR
, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1646 {OPT_FLAG
, "p", (char*)&showPrecedenceConflict
,
1647 "Show conflicts resolved by precedence rules"},
1648 {OPT_FLAG
, "q", (char*)&quiet
, "(Quiet) Don't print the report file."},
1649 {OPT_FLAG
, "r", (char*)&noResort
, "Do not sort or renumber states"},
1650 {OPT_FLAG
, "s", (char*)&statistics
,
1651 "Print parser stats to standard output."},
1652 {OPT_FLAG
, "x", (char*)&version
, "Print the version number."},
1653 {OPT_FSTR
, "T", (char*)handle_T_option
, "Specify a template file."},
1654 {OPT_FSTR
, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1662 OptInit(argv
,options
,stderr
);
1664 printf("Lemon version 1.0\n");
1667 if( OptNArgs()!=1 ){
1668 fprintf(stderr
,"Exactly one filename argument is required.\n");
1671 memset(&lem
, 0, sizeof(lem
));
1674 /* Initialize the machine */
1678 lem
.argv0
= argv
[0];
1679 lem
.filename
= OptArg(0);
1680 lem
.basisflag
= basisflag
;
1681 lem
.nolinenosflag
= nolinenosflag
;
1684 /* Parse the input file */
1686 if( lem
.errorcnt
) exit(lem
.errorcnt
);
1688 fprintf(stderr
,"Empty grammar.\n");
1691 lem
.errsym
= Symbol_find("error");
1693 /* Count and index the symbols of the grammar */
1694 Symbol_new("{default}");
1695 lem
.nsymbol
= Symbol_count();
1696 lem
.symbols
= Symbol_arrayof();
1697 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1698 qsort(lem
.symbols
,lem
.nsymbol
,sizeof(struct symbol
*), Symbolcmpp
);
1699 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1700 while( lem
.symbols
[i
-1]->type
==MULTITERMINAL
){ i
--; }
1701 assert( strcmp(lem
.symbols
[i
-1]->name
,"{default}")==0 );
1702 lem
.nsymbol
= i
- 1;
1703 for(i
=1; ISUPPER(lem
.symbols
[i
]->name
[0]); i
++);
1706 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1707 ** reduce action C-code associated with them last, so that the switch()
1708 ** statement that selects reduction actions will have a smaller jump table.
1710 for(i
=0, rp
=lem
.rule
; rp
; rp
=rp
->next
){
1711 rp
->iRule
= rp
->code
? i
++ : -1;
1713 for(rp
=lem
.rule
; rp
; rp
=rp
->next
){
1714 if( rp
->iRule
<0 ) rp
->iRule
= i
++;
1716 lem
.startRule
= lem
.rule
;
1717 lem
.rule
= Rule_sort(lem
.rule
);
1719 /* Generate a reprint of the grammar, if requested on the command line */
1723 /* Initialize the size for all follow and first sets */
1724 SetSize(lem
.nterminal
+1);
1726 /* Find the precedence for every production rule (that has one) */
1727 FindRulePrecedences(&lem
);
1729 /* Compute the lambda-nonterminals and the first-sets for every
1731 FindFirstSets(&lem
);
1733 /* Compute all LR(0) states. Also record follow-set propagation
1734 ** links so that the follow-set can be computed later */
1737 lem
.sorted
= State_arrayof();
1739 /* Tie up loose ends on the propagation links */
1742 /* Compute the follow set of every reducible configuration */
1743 FindFollowSets(&lem
);
1745 /* Compute the action tables */
1748 /* Compress the action tables */
1749 if( compress
==0 ) CompressTables(&lem
);
1751 /* Reorder and renumber the states so that states with fewer choices
1752 ** occur at the end. This is an optimization that helps make the
1753 ** generated parser tables smaller. */
1754 if( noResort
==0 ) ResortStates(&lem
);
1756 /* Generate a report of the parser generated. (the "y.output" file) */
1757 if( !quiet
) ReportOutput(&lem
);
1759 /* Generate the source code for the parser */
1760 ReportTable(&lem
, mhflag
);
1762 /* Produce a header file for use by the scanner. (This step is
1763 ** omitted if the "-m" option is used because makeheaders will
1764 ** generate the file for us.) */
1765 if( !mhflag
) ReportHeader(&lem
);
1768 printf("Parser statistics:\n");
1769 stats_line("terminal symbols", lem
.nterminal
);
1770 stats_line("non-terminal symbols", lem
.nsymbol
- lem
.nterminal
);
1771 stats_line("total symbols", lem
.nsymbol
);
1772 stats_line("rules", lem
.nrule
);
1773 stats_line("states", lem
.nxstate
);
1774 stats_line("conflicts", lem
.nconflict
);
1775 stats_line("action table entries", lem
.nactiontab
);
1776 stats_line("lookahead table entries", lem
.nlookaheadtab
);
1777 stats_line("total table size (bytes)", lem
.tablesize
);
1779 if( lem
.nconflict
> 0 ){
1780 fprintf(stderr
,"%d parsing conflicts.\n",lem
.nconflict
);
1783 /* return 0 on success, 1 on failure. */
1784 exitcode
= ((lem
.errorcnt
> 0) || (lem
.nconflict
> 0)) ? 1 : 0;
1788 /******************** From the file "msort.c" *******************************/
1790 ** A generic merge-sort program.
1793 ** Let "ptr" be a pointer to some structure which is at the head of
1794 ** a null-terminated list. Then to sort the list call:
1796 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1798 ** In the above, "cmpfnc" is a pointer to a function which compares
1799 ** two instances of the structure and returns an integer, as in
1800 ** strcmp. The second argument is a pointer to the pointer to the
1801 ** second element of the linked list. This address is used to compute
1802 ** the offset to the "next" field within the structure. The offset to
1803 ** the "next" field must be constant for all structures in the list.
1805 ** The function returns a new pointer which is the head of the list
1813 ** Return a pointer to the next structure in the linked list.
1815 #define NEXT(A) (*(char**)(((char*)A)+offset))
1819 ** a: A sorted, null-terminated linked list. (May be null).
1820 ** b: A sorted, null-terminated linked list. (May be null).
1821 ** cmp: A pointer to the comparison function.
1822 ** offset: Offset in the structure to the "next" field.
1825 ** A pointer to the head of a sorted list containing the elements
1829 ** The "next" pointers for elements in the lists a and b are
1835 int (*cmp
)(const char*,const char*),
1845 if( (*cmp
)(a
,b
)<=0 ){
1854 if( (*cmp
)(a
,b
)<=0 ){
1864 if( a
) NEXT(ptr
) = a
;
1872 ** list: Pointer to a singly-linked list of structures.
1873 ** next: Pointer to pointer to the second element of the list.
1874 ** cmp: A comparison function.
1877 ** A pointer to the head of a sorted list containing the elements
1878 ** orginally in list.
1881 ** The "next" pointers for elements in list are changed.
1887 int (*cmp
)(const char*,const char*)
1889 unsigned long offset
;
1891 char *set
[LISTSIZE
];
1893 offset
= (unsigned long)((char*)next
- (char*)list
);
1894 for(i
=0; i
<LISTSIZE
; i
++) set
[i
] = 0;
1899 for(i
=0; i
<LISTSIZE
-1 && set
[i
]!=0; i
++){
1900 ep
= merge(ep
,set
[i
],cmp
,offset
);
1906 for(i
=0; i
<LISTSIZE
; i
++) if( set
[i
] ) ep
= merge(set
[i
],ep
,cmp
,offset
);
1909 /************************ From the file "option.c" **************************/
1911 static struct s_options
*op
;
1912 static FILE *errstream
;
1914 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1917 ** Print the command line with a carrot pointing to the k-th character
1918 ** of the n-th field.
1920 static void errline(int n
, int k
, FILE *err
)
1923 if( argv
[0] ) fprintf(err
,"%s",argv
[0]);
1924 spcnt
= lemonStrlen(argv
[0]) + 1;
1925 for(i
=1; i
<n
&& argv
[i
]; i
++){
1926 fprintf(err
," %s",argv
[i
]);
1927 spcnt
+= lemonStrlen(argv
[i
])+1;
1930 for(; argv
[i
]; i
++) fprintf(err
," %s",argv
[i
]);
1932 fprintf(err
,"\n%*s^-- here\n",spcnt
,"");
1934 fprintf(err
,"\n%*shere --^\n",spcnt
-7,"");
1939 ** Return the index of the N-th non-switch argument. Return -1
1940 ** if N is out of range.
1942 static int argindex(int n
)
1946 if( argv
!=0 && *argv
!=0 ){
1947 for(i
=1; argv
[i
]; i
++){
1948 if( dashdash
|| !ISOPT(argv
[i
]) ){
1949 if( n
==0 ) return i
;
1952 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
1958 static char emsg
[] = "Command line syntax error: ";
1961 ** Process a flag command line argument.
1963 static int handleflags(int i
, FILE *err
)
1968 for(j
=0; op
[j
].label
; j
++){
1969 if( strncmp(&argv
[i
][1],op
[j
].label
,lemonStrlen(op
[j
].label
))==0 ) break;
1971 v
= argv
[i
][0]=='-' ? 1 : 0;
1972 if( op
[j
].label
==0 ){
1974 fprintf(err
,"%sundefined option.\n",emsg
);
1978 }else if( op
[j
].arg
==0 ){
1979 /* Ignore this option */
1980 }else if( op
[j
].type
==OPT_FLAG
){
1981 *((int*)op
[j
].arg
) = v
;
1982 }else if( op
[j
].type
==OPT_FFLAG
){
1983 (*(void(*)(int))(op
[j
].arg
))(v
);
1984 }else if( op
[j
].type
==OPT_FSTR
){
1985 (*(void(*)(char *))(op
[j
].arg
))(&argv
[i
][2]);
1988 fprintf(err
,"%smissing argument on switch.\n",emsg
);
1997 ** Process a command line switch which has an argument.
1999 static int handleswitch(int i
, FILE *err
)
2007 cp
= strchr(argv
[i
],'=');
2010 for(j
=0; op
[j
].label
; j
++){
2011 if( strcmp(argv
[i
],op
[j
].label
)==0 ) break;
2014 if( op
[j
].label
==0 ){
2016 fprintf(err
,"%sundefined option.\n",emsg
);
2022 switch( op
[j
].type
){
2026 fprintf(err
,"%soption requires an argument.\n",emsg
);
2033 dv
= strtod(cp
,&end
);
2037 "%sillegal character in floating-point argument.\n",emsg
);
2038 errline(i
,(int)((char*)end
-(char*)argv
[i
]),err
);
2045 lv
= strtol(cp
,&end
,0);
2048 fprintf(err
,"%sillegal character in integer argument.\n",emsg
);
2049 errline(i
,(int)((char*)end
-(char*)argv
[i
]),err
);
2059 switch( op
[j
].type
){
2064 *(double*)(op
[j
].arg
) = dv
;
2067 (*(void(*)(double))(op
[j
].arg
))(dv
);
2070 *(int*)(op
[j
].arg
) = lv
;
2073 (*(void(*)(int))(op
[j
].arg
))((int)lv
);
2076 *(char**)(op
[j
].arg
) = sv
;
2079 (*(void(*)(char *))(op
[j
].arg
))(sv
);
2086 int OptInit(char **a
, struct s_options
*o
, FILE *err
)
2092 if( argv
&& *argv
&& op
){
2094 for(i
=1; argv
[i
]; i
++){
2095 if( argv
[i
][0]=='+' || argv
[i
][0]=='-' ){
2096 errcnt
+= handleflags(i
,err
);
2097 }else if( strchr(argv
[i
],'=') ){
2098 errcnt
+= handleswitch(i
,err
);
2103 fprintf(err
,"Valid command line options for \"%s\" are:\n",*a
);
2114 if( argv
!=0 && argv
[0]!=0 ){
2115 for(i
=1; argv
[i
]; i
++){
2116 if( dashdash
|| !ISOPT(argv
[i
]) ) cnt
++;
2117 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
2127 return i
>=0 ? argv
[i
] : 0;
2134 if( i
>=0 ) errline(i
,0,errstream
);
2137 void OptPrint(void){
2141 for(i
=0; op
[i
].label
; i
++){
2142 len
= lemonStrlen(op
[i
].label
) + 1;
2143 switch( op
[i
].type
){
2149 len
+= 9; /* length of "<integer>" */
2153 len
+= 6; /* length of "<real>" */
2157 len
+= 8; /* length of "<string>" */
2160 if( len
>max
) max
= len
;
2162 for(i
=0; op
[i
].label
; i
++){
2163 switch( op
[i
].type
){
2166 fprintf(errstream
," -%-*s %s\n",max
,op
[i
].label
,op
[i
].message
);
2170 fprintf(errstream
," -%s<integer>%*s %s\n",op
[i
].label
,
2171 (int)(max
-lemonStrlen(op
[i
].label
)-9),"",op
[i
].message
);
2175 fprintf(errstream
," -%s<real>%*s %s\n",op
[i
].label
,
2176 (int)(max
-lemonStrlen(op
[i
].label
)-6),"",op
[i
].message
);
2180 fprintf(errstream
," -%s<string>%*s %s\n",op
[i
].label
,
2181 (int)(max
-lemonStrlen(op
[i
].label
)-8),"",op
[i
].message
);
2186 /*********************** From the file "parse.c" ****************************/
2188 ** Input file parser for the LEMON parser generator.
2191 /* The state of the parser */
2194 WAITING_FOR_DECL_OR_RULE
,
2195 WAITING_FOR_DECL_KEYWORD
,
2196 WAITING_FOR_DECL_ARG
,
2197 WAITING_FOR_PRECEDENCE_SYMBOL
,
2207 RESYNC_AFTER_RULE_ERROR
,
2208 RESYNC_AFTER_DECL_ERROR
,
2209 WAITING_FOR_DESTRUCTOR_SYMBOL
,
2210 WAITING_FOR_DATATYPE_SYMBOL
,
2211 WAITING_FOR_FALLBACK_ID
,
2212 WAITING_FOR_WILDCARD_ID
,
2213 WAITING_FOR_CLASS_ID
,
2214 WAITING_FOR_CLASS_TOKEN
,
2215 WAITING_FOR_TOKEN_NAME
2218 char *filename
; /* Name of the input file */
2219 int tokenlineno
; /* Linenumber at which current token starts */
2220 int errorcnt
; /* Number of errors so far */
2221 char *tokenstart
; /* Text of current token */
2222 struct lemon
*gp
; /* Global state vector */
2223 enum e_state state
; /* The state of the parser */
2224 struct symbol
*fallback
; /* The fallback token */
2225 struct symbol
*tkclass
; /* Token class symbol */
2226 struct symbol
*lhs
; /* Left-hand side of current rule */
2227 const char *lhsalias
; /* Alias for the LHS */
2228 int nrhs
; /* Number of right-hand side symbols seen */
2229 struct symbol
*rhs
[MAXRHS
]; /* RHS symbols */
2230 const char *alias
[MAXRHS
]; /* Aliases for each RHS symbol (or NULL) */
2231 struct rule
*prevrule
; /* Previous rule parsed */
2232 const char *declkeyword
; /* Keyword of a declaration */
2233 char **declargslot
; /* Where the declaration argument should be put */
2234 int insertLineMacro
; /* Add #line before declaration insert */
2235 int *decllinenoslot
; /* Where to write declaration line number */
2236 enum e_assoc declassoc
; /* Assign this association to decl arguments */
2237 int preccounter
; /* Assign this precedence to decl arguments */
2238 struct rule
*firstrule
; /* Pointer to first rule in the grammar */
2239 struct rule
*lastrule
; /* Pointer to the most recently parsed rule */
2242 /* Parse a single token */
2243 static void parseonetoken(struct pstate
*psp
)
2246 x
= Strsafe(psp
->tokenstart
); /* Save the token permanently */
2248 printf("%s:%d: Token=[%s] state=%d\n",psp
->filename
,psp
->tokenlineno
,
2251 switch( psp
->state
){
2254 psp
->preccounter
= 0;
2255 psp
->firstrule
= psp
->lastrule
= 0;
2257 /* Fall thru to next case */
2258 case WAITING_FOR_DECL_OR_RULE
:
2260 psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2261 }else if( ISLOWER(x
[0]) ){
2262 psp
->lhs
= Symbol_new(x
);
2265 psp
->state
= WAITING_FOR_ARROW
;
2266 }else if( x
[0]=='{' ){
2267 if( psp
->prevrule
==0 ){
2268 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2269 "There is no prior rule upon which to attach the code \
2270 fragment which begins on this line.");
2272 }else if( psp
->prevrule
->code
!=0 ){
2273 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2274 "Code fragment beginning on this line is not the first \
2275 to follow the previous rule.");
2278 psp
->prevrule
->line
= psp
->tokenlineno
;
2279 psp
->prevrule
->code
= &x
[1];
2280 psp
->prevrule
->noCode
= 0;
2282 }else if( x
[0]=='[' ){
2283 psp
->state
= PRECEDENCE_MARK_1
;
2285 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2286 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2291 case PRECEDENCE_MARK_1
:
2292 if( !ISUPPER(x
[0]) ){
2293 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2294 "The precedence symbol must be a terminal.");
2296 }else if( psp
->prevrule
==0 ){
2297 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2298 "There is no prior rule to assign precedence \"[%s]\".",x
);
2300 }else if( psp
->prevrule
->precsym
!=0 ){
2301 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2302 "Precedence mark on this line is not the first \
2303 to follow the previous rule.");
2306 psp
->prevrule
->precsym
= Symbol_new(x
);
2308 psp
->state
= PRECEDENCE_MARK_2
;
2310 case PRECEDENCE_MARK_2
:
2312 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2313 "Missing \"]\" on precedence mark.");
2316 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2318 case WAITING_FOR_ARROW
:
2319 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2320 psp
->state
= IN_RHS
;
2321 }else if( x
[0]=='(' ){
2322 psp
->state
= LHS_ALIAS_1
;
2324 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2325 "Expected to see a \":\" following the LHS symbol \"%s\".",
2328 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2332 if( ISALPHA(x
[0]) ){
2334 psp
->state
= LHS_ALIAS_2
;
2336 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2337 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2340 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2345 psp
->state
= LHS_ALIAS_3
;
2347 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2348 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2350 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2354 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2355 psp
->state
= IN_RHS
;
2357 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2358 "Missing \"->\" following: \"%s(%s)\".",
2359 psp
->lhs
->name
,psp
->lhsalias
);
2361 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2367 rp
= (struct rule
*)calloc( sizeof(struct rule
) +
2368 sizeof(struct symbol
*)*psp
->nrhs
+ sizeof(char*)*psp
->nrhs
, 1);
2370 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2371 "Can't allocate enough memory for this rule.");
2376 rp
->ruleline
= psp
->tokenlineno
;
2377 rp
->rhs
= (struct symbol
**)&rp
[1];
2378 rp
->rhsalias
= (const char**)&(rp
->rhs
[psp
->nrhs
]);
2379 for(i
=0; i
<psp
->nrhs
; i
++){
2380 rp
->rhs
[i
] = psp
->rhs
[i
];
2381 rp
->rhsalias
[i
] = psp
->alias
[i
];
2382 if( rp
->rhsalias
[i
]!=0 ){ rp
->rhs
[i
]->bContent
= 1; }
2385 rp
->lhsalias
= psp
->lhsalias
;
2386 rp
->nrhs
= psp
->nrhs
;
2390 rp
->index
= psp
->gp
->nrule
++;
2391 rp
->nextlhs
= rp
->lhs
->rule
;
2394 if( psp
->firstrule
==0 ){
2395 psp
->firstrule
= psp
->lastrule
= rp
;
2397 psp
->lastrule
->next
= rp
;
2402 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2403 }else if( ISALPHA(x
[0]) ){
2404 if( psp
->nrhs
>=MAXRHS
){
2405 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2406 "Too many symbols on RHS of rule beginning at \"%s\".",
2409 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2411 psp
->rhs
[psp
->nrhs
] = Symbol_new(x
);
2412 psp
->alias
[psp
->nrhs
] = 0;
2415 }else if( (x
[0]=='|' || x
[0]=='/') && psp
->nrhs
>0 ){
2416 struct symbol
*msp
= psp
->rhs
[psp
->nrhs
-1];
2417 if( msp
->type
!=MULTITERMINAL
){
2418 struct symbol
*origsp
= msp
;
2419 msp
= (struct symbol
*) calloc(1,sizeof(*msp
));
2420 memset(msp
, 0, sizeof(*msp
));
2421 msp
->type
= MULTITERMINAL
;
2423 msp
->subsym
= (struct symbol
**) calloc(1,sizeof(struct symbol
*));
2424 msp
->subsym
[0] = origsp
;
2425 msp
->name
= origsp
->name
;
2426 psp
->rhs
[psp
->nrhs
-1] = msp
;
2429 msp
->subsym
= (struct symbol
**) realloc(msp
->subsym
,
2430 sizeof(struct symbol
*)*msp
->nsubsym
);
2431 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(&x
[1]);
2432 if( ISLOWER(x
[1]) || ISLOWER(msp
->subsym
[0]->name
[0]) ){
2433 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2434 "Cannot form a compound containing a non-terminal");
2437 }else if( x
[0]=='(' && psp
->nrhs
>0 ){
2438 psp
->state
= RHS_ALIAS_1
;
2440 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2441 "Illegal character on RHS of rule: \"%s\".",x
);
2443 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2447 if( ISALPHA(x
[0]) ){
2448 psp
->alias
[psp
->nrhs
-1] = x
;
2449 psp
->state
= RHS_ALIAS_2
;
2451 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2452 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2453 x
,psp
->rhs
[psp
->nrhs
-1]->name
);
2455 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2460 psp
->state
= IN_RHS
;
2462 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2463 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2465 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2468 case WAITING_FOR_DECL_KEYWORD
:
2469 if( ISALPHA(x
[0]) ){
2470 psp
->declkeyword
= x
;
2471 psp
->declargslot
= 0;
2472 psp
->decllinenoslot
= 0;
2473 psp
->insertLineMacro
= 1;
2474 psp
->state
= WAITING_FOR_DECL_ARG
;
2475 if( strcmp(x
,"name")==0 ){
2476 psp
->declargslot
= &(psp
->gp
->name
);
2477 psp
->insertLineMacro
= 0;
2478 }else if( strcmp(x
,"include")==0 ){
2479 psp
->declargslot
= &(psp
->gp
->include
);
2480 }else if( strcmp(x
,"code")==0 ){
2481 psp
->declargslot
= &(psp
->gp
->extracode
);
2482 }else if( strcmp(x
,"token_destructor")==0 ){
2483 psp
->declargslot
= &psp
->gp
->tokendest
;
2484 }else if( strcmp(x
,"default_destructor")==0 ){
2485 psp
->declargslot
= &psp
->gp
->vardest
;
2486 }else if( strcmp(x
,"token_prefix")==0 ){
2487 psp
->declargslot
= &psp
->gp
->tokenprefix
;
2488 psp
->insertLineMacro
= 0;
2489 }else if( strcmp(x
,"syntax_error")==0 ){
2490 psp
->declargslot
= &(psp
->gp
->error
);
2491 }else if( strcmp(x
,"parse_accept")==0 ){
2492 psp
->declargslot
= &(psp
->gp
->accept
);
2493 }else if( strcmp(x
,"parse_failure")==0 ){
2494 psp
->declargslot
= &(psp
->gp
->failure
);
2495 }else if( strcmp(x
,"stack_overflow")==0 ){
2496 psp
->declargslot
= &(psp
->gp
->overflow
);
2497 }else if( strcmp(x
,"extra_argument")==0 ){
2498 psp
->declargslot
= &(psp
->gp
->arg
);
2499 psp
->insertLineMacro
= 0;
2500 }else if( strcmp(x
,"extra_context")==0 ){
2501 psp
->declargslot
= &(psp
->gp
->ctx
);
2502 psp
->insertLineMacro
= 0;
2503 }else if( strcmp(x
,"token_type")==0 ){
2504 psp
->declargslot
= &(psp
->gp
->tokentype
);
2505 psp
->insertLineMacro
= 0;
2506 }else if( strcmp(x
,"default_type")==0 ){
2507 psp
->declargslot
= &(psp
->gp
->vartype
);
2508 psp
->insertLineMacro
= 0;
2509 }else if( strcmp(x
,"stack_size")==0 ){
2510 psp
->declargslot
= &(psp
->gp
->stacksize
);
2511 psp
->insertLineMacro
= 0;
2512 }else if( strcmp(x
,"start_symbol")==0 ){
2513 psp
->declargslot
= &(psp
->gp
->start
);
2514 psp
->insertLineMacro
= 0;
2515 }else if( strcmp(x
,"left")==0 ){
2517 psp
->declassoc
= LEFT
;
2518 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2519 }else if( strcmp(x
,"right")==0 ){
2521 psp
->declassoc
= RIGHT
;
2522 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2523 }else if( strcmp(x
,"nonassoc")==0 ){
2525 psp
->declassoc
= NONE
;
2526 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2527 }else if( strcmp(x
,"destructor")==0 ){
2528 psp
->state
= WAITING_FOR_DESTRUCTOR_SYMBOL
;
2529 }else if( strcmp(x
,"type")==0 ){
2530 psp
->state
= WAITING_FOR_DATATYPE_SYMBOL
;
2531 }else if( strcmp(x
,"fallback")==0 ){
2533 psp
->state
= WAITING_FOR_FALLBACK_ID
;
2534 }else if( strcmp(x
,"token")==0 ){
2535 psp
->state
= WAITING_FOR_TOKEN_NAME
;
2536 }else if( strcmp(x
,"wildcard")==0 ){
2537 psp
->state
= WAITING_FOR_WILDCARD_ID
;
2538 }else if( strcmp(x
,"token_class")==0 ){
2539 psp
->state
= WAITING_FOR_CLASS_ID
;
2541 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2542 "Unknown declaration keyword: \"%%%s\".",x
);
2544 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2547 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2548 "Illegal declaration keyword: \"%s\".",x
);
2550 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2553 case WAITING_FOR_DESTRUCTOR_SYMBOL
:
2554 if( !ISALPHA(x
[0]) ){
2555 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2556 "Symbol name missing after %%destructor keyword");
2558 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2560 struct symbol
*sp
= Symbol_new(x
);
2561 psp
->declargslot
= &sp
->destructor
;
2562 psp
->decllinenoslot
= &sp
->destLineno
;
2563 psp
->insertLineMacro
= 1;
2564 psp
->state
= WAITING_FOR_DECL_ARG
;
2567 case WAITING_FOR_DATATYPE_SYMBOL
:
2568 if( !ISALPHA(x
[0]) ){
2569 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2570 "Symbol name missing after %%type keyword");
2572 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2574 struct symbol
*sp
= Symbol_find(x
);
2575 if((sp
) && (sp
->datatype
)){
2576 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2577 "Symbol %%type \"%s\" already defined", x
);
2579 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2584 psp
->declargslot
= &sp
->datatype
;
2585 psp
->insertLineMacro
= 0;
2586 psp
->state
= WAITING_FOR_DECL_ARG
;
2590 case WAITING_FOR_PRECEDENCE_SYMBOL
:
2592 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2593 }else if( ISUPPER(x
[0]) ){
2597 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2598 "Symbol \"%s\" has already be given a precedence.",x
);
2601 sp
->prec
= psp
->preccounter
;
2602 sp
->assoc
= psp
->declassoc
;
2605 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2606 "Can't assign a precedence to \"%s\".",x
);
2610 case WAITING_FOR_DECL_ARG
:
2611 if( x
[0]=='{' || x
[0]=='\"' || ISALNUM(x
[0]) ){
2612 const char *zOld
, *zNew
;
2614 int nOld
, n
, nLine
= 0, nNew
, nBack
;
2618 if( zNew
[0]=='"' || zNew
[0]=='{' ) zNew
++;
2619 nNew
= lemonStrlen(zNew
);
2620 if( *psp
->declargslot
){
2621 zOld
= *psp
->declargslot
;
2625 nOld
= lemonStrlen(zOld
);
2626 n
= nOld
+ nNew
+ 20;
2627 addLineMacro
= !psp
->gp
->nolinenosflag
&& psp
->insertLineMacro
&&
2628 (psp
->decllinenoslot
==0 || psp
->decllinenoslot
[0]!=0);
2630 for(z
=psp
->filename
, nBack
=0; *z
; z
++){
2631 if( *z
=='\\' ) nBack
++;
2633 lemon_sprintf(zLine
, "#line %d ", psp
->tokenlineno
);
2634 nLine
= lemonStrlen(zLine
);
2635 n
+= nLine
+ lemonStrlen(psp
->filename
) + nBack
;
2637 *psp
->declargslot
= (char *) realloc(*psp
->declargslot
, n
);
2638 zBuf
= *psp
->declargslot
+ nOld
;
2640 if( nOld
&& zBuf
[-1]!='\n' ){
2643 memcpy(zBuf
, zLine
, nLine
);
2646 for(z
=psp
->filename
; *z
; z
++){
2655 if( psp
->decllinenoslot
&& psp
->decllinenoslot
[0]==0 ){
2656 psp
->decllinenoslot
[0] = psp
->tokenlineno
;
2658 memcpy(zBuf
, zNew
, nNew
);
2661 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2663 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2664 "Illegal argument to %%%s: %s",psp
->declkeyword
,x
);
2666 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2669 case WAITING_FOR_FALLBACK_ID
:
2671 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2672 }else if( !ISUPPER(x
[0]) ){
2673 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2674 "%%fallback argument \"%s\" should be a token", x
);
2677 struct symbol
*sp
= Symbol_new(x
);
2678 if( psp
->fallback
==0 ){
2680 }else if( sp
->fallback
){
2681 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2682 "More than one fallback assigned to token %s", x
);
2685 sp
->fallback
= psp
->fallback
;
2686 psp
->gp
->has_fallback
= 1;
2690 case WAITING_FOR_TOKEN_NAME
:
2691 /* Tokens do not have to be declared before use. But they can be
2692 ** in order to control their assigned integer number. The number for
2693 ** each token is assigned when it is first seen. So by including
2695 ** %token ONE TWO THREE
2697 ** early in the grammar file, that assigns small consecutive values
2698 ** to each of the tokens ONE TWO and THREE.
2701 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2702 }else if( !ISUPPER(x
[0]) ){
2703 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2704 "%%token argument \"%s\" should be a token", x
);
2707 (void)Symbol_new(x
);
2710 case WAITING_FOR_WILDCARD_ID
:
2712 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2713 }else if( !ISUPPER(x
[0]) ){
2714 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2715 "%%wildcard argument \"%s\" should be a token", x
);
2718 struct symbol
*sp
= Symbol_new(x
);
2719 if( psp
->gp
->wildcard
==0 ){
2720 psp
->gp
->wildcard
= sp
;
2722 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2723 "Extra wildcard to token: %s", x
);
2728 case WAITING_FOR_CLASS_ID
:
2729 if( !ISLOWER(x
[0]) ){
2730 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2731 "%%token_class must be followed by an identifier: ", x
);
2733 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2734 }else if( Symbol_find(x
) ){
2735 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2736 "Symbol \"%s\" already used", x
);
2738 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2740 psp
->tkclass
= Symbol_new(x
);
2741 psp
->tkclass
->type
= MULTITERMINAL
;
2742 psp
->state
= WAITING_FOR_CLASS_TOKEN
;
2745 case WAITING_FOR_CLASS_TOKEN
:
2747 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2748 }else if( ISUPPER(x
[0]) || ((x
[0]=='|' || x
[0]=='/') && ISUPPER(x
[1])) ){
2749 struct symbol
*msp
= psp
->tkclass
;
2751 msp
->subsym
= (struct symbol
**) realloc(msp
->subsym
,
2752 sizeof(struct symbol
*)*msp
->nsubsym
);
2753 if( !ISUPPER(x
[0]) ) x
++;
2754 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(x
);
2756 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2757 "%%token_class argument \"%s\" should be a token", x
);
2759 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2762 case RESYNC_AFTER_RULE_ERROR
:
2763 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2765 case RESYNC_AFTER_DECL_ERROR
:
2766 if( x
[0]=='.' ) psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2767 if( x
[0]=='%' ) psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2772 /* Run the preprocessor over the input file text. The global variables
2773 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2774 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2775 ** comments them out. Text in between is also commented out as appropriate.
2777 static void preprocess_input(char *z
){
2782 int start_lineno
= 1;
2783 for(i
=0; z
[i
]; i
++){
2784 if( z
[i
]=='\n' ) lineno
++;
2785 if( z
[i
]!='%' || (i
>0 && z
[i
-1]!='\n') ) continue;
2786 if( strncmp(&z
[i
],"%endif",6)==0 && ISSPACE(z
[i
+6]) ){
2790 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
2793 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2794 }else if( (strncmp(&z
[i
],"%ifdef",6)==0 && ISSPACE(z
[i
+6]))
2795 || (strncmp(&z
[i
],"%ifndef",7)==0 && ISSPACE(z
[i
+7])) ){
2799 for(j
=i
+7; ISSPACE(z
[j
]); j
++){}
2800 for(n
=0; z
[j
+n
] && !ISSPACE(z
[j
+n
]); n
++){}
2802 for(k
=0; k
<nDefine
; k
++){
2803 if( strncmp(azDefine
[k
],&z
[j
],n
)==0 && lemonStrlen(azDefine
[k
])==n
){
2808 if( z
[i
+3]=='n' ) exclude
= !exclude
;
2811 start_lineno
= lineno
;
2814 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2818 fprintf(stderr
,"unterminated %%ifdef starting on line %d\n", start_lineno
);
2823 /* In spite of its name, this function is really a scanner. It read
2824 ** in the entire input file (all at once) then tokenizes it. Each
2825 ** token is passed to the function "parseonetoken" which builds all
2826 ** the appropriate data structures in the global state vector "gp".
2828 void Parse(struct lemon
*gp
)
2833 unsigned int filesize
;
2839 memset(&ps
, '\0', sizeof(ps
));
2841 ps
.filename
= gp
->filename
;
2843 ps
.state
= INITIALIZE
;
2845 /* Begin by reading the input file */
2846 fp
= fopen(ps
.filename
,"rb");
2848 ErrorMsg(ps
.filename
,0,"Can't open this file for reading.");
2853 filesize
= ftell(fp
);
2855 filebuf
= (char *)malloc( filesize
+1 );
2856 if( filesize
>100000000 || filebuf
==0 ){
2857 ErrorMsg(ps
.filename
,0,"Input file too large.");
2862 if( fread(filebuf
,1,filesize
,fp
)!=filesize
){
2863 ErrorMsg(ps
.filename
,0,"Can't read in all %d bytes of this file.",
2871 filebuf
[filesize
] = 0;
2873 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2874 preprocess_input(filebuf
);
2876 /* Now scan the text of the input file */
2878 for(cp
=filebuf
; (c
= *cp
)!=0; ){
2879 if( c
=='\n' ) lineno
++; /* Keep track of the line number */
2880 if( ISSPACE(c
) ){ cp
++; continue; } /* Skip all white space */
2881 if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments */
2883 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2886 if( c
=='/' && cp
[1]=='*' ){ /* Skip C style comments */
2888 while( (c
= *cp
)!=0 && (c
!='/' || cp
[-1]!='*') ){
2889 if( c
=='\n' ) lineno
++;
2895 ps
.tokenstart
= cp
; /* Mark the beginning of the token */
2896 ps
.tokenlineno
= lineno
; /* Linenumber on which token begins */
2897 if( c
=='\"' ){ /* String literals */
2899 while( (c
= *cp
)!=0 && c
!='\"' ){
2900 if( c
=='\n' ) lineno
++;
2904 ErrorMsg(ps
.filename
,startline
,
2905 "String starting on this line is not terminated before the end of the file.");
2911 }else if( c
=='{' ){ /* A block of C code */
2914 for(level
=1; (c
= *cp
)!=0 && (level
>1 || c
!='}'); cp
++){
2915 if( c
=='\n' ) lineno
++;
2916 else if( c
=='{' ) level
++;
2917 else if( c
=='}' ) level
--;
2918 else if( c
=='/' && cp
[1]=='*' ){ /* Skip comments */
2922 while( (c
= *cp
)!=0 && (c
!='/' || prevc
!='*') ){
2923 if( c
=='\n' ) lineno
++;
2927 }else if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments too */
2929 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2931 }else if( c
=='\'' || c
=='\"' ){ /* String a character literals */
2932 int startchar
, prevc
;
2935 for(cp
++; (c
= *cp
)!=0 && (c
!=startchar
|| prevc
=='\\'); cp
++){
2936 if( c
=='\n' ) lineno
++;
2937 if( prevc
=='\\' ) prevc
= 0;
2943 ErrorMsg(ps
.filename
,ps
.tokenlineno
,
2944 "C code starting on this line is not terminated before the end of the file.");
2950 }else if( ISALNUM(c
) ){ /* Identifiers */
2951 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
2953 }else if( c
==':' && cp
[1]==':' && cp
[2]=='=' ){ /* The operator "::=" */
2956 }else if( (c
=='/' || c
=='|') && ISALPHA(cp
[1]) ){
2958 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
2960 }else{ /* All other (one character) operators */
2965 *cp
= 0; /* Null terminate the token */
2966 parseonetoken(&ps
); /* Parse the token */
2967 *cp
= (char)c
; /* Restore the buffer */
2970 free(filebuf
); /* Release the buffer after parsing */
2971 gp
->rule
= ps
.firstrule
;
2972 gp
->errorcnt
= ps
.errorcnt
;
2974 /*************************** From the file "plink.c" *********************/
2976 ** Routines processing configuration follow-set propagation links
2977 ** in the LEMON parser generator.
2979 static struct plink
*plink_freelist
= 0;
2981 /* Allocate a new plink */
2982 struct plink
*Plink_new(void){
2983 struct plink
*newlink
;
2985 if( plink_freelist
==0 ){
2988 plink_freelist
= (struct plink
*)calloc( amt
, sizeof(struct plink
) );
2989 if( plink_freelist
==0 ){
2991 "Unable to allocate memory for a new follow-set propagation link.\n");
2994 for(i
=0; i
<amt
-1; i
++) plink_freelist
[i
].next
= &plink_freelist
[i
+1];
2995 plink_freelist
[amt
-1].next
= 0;
2997 newlink
= plink_freelist
;
2998 plink_freelist
= plink_freelist
->next
;
3002 /* Add a plink to a plink list */
3003 void Plink_add(struct plink
**plpp
, struct config
*cfp
)
3005 struct plink
*newlink
;
3006 newlink
= Plink_new();
3007 newlink
->next
= *plpp
;
3012 /* Transfer every plink on the list "from" to the list "to" */
3013 void Plink_copy(struct plink
**to
, struct plink
*from
)
3015 struct plink
*nextpl
;
3017 nextpl
= from
->next
;
3024 /* Delete every plink on the list */
3025 void Plink_delete(struct plink
*plp
)
3027 struct plink
*nextpl
;
3031 plp
->next
= plink_freelist
;
3032 plink_freelist
= plp
;
3036 /*********************** From the file "report.c" **************************/
3038 ** Procedures for generating reports and tables in the LEMON parser generator.
3041 /* Generate a filename with the given suffix. Space to hold the
3042 ** name comes from malloc() and must be freed by the calling
3045 PRIVATE
char *file_makename(struct lemon
*lemp
, const char *suffix
)
3049 char *filename
= lemp
->filename
;
3053 cp
= strrchr(filename
, '/');
3054 if( cp
) filename
= cp
+ 1;
3056 sz
= lemonStrlen(filename
);
3057 sz
+= lemonStrlen(suffix
);
3058 if( outputDir
) sz
+= lemonStrlen(outputDir
) + 1;
3060 name
= (char*)malloc( sz
);
3062 fprintf(stderr
,"Can't allocate space for a filename.\n");
3067 lemon_strcpy(name
, outputDir
);
3068 lemon_strcat(name
, "/");
3070 lemon_strcat(name
,filename
);
3071 cp
= strrchr(name
,'.');
3073 lemon_strcat(name
,suffix
);
3077 /* Open a file with a name based on the name of the input file,
3078 ** but with a different (specified) suffix, and return a pointer
3080 PRIVATE
FILE *file_open(
3087 if( lemp
->outname
) free(lemp
->outname
);
3088 lemp
->outname
= file_makename(lemp
, suffix
);
3089 fp
= fopen(lemp
->outname
,mode
);
3090 if( fp
==0 && *mode
=='w' ){
3091 fprintf(stderr
,"Can't open file \"%s\".\n",lemp
->outname
);
3098 /* Print the text of a rule
3100 void rule_print(FILE *out
, struct rule
*rp
){
3102 fprintf(out
, "%s",rp
->lhs
->name
);
3103 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3104 fprintf(out
," ::=");
3105 for(i
=0; i
<rp
->nrhs
; i
++){
3106 struct symbol
*sp
= rp
->rhs
[i
];
3107 if( sp
->type
==MULTITERMINAL
){
3108 fprintf(out
," %s", sp
->subsym
[0]->name
);
3109 for(j
=1; j
<sp
->nsubsym
; j
++){
3110 fprintf(out
,"|%s", sp
->subsym
[j
]->name
);
3113 fprintf(out
," %s", sp
->name
);
3115 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3119 /* Duplicate the input file without comments and without actions
3121 void Reprint(struct lemon
*lemp
)
3125 int i
, j
, maxlen
, len
, ncolumns
, skip
;
3126 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp
->filename
);
3128 for(i
=0; i
<lemp
->nsymbol
; i
++){
3129 sp
= lemp
->symbols
[i
];
3130 len
= lemonStrlen(sp
->name
);
3131 if( len
>maxlen
) maxlen
= len
;
3133 ncolumns
= 76/(maxlen
+5);
3134 if( ncolumns
<1 ) ncolumns
= 1;
3135 skip
= (lemp
->nsymbol
+ ncolumns
- 1)/ncolumns
;
3136 for(i
=0; i
<skip
; i
++){
3138 for(j
=i
; j
<lemp
->nsymbol
; j
+=skip
){
3139 sp
= lemp
->symbols
[j
];
3140 assert( sp
->index
==j
);
3141 printf(" %3d %-*.*s",j
,maxlen
,maxlen
,sp
->name
);
3145 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3146 rule_print(stdout
, rp
);
3148 if( rp
->precsym
) printf(" [%s]",rp
->precsym
->name
);
3149 /* if( rp->code ) printf("\n %s",rp->code); */
3154 /* Print a single rule.
3156 void RulePrint(FILE *fp
, struct rule
*rp
, int iCursor
){
3159 fprintf(fp
,"%s ::=",rp
->lhs
->name
);
3160 for(i
=0; i
<=rp
->nrhs
; i
++){
3161 if( i
==iCursor
) fprintf(fp
," *");
3162 if( i
==rp
->nrhs
) break;
3164 if( sp
->type
==MULTITERMINAL
){
3165 fprintf(fp
," %s", sp
->subsym
[0]->name
);
3166 for(j
=1; j
<sp
->nsubsym
; j
++){
3167 fprintf(fp
,"|%s",sp
->subsym
[j
]->name
);
3170 fprintf(fp
," %s", sp
->name
);
3175 /* Print the rule for a configuration.
3177 void ConfigPrint(FILE *fp
, struct config
*cfp
){
3178 RulePrint(fp
, cfp
->rp
, cfp
->dot
);
3184 PRIVATE
void SetPrint(out
,set
,lemp
)
3192 fprintf(out
,"%12s[","");
3193 for(i
=0; i
<lemp
->nterminal
; i
++){
3194 if( SetFind(set
,i
) ){
3195 fprintf(out
,"%s%s",spacer
,lemp
->symbols
[i
]->name
);
3202 /* Print a plink chain */
3203 PRIVATE
void PlinkPrint(out
,plp
,tag
)
3209 fprintf(out
,"%12s%s (state %2d) ","",tag
,plp
->cfp
->stp
->statenum
);
3210 ConfigPrint(out
,plp
->cfp
);
3217 /* Print an action to the given file descriptor. Return FALSE if
3218 ** nothing was actually printed.
3221 struct action
*ap
, /* The action to print */
3222 FILE *fp
, /* Print the action here */
3223 int indent
/* Indent by this amount */
3228 struct state
*stp
= ap
->x
.stp
;
3229 fprintf(fp
,"%*s shift %-7d",indent
,ap
->sp
->name
,stp
->statenum
);
3233 struct rule
*rp
= ap
->x
.rp
;
3234 fprintf(fp
,"%*s reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3235 RulePrint(fp
, rp
, -1);
3239 struct rule
*rp
= ap
->x
.rp
;
3240 fprintf(fp
,"%*s shift-reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3241 RulePrint(fp
, rp
, -1);
3245 fprintf(fp
,"%*s accept",indent
,ap
->sp
->name
);
3248 fprintf(fp
,"%*s error",indent
,ap
->sp
->name
);
3252 fprintf(fp
,"%*s reduce %-7d ** Parsing conflict **",
3253 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3256 fprintf(fp
,"%*s shift %-7d ** Parsing conflict **",
3257 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3260 if( showPrecedenceConflict
){
3261 fprintf(fp
,"%*s shift %-7d -- dropped by precedence",
3262 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3268 if( showPrecedenceConflict
){
3269 fprintf(fp
,"%*s reduce %-7d -- dropped by precedence",
3270 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3279 if( result
&& ap
->spOpt
){
3280 fprintf(fp
," /* because %s==%s */", ap
->sp
->name
, ap
->spOpt
->name
);
3285 /* Generate the "*.out" log file */
3286 void ReportOutput(struct lemon
*lemp
)
3295 fp
= file_open(lemp
,".out","wb");
3297 for(i
=0; i
<lemp
->nxstate
; i
++){
3298 stp
= lemp
->sorted
[i
];
3299 fprintf(fp
,"State %d:\n",stp
->statenum
);
3300 if( lemp
->basisflag
) cfp
=stp
->bp
;
3304 if( cfp
->dot
==cfp
->rp
->nrhs
){
3305 lemon_sprintf(buf
,"(%d)",cfp
->rp
->iRule
);
3306 fprintf(fp
," %5s ",buf
);
3310 ConfigPrint(fp
,cfp
);
3313 SetPrint(fp
,cfp
->fws
,lemp
);
3314 PlinkPrint(fp
,cfp
->fplp
,"To ");
3315 PlinkPrint(fp
,cfp
->bplp
,"From");
3317 if( lemp
->basisflag
) cfp
=cfp
->bp
;
3321 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3322 if( PrintAction(ap
,fp
,30) ) fprintf(fp
,"\n");
3326 fprintf(fp
, "----------------------------------------------------\n");
3327 fprintf(fp
, "Symbols:\n");
3328 fprintf(fp
, "The first-set of non-terminals is shown after the name.\n\n");
3329 for(i
=0; i
<lemp
->nsymbol
; i
++){
3333 sp
= lemp
->symbols
[i
];
3334 fprintf(fp
, " %3d: %s", i
, sp
->name
);
3335 if( sp
->type
==NONTERMINAL
){
3338 fprintf(fp
, " <lambda>");
3340 for(j
=0; j
<lemp
->nterminal
; j
++){
3341 if( sp
->firstset
&& SetFind(sp
->firstset
, j
) ){
3342 fprintf(fp
, " %s", lemp
->symbols
[j
]->name
);
3346 if( sp
->prec
>=0 ) fprintf(fp
," (precedence=%d)", sp
->prec
);
3349 fprintf(fp
, "----------------------------------------------------\n");
3350 fprintf(fp
, "Syntax-only Symbols:\n");
3351 fprintf(fp
, "The following symbols never carry semantic content.\n\n");
3352 for(i
=n
=0; i
<lemp
->nsymbol
; i
++){
3354 struct symbol
*sp
= lemp
->symbols
[i
];
3355 if( sp
->bContent
) continue;
3356 w
= (int)strlen(sp
->name
);
3357 if( n
>0 && n
+w
>75 ){
3365 fprintf(fp
, "%s", sp
->name
);
3368 if( n
>0 ) fprintf(fp
, "\n");
3369 fprintf(fp
, "----------------------------------------------------\n");
3370 fprintf(fp
, "Rules:\n");
3371 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3372 fprintf(fp
, "%4d: ", rp
->iRule
);
3376 fprintf(fp
," [%s precedence=%d]",
3377 rp
->precsym
->name
, rp
->precsym
->prec
);
3385 /* Search for the file "name" which is in the same directory as
3386 ** the exacutable */
3387 PRIVATE
char *pathsearch(char *argv0
, char *name
, int modemask
)
3389 const char *pathlist
;
3396 cp
= strrchr(argv0
,'\\');
3398 cp
= strrchr(argv0
,'/');
3403 path
= (char *)malloc( lemonStrlen(argv0
) + lemonStrlen(name
) + 2 );
3404 if( path
) lemon_sprintf(path
,"%s/%s",argv0
,name
);
3407 pathlist
= getenv("PATH");
3408 if( pathlist
==0 ) pathlist
= ".:/bin:/usr/bin";
3409 pathbuf
= (char *) malloc( lemonStrlen(pathlist
) + 1 );
3410 path
= (char *)malloc( lemonStrlen(pathlist
)+lemonStrlen(name
)+2 );
3411 if( (pathbuf
!= 0) && (path
!=0) ){
3412 pathbufptr
= pathbuf
;
3413 lemon_strcpy(pathbuf
, pathlist
);
3415 cp
= strchr(pathbuf
,':');
3416 if( cp
==0 ) cp
= &pathbuf
[lemonStrlen(pathbuf
)];
3419 lemon_sprintf(path
,"%s/%s",pathbuf
,name
);
3421 if( c
==0 ) pathbuf
[0] = 0;
3422 else pathbuf
= &cp
[1];
3423 if( access(path
,modemask
)==0 ) break;
3431 /* Given an action, compute the integer value for that action
3432 ** which is to be put in the action table of the generated machine.
3433 ** Return negative if no action should be generated.
3435 PRIVATE
int compute_action(struct lemon
*lemp
, struct action
*ap
)
3439 case SHIFT
: act
= ap
->x
.stp
->statenum
; break;
3441 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3442 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3443 ** REDUCE action: */
3444 if( ap
->sp
->index
>=lemp
->nterminal
){
3445 act
= lemp
->minReduce
+ ap
->x
.rp
->iRule
;
3447 act
= lemp
->minShiftReduce
+ ap
->x
.rp
->iRule
;
3451 case REDUCE
: act
= lemp
->minReduce
+ ap
->x
.rp
->iRule
; break;
3452 case ERROR
: act
= lemp
->errAction
; break;
3453 case ACCEPT
: act
= lemp
->accAction
; break;
3454 default: act
= -1; break;
3459 #define LINESIZE 1000
3460 /* The next cluster of routines are for reading the template file
3461 ** and writing the results to the generated parser */
3462 /* The first function transfers data from "in" to "out" until
3463 ** a line is seen which begins with "%%". The line number is
3466 ** if name!=0, then any word that begin with "Parse" is changed to
3467 ** begin with *name instead.
3469 PRIVATE
void tplt_xfer(char *name
, FILE *in
, FILE *out
, int *lineno
)
3472 char line
[LINESIZE
];
3473 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3477 for(i
=0; line
[i
]; i
++){
3478 if( line
[i
]=='P' && strncmp(&line
[i
],"Parse",5)==0
3479 && (i
==0 || !ISALPHA(line
[i
-1]))
3481 if( i
>iStart
) fprintf(out
,"%.*s",i
-iStart
,&line
[iStart
]);
3482 fprintf(out
,"%s",name
);
3488 fprintf(out
,"%s",&line
[iStart
]);
3492 /* The next function finds the template file and opens it, returning
3493 ** a pointer to the opened file. */
3494 PRIVATE
FILE *tplt_open(struct lemon
*lemp
)
3496 static char templatename
[] = "lempar.c";
3502 /* first, see if user specified a template filename on the command line. */
3503 if (user_templatename
!= 0) {
3504 if( access(user_templatename
,004)==-1 ){
3505 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3510 in
= fopen(user_templatename
,"rb");
3512 fprintf(stderr
,"Can't open the template file \"%s\".\n",
3520 cp
= strrchr(lemp
->filename
,'.');
3522 lemon_sprintf(buf
,"%.*s.lt",(int)(cp
-lemp
->filename
),lemp
->filename
);
3524 lemon_sprintf(buf
,"%s.lt",lemp
->filename
);
3526 if( access(buf
,004)==0 ){
3528 }else if( access(templatename
,004)==0 ){
3529 tpltname
= templatename
;
3531 tpltname
= pathsearch(lemp
->argv0
,templatename
,0);
3534 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3539 in
= fopen(tpltname
,"rb");
3541 fprintf(stderr
,"Can't open the template file \"%s\".\n",templatename
);
3548 /* Print a #line directive line to the output file. */
3549 PRIVATE
void tplt_linedir(FILE *out
, int lineno
, char *filename
)
3551 fprintf(out
,"#line %d \"",lineno
);
3553 if( *filename
== '\\' ) putc('\\',out
);
3554 putc(*filename
,out
);
3557 fprintf(out
,"\"\n");
3560 /* Print a string to the file and keep the linenumber up to date */
3561 PRIVATE
void tplt_print(FILE *out
, struct lemon
*lemp
, char *str
, int *lineno
)
3563 if( str
==0 ) return;
3566 if( *str
=='\n' ) (*lineno
)++;
3569 if( str
[-1]!='\n' ){
3573 if (!lemp
->nolinenosflag
) {
3574 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3580 ** The following routine emits code for the destructor for the
3583 void emit_destructor_code(
3591 if( sp
->type
==TERMINAL
){
3592 cp
= lemp
->tokendest
;
3594 fprintf(out
,"{\n"); (*lineno
)++;
3595 }else if( sp
->destructor
){
3596 cp
= sp
->destructor
;
3597 fprintf(out
,"{\n"); (*lineno
)++;
3598 if( !lemp
->nolinenosflag
){
3600 tplt_linedir(out
,sp
->destLineno
,lemp
->filename
);
3602 }else if( lemp
->vardest
){
3605 fprintf(out
,"{\n"); (*lineno
)++;
3607 assert( 0 ); /* Cannot happen */
3610 if( *cp
=='$' && cp
[1]=='$' ){
3611 fprintf(out
,"(yypminor->yy%d)",sp
->dtnum
);
3615 if( *cp
=='\n' ) (*lineno
)++;
3618 fprintf(out
,"\n"); (*lineno
)++;
3619 if (!lemp
->nolinenosflag
) {
3620 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3622 fprintf(out
,"}\n"); (*lineno
)++;
3627 ** Return TRUE (non-zero) if the given symbol has a destructor.
3629 int has_destructor(struct symbol
*sp
, struct lemon
*lemp
)
3632 if( sp
->type
==TERMINAL
){
3633 ret
= lemp
->tokendest
!=0;
3635 ret
= lemp
->vardest
!=0 || sp
->destructor
!=0;
3641 ** Append text to a dynamically allocated string. If zText is 0 then
3642 ** reset the string to be empty again. Always return the complete text
3643 ** of the string (which is overwritten with each call).
3645 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3646 ** \000 terminator is stored. zText can contain up to two instances of
3647 ** %d. The values of p1 and p2 are written into the first and second
3650 ** If n==-1, then the previous character is overwritten.
3652 PRIVATE
char *append_str(const char *zText
, int n
, int p1
, int p2
){
3653 static char empty
[1] = { 0 };
3655 static int alloced
= 0;
3656 static int used
= 0;
3660 if( used
==0 && z
!=0 ) z
[0] = 0;
3669 n
= lemonStrlen(zText
);
3671 if( (int) (n
+sizeof(zInt
)*2+used
) >= alloced
){
3672 alloced
= n
+ sizeof(zInt
)*2 + used
+ 200;
3673 z
= (char *) realloc(z
, alloced
);
3675 if( z
==0 ) return empty
;
3678 if( c
=='%' && n
>0 && zText
[0]=='d' ){
3679 lemon_sprintf(zInt
, "%d", p1
);
3681 lemon_strcpy(&z
[used
], zInt
);
3682 used
+= lemonStrlen(&z
[used
]);
3686 z
[used
++] = (char)c
;
3694 ** Write and transform the rp->code string so that symbols are expanded.
3695 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3697 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3700 PRIVATE
int translate_code(struct lemon
*lemp
, struct rule
*rp
){
3703 int rc
= 0; /* True if yylhsminor is used */
3704 int dontUseRhs0
= 0; /* If true, use of left-most RHS label is illegal */
3705 const char *zSkip
= 0; /* The zOvwrt comment within rp->code, or NULL */
3706 char lhsused
= 0; /* True if the LHS element has been used */
3707 char lhsdirect
; /* True if LHS writes directly into stack */
3708 char used
[MAXRHS
]; /* True for each RHS element which is used */
3709 char zLhs
[50]; /* Convert the LHS symbol into this string */
3710 char zOvwrt
[900]; /* Comment that to allow LHS to overwrite RHS */
3712 for(i
=0; i
<rp
->nrhs
; i
++) used
[i
] = 0;
3716 static char newlinestr
[2] = { '\n', '\0' };
3717 rp
->code
= newlinestr
;
3718 rp
->line
= rp
->ruleline
;
3726 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3728 }else if( rp
->rhsalias
[0]==0 ){
3729 /* The left-most RHS symbol has no value. LHS direct is ok. But
3730 ** we have to call the distructor on the RHS symbol first. */
3732 if( has_destructor(rp
->rhs
[0],lemp
) ){
3733 append_str(0,0,0,0);
3734 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3735 rp
->rhs
[0]->index
,1-rp
->nrhs
);
3736 rp
->codePrefix
= Strsafe(append_str(0,0,0,0));
3739 }else if( rp
->lhsalias
==0 ){
3740 /* There is no LHS value symbol. */
3742 }else if( strcmp(rp
->lhsalias
,rp
->rhsalias
[0])==0 ){
3743 /* The LHS symbol and the left-most RHS symbol are the same, so
3744 ** direct writing is allowed */
3748 if( rp
->lhs
->dtnum
!=rp
->rhs
[0]->dtnum
){
3749 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3750 "%s(%s) and %s(%s) share the same label but have "
3751 "different datatypes.",
3752 rp
->lhs
->name
, rp
->lhsalias
, rp
->rhs
[0]->name
, rp
->rhsalias
[0]);
3756 lemon_sprintf(zOvwrt
, "/*%s-overwrites-%s*/",
3757 rp
->lhsalias
, rp
->rhsalias
[0]);
3758 zSkip
= strstr(rp
->code
, zOvwrt
);
3760 /* The code contains a special comment that indicates that it is safe
3761 ** for the LHS label to overwrite left-most RHS label. */
3768 sprintf(zLhs
, "yymsp[%d].minor.yy%d",1-rp
->nrhs
,rp
->lhs
->dtnum
);
3771 sprintf(zLhs
, "yylhsminor.yy%d",rp
->lhs
->dtnum
);
3774 append_str(0,0,0,0);
3776 /* This const cast is wrong but harmless, if we're careful. */
3777 for(cp
=(char *)rp
->code
; *cp
; cp
++){
3779 append_str(zOvwrt
,0,0,0);
3780 cp
+= lemonStrlen(zOvwrt
)-1;
3784 if( ISALPHA(*cp
) && (cp
==rp
->code
|| (!ISALNUM(cp
[-1]) && cp
[-1]!='_')) ){
3786 for(xp
= &cp
[1]; ISALNUM(*xp
) || *xp
=='_'; xp
++);
3789 if( rp
->lhsalias
&& strcmp(cp
,rp
->lhsalias
)==0 ){
3790 append_str(zLhs
,0,0,0);
3794 for(i
=0; i
<rp
->nrhs
; i
++){
3795 if( rp
->rhsalias
[i
] && strcmp(cp
,rp
->rhsalias
[i
])==0 ){
3796 if( i
==0 && dontUseRhs0
){
3797 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3798 "Label %s used after '%s'.",
3799 rp
->rhsalias
[0], zOvwrt
);
3801 }else if( cp
!=rp
->code
&& cp
[-1]=='@' ){
3802 /* If the argument is of the form @X then substituted
3803 ** the token number of X, not the value of X */
3804 append_str("yymsp[%d].major",-1,i
-rp
->nrhs
+1,0);
3806 struct symbol
*sp
= rp
->rhs
[i
];
3808 if( sp
->type
==MULTITERMINAL
){
3809 dtnum
= sp
->subsym
[0]->dtnum
;
3813 append_str("yymsp[%d].minor.yy%d",0,i
-rp
->nrhs
+1, dtnum
);
3823 append_str(cp
, 1, 0, 0);
3826 /* Main code generation completed */
3827 cp
= append_str(0,0,0,0);
3828 if( cp
&& cp
[0] ) rp
->code
= Strsafe(cp
);
3829 append_str(0,0,0,0);
3831 /* Check to make sure the LHS has been used */
3832 if( rp
->lhsalias
&& !lhsused
){
3833 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3834 "Label \"%s\" for \"%s(%s)\" is never used.",
3835 rp
->lhsalias
,rp
->lhs
->name
,rp
->lhsalias
);
3839 /* Generate destructor code for RHS minor values which are not referenced.
3840 ** Generate error messages for unused labels and duplicate labels.
3842 for(i
=0; i
<rp
->nrhs
; i
++){
3843 if( rp
->rhsalias
[i
] ){
3846 if( rp
->lhsalias
&& strcmp(rp
->lhsalias
,rp
->rhsalias
[i
])==0 ){
3847 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3848 "%s(%s) has the same label as the LHS but is not the left-most "
3849 "symbol on the RHS.",
3850 rp
->rhs
[i
]->name
, rp
->rhsalias
);
3854 if( rp
->rhsalias
[j
] && strcmp(rp
->rhsalias
[j
],rp
->rhsalias
[i
])==0 ){
3855 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3856 "Label %s used for multiple symbols on the RHS of a rule.",
3864 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3865 "Label %s for \"%s(%s)\" is never used.",
3866 rp
->rhsalias
[i
],rp
->rhs
[i
]->name
,rp
->rhsalias
[i
]);
3869 }else if( i
>0 && has_destructor(rp
->rhs
[i
],lemp
) ){
3870 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3871 rp
->rhs
[i
]->index
,i
-rp
->nrhs
+1);
3875 /* If unable to write LHS values directly into the stack, write the
3876 ** saved LHS value now. */
3878 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp
->nrhs
, rp
->lhs
->dtnum
);
3879 append_str(zLhs
, 0, 0, 0);
3880 append_str(";\n", 0, 0, 0);
3883 /* Suffix code generation complete */
3884 cp
= append_str(0,0,0,0);
3886 rp
->codeSuffix
= Strsafe(cp
);
3894 ** Generate code which executes when the rule "rp" is reduced. Write
3895 ** the code to "out". Make sure lineno stays up-to-date.
3897 PRIVATE
void emit_code(
3905 /* Setup code prior to the #line directive */
3906 if( rp
->codePrefix
&& rp
->codePrefix
[0] ){
3907 fprintf(out
, "{%s", rp
->codePrefix
);
3908 for(cp
=rp
->codePrefix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
3911 /* Generate code to do the reduce action */
3913 if( !lemp
->nolinenosflag
){
3915 tplt_linedir(out
,rp
->line
,lemp
->filename
);
3917 fprintf(out
,"{%s",rp
->code
);
3918 for(cp
=rp
->code
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
3919 fprintf(out
,"}\n"); (*lineno
)++;
3920 if( !lemp
->nolinenosflag
){
3922 tplt_linedir(out
,*lineno
,lemp
->outname
);
3926 /* Generate breakdown code that occurs after the #line directive */
3927 if( rp
->codeSuffix
&& rp
->codeSuffix
[0] ){
3928 fprintf(out
, "%s", rp
->codeSuffix
);
3929 for(cp
=rp
->codeSuffix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
3932 if( rp
->codePrefix
){
3933 fprintf(out
, "}\n"); (*lineno
)++;
3940 ** Print the definition of the union used for the parser's data stack.
3941 ** This union contains fields for every possible data type for tokens
3942 ** and nonterminals. In the process of computing and printing this
3943 ** union, also set the ".dtnum" field of every terminal and nonterminal
3946 void print_stack_union(
3947 FILE *out
, /* The output stream */
3948 struct lemon
*lemp
, /* The main info structure for this parser */
3949 int *plineno
, /* Pointer to the line number */
3950 int mhflag
/* True if generating makeheaders output */
3952 int lineno
= *plineno
; /* The line number of the output */
3953 char **types
; /* A hash table of datatypes */
3954 int arraysize
; /* Size of the "types" array */
3955 int maxdtlength
; /* Maximum length of any ".datatype" field. */
3956 char *stddt
; /* Standardized name for a datatype */
3957 int i
,j
; /* Loop counters */
3958 unsigned hash
; /* For hashing the name of a type */
3959 const char *name
; /* Name of the parser */
3961 /* Allocate and initialize types[] and allocate stddt[] */
3962 arraysize
= lemp
->nsymbol
* 2;
3963 types
= (char**)calloc( arraysize
, sizeof(char*) );
3965 fprintf(stderr
,"Out of memory.\n");
3968 for(i
=0; i
<arraysize
; i
++) types
[i
] = 0;
3970 if( lemp
->vartype
){
3971 maxdtlength
= lemonStrlen(lemp
->vartype
);
3973 for(i
=0; i
<lemp
->nsymbol
; i
++){
3975 struct symbol
*sp
= lemp
->symbols
[i
];
3976 if( sp
->datatype
==0 ) continue;
3977 len
= lemonStrlen(sp
->datatype
);
3978 if( len
>maxdtlength
) maxdtlength
= len
;
3980 stddt
= (char*)malloc( maxdtlength
*2 + 1 );
3982 fprintf(stderr
,"Out of memory.\n");
3986 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3987 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3988 ** used for terminal symbols. If there is no %default_type defined then
3989 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3990 ** a datatype using the %type directive.
3992 for(i
=0; i
<lemp
->nsymbol
; i
++){
3993 struct symbol
*sp
= lemp
->symbols
[i
];
3995 if( sp
==lemp
->errsym
){
3996 sp
->dtnum
= arraysize
+1;
3999 if( sp
->type
!=NONTERMINAL
|| (sp
->datatype
==0 && lemp
->vartype
==0) ){
4004 if( cp
==0 ) cp
= lemp
->vartype
;
4006 while( ISSPACE(*cp
) ) cp
++;
4007 while( *cp
) stddt
[j
++] = *cp
++;
4008 while( j
>0 && ISSPACE(stddt
[j
-1]) ) j
--;
4010 if( lemp
->tokentype
&& strcmp(stddt
, lemp
->tokentype
)==0 ){
4015 for(j
=0; stddt
[j
]; j
++){
4016 hash
= hash
*53 + stddt
[j
];
4018 hash
= (hash
& 0x7fffffff)%arraysize
;
4019 while( types
[hash
] ){
4020 if( strcmp(types
[hash
],stddt
)==0 ){
4021 sp
->dtnum
= hash
+ 1;
4025 if( hash
>=(unsigned)arraysize
) hash
= 0;
4027 if( types
[hash
]==0 ){
4028 sp
->dtnum
= hash
+ 1;
4029 types
[hash
] = (char*)malloc( lemonStrlen(stddt
)+1 );
4030 if( types
[hash
]==0 ){
4031 fprintf(stderr
,"Out of memory.\n");
4034 lemon_strcpy(types
[hash
],stddt
);
4038 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4039 name
= lemp
->name
? lemp
->name
: "Parse";
4041 if( mhflag
){ fprintf(out
,"#if INTERFACE\n"); lineno
++; }
4042 fprintf(out
,"#define %sTOKENTYPE %s\n",name
,
4043 lemp
->tokentype
?lemp
->tokentype
:"void*"); lineno
++;
4044 if( mhflag
){ fprintf(out
,"#endif\n"); lineno
++; }
4045 fprintf(out
,"typedef union {\n"); lineno
++;
4046 fprintf(out
," int yyinit;\n"); lineno
++;
4047 fprintf(out
," %sTOKENTYPE yy0;\n",name
); lineno
++;
4048 for(i
=0; i
<arraysize
; i
++){
4049 if( types
[i
]==0 ) continue;
4050 fprintf(out
," %s yy%d;\n",types
[i
],i
+1); lineno
++;
4053 if( lemp
->errsym
&& lemp
->errsym
->useCnt
){
4054 fprintf(out
," int yy%d;\n",lemp
->errsym
->dtnum
); lineno
++;
4058 fprintf(out
,"} YYMINORTYPE;\n"); lineno
++;
4063 ** Return the name of a C datatype able to represent values between
4064 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4065 ** for that type (1, 2, or 4) into *pnByte.
4067 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
){
4068 const char *zType
= "int";
4072 zType
= "unsigned char";
4074 }else if( upr
<65535 ){
4075 zType
= "unsigned short int";
4078 zType
= "unsigned int";
4081 }else if( lwr
>=-127 && upr
<=127 ){
4082 zType
= "signed char";
4084 }else if( lwr
>=-32767 && upr
<32767 ){
4088 if( pnByte
) *pnByte
= nByte
;
4093 ** Each state contains a set of token transaction and a set of
4094 ** nonterminal transactions. Each of these sets makes an instance
4095 ** of the following structure. An array of these structures is used
4096 ** to order the creation of entries in the yy_action[] table.
4099 struct state
*stp
; /* A pointer to a state */
4100 int isTkn
; /* True to use tokens. False for non-terminals */
4101 int nAction
; /* Number of actions */
4102 int iOrder
; /* Original order of action sets */
4106 ** Compare to axset structures for sorting purposes
4108 static int axset_compare(const void *a
, const void *b
){
4109 struct axset
*p1
= (struct axset
*)a
;
4110 struct axset
*p2
= (struct axset
*)b
;
4112 c
= p2
->nAction
- p1
->nAction
;
4114 c
= p1
->iOrder
- p2
->iOrder
;
4116 assert( c
!=0 || p1
==p2
);
4121 ** Write text on "out" that describes the rule "rp".
4123 static void writeRuleText(FILE *out
, struct rule
*rp
){
4125 fprintf(out
,"%s ::=", rp
->lhs
->name
);
4126 for(j
=0; j
<rp
->nrhs
; j
++){
4127 struct symbol
*sp
= rp
->rhs
[j
];
4128 if( sp
->type
!=MULTITERMINAL
){
4129 fprintf(out
," %s", sp
->name
);
4132 fprintf(out
," %s", sp
->subsym
[0]->name
);
4133 for(k
=1; k
<sp
->nsubsym
; k
++){
4134 fprintf(out
,"|%s",sp
->subsym
[k
]->name
);
4141 /* Generate C source code for the parser */
4144 int mhflag
/* Output in makeheaders format if true */
4147 char line
[LINESIZE
];
4152 struct acttab
*pActtab
;
4154 int szActionType
; /* sizeof(YYACTIONTYPE) */
4155 int szCodeType
; /* sizeof(YYCODETYPE) */
4157 int mnTknOfst
, mxTknOfst
;
4158 int mnNtOfst
, mxNtOfst
;
4161 lemp
->minShiftReduce
= lemp
->nstate
;
4162 lemp
->errAction
= lemp
->minShiftReduce
+ lemp
->nrule
;
4163 lemp
->accAction
= lemp
->errAction
+ 1;
4164 lemp
->noAction
= lemp
->accAction
+ 1;
4165 lemp
->minReduce
= lemp
->noAction
+ 1;
4166 lemp
->maxAction
= lemp
->minReduce
+ lemp
->nrule
;
4168 in
= tplt_open(lemp
);
4170 out
= file_open(lemp
,".c","wb");
4176 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4178 /* Generate the include code, if any */
4179 tplt_print(out
,lemp
,lemp
->include
,&lineno
);
4181 char *incName
= file_makename(lemp
, ".h");
4182 fprintf(out
,"#include \"%s\"\n", incName
); lineno
++;
4185 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4187 /* Generate #defines for all tokens */
4190 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4191 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4193 for(i
=1; i
<lemp
->nterminal
; i
++){
4194 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4197 fprintf(out
,"#endif\n"); lineno
++;
4199 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4201 /* Generate the defines */
4202 fprintf(out
,"#define YYCODETYPE %s\n",
4203 minimum_size_type(0, lemp
->nsymbol
, &szCodeType
)); lineno
++;
4204 fprintf(out
,"#define YYNOCODE %d\n",lemp
->nsymbol
); lineno
++;
4205 fprintf(out
,"#define YYACTIONTYPE %s\n",
4206 minimum_size_type(0,lemp
->maxAction
,&szActionType
)); lineno
++;
4207 if( lemp
->wildcard
){
4208 fprintf(out
,"#define YYWILDCARD %d\n",
4209 lemp
->wildcard
->index
); lineno
++;
4211 print_stack_union(out
,lemp
,&lineno
,mhflag
);
4212 fprintf(out
, "#ifndef YYSTACKDEPTH\n"); lineno
++;
4213 if( lemp
->stacksize
){
4214 fprintf(out
,"#define YYSTACKDEPTH %s\n",lemp
->stacksize
); lineno
++;
4216 fprintf(out
,"#define YYSTACKDEPTH 100\n"); lineno
++;
4218 fprintf(out
, "#endif\n"); lineno
++;
4220 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4222 name
= lemp
->name
? lemp
->name
: "Parse";
4223 if( lemp
->arg
&& lemp
->arg
[0] ){
4224 i
= lemonStrlen(lemp
->arg
);
4225 while( i
>=1 && ISSPACE(lemp
->arg
[i
-1]) ) i
--;
4226 while( i
>=1 && (ISALNUM(lemp
->arg
[i
-1]) || lemp
->arg
[i
-1]=='_') ) i
--;
4227 fprintf(out
,"#define %sARG_SDECL %s;\n",name
,lemp
->arg
); lineno
++;
4228 fprintf(out
,"#define %sARG_PDECL ,%s\n",name
,lemp
->arg
); lineno
++;
4229 fprintf(out
,"#define %sARG_PARAM ,%s\n",name
,&lemp
->arg
[i
]); lineno
++;
4230 fprintf(out
,"#define %sARG_FETCH %s=yypParser->%s;\n",
4231 name
,lemp
->arg
,&lemp
->arg
[i
]); lineno
++;
4232 fprintf(out
,"#define %sARG_STORE yypParser->%s=%s;\n",
4233 name
,&lemp
->arg
[i
],&lemp
->arg
[i
]); lineno
++;
4235 fprintf(out
,"#define %sARG_SDECL\n",name
); lineno
++;
4236 fprintf(out
,"#define %sARG_PDECL\n",name
); lineno
++;
4237 fprintf(out
,"#define %sARG_PARAM\n",name
); lineno
++;
4238 fprintf(out
,"#define %sARG_FETCH\n",name
); lineno
++;
4239 fprintf(out
,"#define %sARG_STORE\n",name
); lineno
++;
4241 if( lemp
->ctx
&& lemp
->ctx
[0] ){
4242 i
= lemonStrlen(lemp
->ctx
);
4243 while( i
>=1 && ISSPACE(lemp
->ctx
[i
-1]) ) i
--;
4244 while( i
>=1 && (ISALNUM(lemp
->ctx
[i
-1]) || lemp
->ctx
[i
-1]=='_') ) i
--;
4245 fprintf(out
,"#define %sCTX_SDECL %s;\n",name
,lemp
->ctx
); lineno
++;
4246 fprintf(out
,"#define %sCTX_PDECL ,%s\n",name
,lemp
->ctx
); lineno
++;
4247 fprintf(out
,"#define %sCTX_PARAM ,%s\n",name
,&lemp
->ctx
[i
]); lineno
++;
4248 fprintf(out
,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4249 name
,lemp
->ctx
,&lemp
->ctx
[i
]); lineno
++;
4250 fprintf(out
,"#define %sCTX_STORE yypParser->%s=%s;\n",
4251 name
,&lemp
->ctx
[i
],&lemp
->ctx
[i
]); lineno
++;
4253 fprintf(out
,"#define %sCTX_SDECL\n",name
); lineno
++;
4254 fprintf(out
,"#define %sCTX_PDECL\n",name
); lineno
++;
4255 fprintf(out
,"#define %sCTX_PARAM\n",name
); lineno
++;
4256 fprintf(out
,"#define %sCTX_FETCH\n",name
); lineno
++;
4257 fprintf(out
,"#define %sCTX_STORE\n",name
); lineno
++;
4260 fprintf(out
,"#endif\n"); lineno
++;
4262 if( lemp
->errsym
&& lemp
->errsym
->useCnt
){
4263 fprintf(out
,"#define YYERRORSYMBOL %d\n",lemp
->errsym
->index
); lineno
++;
4264 fprintf(out
,"#define YYERRSYMDT yy%d\n",lemp
->errsym
->dtnum
); lineno
++;
4266 if( lemp
->has_fallback
){
4267 fprintf(out
,"#define YYFALLBACK 1\n"); lineno
++;
4270 /* Compute the action table, but do not output it yet. The action
4271 ** table must be computed before generating the YYNSTATE macro because
4272 ** we need to know how many states can be eliminated.
4274 ax
= (struct axset
*) calloc(lemp
->nxstate
*2, sizeof(ax
[0]));
4276 fprintf(stderr
,"malloc failed\n");
4279 for(i
=0; i
<lemp
->nxstate
; i
++){
4280 stp
= lemp
->sorted
[i
];
4283 ax
[i
*2].nAction
= stp
->nTknAct
;
4284 ax
[i
*2+1].stp
= stp
;
4285 ax
[i
*2+1].isTkn
= 0;
4286 ax
[i
*2+1].nAction
= stp
->nNtAct
;
4288 mxTknOfst
= mnTknOfst
= 0;
4289 mxNtOfst
= mnNtOfst
= 0;
4290 /* In an effort to minimize the action table size, use the heuristic
4291 ** of placing the largest action sets first */
4292 for(i
=0; i
<lemp
->nxstate
*2; i
++) ax
[i
].iOrder
= i
;
4293 qsort(ax
, lemp
->nxstate
*2, sizeof(ax
[0]), axset_compare
);
4294 pActtab
= acttab_alloc(lemp
->nsymbol
, lemp
->nterminal
);
4295 for(i
=0; i
<lemp
->nxstate
*2 && ax
[i
].nAction
>0; i
++){
4298 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4300 if( ap
->sp
->index
>=lemp
->nterminal
) continue;
4301 action
= compute_action(lemp
, ap
);
4302 if( action
<0 ) continue;
4303 acttab_action(pActtab
, ap
->sp
->index
, action
);
4305 stp
->iTknOfst
= acttab_insert(pActtab
, 1);
4306 if( stp
->iTknOfst
<mnTknOfst
) mnTknOfst
= stp
->iTknOfst
;
4307 if( stp
->iTknOfst
>mxTknOfst
) mxTknOfst
= stp
->iTknOfst
;
4309 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4311 if( ap
->sp
->index
<lemp
->nterminal
) continue;
4312 if( ap
->sp
->index
==lemp
->nsymbol
) continue;
4313 action
= compute_action(lemp
, ap
);
4314 if( action
<0 ) continue;
4315 acttab_action(pActtab
, ap
->sp
->index
, action
);
4317 stp
->iNtOfst
= acttab_insert(pActtab
, 0);
4318 if( stp
->iNtOfst
<mnNtOfst
) mnNtOfst
= stp
->iNtOfst
;
4319 if( stp
->iNtOfst
>mxNtOfst
) mxNtOfst
= stp
->iNtOfst
;
4321 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4323 for(jj
=nn
=0; jj
<pActtab
->nAction
; jj
++){
4324 if( pActtab
->aAction
[jj
].action
<0 ) nn
++;
4326 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4327 i
, stp
->statenum
, ax
[i
].isTkn
? "Token" : "Var ",
4328 ax
[i
].nAction
, pActtab
->nAction
, nn
);
4334 /* Mark rules that are actually used for reduce actions after all
4335 ** optimizations have been applied
4337 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->doesReduce
= LEMON_FALSE
;
4338 for(i
=0; i
<lemp
->nxstate
; i
++){
4339 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
4340 if( ap
->type
==REDUCE
|| ap
->type
==SHIFTREDUCE
){
4341 ap
->x
.rp
->doesReduce
= 1;
4346 /* Finish rendering the constants now that the action table has
4348 fprintf(out
,"#define YYNSTATE %d\n",lemp
->nxstate
); lineno
++;
4349 fprintf(out
,"#define YYNRULE %d\n",lemp
->nrule
); lineno
++;
4350 fprintf(out
,"#define YYNTOKEN %d\n",lemp
->nterminal
); lineno
++;
4351 fprintf(out
,"#define YY_MAX_SHIFT %d\n",lemp
->nxstate
-1); lineno
++;
4352 i
= lemp
->minShiftReduce
;
4353 fprintf(out
,"#define YY_MIN_SHIFTREDUCE %d\n",i
); lineno
++;
4355 fprintf(out
,"#define YY_MAX_SHIFTREDUCE %d\n", i
-1); lineno
++;
4356 fprintf(out
,"#define YY_ERROR_ACTION %d\n", lemp
->errAction
); lineno
++;
4357 fprintf(out
,"#define YY_ACCEPT_ACTION %d\n", lemp
->accAction
); lineno
++;
4358 fprintf(out
,"#define YY_NO_ACTION %d\n", lemp
->noAction
); lineno
++;
4359 fprintf(out
,"#define YY_MIN_REDUCE %d\n", lemp
->minReduce
); lineno
++;
4360 i
= lemp
->minReduce
+ lemp
->nrule
;
4361 fprintf(out
,"#define YY_MAX_REDUCE %d\n", i
-1); lineno
++;
4362 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4364 /* Now output the action table and its associates:
4366 ** yy_action[] A single table containing all actions.
4367 ** yy_lookahead[] A table containing the lookahead for each entry in
4368 ** yy_action. Used to detect hash collisions.
4369 ** yy_shift_ofst[] For each state, the offset into yy_action for
4370 ** shifting terminals.
4371 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4372 ** shifting non-terminals after a reduce.
4373 ** yy_default[] Default action for each state.
4376 /* Output the yy_action table */
4377 lemp
->nactiontab
= n
= acttab_action_size(pActtab
);
4378 lemp
->tablesize
+= n
*szActionType
;
4379 fprintf(out
,"#define YY_ACTTAB_COUNT (%d)\n", n
); lineno
++;
4380 fprintf(out
,"static const YYACTIONTYPE yy_action[] = {\n"); lineno
++;
4381 for(i
=j
=0; i
<n
; i
++){
4382 int action
= acttab_yyaction(pActtab
, i
);
4383 if( action
<0 ) action
= lemp
->noAction
;
4384 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4385 fprintf(out
, " %4d,", action
);
4386 if( j
==9 || i
==n
-1 ){
4387 fprintf(out
, "\n"); lineno
++;
4393 fprintf(out
, "};\n"); lineno
++;
4395 /* Output the yy_lookahead table */
4396 lemp
->nlookaheadtab
= n
= acttab_lookahead_size(pActtab
);
4397 lemp
->tablesize
+= n
*szCodeType
;
4398 fprintf(out
,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno
++;
4399 for(i
=j
=0; i
<n
; i
++){
4400 int la
= acttab_yylookahead(pActtab
, i
);
4401 if( la
<0 ) la
= lemp
->nsymbol
;
4402 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4403 fprintf(out
, " %4d,", la
);
4404 if( j
==9 || i
==n
-1 ){
4405 fprintf(out
, "\n"); lineno
++;
4411 fprintf(out
, "};\n"); lineno
++;
4413 /* Output the yy_shift_ofst[] table */
4415 while( n
>0 && lemp
->sorted
[n
-1]->iTknOfst
==NO_OFFSET
) n
--;
4416 fprintf(out
, "#define YY_SHIFT_COUNT (%d)\n", n
-1); lineno
++;
4417 fprintf(out
, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst
); lineno
++;
4418 fprintf(out
, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst
); lineno
++;
4419 fprintf(out
, "static const %s yy_shift_ofst[] = {\n",
4420 minimum_size_type(mnTknOfst
, lemp
->nterminal
+lemp
->nactiontab
, &sz
));
4422 lemp
->tablesize
+= n
*sz
;
4423 for(i
=j
=0; i
<n
; i
++){
4425 stp
= lemp
->sorted
[i
];
4426 ofst
= stp
->iTknOfst
;
4427 if( ofst
==NO_OFFSET
) ofst
= lemp
->nactiontab
;
4428 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4429 fprintf(out
, " %4d,", ofst
);
4430 if( j
==9 || i
==n
-1 ){
4431 fprintf(out
, "\n"); lineno
++;
4437 fprintf(out
, "};\n"); lineno
++;
4439 /* Output the yy_reduce_ofst[] table */
4441 while( n
>0 && lemp
->sorted
[n
-1]->iNtOfst
==NO_OFFSET
) n
--;
4442 fprintf(out
, "#define YY_REDUCE_COUNT (%d)\n", n
-1); lineno
++;
4443 fprintf(out
, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst
); lineno
++;
4444 fprintf(out
, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst
); lineno
++;
4445 fprintf(out
, "static const %s yy_reduce_ofst[] = {\n",
4446 minimum_size_type(mnNtOfst
-1, mxNtOfst
, &sz
)); lineno
++;
4447 lemp
->tablesize
+= n
*sz
;
4448 for(i
=j
=0; i
<n
; i
++){
4450 stp
= lemp
->sorted
[i
];
4451 ofst
= stp
->iNtOfst
;
4452 if( ofst
==NO_OFFSET
) ofst
= mnNtOfst
- 1;
4453 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4454 fprintf(out
, " %4d,", ofst
);
4455 if( j
==9 || i
==n
-1 ){
4456 fprintf(out
, "\n"); lineno
++;
4462 fprintf(out
, "};\n"); lineno
++;
4464 /* Output the default action table */
4465 fprintf(out
, "static const YYACTIONTYPE yy_default[] = {\n"); lineno
++;
4467 lemp
->tablesize
+= n
*szActionType
;
4468 for(i
=j
=0; i
<n
; i
++){
4469 stp
= lemp
->sorted
[i
];
4470 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4471 if( stp
->iDfltReduce
<0 ){
4472 fprintf(out
, " %4d,", lemp
->errAction
);
4474 fprintf(out
, " %4d,", stp
->iDfltReduce
+ lemp
->minReduce
);
4476 if( j
==9 || i
==n
-1 ){
4477 fprintf(out
, "\n"); lineno
++;
4483 fprintf(out
, "};\n"); lineno
++;
4484 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4486 /* Generate the table of fallback tokens.
4488 if( lemp
->has_fallback
){
4489 int mx
= lemp
->nterminal
- 1;
4490 while( mx
>0 && lemp
->symbols
[mx
]->fallback
==0 ){ mx
--; }
4491 lemp
->tablesize
+= (mx
+1)*szCodeType
;
4492 for(i
=0; i
<=mx
; i
++){
4493 struct symbol
*p
= lemp
->symbols
[i
];
4494 if( p
->fallback
==0 ){
4495 fprintf(out
, " 0, /* %10s => nothing */\n", p
->name
);
4497 fprintf(out
, " %3d, /* %10s => %s */\n", p
->fallback
->index
,
4498 p
->name
, p
->fallback
->name
);
4503 tplt_xfer(lemp
->name
, in
, out
, &lineno
);
4505 /* Generate a table containing the symbolic name of every symbol
4507 for(i
=0; i
<lemp
->nsymbol
; i
++){
4508 lemon_sprintf(line
,"\"%s\",",lemp
->symbols
[i
]->name
);
4509 fprintf(out
," /* %4d */ \"%s\",\n",i
, lemp
->symbols
[i
]->name
); lineno
++;
4511 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4513 /* Generate a table containing a text string that describes every
4514 ** rule in the rule set of the grammar. This information is used
4515 ** when tracing REDUCE actions.
4517 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4518 assert( rp
->iRule
==i
);
4519 fprintf(out
," /* %3d */ \"", i
);
4520 writeRuleText(out
, rp
);
4521 fprintf(out
,"\",\n"); lineno
++;
4523 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4525 /* Generate code which executes every time a symbol is popped from
4526 ** the stack while processing errors or while destroying the parser.
4527 ** (In other words, generate the %destructor actions)
4529 if( lemp
->tokendest
){
4531 for(i
=0; i
<lemp
->nsymbol
; i
++){
4532 struct symbol
*sp
= lemp
->symbols
[i
];
4533 if( sp
==0 || sp
->type
!=TERMINAL
) continue;
4535 fprintf(out
, " /* TERMINAL Destructor */\n"); lineno
++;
4538 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4540 for(i
=0; i
<lemp
->nsymbol
&& lemp
->symbols
[i
]->type
!=TERMINAL
; i
++);
4541 if( i
<lemp
->nsymbol
){
4542 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4543 fprintf(out
," break;\n"); lineno
++;
4546 if( lemp
->vardest
){
4547 struct symbol
*dflt_sp
= 0;
4549 for(i
=0; i
<lemp
->nsymbol
; i
++){
4550 struct symbol
*sp
= lemp
->symbols
[i
];
4551 if( sp
==0 || sp
->type
==TERMINAL
||
4552 sp
->index
<=0 || sp
->destructor
!=0 ) continue;
4554 fprintf(out
, " /* Default NON-TERMINAL Destructor */\n");lineno
++;
4557 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4561 emit_destructor_code(out
,dflt_sp
,lemp
,&lineno
);
4563 fprintf(out
," break;\n"); lineno
++;
4565 for(i
=0; i
<lemp
->nsymbol
; i
++){
4566 struct symbol
*sp
= lemp
->symbols
[i
];
4567 if( sp
==0 || sp
->type
==TERMINAL
|| sp
->destructor
==0 ) continue;
4568 if( sp
->destLineno
<0 ) continue; /* Already emitted */
4569 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4571 /* Combine duplicate destructors into a single case */
4572 for(j
=i
+1; j
<lemp
->nsymbol
; j
++){
4573 struct symbol
*sp2
= lemp
->symbols
[j
];
4574 if( sp2
&& sp2
->type
!=TERMINAL
&& sp2
->destructor
4575 && sp2
->dtnum
==sp
->dtnum
4576 && strcmp(sp
->destructor
,sp2
->destructor
)==0 ){
4577 fprintf(out
," case %d: /* %s */\n",
4578 sp2
->index
, sp2
->name
); lineno
++;
4579 sp2
->destLineno
= -1; /* Avoid emitting this destructor again */
4583 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4584 fprintf(out
," break;\n"); lineno
++;
4586 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4588 /* Generate code which executes whenever the parser stack overflows */
4589 tplt_print(out
,lemp
,lemp
->overflow
,&lineno
);
4590 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4592 /* Generate the table of rule information
4594 ** Note: This code depends on the fact that rules are number
4595 ** sequentually beginning with 0.
4597 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4598 fprintf(out
," { %4d, %4d }, /* (%d) ",rp
->lhs
->index
,-rp
->nrhs
,i
);
4599 rule_print(out
, rp
);
4600 fprintf(out
," */\n"); lineno
++;
4602 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4604 /* Generate code which execution during each REDUCE action */
4606 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4607 i
+= translate_code(lemp
, rp
);
4610 fprintf(out
," YYMINORTYPE yylhsminor;\n"); lineno
++;
4612 /* First output rules other than the default: rule */
4613 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4614 struct rule
*rp2
; /* Other rules with the same action */
4615 if( rp
->codeEmitted
) continue;
4617 /* No C code actions, so this will be part of the "default:" rule */
4620 fprintf(out
," case %d: /* ", rp
->iRule
);
4621 writeRuleText(out
, rp
);
4622 fprintf(out
, " */\n"); lineno
++;
4623 for(rp2
=rp
->next
; rp2
; rp2
=rp2
->next
){
4624 if( rp2
->code
==rp
->code
&& rp2
->codePrefix
==rp
->codePrefix
4625 && rp2
->codeSuffix
==rp
->codeSuffix
){
4626 fprintf(out
," case %d: /* ", rp2
->iRule
);
4627 writeRuleText(out
, rp2
);
4628 fprintf(out
," */ yytestcase(yyruleno==%d);\n", rp2
->iRule
); lineno
++;
4629 rp2
->codeEmitted
= 1;
4632 emit_code(out
,rp
,lemp
,&lineno
);
4633 fprintf(out
," break;\n"); lineno
++;
4634 rp
->codeEmitted
= 1;
4636 /* Finally, output the default: rule. We choose as the default: all
4637 ** empty actions. */
4638 fprintf(out
," default:\n"); lineno
++;
4639 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4640 if( rp
->codeEmitted
) continue;
4641 assert( rp
->noCode
);
4642 fprintf(out
," /* (%d) ", rp
->iRule
);
4643 writeRuleText(out
, rp
);
4644 if( rp
->doesReduce
){
4645 fprintf(out
, " */ yytestcase(yyruleno==%d);\n", rp
->iRule
); lineno
++;
4647 fprintf(out
, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4648 rp
->iRule
); lineno
++;
4651 fprintf(out
," break;\n"); lineno
++;
4652 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4654 /* Generate code which executes if a parse fails */
4655 tplt_print(out
,lemp
,lemp
->failure
,&lineno
);
4656 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4658 /* Generate code which executes when a syntax error occurs */
4659 tplt_print(out
,lemp
,lemp
->error
,&lineno
);
4660 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4662 /* Generate code which executes when the parser accepts its input */
4663 tplt_print(out
,lemp
,lemp
->accept
,&lineno
);
4664 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4666 /* Append any addition code the user desires */
4667 tplt_print(out
,lemp
,lemp
->extracode
,&lineno
);
4674 /* Generate a header file for the parser */
4675 void ReportHeader(struct lemon
*lemp
)
4679 char line
[LINESIZE
];
4680 char pattern
[LINESIZE
];
4683 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4685 in
= file_open(lemp
,".h","rb");
4688 for(i
=1; i
<lemp
->nterminal
&& fgets(line
,LINESIZE
,in
); i
++){
4689 lemon_sprintf(pattern
,"#define %s%-30s %3d\n",
4690 prefix
,lemp
->symbols
[i
]->name
,i
);
4691 if( strcmp(line
,pattern
) ) break;
4693 nextChar
= fgetc(in
);
4695 if( i
==lemp
->nterminal
&& nextChar
==EOF
){
4696 /* No change in the file. Don't rewrite it. */
4700 out
= file_open(lemp
,".h","wb");
4702 for(i
=1; i
<lemp
->nterminal
; i
++){
4703 fprintf(out
,"#define %s%-30s %3d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4710 /* Reduce the size of the action tables, if possible, by making use
4713 ** In this version, we take the most frequent REDUCE action and make
4714 ** it the default. Except, there is no default if the wildcard token
4715 ** is a possible look-ahead.
4717 void CompressTables(struct lemon
*lemp
)
4720 struct action
*ap
, *ap2
, *nextap
;
4721 struct rule
*rp
, *rp2
, *rbest
;
4726 for(i
=0; i
<lemp
->nstate
; i
++){
4727 stp
= lemp
->sorted
[i
];
4732 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4733 if( ap
->type
==SHIFT
&& ap
->sp
==lemp
->wildcard
){
4736 if( ap
->type
!=REDUCE
) continue;
4738 if( rp
->lhsStart
) continue;
4739 if( rp
==rbest
) continue;
4741 for(ap2
=ap
->next
; ap2
; ap2
=ap2
->next
){
4742 if( ap2
->type
!=REDUCE
) continue;
4744 if( rp2
==rbest
) continue;
4753 /* Do not make a default if the number of rules to default
4754 ** is not at least 1 or if the wildcard token is a possible
4757 if( nbest
<1 || usesWildcard
) continue;
4760 /* Combine matching REDUCE actions into a single default */
4761 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4762 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) break;
4765 ap
->sp
= Symbol_new("{default}");
4766 for(ap
=ap
->next
; ap
; ap
=ap
->next
){
4767 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) ap
->type
= NOT_USED
;
4769 stp
->ap
= Action_sort(stp
->ap
);
4771 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4772 if( ap
->type
==SHIFT
) break;
4773 if( ap
->type
==REDUCE
&& ap
->x
.rp
!=rbest
) break;
4776 stp
->autoReduce
= 1;
4777 stp
->pDfltReduce
= rbest
;
4781 /* Make a second pass over all states and actions. Convert
4782 ** every action that is a SHIFT to an autoReduce state into
4783 ** a SHIFTREDUCE action.
4785 for(i
=0; i
<lemp
->nstate
; i
++){
4786 stp
= lemp
->sorted
[i
];
4787 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4788 struct state
*pNextState
;
4789 if( ap
->type
!=SHIFT
) continue;
4790 pNextState
= ap
->x
.stp
;
4791 if( pNextState
->autoReduce
&& pNextState
->pDfltReduce
!=0 ){
4792 ap
->type
= SHIFTREDUCE
;
4793 ap
->x
.rp
= pNextState
->pDfltReduce
;
4798 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4799 ** (meaning that the SHIFTREDUCE will land back in the state where it
4800 ** started) and if there is no C-code associated with the reduce action,
4801 ** then we can go ahead and convert the action to be the same as the
4802 ** action for the RHS of the rule.
4804 for(i
=0; i
<lemp
->nstate
; i
++){
4805 stp
= lemp
->sorted
[i
];
4806 for(ap
=stp
->ap
; ap
; ap
=nextap
){
4808 if( ap
->type
!=SHIFTREDUCE
) continue;
4810 if( rp
->noCode
==0 ) continue;
4811 if( rp
->nrhs
!=1 ) continue;
4813 /* Only apply this optimization to non-terminals. It would be OK to
4814 ** apply it to terminal symbols too, but that makes the parser tables
4816 if( ap
->sp
->index
<lemp
->nterminal
) continue;
4818 /* If we reach this point, it means the optimization can be applied */
4820 for(ap2
=stp
->ap
; ap2
&& (ap2
==ap
|| ap2
->sp
!=rp
->lhs
); ap2
=ap2
->next
){}
4822 ap
->spOpt
= ap2
->sp
;
4823 ap
->type
= ap2
->type
;
4831 ** Compare two states for sorting purposes. The smaller state is the
4832 ** one with the most non-terminal actions. If they have the same number
4833 ** of non-terminal actions, then the smaller is the one with the most
4836 static int stateResortCompare(const void *a
, const void *b
){
4837 const struct state
*pA
= *(const struct state
**)a
;
4838 const struct state
*pB
= *(const struct state
**)b
;
4841 n
= pB
->nNtAct
- pA
->nNtAct
;
4843 n
= pB
->nTknAct
- pA
->nTknAct
;
4845 n
= pB
->statenum
- pA
->statenum
;
4854 ** Renumber and resort states so that states with fewer choices
4855 ** occur at the end. Except, keep state 0 as the first state.
4857 void ResortStates(struct lemon
*lemp
)
4863 for(i
=0; i
<lemp
->nstate
; i
++){
4864 stp
= lemp
->sorted
[i
];
4865 stp
->nTknAct
= stp
->nNtAct
= 0;
4866 stp
->iDfltReduce
= -1; /* Init dflt action to "syntax error" */
4867 stp
->iTknOfst
= NO_OFFSET
;
4868 stp
->iNtOfst
= NO_OFFSET
;
4869 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4870 int iAction
= compute_action(lemp
,ap
);
4872 if( ap
->sp
->index
<lemp
->nterminal
){
4874 }else if( ap
->sp
->index
<lemp
->nsymbol
){
4877 assert( stp
->autoReduce
==0 || stp
->pDfltReduce
==ap
->x
.rp
);
4878 stp
->iDfltReduce
= iAction
;
4883 qsort(&lemp
->sorted
[1], lemp
->nstate
-1, sizeof(lemp
->sorted
[0]),
4884 stateResortCompare
);
4885 for(i
=0; i
<lemp
->nstate
; i
++){
4886 lemp
->sorted
[i
]->statenum
= i
;
4888 lemp
->nxstate
= lemp
->nstate
;
4889 while( lemp
->nxstate
>1 && lemp
->sorted
[lemp
->nxstate
-1]->autoReduce
){
4895 /***************** From the file "set.c" ************************************/
4897 ** Set manipulation routines for the LEMON parser generator.
4900 static int size
= 0;
4902 /* Set the set size */
4908 /* Allocate a new set */
4911 s
= (char*)calloc( size
, 1);
4913 extern void memory_error();
4919 /* Deallocate a set */
4920 void SetFree(char *s
)
4925 /* Add a new element to the set. Return TRUE if the element was added
4926 ** and FALSE if it was already there. */
4927 int SetAdd(char *s
, int e
)
4930 assert( e
>=0 && e
<size
);
4936 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4937 int SetUnion(char *s1
, char *s2
)
4941 for(i
=0; i
<size
; i
++){
4942 if( s2
[i
]==0 ) continue;
4950 /********************** From the file "table.c" ****************************/
4952 ** All code in this file has been automatically generated
4953 ** from a specification in the file
4955 ** by the associative array code building program "aagen".
4956 ** Do not edit this file! Instead, edit the specification
4957 ** file, then rerun aagen.
4960 ** Code for processing tables in the LEMON parser generator.
4963 PRIVATE
unsigned strhash(const char *x
)
4966 while( *x
) h
= h
*13 + *(x
++);
4970 /* Works like strdup, sort of. Save a string in malloced memory, but
4971 ** keep strings in a table so that the same string is not in more
4974 const char *Strsafe(const char *y
)
4979 if( y
==0 ) return 0;
4980 z
= Strsafe_find(y
);
4981 if( z
==0 && (cpy
=(char *)malloc( lemonStrlen(y
)+1 ))!=0 ){
4982 lemon_strcpy(cpy
,y
);
4990 /* There is one instance of the following structure for each
4991 ** associative array of type "x1".
4994 int size
; /* The number of available slots. */
4995 /* Must be a power of 2 greater than or */
4997 int count
; /* Number of currently slots filled */
4998 struct s_x1node
*tbl
; /* The data stored here */
4999 struct s_x1node
**ht
; /* Hash table for lookups */
5002 /* There is one instance of this structure for every data element
5003 ** in an associative array of type "x1".
5005 typedef struct s_x1node
{
5006 const char *data
; /* The data */
5007 struct s_x1node
*next
; /* Next entry with the same hash */
5008 struct s_x1node
**from
; /* Previous link */
5011 /* There is only one instance of the array, which is the following */
5012 static struct s_x1
*x1a
;
5014 /* Allocate a new associative array */
5015 void Strsafe_init(void){
5017 x1a
= (struct s_x1
*)malloc( sizeof(struct s_x1
) );
5021 x1a
->tbl
= (x1node
*)calloc(1024, sizeof(x1node
) + sizeof(x1node
*));
5027 x1a
->ht
= (x1node
**)&(x1a
->tbl
[1024]);
5028 for(i
=0; i
<1024; i
++) x1a
->ht
[i
] = 0;
5032 /* Insert a new record into the array. Return TRUE if successful.
5033 ** Prior data with the same key is NOT overwritten */
5034 int Strsafe_insert(const char *data
)
5040 if( x1a
==0 ) return 0;
5042 h
= ph
& (x1a
->size
-1);
5045 if( strcmp(np
->data
,data
)==0 ){
5046 /* An existing entry with the same key is found. */
5047 /* Fail because overwrite is not allows. */
5052 if( x1a
->count
>=x1a
->size
){
5053 /* Need to make the hash table bigger */
5056 array
.size
= arrSize
= x1a
->size
*2;
5057 array
.count
= x1a
->count
;
5058 array
.tbl
= (x1node
*)calloc(arrSize
, sizeof(x1node
) + sizeof(x1node
*));
5059 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5060 array
.ht
= (x1node
**)&(array
.tbl
[arrSize
]);
5061 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5062 for(i
=0; i
<x1a
->count
; i
++){
5063 x1node
*oldnp
, *newnp
;
5064 oldnp
= &(x1a
->tbl
[i
]);
5065 h
= strhash(oldnp
->data
) & (arrSize
-1);
5066 newnp
= &(array
.tbl
[i
]);
5067 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5068 newnp
->next
= array
.ht
[h
];
5069 newnp
->data
= oldnp
->data
;
5070 newnp
->from
= &(array
.ht
[h
]);
5071 array
.ht
[h
] = newnp
;
5076 /* Insert the new data */
5077 h
= ph
& (x1a
->size
-1);
5078 np
= &(x1a
->tbl
[x1a
->count
++]);
5080 if( x1a
->ht
[h
] ) x1a
->ht
[h
]->from
= &(np
->next
);
5081 np
->next
= x1a
->ht
[h
];
5083 np
->from
= &(x1a
->ht
[h
]);
5087 /* Return a pointer to data assigned to the given key. Return NULL
5088 ** if no such key. */
5089 const char *Strsafe_find(const char *key
)
5094 if( x1a
==0 ) return 0;
5095 h
= strhash(key
) & (x1a
->size
-1);
5098 if( strcmp(np
->data
,key
)==0 ) break;
5101 return np
? np
->data
: 0;
5104 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5105 ** Create a new symbol if this is the first time "x" has been seen.
5107 struct symbol
*Symbol_new(const char *x
)
5111 sp
= Symbol_find(x
);
5113 sp
= (struct symbol
*)calloc(1, sizeof(struct symbol
) );
5115 sp
->name
= Strsafe(x
);
5116 sp
->type
= ISUPPER(*x
) ? TERMINAL
: NONTERMINAL
;
5122 sp
->lambda
= LEMON_FALSE
;
5127 Symbol_insert(sp
,sp
->name
);
5133 /* Compare two symbols for sorting purposes. Return negative,
5134 ** zero, or positive if a is less then, equal to, or greater
5137 ** Symbols that begin with upper case letters (terminals or tokens)
5138 ** must sort before symbols that begin with lower case letters
5139 ** (non-terminals). And MULTITERMINAL symbols (created using the
5140 ** %token_class directive) must sort at the very end. Other than
5141 ** that, the order does not matter.
5143 ** We find experimentally that leaving the symbols in their original
5144 ** order (the order they appeared in the grammar file) gives the
5145 ** smallest parser tables in SQLite.
5147 int Symbolcmpp(const void *_a
, const void *_b
)
5149 const struct symbol
*a
= *(const struct symbol
**) _a
;
5150 const struct symbol
*b
= *(const struct symbol
**) _b
;
5151 int i1
= a
->type
==MULTITERMINAL
? 3 : a
->name
[0]>'Z' ? 2 : 1;
5152 int i2
= b
->type
==MULTITERMINAL
? 3 : b
->name
[0]>'Z' ? 2 : 1;
5153 return i1
==i2
? a
->index
- b
->index
: i1
- i2
;
5156 /* There is one instance of the following structure for each
5157 ** associative array of type "x2".
5160 int size
; /* The number of available slots. */
5161 /* Must be a power of 2 greater than or */
5163 int count
; /* Number of currently slots filled */
5164 struct s_x2node
*tbl
; /* The data stored here */
5165 struct s_x2node
**ht
; /* Hash table for lookups */
5168 /* There is one instance of this structure for every data element
5169 ** in an associative array of type "x2".
5171 typedef struct s_x2node
{
5172 struct symbol
*data
; /* The data */
5173 const char *key
; /* The key */
5174 struct s_x2node
*next
; /* Next entry with the same hash */
5175 struct s_x2node
**from
; /* Previous link */
5178 /* There is only one instance of the array, which is the following */
5179 static struct s_x2
*x2a
;
5181 /* Allocate a new associative array */
5182 void Symbol_init(void){
5184 x2a
= (struct s_x2
*)malloc( sizeof(struct s_x2
) );
5188 x2a
->tbl
= (x2node
*)calloc(128, sizeof(x2node
) + sizeof(x2node
*));
5194 x2a
->ht
= (x2node
**)&(x2a
->tbl
[128]);
5195 for(i
=0; i
<128; i
++) x2a
->ht
[i
] = 0;
5199 /* Insert a new record into the array. Return TRUE if successful.
5200 ** Prior data with the same key is NOT overwritten */
5201 int Symbol_insert(struct symbol
*data
, const char *key
)
5207 if( x2a
==0 ) return 0;
5209 h
= ph
& (x2a
->size
-1);
5212 if( strcmp(np
->key
,key
)==0 ){
5213 /* An existing entry with the same key is found. */
5214 /* Fail because overwrite is not allows. */
5219 if( x2a
->count
>=x2a
->size
){
5220 /* Need to make the hash table bigger */
5223 array
.size
= arrSize
= x2a
->size
*2;
5224 array
.count
= x2a
->count
;
5225 array
.tbl
= (x2node
*)calloc(arrSize
, sizeof(x2node
) + sizeof(x2node
*));
5226 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5227 array
.ht
= (x2node
**)&(array
.tbl
[arrSize
]);
5228 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5229 for(i
=0; i
<x2a
->count
; i
++){
5230 x2node
*oldnp
, *newnp
;
5231 oldnp
= &(x2a
->tbl
[i
]);
5232 h
= strhash(oldnp
->key
) & (arrSize
-1);
5233 newnp
= &(array
.tbl
[i
]);
5234 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5235 newnp
->next
= array
.ht
[h
];
5236 newnp
->key
= oldnp
->key
;
5237 newnp
->data
= oldnp
->data
;
5238 newnp
->from
= &(array
.ht
[h
]);
5239 array
.ht
[h
] = newnp
;
5244 /* Insert the new data */
5245 h
= ph
& (x2a
->size
-1);
5246 np
= &(x2a
->tbl
[x2a
->count
++]);
5249 if( x2a
->ht
[h
] ) x2a
->ht
[h
]->from
= &(np
->next
);
5250 np
->next
= x2a
->ht
[h
];
5252 np
->from
= &(x2a
->ht
[h
]);
5256 /* Return a pointer to data assigned to the given key. Return NULL
5257 ** if no such key. */
5258 struct symbol
*Symbol_find(const char *key
)
5263 if( x2a
==0 ) return 0;
5264 h
= strhash(key
) & (x2a
->size
-1);
5267 if( strcmp(np
->key
,key
)==0 ) break;
5270 return np
? np
->data
: 0;
5273 /* Return the n-th data. Return NULL if n is out of range. */
5274 struct symbol
*Symbol_Nth(int n
)
5276 struct symbol
*data
;
5277 if( x2a
&& n
>0 && n
<=x2a
->count
){
5278 data
= x2a
->tbl
[n
-1].data
;
5285 /* Return the size of the array */
5288 return x2a
? x2a
->count
: 0;
5291 /* Return an array of pointers to all data in the table.
5292 ** The array is obtained from malloc. Return NULL if memory allocation
5293 ** problems, or if the array is empty. */
5294 struct symbol
**Symbol_arrayof()
5296 struct symbol
**array
;
5298 if( x2a
==0 ) return 0;
5299 arrSize
= x2a
->count
;
5300 array
= (struct symbol
**)calloc(arrSize
, sizeof(struct symbol
*));
5302 for(i
=0; i
<arrSize
; i
++) array
[i
] = x2a
->tbl
[i
].data
;
5307 /* Compare two configurations */
5308 int Configcmp(const char *_a
,const char *_b
)
5310 const struct config
*a
= (struct config
*) _a
;
5311 const struct config
*b
= (struct config
*) _b
;
5313 x
= a
->rp
->index
- b
->rp
->index
;
5314 if( x
==0 ) x
= a
->dot
- b
->dot
;
5318 /* Compare two states */
5319 PRIVATE
int statecmp(struct config
*a
, struct config
*b
)
5322 for(rc
=0; rc
==0 && a
&& b
; a
=a
->bp
, b
=b
->bp
){
5323 rc
= a
->rp
->index
- b
->rp
->index
;
5324 if( rc
==0 ) rc
= a
->dot
- b
->dot
;
5334 PRIVATE
unsigned statehash(struct config
*a
)
5338 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5344 /* Allocate a new state structure */
5345 struct state
*State_new()
5347 struct state
*newstate
;
5348 newstate
= (struct state
*)calloc(1, sizeof(struct state
) );
5349 MemoryCheck(newstate
);
5353 /* There is one instance of the following structure for each
5354 ** associative array of type "x3".
5357 int size
; /* The number of available slots. */
5358 /* Must be a power of 2 greater than or */
5360 int count
; /* Number of currently slots filled */
5361 struct s_x3node
*tbl
; /* The data stored here */
5362 struct s_x3node
**ht
; /* Hash table for lookups */
5365 /* There is one instance of this structure for every data element
5366 ** in an associative array of type "x3".
5368 typedef struct s_x3node
{
5369 struct state
*data
; /* The data */
5370 struct config
*key
; /* The key */
5371 struct s_x3node
*next
; /* Next entry with the same hash */
5372 struct s_x3node
**from
; /* Previous link */
5375 /* There is only one instance of the array, which is the following */
5376 static struct s_x3
*x3a
;
5378 /* Allocate a new associative array */
5379 void State_init(void){
5381 x3a
= (struct s_x3
*)malloc( sizeof(struct s_x3
) );
5385 x3a
->tbl
= (x3node
*)calloc(128, sizeof(x3node
) + sizeof(x3node
*));
5391 x3a
->ht
= (x3node
**)&(x3a
->tbl
[128]);
5392 for(i
=0; i
<128; i
++) x3a
->ht
[i
] = 0;
5396 /* Insert a new record into the array. Return TRUE if successful.
5397 ** Prior data with the same key is NOT overwritten */
5398 int State_insert(struct state
*data
, struct config
*key
)
5404 if( x3a
==0 ) return 0;
5405 ph
= statehash(key
);
5406 h
= ph
& (x3a
->size
-1);
5409 if( statecmp(np
->key
,key
)==0 ){
5410 /* An existing entry with the same key is found. */
5411 /* Fail because overwrite is not allows. */
5416 if( x3a
->count
>=x3a
->size
){
5417 /* Need to make the hash table bigger */
5420 array
.size
= arrSize
= x3a
->size
*2;
5421 array
.count
= x3a
->count
;
5422 array
.tbl
= (x3node
*)calloc(arrSize
, sizeof(x3node
) + sizeof(x3node
*));
5423 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5424 array
.ht
= (x3node
**)&(array
.tbl
[arrSize
]);
5425 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5426 for(i
=0; i
<x3a
->count
; i
++){
5427 x3node
*oldnp
, *newnp
;
5428 oldnp
= &(x3a
->tbl
[i
]);
5429 h
= statehash(oldnp
->key
) & (arrSize
-1);
5430 newnp
= &(array
.tbl
[i
]);
5431 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5432 newnp
->next
= array
.ht
[h
];
5433 newnp
->key
= oldnp
->key
;
5434 newnp
->data
= oldnp
->data
;
5435 newnp
->from
= &(array
.ht
[h
]);
5436 array
.ht
[h
] = newnp
;
5441 /* Insert the new data */
5442 h
= ph
& (x3a
->size
-1);
5443 np
= &(x3a
->tbl
[x3a
->count
++]);
5446 if( x3a
->ht
[h
] ) x3a
->ht
[h
]->from
= &(np
->next
);
5447 np
->next
= x3a
->ht
[h
];
5449 np
->from
= &(x3a
->ht
[h
]);
5453 /* Return a pointer to data assigned to the given key. Return NULL
5454 ** if no such key. */
5455 struct state
*State_find(struct config
*key
)
5460 if( x3a
==0 ) return 0;
5461 h
= statehash(key
) & (x3a
->size
-1);
5464 if( statecmp(np
->key
,key
)==0 ) break;
5467 return np
? np
->data
: 0;
5470 /* Return an array of pointers to all data in the table.
5471 ** The array is obtained from malloc. Return NULL if memory allocation
5472 ** problems, or if the array is empty. */
5473 struct state
**State_arrayof(void)
5475 struct state
**array
;
5477 if( x3a
==0 ) return 0;
5478 arrSize
= x3a
->count
;
5479 array
= (struct state
**)calloc(arrSize
, sizeof(struct state
*));
5481 for(i
=0; i
<arrSize
; i
++) array
[i
] = x3a
->tbl
[i
].data
;
5486 /* Hash a configuration */
5487 PRIVATE
unsigned confighash(struct config
*a
)
5490 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5494 /* There is one instance of the following structure for each
5495 ** associative array of type "x4".
5498 int size
; /* The number of available slots. */
5499 /* Must be a power of 2 greater than or */
5501 int count
; /* Number of currently slots filled */
5502 struct s_x4node
*tbl
; /* The data stored here */
5503 struct s_x4node
**ht
; /* Hash table for lookups */
5506 /* There is one instance of this structure for every data element
5507 ** in an associative array of type "x4".
5509 typedef struct s_x4node
{
5510 struct config
*data
; /* The data */
5511 struct s_x4node
*next
; /* Next entry with the same hash */
5512 struct s_x4node
**from
; /* Previous link */
5515 /* There is only one instance of the array, which is the following */
5516 static struct s_x4
*x4a
;
5518 /* Allocate a new associative array */
5519 void Configtable_init(void){
5521 x4a
= (struct s_x4
*)malloc( sizeof(struct s_x4
) );
5525 x4a
->tbl
= (x4node
*)calloc(64, sizeof(x4node
) + sizeof(x4node
*));
5531 x4a
->ht
= (x4node
**)&(x4a
->tbl
[64]);
5532 for(i
=0; i
<64; i
++) x4a
->ht
[i
] = 0;
5536 /* Insert a new record into the array. Return TRUE if successful.
5537 ** Prior data with the same key is NOT overwritten */
5538 int Configtable_insert(struct config
*data
)
5544 if( x4a
==0 ) return 0;
5545 ph
= confighash(data
);
5546 h
= ph
& (x4a
->size
-1);
5549 if( Configcmp((const char *) np
->data
,(const char *) data
)==0 ){
5550 /* An existing entry with the same key is found. */
5551 /* Fail because overwrite is not allows. */
5556 if( x4a
->count
>=x4a
->size
){
5557 /* Need to make the hash table bigger */
5560 array
.size
= arrSize
= x4a
->size
*2;
5561 array
.count
= x4a
->count
;
5562 array
.tbl
= (x4node
*)calloc(arrSize
, sizeof(x4node
) + sizeof(x4node
*));
5563 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5564 array
.ht
= (x4node
**)&(array
.tbl
[arrSize
]);
5565 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5566 for(i
=0; i
<x4a
->count
; i
++){
5567 x4node
*oldnp
, *newnp
;
5568 oldnp
= &(x4a
->tbl
[i
]);
5569 h
= confighash(oldnp
->data
) & (arrSize
-1);
5570 newnp
= &(array
.tbl
[i
]);
5571 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5572 newnp
->next
= array
.ht
[h
];
5573 newnp
->data
= oldnp
->data
;
5574 newnp
->from
= &(array
.ht
[h
]);
5575 array
.ht
[h
] = newnp
;
5580 /* Insert the new data */
5581 h
= ph
& (x4a
->size
-1);
5582 np
= &(x4a
->tbl
[x4a
->count
++]);
5584 if( x4a
->ht
[h
] ) x4a
->ht
[h
]->from
= &(np
->next
);
5585 np
->next
= x4a
->ht
[h
];
5587 np
->from
= &(x4a
->ht
[h
]);
5591 /* Return a pointer to data assigned to the given key. Return NULL
5592 ** if no such key. */
5593 struct config
*Configtable_find(struct config
*key
)
5598 if( x4a
==0 ) return 0;
5599 h
= confighash(key
) & (x4a
->size
-1);
5602 if( Configcmp((const char *) np
->data
,(const char *) key
)==0 ) break;
5605 return np
? np
->data
: 0;
5608 /* Remove all data from the table. Pass each data to the function "f"
5609 ** as it is removed. ("f" may be null to avoid this step.) */
5610 void Configtable_clear(int(*f
)(struct config
*))
5613 if( x4a
==0 || x4a
->count
==0 ) return;
5614 if( f
) for(i
=0; i
<x4a
->count
; i
++) (*f
)(x4a
->tbl
[i
].data
);
5615 for(i
=0; i
<x4a
->size
; i
++) x4a
->ht
[i
] = 0;