2 ** This file contains all sources (including headers) to the LEMON
3 ** LALR(1) parser generator. The sources have been combined into a
4 ** single file to make it easy to include LEMON in the source tree
5 ** and Makefile of another program.
7 ** The author of this program disclaims copyright.
16 #define ISSPACE(X) isspace((unsigned char)(X))
17 #define ISDIGIT(X) isdigit((unsigned char)(X))
18 #define ISALNUM(X) isalnum((unsigned char)(X))
19 #define ISALPHA(X) isalpha((unsigned char)(X))
20 #define ISUPPER(X) isupper((unsigned char)(X))
21 #define ISLOWER(X) islower((unsigned char)(X))
25 # if defined(_WIN32) || defined(WIN32)
34 extern int access(const char *path
, int mode
);
42 /* #define PRIVATE static */
46 #define MAXRHS 5 /* Set low to exercise exception code */
51 extern void memory_error();
52 static int showPrecedenceConflict
= 0;
53 static char *msort(char*,char**,int(*)(const char*,const char*));
56 ** Compilers are getting increasingly pedantic about type conversions
57 ** as C evolves ever closer to Ada.... To work around the latest problems
58 ** we have to define the following variant of strlen().
60 #define lemonStrlen(X) ((int)strlen(X))
63 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
64 ** saying they are unsafe. So we define our own versions of those routines too.
66 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
67 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
68 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
69 ** buffer, making sure the buffer is always zero-terminated.
71 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
72 ** a few simply conversions:
79 static void lemon_addtext(
80 char *zBuf
, /* The buffer to which text is added */
81 int *pnUsed
, /* Slots of the buffer used so far */
82 const char *zIn
, /* Text to add */
83 int nIn
, /* Bytes of text to add. -1 to use strlen() */
84 int iWidth
/* Field width. Negative to left justify */
86 if( nIn
<0 ) for(nIn
=0; zIn
[nIn
]; nIn
++){}
87 while( iWidth
>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
--; }
89 memcpy(&zBuf
[*pnUsed
], zIn
, nIn
);
91 while( (-iWidth
)>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
++; }
94 static int lemon_vsprintf(char *str
, const char *zFormat
, va_list ap
){
100 for(i
=j
=0; (c
= zFormat
[i
])!=0; i
++){
103 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
105 if( ISDIGIT(c
) || (c
=='-' && ISDIGIT(zFormat
[i
+1])) ){
107 while( ISDIGIT(zFormat
[i
]) ) iWidth
= iWidth
*10 + zFormat
[i
++] - '0';
108 if( c
=='-' ) iWidth
= -iWidth
;
112 int v
= va_arg(ap
, int);
114 lemon_addtext(str
, &nUsed
, "-", 1, iWidth
);
117 lemon_addtext(str
, &nUsed
, "0", 1, iWidth
);
122 zTemp
[sizeof(zTemp
)-k
] = (v
%10) + '0';
125 lemon_addtext(str
, &nUsed
, &zTemp
[sizeof(zTemp
)-k
], k
, iWidth
);
127 z
= va_arg(ap
, const char*);
128 lemon_addtext(str
, &nUsed
, z
, -1, iWidth
);
129 }else if( c
=='.' && memcmp(&zFormat
[i
], ".*s", 3)==0 ){
132 z
= va_arg(ap
, const char*);
133 lemon_addtext(str
, &nUsed
, z
, k
, iWidth
);
135 lemon_addtext(str
, &nUsed
, "%", 1, 0);
137 fprintf(stderr
, "illegal format\n");
143 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
146 static int lemon_sprintf(char *str
, const char *format
, ...){
149 va_start(ap
, format
);
150 rc
= lemon_vsprintf(str
, format
, ap
);
154 static void lemon_strcpy(char *dest
, const char *src
){
155 while( (*(dest
++) = *(src
++))!=0 ){}
157 static void lemon_strcat(char *dest
, const char *src
){
158 while( *dest
) dest
++;
159 lemon_strcpy(dest
, src
);
163 /* a few forward declarations... */
168 static struct action
*Action_new(void);
169 static struct action
*Action_sort(struct action
*);
171 /********** From the file "build.h" ************************************/
172 void FindRulePrecedences(struct lemon
*);
173 void FindFirstSets(struct lemon
*);
174 void FindStates(struct lemon
*);
175 void FindLinks(struct lemon
*);
176 void FindFollowSets(struct lemon
*);
177 void FindActions(struct lemon
*);
179 /********* From the file "configlist.h" *********************************/
180 void Configlist_init(void);
181 struct config
*Configlist_add(struct rule
*, int);
182 struct config
*Configlist_addbasis(struct rule
*, int);
183 void Configlist_closure(struct lemon
*);
184 void Configlist_sort(void);
185 void Configlist_sortbasis(void);
186 struct config
*Configlist_return(void);
187 struct config
*Configlist_basis(void);
188 void Configlist_eat(struct config
*);
189 void Configlist_reset(void);
191 /********* From the file "error.h" ***************************************/
192 void ErrorMsg(const char *, int,const char *, ...);
194 /****** From the file "option.h" ******************************************/
195 enum option_type
{ OPT_FLAG
=1, OPT_INT
, OPT_DBL
, OPT_STR
,
196 OPT_FFLAG
, OPT_FINT
, OPT_FDBL
, OPT_FSTR
};
198 enum option_type type
;
203 int OptInit(char**,struct s_options
*,FILE*);
209 /******** From the file "parse.h" *****************************************/
210 void Parse(struct lemon
*lemp
);
212 /********* From the file "plink.h" ***************************************/
213 struct plink
*Plink_new(void);
214 void Plink_add(struct plink
**, struct config
*);
215 void Plink_copy(struct plink
**, struct plink
*);
216 void Plink_delete(struct plink
*);
218 /********** From the file "report.h" *************************************/
219 void Reprint(struct lemon
*);
220 void ReportOutput(struct lemon
*);
221 void ReportTable(struct lemon
*, int, int);
222 void ReportHeader(struct lemon
*);
223 void CompressTables(struct lemon
*);
224 void ResortStates(struct lemon
*);
226 /********** From the file "set.h" ****************************************/
227 void SetSize(int); /* All sets will be of size N */
228 char *SetNew(void); /* A new set for element 0..N */
229 void SetFree(char*); /* Deallocate a set */
230 int SetAdd(char*,int); /* Add element to a set */
231 int SetUnion(char *,char *); /* A <- A U B, thru element N */
232 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
234 /********** From the file "struct.h" *************************************/
236 ** Principal data structures for the LEMON parser generator.
239 typedef enum {LEMON_FALSE
=0, LEMON_TRUE
} Boolean
;
241 /* Symbols (terminals and nonterminals) of the grammar are stored
242 ** in the following: */
255 const char *name
; /* Name of the symbol */
256 int index
; /* Index number for this symbol */
257 enum symbol_type type
; /* Symbols are all either TERMINALS or NTs */
258 struct rule
*rule
; /* Linked list of rules of this (if an NT) */
259 struct symbol
*fallback
; /* fallback token in case this token doesn't parse */
260 int prec
; /* Precedence if defined (-1 otherwise) */
261 enum e_assoc assoc
; /* Associativity if precedence is defined */
262 char *firstset
; /* First-set for all rules of this symbol */
263 Boolean lambda
; /* True if NT and can generate an empty string */
264 int useCnt
; /* Number of times used */
265 char *destructor
; /* Code which executes whenever this symbol is
266 ** popped from the stack during error processing */
267 int destLineno
; /* Line number for start of destructor. Set to
268 ** -1 for duplicate destructors. */
269 char *datatype
; /* The data type of information held by this
270 ** object. Only used if type==NONTERMINAL */
271 int dtnum
; /* The data type number. In the parser, the value
272 ** stack is a union. The .yy%d element of this
273 ** union is the correct data type for this object */
274 int bContent
; /* True if this symbol ever carries content - if
275 ** it is ever more than just syntax */
276 /* The following fields are used by MULTITERMINALs only */
277 int nsubsym
; /* Number of constituent symbols in the MULTI */
278 struct symbol
**subsym
; /* Array of constituent symbols */
281 /* Each production rule in the grammar is stored in the following
284 struct symbol
*lhs
; /* Left-hand side of the rule */
285 const char *lhsalias
; /* Alias for the LHS (NULL if none) */
286 int lhsStart
; /* True if left-hand side is the start symbol */
287 int ruleline
; /* Line number for the rule */
288 int nrhs
; /* Number of RHS symbols */
289 struct symbol
**rhs
; /* The RHS symbols */
290 const char **rhsalias
; /* An alias for each RHS symbol (NULL if none) */
291 int line
; /* Line number at which code begins */
292 const char *code
; /* The code executed when this rule is reduced */
293 const char *codePrefix
; /* Setup code before code[] above */
294 const char *codeSuffix
; /* Breakdown code after code[] above */
295 struct symbol
*precsym
; /* Precedence symbol for this rule */
296 int index
; /* An index number for this rule */
297 int iRule
; /* Rule number as used in the generated tables */
298 Boolean noCode
; /* True if this rule has no associated C code */
299 Boolean codeEmitted
; /* True if the code has been emitted already */
300 Boolean canReduce
; /* True if this rule is ever reduced */
301 Boolean doesReduce
; /* Reduce actions occur after optimization */
302 Boolean neverReduce
; /* Reduce is theoretically possible, but prevented
303 ** by actions or other outside implementation */
304 struct rule
*nextlhs
; /* Next rule with the same LHS */
305 struct rule
*next
; /* Next rule in the global list */
308 /* A configuration is a production rule of the grammar together with
309 ** a mark (dot) showing how much of that rule has been processed so far.
310 ** Configurations also contain a follow-set which is a list of terminal
311 ** symbols which are allowed to immediately follow the end of the rule.
312 ** Every configuration is recorded as an instance of the following: */
318 struct rule
*rp
; /* The rule upon which the configuration is based */
319 int dot
; /* The parse point */
320 char *fws
; /* Follow-set for this configuration only */
321 struct plink
*fplp
; /* Follow-set forward propagation links */
322 struct plink
*bplp
; /* Follow-set backwards propagation links */
323 struct state
*stp
; /* Pointer to state which contains this */
324 enum cfgstatus status
; /* used during followset and shift computations */
325 struct config
*next
; /* Next configuration in the state */
326 struct config
*bp
; /* The next basis configuration */
334 SSCONFLICT
, /* A shift/shift conflict */
335 SRCONFLICT
, /* Was a reduce, but part of a conflict */
336 RRCONFLICT
, /* Was a reduce, but part of a conflict */
337 SH_RESOLVED
, /* Was a shift. Precedence resolved conflict */
338 RD_RESOLVED
, /* Was reduce. Precedence resolved conflict */
339 NOT_USED
, /* Deleted by compression */
340 SHIFTREDUCE
/* Shift first, then reduce */
343 /* Every shift or reduce operation is stored as one of the following */
345 struct symbol
*sp
; /* The look-ahead symbol */
348 struct state
*stp
; /* The new state, if a shift */
349 struct rule
*rp
; /* The rule, if a reduce */
351 struct symbol
*spOpt
; /* SHIFTREDUCE optimization to this symbol */
352 struct action
*next
; /* Next action for this state */
353 struct action
*collide
; /* Next action with the same hash */
356 /* Each state of the generated parser's finite state machine
357 ** is encoded as an instance of the following structure. */
359 struct config
*bp
; /* The basis configurations for this state */
360 struct config
*cfp
; /* All configurations in this set */
361 int statenum
; /* Sequential number for this state */
362 struct action
*ap
; /* List of actions for this state */
363 int nTknAct
, nNtAct
; /* Number of actions on terminals and nonterminals */
364 int iTknOfst
, iNtOfst
; /* yy_action[] offset for terminals and nonterms */
365 int iDfltReduce
; /* Default action is to REDUCE by this rule */
366 struct rule
*pDfltReduce
;/* The default REDUCE rule. */
367 int autoReduce
; /* True if this is an auto-reduce state */
369 #define NO_OFFSET (-2147483647)
371 /* A followset propagation link indicates that the contents of one
372 ** configuration followset should be propagated to another whenever
373 ** the first changes. */
375 struct config
*cfp
; /* The configuration to which linked */
376 struct plink
*next
; /* The next propagate link */
379 /* The state vector for the entire parser generator is recorded as
380 ** follows. (LEMON uses no global variables and makes little use of
381 ** static variables. Fields in the following structure can be thought
382 ** of as begin global variables in the program.) */
384 struct state
**sorted
; /* Table of states sorted by state number */
385 struct rule
*rule
; /* List of all rules */
386 struct rule
*startRule
; /* First rule */
387 int nstate
; /* Number of states */
388 int nxstate
; /* nstate with tail degenerate states removed */
389 int nrule
; /* Number of rules */
390 int nruleWithAction
; /* Number of rules with actions */
391 int nsymbol
; /* Number of terminal and nonterminal symbols */
392 int nterminal
; /* Number of terminal symbols */
393 int minShiftReduce
; /* Minimum shift-reduce action value */
394 int errAction
; /* Error action value */
395 int accAction
; /* Accept action value */
396 int noAction
; /* No-op action value */
397 int minReduce
; /* Minimum reduce action */
398 int maxAction
; /* Maximum action value of any kind */
399 struct symbol
**symbols
; /* Sorted array of pointers to symbols */
400 int errorcnt
; /* Number of errors */
401 struct symbol
*errsym
; /* The error symbol */
402 struct symbol
*wildcard
; /* Token that matches anything */
403 char *name
; /* Name of the generated parser */
404 char *arg
; /* Declaration of the 3rd argument to parser */
405 char *ctx
; /* Declaration of 2nd argument to constructor */
406 char *tokentype
; /* Type of terminal symbols in the parser stack */
407 char *vartype
; /* The default type of non-terminal symbols */
408 char *start
; /* Name of the start symbol for the grammar */
409 char *stacksize
; /* Size of the parser stack */
410 char *include
; /* Code to put at the start of the C file */
411 char *error
; /* Code to execute when an error is seen */
412 char *overflow
; /* Code to execute on a stack overflow */
413 char *failure
; /* Code to execute on parser failure */
414 char *accept
; /* Code to execute when the parser excepts */
415 char *extracode
; /* Code appended to the generated file */
416 char *tokendest
; /* Code to execute to destroy token data */
417 char *vardest
; /* Code for the default non-terminal destructor */
418 char *filename
; /* Name of the input file */
419 char *outname
; /* Name of the current output file */
420 char *tokenprefix
; /* A prefix added to token names in the .h file */
421 int nconflict
; /* Number of parsing conflicts */
422 int nactiontab
; /* Number of entries in the yy_action[] table */
423 int nlookaheadtab
; /* Number of entries in yy_lookahead[] */
424 int tablesize
; /* Total table size of all tables in bytes */
425 int basisflag
; /* Print only basis configurations */
426 int printPreprocessed
; /* Show preprocessor output on stdout */
427 int has_fallback
; /* True if any %fallback is seen in the grammar */
428 int nolinenosflag
; /* True if #line statements should not be printed */
429 char *argv0
; /* Name of the program */
432 #define MemoryCheck(X) if((X)==0){ \
433 extern void memory_error(); \
437 /**************** From the file "table.h" *********************************/
439 ** All code in this file has been automatically generated
440 ** from a specification in the file
442 ** by the associative array code building program "aagen".
443 ** Do not edit this file! Instead, edit the specification
444 ** file, then rerun aagen.
447 ** Code for processing tables in the LEMON parser generator.
449 /* Routines for handling a strings */
451 const char *Strsafe(const char *);
453 void Strsafe_init(void);
454 int Strsafe_insert(const char *);
455 const char *Strsafe_find(const char *);
457 /* Routines for handling symbols of the grammar */
459 struct symbol
*Symbol_new(const char *);
460 int Symbolcmpp(const void *, const void *);
461 void Symbol_init(void);
462 int Symbol_insert(struct symbol
*, const char *);
463 struct symbol
*Symbol_find(const char *);
464 struct symbol
*Symbol_Nth(int);
465 int Symbol_count(void);
466 struct symbol
**Symbol_arrayof(void);
468 /* Routines to manage the state table */
470 int Configcmp(const char *, const char *);
471 struct state
*State_new(void);
472 void State_init(void);
473 int State_insert(struct state
*, struct config
*);
474 struct state
*State_find(struct config
*);
475 struct state
**State_arrayof(void);
477 /* Routines used for efficiency in Configlist_add */
479 void Configtable_init(void);
480 int Configtable_insert(struct config
*);
481 struct config
*Configtable_find(struct config
*);
482 void Configtable_clear(int(*)(struct config
*));
484 /****************** From the file "action.c" *******************************/
486 ** Routines processing parser actions in the LEMON parser generator.
489 /* Allocate a new parser action */
490 static struct action
*Action_new(void){
491 static struct action
*actionfreelist
= 0;
492 struct action
*newaction
;
494 if( actionfreelist
==0 ){
497 actionfreelist
= (struct action
*)calloc(amt
, sizeof(struct action
));
498 if( actionfreelist
==0 ){
499 fprintf(stderr
,"Unable to allocate memory for a new parser action.");
502 for(i
=0; i
<amt
-1; i
++) actionfreelist
[i
].next
= &actionfreelist
[i
+1];
503 actionfreelist
[amt
-1].next
= 0;
505 newaction
= actionfreelist
;
506 actionfreelist
= actionfreelist
->next
;
510 /* Compare two actions for sorting purposes. Return negative, zero, or
511 ** positive if the first action is less than, equal to, or greater than
514 static int actioncmp(
519 rc
= ap1
->sp
->index
- ap2
->sp
->index
;
521 rc
= (int)ap1
->type
- (int)ap2
->type
;
523 if( rc
==0 && (ap1
->type
==REDUCE
|| ap1
->type
==SHIFTREDUCE
) ){
524 rc
= ap1
->x
.rp
->index
- ap2
->x
.rp
->index
;
527 rc
= (int) (ap2
- ap1
);
532 /* Sort parser actions */
533 static struct action
*Action_sort(
536 ap
= (struct action
*)msort((char *)ap
,(char **)&ap
->next
,
537 (int(*)(const char*,const char*))actioncmp
);
547 struct action
*newaction
;
548 newaction
= Action_new();
549 newaction
->next
= *app
;
551 newaction
->type
= type
;
553 newaction
->spOpt
= 0;
555 newaction
->x
.stp
= (struct state
*)arg
;
557 newaction
->x
.rp
= (struct rule
*)arg
;
560 /********************** New code to implement the "acttab" module ***********/
562 ** This module implements routines use to construct the yy_action[] table.
566 ** The state of the yy_action table under construction is an instance of
567 ** the following structure.
569 ** The yy_action table maps the pair (state_number, lookahead) into an
570 ** action_number. The table is an array of integers pairs. The state_number
571 ** determines an initial offset into the yy_action array. The lookahead
572 ** value is then added to this initial offset to get an index X into the
573 ** yy_action array. If the aAction[X].lookahead equals the value of the
574 ** of the lookahead input, then the value of the action_number output is
575 ** aAction[X].action. If the lookaheads do not match then the
576 ** default action for the state_number is returned.
578 ** All actions associated with a single state_number are first entered
579 ** into aLookahead[] using multiple calls to acttab_action(). Then the
580 ** actions for that single state_number are placed into the aAction[]
581 ** array with a single call to acttab_insert(). The acttab_insert() call
582 ** also resets the aLookahead[] array in preparation for the next
585 struct lookahead_action
{
586 int lookahead
; /* Value of the lookahead token */
587 int action
; /* Action to take on the given lookahead */
589 typedef struct acttab acttab
;
591 int nAction
; /* Number of used slots in aAction[] */
592 int nActionAlloc
; /* Slots allocated for aAction[] */
593 struct lookahead_action
594 *aAction
, /* The yy_action[] table under construction */
595 *aLookahead
; /* A single new transaction set */
596 int mnLookahead
; /* Minimum aLookahead[].lookahead */
597 int mnAction
; /* Action associated with mnLookahead */
598 int mxLookahead
; /* Maximum aLookahead[].lookahead */
599 int nLookahead
; /* Used slots in aLookahead[] */
600 int nLookaheadAlloc
; /* Slots allocated in aLookahead[] */
601 int nterminal
; /* Number of terminal symbols */
602 int nsymbol
; /* total number of symbols */
605 /* Return the number of entries in the yy_action table */
606 #define acttab_lookahead_size(X) ((X)->nAction)
608 /* The value for the N-th entry in yy_action */
609 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
611 /* The value for the N-th entry in yy_lookahead */
612 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
614 /* Free all memory associated with the given acttab */
615 void acttab_free(acttab
*p
){
617 free( p
->aLookahead
);
621 /* Allocate a new acttab structure */
622 acttab
*acttab_alloc(int nsymbol
, int nterminal
){
623 acttab
*p
= (acttab
*) calloc( 1, sizeof(*p
) );
625 fprintf(stderr
,"Unable to allocate memory for a new acttab.");
628 memset(p
, 0, sizeof(*p
));
629 p
->nsymbol
= nsymbol
;
630 p
->nterminal
= nterminal
;
634 /* Add a new action to the current transaction set.
636 ** This routine is called once for each lookahead for a particular
639 void acttab_action(acttab
*p
, int lookahead
, int action
){
640 if( p
->nLookahead
>=p
->nLookaheadAlloc
){
641 p
->nLookaheadAlloc
+= 25;
642 p
->aLookahead
= (struct lookahead_action
*) realloc( p
->aLookahead
,
643 sizeof(p
->aLookahead
[0])*p
->nLookaheadAlloc
);
644 if( p
->aLookahead
==0 ){
645 fprintf(stderr
,"malloc failed\n");
649 if( p
->nLookahead
==0 ){
650 p
->mxLookahead
= lookahead
;
651 p
->mnLookahead
= lookahead
;
652 p
->mnAction
= action
;
654 if( p
->mxLookahead
<lookahead
) p
->mxLookahead
= lookahead
;
655 if( p
->mnLookahead
>lookahead
){
656 p
->mnLookahead
= lookahead
;
657 p
->mnAction
= action
;
660 p
->aLookahead
[p
->nLookahead
].lookahead
= lookahead
;
661 p
->aLookahead
[p
->nLookahead
].action
= action
;
666 ** Add the transaction set built up with prior calls to acttab_action()
667 ** into the current action table. Then reset the transaction set back
668 ** to an empty set in preparation for a new round of acttab_action() calls.
670 ** Return the offset into the action table of the new transaction.
672 ** If the makeItSafe parameter is true, then the offset is chosen so that
673 ** it is impossible to overread the yy_lookaside[] table regardless of
674 ** the lookaside token. This is done for the terminal symbols, as they
675 ** come from external inputs and can contain syntax errors. When makeItSafe
676 ** is false, there is more flexibility in selecting offsets, resulting in
677 ** a smaller table. For non-terminal symbols, which are never syntax errors,
678 ** makeItSafe can be false.
680 int acttab_insert(acttab
*p
, int makeItSafe
){
682 assert( p
->nLookahead
>0 );
684 /* Make sure we have enough space to hold the expanded action table
685 ** in the worst case. The worst case occurs if the transaction set
686 ** must be appended to the current action table
689 if( p
->nAction
+ n
>= p
->nActionAlloc
){
690 int oldAlloc
= p
->nActionAlloc
;
691 p
->nActionAlloc
= p
->nAction
+ n
+ p
->nActionAlloc
+ 20;
692 p
->aAction
= (struct lookahead_action
*) realloc( p
->aAction
,
693 sizeof(p
->aAction
[0])*p
->nActionAlloc
);
695 fprintf(stderr
,"malloc failed\n");
698 for(i
=oldAlloc
; i
<p
->nActionAlloc
; i
++){
699 p
->aAction
[i
].lookahead
= -1;
700 p
->aAction
[i
].action
= -1;
704 /* Scan the existing action table looking for an offset that is a
705 ** duplicate of the current transaction set. Fall out of the loop
706 ** if and when the duplicate is found.
708 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
710 end
= makeItSafe
? p
->mnLookahead
: 0;
711 for(i
=p
->nAction
-1; i
>=end
; i
--){
712 if( p
->aAction
[i
].lookahead
==p
->mnLookahead
){
713 /* All lookaheads and actions in the aLookahead[] transaction
714 ** must match against the candidate aAction[i] entry. */
715 if( p
->aAction
[i
].action
!=p
->mnAction
) continue;
716 for(j
=0; j
<p
->nLookahead
; j
++){
717 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
718 if( k
<0 || k
>=p
->nAction
) break;
719 if( p
->aLookahead
[j
].lookahead
!=p
->aAction
[k
].lookahead
) break;
720 if( p
->aLookahead
[j
].action
!=p
->aAction
[k
].action
) break;
722 if( j
<p
->nLookahead
) continue;
724 /* No possible lookahead value that is not in the aLookahead[]
725 ** transaction is allowed to match aAction[i] */
727 for(j
=0; j
<p
->nAction
; j
++){
728 if( p
->aAction
[j
].lookahead
<0 ) continue;
729 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) n
++;
731 if( n
==p
->nLookahead
){
732 break; /* An exact match is found at offset i */
737 /* If no existing offsets exactly match the current transaction, find an
738 ** an empty offset in the aAction[] table in which we can add the
739 ** aLookahead[] transaction.
742 /* Look for holes in the aAction[] table that fit the current
743 ** aLookahead[] transaction. Leave i set to the offset of the hole.
744 ** If no holes are found, i is left at p->nAction, which means the
745 ** transaction will be appended. */
746 i
= makeItSafe
? p
->mnLookahead
: 0;
747 for(; i
<p
->nActionAlloc
- p
->mxLookahead
; i
++){
748 if( p
->aAction
[i
].lookahead
<0 ){
749 for(j
=0; j
<p
->nLookahead
; j
++){
750 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
752 if( p
->aAction
[k
].lookahead
>=0 ) break;
754 if( j
<p
->nLookahead
) continue;
755 for(j
=0; j
<p
->nAction
; j
++){
756 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) break;
759 break; /* Fits in empty slots */
764 /* Insert transaction set at index i. */
767 for(j
=0; j
<p
->nLookahead
; j
++){
768 printf(" %d", p
->aLookahead
[j
].lookahead
);
770 printf(" inserted at %d\n", i
);
772 for(j
=0; j
<p
->nLookahead
; j
++){
773 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
774 p
->aAction
[k
] = p
->aLookahead
[j
];
775 if( k
>=p
->nAction
) p
->nAction
= k
+1;
777 if( makeItSafe
&& i
+p
->nterminal
>=p
->nAction
) p
->nAction
= i
+p
->nterminal
+1;
780 /* Return the offset that is added to the lookahead in order to get the
781 ** index into yy_action of the action */
782 return i
- p
->mnLookahead
;
786 ** Return the size of the action table without the trailing syntax error
789 int acttab_action_size(acttab
*p
){
791 while( n
>0 && p
->aAction
[n
-1].lookahead
<0 ){ n
--; }
795 /********************** From the file "build.c" *****************************/
797 ** Routines to construction the finite state machine for the LEMON
801 /* Find a precedence symbol of every rule in the grammar.
803 ** Those rules which have a precedence symbol coded in the input
804 ** grammar using the "[symbol]" construct will already have the
805 ** rp->precsym field filled. Other rules take as their precedence
806 ** symbol the first RHS symbol with a defined precedence. If there
807 ** are not RHS symbols with a defined precedence, the precedence
808 ** symbol field is left blank.
810 void FindRulePrecedences(struct lemon
*xp
)
813 for(rp
=xp
->rule
; rp
; rp
=rp
->next
){
814 if( rp
->precsym
==0 ){
816 for(i
=0; i
<rp
->nrhs
&& rp
->precsym
==0; i
++){
817 struct symbol
*sp
= rp
->rhs
[i
];
818 if( sp
->type
==MULTITERMINAL
){
819 for(j
=0; j
<sp
->nsubsym
; j
++){
820 if( sp
->subsym
[j
]->prec
>=0 ){
821 rp
->precsym
= sp
->subsym
[j
];
825 }else if( sp
->prec
>=0 ){
826 rp
->precsym
= rp
->rhs
[i
];
834 /* Find all nonterminals which will generate the empty string.
835 ** Then go back and compute the first sets of every nonterminal.
836 ** The first set is the set of all terminal symbols which can begin
837 ** a string generated by that nonterminal.
839 void FindFirstSets(struct lemon
*lemp
)
845 for(i
=0; i
<lemp
->nsymbol
; i
++){
846 lemp
->symbols
[i
]->lambda
= LEMON_FALSE
;
848 for(i
=lemp
->nterminal
; i
<lemp
->nsymbol
; i
++){
849 lemp
->symbols
[i
]->firstset
= SetNew();
852 /* First compute all lambdas */
855 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
856 if( rp
->lhs
->lambda
) continue;
857 for(i
=0; i
<rp
->nrhs
; i
++){
858 struct symbol
*sp
= rp
->rhs
[i
];
859 assert( sp
->type
==NONTERMINAL
|| sp
->lambda
==LEMON_FALSE
);
860 if( sp
->lambda
==LEMON_FALSE
) break;
863 rp
->lhs
->lambda
= LEMON_TRUE
;
869 /* Now compute all first sets */
871 struct symbol
*s1
, *s2
;
873 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
875 for(i
=0; i
<rp
->nrhs
; i
++){
877 if( s2
->type
==TERMINAL
){
878 progress
+= SetAdd(s1
->firstset
,s2
->index
);
880 }else if( s2
->type
==MULTITERMINAL
){
881 for(j
=0; j
<s2
->nsubsym
; j
++){
882 progress
+= SetAdd(s1
->firstset
,s2
->subsym
[j
]->index
);
886 if( s1
->lambda
==LEMON_FALSE
) break;
888 progress
+= SetUnion(s1
->firstset
,s2
->firstset
);
889 if( s2
->lambda
==LEMON_FALSE
) break;
897 /* Compute all LR(0) states for the grammar. Links
898 ** are added to between some states so that the LR(1) follow sets
899 ** can be computed later.
901 PRIVATE
struct state
*getstate(struct lemon
*); /* forward reference */
902 void FindStates(struct lemon
*lemp
)
909 /* Find the start symbol */
911 sp
= Symbol_find(lemp
->start
);
913 ErrorMsg(lemp
->filename
,0,
914 "The specified start symbol \"%s\" is not "
915 "in a nonterminal of the grammar. \"%s\" will be used as the start "
916 "symbol instead.",lemp
->start
,lemp
->startRule
->lhs
->name
);
918 sp
= lemp
->startRule
->lhs
;
921 sp
= lemp
->startRule
->lhs
;
924 /* Make sure the start symbol doesn't occur on the right-hand side of
925 ** any rule. Report an error if it does. (YACC would generate a new
926 ** start symbol in this case.) */
927 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
929 for(i
=0; i
<rp
->nrhs
; i
++){
930 if( rp
->rhs
[i
]==sp
){ /* FIX ME: Deal with multiterminals */
931 ErrorMsg(lemp
->filename
,0,
932 "The start symbol \"%s\" occurs on the "
933 "right-hand side of a rule. This will result in a parser which "
934 "does not work properly.",sp
->name
);
940 /* The basis configuration set for the first state
941 ** is all rules which have the start symbol as their
943 for(rp
=sp
->rule
; rp
; rp
=rp
->nextlhs
){
944 struct config
*newcfp
;
946 newcfp
= Configlist_addbasis(rp
,0);
947 SetAdd(newcfp
->fws
,0);
950 /* Compute the first state. All other states will be
951 ** computed automatically during the computation of the first one.
952 ** The returned pointer to the first state is not used. */
953 (void)getstate(lemp
);
957 /* Return a pointer to a state which is described by the configuration
958 ** list which has been built from calls to Configlist_add.
960 PRIVATE
void buildshifts(struct lemon
*, struct state
*); /* Forwd ref */
961 PRIVATE
struct state
*getstate(struct lemon
*lemp
)
963 struct config
*cfp
, *bp
;
966 /* Extract the sorted basis of the new state. The basis was constructed
967 ** by prior calls to "Configlist_addbasis()". */
968 Configlist_sortbasis();
969 bp
= Configlist_basis();
971 /* Get a state with the same basis */
972 stp
= State_find(bp
);
974 /* A state with the same basis already exists! Copy all the follow-set
975 ** propagation links from the state under construction into the
976 ** preexisting state, then return a pointer to the preexisting state */
977 struct config
*x
, *y
;
978 for(x
=bp
, y
=stp
->bp
; x
&& y
; x
=x
->bp
, y
=y
->bp
){
979 Plink_copy(&y
->bplp
,x
->bplp
);
980 Plink_delete(x
->fplp
);
981 x
->fplp
= x
->bplp
= 0;
983 cfp
= Configlist_return();
986 /* This really is a new state. Construct all the details */
987 Configlist_closure(lemp
); /* Compute the configuration closure */
988 Configlist_sort(); /* Sort the configuration closure */
989 cfp
= Configlist_return(); /* Get a pointer to the config list */
990 stp
= State_new(); /* A new state structure */
992 stp
->bp
= bp
; /* Remember the configuration basis */
993 stp
->cfp
= cfp
; /* Remember the configuration closure */
994 stp
->statenum
= lemp
->nstate
++; /* Every state gets a sequence number */
995 stp
->ap
= 0; /* No actions, yet. */
996 State_insert(stp
,stp
->bp
); /* Add to the state table */
997 buildshifts(lemp
,stp
); /* Recursively compute successor states */
1003 ** Return true if two symbols are the same.
1005 int same_symbol(struct symbol
*a
, struct symbol
*b
)
1008 if( a
==b
) return 1;
1009 if( a
->type
!=MULTITERMINAL
) return 0;
1010 if( b
->type
!=MULTITERMINAL
) return 0;
1011 if( a
->nsubsym
!=b
->nsubsym
) return 0;
1012 for(i
=0; i
<a
->nsubsym
; i
++){
1013 if( a
->subsym
[i
]!=b
->subsym
[i
] ) return 0;
1018 /* Construct all successor states to the given state. A "successor"
1019 ** state is any state which can be reached by a shift action.
1021 PRIVATE
void buildshifts(struct lemon
*lemp
, struct state
*stp
)
1023 struct config
*cfp
; /* For looping thru the config closure of "stp" */
1024 struct config
*bcfp
; /* For the inner loop on config closure of "stp" */
1025 struct config
*newcfg
; /* */
1026 struct symbol
*sp
; /* Symbol following the dot in configuration "cfp" */
1027 struct symbol
*bsp
; /* Symbol following the dot in configuration "bcfp" */
1028 struct state
*newstp
; /* A pointer to a successor state */
1030 /* Each configuration becomes complete after it contributes to a successor
1031 ** state. Initially, all configurations are incomplete */
1032 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
) cfp
->status
= INCOMPLETE
;
1034 /* Loop through all configurations of the state "stp" */
1035 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1036 if( cfp
->status
==COMPLETE
) continue; /* Already used by inner loop */
1037 if( cfp
->dot
>=cfp
->rp
->nrhs
) continue; /* Can't shift this config */
1038 Configlist_reset(); /* Reset the new config set */
1039 sp
= cfp
->rp
->rhs
[cfp
->dot
]; /* Symbol after the dot */
1041 /* For every configuration in the state "stp" which has the symbol "sp"
1042 ** following its dot, add the same configuration to the basis set under
1043 ** construction but with the dot shifted one symbol to the right. */
1044 for(bcfp
=cfp
; bcfp
; bcfp
=bcfp
->next
){
1045 if( bcfp
->status
==COMPLETE
) continue; /* Already used */
1046 if( bcfp
->dot
>=bcfp
->rp
->nrhs
) continue; /* Can't shift this one */
1047 bsp
= bcfp
->rp
->rhs
[bcfp
->dot
]; /* Get symbol after dot */
1048 if( !same_symbol(bsp
,sp
) ) continue; /* Must be same as for "cfp" */
1049 bcfp
->status
= COMPLETE
; /* Mark this config as used */
1050 newcfg
= Configlist_addbasis(bcfp
->rp
,bcfp
->dot
+1);
1051 Plink_add(&newcfg
->bplp
,bcfp
);
1054 /* Get a pointer to the state described by the basis configuration set
1055 ** constructed in the preceding loop */
1056 newstp
= getstate(lemp
);
1058 /* The state "newstp" is reached from the state "stp" by a shift action
1059 ** on the symbol "sp" */
1060 if( sp
->type
==MULTITERMINAL
){
1062 for(i
=0; i
<sp
->nsubsym
; i
++){
1063 Action_add(&stp
->ap
,SHIFT
,sp
->subsym
[i
],(char*)newstp
);
1066 Action_add(&stp
->ap
,SHIFT
,sp
,(char *)newstp
);
1072 ** Construct the propagation links
1074 void FindLinks(struct lemon
*lemp
)
1077 struct config
*cfp
, *other
;
1081 /* Housekeeping detail:
1082 ** Add to every propagate link a pointer back to the state to
1083 ** which the link is attached. */
1084 for(i
=0; i
<lemp
->nstate
; i
++){
1085 stp
= lemp
->sorted
[i
];
1086 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1091 /* Convert all backlinks into forward links. Only the forward
1092 ** links are used in the follow-set computation. */
1093 for(i
=0; i
<lemp
->nstate
; i
++){
1094 stp
= lemp
->sorted
[i
];
1095 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1096 for(plp
=cfp
->bplp
; plp
; plp
=plp
->next
){
1098 Plink_add(&other
->fplp
,cfp
);
1104 /* Compute all followsets.
1106 ** A followset is the set of all symbols which can come immediately
1107 ** after a configuration.
1109 void FindFollowSets(struct lemon
*lemp
)
1117 for(i
=0; i
<lemp
->nstate
; i
++){
1118 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1119 cfp
->status
= INCOMPLETE
;
1125 for(i
=0; i
<lemp
->nstate
; i
++){
1126 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1127 if( cfp
->status
==COMPLETE
) continue;
1128 for(plp
=cfp
->fplp
; plp
; plp
=plp
->next
){
1129 change
= SetUnion(plp
->cfp
->fws
,cfp
->fws
);
1131 plp
->cfp
->status
= INCOMPLETE
;
1135 cfp
->status
= COMPLETE
;
1141 static int resolve_conflict(struct action
*,struct action
*);
1143 /* Compute the reduce actions, and resolve conflicts.
1145 void FindActions(struct lemon
*lemp
)
1153 /* Add all of the reduce actions
1154 ** A reduce action is added for each element of the followset of
1155 ** a configuration which has its dot at the extreme right.
1157 for(i
=0; i
<lemp
->nstate
; i
++){ /* Loop over all states */
1158 stp
= lemp
->sorted
[i
];
1159 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){ /* Loop over all configurations */
1160 if( cfp
->rp
->nrhs
==cfp
->dot
){ /* Is dot at extreme right? */
1161 for(j
=0; j
<lemp
->nterminal
; j
++){
1162 if( SetFind(cfp
->fws
,j
) ){
1163 /* Add a reduce action to the state "stp" which will reduce by the
1164 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1165 Action_add(&stp
->ap
,REDUCE
,lemp
->symbols
[j
],(char *)cfp
->rp
);
1172 /* Add the accepting token */
1174 sp
= Symbol_find(lemp
->start
);
1175 if( sp
==0 ) sp
= lemp
->startRule
->lhs
;
1177 sp
= lemp
->startRule
->lhs
;
1179 /* Add to the first state (which is always the starting state of the
1180 ** finite state machine) an action to ACCEPT if the lookahead is the
1181 ** start nonterminal. */
1182 Action_add(&lemp
->sorted
[0]->ap
,ACCEPT
,sp
,0);
1184 /* Resolve conflicts */
1185 for(i
=0; i
<lemp
->nstate
; i
++){
1186 struct action
*ap
, *nap
;
1187 stp
= lemp
->sorted
[i
];
1188 /* assert( stp->ap ); */
1189 stp
->ap
= Action_sort(stp
->ap
);
1190 for(ap
=stp
->ap
; ap
&& ap
->next
; ap
=ap
->next
){
1191 for(nap
=ap
->next
; nap
&& nap
->sp
==ap
->sp
; nap
=nap
->next
){
1192 /* The two actions "ap" and "nap" have the same lookahead.
1193 ** Figure out which one should be used */
1194 lemp
->nconflict
+= resolve_conflict(ap
,nap
);
1199 /* Report an error for each rule that can never be reduced. */
1200 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->canReduce
= LEMON_FALSE
;
1201 for(i
=0; i
<lemp
->nstate
; i
++){
1203 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
1204 if( ap
->type
==REDUCE
) ap
->x
.rp
->canReduce
= LEMON_TRUE
;
1207 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
1208 if( rp
->canReduce
) continue;
1209 ErrorMsg(lemp
->filename
,rp
->ruleline
,"This rule can not be reduced.\n");
1214 /* Resolve a conflict between the two given actions. If the
1215 ** conflict can't be resolved, return non-zero.
1218 ** To resolve a conflict, first look to see if either action
1219 ** is on an error rule. In that case, take the action which
1220 ** is not associated with the error rule. If neither or both
1221 ** actions are associated with an error rule, then try to
1222 ** use precedence to resolve the conflict.
1224 ** If either action is a SHIFT, then it must be apx. This
1225 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1227 static int resolve_conflict(
1231 struct symbol
*spx
, *spy
;
1233 assert( apx
->sp
==apy
->sp
); /* Otherwise there would be no conflict */
1234 if( apx
->type
==SHIFT
&& apy
->type
==SHIFT
){
1235 apy
->type
= SSCONFLICT
;
1238 if( apx
->type
==SHIFT
&& apy
->type
==REDUCE
){
1240 spy
= apy
->x
.rp
->precsym
;
1241 if( spy
==0 || spx
->prec
<0 || spy
->prec
<0 ){
1242 /* Not enough precedence information. */
1243 apy
->type
= SRCONFLICT
;
1245 }else if( spx
->prec
>spy
->prec
){ /* higher precedence wins */
1246 apy
->type
= RD_RESOLVED
;
1247 }else if( spx
->prec
<spy
->prec
){
1248 apx
->type
= SH_RESOLVED
;
1249 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==RIGHT
){ /* Use operator */
1250 apy
->type
= RD_RESOLVED
; /* associativity */
1251 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==LEFT
){ /* to break tie */
1252 apx
->type
= SH_RESOLVED
;
1254 assert( spx
->prec
==spy
->prec
&& spx
->assoc
==NONE
);
1257 }else if( apx
->type
==REDUCE
&& apy
->type
==REDUCE
){
1258 spx
= apx
->x
.rp
->precsym
;
1259 spy
= apy
->x
.rp
->precsym
;
1260 if( spx
==0 || spy
==0 || spx
->prec
<0 ||
1261 spy
->prec
<0 || spx
->prec
==spy
->prec
){
1262 apy
->type
= RRCONFLICT
;
1264 }else if( spx
->prec
>spy
->prec
){
1265 apy
->type
= RD_RESOLVED
;
1266 }else if( spx
->prec
<spy
->prec
){
1267 apx
->type
= RD_RESOLVED
;
1271 apx
->type
==SH_RESOLVED
||
1272 apx
->type
==RD_RESOLVED
||
1273 apx
->type
==SSCONFLICT
||
1274 apx
->type
==SRCONFLICT
||
1275 apx
->type
==RRCONFLICT
||
1276 apy
->type
==SH_RESOLVED
||
1277 apy
->type
==RD_RESOLVED
||
1278 apy
->type
==SSCONFLICT
||
1279 apy
->type
==SRCONFLICT
||
1280 apy
->type
==RRCONFLICT
1282 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1283 ** REDUCEs on the list. If we reach this point it must be because
1284 ** the parser conflict had already been resolved. */
1288 /********************* From the file "configlist.c" *************************/
1290 ** Routines to processing a configuration list and building a state
1291 ** in the LEMON parser generator.
1294 static struct config
*freelist
= 0; /* List of free configurations */
1295 static struct config
*current
= 0; /* Top of list of configurations */
1296 static struct config
**currentend
= 0; /* Last on list of configs */
1297 static struct config
*basis
= 0; /* Top of list of basis configs */
1298 static struct config
**basisend
= 0; /* End of list of basis configs */
1300 /* Return a pointer to a new configuration */
1301 PRIVATE
struct config
*newconfig(void){
1302 struct config
*newcfg
;
1306 freelist
= (struct config
*)calloc( amt
, sizeof(struct config
) );
1308 fprintf(stderr
,"Unable to allocate memory for a new configuration.");
1311 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
1312 freelist
[amt
-1].next
= 0;
1315 freelist
= freelist
->next
;
1319 /* The configuration "old" is no longer used */
1320 PRIVATE
void deleteconfig(struct config
*old
)
1322 old
->next
= freelist
;
1326 /* Initialized the configuration list builder */
1327 void Configlist_init(void){
1329 currentend
= ¤t
;
1336 /* Initialized the configuration list builder */
1337 void Configlist_reset(void){
1339 currentend
= ¤t
;
1342 Configtable_clear(0);
1346 /* Add another configuration to the configuration list */
1347 struct config
*Configlist_add(
1348 struct rule
*rp
, /* The rule */
1349 int dot
/* Index into the RHS of the rule where the dot goes */
1351 struct config
*cfp
, model
;
1353 assert( currentend
!=0 );
1356 cfp
= Configtable_find(&model
);
1361 cfp
->fws
= SetNew();
1363 cfp
->fplp
= cfp
->bplp
= 0;
1367 currentend
= &cfp
->next
;
1368 Configtable_insert(cfp
);
1373 /* Add a basis configuration to the configuration list */
1374 struct config
*Configlist_addbasis(struct rule
*rp
, int dot
)
1376 struct config
*cfp
, model
;
1378 assert( basisend
!=0 );
1379 assert( currentend
!=0 );
1382 cfp
= Configtable_find(&model
);
1387 cfp
->fws
= SetNew();
1389 cfp
->fplp
= cfp
->bplp
= 0;
1393 currentend
= &cfp
->next
;
1395 basisend
= &cfp
->bp
;
1396 Configtable_insert(cfp
);
1401 /* Compute the closure of the configuration list */
1402 void Configlist_closure(struct lemon
*lemp
)
1404 struct config
*cfp
, *newcfp
;
1405 struct rule
*rp
, *newrp
;
1406 struct symbol
*sp
, *xsp
;
1409 assert( currentend
!=0 );
1410 for(cfp
=current
; cfp
; cfp
=cfp
->next
){
1413 if( dot
>=rp
->nrhs
) continue;
1415 if( sp
->type
==NONTERMINAL
){
1416 if( sp
->rule
==0 && sp
!=lemp
->errsym
){
1417 ErrorMsg(lemp
->filename
,rp
->line
,"Nonterminal \"%s\" has no rules.",
1421 for(newrp
=sp
->rule
; newrp
; newrp
=newrp
->nextlhs
){
1422 newcfp
= Configlist_add(newrp
,0);
1423 for(i
=dot
+1; i
<rp
->nrhs
; i
++){
1425 if( xsp
->type
==TERMINAL
){
1426 SetAdd(newcfp
->fws
,xsp
->index
);
1428 }else if( xsp
->type
==MULTITERMINAL
){
1430 for(k
=0; k
<xsp
->nsubsym
; k
++){
1431 SetAdd(newcfp
->fws
, xsp
->subsym
[k
]->index
);
1435 SetUnion(newcfp
->fws
,xsp
->firstset
);
1436 if( xsp
->lambda
==LEMON_FALSE
) break;
1439 if( i
==rp
->nrhs
) Plink_add(&cfp
->fplp
,newcfp
);
1446 /* Sort the configuration list */
1447 void Configlist_sort(void){
1448 current
= (struct config
*)msort((char*)current
,(char**)&(current
->next
),
1454 /* Sort the basis configuration list */
1455 void Configlist_sortbasis(void){
1456 basis
= (struct config
*)msort((char*)current
,(char**)&(current
->bp
),
1462 /* Return a pointer to the head of the configuration list and
1463 ** reset the list */
1464 struct config
*Configlist_return(void){
1472 /* Return a pointer to the head of the configuration list and
1473 ** reset the list */
1474 struct config
*Configlist_basis(void){
1482 /* Free all elements of the given configuration list */
1483 void Configlist_eat(struct config
*cfp
)
1485 struct config
*nextcfp
;
1486 for(; cfp
; cfp
=nextcfp
){
1487 nextcfp
= cfp
->next
;
1488 assert( cfp
->fplp
==0 );
1489 assert( cfp
->bplp
==0 );
1490 if( cfp
->fws
) SetFree(cfp
->fws
);
1495 /***************** From the file "error.c" *********************************/
1497 ** Code for printing error message.
1500 void ErrorMsg(const char *filename
, int lineno
, const char *format
, ...){
1502 fprintf(stderr
, "%s:%d: ", filename
, lineno
);
1503 va_start(ap
, format
);
1504 vfprintf(stderr
,format
,ap
);
1506 fprintf(stderr
, "\n");
1508 /**************** From the file "main.c" ************************************/
1510 ** Main program file for the LEMON parser generator.
1513 /* Report an out-of-memory condition and abort. This function
1514 ** is used mostly by the "MemoryCheck" macro in struct.h
1516 void memory_error(void){
1517 fprintf(stderr
,"Out of memory. Aborting...\n");
1521 static int nDefine
= 0; /* Number of -D options on the command line */
1522 static char **azDefine
= 0; /* Name of the -D macros */
1524 /* This routine is called with the argument to each -D command-line option.
1525 ** Add the macro defined to the azDefine array.
1527 static void handle_D_option(char *z
){
1530 azDefine
= (char **) realloc(azDefine
, sizeof(azDefine
[0])*nDefine
);
1532 fprintf(stderr
,"out of memory\n");
1535 paz
= &azDefine
[nDefine
-1];
1536 *paz
= (char *) malloc( lemonStrlen(z
)+1 );
1538 fprintf(stderr
,"out of memory\n");
1541 lemon_strcpy(*paz
, z
);
1542 for(z
=*paz
; *z
&& *z
!='='; z
++){}
1546 /* Rember the name of the output directory
1548 static char *outputDir
= NULL
;
1549 static void handle_d_option(char *z
){
1550 outputDir
= (char *) malloc( lemonStrlen(z
)+1 );
1552 fprintf(stderr
,"out of memory\n");
1555 lemon_strcpy(outputDir
, z
);
1558 static char *user_templatename
= NULL
;
1559 static void handle_T_option(char *z
){
1560 user_templatename
= (char *) malloc( lemonStrlen(z
)+1 );
1561 if( user_templatename
==0 ){
1564 lemon_strcpy(user_templatename
, z
);
1567 /* Merge together to lists of rules ordered by rule.iRule */
1568 static struct rule
*Rule_merge(struct rule
*pA
, struct rule
*pB
){
1569 struct rule
*pFirst
= 0;
1570 struct rule
**ppPrev
= &pFirst
;
1572 if( pA
->iRule
<pB
->iRule
){
1591 ** Sort a list of rules in order of increasing iRule value
1593 static struct rule
*Rule_sort(struct rule
*rp
){
1597 memset(x
, 0, sizeof(x
));
1601 for(i
=0; i
<sizeof(x
)/sizeof(x
[0])-1 && x
[i
]; i
++){
1602 rp
= Rule_merge(x
[i
], rp
);
1609 for(i
=0; i
<sizeof(x
)/sizeof(x
[0]); i
++){
1610 rp
= Rule_merge(x
[i
], rp
);
1615 /* forward reference */
1616 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
);
1618 /* Print a single line of the "Parser Stats" output
1620 static void stats_line(const char *zLabel
, int iValue
){
1621 int nLabel
= lemonStrlen(zLabel
);
1622 printf(" %s%.*s %5d\n", zLabel
,
1623 35-nLabel
, "................................",
1627 /* The main program. Parse the command line and do it... */
1628 int main(int argc
, char **argv
){
1629 static int version
= 0;
1630 static int rpflag
= 0;
1631 static int basisflag
= 0;
1632 static int compress
= 0;
1633 static int quiet
= 0;
1634 static int statistics
= 0;
1635 static int mhflag
= 0;
1636 static int nolinenosflag
= 0;
1637 static int noResort
= 0;
1638 static int sqlFlag
= 0;
1639 static int printPP
= 0;
1641 static struct s_options options
[] = {
1642 {OPT_FLAG
, "b", (char*)&basisflag
, "Print only the basis in report."},
1643 {OPT_FLAG
, "c", (char*)&compress
, "Don't compress the action table."},
1644 {OPT_FSTR
, "d", (char*)&handle_d_option
, "Output directory. Default '.'"},
1645 {OPT_FSTR
, "D", (char*)handle_D_option
, "Define an %ifdef macro."},
1646 {OPT_FLAG
, "E", (char*)&printPP
, "Print input file after preprocessing."},
1647 {OPT_FSTR
, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1648 {OPT_FLAG
, "g", (char*)&rpflag
, "Print grammar without actions."},
1649 {OPT_FSTR
, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1650 {OPT_FLAG
, "m", (char*)&mhflag
, "Output a makeheaders compatible file."},
1651 {OPT_FLAG
, "l", (char*)&nolinenosflag
, "Do not print #line statements."},
1652 {OPT_FSTR
, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1653 {OPT_FLAG
, "p", (char*)&showPrecedenceConflict
,
1654 "Show conflicts resolved by precedence rules"},
1655 {OPT_FLAG
, "q", (char*)&quiet
, "(Quiet) Don't print the report file."},
1656 {OPT_FLAG
, "r", (char*)&noResort
, "Do not sort or renumber states"},
1657 {OPT_FLAG
, "s", (char*)&statistics
,
1658 "Print parser stats to standard output."},
1659 {OPT_FLAG
, "S", (char*)&sqlFlag
,
1660 "Generate the *.sql file describing the parser tables."},
1661 {OPT_FLAG
, "x", (char*)&version
, "Print the version number."},
1662 {OPT_FSTR
, "T", (char*)handle_T_option
, "Specify a template file."},
1663 {OPT_FSTR
, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1672 OptInit(argv
,options
,stderr
);
1674 printf("Lemon version 1.0\n");
1677 if( OptNArgs()!=1 ){
1678 fprintf(stderr
,"Exactly one filename argument is required.\n");
1681 memset(&lem
, 0, sizeof(lem
));
1684 /* Initialize the machine */
1688 lem
.argv0
= argv
[0];
1689 lem
.filename
= OptArg(0);
1690 lem
.basisflag
= basisflag
;
1691 lem
.nolinenosflag
= nolinenosflag
;
1692 lem
.printPreprocessed
= printPP
;
1695 /* Parse the input file */
1697 if( lem
.printPreprocessed
|| lem
.errorcnt
) exit(lem
.errorcnt
);
1699 fprintf(stderr
,"Empty grammar.\n");
1702 lem
.errsym
= Symbol_find("error");
1704 /* Count and index the symbols of the grammar */
1705 Symbol_new("{default}");
1706 lem
.nsymbol
= Symbol_count();
1707 lem
.symbols
= Symbol_arrayof();
1708 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1709 qsort(lem
.symbols
,lem
.nsymbol
,sizeof(struct symbol
*), Symbolcmpp
);
1710 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1711 while( lem
.symbols
[i
-1]->type
==MULTITERMINAL
){ i
--; }
1712 assert( strcmp(lem
.symbols
[i
-1]->name
,"{default}")==0 );
1713 lem
.nsymbol
= i
- 1;
1714 for(i
=1; ISUPPER(lem
.symbols
[i
]->name
[0]); i
++);
1717 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1718 ** reduce action C-code associated with them last, so that the switch()
1719 ** statement that selects reduction actions will have a smaller jump table.
1721 for(i
=0, rp
=lem
.rule
; rp
; rp
=rp
->next
){
1722 rp
->iRule
= rp
->code
? i
++ : -1;
1724 lem
.nruleWithAction
= i
;
1725 for(rp
=lem
.rule
; rp
; rp
=rp
->next
){
1726 if( rp
->iRule
<0 ) rp
->iRule
= i
++;
1728 lem
.startRule
= lem
.rule
;
1729 lem
.rule
= Rule_sort(lem
.rule
);
1731 /* Generate a reprint of the grammar, if requested on the command line */
1735 /* Initialize the size for all follow and first sets */
1736 SetSize(lem
.nterminal
+1);
1738 /* Find the precedence for every production rule (that has one) */
1739 FindRulePrecedences(&lem
);
1741 /* Compute the lambda-nonterminals and the first-sets for every
1743 FindFirstSets(&lem
);
1745 /* Compute all LR(0) states. Also record follow-set propagation
1746 ** links so that the follow-set can be computed later */
1749 lem
.sorted
= State_arrayof();
1751 /* Tie up loose ends on the propagation links */
1754 /* Compute the follow set of every reducible configuration */
1755 FindFollowSets(&lem
);
1757 /* Compute the action tables */
1760 /* Compress the action tables */
1761 if( compress
==0 ) CompressTables(&lem
);
1763 /* Reorder and renumber the states so that states with fewer choices
1764 ** occur at the end. This is an optimization that helps make the
1765 ** generated parser tables smaller. */
1766 if( noResort
==0 ) ResortStates(&lem
);
1768 /* Generate a report of the parser generated. (the "y.output" file) */
1769 if( !quiet
) ReportOutput(&lem
);
1771 /* Generate the source code for the parser */
1772 ReportTable(&lem
, mhflag
, sqlFlag
);
1774 /* Produce a header file for use by the scanner. (This step is
1775 ** omitted if the "-m" option is used because makeheaders will
1776 ** generate the file for us.) */
1777 if( !mhflag
) ReportHeader(&lem
);
1780 printf("Parser statistics:\n");
1781 stats_line("terminal symbols", lem
.nterminal
);
1782 stats_line("non-terminal symbols", lem
.nsymbol
- lem
.nterminal
);
1783 stats_line("total symbols", lem
.nsymbol
);
1784 stats_line("rules", lem
.nrule
);
1785 stats_line("states", lem
.nxstate
);
1786 stats_line("conflicts", lem
.nconflict
);
1787 stats_line("action table entries", lem
.nactiontab
);
1788 stats_line("lookahead table entries", lem
.nlookaheadtab
);
1789 stats_line("total table size (bytes)", lem
.tablesize
);
1791 if( lem
.nconflict
> 0 ){
1792 fprintf(stderr
,"%d parsing conflicts.\n",lem
.nconflict
);
1795 /* return 0 on success, 1 on failure. */
1796 exitcode
= ((lem
.errorcnt
> 0) || (lem
.nconflict
> 0)) ? 1 : 0;
1800 /******************** From the file "msort.c" *******************************/
1802 ** A generic merge-sort program.
1805 ** Let "ptr" be a pointer to some structure which is at the head of
1806 ** a null-terminated list. Then to sort the list call:
1808 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1810 ** In the above, "cmpfnc" is a pointer to a function which compares
1811 ** two instances of the structure and returns an integer, as in
1812 ** strcmp. The second argument is a pointer to the pointer to the
1813 ** second element of the linked list. This address is used to compute
1814 ** the offset to the "next" field within the structure. The offset to
1815 ** the "next" field must be constant for all structures in the list.
1817 ** The function returns a new pointer which is the head of the list
1825 ** Return a pointer to the next structure in the linked list.
1827 #define NEXT(A) (*(char**)(((char*)A)+offset))
1831 ** a: A sorted, null-terminated linked list. (May be null).
1832 ** b: A sorted, null-terminated linked list. (May be null).
1833 ** cmp: A pointer to the comparison function.
1834 ** offset: Offset in the structure to the "next" field.
1837 ** A pointer to the head of a sorted list containing the elements
1841 ** The "next" pointers for elements in the lists a and b are
1847 int (*cmp
)(const char*,const char*),
1857 if( (*cmp
)(a
,b
)<=0 ){
1866 if( (*cmp
)(a
,b
)<=0 ){
1876 if( a
) NEXT(ptr
) = a
;
1884 ** list: Pointer to a singly-linked list of structures.
1885 ** next: Pointer to pointer to the second element of the list.
1886 ** cmp: A comparison function.
1889 ** A pointer to the head of a sorted list containing the elements
1890 ** originally in list.
1893 ** The "next" pointers for elements in list are changed.
1899 int (*cmp
)(const char*,const char*)
1901 unsigned long offset
;
1903 char *set
[LISTSIZE
];
1905 offset
= (unsigned long)((char*)next
- (char*)list
);
1906 for(i
=0; i
<LISTSIZE
; i
++) set
[i
] = 0;
1911 for(i
=0; i
<LISTSIZE
-1 && set
[i
]!=0; i
++){
1912 ep
= merge(ep
,set
[i
],cmp
,offset
);
1918 for(i
=0; i
<LISTSIZE
; i
++) if( set
[i
] ) ep
= merge(set
[i
],ep
,cmp
,offset
);
1921 /************************ From the file "option.c" **************************/
1922 static char **g_argv
;
1923 static struct s_options
*op
;
1924 static FILE *errstream
;
1926 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1929 ** Print the command line with a carrot pointing to the k-th character
1930 ** of the n-th field.
1932 static void errline(int n
, int k
, FILE *err
)
1935 if( g_argv
[0] ) fprintf(err
,"%s",g_argv
[0]);
1936 spcnt
= lemonStrlen(g_argv
[0]) + 1;
1937 for(i
=1; i
<n
&& g_argv
[i
]; i
++){
1938 fprintf(err
," %s",g_argv
[i
]);
1939 spcnt
+= lemonStrlen(g_argv
[i
])+1;
1942 for(; g_argv
[i
]; i
++) fprintf(err
," %s",g_argv
[i
]);
1944 fprintf(err
,"\n%*s^-- here\n",spcnt
,"");
1946 fprintf(err
,"\n%*shere --^\n",spcnt
-7,"");
1951 ** Return the index of the N-th non-switch argument. Return -1
1952 ** if N is out of range.
1954 static int argindex(int n
)
1958 if( g_argv
!=0 && *g_argv
!=0 ){
1959 for(i
=1; g_argv
[i
]; i
++){
1960 if( dashdash
|| !ISOPT(g_argv
[i
]) ){
1961 if( n
==0 ) return i
;
1964 if( strcmp(g_argv
[i
],"--")==0 ) dashdash
= 1;
1970 static char emsg
[] = "Command line syntax error: ";
1973 ** Process a flag command line argument.
1975 static int handleflags(int i
, FILE *err
)
1980 for(j
=0; op
[j
].label
; j
++){
1981 if( strncmp(&g_argv
[i
][1],op
[j
].label
,lemonStrlen(op
[j
].label
))==0 ) break;
1983 v
= g_argv
[i
][0]=='-' ? 1 : 0;
1984 if( op
[j
].label
==0 ){
1986 fprintf(err
,"%sundefined option.\n",emsg
);
1990 }else if( op
[j
].arg
==0 ){
1991 /* Ignore this option */
1992 }else if( op
[j
].type
==OPT_FLAG
){
1993 *((int*)op
[j
].arg
) = v
;
1994 }else if( op
[j
].type
==OPT_FFLAG
){
1995 (*(void(*)(int))(op
[j
].arg
))(v
);
1996 }else if( op
[j
].type
==OPT_FSTR
){
1997 (*(void(*)(char *))(op
[j
].arg
))(&g_argv
[i
][2]);
2000 fprintf(err
,"%smissing argument on switch.\n",emsg
);
2009 ** Process a command line switch which has an argument.
2011 static int handleswitch(int i
, FILE *err
)
2019 cp
= strchr(g_argv
[i
],'=');
2022 for(j
=0; op
[j
].label
; j
++){
2023 if( strcmp(g_argv
[i
],op
[j
].label
)==0 ) break;
2026 if( op
[j
].label
==0 ){
2028 fprintf(err
,"%sundefined option.\n",emsg
);
2034 switch( op
[j
].type
){
2038 fprintf(err
,"%soption requires an argument.\n",emsg
);
2045 dv
= strtod(cp
,&end
);
2049 "%sillegal character in floating-point argument.\n",emsg
);
2050 errline(i
,(int)((char*)end
-(char*)g_argv
[i
]),err
);
2057 lv
= strtol(cp
,&end
,0);
2060 fprintf(err
,"%sillegal character in integer argument.\n",emsg
);
2061 errline(i
,(int)((char*)end
-(char*)g_argv
[i
]),err
);
2071 switch( op
[j
].type
){
2076 *(double*)(op
[j
].arg
) = dv
;
2079 (*(void(*)(double))(op
[j
].arg
))(dv
);
2082 *(int*)(op
[j
].arg
) = lv
;
2085 (*(void(*)(int))(op
[j
].arg
))((int)lv
);
2088 *(char**)(op
[j
].arg
) = sv
;
2091 (*(void(*)(char *))(op
[j
].arg
))(sv
);
2098 int OptInit(char **a
, struct s_options
*o
, FILE *err
)
2104 if( g_argv
&& *g_argv
&& op
){
2106 for(i
=1; g_argv
[i
]; i
++){
2107 if( g_argv
[i
][0]=='+' || g_argv
[i
][0]=='-' ){
2108 errcnt
+= handleflags(i
,err
);
2109 }else if( strchr(g_argv
[i
],'=') ){
2110 errcnt
+= handleswitch(i
,err
);
2115 fprintf(err
,"Valid command line options for \"%s\" are:\n",*a
);
2126 if( g_argv
!=0 && g_argv
[0]!=0 ){
2127 for(i
=1; g_argv
[i
]; i
++){
2128 if( dashdash
|| !ISOPT(g_argv
[i
]) ) cnt
++;
2129 if( strcmp(g_argv
[i
],"--")==0 ) dashdash
= 1;
2139 return i
>=0 ? g_argv
[i
] : 0;
2146 if( i
>=0 ) errline(i
,0,errstream
);
2149 void OptPrint(void){
2153 for(i
=0; op
[i
].label
; i
++){
2154 len
= lemonStrlen(op
[i
].label
) + 1;
2155 switch( op
[i
].type
){
2161 len
+= 9; /* length of "<integer>" */
2165 len
+= 6; /* length of "<real>" */
2169 len
+= 8; /* length of "<string>" */
2172 if( len
>max
) max
= len
;
2174 for(i
=0; op
[i
].label
; i
++){
2175 switch( op
[i
].type
){
2178 fprintf(errstream
," -%-*s %s\n",max
,op
[i
].label
,op
[i
].message
);
2182 fprintf(errstream
," -%s<integer>%*s %s\n",op
[i
].label
,
2183 (int)(max
-lemonStrlen(op
[i
].label
)-9),"",op
[i
].message
);
2187 fprintf(errstream
," -%s<real>%*s %s\n",op
[i
].label
,
2188 (int)(max
-lemonStrlen(op
[i
].label
)-6),"",op
[i
].message
);
2192 fprintf(errstream
," -%s<string>%*s %s\n",op
[i
].label
,
2193 (int)(max
-lemonStrlen(op
[i
].label
)-8),"",op
[i
].message
);
2198 /*********************** From the file "parse.c" ****************************/
2200 ** Input file parser for the LEMON parser generator.
2203 /* The state of the parser */
2206 WAITING_FOR_DECL_OR_RULE
,
2207 WAITING_FOR_DECL_KEYWORD
,
2208 WAITING_FOR_DECL_ARG
,
2209 WAITING_FOR_PRECEDENCE_SYMBOL
,
2219 RESYNC_AFTER_RULE_ERROR
,
2220 RESYNC_AFTER_DECL_ERROR
,
2221 WAITING_FOR_DESTRUCTOR_SYMBOL
,
2222 WAITING_FOR_DATATYPE_SYMBOL
,
2223 WAITING_FOR_FALLBACK_ID
,
2224 WAITING_FOR_WILDCARD_ID
,
2225 WAITING_FOR_CLASS_ID
,
2226 WAITING_FOR_CLASS_TOKEN
,
2227 WAITING_FOR_TOKEN_NAME
2230 char *filename
; /* Name of the input file */
2231 int tokenlineno
; /* Linenumber at which current token starts */
2232 int errorcnt
; /* Number of errors so far */
2233 char *tokenstart
; /* Text of current token */
2234 struct lemon
*gp
; /* Global state vector */
2235 enum e_state state
; /* The state of the parser */
2236 struct symbol
*fallback
; /* The fallback token */
2237 struct symbol
*tkclass
; /* Token class symbol */
2238 struct symbol
*lhs
; /* Left-hand side of current rule */
2239 const char *lhsalias
; /* Alias for the LHS */
2240 int nrhs
; /* Number of right-hand side symbols seen */
2241 struct symbol
*rhs
[MAXRHS
]; /* RHS symbols */
2242 const char *alias
[MAXRHS
]; /* Aliases for each RHS symbol (or NULL) */
2243 struct rule
*prevrule
; /* Previous rule parsed */
2244 const char *declkeyword
; /* Keyword of a declaration */
2245 char **declargslot
; /* Where the declaration argument should be put */
2246 int insertLineMacro
; /* Add #line before declaration insert */
2247 int *decllinenoslot
; /* Where to write declaration line number */
2248 enum e_assoc declassoc
; /* Assign this association to decl arguments */
2249 int preccounter
; /* Assign this precedence to decl arguments */
2250 struct rule
*firstrule
; /* Pointer to first rule in the grammar */
2251 struct rule
*lastrule
; /* Pointer to the most recently parsed rule */
2254 /* Parse a single token */
2255 static void parseonetoken(struct pstate
*psp
)
2258 x
= Strsafe(psp
->tokenstart
); /* Save the token permanently */
2260 printf("%s:%d: Token=[%s] state=%d\n",psp
->filename
,psp
->tokenlineno
,
2263 switch( psp
->state
){
2266 psp
->preccounter
= 0;
2267 psp
->firstrule
= psp
->lastrule
= 0;
2270 case WAITING_FOR_DECL_OR_RULE
:
2272 psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2273 }else if( ISLOWER(x
[0]) ){
2274 psp
->lhs
= Symbol_new(x
);
2277 psp
->state
= WAITING_FOR_ARROW
;
2278 }else if( x
[0]=='{' ){
2279 if( psp
->prevrule
==0 ){
2280 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2281 "There is no prior rule upon which to attach the code "
2282 "fragment which begins on this line.");
2284 }else if( psp
->prevrule
->code
!=0 ){
2285 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2286 "Code fragment beginning on this line is not the first "
2287 "to follow the previous rule.");
2289 }else if( strcmp(x
, "{NEVER-REDUCE")==0 ){
2290 psp
->prevrule
->neverReduce
= 1;
2292 psp
->prevrule
->line
= psp
->tokenlineno
;
2293 psp
->prevrule
->code
= &x
[1];
2294 psp
->prevrule
->noCode
= 0;
2296 }else if( x
[0]=='[' ){
2297 psp
->state
= PRECEDENCE_MARK_1
;
2299 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2300 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2305 case PRECEDENCE_MARK_1
:
2306 if( !ISUPPER(x
[0]) ){
2307 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2308 "The precedence symbol must be a terminal.");
2310 }else if( psp
->prevrule
==0 ){
2311 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2312 "There is no prior rule to assign precedence \"[%s]\".",x
);
2314 }else if( psp
->prevrule
->precsym
!=0 ){
2315 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2316 "Precedence mark on this line is not the first "
2317 "to follow the previous rule.");
2320 psp
->prevrule
->precsym
= Symbol_new(x
);
2322 psp
->state
= PRECEDENCE_MARK_2
;
2324 case PRECEDENCE_MARK_2
:
2326 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2327 "Missing \"]\" on precedence mark.");
2330 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2332 case WAITING_FOR_ARROW
:
2333 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2334 psp
->state
= IN_RHS
;
2335 }else if( x
[0]=='(' ){
2336 psp
->state
= LHS_ALIAS_1
;
2338 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2339 "Expected to see a \":\" following the LHS symbol \"%s\".",
2342 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2346 if( ISALPHA(x
[0]) ){
2348 psp
->state
= LHS_ALIAS_2
;
2350 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2351 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2354 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2359 psp
->state
= LHS_ALIAS_3
;
2361 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2362 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2364 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2368 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2369 psp
->state
= IN_RHS
;
2371 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2372 "Missing \"->\" following: \"%s(%s)\".",
2373 psp
->lhs
->name
,psp
->lhsalias
);
2375 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2381 rp
= (struct rule
*)calloc( sizeof(struct rule
) +
2382 sizeof(struct symbol
*)*psp
->nrhs
+ sizeof(char*)*psp
->nrhs
, 1);
2384 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2385 "Can't allocate enough memory for this rule.");
2390 rp
->ruleline
= psp
->tokenlineno
;
2391 rp
->rhs
= (struct symbol
**)&rp
[1];
2392 rp
->rhsalias
= (const char**)&(rp
->rhs
[psp
->nrhs
]);
2393 for(i
=0; i
<psp
->nrhs
; i
++){
2394 rp
->rhs
[i
] = psp
->rhs
[i
];
2395 rp
->rhsalias
[i
] = psp
->alias
[i
];
2396 if( rp
->rhsalias
[i
]!=0 ){ rp
->rhs
[i
]->bContent
= 1; }
2399 rp
->lhsalias
= psp
->lhsalias
;
2400 rp
->nrhs
= psp
->nrhs
;
2404 rp
->index
= psp
->gp
->nrule
++;
2405 rp
->nextlhs
= rp
->lhs
->rule
;
2408 if( psp
->firstrule
==0 ){
2409 psp
->firstrule
= psp
->lastrule
= rp
;
2411 psp
->lastrule
->next
= rp
;
2416 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2417 }else if( ISALPHA(x
[0]) ){
2418 if( psp
->nrhs
>=MAXRHS
){
2419 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2420 "Too many symbols on RHS of rule beginning at \"%s\".",
2423 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2425 psp
->rhs
[psp
->nrhs
] = Symbol_new(x
);
2426 psp
->alias
[psp
->nrhs
] = 0;
2429 }else if( (x
[0]=='|' || x
[0]=='/') && psp
->nrhs
>0 && ISUPPER(x
[1]) ){
2430 struct symbol
*msp
= psp
->rhs
[psp
->nrhs
-1];
2431 if( msp
->type
!=MULTITERMINAL
){
2432 struct symbol
*origsp
= msp
;
2433 msp
= (struct symbol
*) calloc(1,sizeof(*msp
));
2434 memset(msp
, 0, sizeof(*msp
));
2435 msp
->type
= MULTITERMINAL
;
2437 msp
->subsym
= (struct symbol
**) calloc(1,sizeof(struct symbol
*));
2438 msp
->subsym
[0] = origsp
;
2439 msp
->name
= origsp
->name
;
2440 psp
->rhs
[psp
->nrhs
-1] = msp
;
2443 msp
->subsym
= (struct symbol
**) realloc(msp
->subsym
,
2444 sizeof(struct symbol
*)*msp
->nsubsym
);
2445 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(&x
[1]);
2446 if( ISLOWER(x
[1]) || ISLOWER(msp
->subsym
[0]->name
[0]) ){
2447 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2448 "Cannot form a compound containing a non-terminal");
2451 }else if( x
[0]=='(' && psp
->nrhs
>0 ){
2452 psp
->state
= RHS_ALIAS_1
;
2454 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2455 "Illegal character on RHS of rule: \"%s\".",x
);
2457 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2461 if( ISALPHA(x
[0]) ){
2462 psp
->alias
[psp
->nrhs
-1] = x
;
2463 psp
->state
= RHS_ALIAS_2
;
2465 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2466 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2467 x
,psp
->rhs
[psp
->nrhs
-1]->name
);
2469 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2474 psp
->state
= IN_RHS
;
2476 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2477 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2479 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2482 case WAITING_FOR_DECL_KEYWORD
:
2483 if( ISALPHA(x
[0]) ){
2484 psp
->declkeyword
= x
;
2485 psp
->declargslot
= 0;
2486 psp
->decllinenoslot
= 0;
2487 psp
->insertLineMacro
= 1;
2488 psp
->state
= WAITING_FOR_DECL_ARG
;
2489 if( strcmp(x
,"name")==0 ){
2490 psp
->declargslot
= &(psp
->gp
->name
);
2491 psp
->insertLineMacro
= 0;
2492 }else if( strcmp(x
,"include")==0 ){
2493 psp
->declargslot
= &(psp
->gp
->include
);
2494 }else if( strcmp(x
,"code")==0 ){
2495 psp
->declargslot
= &(psp
->gp
->extracode
);
2496 }else if( strcmp(x
,"token_destructor")==0 ){
2497 psp
->declargslot
= &psp
->gp
->tokendest
;
2498 }else if( strcmp(x
,"default_destructor")==0 ){
2499 psp
->declargslot
= &psp
->gp
->vardest
;
2500 }else if( strcmp(x
,"token_prefix")==0 ){
2501 psp
->declargslot
= &psp
->gp
->tokenprefix
;
2502 psp
->insertLineMacro
= 0;
2503 }else if( strcmp(x
,"syntax_error")==0 ){
2504 psp
->declargslot
= &(psp
->gp
->error
);
2505 }else if( strcmp(x
,"parse_accept")==0 ){
2506 psp
->declargslot
= &(psp
->gp
->accept
);
2507 }else if( strcmp(x
,"parse_failure")==0 ){
2508 psp
->declargslot
= &(psp
->gp
->failure
);
2509 }else if( strcmp(x
,"stack_overflow")==0 ){
2510 psp
->declargslot
= &(psp
->gp
->overflow
);
2511 }else if( strcmp(x
,"extra_argument")==0 ){
2512 psp
->declargslot
= &(psp
->gp
->arg
);
2513 psp
->insertLineMacro
= 0;
2514 }else if( strcmp(x
,"extra_context")==0 ){
2515 psp
->declargslot
= &(psp
->gp
->ctx
);
2516 psp
->insertLineMacro
= 0;
2517 }else if( strcmp(x
,"token_type")==0 ){
2518 psp
->declargslot
= &(psp
->gp
->tokentype
);
2519 psp
->insertLineMacro
= 0;
2520 }else if( strcmp(x
,"default_type")==0 ){
2521 psp
->declargslot
= &(psp
->gp
->vartype
);
2522 psp
->insertLineMacro
= 0;
2523 }else if( strcmp(x
,"stack_size")==0 ){
2524 psp
->declargslot
= &(psp
->gp
->stacksize
);
2525 psp
->insertLineMacro
= 0;
2526 }else if( strcmp(x
,"start_symbol")==0 ){
2527 psp
->declargslot
= &(psp
->gp
->start
);
2528 psp
->insertLineMacro
= 0;
2529 }else if( strcmp(x
,"left")==0 ){
2531 psp
->declassoc
= LEFT
;
2532 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2533 }else if( strcmp(x
,"right")==0 ){
2535 psp
->declassoc
= RIGHT
;
2536 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2537 }else if( strcmp(x
,"nonassoc")==0 ){
2539 psp
->declassoc
= NONE
;
2540 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2541 }else if( strcmp(x
,"destructor")==0 ){
2542 psp
->state
= WAITING_FOR_DESTRUCTOR_SYMBOL
;
2543 }else if( strcmp(x
,"type")==0 ){
2544 psp
->state
= WAITING_FOR_DATATYPE_SYMBOL
;
2545 }else if( strcmp(x
,"fallback")==0 ){
2547 psp
->state
= WAITING_FOR_FALLBACK_ID
;
2548 }else if( strcmp(x
,"token")==0 ){
2549 psp
->state
= WAITING_FOR_TOKEN_NAME
;
2550 }else if( strcmp(x
,"wildcard")==0 ){
2551 psp
->state
= WAITING_FOR_WILDCARD_ID
;
2552 }else if( strcmp(x
,"token_class")==0 ){
2553 psp
->state
= WAITING_FOR_CLASS_ID
;
2555 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2556 "Unknown declaration keyword: \"%%%s\".",x
);
2558 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2561 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2562 "Illegal declaration keyword: \"%s\".",x
);
2564 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2567 case WAITING_FOR_DESTRUCTOR_SYMBOL
:
2568 if( !ISALPHA(x
[0]) ){
2569 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2570 "Symbol name missing after %%destructor keyword");
2572 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2574 struct symbol
*sp
= Symbol_new(x
);
2575 psp
->declargslot
= &sp
->destructor
;
2576 psp
->decllinenoslot
= &sp
->destLineno
;
2577 psp
->insertLineMacro
= 1;
2578 psp
->state
= WAITING_FOR_DECL_ARG
;
2581 case WAITING_FOR_DATATYPE_SYMBOL
:
2582 if( !ISALPHA(x
[0]) ){
2583 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2584 "Symbol name missing after %%type keyword");
2586 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2588 struct symbol
*sp
= Symbol_find(x
);
2589 if((sp
) && (sp
->datatype
)){
2590 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2591 "Symbol %%type \"%s\" already defined", x
);
2593 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2598 psp
->declargslot
= &sp
->datatype
;
2599 psp
->insertLineMacro
= 0;
2600 psp
->state
= WAITING_FOR_DECL_ARG
;
2604 case WAITING_FOR_PRECEDENCE_SYMBOL
:
2606 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2607 }else if( ISUPPER(x
[0]) ){
2611 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2612 "Symbol \"%s\" has already be given a precedence.",x
);
2615 sp
->prec
= psp
->preccounter
;
2616 sp
->assoc
= psp
->declassoc
;
2619 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2620 "Can't assign a precedence to \"%s\".",x
);
2624 case WAITING_FOR_DECL_ARG
:
2625 if( x
[0]=='{' || x
[0]=='\"' || ISALNUM(x
[0]) ){
2626 const char *zOld
, *zNew
;
2628 int nOld
, n
, nLine
= 0, nNew
, nBack
;
2632 if( zNew
[0]=='"' || zNew
[0]=='{' ) zNew
++;
2633 nNew
= lemonStrlen(zNew
);
2634 if( *psp
->declargslot
){
2635 zOld
= *psp
->declargslot
;
2639 nOld
= lemonStrlen(zOld
);
2640 n
= nOld
+ nNew
+ 20;
2641 addLineMacro
= !psp
->gp
->nolinenosflag
2642 && psp
->insertLineMacro
2643 && psp
->tokenlineno
>1
2644 && (psp
->decllinenoslot
==0 || psp
->decllinenoslot
[0]!=0);
2646 for(z
=psp
->filename
, nBack
=0; *z
; z
++){
2647 if( *z
=='\\' ) nBack
++;
2649 lemon_sprintf(zLine
, "#line %d ", psp
->tokenlineno
);
2650 nLine
= lemonStrlen(zLine
);
2651 n
+= nLine
+ lemonStrlen(psp
->filename
) + nBack
;
2653 *psp
->declargslot
= (char *) realloc(*psp
->declargslot
, n
);
2654 zBuf
= *psp
->declargslot
+ nOld
;
2656 if( nOld
&& zBuf
[-1]!='\n' ){
2659 memcpy(zBuf
, zLine
, nLine
);
2662 for(z
=psp
->filename
; *z
; z
++){
2671 if( psp
->decllinenoslot
&& psp
->decllinenoslot
[0]==0 ){
2672 psp
->decllinenoslot
[0] = psp
->tokenlineno
;
2674 memcpy(zBuf
, zNew
, nNew
);
2677 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2679 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2680 "Illegal argument to %%%s: %s",psp
->declkeyword
,x
);
2682 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2685 case WAITING_FOR_FALLBACK_ID
:
2687 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2688 }else if( !ISUPPER(x
[0]) ){
2689 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2690 "%%fallback argument \"%s\" should be a token", x
);
2693 struct symbol
*sp
= Symbol_new(x
);
2694 if( psp
->fallback
==0 ){
2696 }else if( sp
->fallback
){
2697 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2698 "More than one fallback assigned to token %s", x
);
2701 sp
->fallback
= psp
->fallback
;
2702 psp
->gp
->has_fallback
= 1;
2706 case WAITING_FOR_TOKEN_NAME
:
2707 /* Tokens do not have to be declared before use. But they can be
2708 ** in order to control their assigned integer number. The number for
2709 ** each token is assigned when it is first seen. So by including
2711 ** %token ONE TWO THREE.
2713 ** early in the grammar file, that assigns small consecutive values
2714 ** to each of the tokens ONE TWO and THREE.
2717 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2718 }else if( !ISUPPER(x
[0]) ){
2719 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2720 "%%token argument \"%s\" should be a token", x
);
2723 (void)Symbol_new(x
);
2726 case WAITING_FOR_WILDCARD_ID
:
2728 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2729 }else if( !ISUPPER(x
[0]) ){
2730 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2731 "%%wildcard argument \"%s\" should be a token", x
);
2734 struct symbol
*sp
= Symbol_new(x
);
2735 if( psp
->gp
->wildcard
==0 ){
2736 psp
->gp
->wildcard
= sp
;
2738 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2739 "Extra wildcard to token: %s", x
);
2744 case WAITING_FOR_CLASS_ID
:
2745 if( !ISLOWER(x
[0]) ){
2746 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2747 "%%token_class must be followed by an identifier: %s", x
);
2749 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2750 }else if( Symbol_find(x
) ){
2751 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2752 "Symbol \"%s\" already used", x
);
2754 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2756 psp
->tkclass
= Symbol_new(x
);
2757 psp
->tkclass
->type
= MULTITERMINAL
;
2758 psp
->state
= WAITING_FOR_CLASS_TOKEN
;
2761 case WAITING_FOR_CLASS_TOKEN
:
2763 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2764 }else if( ISUPPER(x
[0]) || ((x
[0]=='|' || x
[0]=='/') && ISUPPER(x
[1])) ){
2765 struct symbol
*msp
= psp
->tkclass
;
2767 msp
->subsym
= (struct symbol
**) realloc(msp
->subsym
,
2768 sizeof(struct symbol
*)*msp
->nsubsym
);
2769 if( !ISUPPER(x
[0]) ) x
++;
2770 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(x
);
2772 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2773 "%%token_class argument \"%s\" should be a token", x
);
2775 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2778 case RESYNC_AFTER_RULE_ERROR
:
2779 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2781 case RESYNC_AFTER_DECL_ERROR
:
2782 if( x
[0]=='.' ) psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2783 if( x
[0]=='%' ) psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2788 /* The text in the input is part of the argument to an %ifdef or %ifndef.
2789 ** Evaluate the text as a boolean expression. Return true or false.
2791 static int eval_preprocessor_boolean(char *z
, int lineno
){
2796 for(i
=0; z
[i
]!=0; i
++){
2797 if( ISSPACE(z
[i
]) ) continue;
2799 if( !okTerm
) goto pp_syntax_error
;
2803 if( z
[i
]=='|' && z
[i
+1]=='|' ){
2804 if( okTerm
) goto pp_syntax_error
;
2810 if( z
[i
]=='&' && z
[i
+1]=='&' ){
2811 if( okTerm
) goto pp_syntax_error
;
2812 if( !res
) return 0;
2820 if( !okTerm
) goto pp_syntax_error
;
2821 for(k
=i
+1; z
[k
]; k
++){
2826 res
= eval_preprocessor_boolean(&z
[i
+1], -1);
2830 goto pp_syntax_error
;
2835 }else if( z
[k
]=='(' ){
2837 }else if( z
[k
]==0 ){
2839 goto pp_syntax_error
;
2849 if( ISALPHA(z
[i
]) ){
2851 if( !okTerm
) goto pp_syntax_error
;
2852 for(k
=i
+1; ISALNUM(z
[k
]) || z
[k
]=='_'; k
++){}
2855 for(j
=0; j
<nDefine
; j
++){
2856 if( strncmp(azDefine
[j
],&z
[i
],n
)==0 && azDefine
[j
][n
]==0 ){
2869 goto pp_syntax_error
;
2875 fprintf(stderr
, "%%if syntax error on line %d.\n", lineno
);
2876 fprintf(stderr
, " %.*s <-- syntax error here\n", i
+1, z
);
2883 /* Run the preprocessor over the input file text. The global variables
2884 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2885 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2886 ** comments them out. Text in between is also commented out as appropriate.
2888 static void preprocess_input(char *z
){
2893 int start_lineno
= 1;
2894 for(i
=0; z
[i
]; i
++){
2895 if( z
[i
]=='\n' ) lineno
++;
2896 if( z
[i
]!='%' || (i
>0 && z
[i
-1]!='\n') ) continue;
2897 if( strncmp(&z
[i
],"%endif",6)==0 && ISSPACE(z
[i
+6]) ){
2901 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
2904 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2905 }else if( strncmp(&z
[i
],"%else",5)==0 && ISSPACE(z
[i
+5]) ){
2908 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
2909 }else if( exclude
==0 ){
2912 start_lineno
= lineno
;
2914 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2915 }else if( strncmp(&z
[i
],"%ifdef ",7)==0
2916 || strncmp(&z
[i
],"%if ",4)==0
2917 || strncmp(&z
[i
],"%ifndef ",8)==0 ){
2923 for(j
=i
; z
[j
] && !ISSPACE(z
[j
]); j
++){}
2926 while( z
[j
] && z
[j
]!='\n' ){ j
++; }
2929 exclude
= eval_preprocessor_boolean(&z
[iBool
], lineno
);
2931 if( !isNot
) exclude
= !exclude
;
2934 start_lineno
= lineno
;
2937 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2941 fprintf(stderr
,"unterminated %%ifdef starting on line %d\n", start_lineno
);
2946 /* In spite of its name, this function is really a scanner. It read
2947 ** in the entire input file (all at once) then tokenizes it. Each
2948 ** token is passed to the function "parseonetoken" which builds all
2949 ** the appropriate data structures in the global state vector "gp".
2951 void Parse(struct lemon
*gp
)
2956 unsigned int filesize
;
2962 memset(&ps
, '\0', sizeof(ps
));
2964 ps
.filename
= gp
->filename
;
2966 ps
.state
= INITIALIZE
;
2968 /* Begin by reading the input file */
2969 fp
= fopen(ps
.filename
,"rb");
2971 ErrorMsg(ps
.filename
,0,"Can't open this file for reading.");
2976 filesize
= ftell(fp
);
2978 filebuf
= (char *)malloc( filesize
+1 );
2979 if( filesize
>100000000 || filebuf
==0 ){
2980 ErrorMsg(ps
.filename
,0,"Input file too large.");
2986 if( fread(filebuf
,1,filesize
,fp
)!=filesize
){
2987 ErrorMsg(ps
.filename
,0,"Can't read in all %d bytes of this file.",
2995 filebuf
[filesize
] = 0;
2997 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2998 preprocess_input(filebuf
);
2999 if( gp
->printPreprocessed
){
3000 printf("%s\n", filebuf
);
3004 /* Now scan the text of the input file */
3006 for(cp
=filebuf
; (c
= *cp
)!=0; ){
3007 if( c
=='\n' ) lineno
++; /* Keep track of the line number */
3008 if( ISSPACE(c
) ){ cp
++; continue; } /* Skip all white space */
3009 if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments */
3011 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
3014 if( c
=='/' && cp
[1]=='*' ){ /* Skip C style comments */
3016 while( (c
= *cp
)!=0 && (c
!='/' || cp
[-1]!='*') ){
3017 if( c
=='\n' ) lineno
++;
3023 ps
.tokenstart
= cp
; /* Mark the beginning of the token */
3024 ps
.tokenlineno
= lineno
; /* Linenumber on which token begins */
3025 if( c
=='\"' ){ /* String literals */
3027 while( (c
= *cp
)!=0 && c
!='\"' ){
3028 if( c
=='\n' ) lineno
++;
3032 ErrorMsg(ps
.filename
,startline
,
3033 "String starting on this line is not terminated before "
3034 "the end of the file.");
3040 }else if( c
=='{' ){ /* A block of C code */
3043 for(level
=1; (c
= *cp
)!=0 && (level
>1 || c
!='}'); cp
++){
3044 if( c
=='\n' ) lineno
++;
3045 else if( c
=='{' ) level
++;
3046 else if( c
=='}' ) level
--;
3047 else if( c
=='/' && cp
[1]=='*' ){ /* Skip comments */
3051 while( (c
= *cp
)!=0 && (c
!='/' || prevc
!='*') ){
3052 if( c
=='\n' ) lineno
++;
3056 }else if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments too */
3058 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
3060 }else if( c
=='\'' || c
=='\"' ){ /* String a character literals */
3061 int startchar
, prevc
;
3064 for(cp
++; (c
= *cp
)!=0 && (c
!=startchar
|| prevc
=='\\'); cp
++){
3065 if( c
=='\n' ) lineno
++;
3066 if( prevc
=='\\' ) prevc
= 0;
3072 ErrorMsg(ps
.filename
,ps
.tokenlineno
,
3073 "C code starting on this line is not terminated before "
3074 "the end of the file.");
3080 }else if( ISALNUM(c
) ){ /* Identifiers */
3081 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
3083 }else if( c
==':' && cp
[1]==':' && cp
[2]=='=' ){ /* The operator "::=" */
3086 }else if( (c
=='/' || c
=='|') && ISALPHA(cp
[1]) ){
3088 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
3090 }else{ /* All other (one character) operators */
3095 *cp
= 0; /* Null terminate the token */
3096 parseonetoken(&ps
); /* Parse the token */
3097 *cp
= (char)c
; /* Restore the buffer */
3100 free(filebuf
); /* Release the buffer after parsing */
3101 gp
->rule
= ps
.firstrule
;
3102 gp
->errorcnt
= ps
.errorcnt
;
3104 /*************************** From the file "plink.c" *********************/
3106 ** Routines processing configuration follow-set propagation links
3107 ** in the LEMON parser generator.
3109 static struct plink
*plink_freelist
= 0;
3111 /* Allocate a new plink */
3112 struct plink
*Plink_new(void){
3113 struct plink
*newlink
;
3115 if( plink_freelist
==0 ){
3118 plink_freelist
= (struct plink
*)calloc( amt
, sizeof(struct plink
) );
3119 if( plink_freelist
==0 ){
3121 "Unable to allocate memory for a new follow-set propagation link.\n");
3124 for(i
=0; i
<amt
-1; i
++) plink_freelist
[i
].next
= &plink_freelist
[i
+1];
3125 plink_freelist
[amt
-1].next
= 0;
3127 newlink
= plink_freelist
;
3128 plink_freelist
= plink_freelist
->next
;
3132 /* Add a plink to a plink list */
3133 void Plink_add(struct plink
**plpp
, struct config
*cfp
)
3135 struct plink
*newlink
;
3136 newlink
= Plink_new();
3137 newlink
->next
= *plpp
;
3142 /* Transfer every plink on the list "from" to the list "to" */
3143 void Plink_copy(struct plink
**to
, struct plink
*from
)
3145 struct plink
*nextpl
;
3147 nextpl
= from
->next
;
3154 /* Delete every plink on the list */
3155 void Plink_delete(struct plink
*plp
)
3157 struct plink
*nextpl
;
3161 plp
->next
= plink_freelist
;
3162 plink_freelist
= plp
;
3166 /*********************** From the file "report.c" **************************/
3168 ** Procedures for generating reports and tables in the LEMON parser generator.
3171 /* Generate a filename with the given suffix. Space to hold the
3172 ** name comes from malloc() and must be freed by the calling
3175 PRIVATE
char *file_makename(struct lemon
*lemp
, const char *suffix
)
3179 char *filename
= lemp
->filename
;
3183 cp
= strrchr(filename
, '/');
3184 if( cp
) filename
= cp
+ 1;
3186 sz
= lemonStrlen(filename
);
3187 sz
+= lemonStrlen(suffix
);
3188 if( outputDir
) sz
+= lemonStrlen(outputDir
) + 1;
3190 name
= (char*)malloc( sz
);
3192 fprintf(stderr
,"Can't allocate space for a filename.\n");
3197 lemon_strcpy(name
, outputDir
);
3198 lemon_strcat(name
, "/");
3200 lemon_strcat(name
,filename
);
3201 cp
= strrchr(name
,'.');
3203 lemon_strcat(name
,suffix
);
3207 /* Open a file with a name based on the name of the input file,
3208 ** but with a different (specified) suffix, and return a pointer
3210 PRIVATE
FILE *file_open(
3217 if( lemp
->outname
) free(lemp
->outname
);
3218 lemp
->outname
= file_makename(lemp
, suffix
);
3219 fp
= fopen(lemp
->outname
,mode
);
3220 if( fp
==0 && *mode
=='w' ){
3221 fprintf(stderr
,"Can't open file \"%s\".\n",lemp
->outname
);
3228 /* Print the text of a rule
3230 void rule_print(FILE *out
, struct rule
*rp
){
3232 fprintf(out
, "%s",rp
->lhs
->name
);
3233 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3234 fprintf(out
," ::=");
3235 for(i
=0; i
<rp
->nrhs
; i
++){
3236 struct symbol
*sp
= rp
->rhs
[i
];
3237 if( sp
->type
==MULTITERMINAL
){
3238 fprintf(out
," %s", sp
->subsym
[0]->name
);
3239 for(j
=1; j
<sp
->nsubsym
; j
++){
3240 fprintf(out
,"|%s", sp
->subsym
[j
]->name
);
3243 fprintf(out
," %s", sp
->name
);
3245 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3249 /* Duplicate the input file without comments and without actions
3251 void Reprint(struct lemon
*lemp
)
3255 int i
, j
, maxlen
, len
, ncolumns
, skip
;
3256 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp
->filename
);
3258 for(i
=0; i
<lemp
->nsymbol
; i
++){
3259 sp
= lemp
->symbols
[i
];
3260 len
= lemonStrlen(sp
->name
);
3261 if( len
>maxlen
) maxlen
= len
;
3263 ncolumns
= 76/(maxlen
+5);
3264 if( ncolumns
<1 ) ncolumns
= 1;
3265 skip
= (lemp
->nsymbol
+ ncolumns
- 1)/ncolumns
;
3266 for(i
=0; i
<skip
; i
++){
3268 for(j
=i
; j
<lemp
->nsymbol
; j
+=skip
){
3269 sp
= lemp
->symbols
[j
];
3270 assert( sp
->index
==j
);
3271 printf(" %3d %-*.*s",j
,maxlen
,maxlen
,sp
->name
);
3275 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3276 rule_print(stdout
, rp
);
3278 if( rp
->precsym
) printf(" [%s]",rp
->precsym
->name
);
3279 /* if( rp->code ) printf("\n %s",rp->code); */
3284 /* Print a single rule.
3286 void RulePrint(FILE *fp
, struct rule
*rp
, int iCursor
){
3289 fprintf(fp
,"%s ::=",rp
->lhs
->name
);
3290 for(i
=0; i
<=rp
->nrhs
; i
++){
3291 if( i
==iCursor
) fprintf(fp
," *");
3292 if( i
==rp
->nrhs
) break;
3294 if( sp
->type
==MULTITERMINAL
){
3295 fprintf(fp
," %s", sp
->subsym
[0]->name
);
3296 for(j
=1; j
<sp
->nsubsym
; j
++){
3297 fprintf(fp
,"|%s",sp
->subsym
[j
]->name
);
3300 fprintf(fp
," %s", sp
->name
);
3305 /* Print the rule for a configuration.
3307 void ConfigPrint(FILE *fp
, struct config
*cfp
){
3308 RulePrint(fp
, cfp
->rp
, cfp
->dot
);
3314 PRIVATE
void SetPrint(out
,set
,lemp
)
3322 fprintf(out
,"%12s[","");
3323 for(i
=0; i
<lemp
->nterminal
; i
++){
3324 if( SetFind(set
,i
) ){
3325 fprintf(out
,"%s%s",spacer
,lemp
->symbols
[i
]->name
);
3332 /* Print a plink chain */
3333 PRIVATE
void PlinkPrint(out
,plp
,tag
)
3339 fprintf(out
,"%12s%s (state %2d) ","",tag
,plp
->cfp
->stp
->statenum
);
3340 ConfigPrint(out
,plp
->cfp
);
3347 /* Print an action to the given file descriptor. Return FALSE if
3348 ** nothing was actually printed.
3351 struct action
*ap
, /* The action to print */
3352 FILE *fp
, /* Print the action here */
3353 int indent
/* Indent by this amount */
3358 struct state
*stp
= ap
->x
.stp
;
3359 fprintf(fp
,"%*s shift %-7d",indent
,ap
->sp
->name
,stp
->statenum
);
3363 struct rule
*rp
= ap
->x
.rp
;
3364 fprintf(fp
,"%*s reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3365 RulePrint(fp
, rp
, -1);
3369 struct rule
*rp
= ap
->x
.rp
;
3370 fprintf(fp
,"%*s shift-reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3371 RulePrint(fp
, rp
, -1);
3375 fprintf(fp
,"%*s accept",indent
,ap
->sp
->name
);
3378 fprintf(fp
,"%*s error",indent
,ap
->sp
->name
);
3382 fprintf(fp
,"%*s reduce %-7d ** Parsing conflict **",
3383 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3386 fprintf(fp
,"%*s shift %-7d ** Parsing conflict **",
3387 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3390 if( showPrecedenceConflict
){
3391 fprintf(fp
,"%*s shift %-7d -- dropped by precedence",
3392 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3398 if( showPrecedenceConflict
){
3399 fprintf(fp
,"%*s reduce %-7d -- dropped by precedence",
3400 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3409 if( result
&& ap
->spOpt
){
3410 fprintf(fp
," /* because %s==%s */", ap
->sp
->name
, ap
->spOpt
->name
);
3415 /* Generate the "*.out" log file */
3416 void ReportOutput(struct lemon
*lemp
)
3425 fp
= file_open(lemp
,".out","wb");
3427 for(i
=0; i
<lemp
->nxstate
; i
++){
3428 stp
= lemp
->sorted
[i
];
3429 fprintf(fp
,"State %d:\n",stp
->statenum
);
3430 if( lemp
->basisflag
) cfp
=stp
->bp
;
3434 if( cfp
->dot
==cfp
->rp
->nrhs
){
3435 lemon_sprintf(buf
,"(%d)",cfp
->rp
->iRule
);
3436 fprintf(fp
," %5s ",buf
);
3440 ConfigPrint(fp
,cfp
);
3443 SetPrint(fp
,cfp
->fws
,lemp
);
3444 PlinkPrint(fp
,cfp
->fplp
,"To ");
3445 PlinkPrint(fp
,cfp
->bplp
,"From");
3447 if( lemp
->basisflag
) cfp
=cfp
->bp
;
3451 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3452 if( PrintAction(ap
,fp
,30) ) fprintf(fp
,"\n");
3456 fprintf(fp
, "----------------------------------------------------\n");
3457 fprintf(fp
, "Symbols:\n");
3458 fprintf(fp
, "The first-set of non-terminals is shown after the name.\n\n");
3459 for(i
=0; i
<lemp
->nsymbol
; i
++){
3463 sp
= lemp
->symbols
[i
];
3464 fprintf(fp
, " %3d: %s", i
, sp
->name
);
3465 if( sp
->type
==NONTERMINAL
){
3468 fprintf(fp
, " <lambda>");
3470 for(j
=0; j
<lemp
->nterminal
; j
++){
3471 if( sp
->firstset
&& SetFind(sp
->firstset
, j
) ){
3472 fprintf(fp
, " %s", lemp
->symbols
[j
]->name
);
3476 if( sp
->prec
>=0 ) fprintf(fp
," (precedence=%d)", sp
->prec
);
3479 fprintf(fp
, "----------------------------------------------------\n");
3480 fprintf(fp
, "Syntax-only Symbols:\n");
3481 fprintf(fp
, "The following symbols never carry semantic content.\n\n");
3482 for(i
=n
=0; i
<lemp
->nsymbol
; i
++){
3484 struct symbol
*sp
= lemp
->symbols
[i
];
3485 if( sp
->bContent
) continue;
3486 w
= (int)strlen(sp
->name
);
3487 if( n
>0 && n
+w
>75 ){
3495 fprintf(fp
, "%s", sp
->name
);
3498 if( n
>0 ) fprintf(fp
, "\n");
3499 fprintf(fp
, "----------------------------------------------------\n");
3500 fprintf(fp
, "Rules:\n");
3501 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3502 fprintf(fp
, "%4d: ", rp
->iRule
);
3506 fprintf(fp
," [%s precedence=%d]",
3507 rp
->precsym
->name
, rp
->precsym
->prec
);
3515 /* Search for the file "name" which is in the same directory as
3516 ** the executable */
3517 PRIVATE
char *pathsearch(char *argv0
, char *name
, int modemask
)
3519 const char *pathlist
;
3520 char *pathbufptr
= 0;
3526 cp
= strrchr(argv0
,'\\');
3528 cp
= strrchr(argv0
,'/');
3533 path
= (char *)malloc( lemonStrlen(argv0
) + lemonStrlen(name
) + 2 );
3534 if( path
) lemon_sprintf(path
,"%s/%s",argv0
,name
);
3537 pathlist
= getenv("PATH");
3538 if( pathlist
==0 ) pathlist
= ".:/bin:/usr/bin";
3539 pathbuf
= (char *) malloc( lemonStrlen(pathlist
) + 1 );
3540 path
= (char *)malloc( lemonStrlen(pathlist
)+lemonStrlen(name
)+2 );
3541 if( (pathbuf
!= 0) && (path
!=0) ){
3542 pathbufptr
= pathbuf
;
3543 lemon_strcpy(pathbuf
, pathlist
);
3545 cp
= strchr(pathbuf
,':');
3546 if( cp
==0 ) cp
= &pathbuf
[lemonStrlen(pathbuf
)];
3549 lemon_sprintf(path
,"%s/%s",pathbuf
,name
);
3551 if( c
==0 ) pathbuf
[0] = 0;
3552 else pathbuf
= &cp
[1];
3553 if( access(path
,modemask
)==0 ) break;
3561 /* Given an action, compute the integer value for that action
3562 ** which is to be put in the action table of the generated machine.
3563 ** Return negative if no action should be generated.
3565 PRIVATE
int compute_action(struct lemon
*lemp
, struct action
*ap
)
3569 case SHIFT
: act
= ap
->x
.stp
->statenum
; break;
3571 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3572 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3573 ** REDUCE action: */
3574 if( ap
->sp
->index
>=lemp
->nterminal
){
3575 act
= lemp
->minReduce
+ ap
->x
.rp
->iRule
;
3577 act
= lemp
->minShiftReduce
+ ap
->x
.rp
->iRule
;
3581 case REDUCE
: act
= lemp
->minReduce
+ ap
->x
.rp
->iRule
; break;
3582 case ERROR
: act
= lemp
->errAction
; break;
3583 case ACCEPT
: act
= lemp
->accAction
; break;
3584 default: act
= -1; break;
3589 #define LINESIZE 1000
3590 /* The next cluster of routines are for reading the template file
3591 ** and writing the results to the generated parser */
3592 /* The first function transfers data from "in" to "out" until
3593 ** a line is seen which begins with "%%". The line number is
3596 ** if name!=0, then any word that begin with "Parse" is changed to
3597 ** begin with *name instead.
3599 PRIVATE
void tplt_xfer(char *name
, FILE *in
, FILE *out
, int *lineno
)
3602 char line
[LINESIZE
];
3603 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3607 for(i
=0; line
[i
]; i
++){
3608 if( line
[i
]=='P' && strncmp(&line
[i
],"Parse",5)==0
3609 && (i
==0 || !ISALPHA(line
[i
-1]))
3611 if( i
>iStart
) fprintf(out
,"%.*s",i
-iStart
,&line
[iStart
]);
3612 fprintf(out
,"%s",name
);
3618 fprintf(out
,"%s",&line
[iStart
]);
3622 /* Skip forward past the header of the template file to the first "%%"
3624 PRIVATE
void tplt_skip_header(FILE *in
, int *lineno
)
3626 char line
[LINESIZE
];
3627 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3632 /* The next function finds the template file and opens it, returning
3633 ** a pointer to the opened file. */
3634 PRIVATE
FILE *tplt_open(struct lemon
*lemp
)
3636 static char templatename
[] = "lempar.c";
3643 /* first, see if user specified a template filename on the command line. */
3644 if (user_templatename
!= 0) {
3645 if( access(user_templatename
,004)==-1 ){
3646 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3651 in
= fopen(user_templatename
,"rb");
3653 fprintf(stderr
,"Can't open the template file \"%s\".\n",
3661 cp
= strrchr(lemp
->filename
,'.');
3663 lemon_sprintf(buf
,"%.*s.lt",(int)(cp
-lemp
->filename
),lemp
->filename
);
3665 lemon_sprintf(buf
,"%s.lt",lemp
->filename
);
3667 if( access(buf
,004)==0 ){
3669 }else if( access(templatename
,004)==0 ){
3670 tpltname
= templatename
;
3672 toFree
= tpltname
= pathsearch(lemp
->argv0
,templatename
,0);
3675 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3680 in
= fopen(tpltname
,"rb");
3682 fprintf(stderr
,"Can't open the template file \"%s\".\n",tpltname
);
3689 /* Print a #line directive line to the output file. */
3690 PRIVATE
void tplt_linedir(FILE *out
, int lineno
, char *filename
)
3692 fprintf(out
,"#line %d \"",lineno
);
3694 if( *filename
== '\\' ) putc('\\',out
);
3695 putc(*filename
,out
);
3698 fprintf(out
,"\"\n");
3701 /* Print a string to the file and keep the linenumber up to date */
3702 PRIVATE
void tplt_print(FILE *out
, struct lemon
*lemp
, char *str
, int *lineno
)
3704 if( str
==0 ) return;
3707 if( *str
=='\n' ) (*lineno
)++;
3710 if( str
[-1]!='\n' ){
3714 if (!lemp
->nolinenosflag
) {
3715 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3721 ** The following routine emits code for the destructor for the
3724 void emit_destructor_code(
3732 if( sp
->type
==TERMINAL
){
3733 cp
= lemp
->tokendest
;
3735 fprintf(out
,"{\n"); (*lineno
)++;
3736 }else if( sp
->destructor
){
3737 cp
= sp
->destructor
;
3738 fprintf(out
,"{\n"); (*lineno
)++;
3739 if( !lemp
->nolinenosflag
){
3741 tplt_linedir(out
,sp
->destLineno
,lemp
->filename
);
3743 }else if( lemp
->vardest
){
3746 fprintf(out
,"{\n"); (*lineno
)++;
3748 assert( 0 ); /* Cannot happen */
3751 if( *cp
=='$' && cp
[1]=='$' ){
3752 fprintf(out
,"(yypminor->yy%d)",sp
->dtnum
);
3756 if( *cp
=='\n' ) (*lineno
)++;
3759 fprintf(out
,"\n"); (*lineno
)++;
3760 if (!lemp
->nolinenosflag
) {
3761 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3763 fprintf(out
,"}\n"); (*lineno
)++;
3768 ** Return TRUE (non-zero) if the given symbol has a destructor.
3770 int has_destructor(struct symbol
*sp
, struct lemon
*lemp
)
3773 if( sp
->type
==TERMINAL
){
3774 ret
= lemp
->tokendest
!=0;
3776 ret
= lemp
->vardest
!=0 || sp
->destructor
!=0;
3782 ** Append text to a dynamically allocated string. If zText is 0 then
3783 ** reset the string to be empty again. Always return the complete text
3784 ** of the string (which is overwritten with each call).
3786 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3787 ** \000 terminator is stored. zText can contain up to two instances of
3788 ** %d. The values of p1 and p2 are written into the first and second
3791 ** If n==-1, then the previous character is overwritten.
3793 PRIVATE
char *append_str(const char *zText
, int n
, int p1
, int p2
){
3794 static char empty
[1] = { 0 };
3796 static int alloced
= 0;
3797 static int used
= 0;
3801 if( used
==0 && z
!=0 ) z
[0] = 0;
3810 n
= lemonStrlen(zText
);
3812 if( (int) (n
+sizeof(zInt
)*2+used
) >= alloced
){
3813 alloced
= n
+ sizeof(zInt
)*2 + used
+ 200;
3814 z
= (char *) realloc(z
, alloced
);
3816 if( z
==0 ) return empty
;
3819 if( c
=='%' && n
>0 && zText
[0]=='d' ){
3820 lemon_sprintf(zInt
, "%d", p1
);
3822 lemon_strcpy(&z
[used
], zInt
);
3823 used
+= lemonStrlen(&z
[used
]);
3827 z
[used
++] = (char)c
;
3835 ** Write and transform the rp->code string so that symbols are expanded.
3836 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3838 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3841 PRIVATE
int translate_code(struct lemon
*lemp
, struct rule
*rp
){
3844 int rc
= 0; /* True if yylhsminor is used */
3845 int dontUseRhs0
= 0; /* If true, use of left-most RHS label is illegal */
3846 const char *zSkip
= 0; /* The zOvwrt comment within rp->code, or NULL */
3847 char lhsused
= 0; /* True if the LHS element has been used */
3848 char lhsdirect
; /* True if LHS writes directly into stack */
3849 char used
[MAXRHS
]; /* True for each RHS element which is used */
3850 char zLhs
[50]; /* Convert the LHS symbol into this string */
3851 char zOvwrt
[900]; /* Comment that to allow LHS to overwrite RHS */
3853 for(i
=0; i
<rp
->nrhs
; i
++) used
[i
] = 0;
3857 static char newlinestr
[2] = { '\n', '\0' };
3858 rp
->code
= newlinestr
;
3859 rp
->line
= rp
->ruleline
;
3867 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3869 }else if( rp
->rhsalias
[0]==0 ){
3870 /* The left-most RHS symbol has no value. LHS direct is ok. But
3871 ** we have to call the destructor on the RHS symbol first. */
3873 if( has_destructor(rp
->rhs
[0],lemp
) ){
3874 append_str(0,0,0,0);
3875 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3876 rp
->rhs
[0]->index
,1-rp
->nrhs
);
3877 rp
->codePrefix
= Strsafe(append_str(0,0,0,0));
3880 }else if( rp
->lhsalias
==0 ){
3881 /* There is no LHS value symbol. */
3883 }else if( strcmp(rp
->lhsalias
,rp
->rhsalias
[0])==0 ){
3884 /* The LHS symbol and the left-most RHS symbol are the same, so
3885 ** direct writing is allowed */
3889 if( rp
->lhs
->dtnum
!=rp
->rhs
[0]->dtnum
){
3890 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3891 "%s(%s) and %s(%s) share the same label but have "
3892 "different datatypes.",
3893 rp
->lhs
->name
, rp
->lhsalias
, rp
->rhs
[0]->name
, rp
->rhsalias
[0]);
3897 lemon_sprintf(zOvwrt
, "/*%s-overwrites-%s*/",
3898 rp
->lhsalias
, rp
->rhsalias
[0]);
3899 zSkip
= strstr(rp
->code
, zOvwrt
);
3901 /* The code contains a special comment that indicates that it is safe
3902 ** for the LHS label to overwrite left-most RHS label. */
3909 sprintf(zLhs
, "yymsp[%d].minor.yy%d",1-rp
->nrhs
,rp
->lhs
->dtnum
);
3912 sprintf(zLhs
, "yylhsminor.yy%d",rp
->lhs
->dtnum
);
3915 append_str(0,0,0,0);
3917 /* This const cast is wrong but harmless, if we're careful. */
3918 for(cp
=(char *)rp
->code
; *cp
; cp
++){
3920 append_str(zOvwrt
,0,0,0);
3921 cp
+= lemonStrlen(zOvwrt
)-1;
3925 if( ISALPHA(*cp
) && (cp
==rp
->code
|| (!ISALNUM(cp
[-1]) && cp
[-1]!='_')) ){
3927 for(xp
= &cp
[1]; ISALNUM(*xp
) || *xp
=='_'; xp
++);
3930 if( rp
->lhsalias
&& strcmp(cp
,rp
->lhsalias
)==0 ){
3931 append_str(zLhs
,0,0,0);
3935 for(i
=0; i
<rp
->nrhs
; i
++){
3936 if( rp
->rhsalias
[i
] && strcmp(cp
,rp
->rhsalias
[i
])==0 ){
3937 if( i
==0 && dontUseRhs0
){
3938 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3939 "Label %s used after '%s'.",
3940 rp
->rhsalias
[0], zOvwrt
);
3942 }else if( cp
!=rp
->code
&& cp
[-1]=='@' ){
3943 /* If the argument is of the form @X then substituted
3944 ** the token number of X, not the value of X */
3945 append_str("yymsp[%d].major",-1,i
-rp
->nrhs
+1,0);
3947 struct symbol
*sp
= rp
->rhs
[i
];
3949 if( sp
->type
==MULTITERMINAL
){
3950 dtnum
= sp
->subsym
[0]->dtnum
;
3954 append_str("yymsp[%d].minor.yy%d",0,i
-rp
->nrhs
+1, dtnum
);
3964 append_str(cp
, 1, 0, 0);
3967 /* Main code generation completed */
3968 cp
= append_str(0,0,0,0);
3969 if( cp
&& cp
[0] ) rp
->code
= Strsafe(cp
);
3970 append_str(0,0,0,0);
3972 /* Check to make sure the LHS has been used */
3973 if( rp
->lhsalias
&& !lhsused
){
3974 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3975 "Label \"%s\" for \"%s(%s)\" is never used.",
3976 rp
->lhsalias
,rp
->lhs
->name
,rp
->lhsalias
);
3980 /* Generate destructor code for RHS minor values which are not referenced.
3981 ** Generate error messages for unused labels and duplicate labels.
3983 for(i
=0; i
<rp
->nrhs
; i
++){
3984 if( rp
->rhsalias
[i
] ){
3987 if( rp
->lhsalias
&& strcmp(rp
->lhsalias
,rp
->rhsalias
[i
])==0 ){
3988 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3989 "%s(%s) has the same label as the LHS but is not the left-most "
3990 "symbol on the RHS.",
3991 rp
->rhs
[i
]->name
, rp
->rhsalias
[i
]);
3995 if( rp
->rhsalias
[j
] && strcmp(rp
->rhsalias
[j
],rp
->rhsalias
[i
])==0 ){
3996 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3997 "Label %s used for multiple symbols on the RHS of a rule.",
4005 ErrorMsg(lemp
->filename
,rp
->ruleline
,
4006 "Label %s for \"%s(%s)\" is never used.",
4007 rp
->rhsalias
[i
],rp
->rhs
[i
]->name
,rp
->rhsalias
[i
]);
4010 }else if( i
>0 && has_destructor(rp
->rhs
[i
],lemp
) ){
4011 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
4012 rp
->rhs
[i
]->index
,i
-rp
->nrhs
+1);
4016 /* If unable to write LHS values directly into the stack, write the
4017 ** saved LHS value now. */
4019 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp
->nrhs
, rp
->lhs
->dtnum
);
4020 append_str(zLhs
, 0, 0, 0);
4021 append_str(";\n", 0, 0, 0);
4024 /* Suffix code generation complete */
4025 cp
= append_str(0,0,0,0);
4027 rp
->codeSuffix
= Strsafe(cp
);
4035 ** Generate code which executes when the rule "rp" is reduced. Write
4036 ** the code to "out". Make sure lineno stays up-to-date.
4038 PRIVATE
void emit_code(
4046 /* Setup code prior to the #line directive */
4047 if( rp
->codePrefix
&& rp
->codePrefix
[0] ){
4048 fprintf(out
, "{%s", rp
->codePrefix
);
4049 for(cp
=rp
->codePrefix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
4052 /* Generate code to do the reduce action */
4054 if( !lemp
->nolinenosflag
){
4056 tplt_linedir(out
,rp
->line
,lemp
->filename
);
4058 fprintf(out
,"{%s",rp
->code
);
4059 for(cp
=rp
->code
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
4060 fprintf(out
,"}\n"); (*lineno
)++;
4061 if( !lemp
->nolinenosflag
){
4063 tplt_linedir(out
,*lineno
,lemp
->outname
);
4067 /* Generate breakdown code that occurs after the #line directive */
4068 if( rp
->codeSuffix
&& rp
->codeSuffix
[0] ){
4069 fprintf(out
, "%s", rp
->codeSuffix
);
4070 for(cp
=rp
->codeSuffix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
4073 if( rp
->codePrefix
){
4074 fprintf(out
, "}\n"); (*lineno
)++;
4081 ** Print the definition of the union used for the parser's data stack.
4082 ** This union contains fields for every possible data type for tokens
4083 ** and nonterminals. In the process of computing and printing this
4084 ** union, also set the ".dtnum" field of every terminal and nonterminal
4087 void print_stack_union(
4088 FILE *out
, /* The output stream */
4089 struct lemon
*lemp
, /* The main info structure for this parser */
4090 int *plineno
, /* Pointer to the line number */
4091 int mhflag
/* True if generating makeheaders output */
4093 int lineno
= *plineno
; /* The line number of the output */
4094 char **types
; /* A hash table of datatypes */
4095 int arraysize
; /* Size of the "types" array */
4096 int maxdtlength
; /* Maximum length of any ".datatype" field. */
4097 char *stddt
; /* Standardized name for a datatype */
4098 int i
,j
; /* Loop counters */
4099 unsigned hash
; /* For hashing the name of a type */
4100 const char *name
; /* Name of the parser */
4102 /* Allocate and initialize types[] and allocate stddt[] */
4103 arraysize
= lemp
->nsymbol
* 2;
4104 types
= (char**)calloc( arraysize
, sizeof(char*) );
4106 fprintf(stderr
,"Out of memory.\n");
4109 for(i
=0; i
<arraysize
; i
++) types
[i
] = 0;
4111 if( lemp
->vartype
){
4112 maxdtlength
= lemonStrlen(lemp
->vartype
);
4114 for(i
=0; i
<lemp
->nsymbol
; i
++){
4116 struct symbol
*sp
= lemp
->symbols
[i
];
4117 if( sp
->datatype
==0 ) continue;
4118 len
= lemonStrlen(sp
->datatype
);
4119 if( len
>maxdtlength
) maxdtlength
= len
;
4121 stddt
= (char*)malloc( maxdtlength
*2 + 1 );
4123 fprintf(stderr
,"Out of memory.\n");
4127 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4128 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
4129 ** used for terminal symbols. If there is no %default_type defined then
4130 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4131 ** a datatype using the %type directive.
4133 for(i
=0; i
<lemp
->nsymbol
; i
++){
4134 struct symbol
*sp
= lemp
->symbols
[i
];
4136 if( sp
==lemp
->errsym
){
4137 sp
->dtnum
= arraysize
+1;
4140 if( sp
->type
!=NONTERMINAL
|| (sp
->datatype
==0 && lemp
->vartype
==0) ){
4145 if( cp
==0 ) cp
= lemp
->vartype
;
4147 while( ISSPACE(*cp
) ) cp
++;
4148 while( *cp
) stddt
[j
++] = *cp
++;
4149 while( j
>0 && ISSPACE(stddt
[j
-1]) ) j
--;
4151 if( lemp
->tokentype
&& strcmp(stddt
, lemp
->tokentype
)==0 ){
4156 for(j
=0; stddt
[j
]; j
++){
4157 hash
= hash
*53 + stddt
[j
];
4159 hash
= (hash
& 0x7fffffff)%arraysize
;
4160 while( types
[hash
] ){
4161 if( strcmp(types
[hash
],stddt
)==0 ){
4162 sp
->dtnum
= hash
+ 1;
4166 if( hash
>=(unsigned)arraysize
) hash
= 0;
4168 if( types
[hash
]==0 ){
4169 sp
->dtnum
= hash
+ 1;
4170 types
[hash
] = (char*)malloc( lemonStrlen(stddt
)+1 );
4171 if( types
[hash
]==0 ){
4172 fprintf(stderr
,"Out of memory.\n");
4175 lemon_strcpy(types
[hash
],stddt
);
4179 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4180 name
= lemp
->name
? lemp
->name
: "Parse";
4182 if( mhflag
){ fprintf(out
,"#if INTERFACE\n"); lineno
++; }
4183 fprintf(out
,"#define %sTOKENTYPE %s\n",name
,
4184 lemp
->tokentype
?lemp
->tokentype
:"void*"); lineno
++;
4185 if( mhflag
){ fprintf(out
,"#endif\n"); lineno
++; }
4186 fprintf(out
,"typedef union {\n"); lineno
++;
4187 fprintf(out
," int yyinit;\n"); lineno
++;
4188 fprintf(out
," %sTOKENTYPE yy0;\n",name
); lineno
++;
4189 for(i
=0; i
<arraysize
; i
++){
4190 if( types
[i
]==0 ) continue;
4191 fprintf(out
," %s yy%d;\n",types
[i
],i
+1); lineno
++;
4194 if( lemp
->errsym
&& lemp
->errsym
->useCnt
){
4195 fprintf(out
," int yy%d;\n",lemp
->errsym
->dtnum
); lineno
++;
4199 fprintf(out
,"} YYMINORTYPE;\n"); lineno
++;
4204 ** Return the name of a C datatype able to represent values between
4205 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4206 ** for that type (1, 2, or 4) into *pnByte.
4208 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
){
4209 const char *zType
= "int";
4213 zType
= "unsigned char";
4215 }else if( upr
<65535 ){
4216 zType
= "unsigned short int";
4219 zType
= "unsigned int";
4222 }else if( lwr
>=-127 && upr
<=127 ){
4223 zType
= "signed char";
4225 }else if( lwr
>=-32767 && upr
<32767 ){
4229 if( pnByte
) *pnByte
= nByte
;
4234 ** Each state contains a set of token transaction and a set of
4235 ** nonterminal transactions. Each of these sets makes an instance
4236 ** of the following structure. An array of these structures is used
4237 ** to order the creation of entries in the yy_action[] table.
4240 struct state
*stp
; /* A pointer to a state */
4241 int isTkn
; /* True to use tokens. False for non-terminals */
4242 int nAction
; /* Number of actions */
4243 int iOrder
; /* Original order of action sets */
4247 ** Compare to axset structures for sorting purposes
4249 static int axset_compare(const void *a
, const void *b
){
4250 struct axset
*p1
= (struct axset
*)a
;
4251 struct axset
*p2
= (struct axset
*)b
;
4253 c
= p2
->nAction
- p1
->nAction
;
4255 c
= p1
->iOrder
- p2
->iOrder
;
4257 assert( c
!=0 || p1
==p2
);
4262 ** Write text on "out" that describes the rule "rp".
4264 static void writeRuleText(FILE *out
, struct rule
*rp
){
4266 fprintf(out
,"%s ::=", rp
->lhs
->name
);
4267 for(j
=0; j
<rp
->nrhs
; j
++){
4268 struct symbol
*sp
= rp
->rhs
[j
];
4269 if( sp
->type
!=MULTITERMINAL
){
4270 fprintf(out
," %s", sp
->name
);
4273 fprintf(out
," %s", sp
->subsym
[0]->name
);
4274 for(k
=1; k
<sp
->nsubsym
; k
++){
4275 fprintf(out
,"|%s",sp
->subsym
[k
]->name
);
4282 /* Generate C source code for the parser */
4285 int mhflag
, /* Output in makeheaders format if true */
4286 int sqlFlag
/* Generate the *.sql file too */
4288 FILE *out
, *in
, *sql
;
4289 char line
[LINESIZE
];
4294 struct acttab
*pActtab
;
4297 int szActionType
; /* sizeof(YYACTIONTYPE) */
4298 int szCodeType
; /* sizeof(YYCODETYPE) */
4300 int mnTknOfst
, mxTknOfst
;
4301 int mnNtOfst
, mxNtOfst
;
4305 lemp
->minShiftReduce
= lemp
->nstate
;
4306 lemp
->errAction
= lemp
->minShiftReduce
+ lemp
->nrule
;
4307 lemp
->accAction
= lemp
->errAction
+ 1;
4308 lemp
->noAction
= lemp
->accAction
+ 1;
4309 lemp
->minReduce
= lemp
->noAction
+ 1;
4310 lemp
->maxAction
= lemp
->minReduce
+ lemp
->nrule
;
4312 in
= tplt_open(lemp
);
4314 out
= file_open(lemp
,".c","wb");
4322 sql
= file_open(lemp
, ".sql", "wb");
4330 "CREATE TABLE symbol(\n"
4331 " id INTEGER PRIMARY KEY,\n"
4332 " name TEXT NOT NULL,\n"
4333 " isTerminal BOOLEAN NOT NULL,\n"
4334 " fallback INTEGER REFERENCES symbol"
4335 " DEFERRABLE INITIALLY DEFERRED\n"
4338 for(i
=0; i
<lemp
->nsymbol
; i
++){
4340 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4341 "VALUES(%d,'%s',%s",
4342 i
, lemp
->symbols
[i
]->name
,
4343 i
<lemp
->nterminal
? "TRUE" : "FALSE"
4345 if( lemp
->symbols
[i
]->fallback
){
4346 fprintf(sql
, ",%d);\n", lemp
->symbols
[i
]->fallback
->index
);
4348 fprintf(sql
, ",NULL);\n");
4352 "CREATE TABLE rule(\n"
4353 " ruleid INTEGER PRIMARY KEY,\n"
4354 " lhs INTEGER REFERENCES symbol(id),\n"
4357 "CREATE TABLE rulerhs(\n"
4358 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4360 " sym INTEGER REFERENCES symbol(id)\n"
4363 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4364 assert( i
==rp
->iRule
);
4366 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
4367 rp
->iRule
, rp
->lhs
->index
4369 writeRuleText(sql
, rp
);
4370 fprintf(sql
,"');\n");
4371 for(j
=0; j
<rp
->nrhs
; j
++){
4372 struct symbol
*sp
= rp
->rhs
[j
];
4373 if( sp
->type
!=MULTITERMINAL
){
4375 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4380 for(k
=0; k
<sp
->nsubsym
; k
++){
4382 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4383 i
,j
,sp
->subsym
[k
]->index
4389 fprintf(sql
, "COMMIT;\n");
4394 "/* This file is automatically generated by Lemon from input grammar\n"
4395 "** source file \"%s\". */\n", lemp
->filename
); lineno
+= 2;
4397 /* The first %include directive begins with a C-language comment,
4398 ** then skip over the header comment of the template file
4400 if( lemp
->include
==0 ) lemp
->include
= "";
4401 for(i
=0; ISSPACE(lemp
->include
[i
]); i
++){
4402 if( lemp
->include
[i
]=='\n' ){
4403 lemp
->include
+= i
+1;
4407 if( lemp
->include
[0]=='/' ){
4408 tplt_skip_header(in
,&lineno
);
4410 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4413 /* Generate the include code, if any */
4414 tplt_print(out
,lemp
,lemp
->include
,&lineno
);
4416 char *incName
= file_makename(lemp
, ".h");
4417 fprintf(out
,"#include \"%s\"\n", incName
); lineno
++;
4420 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4422 /* Generate #defines for all tokens */
4423 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4426 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4428 fprintf(out
,"#ifndef %s%s\n", prefix
, lemp
->symbols
[1]->name
);
4430 for(i
=1; i
<lemp
->nterminal
; i
++){
4431 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4434 fprintf(out
,"#endif\n"); lineno
++;
4435 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4437 /* Generate the defines */
4438 fprintf(out
,"#define YYCODETYPE %s\n",
4439 minimum_size_type(0, lemp
->nsymbol
, &szCodeType
)); lineno
++;
4440 fprintf(out
,"#define YYNOCODE %d\n",lemp
->nsymbol
); lineno
++;
4441 fprintf(out
,"#define YYACTIONTYPE %s\n",
4442 minimum_size_type(0,lemp
->maxAction
,&szActionType
)); lineno
++;
4443 if( lemp
->wildcard
){
4444 fprintf(out
,"#define YYWILDCARD %d\n",
4445 lemp
->wildcard
->index
); lineno
++;
4447 print_stack_union(out
,lemp
,&lineno
,mhflag
);
4448 fprintf(out
, "#ifndef YYSTACKDEPTH\n"); lineno
++;
4449 if( lemp
->stacksize
){
4450 fprintf(out
,"#define YYSTACKDEPTH %s\n",lemp
->stacksize
); lineno
++;
4452 fprintf(out
,"#define YYSTACKDEPTH 100\n"); lineno
++;
4454 fprintf(out
, "#endif\n"); lineno
++;
4456 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4458 name
= lemp
->name
? lemp
->name
: "Parse";
4459 if( lemp
->arg
&& lemp
->arg
[0] ){
4460 i
= lemonStrlen(lemp
->arg
);
4461 while( i
>=1 && ISSPACE(lemp
->arg
[i
-1]) ) i
--;
4462 while( i
>=1 && (ISALNUM(lemp
->arg
[i
-1]) || lemp
->arg
[i
-1]=='_') ) i
--;
4463 fprintf(out
,"#define %sARG_SDECL %s;\n",name
,lemp
->arg
); lineno
++;
4464 fprintf(out
,"#define %sARG_PDECL ,%s\n",name
,lemp
->arg
); lineno
++;
4465 fprintf(out
,"#define %sARG_PARAM ,%s\n",name
,&lemp
->arg
[i
]); lineno
++;
4466 fprintf(out
,"#define %sARG_FETCH %s=yypParser->%s;\n",
4467 name
,lemp
->arg
,&lemp
->arg
[i
]); lineno
++;
4468 fprintf(out
,"#define %sARG_STORE yypParser->%s=%s;\n",
4469 name
,&lemp
->arg
[i
],&lemp
->arg
[i
]); lineno
++;
4471 fprintf(out
,"#define %sARG_SDECL\n",name
); lineno
++;
4472 fprintf(out
,"#define %sARG_PDECL\n",name
); lineno
++;
4473 fprintf(out
,"#define %sARG_PARAM\n",name
); lineno
++;
4474 fprintf(out
,"#define %sARG_FETCH\n",name
); lineno
++;
4475 fprintf(out
,"#define %sARG_STORE\n",name
); lineno
++;
4477 if( lemp
->ctx
&& lemp
->ctx
[0] ){
4478 i
= lemonStrlen(lemp
->ctx
);
4479 while( i
>=1 && ISSPACE(lemp
->ctx
[i
-1]) ) i
--;
4480 while( i
>=1 && (ISALNUM(lemp
->ctx
[i
-1]) || lemp
->ctx
[i
-1]=='_') ) i
--;
4481 fprintf(out
,"#define %sCTX_SDECL %s;\n",name
,lemp
->ctx
); lineno
++;
4482 fprintf(out
,"#define %sCTX_PDECL ,%s\n",name
,lemp
->ctx
); lineno
++;
4483 fprintf(out
,"#define %sCTX_PARAM ,%s\n",name
,&lemp
->ctx
[i
]); lineno
++;
4484 fprintf(out
,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4485 name
,lemp
->ctx
,&lemp
->ctx
[i
]); lineno
++;
4486 fprintf(out
,"#define %sCTX_STORE yypParser->%s=%s;\n",
4487 name
,&lemp
->ctx
[i
],&lemp
->ctx
[i
]); lineno
++;
4489 fprintf(out
,"#define %sCTX_SDECL\n",name
); lineno
++;
4490 fprintf(out
,"#define %sCTX_PDECL\n",name
); lineno
++;
4491 fprintf(out
,"#define %sCTX_PARAM\n",name
); lineno
++;
4492 fprintf(out
,"#define %sCTX_FETCH\n",name
); lineno
++;
4493 fprintf(out
,"#define %sCTX_STORE\n",name
); lineno
++;
4496 fprintf(out
,"#endif\n"); lineno
++;
4498 if( lemp
->errsym
&& lemp
->errsym
->useCnt
){
4499 fprintf(out
,"#define YYERRORSYMBOL %d\n",lemp
->errsym
->index
); lineno
++;
4500 fprintf(out
,"#define YYERRSYMDT yy%d\n",lemp
->errsym
->dtnum
); lineno
++;
4502 if( lemp
->has_fallback
){
4503 fprintf(out
,"#define YYFALLBACK 1\n"); lineno
++;
4506 /* Compute the action table, but do not output it yet. The action
4507 ** table must be computed before generating the YYNSTATE macro because
4508 ** we need to know how many states can be eliminated.
4510 ax
= (struct axset
*) calloc(lemp
->nxstate
*2, sizeof(ax
[0]));
4512 fprintf(stderr
,"malloc failed\n");
4515 for(i
=0; i
<lemp
->nxstate
; i
++){
4516 stp
= lemp
->sorted
[i
];
4519 ax
[i
*2].nAction
= stp
->nTknAct
;
4520 ax
[i
*2+1].stp
= stp
;
4521 ax
[i
*2+1].isTkn
= 0;
4522 ax
[i
*2+1].nAction
= stp
->nNtAct
;
4524 mxTknOfst
= mnTknOfst
= 0;
4525 mxNtOfst
= mnNtOfst
= 0;
4526 /* In an effort to minimize the action table size, use the heuristic
4527 ** of placing the largest action sets first */
4528 for(i
=0; i
<lemp
->nxstate
*2; i
++) ax
[i
].iOrder
= i
;
4529 qsort(ax
, lemp
->nxstate
*2, sizeof(ax
[0]), axset_compare
);
4530 pActtab
= acttab_alloc(lemp
->nsymbol
, lemp
->nterminal
);
4531 for(i
=0; i
<lemp
->nxstate
*2 && ax
[i
].nAction
>0; i
++){
4534 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4536 if( ap
->sp
->index
>=lemp
->nterminal
) continue;
4537 action
= compute_action(lemp
, ap
);
4538 if( action
<0 ) continue;
4539 acttab_action(pActtab
, ap
->sp
->index
, action
);
4541 stp
->iTknOfst
= acttab_insert(pActtab
, 1);
4542 if( stp
->iTknOfst
<mnTknOfst
) mnTknOfst
= stp
->iTknOfst
;
4543 if( stp
->iTknOfst
>mxTknOfst
) mxTknOfst
= stp
->iTknOfst
;
4545 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4547 if( ap
->sp
->index
<lemp
->nterminal
) continue;
4548 if( ap
->sp
->index
==lemp
->nsymbol
) continue;
4549 action
= compute_action(lemp
, ap
);
4550 if( action
<0 ) continue;
4551 acttab_action(pActtab
, ap
->sp
->index
, action
);
4553 stp
->iNtOfst
= acttab_insert(pActtab
, 0);
4554 if( stp
->iNtOfst
<mnNtOfst
) mnNtOfst
= stp
->iNtOfst
;
4555 if( stp
->iNtOfst
>mxNtOfst
) mxNtOfst
= stp
->iNtOfst
;
4557 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4559 for(jj
=nn
=0; jj
<pActtab
->nAction
; jj
++){
4560 if( pActtab
->aAction
[jj
].action
<0 ) nn
++;
4562 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4563 i
, stp
->statenum
, ax
[i
].isTkn
? "Token" : "Var ",
4564 ax
[i
].nAction
, pActtab
->nAction
, nn
);
4570 /* Mark rules that are actually used for reduce actions after all
4571 ** optimizations have been applied
4573 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->doesReduce
= LEMON_FALSE
;
4574 for(i
=0; i
<lemp
->nxstate
; i
++){
4575 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
4576 if( ap
->type
==REDUCE
|| ap
->type
==SHIFTREDUCE
){
4577 ap
->x
.rp
->doesReduce
= 1;
4582 /* Finish rendering the constants now that the action table has
4584 fprintf(out
,"#define YYNSTATE %d\n",lemp
->nxstate
); lineno
++;
4585 fprintf(out
,"#define YYNRULE %d\n",lemp
->nrule
); lineno
++;
4586 fprintf(out
,"#define YYNRULE_WITH_ACTION %d\n",lemp
->nruleWithAction
);
4588 fprintf(out
,"#define YYNTOKEN %d\n",lemp
->nterminal
); lineno
++;
4589 fprintf(out
,"#define YY_MAX_SHIFT %d\n",lemp
->nxstate
-1); lineno
++;
4590 i
= lemp
->minShiftReduce
;
4591 fprintf(out
,"#define YY_MIN_SHIFTREDUCE %d\n",i
); lineno
++;
4593 fprintf(out
,"#define YY_MAX_SHIFTREDUCE %d\n", i
-1); lineno
++;
4594 fprintf(out
,"#define YY_ERROR_ACTION %d\n", lemp
->errAction
); lineno
++;
4595 fprintf(out
,"#define YY_ACCEPT_ACTION %d\n", lemp
->accAction
); lineno
++;
4596 fprintf(out
,"#define YY_NO_ACTION %d\n", lemp
->noAction
); lineno
++;
4597 fprintf(out
,"#define YY_MIN_REDUCE %d\n", lemp
->minReduce
); lineno
++;
4598 i
= lemp
->minReduce
+ lemp
->nrule
;
4599 fprintf(out
,"#define YY_MAX_REDUCE %d\n", i
-1); lineno
++;
4600 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4602 /* Now output the action table and its associates:
4604 ** yy_action[] A single table containing all actions.
4605 ** yy_lookahead[] A table containing the lookahead for each entry in
4606 ** yy_action. Used to detect hash collisions.
4607 ** yy_shift_ofst[] For each state, the offset into yy_action for
4608 ** shifting terminals.
4609 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4610 ** shifting non-terminals after a reduce.
4611 ** yy_default[] Default action for each state.
4614 /* Output the yy_action table */
4615 lemp
->nactiontab
= n
= acttab_action_size(pActtab
);
4616 lemp
->tablesize
+= n
*szActionType
;
4617 fprintf(out
,"#define YY_ACTTAB_COUNT (%d)\n", n
); lineno
++;
4618 fprintf(out
,"static const YYACTIONTYPE yy_action[] = {\n"); lineno
++;
4619 for(i
=j
=0; i
<n
; i
++){
4620 int action
= acttab_yyaction(pActtab
, i
);
4621 if( action
<0 ) action
= lemp
->noAction
;
4622 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4623 fprintf(out
, " %4d,", action
);
4624 if( j
==9 || i
==n
-1 ){
4625 fprintf(out
, "\n"); lineno
++;
4631 fprintf(out
, "};\n"); lineno
++;
4633 /* Output the yy_lookahead table */
4634 lemp
->nlookaheadtab
= n
= acttab_lookahead_size(pActtab
);
4635 lemp
->tablesize
+= n
*szCodeType
;
4636 fprintf(out
,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno
++;
4637 for(i
=j
=0; i
<n
; i
++){
4638 int la
= acttab_yylookahead(pActtab
, i
);
4639 if( la
<0 ) la
= lemp
->nsymbol
;
4640 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4641 fprintf(out
, " %4d,", la
);
4643 fprintf(out
, "\n"); lineno
++;
4649 /* Add extra entries to the end of the yy_lookahead[] table so that
4650 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4651 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4652 nLookAhead
= lemp
->nterminal
+ lemp
->nactiontab
;
4653 while( i
<nLookAhead
){
4654 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4655 fprintf(out
, " %4d,", lemp
->nterminal
);
4657 fprintf(out
, "\n"); lineno
++;
4664 if( j
>0 ){ fprintf(out
, "\n"); lineno
++; }
4665 fprintf(out
, "};\n"); lineno
++;
4667 /* Output the yy_shift_ofst[] table */
4669 while( n
>0 && lemp
->sorted
[n
-1]->iTknOfst
==NO_OFFSET
) n
--;
4670 fprintf(out
, "#define YY_SHIFT_COUNT (%d)\n", n
-1); lineno
++;
4671 fprintf(out
, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst
); lineno
++;
4672 fprintf(out
, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst
); lineno
++;
4673 fprintf(out
, "static const %s yy_shift_ofst[] = {\n",
4674 minimum_size_type(mnTknOfst
, lemp
->nterminal
+lemp
->nactiontab
, &sz
));
4676 lemp
->tablesize
+= n
*sz
;
4677 for(i
=j
=0; i
<n
; i
++){
4679 stp
= lemp
->sorted
[i
];
4680 ofst
= stp
->iTknOfst
;
4681 if( ofst
==NO_OFFSET
) ofst
= lemp
->nactiontab
;
4682 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4683 fprintf(out
, " %4d,", ofst
);
4684 if( j
==9 || i
==n
-1 ){
4685 fprintf(out
, "\n"); lineno
++;
4691 fprintf(out
, "};\n"); lineno
++;
4693 /* Output the yy_reduce_ofst[] table */
4695 while( n
>0 && lemp
->sorted
[n
-1]->iNtOfst
==NO_OFFSET
) n
--;
4696 fprintf(out
, "#define YY_REDUCE_COUNT (%d)\n", n
-1); lineno
++;
4697 fprintf(out
, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst
); lineno
++;
4698 fprintf(out
, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst
); lineno
++;
4699 fprintf(out
, "static const %s yy_reduce_ofst[] = {\n",
4700 minimum_size_type(mnNtOfst
-1, mxNtOfst
, &sz
)); lineno
++;
4701 lemp
->tablesize
+= n
*sz
;
4702 for(i
=j
=0; i
<n
; i
++){
4704 stp
= lemp
->sorted
[i
];
4705 ofst
= stp
->iNtOfst
;
4706 if( ofst
==NO_OFFSET
) ofst
= mnNtOfst
- 1;
4707 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4708 fprintf(out
, " %4d,", ofst
);
4709 if( j
==9 || i
==n
-1 ){
4710 fprintf(out
, "\n"); lineno
++;
4716 fprintf(out
, "};\n"); lineno
++;
4718 /* Output the default action table */
4719 fprintf(out
, "static const YYACTIONTYPE yy_default[] = {\n"); lineno
++;
4721 lemp
->tablesize
+= n
*szActionType
;
4722 for(i
=j
=0; i
<n
; i
++){
4723 stp
= lemp
->sorted
[i
];
4724 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4725 if( stp
->iDfltReduce
<0 ){
4726 fprintf(out
, " %4d,", lemp
->errAction
);
4728 fprintf(out
, " %4d,", stp
->iDfltReduce
+ lemp
->minReduce
);
4730 if( j
==9 || i
==n
-1 ){
4731 fprintf(out
, "\n"); lineno
++;
4737 fprintf(out
, "};\n"); lineno
++;
4738 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4740 /* Generate the table of fallback tokens.
4742 if( lemp
->has_fallback
){
4743 int mx
= lemp
->nterminal
- 1;
4744 /* 2019-08-28: Generate fallback entries for every token to avoid
4745 ** having to do a range check on the index */
4746 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
4747 lemp
->tablesize
+= (mx
+1)*szCodeType
;
4748 for(i
=0; i
<=mx
; i
++){
4749 struct symbol
*p
= lemp
->symbols
[i
];
4750 if( p
->fallback
==0 ){
4751 fprintf(out
, " 0, /* %10s => nothing */\n", p
->name
);
4753 fprintf(out
, " %3d, /* %10s => %s */\n", p
->fallback
->index
,
4754 p
->name
, p
->fallback
->name
);
4759 tplt_xfer(lemp
->name
, in
, out
, &lineno
);
4761 /* Generate a table containing the symbolic name of every symbol
4763 for(i
=0; i
<lemp
->nsymbol
; i
++){
4764 lemon_sprintf(line
,"\"%s\",",lemp
->symbols
[i
]->name
);
4765 fprintf(out
," /* %4d */ \"%s\",\n",i
, lemp
->symbols
[i
]->name
); lineno
++;
4767 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4769 /* Generate a table containing a text string that describes every
4770 ** rule in the rule set of the grammar. This information is used
4771 ** when tracing REDUCE actions.
4773 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4774 assert( rp
->iRule
==i
);
4775 fprintf(out
," /* %3d */ \"", i
);
4776 writeRuleText(out
, rp
);
4777 fprintf(out
,"\",\n"); lineno
++;
4779 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4781 /* Generate code which executes every time a symbol is popped from
4782 ** the stack while processing errors or while destroying the parser.
4783 ** (In other words, generate the %destructor actions)
4785 if( lemp
->tokendest
){
4787 for(i
=0; i
<lemp
->nsymbol
; i
++){
4788 struct symbol
*sp
= lemp
->symbols
[i
];
4789 if( sp
==0 || sp
->type
!=TERMINAL
) continue;
4791 fprintf(out
, " /* TERMINAL Destructor */\n"); lineno
++;
4794 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4796 for(i
=0; i
<lemp
->nsymbol
&& lemp
->symbols
[i
]->type
!=TERMINAL
; i
++);
4797 if( i
<lemp
->nsymbol
){
4798 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4799 fprintf(out
," break;\n"); lineno
++;
4802 if( lemp
->vardest
){
4803 struct symbol
*dflt_sp
= 0;
4805 for(i
=0; i
<lemp
->nsymbol
; i
++){
4806 struct symbol
*sp
= lemp
->symbols
[i
];
4807 if( sp
==0 || sp
->type
==TERMINAL
||
4808 sp
->index
<=0 || sp
->destructor
!=0 ) continue;
4810 fprintf(out
, " /* Default NON-TERMINAL Destructor */\n");lineno
++;
4813 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4817 emit_destructor_code(out
,dflt_sp
,lemp
,&lineno
);
4819 fprintf(out
," break;\n"); lineno
++;
4821 for(i
=0; i
<lemp
->nsymbol
; i
++){
4822 struct symbol
*sp
= lemp
->symbols
[i
];
4823 if( sp
==0 || sp
->type
==TERMINAL
|| sp
->destructor
==0 ) continue;
4824 if( sp
->destLineno
<0 ) continue; /* Already emitted */
4825 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4827 /* Combine duplicate destructors into a single case */
4828 for(j
=i
+1; j
<lemp
->nsymbol
; j
++){
4829 struct symbol
*sp2
= lemp
->symbols
[j
];
4830 if( sp2
&& sp2
->type
!=TERMINAL
&& sp2
->destructor
4831 && sp2
->dtnum
==sp
->dtnum
4832 && strcmp(sp
->destructor
,sp2
->destructor
)==0 ){
4833 fprintf(out
," case %d: /* %s */\n",
4834 sp2
->index
, sp2
->name
); lineno
++;
4835 sp2
->destLineno
= -1; /* Avoid emitting this destructor again */
4839 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4840 fprintf(out
," break;\n"); lineno
++;
4842 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4844 /* Generate code which executes whenever the parser stack overflows */
4845 tplt_print(out
,lemp
,lemp
->overflow
,&lineno
);
4846 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4848 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4849 ** yyRuleInfoNRhs[].
4851 ** Note: This code depends on the fact that rules are number
4852 ** sequentially beginning with 0.
4854 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4855 fprintf(out
," %4d, /* (%d) ", rp
->lhs
->index
, i
);
4856 rule_print(out
, rp
);
4857 fprintf(out
," */\n"); lineno
++;
4859 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4860 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4861 fprintf(out
," %3d, /* (%d) ", -rp
->nrhs
, i
);
4862 rule_print(out
, rp
);
4863 fprintf(out
," */\n"); lineno
++;
4865 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4867 /* Generate code which execution during each REDUCE action */
4869 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4870 i
+= translate_code(lemp
, rp
);
4873 fprintf(out
," YYMINORTYPE yylhsminor;\n"); lineno
++;
4875 /* First output rules other than the default: rule */
4876 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4877 struct rule
*rp2
; /* Other rules with the same action */
4878 if( rp
->codeEmitted
) continue;
4880 /* No C code actions, so this will be part of the "default:" rule */
4883 fprintf(out
," case %d: /* ", rp
->iRule
);
4884 writeRuleText(out
, rp
);
4885 fprintf(out
, " */\n"); lineno
++;
4886 for(rp2
=rp
->next
; rp2
; rp2
=rp2
->next
){
4887 if( rp2
->code
==rp
->code
&& rp2
->codePrefix
==rp
->codePrefix
4888 && rp2
->codeSuffix
==rp
->codeSuffix
){
4889 fprintf(out
," case %d: /* ", rp2
->iRule
);
4890 writeRuleText(out
, rp2
);
4891 fprintf(out
," */ yytestcase(yyruleno==%d);\n", rp2
->iRule
); lineno
++;
4892 rp2
->codeEmitted
= 1;
4895 emit_code(out
,rp
,lemp
,&lineno
);
4896 fprintf(out
," break;\n"); lineno
++;
4897 rp
->codeEmitted
= 1;
4899 /* Finally, output the default: rule. We choose as the default: all
4900 ** empty actions. */
4901 fprintf(out
," default:\n"); lineno
++;
4902 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4903 if( rp
->codeEmitted
) continue;
4904 assert( rp
->noCode
);
4905 fprintf(out
," /* (%d) ", rp
->iRule
);
4906 writeRuleText(out
, rp
);
4907 if( rp
->neverReduce
){
4908 fprintf(out
, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
4909 rp
->iRule
); lineno
++;
4910 }else if( rp
->doesReduce
){
4911 fprintf(out
, " */ yytestcase(yyruleno==%d);\n", rp
->iRule
); lineno
++;
4913 fprintf(out
, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4914 rp
->iRule
); lineno
++;
4917 fprintf(out
," break;\n"); lineno
++;
4918 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4920 /* Generate code which executes if a parse fails */
4921 tplt_print(out
,lemp
,lemp
->failure
,&lineno
);
4922 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4924 /* Generate code which executes when a syntax error occurs */
4925 tplt_print(out
,lemp
,lemp
->error
,&lineno
);
4926 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4928 /* Generate code which executes when the parser accepts its input */
4929 tplt_print(out
,lemp
,lemp
->accept
,&lineno
);
4930 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4932 /* Append any addition code the user desires */
4933 tplt_print(out
,lemp
,lemp
->extracode
,&lineno
);
4935 acttab_free(pActtab
);
4938 if( sql
) fclose(sql
);
4942 /* Generate a header file for the parser */
4943 void ReportHeader(struct lemon
*lemp
)
4947 char line
[LINESIZE
];
4948 char pattern
[LINESIZE
];
4951 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4953 in
= file_open(lemp
,".h","rb");
4956 for(i
=1; i
<lemp
->nterminal
&& fgets(line
,LINESIZE
,in
); i
++){
4957 lemon_sprintf(pattern
,"#define %s%-30s %3d\n",
4958 prefix
,lemp
->symbols
[i
]->name
,i
);
4959 if( strcmp(line
,pattern
) ) break;
4961 nextChar
= fgetc(in
);
4963 if( i
==lemp
->nterminal
&& nextChar
==EOF
){
4964 /* No change in the file. Don't rewrite it. */
4968 out
= file_open(lemp
,".h","wb");
4970 for(i
=1; i
<lemp
->nterminal
; i
++){
4971 fprintf(out
,"#define %s%-30s %3d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4978 /* Reduce the size of the action tables, if possible, by making use
4981 ** In this version, we take the most frequent REDUCE action and make
4982 ** it the default. Except, there is no default if the wildcard token
4983 ** is a possible look-ahead.
4985 void CompressTables(struct lemon
*lemp
)
4988 struct action
*ap
, *ap2
, *nextap
;
4989 struct rule
*rp
, *rp2
, *rbest
;
4994 for(i
=0; i
<lemp
->nstate
; i
++){
4995 stp
= lemp
->sorted
[i
];
5000 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5001 if( ap
->type
==SHIFT
&& ap
->sp
==lemp
->wildcard
){
5004 if( ap
->type
!=REDUCE
) continue;
5006 if( rp
->lhsStart
) continue;
5007 if( rp
==rbest
) continue;
5009 for(ap2
=ap
->next
; ap2
; ap2
=ap2
->next
){
5010 if( ap2
->type
!=REDUCE
) continue;
5012 if( rp2
==rbest
) continue;
5021 /* Do not make a default if the number of rules to default
5022 ** is not at least 1 or if the wildcard token is a possible
5025 if( nbest
<1 || usesWildcard
) continue;
5028 /* Combine matching REDUCE actions into a single default */
5029 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5030 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) break;
5033 ap
->sp
= Symbol_new("{default}");
5034 for(ap
=ap
->next
; ap
; ap
=ap
->next
){
5035 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) ap
->type
= NOT_USED
;
5037 stp
->ap
= Action_sort(stp
->ap
);
5039 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5040 if( ap
->type
==SHIFT
) break;
5041 if( ap
->type
==REDUCE
&& ap
->x
.rp
!=rbest
) break;
5044 stp
->autoReduce
= 1;
5045 stp
->pDfltReduce
= rbest
;
5049 /* Make a second pass over all states and actions. Convert
5050 ** every action that is a SHIFT to an autoReduce state into
5051 ** a SHIFTREDUCE action.
5053 for(i
=0; i
<lemp
->nstate
; i
++){
5054 stp
= lemp
->sorted
[i
];
5055 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5056 struct state
*pNextState
;
5057 if( ap
->type
!=SHIFT
) continue;
5058 pNextState
= ap
->x
.stp
;
5059 if( pNextState
->autoReduce
&& pNextState
->pDfltReduce
!=0 ){
5060 ap
->type
= SHIFTREDUCE
;
5061 ap
->x
.rp
= pNextState
->pDfltReduce
;
5066 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
5067 ** (meaning that the SHIFTREDUCE will land back in the state where it
5068 ** started) and if there is no C-code associated with the reduce action,
5069 ** then we can go ahead and convert the action to be the same as the
5070 ** action for the RHS of the rule.
5072 for(i
=0; i
<lemp
->nstate
; i
++){
5073 stp
= lemp
->sorted
[i
];
5074 for(ap
=stp
->ap
; ap
; ap
=nextap
){
5076 if( ap
->type
!=SHIFTREDUCE
) continue;
5078 if( rp
->noCode
==0 ) continue;
5079 if( rp
->nrhs
!=1 ) continue;
5081 /* Only apply this optimization to non-terminals. It would be OK to
5082 ** apply it to terminal symbols too, but that makes the parser tables
5084 if( ap
->sp
->index
<lemp
->nterminal
) continue;
5086 /* If we reach this point, it means the optimization can be applied */
5088 for(ap2
=stp
->ap
; ap2
&& (ap2
==ap
|| ap2
->sp
!=rp
->lhs
); ap2
=ap2
->next
){}
5090 ap
->spOpt
= ap2
->sp
;
5091 ap
->type
= ap2
->type
;
5099 ** Compare two states for sorting purposes. The smaller state is the
5100 ** one with the most non-terminal actions. If they have the same number
5101 ** of non-terminal actions, then the smaller is the one with the most
5104 static int stateResortCompare(const void *a
, const void *b
){
5105 const struct state
*pA
= *(const struct state
**)a
;
5106 const struct state
*pB
= *(const struct state
**)b
;
5109 n
= pB
->nNtAct
- pA
->nNtAct
;
5111 n
= pB
->nTknAct
- pA
->nTknAct
;
5113 n
= pB
->statenum
- pA
->statenum
;
5122 ** Renumber and resort states so that states with fewer choices
5123 ** occur at the end. Except, keep state 0 as the first state.
5125 void ResortStates(struct lemon
*lemp
)
5131 for(i
=0; i
<lemp
->nstate
; i
++){
5132 stp
= lemp
->sorted
[i
];
5133 stp
->nTknAct
= stp
->nNtAct
= 0;
5134 stp
->iDfltReduce
= -1; /* Init dflt action to "syntax error" */
5135 stp
->iTknOfst
= NO_OFFSET
;
5136 stp
->iNtOfst
= NO_OFFSET
;
5137 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
5138 int iAction
= compute_action(lemp
,ap
);
5140 if( ap
->sp
->index
<lemp
->nterminal
){
5142 }else if( ap
->sp
->index
<lemp
->nsymbol
){
5145 assert( stp
->autoReduce
==0 || stp
->pDfltReduce
==ap
->x
.rp
);
5146 stp
->iDfltReduce
= iAction
;
5151 qsort(&lemp
->sorted
[1], lemp
->nstate
-1, sizeof(lemp
->sorted
[0]),
5152 stateResortCompare
);
5153 for(i
=0; i
<lemp
->nstate
; i
++){
5154 lemp
->sorted
[i
]->statenum
= i
;
5156 lemp
->nxstate
= lemp
->nstate
;
5157 while( lemp
->nxstate
>1 && lemp
->sorted
[lemp
->nxstate
-1]->autoReduce
){
5163 /***************** From the file "set.c" ************************************/
5165 ** Set manipulation routines for the LEMON parser generator.
5168 static int size
= 0;
5170 /* Set the set size */
5176 /* Allocate a new set */
5179 s
= (char*)calloc( size
, 1);
5186 /* Deallocate a set */
5187 void SetFree(char *s
)
5192 /* Add a new element to the set. Return TRUE if the element was added
5193 ** and FALSE if it was already there. */
5194 int SetAdd(char *s
, int e
)
5197 assert( e
>=0 && e
<size
);
5203 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
5204 int SetUnion(char *s1
, char *s2
)
5208 for(i
=0; i
<size
; i
++){
5209 if( s2
[i
]==0 ) continue;
5217 /********************** From the file "table.c" ****************************/
5219 ** All code in this file has been automatically generated
5220 ** from a specification in the file
5222 ** by the associative array code building program "aagen".
5223 ** Do not edit this file! Instead, edit the specification
5224 ** file, then rerun aagen.
5227 ** Code for processing tables in the LEMON parser generator.
5230 PRIVATE
unsigned strhash(const char *x
)
5233 while( *x
) h
= h
*13 + *(x
++);
5237 /* Works like strdup, sort of. Save a string in malloced memory, but
5238 ** keep strings in a table so that the same string is not in more
5241 const char *Strsafe(const char *y
)
5246 if( y
==0 ) return 0;
5247 z
= Strsafe_find(y
);
5248 if( z
==0 && (cpy
=(char *)malloc( lemonStrlen(y
)+1 ))!=0 ){
5249 lemon_strcpy(cpy
,y
);
5257 /* There is one instance of the following structure for each
5258 ** associative array of type "x1".
5261 int size
; /* The number of available slots. */
5262 /* Must be a power of 2 greater than or */
5264 int count
; /* Number of currently slots filled */
5265 struct s_x1node
*tbl
; /* The data stored here */
5266 struct s_x1node
**ht
; /* Hash table for lookups */
5269 /* There is one instance of this structure for every data element
5270 ** in an associative array of type "x1".
5272 typedef struct s_x1node
{
5273 const char *data
; /* The data */
5274 struct s_x1node
*next
; /* Next entry with the same hash */
5275 struct s_x1node
**from
; /* Previous link */
5278 /* There is only one instance of the array, which is the following */
5279 static struct s_x1
*x1a
;
5281 /* Allocate a new associative array */
5282 void Strsafe_init(void){
5284 x1a
= (struct s_x1
*)malloc( sizeof(struct s_x1
) );
5288 x1a
->tbl
= (x1node
*)calloc(1024, sizeof(x1node
) + sizeof(x1node
*));
5294 x1a
->ht
= (x1node
**)&(x1a
->tbl
[1024]);
5295 for(i
=0; i
<1024; i
++) x1a
->ht
[i
] = 0;
5299 /* Insert a new record into the array. Return TRUE if successful.
5300 ** Prior data with the same key is NOT overwritten */
5301 int Strsafe_insert(const char *data
)
5307 if( x1a
==0 ) return 0;
5309 h
= ph
& (x1a
->size
-1);
5312 if( strcmp(np
->data
,data
)==0 ){
5313 /* An existing entry with the same key is found. */
5314 /* Fail because overwrite is not allows. */
5319 if( x1a
->count
>=x1a
->size
){
5320 /* Need to make the hash table bigger */
5323 array
.size
= arrSize
= x1a
->size
*2;
5324 array
.count
= x1a
->count
;
5325 array
.tbl
= (x1node
*)calloc(arrSize
, sizeof(x1node
) + sizeof(x1node
*));
5326 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5327 array
.ht
= (x1node
**)&(array
.tbl
[arrSize
]);
5328 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5329 for(i
=0; i
<x1a
->count
; i
++){
5330 x1node
*oldnp
, *newnp
;
5331 oldnp
= &(x1a
->tbl
[i
]);
5332 h
= strhash(oldnp
->data
) & (arrSize
-1);
5333 newnp
= &(array
.tbl
[i
]);
5334 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5335 newnp
->next
= array
.ht
[h
];
5336 newnp
->data
= oldnp
->data
;
5337 newnp
->from
= &(array
.ht
[h
]);
5338 array
.ht
[h
] = newnp
;
5343 /* Insert the new data */
5344 h
= ph
& (x1a
->size
-1);
5345 np
= &(x1a
->tbl
[x1a
->count
++]);
5347 if( x1a
->ht
[h
] ) x1a
->ht
[h
]->from
= &(np
->next
);
5348 np
->next
= x1a
->ht
[h
];
5350 np
->from
= &(x1a
->ht
[h
]);
5354 /* Return a pointer to data assigned to the given key. Return NULL
5355 ** if no such key. */
5356 const char *Strsafe_find(const char *key
)
5361 if( x1a
==0 ) return 0;
5362 h
= strhash(key
) & (x1a
->size
-1);
5365 if( strcmp(np
->data
,key
)==0 ) break;
5368 return np
? np
->data
: 0;
5371 /* Return a pointer to the (terminal or nonterminal) symbol "x".
5372 ** Create a new symbol if this is the first time "x" has been seen.
5374 struct symbol
*Symbol_new(const char *x
)
5378 sp
= Symbol_find(x
);
5380 sp
= (struct symbol
*)calloc(1, sizeof(struct symbol
) );
5382 sp
->name
= Strsafe(x
);
5383 sp
->type
= ISUPPER(*x
) ? TERMINAL
: NONTERMINAL
;
5389 sp
->lambda
= LEMON_FALSE
;
5394 Symbol_insert(sp
,sp
->name
);
5400 /* Compare two symbols for sorting purposes. Return negative,
5401 ** zero, or positive if a is less then, equal to, or greater
5404 ** Symbols that begin with upper case letters (terminals or tokens)
5405 ** must sort before symbols that begin with lower case letters
5406 ** (non-terminals). And MULTITERMINAL symbols (created using the
5407 ** %token_class directive) must sort at the very end. Other than
5408 ** that, the order does not matter.
5410 ** We find experimentally that leaving the symbols in their original
5411 ** order (the order they appeared in the grammar file) gives the
5412 ** smallest parser tables in SQLite.
5414 int Symbolcmpp(const void *_a
, const void *_b
)
5416 const struct symbol
*a
= *(const struct symbol
**) _a
;
5417 const struct symbol
*b
= *(const struct symbol
**) _b
;
5418 int i1
= a
->type
==MULTITERMINAL
? 3 : a
->name
[0]>'Z' ? 2 : 1;
5419 int i2
= b
->type
==MULTITERMINAL
? 3 : b
->name
[0]>'Z' ? 2 : 1;
5420 return i1
==i2
? a
->index
- b
->index
: i1
- i2
;
5423 /* There is one instance of the following structure for each
5424 ** associative array of type "x2".
5427 int size
; /* The number of available slots. */
5428 /* Must be a power of 2 greater than or */
5430 int count
; /* Number of currently slots filled */
5431 struct s_x2node
*tbl
; /* The data stored here */
5432 struct s_x2node
**ht
; /* Hash table for lookups */
5435 /* There is one instance of this structure for every data element
5436 ** in an associative array of type "x2".
5438 typedef struct s_x2node
{
5439 struct symbol
*data
; /* The data */
5440 const char *key
; /* The key */
5441 struct s_x2node
*next
; /* Next entry with the same hash */
5442 struct s_x2node
**from
; /* Previous link */
5445 /* There is only one instance of the array, which is the following */
5446 static struct s_x2
*x2a
;
5448 /* Allocate a new associative array */
5449 void Symbol_init(void){
5451 x2a
= (struct s_x2
*)malloc( sizeof(struct s_x2
) );
5455 x2a
->tbl
= (x2node
*)calloc(128, sizeof(x2node
) + sizeof(x2node
*));
5461 x2a
->ht
= (x2node
**)&(x2a
->tbl
[128]);
5462 for(i
=0; i
<128; i
++) x2a
->ht
[i
] = 0;
5466 /* Insert a new record into the array. Return TRUE if successful.
5467 ** Prior data with the same key is NOT overwritten */
5468 int Symbol_insert(struct symbol
*data
, const char *key
)
5474 if( x2a
==0 ) return 0;
5476 h
= ph
& (x2a
->size
-1);
5479 if( strcmp(np
->key
,key
)==0 ){
5480 /* An existing entry with the same key is found. */
5481 /* Fail because overwrite is not allows. */
5486 if( x2a
->count
>=x2a
->size
){
5487 /* Need to make the hash table bigger */
5490 array
.size
= arrSize
= x2a
->size
*2;
5491 array
.count
= x2a
->count
;
5492 array
.tbl
= (x2node
*)calloc(arrSize
, sizeof(x2node
) + sizeof(x2node
*));
5493 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5494 array
.ht
= (x2node
**)&(array
.tbl
[arrSize
]);
5495 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5496 for(i
=0; i
<x2a
->count
; i
++){
5497 x2node
*oldnp
, *newnp
;
5498 oldnp
= &(x2a
->tbl
[i
]);
5499 h
= strhash(oldnp
->key
) & (arrSize
-1);
5500 newnp
= &(array
.tbl
[i
]);
5501 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5502 newnp
->next
= array
.ht
[h
];
5503 newnp
->key
= oldnp
->key
;
5504 newnp
->data
= oldnp
->data
;
5505 newnp
->from
= &(array
.ht
[h
]);
5506 array
.ht
[h
] = newnp
;
5511 /* Insert the new data */
5512 h
= ph
& (x2a
->size
-1);
5513 np
= &(x2a
->tbl
[x2a
->count
++]);
5516 if( x2a
->ht
[h
] ) x2a
->ht
[h
]->from
= &(np
->next
);
5517 np
->next
= x2a
->ht
[h
];
5519 np
->from
= &(x2a
->ht
[h
]);
5523 /* Return a pointer to data assigned to the given key. Return NULL
5524 ** if no such key. */
5525 struct symbol
*Symbol_find(const char *key
)
5530 if( x2a
==0 ) return 0;
5531 h
= strhash(key
) & (x2a
->size
-1);
5534 if( strcmp(np
->key
,key
)==0 ) break;
5537 return np
? np
->data
: 0;
5540 /* Return the n-th data. Return NULL if n is out of range. */
5541 struct symbol
*Symbol_Nth(int n
)
5543 struct symbol
*data
;
5544 if( x2a
&& n
>0 && n
<=x2a
->count
){
5545 data
= x2a
->tbl
[n
-1].data
;
5552 /* Return the size of the array */
5555 return x2a
? x2a
->count
: 0;
5558 /* Return an array of pointers to all data in the table.
5559 ** The array is obtained from malloc. Return NULL if memory allocation
5560 ** problems, or if the array is empty. */
5561 struct symbol
**Symbol_arrayof()
5563 struct symbol
**array
;
5565 if( x2a
==0 ) return 0;
5566 arrSize
= x2a
->count
;
5567 array
= (struct symbol
**)calloc(arrSize
, sizeof(struct symbol
*));
5569 for(i
=0; i
<arrSize
; i
++) array
[i
] = x2a
->tbl
[i
].data
;
5574 /* Compare two configurations */
5575 int Configcmp(const char *_a
,const char *_b
)
5577 const struct config
*a
= (struct config
*) _a
;
5578 const struct config
*b
= (struct config
*) _b
;
5580 x
= a
->rp
->index
- b
->rp
->index
;
5581 if( x
==0 ) x
= a
->dot
- b
->dot
;
5585 /* Compare two states */
5586 PRIVATE
int statecmp(struct config
*a
, struct config
*b
)
5589 for(rc
=0; rc
==0 && a
&& b
; a
=a
->bp
, b
=b
->bp
){
5590 rc
= a
->rp
->index
- b
->rp
->index
;
5591 if( rc
==0 ) rc
= a
->dot
- b
->dot
;
5601 PRIVATE
unsigned statehash(struct config
*a
)
5605 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5611 /* Allocate a new state structure */
5612 struct state
*State_new()
5614 struct state
*newstate
;
5615 newstate
= (struct state
*)calloc(1, sizeof(struct state
) );
5616 MemoryCheck(newstate
);
5620 /* There is one instance of the following structure for each
5621 ** associative array of type "x3".
5624 int size
; /* The number of available slots. */
5625 /* Must be a power of 2 greater than or */
5627 int count
; /* Number of currently slots filled */
5628 struct s_x3node
*tbl
; /* The data stored here */
5629 struct s_x3node
**ht
; /* Hash table for lookups */
5632 /* There is one instance of this structure for every data element
5633 ** in an associative array of type "x3".
5635 typedef struct s_x3node
{
5636 struct state
*data
; /* The data */
5637 struct config
*key
; /* The key */
5638 struct s_x3node
*next
; /* Next entry with the same hash */
5639 struct s_x3node
**from
; /* Previous link */
5642 /* There is only one instance of the array, which is the following */
5643 static struct s_x3
*x3a
;
5645 /* Allocate a new associative array */
5646 void State_init(void){
5648 x3a
= (struct s_x3
*)malloc( sizeof(struct s_x3
) );
5652 x3a
->tbl
= (x3node
*)calloc(128, sizeof(x3node
) + sizeof(x3node
*));
5658 x3a
->ht
= (x3node
**)&(x3a
->tbl
[128]);
5659 for(i
=0; i
<128; i
++) x3a
->ht
[i
] = 0;
5663 /* Insert a new record into the array. Return TRUE if successful.
5664 ** Prior data with the same key is NOT overwritten */
5665 int State_insert(struct state
*data
, struct config
*key
)
5671 if( x3a
==0 ) return 0;
5672 ph
= statehash(key
);
5673 h
= ph
& (x3a
->size
-1);
5676 if( statecmp(np
->key
,key
)==0 ){
5677 /* An existing entry with the same key is found. */
5678 /* Fail because overwrite is not allows. */
5683 if( x3a
->count
>=x3a
->size
){
5684 /* Need to make the hash table bigger */
5687 array
.size
= arrSize
= x3a
->size
*2;
5688 array
.count
= x3a
->count
;
5689 array
.tbl
= (x3node
*)calloc(arrSize
, sizeof(x3node
) + sizeof(x3node
*));
5690 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5691 array
.ht
= (x3node
**)&(array
.tbl
[arrSize
]);
5692 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5693 for(i
=0; i
<x3a
->count
; i
++){
5694 x3node
*oldnp
, *newnp
;
5695 oldnp
= &(x3a
->tbl
[i
]);
5696 h
= statehash(oldnp
->key
) & (arrSize
-1);
5697 newnp
= &(array
.tbl
[i
]);
5698 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5699 newnp
->next
= array
.ht
[h
];
5700 newnp
->key
= oldnp
->key
;
5701 newnp
->data
= oldnp
->data
;
5702 newnp
->from
= &(array
.ht
[h
]);
5703 array
.ht
[h
] = newnp
;
5708 /* Insert the new data */
5709 h
= ph
& (x3a
->size
-1);
5710 np
= &(x3a
->tbl
[x3a
->count
++]);
5713 if( x3a
->ht
[h
] ) x3a
->ht
[h
]->from
= &(np
->next
);
5714 np
->next
= x3a
->ht
[h
];
5716 np
->from
= &(x3a
->ht
[h
]);
5720 /* Return a pointer to data assigned to the given key. Return NULL
5721 ** if no such key. */
5722 struct state
*State_find(struct config
*key
)
5727 if( x3a
==0 ) return 0;
5728 h
= statehash(key
) & (x3a
->size
-1);
5731 if( statecmp(np
->key
,key
)==0 ) break;
5734 return np
? np
->data
: 0;
5737 /* Return an array of pointers to all data in the table.
5738 ** The array is obtained from malloc. Return NULL if memory allocation
5739 ** problems, or if the array is empty. */
5740 struct state
**State_arrayof(void)
5742 struct state
**array
;
5744 if( x3a
==0 ) return 0;
5745 arrSize
= x3a
->count
;
5746 array
= (struct state
**)calloc(arrSize
, sizeof(struct state
*));
5748 for(i
=0; i
<arrSize
; i
++) array
[i
] = x3a
->tbl
[i
].data
;
5753 /* Hash a configuration */
5754 PRIVATE
unsigned confighash(struct config
*a
)
5757 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5761 /* There is one instance of the following structure for each
5762 ** associative array of type "x4".
5765 int size
; /* The number of available slots. */
5766 /* Must be a power of 2 greater than or */
5768 int count
; /* Number of currently slots filled */
5769 struct s_x4node
*tbl
; /* The data stored here */
5770 struct s_x4node
**ht
; /* Hash table for lookups */
5773 /* There is one instance of this structure for every data element
5774 ** in an associative array of type "x4".
5776 typedef struct s_x4node
{
5777 struct config
*data
; /* The data */
5778 struct s_x4node
*next
; /* Next entry with the same hash */
5779 struct s_x4node
**from
; /* Previous link */
5782 /* There is only one instance of the array, which is the following */
5783 static struct s_x4
*x4a
;
5785 /* Allocate a new associative array */
5786 void Configtable_init(void){
5788 x4a
= (struct s_x4
*)malloc( sizeof(struct s_x4
) );
5792 x4a
->tbl
= (x4node
*)calloc(64, sizeof(x4node
) + sizeof(x4node
*));
5798 x4a
->ht
= (x4node
**)&(x4a
->tbl
[64]);
5799 for(i
=0; i
<64; i
++) x4a
->ht
[i
] = 0;
5803 /* Insert a new record into the array. Return TRUE if successful.
5804 ** Prior data with the same key is NOT overwritten */
5805 int Configtable_insert(struct config
*data
)
5811 if( x4a
==0 ) return 0;
5812 ph
= confighash(data
);
5813 h
= ph
& (x4a
->size
-1);
5816 if( Configcmp((const char *) np
->data
,(const char *) data
)==0 ){
5817 /* An existing entry with the same key is found. */
5818 /* Fail because overwrite is not allows. */
5823 if( x4a
->count
>=x4a
->size
){
5824 /* Need to make the hash table bigger */
5827 array
.size
= arrSize
= x4a
->size
*2;
5828 array
.count
= x4a
->count
;
5829 array
.tbl
= (x4node
*)calloc(arrSize
, sizeof(x4node
) + sizeof(x4node
*));
5830 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5831 array
.ht
= (x4node
**)&(array
.tbl
[arrSize
]);
5832 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5833 for(i
=0; i
<x4a
->count
; i
++){
5834 x4node
*oldnp
, *newnp
;
5835 oldnp
= &(x4a
->tbl
[i
]);
5836 h
= confighash(oldnp
->data
) & (arrSize
-1);
5837 newnp
= &(array
.tbl
[i
]);
5838 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5839 newnp
->next
= array
.ht
[h
];
5840 newnp
->data
= oldnp
->data
;
5841 newnp
->from
= &(array
.ht
[h
]);
5842 array
.ht
[h
] = newnp
;
5847 /* Insert the new data */
5848 h
= ph
& (x4a
->size
-1);
5849 np
= &(x4a
->tbl
[x4a
->count
++]);
5851 if( x4a
->ht
[h
] ) x4a
->ht
[h
]->from
= &(np
->next
);
5852 np
->next
= x4a
->ht
[h
];
5854 np
->from
= &(x4a
->ht
[h
]);
5858 /* Return a pointer to data assigned to the given key. Return NULL
5859 ** if no such key. */
5860 struct config
*Configtable_find(struct config
*key
)
5865 if( x4a
==0 ) return 0;
5866 h
= confighash(key
) & (x4a
->size
-1);
5869 if( Configcmp((const char *) np
->data
,(const char *) key
)==0 ) break;
5872 return np
? np
->data
: 0;
5875 /* Remove all data from the table. Pass each data to the function "f"
5876 ** as it is removed. ("f" may be null to avoid this step.) */
5877 void Configtable_clear(int(*f
)(struct config
*))
5880 if( x4a
==0 || x4a
->count
==0 ) return;
5881 if( f
) for(i
=0; i
<x4a
->count
; i
++) (*f
)(x4a
->tbl
[i
].data
);
5882 for(i
=0; i
<x4a
->size
; i
++) x4a
->ht
[i
] = 0;