2 ** This file contains all sources (including headers) to the LEMON
3 ** LALR(1) parser generator. The sources have been combined into a
4 ** single file to make it easy to include LEMON in the source tree
5 ** and Makefile of another program.
7 ** The author of this program disclaims copyright.
16 #define ISSPACE(X) isspace((unsigned char)(X))
17 #define ISDIGIT(X) isdigit((unsigned char)(X))
18 #define ISALNUM(X) isalnum((unsigned char)(X))
19 #define ISALPHA(X) isalpha((unsigned char)(X))
20 #define ISUPPER(X) isupper((unsigned char)(X))
21 #define ISLOWER(X) islower((unsigned char)(X))
25 # if defined(_WIN32) || defined(WIN32)
34 extern int access(const char *path
, int mode
);
42 /* #define PRIVATE static */
46 #define MAXRHS 5 /* Set low to exercise exception code */
51 static int showPrecedenceConflict
= 0;
52 static char *msort(char*,char**,int(*)(const char*,const char*));
55 ** Compilers are getting increasingly pedantic about type conversions
56 ** as C evolves ever closer to Ada.... To work around the latest problems
57 ** we have to define the following variant of strlen().
59 #define lemonStrlen(X) ((int)strlen(X))
62 ** Compilers are starting to complain about the use of sprintf() and strcpy(),
63 ** saying they are unsafe. So we define our own versions of those routines too.
65 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
66 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
67 ** The third is a helper routine for vsnprintf() that adds texts to the end of a
68 ** buffer, making sure the buffer is always zero-terminated.
70 ** The string formatter is a minimal subset of stdlib sprintf() supporting only
71 ** a few simply conversions:
78 static void lemon_addtext(
79 char *zBuf
, /* The buffer to which text is added */
80 int *pnUsed
, /* Slots of the buffer used so far */
81 const char *zIn
, /* Text to add */
82 int nIn
, /* Bytes of text to add. -1 to use strlen() */
83 int iWidth
/* Field width. Negative to left justify */
85 if( nIn
<0 ) for(nIn
=0; zIn
[nIn
]; nIn
++){}
86 while( iWidth
>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
--; }
88 memcpy(&zBuf
[*pnUsed
], zIn
, nIn
);
90 while( (-iWidth
)>nIn
){ zBuf
[(*pnUsed
)++] = ' '; iWidth
++; }
93 static int lemon_vsprintf(char *str
, const char *zFormat
, va_list ap
){
99 for(i
=j
=0; (c
= zFormat
[i
])!=0; i
++){
102 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
104 if( ISDIGIT(c
) || (c
=='-' && ISDIGIT(zFormat
[i
+1])) ){
106 while( ISDIGIT(zFormat
[i
]) ) iWidth
= iWidth
*10 + zFormat
[i
++] - '0';
107 if( c
=='-' ) iWidth
= -iWidth
;
111 int v
= va_arg(ap
, int);
113 lemon_addtext(str
, &nUsed
, "-", 1, iWidth
);
116 lemon_addtext(str
, &nUsed
, "0", 1, iWidth
);
121 zTemp
[sizeof(zTemp
)-k
] = (v
%10) + '0';
124 lemon_addtext(str
, &nUsed
, &zTemp
[sizeof(zTemp
)-k
], k
, iWidth
);
126 z
= va_arg(ap
, const char*);
127 lemon_addtext(str
, &nUsed
, z
, -1, iWidth
);
128 }else if( c
=='.' && memcmp(&zFormat
[i
], ".*s", 3)==0 ){
131 z
= va_arg(ap
, const char*);
132 lemon_addtext(str
, &nUsed
, z
, k
, iWidth
);
134 lemon_addtext(str
, &nUsed
, "%", 1, 0);
136 fprintf(stderr
, "illegal format\n");
142 lemon_addtext(str
, &nUsed
, &zFormat
[j
], i
-j
, 0);
145 static int lemon_sprintf(char *str
, const char *format
, ...){
148 va_start(ap
, format
);
149 rc
= lemon_vsprintf(str
, format
, ap
);
153 static void lemon_strcpy(char *dest
, const char *src
){
154 while( (*(dest
++) = *(src
++))!=0 ){}
156 static void lemon_strcat(char *dest
, const char *src
){
157 while( *dest
) dest
++;
158 lemon_strcpy(dest
, src
);
162 /* a few forward declarations... */
167 static struct action
*Action_new(void);
168 static struct action
*Action_sort(struct action
*);
170 /********** From the file "build.h" ************************************/
171 void FindRulePrecedences(struct lemon
*);
172 void FindFirstSets(struct lemon
*);
173 void FindStates(struct lemon
*);
174 void FindLinks(struct lemon
*);
175 void FindFollowSets(struct lemon
*);
176 void FindActions(struct lemon
*);
178 /********* From the file "configlist.h" *********************************/
179 void Configlist_init(void);
180 struct config
*Configlist_add(struct rule
*, int);
181 struct config
*Configlist_addbasis(struct rule
*, int);
182 void Configlist_closure(struct lemon
*);
183 void Configlist_sort(void);
184 void Configlist_sortbasis(void);
185 struct config
*Configlist_return(void);
186 struct config
*Configlist_basis(void);
187 void Configlist_eat(struct config
*);
188 void Configlist_reset(void);
190 /********* From the file "error.h" ***************************************/
191 void ErrorMsg(const char *, int,const char *, ...);
193 /****** From the file "option.h" ******************************************/
194 enum option_type
{ OPT_FLAG
=1, OPT_INT
, OPT_DBL
, OPT_STR
,
195 OPT_FFLAG
, OPT_FINT
, OPT_FDBL
, OPT_FSTR
};
197 enum option_type type
;
202 int OptInit(char**,struct s_options
*,FILE*);
208 /******** From the file "parse.h" *****************************************/
209 void Parse(struct lemon
*lemp
);
211 /********* From the file "plink.h" ***************************************/
212 struct plink
*Plink_new(void);
213 void Plink_add(struct plink
**, struct config
*);
214 void Plink_copy(struct plink
**, struct plink
*);
215 void Plink_delete(struct plink
*);
217 /********** From the file "report.h" *************************************/
218 void Reprint(struct lemon
*);
219 void ReportOutput(struct lemon
*);
220 void ReportTable(struct lemon
*, int);
221 void ReportHeader(struct lemon
*);
222 void CompressTables(struct lemon
*);
223 void ResortStates(struct lemon
*);
225 /********** From the file "set.h" ****************************************/
226 void SetSize(int); /* All sets will be of size N */
227 char *SetNew(void); /* A new set for element 0..N */
228 void SetFree(char*); /* Deallocate a set */
229 int SetAdd(char*,int); /* Add element to a set */
230 int SetUnion(char *,char *); /* A <- A U B, thru element N */
231 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
233 /********** From the file "struct.h" *************************************/
235 ** Principal data structures for the LEMON parser generator.
238 typedef enum {LEMON_FALSE
=0, LEMON_TRUE
} Boolean
;
240 /* Symbols (terminals and nonterminals) of the grammar are stored
241 ** in the following: */
254 const char *name
; /* Name of the symbol */
255 int index
; /* Index number for this symbol */
256 enum symbol_type type
; /* Symbols are all either TERMINALS or NTs */
257 struct rule
*rule
; /* Linked list of rules of this (if an NT) */
258 struct symbol
*fallback
; /* fallback token in case this token doesn't parse */
259 int prec
; /* Precedence if defined (-1 otherwise) */
260 enum e_assoc assoc
; /* Associativity if precedence is defined */
261 char *firstset
; /* First-set for all rules of this symbol */
262 Boolean lambda
; /* True if NT and can generate an empty string */
263 int useCnt
; /* Number of times used */
264 char *destructor
; /* Code which executes whenever this symbol is
265 ** popped from the stack during error processing */
266 int destLineno
; /* Line number for start of destructor. Set to
267 ** -1 for duplicate destructors. */
268 char *datatype
; /* The data type of information held by this
269 ** object. Only used if type==NONTERMINAL */
270 int dtnum
; /* The data type number. In the parser, the value
271 ** stack is a union. The .yy%d element of this
272 ** union is the correct data type for this object */
273 /* The following fields are used by MULTITERMINALs only */
274 int nsubsym
; /* Number of constituent symbols in the MULTI */
275 struct symbol
**subsym
; /* Array of constituent symbols */
278 /* Each production rule in the grammar is stored in the following
281 struct symbol
*lhs
; /* Left-hand side of the rule */
282 const char *lhsalias
; /* Alias for the LHS (NULL if none) */
283 int lhsStart
; /* True if left-hand side is the start symbol */
284 int ruleline
; /* Line number for the rule */
285 int nrhs
; /* Number of RHS symbols */
286 struct symbol
**rhs
; /* The RHS symbols */
287 const char **rhsalias
; /* An alias for each RHS symbol (NULL if none) */
288 int line
; /* Line number at which code begins */
289 const char *code
; /* The code executed when this rule is reduced */
290 const char *codePrefix
; /* Setup code before code[] above */
291 const char *codeSuffix
; /* Breakdown code after code[] above */
292 int noCode
; /* True if this rule has no associated C code */
293 int codeEmitted
; /* True if the code has been emitted already */
294 struct symbol
*precsym
; /* Precedence symbol for this rule */
295 int index
; /* An index number for this rule */
296 int iRule
; /* Rule number as used in the generated tables */
297 Boolean canReduce
; /* True if this rule is ever reduced */
298 Boolean doesReduce
; /* Reduce actions occur after optimization */
299 struct rule
*nextlhs
; /* Next rule with the same LHS */
300 struct rule
*next
; /* Next rule in the global list */
303 /* A configuration is a production rule of the grammar together with
304 ** a mark (dot) showing how much of that rule has been processed so far.
305 ** Configurations also contain a follow-set which is a list of terminal
306 ** symbols which are allowed to immediately follow the end of the rule.
307 ** Every configuration is recorded as an instance of the following: */
313 struct rule
*rp
; /* The rule upon which the configuration is based */
314 int dot
; /* The parse point */
315 char *fws
; /* Follow-set for this configuration only */
316 struct plink
*fplp
; /* Follow-set forward propagation links */
317 struct plink
*bplp
; /* Follow-set backwards propagation links */
318 struct state
*stp
; /* Pointer to state which contains this */
319 enum cfgstatus status
; /* used during followset and shift computations */
320 struct config
*next
; /* Next configuration in the state */
321 struct config
*bp
; /* The next basis configuration */
329 SSCONFLICT
, /* A shift/shift conflict */
330 SRCONFLICT
, /* Was a reduce, but part of a conflict */
331 RRCONFLICT
, /* Was a reduce, but part of a conflict */
332 SH_RESOLVED
, /* Was a shift. Precedence resolved conflict */
333 RD_RESOLVED
, /* Was reduce. Precedence resolved conflict */
334 NOT_USED
, /* Deleted by compression */
335 SHIFTREDUCE
/* Shift first, then reduce */
338 /* Every shift or reduce operation is stored as one of the following */
340 struct symbol
*sp
; /* The look-ahead symbol */
343 struct state
*stp
; /* The new state, if a shift */
344 struct rule
*rp
; /* The rule, if a reduce */
346 struct symbol
*spOpt
; /* SHIFTREDUCE optimization to this symbol */
347 struct action
*next
; /* Next action for this state */
348 struct action
*collide
; /* Next action with the same hash */
351 /* Each state of the generated parser's finite state machine
352 ** is encoded as an instance of the following structure. */
354 struct config
*bp
; /* The basis configurations for this state */
355 struct config
*cfp
; /* All configurations in this set */
356 int statenum
; /* Sequential number for this state */
357 struct action
*ap
; /* List of actions for this state */
358 int nTknAct
, nNtAct
; /* Number of actions on terminals and nonterminals */
359 int iTknOfst
, iNtOfst
; /* yy_action[] offset for terminals and nonterms */
360 int iDfltReduce
; /* Default action is to REDUCE by this rule */
361 struct rule
*pDfltReduce
;/* The default REDUCE rule. */
362 int autoReduce
; /* True if this is an auto-reduce state */
364 #define NO_OFFSET (-2147483647)
366 /* A followset propagation link indicates that the contents of one
367 ** configuration followset should be propagated to another whenever
368 ** the first changes. */
370 struct config
*cfp
; /* The configuration to which linked */
371 struct plink
*next
; /* The next propagate link */
374 /* The state vector for the entire parser generator is recorded as
375 ** follows. (LEMON uses no global variables and makes little use of
376 ** static variables. Fields in the following structure can be thought
377 ** of as begin global variables in the program.) */
379 struct state
**sorted
; /* Table of states sorted by state number */
380 struct rule
*rule
; /* List of all rules */
381 struct rule
*startRule
; /* First rule */
382 int nstate
; /* Number of states */
383 int nxstate
; /* nstate with tail degenerate states removed */
384 int nrule
; /* Number of rules */
385 int nsymbol
; /* Number of terminal and nonterminal symbols */
386 int nterminal
; /* Number of terminal symbols */
387 struct symbol
**symbols
; /* Sorted array of pointers to symbols */
388 int errorcnt
; /* Number of errors */
389 struct symbol
*errsym
; /* The error symbol */
390 struct symbol
*wildcard
; /* Token that matches anything */
391 char *name
; /* Name of the generated parser */
392 char *arg
; /* Declaration of the 3th argument to parser */
393 char *tokentype
; /* Type of terminal symbols in the parser stack */
394 char *vartype
; /* The default type of non-terminal symbols */
395 char *start
; /* Name of the start symbol for the grammar */
396 char *stacksize
; /* Size of the parser stack */
397 char *include
; /* Code to put at the start of the C file */
398 char *error
; /* Code to execute when an error is seen */
399 char *overflow
; /* Code to execute on a stack overflow */
400 char *failure
; /* Code to execute on parser failure */
401 char *accept
; /* Code to execute when the parser excepts */
402 char *extracode
; /* Code appended to the generated file */
403 char *tokendest
; /* Code to execute to destroy token data */
404 char *vardest
; /* Code for the default non-terminal destructor */
405 char *filename
; /* Name of the input file */
406 char *outname
; /* Name of the current output file */
407 char *tokenprefix
; /* A prefix added to token names in the .h file */
408 int nconflict
; /* Number of parsing conflicts */
409 int nactiontab
; /* Number of entries in the yy_action[] table */
410 int tablesize
; /* Total table size of all tables in bytes */
411 int basisflag
; /* Print only basis configurations */
412 int has_fallback
; /* True if any %fallback is seen in the grammar */
413 int nolinenosflag
; /* True if #line statements should not be printed */
414 char *argv0
; /* Name of the program */
417 #define MemoryCheck(X) if((X)==0){ \
418 extern void memory_error(); \
422 /**************** From the file "table.h" *********************************/
424 ** All code in this file has been automatically generated
425 ** from a specification in the file
427 ** by the associative array code building program "aagen".
428 ** Do not edit this file! Instead, edit the specification
429 ** file, then rerun aagen.
432 ** Code for processing tables in the LEMON parser generator.
434 /* Routines for handling a strings */
436 const char *Strsafe(const char *);
438 void Strsafe_init(void);
439 int Strsafe_insert(const char *);
440 const char *Strsafe_find(const char *);
442 /* Routines for handling symbols of the grammar */
444 struct symbol
*Symbol_new(const char *);
445 int Symbolcmpp(const void *, const void *);
446 void Symbol_init(void);
447 int Symbol_insert(struct symbol
*, const char *);
448 struct symbol
*Symbol_find(const char *);
449 struct symbol
*Symbol_Nth(int);
450 int Symbol_count(void);
451 struct symbol
**Symbol_arrayof(void);
453 /* Routines to manage the state table */
455 int Configcmp(const char *, const char *);
456 struct state
*State_new(void);
457 void State_init(void);
458 int State_insert(struct state
*, struct config
*);
459 struct state
*State_find(struct config
*);
460 struct state
**State_arrayof(void);
462 /* Routines used for efficiency in Configlist_add */
464 void Configtable_init(void);
465 int Configtable_insert(struct config
*);
466 struct config
*Configtable_find(struct config
*);
467 void Configtable_clear(int(*)(struct config
*));
469 /****************** From the file "action.c" *******************************/
471 ** Routines processing parser actions in the LEMON parser generator.
474 /* Allocate a new parser action */
475 static struct action
*Action_new(void){
476 static struct action
*freelist
= 0;
477 struct action
*newaction
;
482 freelist
= (struct action
*)calloc(amt
, sizeof(struct action
));
484 fprintf(stderr
,"Unable to allocate memory for a new parser action.");
487 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
488 freelist
[amt
-1].next
= 0;
490 newaction
= freelist
;
491 freelist
= freelist
->next
;
495 /* Compare two actions for sorting purposes. Return negative, zero, or
496 ** positive if the first action is less than, equal to, or greater than
499 static int actioncmp(
504 rc
= ap1
->sp
->index
- ap2
->sp
->index
;
506 rc
= (int)ap1
->type
- (int)ap2
->type
;
508 if( rc
==0 && (ap1
->type
==REDUCE
|| ap1
->type
==SHIFTREDUCE
) ){
509 rc
= ap1
->x
.rp
->index
- ap2
->x
.rp
->index
;
512 rc
= (int) (ap2
- ap1
);
517 /* Sort parser actions */
518 static struct action
*Action_sort(
521 ap
= (struct action
*)msort((char *)ap
,(char **)&ap
->next
,
522 (int(*)(const char*,const char*))actioncmp
);
532 struct action
*newaction
;
533 newaction
= Action_new();
534 newaction
->next
= *app
;
536 newaction
->type
= type
;
538 newaction
->spOpt
= 0;
540 newaction
->x
.stp
= (struct state
*)arg
;
542 newaction
->x
.rp
= (struct rule
*)arg
;
545 /********************** New code to implement the "acttab" module ***********/
547 ** This module implements routines use to construct the yy_action[] table.
551 ** The state of the yy_action table under construction is an instance of
552 ** the following structure.
554 ** The yy_action table maps the pair (state_number, lookahead) into an
555 ** action_number. The table is an array of integers pairs. The state_number
556 ** determines an initial offset into the yy_action array. The lookahead
557 ** value is then added to this initial offset to get an index X into the
558 ** yy_action array. If the aAction[X].lookahead equals the value of the
559 ** of the lookahead input, then the value of the action_number output is
560 ** aAction[X].action. If the lookaheads do not match then the
561 ** default action for the state_number is returned.
563 ** All actions associated with a single state_number are first entered
564 ** into aLookahead[] using multiple calls to acttab_action(). Then the
565 ** actions for that single state_number are placed into the aAction[]
566 ** array with a single call to acttab_insert(). The acttab_insert() call
567 ** also resets the aLookahead[] array in preparation for the next
570 struct lookahead_action
{
571 int lookahead
; /* Value of the lookahead token */
572 int action
; /* Action to take on the given lookahead */
574 typedef struct acttab acttab
;
576 int nAction
; /* Number of used slots in aAction[] */
577 int nActionAlloc
; /* Slots allocated for aAction[] */
578 struct lookahead_action
579 *aAction
, /* The yy_action[] table under construction */
580 *aLookahead
; /* A single new transaction set */
581 int mnLookahead
; /* Minimum aLookahead[].lookahead */
582 int mnAction
; /* Action associated with mnLookahead */
583 int mxLookahead
; /* Maximum aLookahead[].lookahead */
584 int nLookahead
; /* Used slots in aLookahead[] */
585 int nLookaheadAlloc
; /* Slots allocated in aLookahead[] */
588 /* Return the number of entries in the yy_action table */
589 #define acttab_size(X) ((X)->nAction)
591 /* The value for the N-th entry in yy_action */
592 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
594 /* The value for the N-th entry in yy_lookahead */
595 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
597 /* Free all memory associated with the given acttab */
598 void acttab_free(acttab
*p
){
600 free( p
->aLookahead
);
604 /* Allocate a new acttab structure */
605 acttab
*acttab_alloc(void){
606 acttab
*p
= (acttab
*) calloc( 1, sizeof(*p
) );
608 fprintf(stderr
,"Unable to allocate memory for a new acttab.");
611 memset(p
, 0, sizeof(*p
));
615 /* Add a new action to the current transaction set.
617 ** This routine is called once for each lookahead for a particular
620 void acttab_action(acttab
*p
, int lookahead
, int action
){
621 if( p
->nLookahead
>=p
->nLookaheadAlloc
){
622 p
->nLookaheadAlloc
+= 25;
623 p
->aLookahead
= (struct lookahead_action
*) realloc( p
->aLookahead
,
624 sizeof(p
->aLookahead
[0])*p
->nLookaheadAlloc
);
625 if( p
->aLookahead
==0 ){
626 fprintf(stderr
,"malloc failed\n");
630 if( p
->nLookahead
==0 ){
631 p
->mxLookahead
= lookahead
;
632 p
->mnLookahead
= lookahead
;
633 p
->mnAction
= action
;
635 if( p
->mxLookahead
<lookahead
) p
->mxLookahead
= lookahead
;
636 if( p
->mnLookahead
>lookahead
){
637 p
->mnLookahead
= lookahead
;
638 p
->mnAction
= action
;
641 p
->aLookahead
[p
->nLookahead
].lookahead
= lookahead
;
642 p
->aLookahead
[p
->nLookahead
].action
= action
;
647 ** Add the transaction set built up with prior calls to acttab_action()
648 ** into the current action table. Then reset the transaction set back
649 ** to an empty set in preparation for a new round of acttab_action() calls.
651 ** Return the offset into the action table of the new transaction.
653 int acttab_insert(acttab
*p
){
655 assert( p
->nLookahead
>0 );
657 /* Make sure we have enough space to hold the expanded action table
658 ** in the worst case. The worst case occurs if the transaction set
659 ** must be appended to the current action table
661 n
= p
->mxLookahead
+ 1;
662 if( p
->nAction
+ n
>= p
->nActionAlloc
){
663 int oldAlloc
= p
->nActionAlloc
;
664 p
->nActionAlloc
= p
->nAction
+ n
+ p
->nActionAlloc
+ 20;
665 p
->aAction
= (struct lookahead_action
*) realloc( p
->aAction
,
666 sizeof(p
->aAction
[0])*p
->nActionAlloc
);
668 fprintf(stderr
,"malloc failed\n");
671 for(i
=oldAlloc
; i
<p
->nActionAlloc
; i
++){
672 p
->aAction
[i
].lookahead
= -1;
673 p
->aAction
[i
].action
= -1;
677 /* Scan the existing action table looking for an offset that is a
678 ** duplicate of the current transaction set. Fall out of the loop
679 ** if and when the duplicate is found.
681 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
683 for(i
=p
->nAction
-1; i
>=0; i
--){
684 if( p
->aAction
[i
].lookahead
==p
->mnLookahead
){
685 /* All lookaheads and actions in the aLookahead[] transaction
686 ** must match against the candidate aAction[i] entry. */
687 if( p
->aAction
[i
].action
!=p
->mnAction
) continue;
688 for(j
=0; j
<p
->nLookahead
; j
++){
689 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
690 if( k
<0 || k
>=p
->nAction
) break;
691 if( p
->aLookahead
[j
].lookahead
!=p
->aAction
[k
].lookahead
) break;
692 if( p
->aLookahead
[j
].action
!=p
->aAction
[k
].action
) break;
694 if( j
<p
->nLookahead
) continue;
696 /* No possible lookahead value that is not in the aLookahead[]
697 ** transaction is allowed to match aAction[i] */
699 for(j
=0; j
<p
->nAction
; j
++){
700 if( p
->aAction
[j
].lookahead
<0 ) continue;
701 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) n
++;
703 if( n
==p
->nLookahead
){
704 break; /* An exact match is found at offset i */
709 /* If no existing offsets exactly match the current transaction, find an
710 ** an empty offset in the aAction[] table in which we can add the
711 ** aLookahead[] transaction.
714 /* Look for holes in the aAction[] table that fit the current
715 ** aLookahead[] transaction. Leave i set to the offset of the hole.
716 ** If no holes are found, i is left at p->nAction, which means the
717 ** transaction will be appended. */
718 for(i
=0; i
<p
->nActionAlloc
- p
->mxLookahead
; i
++){
719 if( p
->aAction
[i
].lookahead
<0 ){
720 for(j
=0; j
<p
->nLookahead
; j
++){
721 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
723 if( p
->aAction
[k
].lookahead
>=0 ) break;
725 if( j
<p
->nLookahead
) continue;
726 for(j
=0; j
<p
->nAction
; j
++){
727 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) break;
730 break; /* Fits in empty slots */
735 /* Insert transaction set at index i. */
736 for(j
=0; j
<p
->nLookahead
; j
++){
737 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
738 p
->aAction
[k
] = p
->aLookahead
[j
];
739 if( k
>=p
->nAction
) p
->nAction
= k
+1;
743 /* Return the offset that is added to the lookahead in order to get the
744 ** index into yy_action of the action */
745 return i
- p
->mnLookahead
;
748 /********************** From the file "build.c" *****************************/
750 ** Routines to construction the finite state machine for the LEMON
754 /* Find a precedence symbol of every rule in the grammar.
756 ** Those rules which have a precedence symbol coded in the input
757 ** grammar using the "[symbol]" construct will already have the
758 ** rp->precsym field filled. Other rules take as their precedence
759 ** symbol the first RHS symbol with a defined precedence. If there
760 ** are not RHS symbols with a defined precedence, the precedence
761 ** symbol field is left blank.
763 void FindRulePrecedences(struct lemon
*xp
)
766 for(rp
=xp
->rule
; rp
; rp
=rp
->next
){
767 if( rp
->precsym
==0 ){
769 for(i
=0; i
<rp
->nrhs
&& rp
->precsym
==0; i
++){
770 struct symbol
*sp
= rp
->rhs
[i
];
771 if( sp
->type
==MULTITERMINAL
){
772 for(j
=0; j
<sp
->nsubsym
; j
++){
773 if( sp
->subsym
[j
]->prec
>=0 ){
774 rp
->precsym
= sp
->subsym
[j
];
778 }else if( sp
->prec
>=0 ){
779 rp
->precsym
= rp
->rhs
[i
];
787 /* Find all nonterminals which will generate the empty string.
788 ** Then go back and compute the first sets of every nonterminal.
789 ** The first set is the set of all terminal symbols which can begin
790 ** a string generated by that nonterminal.
792 void FindFirstSets(struct lemon
*lemp
)
798 for(i
=0; i
<lemp
->nsymbol
; i
++){
799 lemp
->symbols
[i
]->lambda
= LEMON_FALSE
;
801 for(i
=lemp
->nterminal
; i
<lemp
->nsymbol
; i
++){
802 lemp
->symbols
[i
]->firstset
= SetNew();
805 /* First compute all lambdas */
808 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
809 if( rp
->lhs
->lambda
) continue;
810 for(i
=0; i
<rp
->nrhs
; i
++){
811 struct symbol
*sp
= rp
->rhs
[i
];
812 assert( sp
->type
==NONTERMINAL
|| sp
->lambda
==LEMON_FALSE
);
813 if( sp
->lambda
==LEMON_FALSE
) break;
816 rp
->lhs
->lambda
= LEMON_TRUE
;
822 /* Now compute all first sets */
824 struct symbol
*s1
, *s2
;
826 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
828 for(i
=0; i
<rp
->nrhs
; i
++){
830 if( s2
->type
==TERMINAL
){
831 progress
+= SetAdd(s1
->firstset
,s2
->index
);
833 }else if( s2
->type
==MULTITERMINAL
){
834 for(j
=0; j
<s2
->nsubsym
; j
++){
835 progress
+= SetAdd(s1
->firstset
,s2
->subsym
[j
]->index
);
839 if( s1
->lambda
==LEMON_FALSE
) break;
841 progress
+= SetUnion(s1
->firstset
,s2
->firstset
);
842 if( s2
->lambda
==LEMON_FALSE
) break;
850 /* Compute all LR(0) states for the grammar. Links
851 ** are added to between some states so that the LR(1) follow sets
852 ** can be computed later.
854 PRIVATE
struct state
*getstate(struct lemon
*); /* forward reference */
855 void FindStates(struct lemon
*lemp
)
862 /* Find the start symbol */
864 sp
= Symbol_find(lemp
->start
);
866 ErrorMsg(lemp
->filename
,0,
867 "The specified start symbol \"%s\" is not \
868 in a nonterminal of the grammar. \"%s\" will be used as the start \
869 symbol instead.",lemp
->start
,lemp
->startRule
->lhs
->name
);
871 sp
= lemp
->startRule
->lhs
;
874 sp
= lemp
->startRule
->lhs
;
877 /* Make sure the start symbol doesn't occur on the right-hand side of
878 ** any rule. Report an error if it does. (YACC would generate a new
879 ** start symbol in this case.) */
880 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
882 for(i
=0; i
<rp
->nrhs
; i
++){
883 if( rp
->rhs
[i
]==sp
){ /* FIX ME: Deal with multiterminals */
884 ErrorMsg(lemp
->filename
,0,
885 "The start symbol \"%s\" occurs on the \
886 right-hand side of a rule. This will result in a parser which \
887 does not work properly.",sp
->name
);
893 /* The basis configuration set for the first state
894 ** is all rules which have the start symbol as their
896 for(rp
=sp
->rule
; rp
; rp
=rp
->nextlhs
){
897 struct config
*newcfp
;
899 newcfp
= Configlist_addbasis(rp
,0);
900 SetAdd(newcfp
->fws
,0);
903 /* Compute the first state. All other states will be
904 ** computed automatically during the computation of the first one.
905 ** The returned pointer to the first state is not used. */
906 (void)getstate(lemp
);
910 /* Return a pointer to a state which is described by the configuration
911 ** list which has been built from calls to Configlist_add.
913 PRIVATE
void buildshifts(struct lemon
*, struct state
*); /* Forwd ref */
914 PRIVATE
struct state
*getstate(struct lemon
*lemp
)
916 struct config
*cfp
, *bp
;
919 /* Extract the sorted basis of the new state. The basis was constructed
920 ** by prior calls to "Configlist_addbasis()". */
921 Configlist_sortbasis();
922 bp
= Configlist_basis();
924 /* Get a state with the same basis */
925 stp
= State_find(bp
);
927 /* A state with the same basis already exists! Copy all the follow-set
928 ** propagation links from the state under construction into the
929 ** preexisting state, then return a pointer to the preexisting state */
930 struct config
*x
, *y
;
931 for(x
=bp
, y
=stp
->bp
; x
&& y
; x
=x
->bp
, y
=y
->bp
){
932 Plink_copy(&y
->bplp
,x
->bplp
);
933 Plink_delete(x
->fplp
);
934 x
->fplp
= x
->bplp
= 0;
936 cfp
= Configlist_return();
939 /* This really is a new state. Construct all the details */
940 Configlist_closure(lemp
); /* Compute the configuration closure */
941 Configlist_sort(); /* Sort the configuration closure */
942 cfp
= Configlist_return(); /* Get a pointer to the config list */
943 stp
= State_new(); /* A new state structure */
945 stp
->bp
= bp
; /* Remember the configuration basis */
946 stp
->cfp
= cfp
; /* Remember the configuration closure */
947 stp
->statenum
= lemp
->nstate
++; /* Every state gets a sequence number */
948 stp
->ap
= 0; /* No actions, yet. */
949 State_insert(stp
,stp
->bp
); /* Add to the state table */
950 buildshifts(lemp
,stp
); /* Recursively compute successor states */
956 ** Return true if two symbols are the same.
958 int same_symbol(struct symbol
*a
, struct symbol
*b
)
962 if( a
->type
!=MULTITERMINAL
) return 0;
963 if( b
->type
!=MULTITERMINAL
) return 0;
964 if( a
->nsubsym
!=b
->nsubsym
) return 0;
965 for(i
=0; i
<a
->nsubsym
; i
++){
966 if( a
->subsym
[i
]!=b
->subsym
[i
] ) return 0;
971 /* Construct all successor states to the given state. A "successor"
972 ** state is any state which can be reached by a shift action.
974 PRIVATE
void buildshifts(struct lemon
*lemp
, struct state
*stp
)
976 struct config
*cfp
; /* For looping thru the config closure of "stp" */
977 struct config
*bcfp
; /* For the inner loop on config closure of "stp" */
978 struct config
*newcfg
; /* */
979 struct symbol
*sp
; /* Symbol following the dot in configuration "cfp" */
980 struct symbol
*bsp
; /* Symbol following the dot in configuration "bcfp" */
981 struct state
*newstp
; /* A pointer to a successor state */
983 /* Each configuration becomes complete after it contibutes to a successor
984 ** state. Initially, all configurations are incomplete */
985 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
) cfp
->status
= INCOMPLETE
;
987 /* Loop through all configurations of the state "stp" */
988 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
989 if( cfp
->status
==COMPLETE
) continue; /* Already used by inner loop */
990 if( cfp
->dot
>=cfp
->rp
->nrhs
) continue; /* Can't shift this config */
991 Configlist_reset(); /* Reset the new config set */
992 sp
= cfp
->rp
->rhs
[cfp
->dot
]; /* Symbol after the dot */
994 /* For every configuration in the state "stp" which has the symbol "sp"
995 ** following its dot, add the same configuration to the basis set under
996 ** construction but with the dot shifted one symbol to the right. */
997 for(bcfp
=cfp
; bcfp
; bcfp
=bcfp
->next
){
998 if( bcfp
->status
==COMPLETE
) continue; /* Already used */
999 if( bcfp
->dot
>=bcfp
->rp
->nrhs
) continue; /* Can't shift this one */
1000 bsp
= bcfp
->rp
->rhs
[bcfp
->dot
]; /* Get symbol after dot */
1001 if( !same_symbol(bsp
,sp
) ) continue; /* Must be same as for "cfp" */
1002 bcfp
->status
= COMPLETE
; /* Mark this config as used */
1003 newcfg
= Configlist_addbasis(bcfp
->rp
,bcfp
->dot
+1);
1004 Plink_add(&newcfg
->bplp
,bcfp
);
1007 /* Get a pointer to the state described by the basis configuration set
1008 ** constructed in the preceding loop */
1009 newstp
= getstate(lemp
);
1011 /* The state "newstp" is reached from the state "stp" by a shift action
1012 ** on the symbol "sp" */
1013 if( sp
->type
==MULTITERMINAL
){
1015 for(i
=0; i
<sp
->nsubsym
; i
++){
1016 Action_add(&stp
->ap
,SHIFT
,sp
->subsym
[i
],(char*)newstp
);
1019 Action_add(&stp
->ap
,SHIFT
,sp
,(char *)newstp
);
1025 ** Construct the propagation links
1027 void FindLinks(struct lemon
*lemp
)
1030 struct config
*cfp
, *other
;
1034 /* Housekeeping detail:
1035 ** Add to every propagate link a pointer back to the state to
1036 ** which the link is attached. */
1037 for(i
=0; i
<lemp
->nstate
; i
++){
1038 stp
= lemp
->sorted
[i
];
1039 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1044 /* Convert all backlinks into forward links. Only the forward
1045 ** links are used in the follow-set computation. */
1046 for(i
=0; i
<lemp
->nstate
; i
++){
1047 stp
= lemp
->sorted
[i
];
1048 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
1049 for(plp
=cfp
->bplp
; plp
; plp
=plp
->next
){
1051 Plink_add(&other
->fplp
,cfp
);
1057 /* Compute all followsets.
1059 ** A followset is the set of all symbols which can come immediately
1060 ** after a configuration.
1062 void FindFollowSets(struct lemon
*lemp
)
1070 for(i
=0; i
<lemp
->nstate
; i
++){
1071 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1072 cfp
->status
= INCOMPLETE
;
1078 for(i
=0; i
<lemp
->nstate
; i
++){
1079 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
1080 if( cfp
->status
==COMPLETE
) continue;
1081 for(plp
=cfp
->fplp
; plp
; plp
=plp
->next
){
1082 change
= SetUnion(plp
->cfp
->fws
,cfp
->fws
);
1084 plp
->cfp
->status
= INCOMPLETE
;
1088 cfp
->status
= COMPLETE
;
1094 static int resolve_conflict(struct action
*,struct action
*);
1096 /* Compute the reduce actions, and resolve conflicts.
1098 void FindActions(struct lemon
*lemp
)
1106 /* Add all of the reduce actions
1107 ** A reduce action is added for each element of the followset of
1108 ** a configuration which has its dot at the extreme right.
1110 for(i
=0; i
<lemp
->nstate
; i
++){ /* Loop over all states */
1111 stp
= lemp
->sorted
[i
];
1112 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){ /* Loop over all configurations */
1113 if( cfp
->rp
->nrhs
==cfp
->dot
){ /* Is dot at extreme right? */
1114 for(j
=0; j
<lemp
->nterminal
; j
++){
1115 if( SetFind(cfp
->fws
,j
) ){
1116 /* Add a reduce action to the state "stp" which will reduce by the
1117 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
1118 Action_add(&stp
->ap
,REDUCE
,lemp
->symbols
[j
],(char *)cfp
->rp
);
1125 /* Add the accepting token */
1127 sp
= Symbol_find(lemp
->start
);
1128 if( sp
==0 ) sp
= lemp
->startRule
->lhs
;
1130 sp
= lemp
->startRule
->lhs
;
1132 /* Add to the first state (which is always the starting state of the
1133 ** finite state machine) an action to ACCEPT if the lookahead is the
1134 ** start nonterminal. */
1135 Action_add(&lemp
->sorted
[0]->ap
,ACCEPT
,sp
,0);
1137 /* Resolve conflicts */
1138 for(i
=0; i
<lemp
->nstate
; i
++){
1139 struct action
*ap
, *nap
;
1140 stp
= lemp
->sorted
[i
];
1141 /* assert( stp->ap ); */
1142 stp
->ap
= Action_sort(stp
->ap
);
1143 for(ap
=stp
->ap
; ap
&& ap
->next
; ap
=ap
->next
){
1144 for(nap
=ap
->next
; nap
&& nap
->sp
==ap
->sp
; nap
=nap
->next
){
1145 /* The two actions "ap" and "nap" have the same lookahead.
1146 ** Figure out which one should be used */
1147 lemp
->nconflict
+= resolve_conflict(ap
,nap
);
1152 /* Report an error for each rule that can never be reduced. */
1153 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->canReduce
= LEMON_FALSE
;
1154 for(i
=0; i
<lemp
->nstate
; i
++){
1156 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
1157 if( ap
->type
==REDUCE
) ap
->x
.rp
->canReduce
= LEMON_TRUE
;
1160 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
1161 if( rp
->canReduce
) continue;
1162 ErrorMsg(lemp
->filename
,rp
->ruleline
,"This rule can not be reduced.\n");
1167 /* Resolve a conflict between the two given actions. If the
1168 ** conflict can't be resolved, return non-zero.
1171 ** To resolve a conflict, first look to see if either action
1172 ** is on an error rule. In that case, take the action which
1173 ** is not associated with the error rule. If neither or both
1174 ** actions are associated with an error rule, then try to
1175 ** use precedence to resolve the conflict.
1177 ** If either action is a SHIFT, then it must be apx. This
1178 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1180 static int resolve_conflict(
1184 struct symbol
*spx
, *spy
;
1186 assert( apx
->sp
==apy
->sp
); /* Otherwise there would be no conflict */
1187 if( apx
->type
==SHIFT
&& apy
->type
==SHIFT
){
1188 apy
->type
= SSCONFLICT
;
1191 if( apx
->type
==SHIFT
&& apy
->type
==REDUCE
){
1193 spy
= apy
->x
.rp
->precsym
;
1194 if( spy
==0 || spx
->prec
<0 || spy
->prec
<0 ){
1195 /* Not enough precedence information. */
1196 apy
->type
= SRCONFLICT
;
1198 }else if( spx
->prec
>spy
->prec
){ /* higher precedence wins */
1199 apy
->type
= RD_RESOLVED
;
1200 }else if( spx
->prec
<spy
->prec
){
1201 apx
->type
= SH_RESOLVED
;
1202 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==RIGHT
){ /* Use operator */
1203 apy
->type
= RD_RESOLVED
; /* associativity */
1204 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==LEFT
){ /* to break tie */
1205 apx
->type
= SH_RESOLVED
;
1207 assert( spx
->prec
==spy
->prec
&& spx
->assoc
==NONE
);
1210 }else if( apx
->type
==REDUCE
&& apy
->type
==REDUCE
){
1211 spx
= apx
->x
.rp
->precsym
;
1212 spy
= apy
->x
.rp
->precsym
;
1213 if( spx
==0 || spy
==0 || spx
->prec
<0 ||
1214 spy
->prec
<0 || spx
->prec
==spy
->prec
){
1215 apy
->type
= RRCONFLICT
;
1217 }else if( spx
->prec
>spy
->prec
){
1218 apy
->type
= RD_RESOLVED
;
1219 }else if( spx
->prec
<spy
->prec
){
1220 apx
->type
= RD_RESOLVED
;
1224 apx
->type
==SH_RESOLVED
||
1225 apx
->type
==RD_RESOLVED
||
1226 apx
->type
==SSCONFLICT
||
1227 apx
->type
==SRCONFLICT
||
1228 apx
->type
==RRCONFLICT
||
1229 apy
->type
==SH_RESOLVED
||
1230 apy
->type
==RD_RESOLVED
||
1231 apy
->type
==SSCONFLICT
||
1232 apy
->type
==SRCONFLICT
||
1233 apy
->type
==RRCONFLICT
1235 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1236 ** REDUCEs on the list. If we reach this point it must be because
1237 ** the parser conflict had already been resolved. */
1241 /********************* From the file "configlist.c" *************************/
1243 ** Routines to processing a configuration list and building a state
1244 ** in the LEMON parser generator.
1247 static struct config
*freelist
= 0; /* List of free configurations */
1248 static struct config
*current
= 0; /* Top of list of configurations */
1249 static struct config
**currentend
= 0; /* Last on list of configs */
1250 static struct config
*basis
= 0; /* Top of list of basis configs */
1251 static struct config
**basisend
= 0; /* End of list of basis configs */
1253 /* Return a pointer to a new configuration */
1254 PRIVATE
struct config
*newconfig(void){
1255 struct config
*newcfg
;
1259 freelist
= (struct config
*)calloc( amt
, sizeof(struct config
) );
1261 fprintf(stderr
,"Unable to allocate memory for a new configuration.");
1264 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
1265 freelist
[amt
-1].next
= 0;
1268 freelist
= freelist
->next
;
1272 /* The configuration "old" is no longer used */
1273 PRIVATE
void deleteconfig(struct config
*old
)
1275 old
->next
= freelist
;
1279 /* Initialized the configuration list builder */
1280 void Configlist_init(void){
1282 currentend
= ¤t
;
1289 /* Initialized the configuration list builder */
1290 void Configlist_reset(void){
1292 currentend
= ¤t
;
1295 Configtable_clear(0);
1299 /* Add another configuration to the configuration list */
1300 struct config
*Configlist_add(
1301 struct rule
*rp
, /* The rule */
1302 int dot
/* Index into the RHS of the rule where the dot goes */
1304 struct config
*cfp
, model
;
1306 assert( currentend
!=0 );
1309 cfp
= Configtable_find(&model
);
1314 cfp
->fws
= SetNew();
1316 cfp
->fplp
= cfp
->bplp
= 0;
1320 currentend
= &cfp
->next
;
1321 Configtable_insert(cfp
);
1326 /* Add a basis configuration to the configuration list */
1327 struct config
*Configlist_addbasis(struct rule
*rp
, int dot
)
1329 struct config
*cfp
, model
;
1331 assert( basisend
!=0 );
1332 assert( currentend
!=0 );
1335 cfp
= Configtable_find(&model
);
1340 cfp
->fws
= SetNew();
1342 cfp
->fplp
= cfp
->bplp
= 0;
1346 currentend
= &cfp
->next
;
1348 basisend
= &cfp
->bp
;
1349 Configtable_insert(cfp
);
1354 /* Compute the closure of the configuration list */
1355 void Configlist_closure(struct lemon
*lemp
)
1357 struct config
*cfp
, *newcfp
;
1358 struct rule
*rp
, *newrp
;
1359 struct symbol
*sp
, *xsp
;
1362 assert( currentend
!=0 );
1363 for(cfp
=current
; cfp
; cfp
=cfp
->next
){
1366 if( dot
>=rp
->nrhs
) continue;
1368 if( sp
->type
==NONTERMINAL
){
1369 if( sp
->rule
==0 && sp
!=lemp
->errsym
){
1370 ErrorMsg(lemp
->filename
,rp
->line
,"Nonterminal \"%s\" has no rules.",
1374 for(newrp
=sp
->rule
; newrp
; newrp
=newrp
->nextlhs
){
1375 newcfp
= Configlist_add(newrp
,0);
1376 for(i
=dot
+1; i
<rp
->nrhs
; i
++){
1378 if( xsp
->type
==TERMINAL
){
1379 SetAdd(newcfp
->fws
,xsp
->index
);
1381 }else if( xsp
->type
==MULTITERMINAL
){
1383 for(k
=0; k
<xsp
->nsubsym
; k
++){
1384 SetAdd(newcfp
->fws
, xsp
->subsym
[k
]->index
);
1388 SetUnion(newcfp
->fws
,xsp
->firstset
);
1389 if( xsp
->lambda
==LEMON_FALSE
) break;
1392 if( i
==rp
->nrhs
) Plink_add(&cfp
->fplp
,newcfp
);
1399 /* Sort the configuration list */
1400 void Configlist_sort(void){
1401 current
= (struct config
*)msort((char*)current
,(char**)&(current
->next
),
1407 /* Sort the basis configuration list */
1408 void Configlist_sortbasis(void){
1409 basis
= (struct config
*)msort((char*)current
,(char**)&(current
->bp
),
1415 /* Return a pointer to the head of the configuration list and
1416 ** reset the list */
1417 struct config
*Configlist_return(void){
1425 /* Return a pointer to the head of the configuration list and
1426 ** reset the list */
1427 struct config
*Configlist_basis(void){
1435 /* Free all elements of the given configuration list */
1436 void Configlist_eat(struct config
*cfp
)
1438 struct config
*nextcfp
;
1439 for(; cfp
; cfp
=nextcfp
){
1440 nextcfp
= cfp
->next
;
1441 assert( cfp
->fplp
==0 );
1442 assert( cfp
->bplp
==0 );
1443 if( cfp
->fws
) SetFree(cfp
->fws
);
1448 /***************** From the file "error.c" *********************************/
1450 ** Code for printing error message.
1453 void ErrorMsg(const char *filename
, int lineno
, const char *format
, ...){
1455 fprintf(stderr
, "%s:%d: ", filename
, lineno
);
1456 va_start(ap
, format
);
1457 vfprintf(stderr
,format
,ap
);
1459 fprintf(stderr
, "\n");
1461 /**************** From the file "main.c" ************************************/
1463 ** Main program file for the LEMON parser generator.
1466 /* Report an out-of-memory condition and abort. This function
1467 ** is used mostly by the "MemoryCheck" macro in struct.h
1469 void memory_error(void){
1470 fprintf(stderr
,"Out of memory. Aborting...\n");
1474 static int nDefine
= 0; /* Number of -D options on the command line */
1475 static char **azDefine
= 0; /* Name of the -D macros */
1477 /* This routine is called with the argument to each -D command-line option.
1478 ** Add the macro defined to the azDefine array.
1480 static void handle_D_option(char *z
){
1483 azDefine
= (char **) realloc(azDefine
, sizeof(azDefine
[0])*nDefine
);
1485 fprintf(stderr
,"out of memory\n");
1488 paz
= &azDefine
[nDefine
-1];
1489 *paz
= (char *) malloc( lemonStrlen(z
)+1 );
1491 fprintf(stderr
,"out of memory\n");
1494 lemon_strcpy(*paz
, z
);
1495 for(z
=*paz
; *z
&& *z
!='='; z
++){}
1499 static char *user_templatename
= NULL
;
1500 static void handle_T_option(char *z
){
1501 user_templatename
= (char *) malloc( lemonStrlen(z
)+1 );
1502 if( user_templatename
==0 ){
1505 lemon_strcpy(user_templatename
, z
);
1508 /* Merge together to lists of rules ordered by rule.iRule */
1509 static struct rule
*Rule_merge(struct rule
*pA
, struct rule
*pB
){
1510 struct rule
*pFirst
= 0;
1511 struct rule
**ppPrev
= &pFirst
;
1513 if( pA
->iRule
<pB
->iRule
){
1532 ** Sort a list of rules in order of increasing iRule value
1534 static struct rule
*Rule_sort(struct rule
*rp
){
1538 memset(x
, 0, sizeof(x
));
1542 for(i
=0; i
<sizeof(x
)/sizeof(x
[0]) && x
[i
]; i
++){
1543 rp
= Rule_merge(x
[i
], rp
);
1550 for(i
=0; i
<sizeof(x
)/sizeof(x
[0]); i
++){
1551 rp
= Rule_merge(x
[i
], rp
);
1556 /* forward reference */
1557 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
);
1559 /* Print a single line of the "Parser Stats" output
1561 static void stats_line(const char *zLabel
, int iValue
){
1562 int nLabel
= lemonStrlen(zLabel
);
1563 printf(" %s%.*s %5d\n", zLabel
,
1564 35-nLabel
, "................................",
1568 /* The main program. Parse the command line and do it... */
1569 int main(int argc
, char **argv
)
1571 static int version
= 0;
1572 static int rpflag
= 0;
1573 static int basisflag
= 0;
1574 static int compress
= 0;
1575 static int quiet
= 0;
1576 static int statistics
= 0;
1577 static int mhflag
= 0;
1578 static int nolinenosflag
= 0;
1579 static int noResort
= 0;
1580 static struct s_options options
[] = {
1581 {OPT_FLAG
, "b", (char*)&basisflag
, "Print only the basis in report."},
1582 {OPT_FLAG
, "c", (char*)&compress
, "Don't compress the action table."},
1583 {OPT_FSTR
, "D", (char*)handle_D_option
, "Define an %ifdef macro."},
1584 {OPT_FSTR
, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
1585 {OPT_FLAG
, "g", (char*)&rpflag
, "Print grammar without actions."},
1586 {OPT_FSTR
, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
1587 {OPT_FLAG
, "m", (char*)&mhflag
, "Output a makeheaders compatible file."},
1588 {OPT_FLAG
, "l", (char*)&nolinenosflag
, "Do not print #line statements."},
1589 {OPT_FSTR
, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
1590 {OPT_FLAG
, "p", (char*)&showPrecedenceConflict
,
1591 "Show conflicts resolved by precedence rules"},
1592 {OPT_FLAG
, "q", (char*)&quiet
, "(Quiet) Don't print the report file."},
1593 {OPT_FLAG
, "r", (char*)&noResort
, "Do not sort or renumber states"},
1594 {OPT_FLAG
, "s", (char*)&statistics
,
1595 "Print parser stats to standard output."},
1596 {OPT_FLAG
, "x", (char*)&version
, "Print the version number."},
1597 {OPT_FSTR
, "T", (char*)handle_T_option
, "Specify a template file."},
1598 {OPT_FSTR
, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
1606 OptInit(argv
,options
,stderr
);
1608 printf("Lemon version 1.0\n");
1611 if( OptNArgs()!=1 ){
1612 fprintf(stderr
,"Exactly one filename argument is required.\n");
1615 memset(&lem
, 0, sizeof(lem
));
1618 /* Initialize the machine */
1622 lem
.argv0
= argv
[0];
1623 lem
.filename
= OptArg(0);
1624 lem
.basisflag
= basisflag
;
1625 lem
.nolinenosflag
= nolinenosflag
;
1627 lem
.errsym
= Symbol_new("error");
1628 lem
.errsym
->useCnt
= 0;
1630 /* Parse the input file */
1632 if( lem
.errorcnt
) exit(lem
.errorcnt
);
1634 fprintf(stderr
,"Empty grammar.\n");
1638 /* Count and index the symbols of the grammar */
1639 Symbol_new("{default}");
1640 lem
.nsymbol
= Symbol_count();
1641 lem
.symbols
= Symbol_arrayof();
1642 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1643 qsort(lem
.symbols
,lem
.nsymbol
,sizeof(struct symbol
*), Symbolcmpp
);
1644 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1645 while( lem
.symbols
[i
-1]->type
==MULTITERMINAL
){ i
--; }
1646 assert( strcmp(lem
.symbols
[i
-1]->name
,"{default}")==0 );
1647 lem
.nsymbol
= i
- 1;
1648 for(i
=1; ISUPPER(lem
.symbols
[i
]->name
[0]); i
++);
1651 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1652 ** reduce action C-code associated with them last, so that the switch()
1653 ** statement that selects reduction actions will have a smaller jump table.
1655 for(i
=0, rp
=lem
.rule
; rp
; rp
=rp
->next
){
1656 rp
->iRule
= rp
->code
? i
++ : -1;
1658 for(rp
=lem
.rule
; rp
; rp
=rp
->next
){
1659 if( rp
->iRule
<0 ) rp
->iRule
= i
++;
1661 lem
.startRule
= lem
.rule
;
1662 lem
.rule
= Rule_sort(lem
.rule
);
1664 /* Generate a reprint of the grammar, if requested on the command line */
1668 /* Initialize the size for all follow and first sets */
1669 SetSize(lem
.nterminal
+1);
1671 /* Find the precedence for every production rule (that has one) */
1672 FindRulePrecedences(&lem
);
1674 /* Compute the lambda-nonterminals and the first-sets for every
1676 FindFirstSets(&lem
);
1678 /* Compute all LR(0) states. Also record follow-set propagation
1679 ** links so that the follow-set can be computed later */
1682 lem
.sorted
= State_arrayof();
1684 /* Tie up loose ends on the propagation links */
1687 /* Compute the follow set of every reducible configuration */
1688 FindFollowSets(&lem
);
1690 /* Compute the action tables */
1693 /* Compress the action tables */
1694 if( compress
==0 ) CompressTables(&lem
);
1696 /* Reorder and renumber the states so that states with fewer choices
1697 ** occur at the end. This is an optimization that helps make the
1698 ** generated parser tables smaller. */
1699 if( noResort
==0 ) ResortStates(&lem
);
1701 /* Generate a report of the parser generated. (the "y.output" file) */
1702 if( !quiet
) ReportOutput(&lem
);
1704 /* Generate the source code for the parser */
1705 ReportTable(&lem
, mhflag
);
1707 /* Produce a header file for use by the scanner. (This step is
1708 ** omitted if the "-m" option is used because makeheaders will
1709 ** generate the file for us.) */
1710 if( !mhflag
) ReportHeader(&lem
);
1713 printf("Parser statistics:\n");
1714 stats_line("terminal symbols", lem
.nterminal
);
1715 stats_line("non-terminal symbols", lem
.nsymbol
- lem
.nterminal
);
1716 stats_line("total symbols", lem
.nsymbol
);
1717 stats_line("rules", lem
.nrule
);
1718 stats_line("states", lem
.nxstate
);
1719 stats_line("conflicts", lem
.nconflict
);
1720 stats_line("action table entries", lem
.nactiontab
);
1721 stats_line("total table size (bytes)", lem
.tablesize
);
1723 if( lem
.nconflict
> 0 ){
1724 fprintf(stderr
,"%d parsing conflicts.\n",lem
.nconflict
);
1727 /* return 0 on success, 1 on failure. */
1728 exitcode
= ((lem
.errorcnt
> 0) || (lem
.nconflict
> 0)) ? 1 : 0;
1732 /******************** From the file "msort.c" *******************************/
1734 ** A generic merge-sort program.
1737 ** Let "ptr" be a pointer to some structure which is at the head of
1738 ** a null-terminated list. Then to sort the list call:
1740 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1742 ** In the above, "cmpfnc" is a pointer to a function which compares
1743 ** two instances of the structure and returns an integer, as in
1744 ** strcmp. The second argument is a pointer to the pointer to the
1745 ** second element of the linked list. This address is used to compute
1746 ** the offset to the "next" field within the structure. The offset to
1747 ** the "next" field must be constant for all structures in the list.
1749 ** The function returns a new pointer which is the head of the list
1757 ** Return a pointer to the next structure in the linked list.
1759 #define NEXT(A) (*(char**)(((char*)A)+offset))
1763 ** a: A sorted, null-terminated linked list. (May be null).
1764 ** b: A sorted, null-terminated linked list. (May be null).
1765 ** cmp: A pointer to the comparison function.
1766 ** offset: Offset in the structure to the "next" field.
1769 ** A pointer to the head of a sorted list containing the elements
1773 ** The "next" pointers for elements in the lists a and b are
1779 int (*cmp
)(const char*,const char*),
1789 if( (*cmp
)(a
,b
)<=0 ){
1798 if( (*cmp
)(a
,b
)<=0 ){
1808 if( a
) NEXT(ptr
) = a
;
1816 ** list: Pointer to a singly-linked list of structures.
1817 ** next: Pointer to pointer to the second element of the list.
1818 ** cmp: A comparison function.
1821 ** A pointer to the head of a sorted list containing the elements
1822 ** orginally in list.
1825 ** The "next" pointers for elements in list are changed.
1831 int (*cmp
)(const char*,const char*)
1833 unsigned long offset
;
1835 char *set
[LISTSIZE
];
1837 offset
= (unsigned long)((char*)next
- (char*)list
);
1838 for(i
=0; i
<LISTSIZE
; i
++) set
[i
] = 0;
1843 for(i
=0; i
<LISTSIZE
-1 && set
[i
]!=0; i
++){
1844 ep
= merge(ep
,set
[i
],cmp
,offset
);
1850 for(i
=0; i
<LISTSIZE
; i
++) if( set
[i
] ) ep
= merge(set
[i
],ep
,cmp
,offset
);
1853 /************************ From the file "option.c" **************************/
1855 static struct s_options
*op
;
1856 static FILE *errstream
;
1858 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1861 ** Print the command line with a carrot pointing to the k-th character
1862 ** of the n-th field.
1864 static void errline(int n
, int k
, FILE *err
)
1867 if( argv
[0] ) fprintf(err
,"%s",argv
[0]);
1868 spcnt
= lemonStrlen(argv
[0]) + 1;
1869 for(i
=1; i
<n
&& argv
[i
]; i
++){
1870 fprintf(err
," %s",argv
[i
]);
1871 spcnt
+= lemonStrlen(argv
[i
])+1;
1874 for(; argv
[i
]; i
++) fprintf(err
," %s",argv
[i
]);
1876 fprintf(err
,"\n%*s^-- here\n",spcnt
,"");
1878 fprintf(err
,"\n%*shere --^\n",spcnt
-7,"");
1883 ** Return the index of the N-th non-switch argument. Return -1
1884 ** if N is out of range.
1886 static int argindex(int n
)
1890 if( argv
!=0 && *argv
!=0 ){
1891 for(i
=1; argv
[i
]; i
++){
1892 if( dashdash
|| !ISOPT(argv
[i
]) ){
1893 if( n
==0 ) return i
;
1896 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
1902 static char emsg
[] = "Command line syntax error: ";
1905 ** Process a flag command line argument.
1907 static int handleflags(int i
, FILE *err
)
1912 for(j
=0; op
[j
].label
; j
++){
1913 if( strncmp(&argv
[i
][1],op
[j
].label
,lemonStrlen(op
[j
].label
))==0 ) break;
1915 v
= argv
[i
][0]=='-' ? 1 : 0;
1916 if( op
[j
].label
==0 ){
1918 fprintf(err
,"%sundefined option.\n",emsg
);
1922 }else if( op
[j
].arg
==0 ){
1923 /* Ignore this option */
1924 }else if( op
[j
].type
==OPT_FLAG
){
1925 *((int*)op
[j
].arg
) = v
;
1926 }else if( op
[j
].type
==OPT_FFLAG
){
1927 (*(void(*)(int))(op
[j
].arg
))(v
);
1928 }else if( op
[j
].type
==OPT_FSTR
){
1929 (*(void(*)(char *))(op
[j
].arg
))(&argv
[i
][2]);
1932 fprintf(err
,"%smissing argument on switch.\n",emsg
);
1941 ** Process a command line switch which has an argument.
1943 static int handleswitch(int i
, FILE *err
)
1951 cp
= strchr(argv
[i
],'=');
1954 for(j
=0; op
[j
].label
; j
++){
1955 if( strcmp(argv
[i
],op
[j
].label
)==0 ) break;
1958 if( op
[j
].label
==0 ){
1960 fprintf(err
,"%sundefined option.\n",emsg
);
1966 switch( op
[j
].type
){
1970 fprintf(err
,"%soption requires an argument.\n",emsg
);
1977 dv
= strtod(cp
,&end
);
1981 "%sillegal character in floating-point argument.\n",emsg
);
1982 errline(i
,(int)((char*)end
-(char*)argv
[i
]),err
);
1989 lv
= strtol(cp
,&end
,0);
1992 fprintf(err
,"%sillegal character in integer argument.\n",emsg
);
1993 errline(i
,(int)((char*)end
-(char*)argv
[i
]),err
);
2003 switch( op
[j
].type
){
2008 *(double*)(op
[j
].arg
) = dv
;
2011 (*(void(*)(double))(op
[j
].arg
))(dv
);
2014 *(int*)(op
[j
].arg
) = lv
;
2017 (*(void(*)(int))(op
[j
].arg
))((int)lv
);
2020 *(char**)(op
[j
].arg
) = sv
;
2023 (*(void(*)(char *))(op
[j
].arg
))(sv
);
2030 int OptInit(char **a
, struct s_options
*o
, FILE *err
)
2036 if( argv
&& *argv
&& op
){
2038 for(i
=1; argv
[i
]; i
++){
2039 if( argv
[i
][0]=='+' || argv
[i
][0]=='-' ){
2040 errcnt
+= handleflags(i
,err
);
2041 }else if( strchr(argv
[i
],'=') ){
2042 errcnt
+= handleswitch(i
,err
);
2047 fprintf(err
,"Valid command line options for \"%s\" are:\n",*a
);
2058 if( argv
!=0 && argv
[0]!=0 ){
2059 for(i
=1; argv
[i
]; i
++){
2060 if( dashdash
|| !ISOPT(argv
[i
]) ) cnt
++;
2061 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
2071 return i
>=0 ? argv
[i
] : 0;
2078 if( i
>=0 ) errline(i
,0,errstream
);
2081 void OptPrint(void){
2085 for(i
=0; op
[i
].label
; i
++){
2086 len
= lemonStrlen(op
[i
].label
) + 1;
2087 switch( op
[i
].type
){
2093 len
+= 9; /* length of "<integer>" */
2097 len
+= 6; /* length of "<real>" */
2101 len
+= 8; /* length of "<string>" */
2104 if( len
>max
) max
= len
;
2106 for(i
=0; op
[i
].label
; i
++){
2107 switch( op
[i
].type
){
2110 fprintf(errstream
," -%-*s %s\n",max
,op
[i
].label
,op
[i
].message
);
2114 fprintf(errstream
," -%s<integer>%*s %s\n",op
[i
].label
,
2115 (int)(max
-lemonStrlen(op
[i
].label
)-9),"",op
[i
].message
);
2119 fprintf(errstream
," -%s<real>%*s %s\n",op
[i
].label
,
2120 (int)(max
-lemonStrlen(op
[i
].label
)-6),"",op
[i
].message
);
2124 fprintf(errstream
," -%s<string>%*s %s\n",op
[i
].label
,
2125 (int)(max
-lemonStrlen(op
[i
].label
)-8),"",op
[i
].message
);
2130 /*********************** From the file "parse.c" ****************************/
2132 ** Input file parser for the LEMON parser generator.
2135 /* The state of the parser */
2138 WAITING_FOR_DECL_OR_RULE
,
2139 WAITING_FOR_DECL_KEYWORD
,
2140 WAITING_FOR_DECL_ARG
,
2141 WAITING_FOR_PRECEDENCE_SYMBOL
,
2151 RESYNC_AFTER_RULE_ERROR
,
2152 RESYNC_AFTER_DECL_ERROR
,
2153 WAITING_FOR_DESTRUCTOR_SYMBOL
,
2154 WAITING_FOR_DATATYPE_SYMBOL
,
2155 WAITING_FOR_FALLBACK_ID
,
2156 WAITING_FOR_WILDCARD_ID
,
2157 WAITING_FOR_CLASS_ID
,
2158 WAITING_FOR_CLASS_TOKEN
,
2159 WAITING_FOR_TOKEN_NAME
2162 char *filename
; /* Name of the input file */
2163 int tokenlineno
; /* Linenumber at which current token starts */
2164 int errorcnt
; /* Number of errors so far */
2165 char *tokenstart
; /* Text of current token */
2166 struct lemon
*gp
; /* Global state vector */
2167 enum e_state state
; /* The state of the parser */
2168 struct symbol
*fallback
; /* The fallback token */
2169 struct symbol
*tkclass
; /* Token class symbol */
2170 struct symbol
*lhs
; /* Left-hand side of current rule */
2171 const char *lhsalias
; /* Alias for the LHS */
2172 int nrhs
; /* Number of right-hand side symbols seen */
2173 struct symbol
*rhs
[MAXRHS
]; /* RHS symbols */
2174 const char *alias
[MAXRHS
]; /* Aliases for each RHS symbol (or NULL) */
2175 struct rule
*prevrule
; /* Previous rule parsed */
2176 const char *declkeyword
; /* Keyword of a declaration */
2177 char **declargslot
; /* Where the declaration argument should be put */
2178 int insertLineMacro
; /* Add #line before declaration insert */
2179 int *decllinenoslot
; /* Where to write declaration line number */
2180 enum e_assoc declassoc
; /* Assign this association to decl arguments */
2181 int preccounter
; /* Assign this precedence to decl arguments */
2182 struct rule
*firstrule
; /* Pointer to first rule in the grammar */
2183 struct rule
*lastrule
; /* Pointer to the most recently parsed rule */
2186 /* Parse a single token */
2187 static void parseonetoken(struct pstate
*psp
)
2190 x
= Strsafe(psp
->tokenstart
); /* Save the token permanently */
2192 printf("%s:%d: Token=[%s] state=%d\n",psp
->filename
,psp
->tokenlineno
,
2195 switch( psp
->state
){
2198 psp
->preccounter
= 0;
2199 psp
->firstrule
= psp
->lastrule
= 0;
2201 /* Fall thru to next case */
2202 case WAITING_FOR_DECL_OR_RULE
:
2204 psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2205 }else if( ISLOWER(x
[0]) ){
2206 psp
->lhs
= Symbol_new(x
);
2209 psp
->state
= WAITING_FOR_ARROW
;
2210 }else if( x
[0]=='{' ){
2211 if( psp
->prevrule
==0 ){
2212 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2213 "There is no prior rule upon which to attach the code \
2214 fragment which begins on this line.");
2216 }else if( psp
->prevrule
->code
!=0 ){
2217 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2218 "Code fragment beginning on this line is not the first \
2219 to follow the previous rule.");
2222 psp
->prevrule
->line
= psp
->tokenlineno
;
2223 psp
->prevrule
->code
= &x
[1];
2224 psp
->prevrule
->noCode
= 0;
2226 }else if( x
[0]=='[' ){
2227 psp
->state
= PRECEDENCE_MARK_1
;
2229 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2230 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2235 case PRECEDENCE_MARK_1
:
2236 if( !ISUPPER(x
[0]) ){
2237 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2238 "The precedence symbol must be a terminal.");
2240 }else if( psp
->prevrule
==0 ){
2241 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2242 "There is no prior rule to assign precedence \"[%s]\".",x
);
2244 }else if( psp
->prevrule
->precsym
!=0 ){
2245 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2246 "Precedence mark on this line is not the first \
2247 to follow the previous rule.");
2250 psp
->prevrule
->precsym
= Symbol_new(x
);
2252 psp
->state
= PRECEDENCE_MARK_2
;
2254 case PRECEDENCE_MARK_2
:
2256 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2257 "Missing \"]\" on precedence mark.");
2260 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2262 case WAITING_FOR_ARROW
:
2263 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2264 psp
->state
= IN_RHS
;
2265 }else if( x
[0]=='(' ){
2266 psp
->state
= LHS_ALIAS_1
;
2268 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2269 "Expected to see a \":\" following the LHS symbol \"%s\".",
2272 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2276 if( ISALPHA(x
[0]) ){
2278 psp
->state
= LHS_ALIAS_2
;
2280 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2281 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2284 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2289 psp
->state
= LHS_ALIAS_3
;
2291 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2292 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2294 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2298 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2299 psp
->state
= IN_RHS
;
2301 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2302 "Missing \"->\" following: \"%s(%s)\".",
2303 psp
->lhs
->name
,psp
->lhsalias
);
2305 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2311 rp
= (struct rule
*)calloc( sizeof(struct rule
) +
2312 sizeof(struct symbol
*)*psp
->nrhs
+ sizeof(char*)*psp
->nrhs
, 1);
2314 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2315 "Can't allocate enough memory for this rule.");
2320 rp
->ruleline
= psp
->tokenlineno
;
2321 rp
->rhs
= (struct symbol
**)&rp
[1];
2322 rp
->rhsalias
= (const char**)&(rp
->rhs
[psp
->nrhs
]);
2323 for(i
=0; i
<psp
->nrhs
; i
++){
2324 rp
->rhs
[i
] = psp
->rhs
[i
];
2325 rp
->rhsalias
[i
] = psp
->alias
[i
];
2328 rp
->lhsalias
= psp
->lhsalias
;
2329 rp
->nrhs
= psp
->nrhs
;
2333 rp
->index
= psp
->gp
->nrule
++;
2334 rp
->nextlhs
= rp
->lhs
->rule
;
2337 if( psp
->firstrule
==0 ){
2338 psp
->firstrule
= psp
->lastrule
= rp
;
2340 psp
->lastrule
->next
= rp
;
2345 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2346 }else if( ISALPHA(x
[0]) ){
2347 if( psp
->nrhs
>=MAXRHS
){
2348 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2349 "Too many symbols on RHS of rule beginning at \"%s\".",
2352 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2354 psp
->rhs
[psp
->nrhs
] = Symbol_new(x
);
2355 psp
->alias
[psp
->nrhs
] = 0;
2358 }else if( (x
[0]=='|' || x
[0]=='/') && psp
->nrhs
>0 ){
2359 struct symbol
*msp
= psp
->rhs
[psp
->nrhs
-1];
2360 if( msp
->type
!=MULTITERMINAL
){
2361 struct symbol
*origsp
= msp
;
2362 msp
= (struct symbol
*) calloc(1,sizeof(*msp
));
2363 memset(msp
, 0, sizeof(*msp
));
2364 msp
->type
= MULTITERMINAL
;
2366 msp
->subsym
= (struct symbol
**) calloc(1,sizeof(struct symbol
*));
2367 msp
->subsym
[0] = origsp
;
2368 msp
->name
= origsp
->name
;
2369 psp
->rhs
[psp
->nrhs
-1] = msp
;
2372 msp
->subsym
= (struct symbol
**) realloc(msp
->subsym
,
2373 sizeof(struct symbol
*)*msp
->nsubsym
);
2374 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(&x
[1]);
2375 if( ISLOWER(x
[1]) || ISLOWER(msp
->subsym
[0]->name
[0]) ){
2376 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2377 "Cannot form a compound containing a non-terminal");
2380 }else if( x
[0]=='(' && psp
->nrhs
>0 ){
2381 psp
->state
= RHS_ALIAS_1
;
2383 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2384 "Illegal character on RHS of rule: \"%s\".",x
);
2386 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2390 if( ISALPHA(x
[0]) ){
2391 psp
->alias
[psp
->nrhs
-1] = x
;
2392 psp
->state
= RHS_ALIAS_2
;
2394 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2395 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2396 x
,psp
->rhs
[psp
->nrhs
-1]->name
);
2398 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2403 psp
->state
= IN_RHS
;
2405 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2406 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2408 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2411 case WAITING_FOR_DECL_KEYWORD
:
2412 if( ISALPHA(x
[0]) ){
2413 psp
->declkeyword
= x
;
2414 psp
->declargslot
= 0;
2415 psp
->decllinenoslot
= 0;
2416 psp
->insertLineMacro
= 1;
2417 psp
->state
= WAITING_FOR_DECL_ARG
;
2418 if( strcmp(x
,"name")==0 ){
2419 psp
->declargslot
= &(psp
->gp
->name
);
2420 psp
->insertLineMacro
= 0;
2421 }else if( strcmp(x
,"include")==0 ){
2422 psp
->declargslot
= &(psp
->gp
->include
);
2423 }else if( strcmp(x
,"code")==0 ){
2424 psp
->declargslot
= &(psp
->gp
->extracode
);
2425 }else if( strcmp(x
,"token_destructor")==0 ){
2426 psp
->declargslot
= &psp
->gp
->tokendest
;
2427 }else if( strcmp(x
,"default_destructor")==0 ){
2428 psp
->declargslot
= &psp
->gp
->vardest
;
2429 }else if( strcmp(x
,"token_prefix")==0 ){
2430 psp
->declargslot
= &psp
->gp
->tokenprefix
;
2431 psp
->insertLineMacro
= 0;
2432 }else if( strcmp(x
,"syntax_error")==0 ){
2433 psp
->declargslot
= &(psp
->gp
->error
);
2434 }else if( strcmp(x
,"parse_accept")==0 ){
2435 psp
->declargslot
= &(psp
->gp
->accept
);
2436 }else if( strcmp(x
,"parse_failure")==0 ){
2437 psp
->declargslot
= &(psp
->gp
->failure
);
2438 }else if( strcmp(x
,"stack_overflow")==0 ){
2439 psp
->declargslot
= &(psp
->gp
->overflow
);
2440 }else if( strcmp(x
,"extra_argument")==0 ){
2441 psp
->declargslot
= &(psp
->gp
->arg
);
2442 psp
->insertLineMacro
= 0;
2443 }else if( strcmp(x
,"token_type")==0 ){
2444 psp
->declargslot
= &(psp
->gp
->tokentype
);
2445 psp
->insertLineMacro
= 0;
2446 }else if( strcmp(x
,"default_type")==0 ){
2447 psp
->declargslot
= &(psp
->gp
->vartype
);
2448 psp
->insertLineMacro
= 0;
2449 }else if( strcmp(x
,"stack_size")==0 ){
2450 psp
->declargslot
= &(psp
->gp
->stacksize
);
2451 psp
->insertLineMacro
= 0;
2452 }else if( strcmp(x
,"start_symbol")==0 ){
2453 psp
->declargslot
= &(psp
->gp
->start
);
2454 psp
->insertLineMacro
= 0;
2455 }else if( strcmp(x
,"left")==0 ){
2457 psp
->declassoc
= LEFT
;
2458 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2459 }else if( strcmp(x
,"right")==0 ){
2461 psp
->declassoc
= RIGHT
;
2462 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2463 }else if( strcmp(x
,"nonassoc")==0 ){
2465 psp
->declassoc
= NONE
;
2466 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2467 }else if( strcmp(x
,"destructor")==0 ){
2468 psp
->state
= WAITING_FOR_DESTRUCTOR_SYMBOL
;
2469 }else if( strcmp(x
,"type")==0 ){
2470 psp
->state
= WAITING_FOR_DATATYPE_SYMBOL
;
2471 }else if( strcmp(x
,"fallback")==0 ){
2473 psp
->state
= WAITING_FOR_FALLBACK_ID
;
2474 }else if( strcmp(x
,"token")==0 ){
2475 psp
->state
= WAITING_FOR_TOKEN_NAME
;
2476 }else if( strcmp(x
,"wildcard")==0 ){
2477 psp
->state
= WAITING_FOR_WILDCARD_ID
;
2478 }else if( strcmp(x
,"token_class")==0 ){
2479 psp
->state
= WAITING_FOR_CLASS_ID
;
2481 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2482 "Unknown declaration keyword: \"%%%s\".",x
);
2484 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2487 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2488 "Illegal declaration keyword: \"%s\".",x
);
2490 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2493 case WAITING_FOR_DESTRUCTOR_SYMBOL
:
2494 if( !ISALPHA(x
[0]) ){
2495 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2496 "Symbol name missing after %%destructor keyword");
2498 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2500 struct symbol
*sp
= Symbol_new(x
);
2501 psp
->declargslot
= &sp
->destructor
;
2502 psp
->decllinenoslot
= &sp
->destLineno
;
2503 psp
->insertLineMacro
= 1;
2504 psp
->state
= WAITING_FOR_DECL_ARG
;
2507 case WAITING_FOR_DATATYPE_SYMBOL
:
2508 if( !ISALPHA(x
[0]) ){
2509 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2510 "Symbol name missing after %%type keyword");
2512 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2514 struct symbol
*sp
= Symbol_find(x
);
2515 if((sp
) && (sp
->datatype
)){
2516 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2517 "Symbol %%type \"%s\" already defined", x
);
2519 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2524 psp
->declargslot
= &sp
->datatype
;
2525 psp
->insertLineMacro
= 0;
2526 psp
->state
= WAITING_FOR_DECL_ARG
;
2530 case WAITING_FOR_PRECEDENCE_SYMBOL
:
2532 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2533 }else if( ISUPPER(x
[0]) ){
2537 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2538 "Symbol \"%s\" has already be given a precedence.",x
);
2541 sp
->prec
= psp
->preccounter
;
2542 sp
->assoc
= psp
->declassoc
;
2545 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2546 "Can't assign a precedence to \"%s\".",x
);
2550 case WAITING_FOR_DECL_ARG
:
2551 if( x
[0]=='{' || x
[0]=='\"' || ISALNUM(x
[0]) ){
2552 const char *zOld
, *zNew
;
2554 int nOld
, n
, nLine
= 0, nNew
, nBack
;
2558 if( zNew
[0]=='"' || zNew
[0]=='{' ) zNew
++;
2559 nNew
= lemonStrlen(zNew
);
2560 if( *psp
->declargslot
){
2561 zOld
= *psp
->declargslot
;
2565 nOld
= lemonStrlen(zOld
);
2566 n
= nOld
+ nNew
+ 20;
2567 addLineMacro
= !psp
->gp
->nolinenosflag
&& psp
->insertLineMacro
&&
2568 (psp
->decllinenoslot
==0 || psp
->decllinenoslot
[0]!=0);
2570 for(z
=psp
->filename
, nBack
=0; *z
; z
++){
2571 if( *z
=='\\' ) nBack
++;
2573 lemon_sprintf(zLine
, "#line %d ", psp
->tokenlineno
);
2574 nLine
= lemonStrlen(zLine
);
2575 n
+= nLine
+ lemonStrlen(psp
->filename
) + nBack
;
2577 *psp
->declargslot
= (char *) realloc(*psp
->declargslot
, n
);
2578 zBuf
= *psp
->declargslot
+ nOld
;
2580 if( nOld
&& zBuf
[-1]!='\n' ){
2583 memcpy(zBuf
, zLine
, nLine
);
2586 for(z
=psp
->filename
; *z
; z
++){
2595 if( psp
->decllinenoslot
&& psp
->decllinenoslot
[0]==0 ){
2596 psp
->decllinenoslot
[0] = psp
->tokenlineno
;
2598 memcpy(zBuf
, zNew
, nNew
);
2601 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2603 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2604 "Illegal argument to %%%s: %s",psp
->declkeyword
,x
);
2606 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2609 case WAITING_FOR_FALLBACK_ID
:
2611 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2612 }else if( !ISUPPER(x
[0]) ){
2613 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2614 "%%fallback argument \"%s\" should be a token", x
);
2617 struct symbol
*sp
= Symbol_new(x
);
2618 if( psp
->fallback
==0 ){
2620 }else if( sp
->fallback
){
2621 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2622 "More than one fallback assigned to token %s", x
);
2625 sp
->fallback
= psp
->fallback
;
2626 psp
->gp
->has_fallback
= 1;
2630 case WAITING_FOR_TOKEN_NAME
:
2631 /* Tokens do not have to be declared before use. But they can be
2632 ** in order to control their assigned integer number. The number for
2633 ** each token is assigned when it is first seen. So by including
2635 ** %token ONE TWO THREE
2637 ** early in the grammar file, that assigns small consecutive values
2638 ** to each of the tokens ONE TWO and THREE.
2641 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2642 }else if( !ISUPPER(x
[0]) ){
2643 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2644 "%%token argument \"%s\" should be a token", x
);
2647 (void)Symbol_new(x
);
2650 case WAITING_FOR_WILDCARD_ID
:
2652 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2653 }else if( !ISUPPER(x
[0]) ){
2654 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2655 "%%wildcard argument \"%s\" should be a token", x
);
2658 struct symbol
*sp
= Symbol_new(x
);
2659 if( psp
->gp
->wildcard
==0 ){
2660 psp
->gp
->wildcard
= sp
;
2662 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2663 "Extra wildcard to token: %s", x
);
2668 case WAITING_FOR_CLASS_ID
:
2669 if( !ISLOWER(x
[0]) ){
2670 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2671 "%%token_class must be followed by an identifier: ", x
);
2673 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2674 }else if( Symbol_find(x
) ){
2675 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2676 "Symbol \"%s\" already used", x
);
2678 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2680 psp
->tkclass
= Symbol_new(x
);
2681 psp
->tkclass
->type
= MULTITERMINAL
;
2682 psp
->state
= WAITING_FOR_CLASS_TOKEN
;
2685 case WAITING_FOR_CLASS_TOKEN
:
2687 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2688 }else if( ISUPPER(x
[0]) || ((x
[0]=='|' || x
[0]=='/') && ISUPPER(x
[1])) ){
2689 struct symbol
*msp
= psp
->tkclass
;
2691 msp
->subsym
= (struct symbol
**) realloc(msp
->subsym
,
2692 sizeof(struct symbol
*)*msp
->nsubsym
);
2693 if( !ISUPPER(x
[0]) ) x
++;
2694 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(x
);
2696 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2697 "%%token_class argument \"%s\" should be a token", x
);
2699 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2702 case RESYNC_AFTER_RULE_ERROR
:
2703 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2705 case RESYNC_AFTER_DECL_ERROR
:
2706 if( x
[0]=='.' ) psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2707 if( x
[0]=='%' ) psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2712 /* Run the preprocessor over the input file text. The global variables
2713 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2714 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2715 ** comments them out. Text in between is also commented out as appropriate.
2717 static void preprocess_input(char *z
){
2722 int start_lineno
= 1;
2723 for(i
=0; z
[i
]; i
++){
2724 if( z
[i
]=='\n' ) lineno
++;
2725 if( z
[i
]!='%' || (i
>0 && z
[i
-1]!='\n') ) continue;
2726 if( strncmp(&z
[i
],"%endif",6)==0 && ISSPACE(z
[i
+6]) ){
2730 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
2733 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2734 }else if( (strncmp(&z
[i
],"%ifdef",6)==0 && ISSPACE(z
[i
+6]))
2735 || (strncmp(&z
[i
],"%ifndef",7)==0 && ISSPACE(z
[i
+7])) ){
2739 for(j
=i
+7; ISSPACE(z
[j
]); j
++){}
2740 for(n
=0; z
[j
+n
] && !ISSPACE(z
[j
+n
]); n
++){}
2742 for(k
=0; k
<nDefine
; k
++){
2743 if( strncmp(azDefine
[k
],&z
[j
],n
)==0 && lemonStrlen(azDefine
[k
])==n
){
2748 if( z
[i
+3]=='n' ) exclude
= !exclude
;
2751 start_lineno
= lineno
;
2754 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2758 fprintf(stderr
,"unterminated %%ifdef starting on line %d\n", start_lineno
);
2763 /* In spite of its name, this function is really a scanner. It read
2764 ** in the entire input file (all at once) then tokenizes it. Each
2765 ** token is passed to the function "parseonetoken" which builds all
2766 ** the appropriate data structures in the global state vector "gp".
2768 void Parse(struct lemon
*gp
)
2773 unsigned int filesize
;
2779 memset(&ps
, '\0', sizeof(ps
));
2781 ps
.filename
= gp
->filename
;
2783 ps
.state
= INITIALIZE
;
2785 /* Begin by reading the input file */
2786 fp
= fopen(ps
.filename
,"rb");
2788 ErrorMsg(ps
.filename
,0,"Can't open this file for reading.");
2793 filesize
= ftell(fp
);
2795 filebuf
= (char *)malloc( filesize
+1 );
2796 if( filesize
>100000000 || filebuf
==0 ){
2797 ErrorMsg(ps
.filename
,0,"Input file too large.");
2802 if( fread(filebuf
,1,filesize
,fp
)!=filesize
){
2803 ErrorMsg(ps
.filename
,0,"Can't read in all %d bytes of this file.",
2811 filebuf
[filesize
] = 0;
2813 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2814 preprocess_input(filebuf
);
2816 /* Now scan the text of the input file */
2818 for(cp
=filebuf
; (c
= *cp
)!=0; ){
2819 if( c
=='\n' ) lineno
++; /* Keep track of the line number */
2820 if( ISSPACE(c
) ){ cp
++; continue; } /* Skip all white space */
2821 if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments */
2823 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2826 if( c
=='/' && cp
[1]=='*' ){ /* Skip C style comments */
2828 while( (c
= *cp
)!=0 && (c
!='/' || cp
[-1]!='*') ){
2829 if( c
=='\n' ) lineno
++;
2835 ps
.tokenstart
= cp
; /* Mark the beginning of the token */
2836 ps
.tokenlineno
= lineno
; /* Linenumber on which token begins */
2837 if( c
=='\"' ){ /* String literals */
2839 while( (c
= *cp
)!=0 && c
!='\"' ){
2840 if( c
=='\n' ) lineno
++;
2844 ErrorMsg(ps
.filename
,startline
,
2845 "String starting on this line is not terminated before the end of the file.");
2851 }else if( c
=='{' ){ /* A block of C code */
2854 for(level
=1; (c
= *cp
)!=0 && (level
>1 || c
!='}'); cp
++){
2855 if( c
=='\n' ) lineno
++;
2856 else if( c
=='{' ) level
++;
2857 else if( c
=='}' ) level
--;
2858 else if( c
=='/' && cp
[1]=='*' ){ /* Skip comments */
2862 while( (c
= *cp
)!=0 && (c
!='/' || prevc
!='*') ){
2863 if( c
=='\n' ) lineno
++;
2867 }else if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments too */
2869 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2871 }else if( c
=='\'' || c
=='\"' ){ /* String a character literals */
2872 int startchar
, prevc
;
2875 for(cp
++; (c
= *cp
)!=0 && (c
!=startchar
|| prevc
=='\\'); cp
++){
2876 if( c
=='\n' ) lineno
++;
2877 if( prevc
=='\\' ) prevc
= 0;
2883 ErrorMsg(ps
.filename
,ps
.tokenlineno
,
2884 "C code starting on this line is not terminated before the end of the file.");
2890 }else if( ISALNUM(c
) ){ /* Identifiers */
2891 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
2893 }else if( c
==':' && cp
[1]==':' && cp
[2]=='=' ){ /* The operator "::=" */
2896 }else if( (c
=='/' || c
=='|') && ISALPHA(cp
[1]) ){
2898 while( (c
= *cp
)!=0 && (ISALNUM(c
) || c
=='_') ) cp
++;
2900 }else{ /* All other (one character) operators */
2905 *cp
= 0; /* Null terminate the token */
2906 parseonetoken(&ps
); /* Parse the token */
2907 *cp
= (char)c
; /* Restore the buffer */
2910 free(filebuf
); /* Release the buffer after parsing */
2911 gp
->rule
= ps
.firstrule
;
2912 gp
->errorcnt
= ps
.errorcnt
;
2914 /*************************** From the file "plink.c" *********************/
2916 ** Routines processing configuration follow-set propagation links
2917 ** in the LEMON parser generator.
2919 static struct plink
*plink_freelist
= 0;
2921 /* Allocate a new plink */
2922 struct plink
*Plink_new(void){
2923 struct plink
*newlink
;
2925 if( plink_freelist
==0 ){
2928 plink_freelist
= (struct plink
*)calloc( amt
, sizeof(struct plink
) );
2929 if( plink_freelist
==0 ){
2931 "Unable to allocate memory for a new follow-set propagation link.\n");
2934 for(i
=0; i
<amt
-1; i
++) plink_freelist
[i
].next
= &plink_freelist
[i
+1];
2935 plink_freelist
[amt
-1].next
= 0;
2937 newlink
= plink_freelist
;
2938 plink_freelist
= plink_freelist
->next
;
2942 /* Add a plink to a plink list */
2943 void Plink_add(struct plink
**plpp
, struct config
*cfp
)
2945 struct plink
*newlink
;
2946 newlink
= Plink_new();
2947 newlink
->next
= *plpp
;
2952 /* Transfer every plink on the list "from" to the list "to" */
2953 void Plink_copy(struct plink
**to
, struct plink
*from
)
2955 struct plink
*nextpl
;
2957 nextpl
= from
->next
;
2964 /* Delete every plink on the list */
2965 void Plink_delete(struct plink
*plp
)
2967 struct plink
*nextpl
;
2971 plp
->next
= plink_freelist
;
2972 plink_freelist
= plp
;
2976 /*********************** From the file "report.c" **************************/
2978 ** Procedures for generating reports and tables in the LEMON parser generator.
2981 /* Generate a filename with the given suffix. Space to hold the
2982 ** name comes from malloc() and must be freed by the calling
2985 PRIVATE
char *file_makename(struct lemon
*lemp
, const char *suffix
)
2990 name
= (char*)malloc( lemonStrlen(lemp
->filename
) + lemonStrlen(suffix
) + 5 );
2992 fprintf(stderr
,"Can't allocate space for a filename.\n");
2995 lemon_strcpy(name
,lemp
->filename
);
2996 cp
= strrchr(name
,'.');
2998 lemon_strcat(name
,suffix
);
3002 /* Open a file with a name based on the name of the input file,
3003 ** but with a different (specified) suffix, and return a pointer
3005 PRIVATE
FILE *file_open(
3012 if( lemp
->outname
) free(lemp
->outname
);
3013 lemp
->outname
= file_makename(lemp
, suffix
);
3014 fp
= fopen(lemp
->outname
,mode
);
3015 if( fp
==0 && *mode
=='w' ){
3016 fprintf(stderr
,"Can't open file \"%s\".\n",lemp
->outname
);
3023 /* Duplicate the input file without comments and without actions
3025 void Reprint(struct lemon
*lemp
)
3029 int i
, j
, maxlen
, len
, ncolumns
, skip
;
3030 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp
->filename
);
3032 for(i
=0; i
<lemp
->nsymbol
; i
++){
3033 sp
= lemp
->symbols
[i
];
3034 len
= lemonStrlen(sp
->name
);
3035 if( len
>maxlen
) maxlen
= len
;
3037 ncolumns
= 76/(maxlen
+5);
3038 if( ncolumns
<1 ) ncolumns
= 1;
3039 skip
= (lemp
->nsymbol
+ ncolumns
- 1)/ncolumns
;
3040 for(i
=0; i
<skip
; i
++){
3042 for(j
=i
; j
<lemp
->nsymbol
; j
+=skip
){
3043 sp
= lemp
->symbols
[j
];
3044 assert( sp
->index
==j
);
3045 printf(" %3d %-*.*s",j
,maxlen
,maxlen
,sp
->name
);
3049 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3050 printf("%s",rp
->lhs
->name
);
3051 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
3053 for(i
=0; i
<rp
->nrhs
; i
++){
3055 if( sp
->type
==MULTITERMINAL
){
3056 printf(" %s", sp
->subsym
[0]->name
);
3057 for(j
=1; j
<sp
->nsubsym
; j
++){
3058 printf("|%s", sp
->subsym
[j
]->name
);
3061 printf(" %s", sp
->name
);
3063 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
3066 if( rp
->precsym
) printf(" [%s]",rp
->precsym
->name
);
3067 /* if( rp->code ) printf("\n %s",rp->code); */
3072 /* Print a single rule.
3074 void RulePrint(FILE *fp
, struct rule
*rp
, int iCursor
){
3077 fprintf(fp
,"%s ::=",rp
->lhs
->name
);
3078 for(i
=0; i
<=rp
->nrhs
; i
++){
3079 if( i
==iCursor
) fprintf(fp
," *");
3080 if( i
==rp
->nrhs
) break;
3082 if( sp
->type
==MULTITERMINAL
){
3083 fprintf(fp
," %s", sp
->subsym
[0]->name
);
3084 for(j
=1; j
<sp
->nsubsym
; j
++){
3085 fprintf(fp
,"|%s",sp
->subsym
[j
]->name
);
3088 fprintf(fp
," %s", sp
->name
);
3093 /* Print the rule for a configuration.
3095 void ConfigPrint(FILE *fp
, struct config
*cfp
){
3096 RulePrint(fp
, cfp
->rp
, cfp
->dot
);
3102 PRIVATE
void SetPrint(out
,set
,lemp
)
3110 fprintf(out
,"%12s[","");
3111 for(i
=0; i
<lemp
->nterminal
; i
++){
3112 if( SetFind(set
,i
) ){
3113 fprintf(out
,"%s%s",spacer
,lemp
->symbols
[i
]->name
);
3120 /* Print a plink chain */
3121 PRIVATE
void PlinkPrint(out
,plp
,tag
)
3127 fprintf(out
,"%12s%s (state %2d) ","",tag
,plp
->cfp
->stp
->statenum
);
3128 ConfigPrint(out
,plp
->cfp
);
3135 /* Print an action to the given file descriptor. Return FALSE if
3136 ** nothing was actually printed.
3139 struct action
*ap
, /* The action to print */
3140 FILE *fp
, /* Print the action here */
3141 int indent
/* Indent by this amount */
3146 struct state
*stp
= ap
->x
.stp
;
3147 fprintf(fp
,"%*s shift %-7d",indent
,ap
->sp
->name
,stp
->statenum
);
3151 struct rule
*rp
= ap
->x
.rp
;
3152 fprintf(fp
,"%*s reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3153 RulePrint(fp
, rp
, -1);
3157 struct rule
*rp
= ap
->x
.rp
;
3158 fprintf(fp
,"%*s shift-reduce %-7d",indent
,ap
->sp
->name
,rp
->iRule
);
3159 RulePrint(fp
, rp
, -1);
3163 fprintf(fp
,"%*s accept",indent
,ap
->sp
->name
);
3166 fprintf(fp
,"%*s error",indent
,ap
->sp
->name
);
3170 fprintf(fp
,"%*s reduce %-7d ** Parsing conflict **",
3171 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3174 fprintf(fp
,"%*s shift %-7d ** Parsing conflict **",
3175 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3178 if( showPrecedenceConflict
){
3179 fprintf(fp
,"%*s shift %-7d -- dropped by precedence",
3180 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
3186 if( showPrecedenceConflict
){
3187 fprintf(fp
,"%*s reduce %-7d -- dropped by precedence",
3188 indent
,ap
->sp
->name
,ap
->x
.rp
->iRule
);
3197 if( result
&& ap
->spOpt
){
3198 fprintf(fp
," /* because %s==%s */", ap
->sp
->name
, ap
->spOpt
->name
);
3203 /* Generate the "*.out" log file */
3204 void ReportOutput(struct lemon
*lemp
)
3212 fp
= file_open(lemp
,".out","wb");
3214 for(i
=0; i
<lemp
->nxstate
; i
++){
3215 stp
= lemp
->sorted
[i
];
3216 fprintf(fp
,"State %d:\n",stp
->statenum
);
3217 if( lemp
->basisflag
) cfp
=stp
->bp
;
3221 if( cfp
->dot
==cfp
->rp
->nrhs
){
3222 lemon_sprintf(buf
,"(%d)",cfp
->rp
->iRule
);
3223 fprintf(fp
," %5s ",buf
);
3227 ConfigPrint(fp
,cfp
);
3230 SetPrint(fp
,cfp
->fws
,lemp
);
3231 PlinkPrint(fp
,cfp
->fplp
,"To ");
3232 PlinkPrint(fp
,cfp
->bplp
,"From");
3234 if( lemp
->basisflag
) cfp
=cfp
->bp
;
3238 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3239 if( PrintAction(ap
,fp
,30) ) fprintf(fp
,"\n");
3243 fprintf(fp
, "----------------------------------------------------\n");
3244 fprintf(fp
, "Symbols:\n");
3245 for(i
=0; i
<lemp
->nsymbol
; i
++){
3249 sp
= lemp
->symbols
[i
];
3250 fprintf(fp
, " %3d: %s", i
, sp
->name
);
3251 if( sp
->type
==NONTERMINAL
){
3254 fprintf(fp
, " <lambda>");
3256 for(j
=0; j
<lemp
->nterminal
; j
++){
3257 if( sp
->firstset
&& SetFind(sp
->firstset
, j
) ){
3258 fprintf(fp
, " %s", lemp
->symbols
[j
]->name
);
3268 /* Search for the file "name" which is in the same directory as
3269 ** the exacutable */
3270 PRIVATE
char *pathsearch(char *argv0
, char *name
, int modemask
)
3272 const char *pathlist
;
3279 cp
= strrchr(argv0
,'\\');
3281 cp
= strrchr(argv0
,'/');
3286 path
= (char *)malloc( lemonStrlen(argv0
) + lemonStrlen(name
) + 2 );
3287 if( path
) lemon_sprintf(path
,"%s/%s",argv0
,name
);
3290 pathlist
= getenv("PATH");
3291 if( pathlist
==0 ) pathlist
= ".:/bin:/usr/bin";
3292 pathbuf
= (char *) malloc( lemonStrlen(pathlist
) + 1 );
3293 path
= (char *)malloc( lemonStrlen(pathlist
)+lemonStrlen(name
)+2 );
3294 if( (pathbuf
!= 0) && (path
!=0) ){
3295 pathbufptr
= pathbuf
;
3296 lemon_strcpy(pathbuf
, pathlist
);
3298 cp
= strchr(pathbuf
,':');
3299 if( cp
==0 ) cp
= &pathbuf
[lemonStrlen(pathbuf
)];
3302 lemon_sprintf(path
,"%s/%s",pathbuf
,name
);
3304 if( c
==0 ) pathbuf
[0] = 0;
3305 else pathbuf
= &cp
[1];
3306 if( access(path
,modemask
)==0 ) break;
3314 /* Given an action, compute the integer value for that action
3315 ** which is to be put in the action table of the generated machine.
3316 ** Return negative if no action should be generated.
3318 PRIVATE
int compute_action(struct lemon
*lemp
, struct action
*ap
)
3322 case SHIFT
: act
= ap
->x
.stp
->statenum
; break;
3324 act
= ap
->x
.rp
->iRule
+ lemp
->nstate
;
3325 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3326 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3327 ** REDUCE action: */
3328 if( ap
->sp
->index
>=lemp
->nterminal
) act
+= lemp
->nrule
;
3331 case REDUCE
: act
= ap
->x
.rp
->iRule
+ lemp
->nstate
+lemp
->nrule
; break;
3332 case ERROR
: act
= lemp
->nstate
+ lemp
->nrule
*2; break;
3333 case ACCEPT
: act
= lemp
->nstate
+ lemp
->nrule
*2 + 1; break;
3334 default: act
= -1; break;
3339 #define LINESIZE 1000
3340 /* The next cluster of routines are for reading the template file
3341 ** and writing the results to the generated parser */
3342 /* The first function transfers data from "in" to "out" until
3343 ** a line is seen which begins with "%%". The line number is
3346 ** if name!=0, then any word that begin with "Parse" is changed to
3347 ** begin with *name instead.
3349 PRIVATE
void tplt_xfer(char *name
, FILE *in
, FILE *out
, int *lineno
)
3352 char line
[LINESIZE
];
3353 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3357 for(i
=0; line
[i
]; i
++){
3358 if( line
[i
]=='P' && strncmp(&line
[i
],"Parse",5)==0
3359 && (i
==0 || !ISALPHA(line
[i
-1]))
3361 if( i
>iStart
) fprintf(out
,"%.*s",i
-iStart
,&line
[iStart
]);
3362 fprintf(out
,"%s",name
);
3368 fprintf(out
,"%s",&line
[iStart
]);
3372 /* The next function finds the template file and opens it, returning
3373 ** a pointer to the opened file. */
3374 PRIVATE
FILE *tplt_open(struct lemon
*lemp
)
3376 static char templatename
[] = "lempar.c";
3382 /* first, see if user specified a template filename on the command line. */
3383 if (user_templatename
!= 0) {
3384 if( access(user_templatename
,004)==-1 ){
3385 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3390 in
= fopen(user_templatename
,"rb");
3392 fprintf(stderr
,"Can't open the template file \"%s\".\n",
3400 cp
= strrchr(lemp
->filename
,'.');
3402 lemon_sprintf(buf
,"%.*s.lt",(int)(cp
-lemp
->filename
),lemp
->filename
);
3404 lemon_sprintf(buf
,"%s.lt",lemp
->filename
);
3406 if( access(buf
,004)==0 ){
3408 }else if( access(templatename
,004)==0 ){
3409 tpltname
= templatename
;
3411 tpltname
= pathsearch(lemp
->argv0
,templatename
,0);
3414 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3419 in
= fopen(tpltname
,"rb");
3421 fprintf(stderr
,"Can't open the template file \"%s\".\n",templatename
);
3428 /* Print a #line directive line to the output file. */
3429 PRIVATE
void tplt_linedir(FILE *out
, int lineno
, char *filename
)
3431 fprintf(out
,"#line %d \"",lineno
);
3433 if( *filename
== '\\' ) putc('\\',out
);
3434 putc(*filename
,out
);
3437 fprintf(out
,"\"\n");
3440 /* Print a string to the file and keep the linenumber up to date */
3441 PRIVATE
void tplt_print(FILE *out
, struct lemon
*lemp
, char *str
, int *lineno
)
3443 if( str
==0 ) return;
3446 if( *str
=='\n' ) (*lineno
)++;
3449 if( str
[-1]!='\n' ){
3453 if (!lemp
->nolinenosflag
) {
3454 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3460 ** The following routine emits code for the destructor for the
3463 void emit_destructor_code(
3471 if( sp
->type
==TERMINAL
){
3472 cp
= lemp
->tokendest
;
3474 fprintf(out
,"{\n"); (*lineno
)++;
3475 }else if( sp
->destructor
){
3476 cp
= sp
->destructor
;
3477 fprintf(out
,"{\n"); (*lineno
)++;
3478 if( !lemp
->nolinenosflag
){
3480 tplt_linedir(out
,sp
->destLineno
,lemp
->filename
);
3482 }else if( lemp
->vardest
){
3485 fprintf(out
,"{\n"); (*lineno
)++;
3487 assert( 0 ); /* Cannot happen */
3490 if( *cp
=='$' && cp
[1]=='$' ){
3491 fprintf(out
,"(yypminor->yy%d)",sp
->dtnum
);
3495 if( *cp
=='\n' ) (*lineno
)++;
3498 fprintf(out
,"\n"); (*lineno
)++;
3499 if (!lemp
->nolinenosflag
) {
3500 (*lineno
)++; tplt_linedir(out
,*lineno
,lemp
->outname
);
3502 fprintf(out
,"}\n"); (*lineno
)++;
3507 ** Return TRUE (non-zero) if the given symbol has a destructor.
3509 int has_destructor(struct symbol
*sp
, struct lemon
*lemp
)
3512 if( sp
->type
==TERMINAL
){
3513 ret
= lemp
->tokendest
!=0;
3515 ret
= lemp
->vardest
!=0 || sp
->destructor
!=0;
3521 ** Append text to a dynamically allocated string. If zText is 0 then
3522 ** reset the string to be empty again. Always return the complete text
3523 ** of the string (which is overwritten with each call).
3525 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3526 ** \000 terminator is stored. zText can contain up to two instances of
3527 ** %d. The values of p1 and p2 are written into the first and second
3530 ** If n==-1, then the previous character is overwritten.
3532 PRIVATE
char *append_str(const char *zText
, int n
, int p1
, int p2
){
3533 static char empty
[1] = { 0 };
3535 static int alloced
= 0;
3536 static int used
= 0;
3540 if( used
==0 && z
!=0 ) z
[0] = 0;
3549 n
= lemonStrlen(zText
);
3551 if( (int) (n
+sizeof(zInt
)*2+used
) >= alloced
){
3552 alloced
= n
+ sizeof(zInt
)*2 + used
+ 200;
3553 z
= (char *) realloc(z
, alloced
);
3555 if( z
==0 ) return empty
;
3558 if( c
=='%' && n
>0 && zText
[0]=='d' ){
3559 lemon_sprintf(zInt
, "%d", p1
);
3561 lemon_strcpy(&z
[used
], zInt
);
3562 used
+= lemonStrlen(&z
[used
]);
3566 z
[used
++] = (char)c
;
3574 ** Write and transform the rp->code string so that symbols are expanded.
3575 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
3577 ** Return 1 if the expanded code requires that "yylhsminor" local variable
3580 PRIVATE
int translate_code(struct lemon
*lemp
, struct rule
*rp
){
3583 int rc
= 0; /* True if yylhsminor is used */
3584 int dontUseRhs0
= 0; /* If true, use of left-most RHS label is illegal */
3585 const char *zSkip
= 0; /* The zOvwrt comment within rp->code, or NULL */
3586 char lhsused
= 0; /* True if the LHS element has been used */
3587 char lhsdirect
; /* True if LHS writes directly into stack */
3588 char used
[MAXRHS
]; /* True for each RHS element which is used */
3589 char zLhs
[50]; /* Convert the LHS symbol into this string */
3590 char zOvwrt
[900]; /* Comment that to allow LHS to overwrite RHS */
3592 for(i
=0; i
<rp
->nrhs
; i
++) used
[i
] = 0;
3596 static char newlinestr
[2] = { '\n', '\0' };
3597 rp
->code
= newlinestr
;
3598 rp
->line
= rp
->ruleline
;
3606 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3608 }else if( rp
->rhsalias
[0]==0 ){
3609 /* The left-most RHS symbol has no value. LHS direct is ok. But
3610 ** we have to call the distructor on the RHS symbol first. */
3612 if( has_destructor(rp
->rhs
[0],lemp
) ){
3613 append_str(0,0,0,0);
3614 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3615 rp
->rhs
[0]->index
,1-rp
->nrhs
);
3616 rp
->codePrefix
= Strsafe(append_str(0,0,0,0));
3619 }else if( rp
->lhsalias
==0 ){
3620 /* There is no LHS value symbol. */
3622 }else if( strcmp(rp
->lhsalias
,rp
->rhsalias
[0])==0 ){
3623 /* The LHS symbol and the left-most RHS symbol are the same, so
3624 ** direct writing is allowed */
3628 if( rp
->lhs
->dtnum
!=rp
->rhs
[0]->dtnum
){
3629 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3630 "%s(%s) and %s(%s) share the same label but have "
3631 "different datatypes.",
3632 rp
->lhs
->name
, rp
->lhsalias
, rp
->rhs
[0]->name
, rp
->rhsalias
[0]);
3636 lemon_sprintf(zOvwrt
, "/*%s-overwrites-%s*/",
3637 rp
->lhsalias
, rp
->rhsalias
[0]);
3638 zSkip
= strstr(rp
->code
, zOvwrt
);
3640 /* The code contains a special comment that indicates that it is safe
3641 ** for the LHS label to overwrite left-most RHS label. */
3648 sprintf(zLhs
, "yymsp[%d].minor.yy%d",1-rp
->nrhs
,rp
->lhs
->dtnum
);
3651 sprintf(zLhs
, "yylhsminor.yy%d",rp
->lhs
->dtnum
);
3654 append_str(0,0,0,0);
3656 /* This const cast is wrong but harmless, if we're careful. */
3657 for(cp
=(char *)rp
->code
; *cp
; cp
++){
3659 append_str(zOvwrt
,0,0,0);
3660 cp
+= lemonStrlen(zOvwrt
)-1;
3664 if( ISALPHA(*cp
) && (cp
==rp
->code
|| (!ISALNUM(cp
[-1]) && cp
[-1]!='_')) ){
3666 for(xp
= &cp
[1]; ISALNUM(*xp
) || *xp
=='_'; xp
++);
3669 if( rp
->lhsalias
&& strcmp(cp
,rp
->lhsalias
)==0 ){
3670 append_str(zLhs
,0,0,0);
3674 for(i
=0; i
<rp
->nrhs
; i
++){
3675 if( rp
->rhsalias
[i
] && strcmp(cp
,rp
->rhsalias
[i
])==0 ){
3676 if( i
==0 && dontUseRhs0
){
3677 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3678 "Label %s used after '%s'.",
3679 rp
->rhsalias
[0], zOvwrt
);
3681 }else if( cp
!=rp
->code
&& cp
[-1]=='@' ){
3682 /* If the argument is of the form @X then substituted
3683 ** the token number of X, not the value of X */
3684 append_str("yymsp[%d].major",-1,i
-rp
->nrhs
+1,0);
3686 struct symbol
*sp
= rp
->rhs
[i
];
3688 if( sp
->type
==MULTITERMINAL
){
3689 dtnum
= sp
->subsym
[0]->dtnum
;
3693 append_str("yymsp[%d].minor.yy%d",0,i
-rp
->nrhs
+1, dtnum
);
3703 append_str(cp
, 1, 0, 0);
3706 /* Main code generation completed */
3707 cp
= append_str(0,0,0,0);
3708 if( cp
&& cp
[0] ) rp
->code
= Strsafe(cp
);
3709 append_str(0,0,0,0);
3711 /* Check to make sure the LHS has been used */
3712 if( rp
->lhsalias
&& !lhsused
){
3713 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3714 "Label \"%s\" for \"%s(%s)\" is never used.",
3715 rp
->lhsalias
,rp
->lhs
->name
,rp
->lhsalias
);
3719 /* Generate destructor code for RHS minor values which are not referenced.
3720 ** Generate error messages for unused labels and duplicate labels.
3722 for(i
=0; i
<rp
->nrhs
; i
++){
3723 if( rp
->rhsalias
[i
] ){
3726 if( rp
->lhsalias
&& strcmp(rp
->lhsalias
,rp
->rhsalias
[i
])==0 ){
3727 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3728 "%s(%s) has the same label as the LHS but is not the left-most "
3729 "symbol on the RHS.",
3730 rp
->rhs
[i
]->name
, rp
->rhsalias
);
3734 if( rp
->rhsalias
[j
] && strcmp(rp
->rhsalias
[j
],rp
->rhsalias
[i
])==0 ){
3735 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3736 "Label %s used for multiple symbols on the RHS of a rule.",
3744 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3745 "Label %s for \"%s(%s)\" is never used.",
3746 rp
->rhsalias
[i
],rp
->rhs
[i
]->name
,rp
->rhsalias
[i
]);
3749 }else if( i
>0 && has_destructor(rp
->rhs
[i
],lemp
) ){
3750 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3751 rp
->rhs
[i
]->index
,i
-rp
->nrhs
+1);
3755 /* If unable to write LHS values directly into the stack, write the
3756 ** saved LHS value now. */
3758 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp
->nrhs
, rp
->lhs
->dtnum
);
3759 append_str(zLhs
, 0, 0, 0);
3760 append_str(";\n", 0, 0, 0);
3763 /* Suffix code generation complete */
3764 cp
= append_str(0,0,0,0);
3766 rp
->codeSuffix
= Strsafe(cp
);
3774 ** Generate code which executes when the rule "rp" is reduced. Write
3775 ** the code to "out". Make sure lineno stays up-to-date.
3777 PRIVATE
void emit_code(
3785 /* Setup code prior to the #line directive */
3786 if( rp
->codePrefix
&& rp
->codePrefix
[0] ){
3787 fprintf(out
, "{%s", rp
->codePrefix
);
3788 for(cp
=rp
->codePrefix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
3791 /* Generate code to do the reduce action */
3793 if( !lemp
->nolinenosflag
){
3795 tplt_linedir(out
,rp
->line
,lemp
->filename
);
3797 fprintf(out
,"{%s",rp
->code
);
3798 for(cp
=rp
->code
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
3799 fprintf(out
,"}\n"); (*lineno
)++;
3800 if( !lemp
->nolinenosflag
){
3802 tplt_linedir(out
,*lineno
,lemp
->outname
);
3806 /* Generate breakdown code that occurs after the #line directive */
3807 if( rp
->codeSuffix
&& rp
->codeSuffix
[0] ){
3808 fprintf(out
, "%s", rp
->codeSuffix
);
3809 for(cp
=rp
->codeSuffix
; *cp
; cp
++){ if( *cp
=='\n' ) (*lineno
)++; }
3812 if( rp
->codePrefix
){
3813 fprintf(out
, "}\n"); (*lineno
)++;
3820 ** Print the definition of the union used for the parser's data stack.
3821 ** This union contains fields for every possible data type for tokens
3822 ** and nonterminals. In the process of computing and printing this
3823 ** union, also set the ".dtnum" field of every terminal and nonterminal
3826 void print_stack_union(
3827 FILE *out
, /* The output stream */
3828 struct lemon
*lemp
, /* The main info structure for this parser */
3829 int *plineno
, /* Pointer to the line number */
3830 int mhflag
/* True if generating makeheaders output */
3832 int lineno
= *plineno
; /* The line number of the output */
3833 char **types
; /* A hash table of datatypes */
3834 int arraysize
; /* Size of the "types" array */
3835 int maxdtlength
; /* Maximum length of any ".datatype" field. */
3836 char *stddt
; /* Standardized name for a datatype */
3837 int i
,j
; /* Loop counters */
3838 unsigned hash
; /* For hashing the name of a type */
3839 const char *name
; /* Name of the parser */
3841 /* Allocate and initialize types[] and allocate stddt[] */
3842 arraysize
= lemp
->nsymbol
* 2;
3843 types
= (char**)calloc( arraysize
, sizeof(char*) );
3845 fprintf(stderr
,"Out of memory.\n");
3848 for(i
=0; i
<arraysize
; i
++) types
[i
] = 0;
3850 if( lemp
->vartype
){
3851 maxdtlength
= lemonStrlen(lemp
->vartype
);
3853 for(i
=0; i
<lemp
->nsymbol
; i
++){
3855 struct symbol
*sp
= lemp
->symbols
[i
];
3856 if( sp
->datatype
==0 ) continue;
3857 len
= lemonStrlen(sp
->datatype
);
3858 if( len
>maxdtlength
) maxdtlength
= len
;
3860 stddt
= (char*)malloc( maxdtlength
*2 + 1 );
3862 fprintf(stderr
,"Out of memory.\n");
3866 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3867 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3868 ** used for terminal symbols. If there is no %default_type defined then
3869 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3870 ** a datatype using the %type directive.
3872 for(i
=0; i
<lemp
->nsymbol
; i
++){
3873 struct symbol
*sp
= lemp
->symbols
[i
];
3875 if( sp
==lemp
->errsym
){
3876 sp
->dtnum
= arraysize
+1;
3879 if( sp
->type
!=NONTERMINAL
|| (sp
->datatype
==0 && lemp
->vartype
==0) ){
3884 if( cp
==0 ) cp
= lemp
->vartype
;
3886 while( ISSPACE(*cp
) ) cp
++;
3887 while( *cp
) stddt
[j
++] = *cp
++;
3888 while( j
>0 && ISSPACE(stddt
[j
-1]) ) j
--;
3890 if( lemp
->tokentype
&& strcmp(stddt
, lemp
->tokentype
)==0 ){
3895 for(j
=0; stddt
[j
]; j
++){
3896 hash
= hash
*53 + stddt
[j
];
3898 hash
= (hash
& 0x7fffffff)%arraysize
;
3899 while( types
[hash
] ){
3900 if( strcmp(types
[hash
],stddt
)==0 ){
3901 sp
->dtnum
= hash
+ 1;
3905 if( hash
>=(unsigned)arraysize
) hash
= 0;
3907 if( types
[hash
]==0 ){
3908 sp
->dtnum
= hash
+ 1;
3909 types
[hash
] = (char*)malloc( lemonStrlen(stddt
)+1 );
3910 if( types
[hash
]==0 ){
3911 fprintf(stderr
,"Out of memory.\n");
3914 lemon_strcpy(types
[hash
],stddt
);
3918 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3919 name
= lemp
->name
? lemp
->name
: "Parse";
3921 if( mhflag
){ fprintf(out
,"#if INTERFACE\n"); lineno
++; }
3922 fprintf(out
,"#define %sTOKENTYPE %s\n",name
,
3923 lemp
->tokentype
?lemp
->tokentype
:"void*"); lineno
++;
3924 if( mhflag
){ fprintf(out
,"#endif\n"); lineno
++; }
3925 fprintf(out
,"typedef union {\n"); lineno
++;
3926 fprintf(out
," int yyinit;\n"); lineno
++;
3927 fprintf(out
," %sTOKENTYPE yy0;\n",name
); lineno
++;
3928 for(i
=0; i
<arraysize
; i
++){
3929 if( types
[i
]==0 ) continue;
3930 fprintf(out
," %s yy%d;\n",types
[i
],i
+1); lineno
++;
3933 if( lemp
->errsym
->useCnt
){
3934 fprintf(out
," int yy%d;\n",lemp
->errsym
->dtnum
); lineno
++;
3938 fprintf(out
,"} YYMINORTYPE;\n"); lineno
++;
3943 ** Return the name of a C datatype able to represent values between
3944 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3945 ** for that type (1, 2, or 4) into *pnByte.
3947 static const char *minimum_size_type(int lwr
, int upr
, int *pnByte
){
3948 const char *zType
= "int";
3952 zType
= "unsigned char";
3954 }else if( upr
<65535 ){
3955 zType
= "unsigned short int";
3958 zType
= "unsigned int";
3961 }else if( lwr
>=-127 && upr
<=127 ){
3962 zType
= "signed char";
3964 }else if( lwr
>=-32767 && upr
<32767 ){
3968 if( pnByte
) *pnByte
= nByte
;
3973 ** Each state contains a set of token transaction and a set of
3974 ** nonterminal transactions. Each of these sets makes an instance
3975 ** of the following structure. An array of these structures is used
3976 ** to order the creation of entries in the yy_action[] table.
3979 struct state
*stp
; /* A pointer to a state */
3980 int isTkn
; /* True to use tokens. False for non-terminals */
3981 int nAction
; /* Number of actions */
3982 int iOrder
; /* Original order of action sets */
3986 ** Compare to axset structures for sorting purposes
3988 static int axset_compare(const void *a
, const void *b
){
3989 struct axset
*p1
= (struct axset
*)a
;
3990 struct axset
*p2
= (struct axset
*)b
;
3992 c
= p2
->nAction
- p1
->nAction
;
3994 c
= p1
->iOrder
- p2
->iOrder
;
3996 assert( c
!=0 || p1
==p2
);
4001 ** Write text on "out" that describes the rule "rp".
4003 static void writeRuleText(FILE *out
, struct rule
*rp
){
4005 fprintf(out
,"%s ::=", rp
->lhs
->name
);
4006 for(j
=0; j
<rp
->nrhs
; j
++){
4007 struct symbol
*sp
= rp
->rhs
[j
];
4008 if( sp
->type
!=MULTITERMINAL
){
4009 fprintf(out
," %s", sp
->name
);
4012 fprintf(out
," %s", sp
->subsym
[0]->name
);
4013 for(k
=1; k
<sp
->nsubsym
; k
++){
4014 fprintf(out
,"|%s",sp
->subsym
[k
]->name
);
4021 /* Generate C source code for the parser */
4024 int mhflag
/* Output in makeheaders format if true */
4027 char line
[LINESIZE
];
4032 struct acttab
*pActtab
;
4034 int szActionType
; /* sizeof(YYACTIONTYPE) */
4035 int szCodeType
; /* sizeof(YYCODETYPE) */
4037 int mnTknOfst
, mxTknOfst
;
4038 int mnNtOfst
, mxNtOfst
;
4041 in
= tplt_open(lemp
);
4043 out
= file_open(lemp
,".c","wb");
4049 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4051 /* Generate the include code, if any */
4052 tplt_print(out
,lemp
,lemp
->include
,&lineno
);
4054 char *incName
= file_makename(lemp
, ".h");
4055 fprintf(out
,"#include \"%s\"\n", incName
); lineno
++;
4058 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4060 /* Generate #defines for all tokens */
4063 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4064 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4066 for(i
=1; i
<lemp
->nterminal
; i
++){
4067 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4070 fprintf(out
,"#endif\n"); lineno
++;
4072 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4074 /* Generate the defines */
4075 fprintf(out
,"#define YYCODETYPE %s\n",
4076 minimum_size_type(0, lemp
->nsymbol
+1, &szCodeType
)); lineno
++;
4077 fprintf(out
,"#define YYNOCODE %d\n",lemp
->nsymbol
+1); lineno
++;
4078 fprintf(out
,"#define YYACTIONTYPE %s\n",
4079 minimum_size_type(0,lemp
->nstate
+lemp
->nrule
*2+5,&szActionType
)); lineno
++;
4080 if( lemp
->wildcard
){
4081 fprintf(out
,"#define YYWILDCARD %d\n",
4082 lemp
->wildcard
->index
); lineno
++;
4084 print_stack_union(out
,lemp
,&lineno
,mhflag
);
4085 fprintf(out
, "#ifndef YYSTACKDEPTH\n"); lineno
++;
4086 if( lemp
->stacksize
){
4087 fprintf(out
,"#define YYSTACKDEPTH %s\n",lemp
->stacksize
); lineno
++;
4089 fprintf(out
,"#define YYSTACKDEPTH 100\n"); lineno
++;
4091 fprintf(out
, "#endif\n"); lineno
++;
4093 fprintf(out
,"#if INTERFACE\n"); lineno
++;
4095 name
= lemp
->name
? lemp
->name
: "Parse";
4096 if( lemp
->arg
&& lemp
->arg
[0] ){
4097 i
= lemonStrlen(lemp
->arg
);
4098 while( i
>=1 && ISSPACE(lemp
->arg
[i
-1]) ) i
--;
4099 while( i
>=1 && (ISALNUM(lemp
->arg
[i
-1]) || lemp
->arg
[i
-1]=='_') ) i
--;
4100 fprintf(out
,"#define %sARG_SDECL %s;\n",name
,lemp
->arg
); lineno
++;
4101 fprintf(out
,"#define %sARG_PDECL ,%s\n",name
,lemp
->arg
); lineno
++;
4102 fprintf(out
,"#define %sARG_FETCH %s = yypParser->%s\n",
4103 name
,lemp
->arg
,&lemp
->arg
[i
]); lineno
++;
4104 fprintf(out
,"#define %sARG_STORE yypParser->%s = %s\n",
4105 name
,&lemp
->arg
[i
],&lemp
->arg
[i
]); lineno
++;
4107 fprintf(out
,"#define %sARG_SDECL\n",name
); lineno
++;
4108 fprintf(out
,"#define %sARG_PDECL\n",name
); lineno
++;
4109 fprintf(out
,"#define %sARG_FETCH\n",name
); lineno
++;
4110 fprintf(out
,"#define %sARG_STORE\n",name
); lineno
++;
4113 fprintf(out
,"#endif\n"); lineno
++;
4115 if( lemp
->errsym
->useCnt
){
4116 fprintf(out
,"#define YYERRORSYMBOL %d\n",lemp
->errsym
->index
); lineno
++;
4117 fprintf(out
,"#define YYERRSYMDT yy%d\n",lemp
->errsym
->dtnum
); lineno
++;
4119 if( lemp
->has_fallback
){
4120 fprintf(out
,"#define YYFALLBACK 1\n"); lineno
++;
4123 /* Compute the action table, but do not output it yet. The action
4124 ** table must be computed before generating the YYNSTATE macro because
4125 ** we need to know how many states can be eliminated.
4127 ax
= (struct axset
*) calloc(lemp
->nxstate
*2, sizeof(ax
[0]));
4129 fprintf(stderr
,"malloc failed\n");
4132 for(i
=0; i
<lemp
->nxstate
; i
++){
4133 stp
= lemp
->sorted
[i
];
4136 ax
[i
*2].nAction
= stp
->nTknAct
;
4137 ax
[i
*2+1].stp
= stp
;
4138 ax
[i
*2+1].isTkn
= 0;
4139 ax
[i
*2+1].nAction
= stp
->nNtAct
;
4141 mxTknOfst
= mnTknOfst
= 0;
4142 mxNtOfst
= mnNtOfst
= 0;
4143 /* In an effort to minimize the action table size, use the heuristic
4144 ** of placing the largest action sets first */
4145 for(i
=0; i
<lemp
->nxstate
*2; i
++) ax
[i
].iOrder
= i
;
4146 qsort(ax
, lemp
->nxstate
*2, sizeof(ax
[0]), axset_compare
);
4147 pActtab
= acttab_alloc();
4148 for(i
=0; i
<lemp
->nxstate
*2 && ax
[i
].nAction
>0; i
++){
4151 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4153 if( ap
->sp
->index
>=lemp
->nterminal
) continue;
4154 action
= compute_action(lemp
, ap
);
4155 if( action
<0 ) continue;
4156 acttab_action(pActtab
, ap
->sp
->index
, action
);
4158 stp
->iTknOfst
= acttab_insert(pActtab
);
4159 if( stp
->iTknOfst
<mnTknOfst
) mnTknOfst
= stp
->iTknOfst
;
4160 if( stp
->iTknOfst
>mxTknOfst
) mxTknOfst
= stp
->iTknOfst
;
4162 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4164 if( ap
->sp
->index
<lemp
->nterminal
) continue;
4165 if( ap
->sp
->index
==lemp
->nsymbol
) continue;
4166 action
= compute_action(lemp
, ap
);
4167 if( action
<0 ) continue;
4168 acttab_action(pActtab
, ap
->sp
->index
, action
);
4170 stp
->iNtOfst
= acttab_insert(pActtab
);
4171 if( stp
->iNtOfst
<mnNtOfst
) mnNtOfst
= stp
->iNtOfst
;
4172 if( stp
->iNtOfst
>mxNtOfst
) mxNtOfst
= stp
->iNtOfst
;
4174 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4176 for(jj
=nn
=0; jj
<pActtab
->nAction
; jj
++){
4177 if( pActtab
->aAction
[jj
].action
<0 ) nn
++;
4179 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4180 i
, stp
->statenum
, ax
[i
].isTkn
? "Token" : "Var ",
4181 ax
[i
].nAction
, pActtab
->nAction
, nn
);
4187 /* Mark rules that are actually used for reduce actions after all
4188 ** optimizations have been applied
4190 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->doesReduce
= LEMON_FALSE
;
4191 for(i
=0; i
<lemp
->nxstate
; i
++){
4192 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
4193 if( ap
->type
==REDUCE
|| ap
->type
==SHIFTREDUCE
){
4194 ap
->x
.rp
->doesReduce
= 1;
4199 /* Finish rendering the constants now that the action table has
4201 fprintf(out
,"#define YYNSTATE %d\n",lemp
->nxstate
); lineno
++;
4202 fprintf(out
,"#define YYNRULE %d\n",lemp
->nrule
); lineno
++;
4203 fprintf(out
,"#define YY_MAX_SHIFT %d\n",lemp
->nxstate
-1); lineno
++;
4204 fprintf(out
,"#define YY_MIN_SHIFTREDUCE %d\n",lemp
->nstate
); lineno
++;
4205 i
= lemp
->nstate
+ lemp
->nrule
;
4206 fprintf(out
,"#define YY_MAX_SHIFTREDUCE %d\n", i
-1); lineno
++;
4207 fprintf(out
,"#define YY_MIN_REDUCE %d\n", i
); lineno
++;
4208 i
= lemp
->nstate
+ lemp
->nrule
*2;
4209 fprintf(out
,"#define YY_MAX_REDUCE %d\n", i
-1); lineno
++;
4210 fprintf(out
,"#define YY_ERROR_ACTION %d\n", i
); lineno
++;
4211 fprintf(out
,"#define YY_ACCEPT_ACTION %d\n", i
+1); lineno
++;
4212 fprintf(out
,"#define YY_NO_ACTION %d\n", i
+2); lineno
++;
4213 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4215 /* Now output the action table and its associates:
4217 ** yy_action[] A single table containing all actions.
4218 ** yy_lookahead[] A table containing the lookahead for each entry in
4219 ** yy_action. Used to detect hash collisions.
4220 ** yy_shift_ofst[] For each state, the offset into yy_action for
4221 ** shifting terminals.
4222 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4223 ** shifting non-terminals after a reduce.
4224 ** yy_default[] Default action for each state.
4227 /* Output the yy_action table */
4228 lemp
->nactiontab
= n
= acttab_size(pActtab
);
4229 lemp
->tablesize
+= n
*szActionType
;
4230 fprintf(out
,"#define YY_ACTTAB_COUNT (%d)\n", n
); lineno
++;
4231 fprintf(out
,"static const YYACTIONTYPE yy_action[] = {\n"); lineno
++;
4232 for(i
=j
=0; i
<n
; i
++){
4233 int action
= acttab_yyaction(pActtab
, i
);
4234 if( action
<0 ) action
= lemp
->nstate
+ lemp
->nrule
+ 2;
4235 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4236 fprintf(out
, " %4d,", action
);
4237 if( j
==9 || i
==n
-1 ){
4238 fprintf(out
, "\n"); lineno
++;
4244 fprintf(out
, "};\n"); lineno
++;
4246 /* Output the yy_lookahead table */
4247 lemp
->tablesize
+= n
*szCodeType
;
4248 fprintf(out
,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno
++;
4249 for(i
=j
=0; i
<n
; i
++){
4250 int la
= acttab_yylookahead(pActtab
, i
);
4251 if( la
<0 ) la
= lemp
->nsymbol
;
4252 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4253 fprintf(out
, " %4d,", la
);
4254 if( j
==9 || i
==n
-1 ){
4255 fprintf(out
, "\n"); lineno
++;
4261 fprintf(out
, "};\n"); lineno
++;
4263 /* Output the yy_shift_ofst[] table */
4265 while( n
>0 && lemp
->sorted
[n
-1]->iTknOfst
==NO_OFFSET
) n
--;
4266 fprintf(out
, "#define YY_SHIFT_USE_DFLT (%d)\n", lemp
->nactiontab
); lineno
++;
4267 fprintf(out
, "#define YY_SHIFT_COUNT (%d)\n", n
-1); lineno
++;
4268 fprintf(out
, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst
); lineno
++;
4269 fprintf(out
, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst
); lineno
++;
4270 fprintf(out
, "static const %s yy_shift_ofst[] = {\n",
4271 minimum_size_type(mnTknOfst
, lemp
->nterminal
+lemp
->nactiontab
, &sz
));
4273 lemp
->tablesize
+= n
*sz
;
4274 for(i
=j
=0; i
<n
; i
++){
4276 stp
= lemp
->sorted
[i
];
4277 ofst
= stp
->iTknOfst
;
4278 if( ofst
==NO_OFFSET
) ofst
= lemp
->nactiontab
;
4279 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4280 fprintf(out
, " %4d,", ofst
);
4281 if( j
==9 || i
==n
-1 ){
4282 fprintf(out
, "\n"); lineno
++;
4288 fprintf(out
, "};\n"); lineno
++;
4290 /* Output the yy_reduce_ofst[] table */
4291 fprintf(out
, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst
-1); lineno
++;
4293 while( n
>0 && lemp
->sorted
[n
-1]->iNtOfst
==NO_OFFSET
) n
--;
4294 fprintf(out
, "#define YY_REDUCE_COUNT (%d)\n", n
-1); lineno
++;
4295 fprintf(out
, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst
); lineno
++;
4296 fprintf(out
, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst
); lineno
++;
4297 fprintf(out
, "static const %s yy_reduce_ofst[] = {\n",
4298 minimum_size_type(mnNtOfst
-1, mxNtOfst
, &sz
)); lineno
++;
4299 lemp
->tablesize
+= n
*sz
;
4300 for(i
=j
=0; i
<n
; i
++){
4302 stp
= lemp
->sorted
[i
];
4303 ofst
= stp
->iNtOfst
;
4304 if( ofst
==NO_OFFSET
) ofst
= mnNtOfst
- 1;
4305 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4306 fprintf(out
, " %4d,", ofst
);
4307 if( j
==9 || i
==n
-1 ){
4308 fprintf(out
, "\n"); lineno
++;
4314 fprintf(out
, "};\n"); lineno
++;
4316 /* Output the default action table */
4317 fprintf(out
, "static const YYACTIONTYPE yy_default[] = {\n"); lineno
++;
4319 lemp
->tablesize
+= n
*szActionType
;
4320 for(i
=j
=0; i
<n
; i
++){
4321 stp
= lemp
->sorted
[i
];
4322 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
4323 fprintf(out
, " %4d,", stp
->iDfltReduce
+lemp
->nstate
+lemp
->nrule
);
4324 if( j
==9 || i
==n
-1 ){
4325 fprintf(out
, "\n"); lineno
++;
4331 fprintf(out
, "};\n"); lineno
++;
4332 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4334 /* Generate the table of fallback tokens.
4336 if( lemp
->has_fallback
){
4337 int mx
= lemp
->nterminal
- 1;
4338 while( mx
>0 && lemp
->symbols
[mx
]->fallback
==0 ){ mx
--; }
4339 lemp
->tablesize
+= (mx
+1)*szCodeType
;
4340 for(i
=0; i
<=mx
; i
++){
4341 struct symbol
*p
= lemp
->symbols
[i
];
4342 if( p
->fallback
==0 ){
4343 fprintf(out
, " 0, /* %10s => nothing */\n", p
->name
);
4345 fprintf(out
, " %3d, /* %10s => %s */\n", p
->fallback
->index
,
4346 p
->name
, p
->fallback
->name
);
4351 tplt_xfer(lemp
->name
, in
, out
, &lineno
);
4353 /* Generate a table containing the symbolic name of every symbol
4355 for(i
=0; i
<lemp
->nsymbol
; i
++){
4356 lemon_sprintf(line
,"\"%s\",",lemp
->symbols
[i
]->name
);
4357 fprintf(out
," %-15s",line
);
4358 if( (i
&3)==3 ){ fprintf(out
,"\n"); lineno
++; }
4360 if( (i
&3)!=0 ){ fprintf(out
,"\n"); lineno
++; }
4361 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4363 /* Generate a table containing a text string that describes every
4364 ** rule in the rule set of the grammar. This information is used
4365 ** when tracing REDUCE actions.
4367 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
4368 assert( rp
->iRule
==i
);
4369 fprintf(out
," /* %3d */ \"", i
);
4370 writeRuleText(out
, rp
);
4371 fprintf(out
,"\",\n"); lineno
++;
4373 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4375 /* Generate code which executes every time a symbol is popped from
4376 ** the stack while processing errors or while destroying the parser.
4377 ** (In other words, generate the %destructor actions)
4379 if( lemp
->tokendest
){
4381 for(i
=0; i
<lemp
->nsymbol
; i
++){
4382 struct symbol
*sp
= lemp
->symbols
[i
];
4383 if( sp
==0 || sp
->type
!=TERMINAL
) continue;
4385 fprintf(out
, " /* TERMINAL Destructor */\n"); lineno
++;
4388 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4390 for(i
=0; i
<lemp
->nsymbol
&& lemp
->symbols
[i
]->type
!=TERMINAL
; i
++);
4391 if( i
<lemp
->nsymbol
){
4392 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4393 fprintf(out
," break;\n"); lineno
++;
4396 if( lemp
->vardest
){
4397 struct symbol
*dflt_sp
= 0;
4399 for(i
=0; i
<lemp
->nsymbol
; i
++){
4400 struct symbol
*sp
= lemp
->symbols
[i
];
4401 if( sp
==0 || sp
->type
==TERMINAL
||
4402 sp
->index
<=0 || sp
->destructor
!=0 ) continue;
4404 fprintf(out
, " /* Default NON-TERMINAL Destructor */\n"); lineno
++;
4407 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4411 emit_destructor_code(out
,dflt_sp
,lemp
,&lineno
);
4413 fprintf(out
," break;\n"); lineno
++;
4415 for(i
=0; i
<lemp
->nsymbol
; i
++){
4416 struct symbol
*sp
= lemp
->symbols
[i
];
4417 if( sp
==0 || sp
->type
==TERMINAL
|| sp
->destructor
==0 ) continue;
4418 if( sp
->destLineno
<0 ) continue; /* Already emitted */
4419 fprintf(out
," case %d: /* %s */\n", sp
->index
, sp
->name
); lineno
++;
4421 /* Combine duplicate destructors into a single case */
4422 for(j
=i
+1; j
<lemp
->nsymbol
; j
++){
4423 struct symbol
*sp2
= lemp
->symbols
[j
];
4424 if( sp2
&& sp2
->type
!=TERMINAL
&& sp2
->destructor
4425 && sp2
->dtnum
==sp
->dtnum
4426 && strcmp(sp
->destructor
,sp2
->destructor
)==0 ){
4427 fprintf(out
," case %d: /* %s */\n",
4428 sp2
->index
, sp2
->name
); lineno
++;
4429 sp2
->destLineno
= -1; /* Avoid emitting this destructor again */
4433 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
4434 fprintf(out
," break;\n"); lineno
++;
4436 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4438 /* Generate code which executes whenever the parser stack overflows */
4439 tplt_print(out
,lemp
,lemp
->overflow
,&lineno
);
4440 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4442 /* Generate the table of rule information
4444 ** Note: This code depends on the fact that rules are number
4445 ** sequentually beginning with 0.
4447 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4448 fprintf(out
," { %d, %d },\n",rp
->lhs
->index
,-rp
->nrhs
); lineno
++;
4450 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4452 /* Generate code which execution during each REDUCE action */
4454 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4455 i
+= translate_code(lemp
, rp
);
4458 fprintf(out
," YYMINORTYPE yylhsminor;\n"); lineno
++;
4460 /* First output rules other than the default: rule */
4461 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4462 struct rule
*rp2
; /* Other rules with the same action */
4463 if( rp
->codeEmitted
) continue;
4465 /* No C code actions, so this will be part of the "default:" rule */
4468 fprintf(out
," case %d: /* ", rp
->iRule
);
4469 writeRuleText(out
, rp
);
4470 fprintf(out
, " */\n"); lineno
++;
4471 for(rp2
=rp
->next
; rp2
; rp2
=rp2
->next
){
4472 if( rp2
->code
==rp
->code
&& rp2
->codePrefix
==rp
->codePrefix
4473 && rp2
->codeSuffix
==rp
->codeSuffix
){
4474 fprintf(out
," case %d: /* ", rp2
->iRule
);
4475 writeRuleText(out
, rp2
);
4476 fprintf(out
," */ yytestcase(yyruleno==%d);\n", rp2
->iRule
); lineno
++;
4477 rp2
->codeEmitted
= 1;
4480 emit_code(out
,rp
,lemp
,&lineno
);
4481 fprintf(out
," break;\n"); lineno
++;
4482 rp
->codeEmitted
= 1;
4484 /* Finally, output the default: rule. We choose as the default: all
4485 ** empty actions. */
4486 fprintf(out
," default:\n"); lineno
++;
4487 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
4488 if( rp
->codeEmitted
) continue;
4489 assert( rp
->noCode
);
4490 fprintf(out
," /* (%d) ", rp
->iRule
);
4491 writeRuleText(out
, rp
);
4492 if( rp
->doesReduce
){
4493 fprintf(out
, " */ yytestcase(yyruleno==%d);\n", rp
->iRule
); lineno
++;
4495 fprintf(out
, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4496 rp
->iRule
); lineno
++;
4499 fprintf(out
," break;\n"); lineno
++;
4500 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4502 /* Generate code which executes if a parse fails */
4503 tplt_print(out
,lemp
,lemp
->failure
,&lineno
);
4504 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4506 /* Generate code which executes when a syntax error occurs */
4507 tplt_print(out
,lemp
,lemp
->error
,&lineno
);
4508 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4510 /* Generate code which executes when the parser accepts its input */
4511 tplt_print(out
,lemp
,lemp
->accept
,&lineno
);
4512 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
4514 /* Append any addition code the user desires */
4515 tplt_print(out
,lemp
,lemp
->extracode
,&lineno
);
4522 /* Generate a header file for the parser */
4523 void ReportHeader(struct lemon
*lemp
)
4527 char line
[LINESIZE
];
4528 char pattern
[LINESIZE
];
4531 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
4533 in
= file_open(lemp
,".h","rb");
4536 for(i
=1; i
<lemp
->nterminal
&& fgets(line
,LINESIZE
,in
); i
++){
4537 lemon_sprintf(pattern
,"#define %s%-30s %3d\n",
4538 prefix
,lemp
->symbols
[i
]->name
,i
);
4539 if( strcmp(line
,pattern
) ) break;
4541 nextChar
= fgetc(in
);
4543 if( i
==lemp
->nterminal
&& nextChar
==EOF
){
4544 /* No change in the file. Don't rewrite it. */
4548 out
= file_open(lemp
,".h","wb");
4550 for(i
=1; i
<lemp
->nterminal
; i
++){
4551 fprintf(out
,"#define %s%-30s %3d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
4558 /* Reduce the size of the action tables, if possible, by making use
4561 ** In this version, we take the most frequent REDUCE action and make
4562 ** it the default. Except, there is no default if the wildcard token
4563 ** is a possible look-ahead.
4565 void CompressTables(struct lemon
*lemp
)
4568 struct action
*ap
, *ap2
, *nextap
;
4569 struct rule
*rp
, *rp2
, *rbest
;
4574 for(i
=0; i
<lemp
->nstate
; i
++){
4575 stp
= lemp
->sorted
[i
];
4580 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4581 if( ap
->type
==SHIFT
&& ap
->sp
==lemp
->wildcard
){
4584 if( ap
->type
!=REDUCE
) continue;
4586 if( rp
->lhsStart
) continue;
4587 if( rp
==rbest
) continue;
4589 for(ap2
=ap
->next
; ap2
; ap2
=ap2
->next
){
4590 if( ap2
->type
!=REDUCE
) continue;
4592 if( rp2
==rbest
) continue;
4601 /* Do not make a default if the number of rules to default
4602 ** is not at least 1 or if the wildcard token is a possible
4605 if( nbest
<1 || usesWildcard
) continue;
4608 /* Combine matching REDUCE actions into a single default */
4609 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4610 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) break;
4613 ap
->sp
= Symbol_new("{default}");
4614 for(ap
=ap
->next
; ap
; ap
=ap
->next
){
4615 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) ap
->type
= NOT_USED
;
4617 stp
->ap
= Action_sort(stp
->ap
);
4619 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4620 if( ap
->type
==SHIFT
) break;
4621 if( ap
->type
==REDUCE
&& ap
->x
.rp
!=rbest
) break;
4624 stp
->autoReduce
= 1;
4625 stp
->pDfltReduce
= rbest
;
4629 /* Make a second pass over all states and actions. Convert
4630 ** every action that is a SHIFT to an autoReduce state into
4631 ** a SHIFTREDUCE action.
4633 for(i
=0; i
<lemp
->nstate
; i
++){
4634 stp
= lemp
->sorted
[i
];
4635 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4636 struct state
*pNextState
;
4637 if( ap
->type
!=SHIFT
) continue;
4638 pNextState
= ap
->x
.stp
;
4639 if( pNextState
->autoReduce
&& pNextState
->pDfltReduce
!=0 ){
4640 ap
->type
= SHIFTREDUCE
;
4641 ap
->x
.rp
= pNextState
->pDfltReduce
;
4646 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4647 ** (meaning that the SHIFTREDUCE will land back in the state where it
4648 ** started) and if there is no C-code associated with the reduce action,
4649 ** then we can go ahead and convert the action to be the same as the
4650 ** action for the RHS of the rule.
4652 for(i
=0; i
<lemp
->nstate
; i
++){
4653 stp
= lemp
->sorted
[i
];
4654 for(ap
=stp
->ap
; ap
; ap
=nextap
){
4656 if( ap
->type
!=SHIFTREDUCE
) continue;
4658 if( rp
->noCode
==0 ) continue;
4659 if( rp
->nrhs
!=1 ) continue;
4661 /* Only apply this optimization to non-terminals. It would be OK to
4662 ** apply it to terminal symbols too, but that makes the parser tables
4664 if( ap
->sp
->index
<lemp
->nterminal
) continue;
4666 /* If we reach this point, it means the optimization can be applied */
4668 for(ap2
=stp
->ap
; ap2
&& (ap2
==ap
|| ap2
->sp
!=rp
->lhs
); ap2
=ap2
->next
){}
4670 ap
->spOpt
= ap2
->sp
;
4671 ap
->type
= ap2
->type
;
4679 ** Compare two states for sorting purposes. The smaller state is the
4680 ** one with the most non-terminal actions. If they have the same number
4681 ** of non-terminal actions, then the smaller is the one with the most
4684 static int stateResortCompare(const void *a
, const void *b
){
4685 const struct state
*pA
= *(const struct state
**)a
;
4686 const struct state
*pB
= *(const struct state
**)b
;
4689 n
= pB
->nNtAct
- pA
->nNtAct
;
4691 n
= pB
->nTknAct
- pA
->nTknAct
;
4693 n
= pB
->statenum
- pA
->statenum
;
4702 ** Renumber and resort states so that states with fewer choices
4703 ** occur at the end. Except, keep state 0 as the first state.
4705 void ResortStates(struct lemon
*lemp
)
4711 for(i
=0; i
<lemp
->nstate
; i
++){
4712 stp
= lemp
->sorted
[i
];
4713 stp
->nTknAct
= stp
->nNtAct
= 0;
4714 stp
->iDfltReduce
= lemp
->nrule
; /* Init dflt action to "syntax error" */
4715 stp
->iTknOfst
= NO_OFFSET
;
4716 stp
->iNtOfst
= NO_OFFSET
;
4717 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4718 int iAction
= compute_action(lemp
,ap
);
4720 if( ap
->sp
->index
<lemp
->nterminal
){
4722 }else if( ap
->sp
->index
<lemp
->nsymbol
){
4725 assert( stp
->autoReduce
==0 || stp
->pDfltReduce
==ap
->x
.rp
);
4726 stp
->iDfltReduce
= iAction
- lemp
->nstate
- lemp
->nrule
;
4731 qsort(&lemp
->sorted
[1], lemp
->nstate
-1, sizeof(lemp
->sorted
[0]),
4732 stateResortCompare
);
4733 for(i
=0; i
<lemp
->nstate
; i
++){
4734 lemp
->sorted
[i
]->statenum
= i
;
4736 lemp
->nxstate
= lemp
->nstate
;
4737 while( lemp
->nxstate
>1 && lemp
->sorted
[lemp
->nxstate
-1]->autoReduce
){
4743 /***************** From the file "set.c" ************************************/
4745 ** Set manipulation routines for the LEMON parser generator.
4748 static int size
= 0;
4750 /* Set the set size */
4756 /* Allocate a new set */
4759 s
= (char*)calloc( size
, 1);
4761 extern void memory_error();
4767 /* Deallocate a set */
4768 void SetFree(char *s
)
4773 /* Add a new element to the set. Return TRUE if the element was added
4774 ** and FALSE if it was already there. */
4775 int SetAdd(char *s
, int e
)
4778 assert( e
>=0 && e
<size
);
4784 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4785 int SetUnion(char *s1
, char *s2
)
4789 for(i
=0; i
<size
; i
++){
4790 if( s2
[i
]==0 ) continue;
4798 /********************** From the file "table.c" ****************************/
4800 ** All code in this file has been automatically generated
4801 ** from a specification in the file
4803 ** by the associative array code building program "aagen".
4804 ** Do not edit this file! Instead, edit the specification
4805 ** file, then rerun aagen.
4808 ** Code for processing tables in the LEMON parser generator.
4811 PRIVATE
unsigned strhash(const char *x
)
4814 while( *x
) h
= h
*13 + *(x
++);
4818 /* Works like strdup, sort of. Save a string in malloced memory, but
4819 ** keep strings in a table so that the same string is not in more
4822 const char *Strsafe(const char *y
)
4827 if( y
==0 ) return 0;
4828 z
= Strsafe_find(y
);
4829 if( z
==0 && (cpy
=(char *)malloc( lemonStrlen(y
)+1 ))!=0 ){
4830 lemon_strcpy(cpy
,y
);
4838 /* There is one instance of the following structure for each
4839 ** associative array of type "x1".
4842 int size
; /* The number of available slots. */
4843 /* Must be a power of 2 greater than or */
4845 int count
; /* Number of currently slots filled */
4846 struct s_x1node
*tbl
; /* The data stored here */
4847 struct s_x1node
**ht
; /* Hash table for lookups */
4850 /* There is one instance of this structure for every data element
4851 ** in an associative array of type "x1".
4853 typedef struct s_x1node
{
4854 const char *data
; /* The data */
4855 struct s_x1node
*next
; /* Next entry with the same hash */
4856 struct s_x1node
**from
; /* Previous link */
4859 /* There is only one instance of the array, which is the following */
4860 static struct s_x1
*x1a
;
4862 /* Allocate a new associative array */
4863 void Strsafe_init(void){
4865 x1a
= (struct s_x1
*)malloc( sizeof(struct s_x1
) );
4869 x1a
->tbl
= (x1node
*)calloc(1024, sizeof(x1node
) + sizeof(x1node
*));
4875 x1a
->ht
= (x1node
**)&(x1a
->tbl
[1024]);
4876 for(i
=0; i
<1024; i
++) x1a
->ht
[i
] = 0;
4880 /* Insert a new record into the array. Return TRUE if successful.
4881 ** Prior data with the same key is NOT overwritten */
4882 int Strsafe_insert(const char *data
)
4888 if( x1a
==0 ) return 0;
4890 h
= ph
& (x1a
->size
-1);
4893 if( strcmp(np
->data
,data
)==0 ){
4894 /* An existing entry with the same key is found. */
4895 /* Fail because overwrite is not allows. */
4900 if( x1a
->count
>=x1a
->size
){
4901 /* Need to make the hash table bigger */
4904 array
.size
= arrSize
= x1a
->size
*2;
4905 array
.count
= x1a
->count
;
4906 array
.tbl
= (x1node
*)calloc(arrSize
, sizeof(x1node
) + sizeof(x1node
*));
4907 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4908 array
.ht
= (x1node
**)&(array
.tbl
[arrSize
]);
4909 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
4910 for(i
=0; i
<x1a
->count
; i
++){
4911 x1node
*oldnp
, *newnp
;
4912 oldnp
= &(x1a
->tbl
[i
]);
4913 h
= strhash(oldnp
->data
) & (arrSize
-1);
4914 newnp
= &(array
.tbl
[i
]);
4915 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4916 newnp
->next
= array
.ht
[h
];
4917 newnp
->data
= oldnp
->data
;
4918 newnp
->from
= &(array
.ht
[h
]);
4919 array
.ht
[h
] = newnp
;
4924 /* Insert the new data */
4925 h
= ph
& (x1a
->size
-1);
4926 np
= &(x1a
->tbl
[x1a
->count
++]);
4928 if( x1a
->ht
[h
] ) x1a
->ht
[h
]->from
= &(np
->next
);
4929 np
->next
= x1a
->ht
[h
];
4931 np
->from
= &(x1a
->ht
[h
]);
4935 /* Return a pointer to data assigned to the given key. Return NULL
4936 ** if no such key. */
4937 const char *Strsafe_find(const char *key
)
4942 if( x1a
==0 ) return 0;
4943 h
= strhash(key
) & (x1a
->size
-1);
4946 if( strcmp(np
->data
,key
)==0 ) break;
4949 return np
? np
->data
: 0;
4952 /* Return a pointer to the (terminal or nonterminal) symbol "x".
4953 ** Create a new symbol if this is the first time "x" has been seen.
4955 struct symbol
*Symbol_new(const char *x
)
4959 sp
= Symbol_find(x
);
4961 sp
= (struct symbol
*)calloc(1, sizeof(struct symbol
) );
4963 sp
->name
= Strsafe(x
);
4964 sp
->type
= ISUPPER(*x
) ? TERMINAL
: NONTERMINAL
;
4970 sp
->lambda
= LEMON_FALSE
;
4975 Symbol_insert(sp
,sp
->name
);
4981 /* Compare two symbols for sorting purposes. Return negative,
4982 ** zero, or positive if a is less then, equal to, or greater
4985 ** Symbols that begin with upper case letters (terminals or tokens)
4986 ** must sort before symbols that begin with lower case letters
4987 ** (non-terminals). And MULTITERMINAL symbols (created using the
4988 ** %token_class directive) must sort at the very end. Other than
4989 ** that, the order does not matter.
4991 ** We find experimentally that leaving the symbols in their original
4992 ** order (the order they appeared in the grammar file) gives the
4993 ** smallest parser tables in SQLite.
4995 int Symbolcmpp(const void *_a
, const void *_b
)
4997 const struct symbol
*a
= *(const struct symbol
**) _a
;
4998 const struct symbol
*b
= *(const struct symbol
**) _b
;
4999 int i1
= a
->type
==MULTITERMINAL
? 3 : a
->name
[0]>'Z' ? 2 : 1;
5000 int i2
= b
->type
==MULTITERMINAL
? 3 : b
->name
[0]>'Z' ? 2 : 1;
5001 return i1
==i2
? a
->index
- b
->index
: i1
- i2
;
5004 /* There is one instance of the following structure for each
5005 ** associative array of type "x2".
5008 int size
; /* The number of available slots. */
5009 /* Must be a power of 2 greater than or */
5011 int count
; /* Number of currently slots filled */
5012 struct s_x2node
*tbl
; /* The data stored here */
5013 struct s_x2node
**ht
; /* Hash table for lookups */
5016 /* There is one instance of this structure for every data element
5017 ** in an associative array of type "x2".
5019 typedef struct s_x2node
{
5020 struct symbol
*data
; /* The data */
5021 const char *key
; /* The key */
5022 struct s_x2node
*next
; /* Next entry with the same hash */
5023 struct s_x2node
**from
; /* Previous link */
5026 /* There is only one instance of the array, which is the following */
5027 static struct s_x2
*x2a
;
5029 /* Allocate a new associative array */
5030 void Symbol_init(void){
5032 x2a
= (struct s_x2
*)malloc( sizeof(struct s_x2
) );
5036 x2a
->tbl
= (x2node
*)calloc(128, sizeof(x2node
) + sizeof(x2node
*));
5042 x2a
->ht
= (x2node
**)&(x2a
->tbl
[128]);
5043 for(i
=0; i
<128; i
++) x2a
->ht
[i
] = 0;
5047 /* Insert a new record into the array. Return TRUE if successful.
5048 ** Prior data with the same key is NOT overwritten */
5049 int Symbol_insert(struct symbol
*data
, const char *key
)
5055 if( x2a
==0 ) return 0;
5057 h
= ph
& (x2a
->size
-1);
5060 if( strcmp(np
->key
,key
)==0 ){
5061 /* An existing entry with the same key is found. */
5062 /* Fail because overwrite is not allows. */
5067 if( x2a
->count
>=x2a
->size
){
5068 /* Need to make the hash table bigger */
5071 array
.size
= arrSize
= x2a
->size
*2;
5072 array
.count
= x2a
->count
;
5073 array
.tbl
= (x2node
*)calloc(arrSize
, sizeof(x2node
) + sizeof(x2node
*));
5074 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5075 array
.ht
= (x2node
**)&(array
.tbl
[arrSize
]);
5076 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5077 for(i
=0; i
<x2a
->count
; i
++){
5078 x2node
*oldnp
, *newnp
;
5079 oldnp
= &(x2a
->tbl
[i
]);
5080 h
= strhash(oldnp
->key
) & (arrSize
-1);
5081 newnp
= &(array
.tbl
[i
]);
5082 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5083 newnp
->next
= array
.ht
[h
];
5084 newnp
->key
= oldnp
->key
;
5085 newnp
->data
= oldnp
->data
;
5086 newnp
->from
= &(array
.ht
[h
]);
5087 array
.ht
[h
] = newnp
;
5092 /* Insert the new data */
5093 h
= ph
& (x2a
->size
-1);
5094 np
= &(x2a
->tbl
[x2a
->count
++]);
5097 if( x2a
->ht
[h
] ) x2a
->ht
[h
]->from
= &(np
->next
);
5098 np
->next
= x2a
->ht
[h
];
5100 np
->from
= &(x2a
->ht
[h
]);
5104 /* Return a pointer to data assigned to the given key. Return NULL
5105 ** if no such key. */
5106 struct symbol
*Symbol_find(const char *key
)
5111 if( x2a
==0 ) return 0;
5112 h
= strhash(key
) & (x2a
->size
-1);
5115 if( strcmp(np
->key
,key
)==0 ) break;
5118 return np
? np
->data
: 0;
5121 /* Return the n-th data. Return NULL if n is out of range. */
5122 struct symbol
*Symbol_Nth(int n
)
5124 struct symbol
*data
;
5125 if( x2a
&& n
>0 && n
<=x2a
->count
){
5126 data
= x2a
->tbl
[n
-1].data
;
5133 /* Return the size of the array */
5136 return x2a
? x2a
->count
: 0;
5139 /* Return an array of pointers to all data in the table.
5140 ** The array is obtained from malloc. Return NULL if memory allocation
5141 ** problems, or if the array is empty. */
5142 struct symbol
**Symbol_arrayof()
5144 struct symbol
**array
;
5146 if( x2a
==0 ) return 0;
5147 arrSize
= x2a
->count
;
5148 array
= (struct symbol
**)calloc(arrSize
, sizeof(struct symbol
*));
5150 for(i
=0; i
<arrSize
; i
++) array
[i
] = x2a
->tbl
[i
].data
;
5155 /* Compare two configurations */
5156 int Configcmp(const char *_a
,const char *_b
)
5158 const struct config
*a
= (struct config
*) _a
;
5159 const struct config
*b
= (struct config
*) _b
;
5161 x
= a
->rp
->index
- b
->rp
->index
;
5162 if( x
==0 ) x
= a
->dot
- b
->dot
;
5166 /* Compare two states */
5167 PRIVATE
int statecmp(struct config
*a
, struct config
*b
)
5170 for(rc
=0; rc
==0 && a
&& b
; a
=a
->bp
, b
=b
->bp
){
5171 rc
= a
->rp
->index
- b
->rp
->index
;
5172 if( rc
==0 ) rc
= a
->dot
- b
->dot
;
5182 PRIVATE
unsigned statehash(struct config
*a
)
5186 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5192 /* Allocate a new state structure */
5193 struct state
*State_new()
5195 struct state
*newstate
;
5196 newstate
= (struct state
*)calloc(1, sizeof(struct state
) );
5197 MemoryCheck(newstate
);
5201 /* There is one instance of the following structure for each
5202 ** associative array of type "x3".
5205 int size
; /* The number of available slots. */
5206 /* Must be a power of 2 greater than or */
5208 int count
; /* Number of currently slots filled */
5209 struct s_x3node
*tbl
; /* The data stored here */
5210 struct s_x3node
**ht
; /* Hash table for lookups */
5213 /* There is one instance of this structure for every data element
5214 ** in an associative array of type "x3".
5216 typedef struct s_x3node
{
5217 struct state
*data
; /* The data */
5218 struct config
*key
; /* The key */
5219 struct s_x3node
*next
; /* Next entry with the same hash */
5220 struct s_x3node
**from
; /* Previous link */
5223 /* There is only one instance of the array, which is the following */
5224 static struct s_x3
*x3a
;
5226 /* Allocate a new associative array */
5227 void State_init(void){
5229 x3a
= (struct s_x3
*)malloc( sizeof(struct s_x3
) );
5233 x3a
->tbl
= (x3node
*)calloc(128, sizeof(x3node
) + sizeof(x3node
*));
5239 x3a
->ht
= (x3node
**)&(x3a
->tbl
[128]);
5240 for(i
=0; i
<128; i
++) x3a
->ht
[i
] = 0;
5244 /* Insert a new record into the array. Return TRUE if successful.
5245 ** Prior data with the same key is NOT overwritten */
5246 int State_insert(struct state
*data
, struct config
*key
)
5252 if( x3a
==0 ) return 0;
5253 ph
= statehash(key
);
5254 h
= ph
& (x3a
->size
-1);
5257 if( statecmp(np
->key
,key
)==0 ){
5258 /* An existing entry with the same key is found. */
5259 /* Fail because overwrite is not allows. */
5264 if( x3a
->count
>=x3a
->size
){
5265 /* Need to make the hash table bigger */
5268 array
.size
= arrSize
= x3a
->size
*2;
5269 array
.count
= x3a
->count
;
5270 array
.tbl
= (x3node
*)calloc(arrSize
, sizeof(x3node
) + sizeof(x3node
*));
5271 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5272 array
.ht
= (x3node
**)&(array
.tbl
[arrSize
]);
5273 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5274 for(i
=0; i
<x3a
->count
; i
++){
5275 x3node
*oldnp
, *newnp
;
5276 oldnp
= &(x3a
->tbl
[i
]);
5277 h
= statehash(oldnp
->key
) & (arrSize
-1);
5278 newnp
= &(array
.tbl
[i
]);
5279 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5280 newnp
->next
= array
.ht
[h
];
5281 newnp
->key
= oldnp
->key
;
5282 newnp
->data
= oldnp
->data
;
5283 newnp
->from
= &(array
.ht
[h
]);
5284 array
.ht
[h
] = newnp
;
5289 /* Insert the new data */
5290 h
= ph
& (x3a
->size
-1);
5291 np
= &(x3a
->tbl
[x3a
->count
++]);
5294 if( x3a
->ht
[h
] ) x3a
->ht
[h
]->from
= &(np
->next
);
5295 np
->next
= x3a
->ht
[h
];
5297 np
->from
= &(x3a
->ht
[h
]);
5301 /* Return a pointer to data assigned to the given key. Return NULL
5302 ** if no such key. */
5303 struct state
*State_find(struct config
*key
)
5308 if( x3a
==0 ) return 0;
5309 h
= statehash(key
) & (x3a
->size
-1);
5312 if( statecmp(np
->key
,key
)==0 ) break;
5315 return np
? np
->data
: 0;
5318 /* Return an array of pointers to all data in the table.
5319 ** The array is obtained from malloc. Return NULL if memory allocation
5320 ** problems, or if the array is empty. */
5321 struct state
**State_arrayof(void)
5323 struct state
**array
;
5325 if( x3a
==0 ) return 0;
5326 arrSize
= x3a
->count
;
5327 array
= (struct state
**)calloc(arrSize
, sizeof(struct state
*));
5329 for(i
=0; i
<arrSize
; i
++) array
[i
] = x3a
->tbl
[i
].data
;
5334 /* Hash a configuration */
5335 PRIVATE
unsigned confighash(struct config
*a
)
5338 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
5342 /* There is one instance of the following structure for each
5343 ** associative array of type "x4".
5346 int size
; /* The number of available slots. */
5347 /* Must be a power of 2 greater than or */
5349 int count
; /* Number of currently slots filled */
5350 struct s_x4node
*tbl
; /* The data stored here */
5351 struct s_x4node
**ht
; /* Hash table for lookups */
5354 /* There is one instance of this structure for every data element
5355 ** in an associative array of type "x4".
5357 typedef struct s_x4node
{
5358 struct config
*data
; /* The data */
5359 struct s_x4node
*next
; /* Next entry with the same hash */
5360 struct s_x4node
**from
; /* Previous link */
5363 /* There is only one instance of the array, which is the following */
5364 static struct s_x4
*x4a
;
5366 /* Allocate a new associative array */
5367 void Configtable_init(void){
5369 x4a
= (struct s_x4
*)malloc( sizeof(struct s_x4
) );
5373 x4a
->tbl
= (x4node
*)calloc(64, sizeof(x4node
) + sizeof(x4node
*));
5379 x4a
->ht
= (x4node
**)&(x4a
->tbl
[64]);
5380 for(i
=0; i
<64; i
++) x4a
->ht
[i
] = 0;
5384 /* Insert a new record into the array. Return TRUE if successful.
5385 ** Prior data with the same key is NOT overwritten */
5386 int Configtable_insert(struct config
*data
)
5392 if( x4a
==0 ) return 0;
5393 ph
= confighash(data
);
5394 h
= ph
& (x4a
->size
-1);
5397 if( Configcmp((const char *) np
->data
,(const char *) data
)==0 ){
5398 /* An existing entry with the same key is found. */
5399 /* Fail because overwrite is not allows. */
5404 if( x4a
->count
>=x4a
->size
){
5405 /* Need to make the hash table bigger */
5408 array
.size
= arrSize
= x4a
->size
*2;
5409 array
.count
= x4a
->count
;
5410 array
.tbl
= (x4node
*)calloc(arrSize
, sizeof(x4node
) + sizeof(x4node
*));
5411 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
5412 array
.ht
= (x4node
**)&(array
.tbl
[arrSize
]);
5413 for(i
=0; i
<arrSize
; i
++) array
.ht
[i
] = 0;
5414 for(i
=0; i
<x4a
->count
; i
++){
5415 x4node
*oldnp
, *newnp
;
5416 oldnp
= &(x4a
->tbl
[i
]);
5417 h
= confighash(oldnp
->data
) & (arrSize
-1);
5418 newnp
= &(array
.tbl
[i
]);
5419 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
5420 newnp
->next
= array
.ht
[h
];
5421 newnp
->data
= oldnp
->data
;
5422 newnp
->from
= &(array
.ht
[h
]);
5423 array
.ht
[h
] = newnp
;
5428 /* Insert the new data */
5429 h
= ph
& (x4a
->size
-1);
5430 np
= &(x4a
->tbl
[x4a
->count
++]);
5432 if( x4a
->ht
[h
] ) x4a
->ht
[h
]->from
= &(np
->next
);
5433 np
->next
= x4a
->ht
[h
];
5435 np
->from
= &(x4a
->ht
[h
]);
5439 /* Return a pointer to data assigned to the given key. Return NULL
5440 ** if no such key. */
5441 struct config
*Configtable_find(struct config
*key
)
5446 if( x4a
==0 ) return 0;
5447 h
= confighash(key
) & (x4a
->size
-1);
5450 if( Configcmp((const char *) np
->data
,(const char *) key
)==0 ) break;
5453 return np
? np
->data
: 0;
5456 /* Remove all data from the table. Pass each data to the function "f"
5457 ** as it is removed. ("f" may be null to avoid this step.) */
5458 void Configtable_clear(int(*f
)(struct config
*))
5461 if( x4a
==0 || x4a
->count
==0 ) return;
5462 if( f
) for(i
=0; i
<x4a
->count
; i
++) (*f
)(x4a
->tbl
[i
].data
);
5463 for(i
=0; i
<x4a
->size
; i
++) x4a
->ht
[i
] = 0;