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.
17 # if defined(_WIN32) || defined(WIN32)
28 /* #define PRIVATE static */
32 #define MAXRHS 5 /* Set low to exercise exception code */
37 static const char *mybasename(const char *str
) {
38 const char *base
= strrchr(str
, '/');
39 return base
? base
+1 : str
;
42 static char *msort(char*,char**,int(*)(const char*,const char*));
44 static struct action
*Action_new(void);
45 static struct action
*Action_sort(struct action
*);
47 /********** From the file "build.h" ************************************/
48 void FindRulePrecedences();
52 void FindFollowSets();
55 /********* From the file "configlist.h" *********************************/
56 void Configlist_init(/* void */);
57 struct config
*Configlist_add(/* struct rule *, int */);
58 struct config
*Configlist_addbasis(/* struct rule *, int */);
59 void Configlist_closure(/* void */);
60 void Configlist_sort(/* void */);
61 void Configlist_sortbasis(/* void */);
62 struct config
*Configlist_return(/* void */);
63 struct config
*Configlist_basis(/* void */);
64 void Configlist_eat(/* struct config * */);
65 void Configlist_reset(/* void */);
67 /********* From the file "error.h" ***************************************/
68 void ErrorMsg(const char *, int,const char *, ...);
70 /****** From the file "option.h" ******************************************/
72 enum { OPT_FLAG
=1, OPT_INT
, OPT_DBL
, OPT_STR
,
73 OPT_FFLAG
, OPT_FINT
, OPT_FDBL
, OPT_FSTR
} type
;
78 int OptInit(/* char**,struct s_options*,FILE* */);
79 int OptNArgs(/* void */);
80 char *OptArg(/* int */);
81 void OptErr(/* int */);
82 void OptPrint(/* void */);
84 /******** From the file "parse.h" *****************************************/
85 void Parse(/* struct lemon *lemp */);
87 /********* From the file "plink.h" ***************************************/
88 struct plink
*Plink_new(/* void */);
89 void Plink_add(/* struct plink **, struct config * */);
90 void Plink_copy(/* struct plink **, struct plink * */);
91 void Plink_delete(/* struct plink * */);
93 /********** From the file "report.h" *************************************/
94 void Reprint(/* struct lemon * */);
95 void ReportOutput(/* struct lemon * */);
96 void ReportTable(/* struct lemon * */);
97 void ReportHeader(/* struct lemon * */);
98 void CompressTables(/* struct lemon * */);
99 void ResortStates(/* struct lemon * */);
101 /********** From the file "set.h" ****************************************/
102 void SetSize(/* int N */); /* All sets will be of size N */
103 char *SetNew(/* void */); /* A new set for element 0..N */
104 void SetFree(/* char* */); /* Deallocate a set */
106 int SetAdd(/* char*,int */); /* Add element to a set */
107 int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
109 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
111 /********** From the file "struct.h" *************************************/
113 ** Principal data structures for the LEMON parser generator.
116 typedef enum {LEMON_FALSE
=0, LEMON_TRUE
} Boolean
;
118 /* Symbols (terminals and nonterminals) of the grammar are stored
119 ** in the following: */
121 char *name
; /* Name of the symbol */
122 int index
; /* Index number for this symbol */
127 } type
; /* Symbols are all either TERMINALS or NTs */
128 struct rule
*rule
; /* Linked list of rules of this (if an NT) */
129 struct symbol
*fallback
; /* fallback token in case this token doesn't parse */
130 int prec
; /* Precedence if defined (-1 otherwise) */
136 } assoc
; /* Associativity if predecence is defined */
137 char *firstset
; /* First-set for all rules of this symbol */
138 Boolean lambda
; /* True if NT and can generate an empty string */
139 int useCnt
; /* Number of times used */
140 char *destructor
; /* Code which executes whenever this symbol is
141 ** popped from the stack during error processing */
142 int destructorln
; /* Line number of destructor code */
143 char *datatype
; /* The data type of information held by this
144 ** object. Only used if type==NONTERMINAL */
145 int dtnum
; /* The data type number. In the parser, the value
146 ** stack is a union. The .yy%d element of this
147 ** union is the correct data type for this object */
148 /* The following fields are used by MULTITERMINALs only */
149 int nsubsym
; /* Number of constituent symbols in the MULTI */
150 struct symbol
**subsym
; /* Array of constituent symbols */
153 /* Each production rule in the grammar is stored in the following
156 struct symbol
*lhs
; /* Left-hand side of the rule */
157 char *lhsalias
; /* Alias for the LHS (NULL if none) */
158 int lhsStart
; /* True if left-hand side is the start symbol */
159 int ruleline
; /* Line number for the rule */
160 int nrhs
; /* Number of RHS symbols */
161 struct symbol
**rhs
; /* The RHS symbols */
162 char **rhsalias
; /* An alias for each RHS symbol (NULL if none) */
163 int line
; /* Line number at which code begins */
164 char *code
; /* The code executed when this rule is reduced */
165 struct symbol
*precsym
; /* Precedence symbol for this rule */
166 int index
; /* An index number for this rule */
167 Boolean canReduce
; /* True if this rule is ever reduced */
168 struct rule
*nextlhs
; /* Next rule with the same LHS */
169 struct rule
*next
; /* Next rule in the global list */
172 /* A configuration is a production rule of the grammar together with
173 ** a mark (dot) showing how much of that rule has been processed so far.
174 ** Configurations also contain a follow-set which is a list of terminal
175 ** symbols which are allowed to immediately follow the end of the rule.
176 ** Every configuration is recorded as an instance of the following: */
178 struct rule
*rp
; /* The rule upon which the configuration is based */
179 int dot
; /* The parse point */
180 char *fws
; /* Follow-set for this configuration only */
181 struct plink
*fplp
; /* Follow-set forward propagation links */
182 struct plink
*bplp
; /* Follow-set backwards propagation links */
183 struct state
*stp
; /* Pointer to state which contains this */
185 COMPLETE
, /* The status is used during followset and */
186 INCOMPLETE
/* shift computations */
188 struct config
*next
; /* Next configuration in the state */
189 struct config
*bp
; /* The next basis configuration */
192 /* Every shift or reduce operation is stored as one of the following */
194 struct symbol
*sp
; /* The look-ahead symbol */
200 SSCONFLICT
, /* A shift/shift conflict */
201 SRCONFLICT
, /* Was a reduce, but part of a conflict */
202 RRCONFLICT
, /* Was a reduce, but part of a conflict */
203 SH_RESOLVED
, /* Was a shift. Precedence resolved conflict */
204 RD_RESOLVED
, /* Was reduce. Precedence resolved conflict */
205 NOT_USED
/* Deleted by compression */
208 struct state
*stp
; /* The new state, if a shift */
209 struct rule
*rp
; /* The rule, if a reduce */
211 struct action
*next
; /* Next action for this state */
212 struct action
*collide
; /* Next action with the same hash */
215 /* Each state of the generated parser's finite state machine
216 ** is encoded as an instance of the following structure. */
218 struct config
*bp
; /* The basis configurations for this state */
219 struct config
*cfp
; /* All configurations in this set */
220 int statenum
; /* Sequencial number for this state */
221 struct action
*ap
; /* Array of actions for this state */
222 int nTknAct
, nNtAct
; /* Number of actions on terminals and nonterminals */
223 int iTknOfst
, iNtOfst
; /* yy_action[] offset for terminals and nonterms */
224 int iDflt
; /* Default action */
226 #define NO_OFFSET (-2147483647)
228 /* A followset propagation link indicates that the contents of one
229 ** configuration followset should be propagated to another whenever
230 ** the first changes. */
232 struct config
*cfp
; /* The configuration to which linked */
233 struct plink
*next
; /* The next propagate link */
236 /* The state vector for the entire parser generator is recorded as
237 ** follows. (LEMON uses no global variables and makes little use of
238 ** static variables. Fields in the following structure can be thought
239 ** of as begin global variables in the program.) */
241 struct state
**sorted
; /* Table of states sorted by state number */
242 struct rule
*rule
; /* List of all rules */
243 int nstate
; /* Number of states */
244 int nrule
; /* Number of rules */
245 int nsymbol
; /* Number of terminal and nonterminal symbols */
246 int nterminal
; /* Number of terminal symbols */
247 struct symbol
**symbols
; /* Sorted array of pointers to symbols */
248 int errorcnt
; /* Number of errors */
249 struct symbol
*errsym
; /* The error symbol */
250 struct symbol
*wildcard
; /* Token that matches anything */
251 char *name
; /* Name of the generated parser */
252 char *arg
; /* Declaration of the 3th argument to parser */
253 char *tokentype
; /* Type of terminal symbols in the parser stack */
254 char *vartype
; /* The default type of non-terminal symbols */
255 char *start
; /* Name of the start symbol for the grammar */
256 char *stacksize
; /* Size of the parser stack */
257 char *include
; /* Code to put at the start of the C file */
258 int includeln
; /* Line number for start of include code */
259 char *error
; /* Code to execute when an error is seen */
260 int errorln
; /* Line number for start of error code */
261 char *overflow
; /* Code to execute on a stack overflow */
262 int overflowln
; /* Line number for start of overflow code */
263 char *failure
; /* Code to execute on parser failure */
264 int failureln
; /* Line number for start of failure code */
265 char *accept
; /* Code to execute when the parser excepts */
266 int acceptln
; /* Line number for the start of accept code */
267 char *extracode
; /* Code appended to the generated file */
268 int extracodeln
; /* Line number for the start of the extra code */
269 char *tokendest
; /* Code to execute to destroy token data */
270 int tokendestln
; /* Line number for token destroyer code */
271 char *vardest
; /* Code for the default non-terminal destructor */
272 int vardestln
; /* Line number for default non-term destructor code*/
273 char *filename
; /* Name of the input file */
274 char *outname
; /* Name of the current output file */
275 char *tokenprefix
; /* A prefix added to token names in the .h file */
276 int nconflict
; /* Number of parsing conflicts */
277 int tablesize
; /* Size of the parse tables */
278 int basisflag
; /* Print only basis configurations */
279 int has_fallback
; /* True if any %fallback is seen in the grammer */
280 char *argv0
; /* Name of the program */
283 #define MemoryCheck(X) if((X)==0){ \
284 extern void memory_error(); \
288 /**************** From the file "table.h" *********************************/
290 ** All code in this file has been automatically generated
291 ** from a specification in the file
293 ** by the associative array code building program "aagen".
294 ** Do not edit this file! Instead, edit the specification
295 ** file, then rerun aagen.
298 ** Code for processing tables in the LEMON parser generator.
301 /* Routines for handling a strings */
305 void Strsafe_init(/* void */);
306 int Strsafe_insert(/* char * */);
307 char *Strsafe_find(/* char * */);
309 /* Routines for handling symbols of the grammar */
311 struct symbol
*Symbol_new();
312 int Symbolcmpp(/* struct symbol **, struct symbol ** */);
313 void Symbol_init(/* void */);
314 int Symbol_insert(/* struct symbol *, char * */);
315 struct symbol
*Symbol_find(/* char * */);
316 struct symbol
*Symbol_Nth(/* int */);
317 int Symbol_count(/* */);
318 struct symbol
**Symbol_arrayof(/* */);
320 /* Routines to manage the state table */
322 int Configcmp(/* struct config *, struct config * */);
323 struct state
*State_new();
324 void State_init(/* void */);
325 int State_insert(/* struct state *, struct config * */);
326 struct state
*State_find(/* struct config * */);
327 struct state
**State_arrayof(/* */);
329 /* Routines used for efficiency in Configlist_add */
331 void Configtable_init(/* void */);
332 int Configtable_insert(/* struct config * */);
333 struct config
*Configtable_find(/* struct config * */);
334 void Configtable_clear(/* int(*)(struct config *) */);
335 /****************** From the file "action.c" *******************************/
337 ** Routines processing parser actions in the LEMON parser generator.
340 /* Allocate a new parser action */
341 static struct action
*Action_new(void){
342 static struct action
*freelist
= 0;
348 freelist
= (struct action
*)calloc(amt
, sizeof(struct action
));
350 fprintf(stderr
,"Unable to allocate memory for a new parser action.");
353 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
354 freelist
[amt
-1].next
= 0;
357 freelist
= freelist
->next
;
361 /* Compare two actions for sorting purposes. Return negative, zero, or
362 ** positive if the first action is less than, equal to, or greater than
365 static int actioncmp(
370 rc
= ap1
->sp
->index
- ap2
->sp
->index
;
372 rc
= (int)ap1
->type
- (int)ap2
->type
;
374 if( rc
==0 && ap1
->type
==REDUCE
){
375 rc
= ap1
->x
.rp
->index
- ap2
->x
.rp
->index
;
380 /* Sort parser actions */
381 static struct action
*Action_sort(
384 ap
= (struct action
*)msort((char *)ap
,(char **)&ap
->next
,
385 (int(*)(const char*,const char*))actioncmp
);
389 void Action_add(app
,type
,sp
,arg
)
402 new->x
.stp
= (struct state
*)arg
;
404 new->x
.rp
= (struct rule
*)arg
;
407 /********************** New code to implement the "acttab" module ***********/
409 ** This module implements routines use to construct the yy_action[] table.
413 ** The state of the yy_action table under construction is an instance of
414 ** the following structure
416 typedef struct acttab acttab
;
418 int nAction
; /* Number of used slots in aAction[] */
419 int nActionAlloc
; /* Slots allocated for aAction[] */
421 int lookahead
; /* Value of the lookahead token */
422 int action
; /* Action to take on the given lookahead */
423 } *aAction
, /* The yy_action[] table under construction */
424 *aLookahead
; /* A single new transaction set */
425 int mnLookahead
; /* Minimum aLookahead[].lookahead */
426 int mnAction
; /* Action associated with mnLookahead */
427 int mxLookahead
; /* Maximum aLookahead[].lookahead */
428 int nLookahead
; /* Used slots in aLookahead[] */
429 int nLookaheadAlloc
; /* Slots allocated in aLookahead[] */
432 /* Return the number of entries in the yy_action table */
433 #define acttab_size(X) ((X)->nAction)
435 /* The value for the N-th entry in yy_action */
436 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
438 /* The value for the N-th entry in yy_lookahead */
439 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
441 /* Free all memory associated with the given acttab */
442 void acttab_free(acttab
*p
){
444 free( p
->aLookahead
);
448 /* Allocate a new acttab structure */
449 acttab
*acttab_alloc(void){
450 acttab
*p
= calloc( 1, sizeof(*p
) );
452 fprintf(stderr
,"Unable to allocate memory for a new acttab.");
455 memset(p
, 0, sizeof(*p
));
459 /* Add a new action to the current transaction set
461 void acttab_action(acttab
*p
, int lookahead
, int action
){
462 if( p
->nLookahead
>=p
->nLookaheadAlloc
){
463 p
->nLookaheadAlloc
+= 25;
464 p
->aLookahead
= realloc( p
->aLookahead
,
465 sizeof(p
->aLookahead
[0])*p
->nLookaheadAlloc
);
466 if( p
->aLookahead
==0 ){
467 fprintf(stderr
,"malloc failed\n");
471 if( p
->nLookahead
==0 ){
472 p
->mxLookahead
= lookahead
;
473 p
->mnLookahead
= lookahead
;
474 p
->mnAction
= action
;
476 if( p
->mxLookahead
<lookahead
) p
->mxLookahead
= lookahead
;
477 if( p
->mnLookahead
>lookahead
){
478 p
->mnLookahead
= lookahead
;
479 p
->mnAction
= action
;
482 p
->aLookahead
[p
->nLookahead
].lookahead
= lookahead
;
483 p
->aLookahead
[p
->nLookahead
].action
= action
;
488 ** Add the transaction set built up with prior calls to acttab_action()
489 ** into the current action table. Then reset the transaction set back
490 ** to an empty set in preparation for a new round of acttab_action() calls.
492 ** Return the offset into the action table of the new transaction.
494 int acttab_insert(acttab
*p
){
496 assert( p
->nLookahead
>0 );
498 /* Make sure we have enough space to hold the expanded action table
499 ** in the worst case. The worst case occurs if the transaction set
500 ** must be appended to the current action table
502 n
= p
->mxLookahead
+ 1;
503 if( p
->nAction
+ n
>= p
->nActionAlloc
){
504 int oldAlloc
= p
->nActionAlloc
;
505 p
->nActionAlloc
= p
->nAction
+ n
+ p
->nActionAlloc
+ 20;
506 p
->aAction
= realloc( p
->aAction
,
507 sizeof(p
->aAction
[0])*p
->nActionAlloc
);
509 fprintf(stderr
,"malloc failed\n");
512 for(i
=oldAlloc
; i
<p
->nActionAlloc
; i
++){
513 p
->aAction
[i
].lookahead
= -1;
514 p
->aAction
[i
].action
= -1;
518 /* Scan the existing action table looking for an offset where we can
519 ** insert the current transaction set. Fall out of the loop when that
520 ** offset is found. In the worst case, we fall out of the loop when
521 ** i reaches p->nAction, which means we append the new transaction set.
523 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
525 for(i
=0; i
<p
->nAction
+p
->mnLookahead
; i
++){
526 if( p
->aAction
[i
].lookahead
<0 ){
527 for(j
=0; j
<p
->nLookahead
; j
++){
528 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
530 if( p
->aAction
[k
].lookahead
>=0 ) break;
532 if( j
<p
->nLookahead
) continue;
533 for(j
=0; j
<p
->nAction
; j
++){
534 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) break;
537 break; /* Fits in empty slots */
539 }else if( p
->aAction
[i
].lookahead
==p
->mnLookahead
){
540 if( p
->aAction
[i
].action
!=p
->mnAction
) continue;
541 for(j
=0; j
<p
->nLookahead
; j
++){
542 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
543 if( k
<0 || k
>=p
->nAction
) break;
544 if( p
->aLookahead
[j
].lookahead
!=p
->aAction
[k
].lookahead
) break;
545 if( p
->aLookahead
[j
].action
!=p
->aAction
[k
].action
) break;
547 if( j
<p
->nLookahead
) continue;
549 for(j
=0; j
<p
->nAction
; j
++){
550 if( p
->aAction
[j
].lookahead
<0 ) continue;
551 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) n
++;
553 if( n
==p
->nLookahead
){
554 break; /* Same as a prior transaction set */
558 /* Insert transaction set at index i. */
559 for(j
=0; j
<p
->nLookahead
; j
++){
560 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
561 p
->aAction
[k
] = p
->aLookahead
[j
];
562 if( k
>=p
->nAction
) p
->nAction
= k
+1;
566 /* Return the offset that is added to the lookahead in order to get the
567 ** index into yy_action of the action */
568 return i
- p
->mnLookahead
;
571 /********************** From the file "build.c" *****************************/
573 ** Routines to construction the finite state machine for the LEMON
577 /* Find a precedence symbol of every rule in the grammar.
579 ** Those rules which have a precedence symbol coded in the input
580 ** grammar using the "[symbol]" construct will already have the
581 ** rp->precsym field filled. Other rules take as their precedence
582 ** symbol the first RHS symbol with a defined precedence. If there
583 ** are not RHS symbols with a defined precedence, the precedence
584 ** symbol field is left blank.
586 void FindRulePrecedences(xp
)
590 for(rp
=xp
->rule
; rp
; rp
=rp
->next
){
591 if( rp
->precsym
==0 ){
593 for(i
=0; i
<rp
->nrhs
&& rp
->precsym
==0; i
++){
594 struct symbol
*sp
= rp
->rhs
[i
];
595 if( sp
->type
==MULTITERMINAL
){
596 for(j
=0; j
<sp
->nsubsym
; j
++){
597 if( sp
->subsym
[j
]->prec
>=0 ){
598 rp
->precsym
= sp
->subsym
[j
];
602 }else if( sp
->prec
>=0 ){
603 rp
->precsym
= rp
->rhs
[i
];
611 /* Find all nonterminals which will generate the empty string.
612 ** Then go back and compute the first sets of every nonterminal.
613 ** The first set is the set of all terminal symbols which can begin
614 ** a string generated by that nonterminal.
616 void FindFirstSets(lemp
)
623 for(i
=0; i
<lemp
->nsymbol
; i
++){
624 lemp
->symbols
[i
]->lambda
= LEMON_FALSE
;
626 for(i
=lemp
->nterminal
; i
<lemp
->nsymbol
; i
++){
627 lemp
->symbols
[i
]->firstset
= SetNew();
630 /* First compute all lambdas */
633 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
634 if( rp
->lhs
->lambda
) continue;
635 for(i
=0; i
<rp
->nrhs
; i
++){
636 struct symbol
*sp
= rp
->rhs
[i
];
637 if( sp
->type
!=TERMINAL
|| sp
->lambda
==LEMON_FALSE
) break;
640 rp
->lhs
->lambda
= LEMON_TRUE
;
646 /* Now compute all first sets */
648 struct symbol
*s1
, *s2
;
650 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
652 for(i
=0; i
<rp
->nrhs
; i
++){
654 if( s2
->type
==TERMINAL
){
655 progress
+= SetAdd(s1
->firstset
,s2
->index
);
657 }else if( s2
->type
==MULTITERMINAL
){
658 for(j
=0; j
<s2
->nsubsym
; j
++){
659 progress
+= SetAdd(s1
->firstset
,s2
->subsym
[j
]->index
);
663 if( s1
->lambda
==LEMON_FALSE
) break;
665 progress
+= SetUnion(s1
->firstset
,s2
->firstset
);
666 if( s2
->lambda
==LEMON_FALSE
) break;
674 /* Compute all LR(0) states for the grammar. Links
675 ** are added to between some states so that the LR(1) follow sets
676 ** can be computed later.
678 PRIVATE
struct state
*getstate(/* struct lemon * */); /* forward reference */
679 void FindStates(lemp
)
687 /* Find the start symbol */
689 sp
= Symbol_find(lemp
->start
);
691 ErrorMsg(lemp
->filename
,0,
692 "The specified start symbol \"%s\" is not \
693 in a nonterminal of the grammar. \"%s\" will be used as the start \
694 symbol instead.",lemp
->start
,lemp
->rule
->lhs
->name
);
696 sp
= lemp
->rule
->lhs
;
699 sp
= lemp
->rule
->lhs
;
702 /* Make sure the start symbol doesn't occur on the right-hand side of
703 ** any rule. Report an error if it does. (YACC would generate a new
704 ** start symbol in this case.) */
705 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
707 for(i
=0; i
<rp
->nrhs
; i
++){
708 if( rp
->rhs
[i
]==sp
){ /* FIX ME: Deal with multiterminals */
709 ErrorMsg(lemp
->filename
,0,
710 "The start symbol \"%s\" occurs on the \
711 right-hand side of a rule. This will result in a parser which \
712 does not work properly.",sp
->name
);
718 /* The basis configuration set for the first state
719 ** is all rules which have the start symbol as their
721 for(rp
=sp
->rule
; rp
; rp
=rp
->nextlhs
){
722 struct config
*newcfp
;
724 newcfp
= Configlist_addbasis(rp
,0);
725 SetAdd(newcfp
->fws
,0);
728 /* Compute the first state. All other states will be
729 ** computed automatically during the computation of the first one.
730 ** The returned pointer to the first state is not used. */
731 (void)getstate(lemp
);
735 /* Return a pointer to a state which is described by the configuration
736 ** list which has been built from calls to Configlist_add.
738 PRIVATE
void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
739 PRIVATE
struct state
*getstate(lemp
)
742 struct config
*cfp
, *bp
;
745 /* Extract the sorted basis of the new state. The basis was constructed
746 ** by prior calls to "Configlist_addbasis()". */
747 Configlist_sortbasis();
748 bp
= Configlist_basis();
750 /* Get a state with the same basis */
751 stp
= State_find(bp
);
753 /* A state with the same basis already exists! Copy all the follow-set
754 ** propagation links from the state under construction into the
755 ** preexisting state, then return a pointer to the preexisting state */
756 struct config
*x
, *y
;
757 for(x
=bp
, y
=stp
->bp
; x
&& y
; x
=x
->bp
, y
=y
->bp
){
758 Plink_copy(&y
->bplp
,x
->bplp
);
759 Plink_delete(x
->fplp
);
760 x
->fplp
= x
->bplp
= 0;
762 cfp
= Configlist_return();
765 /* This really is a new state. Construct all the details */
766 Configlist_closure(lemp
); /* Compute the configuration closure */
767 Configlist_sort(); /* Sort the configuration closure */
768 cfp
= Configlist_return(); /* Get a pointer to the config list */
769 stp
= State_new(); /* A new state structure */
771 stp
->bp
= bp
; /* Remember the configuration basis */
772 stp
->cfp
= cfp
; /* Remember the configuration closure */
773 stp
->statenum
= lemp
->nstate
++; /* Every state gets a sequence number */
774 stp
->ap
= 0; /* No actions, yet. */
775 State_insert(stp
,stp
->bp
); /* Add to the state table */
776 buildshifts(lemp
,stp
); /* Recursively compute successor states */
782 ** Return true if two symbols are the same.
790 if( a
->type
!=MULTITERMINAL
) return 0;
791 if( b
->type
!=MULTITERMINAL
) return 0;
792 if( a
->nsubsym
!=b
->nsubsym
) return 0;
793 for(i
=0; i
<a
->nsubsym
; i
++){
794 if( a
->subsym
[i
]!=b
->subsym
[i
] ) return 0;
799 /* Construct all successor states to the given state. A "successor"
800 ** state is any state which can be reached by a shift action.
802 PRIVATE
void buildshifts(lemp
,stp
)
804 struct state
*stp
; /* The state from which successors are computed */
806 struct config
*cfp
; /* For looping thru the config closure of "stp" */
807 struct config
*bcfp
; /* For the inner loop on config closure of "stp" */
808 struct config
*new; /* */
809 struct symbol
*sp
; /* Symbol following the dot in configuration "cfp" */
810 struct symbol
*bsp
; /* Symbol following the dot in configuration "bcfp" */
811 struct state
*newstp
; /* A pointer to a successor state */
813 /* Each configuration becomes complete after it contibutes to a successor
814 ** state. Initially, all configurations are incomplete */
815 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
) cfp
->status
= INCOMPLETE
;
817 /* Loop through all configurations of the state "stp" */
818 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
819 if( cfp
->status
==COMPLETE
) continue; /* Already used by inner loop */
820 if( cfp
->dot
>=cfp
->rp
->nrhs
) continue; /* Can't shift this config */
821 Configlist_reset(); /* Reset the new config set */
822 sp
= cfp
->rp
->rhs
[cfp
->dot
]; /* Symbol after the dot */
824 /* For every configuration in the state "stp" which has the symbol "sp"
825 ** following its dot, add the same configuration to the basis set under
826 ** construction but with the dot shifted one symbol to the right. */
827 for(bcfp
=cfp
; bcfp
; bcfp
=bcfp
->next
){
828 if( bcfp
->status
==COMPLETE
) continue; /* Already used */
829 if( bcfp
->dot
>=bcfp
->rp
->nrhs
) continue; /* Can't shift this one */
830 bsp
= bcfp
->rp
->rhs
[bcfp
->dot
]; /* Get symbol after dot */
831 if( !same_symbol(bsp
,sp
) ) continue; /* Must be same as for "cfp" */
832 bcfp
->status
= COMPLETE
; /* Mark this config as used */
833 new = Configlist_addbasis(bcfp
->rp
,bcfp
->dot
+1);
834 Plink_add(&new->bplp
,bcfp
);
837 /* Get a pointer to the state described by the basis configuration set
838 ** constructed in the preceding loop */
839 newstp
= getstate(lemp
);
841 /* The state "newstp" is reached from the state "stp" by a shift action
842 ** on the symbol "sp" */
843 if( sp
->type
==MULTITERMINAL
){
845 for(i
=0; i
<sp
->nsubsym
; i
++){
846 Action_add(&stp
->ap
,SHIFT
,sp
->subsym
[i
],(char*)newstp
);
849 Action_add(&stp
->ap
,SHIFT
,sp
,(char *)newstp
);
855 ** Construct the propagation links
861 struct config
*cfp
, *other
;
865 /* Housekeeping detail:
866 ** Add to every propagate link a pointer back to the state to
867 ** which the link is attached. */
868 for(i
=0; i
<lemp
->nstate
; i
++){
869 stp
= lemp
->sorted
[i
];
870 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
875 /* Convert all backlinks into forward links. Only the forward
876 ** links are used in the follow-set computation. */
877 for(i
=0; i
<lemp
->nstate
; i
++){
878 stp
= lemp
->sorted
[i
];
879 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
880 for(plp
=cfp
->bplp
; plp
; plp
=plp
->next
){
882 Plink_add(&other
->fplp
,cfp
);
888 /* Compute all followsets.
890 ** A followset is the set of all symbols which can come immediately
891 ** after a configuration.
893 void FindFollowSets(lemp
)
902 for(i
=0; i
<lemp
->nstate
; i
++){
903 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
904 cfp
->status
= INCOMPLETE
;
910 for(i
=0; i
<lemp
->nstate
; i
++){
911 for(cfp
=lemp
->sorted
[i
]->cfp
; cfp
; cfp
=cfp
->next
){
912 if( cfp
->status
==COMPLETE
) continue;
913 for(plp
=cfp
->fplp
; plp
; plp
=plp
->next
){
914 change
= SetUnion(plp
->cfp
->fws
,cfp
->fws
);
916 plp
->cfp
->status
= INCOMPLETE
;
920 cfp
->status
= COMPLETE
;
926 static int resolve_conflict();
928 /* Compute the reduce actions, and resolve conflicts.
930 void FindActions(lemp
)
939 /* Add all of the reduce actions
940 ** A reduce action is added for each element of the followset of
941 ** a configuration which has its dot at the extreme right.
943 for(i
=0; i
<lemp
->nstate
; i
++){ /* Loop over all states */
944 stp
= lemp
->sorted
[i
];
945 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){ /* Loop over all configurations */
946 if( cfp
->rp
->nrhs
==cfp
->dot
){ /* Is dot at extreme right? */
947 for(j
=0; j
<lemp
->nterminal
; j
++){
948 if( SetFind(cfp
->fws
,j
) ){
949 /* Add a reduce action to the state "stp" which will reduce by the
950 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
951 Action_add(&stp
->ap
,REDUCE
,lemp
->symbols
[j
],(char *)cfp
->rp
);
958 /* Add the accepting token */
960 sp
= Symbol_find(lemp
->start
);
961 if( sp
==0 ) sp
= lemp
->rule
->lhs
;
963 sp
= lemp
->rule
->lhs
;
965 /* Add to the first state (which is always the starting state of the
966 ** finite state machine) an action to ACCEPT if the lookahead is the
967 ** start nonterminal. */
968 Action_add(&lemp
->sorted
[0]->ap
,ACCEPT
,sp
,0);
970 /* Resolve conflicts */
971 for(i
=0; i
<lemp
->nstate
; i
++){
972 struct action
*ap
, *nap
;
974 stp
= lemp
->sorted
[i
];
975 /* assert( stp->ap ); */
976 stp
->ap
= Action_sort(stp
->ap
);
977 for(ap
=stp
->ap
; ap
&& ap
->next
; ap
=ap
->next
){
978 for(nap
=ap
->next
; nap
&& nap
->sp
==ap
->sp
; nap
=nap
->next
){
979 /* The two actions "ap" and "nap" have the same lookahead.
980 ** Figure out which one should be used */
981 lemp
->nconflict
+= resolve_conflict(ap
,nap
,lemp
->errsym
);
986 /* Report an error for each rule that can never be reduced. */
987 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->canReduce
= LEMON_FALSE
;
988 for(i
=0; i
<lemp
->nstate
; i
++){
990 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
991 if( ap
->type
==REDUCE
) ap
->x
.rp
->canReduce
= LEMON_TRUE
;
994 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
995 if( rp
->canReduce
) continue;
996 ErrorMsg(lemp
->filename
,rp
->ruleline
,"This rule can not be reduced.\n");
1001 /* Resolve a conflict between the two given actions. If the
1002 ** conflict can't be resolve, return non-zero.
1005 ** To resolve a conflict, first look to see if either action
1006 ** is on an error rule. In that case, take the action which
1007 ** is not associated with the error rule. If neither or both
1008 ** actions are associated with an error rule, then try to
1009 ** use precedence to resolve the conflict.
1011 ** If either action is a SHIFT, then it must be apx. This
1012 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1014 static int resolve_conflict(apx
,apy
,errsym
)
1017 struct symbol
*errsym
; /* The error symbol (if defined. NULL otherwise) */
1019 struct symbol
*spx
, *spy
;
1021 assert( apx
->sp
==apy
->sp
); /* Otherwise there would be no conflict */
1022 if( apx
->type
==SHIFT
&& apy
->type
==SHIFT
){
1023 apy
->type
= SSCONFLICT
;
1026 if( apx
->type
==SHIFT
&& apy
->type
==REDUCE
){
1028 spy
= apy
->x
.rp
->precsym
;
1029 if( spy
==0 || spx
->prec
<0 || spy
->prec
<0 ){
1030 /* Not enough precedence information. */
1031 apy
->type
= SRCONFLICT
;
1033 }else if( spx
->prec
>spy
->prec
){ /* Lower precedence wins */
1034 apy
->type
= RD_RESOLVED
;
1035 }else if( spx
->prec
<spy
->prec
){
1036 apx
->type
= SH_RESOLVED
;
1037 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==RIGHT
){ /* Use operator */
1038 apy
->type
= RD_RESOLVED
; /* associativity */
1039 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==LEFT
){ /* to break tie */
1040 apx
->type
= SH_RESOLVED
;
1042 assert( spx
->prec
==spy
->prec
&& spx
->assoc
==NONE
);
1043 apy
->type
= SRCONFLICT
;
1046 }else if( apx
->type
==REDUCE
&& apy
->type
==REDUCE
){
1047 spx
= apx
->x
.rp
->precsym
;
1048 spy
= apy
->x
.rp
->precsym
;
1049 if( spx
==0 || spy
==0 || spx
->prec
<0 ||
1050 spy
->prec
<0 || spx
->prec
==spy
->prec
){
1051 apy
->type
= RRCONFLICT
;
1053 }else if( spx
->prec
>spy
->prec
){
1054 apy
->type
= RD_RESOLVED
;
1055 }else if( spx
->prec
<spy
->prec
){
1056 apx
->type
= RD_RESOLVED
;
1060 apx
->type
==SH_RESOLVED
||
1061 apx
->type
==RD_RESOLVED
||
1062 apx
->type
==SSCONFLICT
||
1063 apx
->type
==SRCONFLICT
||
1064 apx
->type
==RRCONFLICT
||
1065 apy
->type
==SH_RESOLVED
||
1066 apy
->type
==RD_RESOLVED
||
1067 apy
->type
==SSCONFLICT
||
1068 apy
->type
==SRCONFLICT
||
1069 apy
->type
==RRCONFLICT
1071 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1072 ** REDUCEs on the list. If we reach this point it must be because
1073 ** the parser conflict had already been resolved. */
1077 /********************* From the file "configlist.c" *************************/
1079 ** Routines to processing a configuration list and building a state
1080 ** in the LEMON parser generator.
1083 static struct config
*freelist
= 0; /* List of free configurations */
1084 static struct config
*current
= 0; /* Top of list of configurations */
1085 static struct config
**currentend
= 0; /* Last on list of configs */
1086 static struct config
*basis
= 0; /* Top of list of basis configs */
1087 static struct config
**basisend
= 0; /* End of list of basis configs */
1089 /* Return a pointer to a new configuration */
1090 PRIVATE
struct config
*newconfig(){
1095 freelist
= (struct config
*)calloc( amt
, sizeof(struct config
) );
1097 fprintf(stderr
,"Unable to allocate memory for a new configuration.");
1100 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
1101 freelist
[amt
-1].next
= 0;
1104 freelist
= freelist
->next
;
1108 /* The configuration "old" is no longer used */
1109 PRIVATE
void deleteconfig(old
)
1112 old
->next
= freelist
;
1116 /* Initialized the configuration list builder */
1117 void Configlist_init(){
1119 currentend
= ¤t
;
1126 /* Initialized the configuration list builder */
1127 void Configlist_reset(){
1129 currentend
= ¤t
;
1132 Configtable_clear(0);
1136 /* Add another configuration to the configuration list */
1137 struct config
*Configlist_add(rp
,dot
)
1138 struct rule
*rp
; /* The rule */
1139 int dot
; /* Index into the RHS of the rule where the dot goes */
1141 struct config
*cfp
, model
;
1143 assert( currentend
!=0 );
1146 cfp
= Configtable_find(&model
);
1151 cfp
->fws
= SetNew();
1153 cfp
->fplp
= cfp
->bplp
= 0;
1157 currentend
= &cfp
->next
;
1158 Configtable_insert(cfp
);
1163 /* Add a basis configuration to the configuration list */
1164 struct config
*Configlist_addbasis(rp
,dot
)
1168 struct config
*cfp
, model
;
1170 assert( basisend
!=0 );
1171 assert( currentend
!=0 );
1174 cfp
= Configtable_find(&model
);
1179 cfp
->fws
= SetNew();
1181 cfp
->fplp
= cfp
->bplp
= 0;
1185 currentend
= &cfp
->next
;
1187 basisend
= &cfp
->bp
;
1188 Configtable_insert(cfp
);
1193 /* Compute the closure of the configuration list */
1194 void Configlist_closure(lemp
)
1197 struct config
*cfp
, *newcfp
;
1198 struct rule
*rp
, *newrp
;
1199 struct symbol
*sp
, *xsp
;
1202 assert( currentend
!=0 );
1203 for(cfp
=current
; cfp
; cfp
=cfp
->next
){
1206 if( dot
>=rp
->nrhs
) continue;
1208 if( sp
->type
==NONTERMINAL
){
1209 if( sp
->rule
==0 && sp
!=lemp
->errsym
){
1210 ErrorMsg(lemp
->filename
,rp
->line
,"Nonterminal \"%s\" has no rules.",
1214 for(newrp
=sp
->rule
; newrp
; newrp
=newrp
->nextlhs
){
1215 newcfp
= Configlist_add(newrp
,0);
1216 for(i
=dot
+1; i
<rp
->nrhs
; i
++){
1218 if( xsp
->type
==TERMINAL
){
1219 SetAdd(newcfp
->fws
,xsp
->index
);
1221 }else if( xsp
->type
==MULTITERMINAL
){
1223 for(k
=0; k
<xsp
->nsubsym
; k
++){
1224 SetAdd(newcfp
->fws
, xsp
->subsym
[k
]->index
);
1228 SetUnion(newcfp
->fws
,xsp
->firstset
);
1229 if( xsp
->lambda
==LEMON_FALSE
) break;
1232 if( i
==rp
->nrhs
) Plink_add(&cfp
->fplp
,newcfp
);
1239 /* Sort the configuration list */
1240 void Configlist_sort(){
1241 current
= (struct config
*)msort((char *)current
,(char **)&(current
->next
),Configcmp
);
1246 /* Sort the basis configuration list */
1247 void Configlist_sortbasis(){
1248 basis
= (struct config
*)msort((char *)current
,(char **)&(current
->bp
),Configcmp
);
1253 /* Return a pointer to the head of the configuration list and
1254 ** reset the list */
1255 struct config
*Configlist_return(){
1263 /* Return a pointer to the head of the configuration list and
1264 ** reset the list */
1265 struct config
*Configlist_basis(){
1273 /* Free all elements of the given configuration list */
1274 void Configlist_eat(cfp
)
1277 struct config
*nextcfp
;
1278 for(; cfp
; cfp
=nextcfp
){
1279 nextcfp
= cfp
->next
;
1280 assert( cfp
->fplp
==0 );
1281 assert( cfp
->bplp
==0 );
1282 if( cfp
->fws
) SetFree(cfp
->fws
);
1287 /***************** From the file "error.c" *********************************/
1289 ** Code for printing error message.
1292 /* Find a good place to break "msg" so that its length is at least "min"
1293 ** but no more than "max". Make the point as close to max as possible.
1295 static int findbreak(msg
,min
,max
)
1302 for(i
=spot
=min
; i
<=max
; i
++){
1304 if( c
=='\t' ) msg
[i
] = ' ';
1305 if( c
=='\n' ){ msg
[i
] = ' '; spot
= i
; break; }
1306 if( c
==0 ){ spot
= i
; break; }
1307 if( c
=='-' && i
<max
-1 ) spot
= i
+1;
1308 if( c
==' ' ) spot
= i
;
1314 ** The error message is split across multiple lines if necessary. The
1315 ** splits occur at a space, if there is a space available near the end
1318 #define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1319 #define LINEWIDTH 79 /* Max width of any output line */
1320 #define PREFIXLIMIT 30 /* Max width of the prefix on each line */
1321 void ErrorMsg(const char *filename
, int lineno
, const char *format
, ...){
1322 char errmsg
[ERRMSGSIZE
];
1323 char prefix
[PREFIXLIMIT
+10];
1328 int end
, restart
, base
;
1330 va_start(ap
, format
);
1331 /* Prepare a prefix to be prepended to every output line */
1333 sprintf(prefix
,"%.*s:%d: ",PREFIXLIMIT
-10,filename
,lineno
);
1335 sprintf(prefix
,"%.*s: ",PREFIXLIMIT
-10,filename
);
1337 prefixsize
= strlen(prefix
);
1338 availablewidth
= LINEWIDTH
- prefixsize
;
1340 /* Generate the error message */
1341 vsprintf(errmsg
,format
,ap
);
1343 errmsgsize
= strlen(errmsg
);
1344 /* Remove trailing '\n's from the error message. */
1345 while( errmsgsize
>0 && errmsg
[errmsgsize
-1]=='\n' ){
1346 errmsg
[--errmsgsize
] = 0;
1349 /* Print the error message */
1351 while( errmsg
[base
]!=0 ){
1352 end
= restart
= findbreak(&errmsg
[base
],0,availablewidth
);
1354 while( errmsg
[restart
]==' ' ) restart
++;
1355 fprintf(stdout
,"%s%.*s\n",prefix
,end
,&errmsg
[base
]);
1359 /**************** From the file "main.c" ************************************/
1361 ** Main program file for the LEMON parser generator.
1364 /* Report an out-of-memory condition and abort. This function
1365 ** is used mostly by the "MemoryCheck" macro in struct.h
1367 void memory_error(){
1368 fprintf(stderr
,"Out of memory. Aborting...\n");
1372 static int nDefine
= 0; /* Number of -D options on the command line */
1373 static char **azDefine
= 0; /* Name of the -D macros */
1375 /* This routine is called with the argument to each -D command-line option.
1376 ** Add the macro defined to the azDefine array.
1378 static void handle_D_option(char *z
){
1381 azDefine
= realloc(azDefine
, sizeof(azDefine
[0])*nDefine
);
1383 fprintf(stderr
,"out of memory\n");
1386 paz
= &azDefine
[nDefine
-1];
1387 *paz
= malloc( strlen(z
)+1 );
1389 fprintf(stderr
,"out of memory\n");
1393 for(z
=*paz
; *z
&& *z
!='='; z
++){}
1398 /* The main program. Parse the command line and do it... */
1399 int lemon_main(int argc
,char **argv
)
1401 static int version
= 0;
1402 static int rpflag
= 0;
1403 static int basisflag
= 0;
1404 static int compress
= 0;
1405 static int quiet
= 0;
1406 static int statistics
= 0;
1407 static int mhflag
= 0;
1408 static struct s_options options
[] = {
1409 {OPT_FLAG
, "b", (char*)&basisflag
, "Print only the basis in report."},
1410 {OPT_FLAG
, "c", (char*)&compress
, "Don't compress the action table."},
1411 {OPT_FSTR
, "D", (char*)handle_D_option
, "Define an %ifdef macro."},
1412 {OPT_FLAG
, "g", (char*)&rpflag
, "Print grammar without actions."},
1413 {OPT_FLAG
, "m", (char*)&mhflag
, "Output a makeheaders compatible file"},
1414 {OPT_FLAG
, "q", (char*)&quiet
, "(Quiet) Don't print the report file."},
1415 {OPT_FLAG
, "s", (char*)&statistics
,
1416 "Print parser stats to standard output."},
1417 {OPT_FLAG
, "x", (char*)&version
, "Print the version number."},
1423 OptInit(argv
,options
,stderr
);
1425 printf("Lemon version 1.0\n");
1428 if( OptNArgs()!=1 ){
1429 fprintf(stderr
,"Exactly one filename argument is required.\n");
1432 memset(&lem
, 0, sizeof(lem
));
1435 /* Initialize the machine */
1439 lem
.argv0
= argv
[0];
1440 lem
.filename
= OptArg(0);
1441 lem
.basisflag
= basisflag
;
1443 lem
.errsym
= Symbol_new("error");
1444 lem
.errsym
->useCnt
= 0;
1446 /* Parse the input file */
1448 if( lem
.errorcnt
) exit(lem
.errorcnt
);
1450 fprintf(stderr
,"Empty grammar.\n");
1454 /* Count and index the symbols of the grammar */
1455 lem
.nsymbol
= Symbol_count();
1456 Symbol_new("{default}");
1457 lem
.symbols
= Symbol_arrayof();
1458 for(i
=0; i
<=lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1459 qsort(lem
.symbols
,lem
.nsymbol
+1,sizeof(struct symbol
*),
1460 (int(*)())Symbolcmpp
);
1461 for(i
=0; i
<=lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1462 for(i
=1; isupper(lem
.symbols
[i
]->name
[0]); i
++);
1465 /* Generate a reprint of the grammar, if requested on the command line */
1469 /* Initialize the size for all follow and first sets */
1470 SetSize(lem
.nterminal
+1);
1472 /* Find the precedence for every production rule (that has one) */
1473 FindRulePrecedences(&lem
);
1475 /* Compute the lambda-nonterminals and the first-sets for every
1477 FindFirstSets(&lem
);
1479 /* Compute all LR(0) states. Also record follow-set propagation
1480 ** links so that the follow-set can be computed later */
1483 lem
.sorted
= State_arrayof();
1485 /* Tie up loose ends on the propagation links */
1488 /* Compute the follow set of every reducible configuration */
1489 FindFollowSets(&lem
);
1491 /* Compute the action tables */
1494 /* Compress the action tables */
1495 if( compress
==0 ) CompressTables(&lem
);
1497 /* Reorder and renumber the states so that states with fewer choices
1498 ** occur at the end. */
1501 /* Generate a report of the parser generated. (the "y.output" file) */
1502 if( !quiet
) ReportOutput(&lem
);
1504 /* Generate the source code for the parser */
1505 ReportTable(&lem
, mhflag
);
1507 /* Produce a header file for use by the scanner. (This step is
1508 ** omitted if the "-m" option is used because makeheaders will
1509 ** generate the file for us.) */
1510 if( !mhflag
) ReportHeader(&lem
);
1513 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1514 lem
.nterminal
, lem
.nsymbol
- lem
.nterminal
, lem
.nrule
);
1515 printf(" %d states, %d parser table entries, %d conflicts\n",
1516 lem
.nstate
, lem
.tablesize
, lem
.nconflict
);
1518 exit(lem
.errorcnt
+ lem
.nconflict
);
1519 return (lem
.errorcnt
+ lem
.nconflict
);
1521 /******************** From the file "msort.c" *******************************/
1523 ** A generic merge-sort program.
1526 ** Let "ptr" be a pointer to some structure which is at the head of
1527 ** a null-terminated list. Then to sort the list call:
1529 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1531 ** In the above, "cmpfnc" is a pointer to a function which compares
1532 ** two instances of the structure and returns an integer, as in
1533 ** strcmp. The second argument is a pointer to the pointer to the
1534 ** second element of the linked list. This address is used to compute
1535 ** the offset to the "next" field within the structure. The offset to
1536 ** the "next" field must be constant for all structures in the list.
1538 ** The function returns a new pointer which is the head of the list
1546 ** Return a pointer to the next structure in the linked list.
1548 #define NEXT(A) (*(char**)(((unsigned long)A)+offset))
1552 ** a: A sorted, null-terminated linked list. (May be null).
1553 ** b: A sorted, null-terminated linked list. (May be null).
1554 ** cmp: A pointer to the comparison function.
1555 ** offset: Offset in the structure to the "next" field.
1558 ** A pointer to the head of a sorted list containing the elements
1562 ** The "next" pointers for elements in the lists a and b are
1568 int (*cmp
)(const char*,const char*),
1578 if( (*cmp
)(a
,b
)<0 ){
1587 if( (*cmp
)(a
,b
)<0 ){
1597 if( a
) NEXT(ptr
) = a
;
1605 ** list: Pointer to a singly-linked list of structures.
1606 ** next: Pointer to pointer to the second element of the list.
1607 ** cmp: A comparison function.
1610 ** A pointer to the head of a sorted list containing the elements
1611 ** orginally in list.
1614 ** The "next" pointers for elements in list are changed.
1620 int (*cmp
)(const char*,const char*)
1622 unsigned long offset
;
1624 char *set
[LISTSIZE
];
1626 offset
= (unsigned long)next
- (unsigned long)list
;
1627 for(i
=0; i
<LISTSIZE
; i
++) set
[i
] = 0;
1632 for(i
=0; i
<LISTSIZE
-1 && set
[i
]!=0; i
++){
1633 ep
= merge(ep
,set
[i
],cmp
,offset
);
1639 for(i
=0; i
<LISTSIZE
; i
++) if( set
[i
] ) ep
= merge(ep
,set
[i
],cmp
,offset
);
1642 /************************ From the file "option.c" **************************/
1644 static struct s_options
*op
;
1645 static FILE *errstream
;
1647 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1650 ** Print the command line with a carrot pointing to the k-th character
1651 ** of the n-th field.
1653 static void errline(n
,k
,err
)
1659 if( argv
[0] ) fprintf(err
,"%s",argv
[0]);
1660 spcnt
= strlen(argv
[0]) + 1;
1661 for(i
=1; i
<n
&& argv
[i
]; i
++){
1662 fprintf(err
," %s",argv
[i
]);
1663 spcnt
+= strlen(argv
[i
])+1;
1666 for(; argv
[i
]; i
++) fprintf(err
," %s",argv
[i
]);
1668 fprintf(err
,"\n%*s^-- here\n",spcnt
,"");
1670 fprintf(err
,"\n%*shere --^\n",spcnt
-7,"");
1675 ** Return the index of the N-th non-switch argument. Return -1
1676 ** if N is out of range.
1678 static int argindex(n
)
1683 if( argv
!=0 && *argv
!=0 ){
1684 for(i
=1; argv
[i
]; i
++){
1685 if( dashdash
|| !ISOPT(argv
[i
]) ){
1686 if( n
==0 ) return i
;
1689 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
1695 static char emsg
[] = "Command line syntax error: ";
1698 ** Process a flag command line argument.
1700 static int handleflags(i
,err
)
1707 for(j
=0; op
[j
].label
; j
++){
1708 if( strncmp(&argv
[i
][1],op
[j
].label
,strlen(op
[j
].label
))==0 ) break;
1710 v
= argv
[i
][0]=='-' ? 1 : 0;
1711 if( op
[j
].label
==0 ){
1713 fprintf(err
,"%sundefined option.\n",emsg
);
1717 }else if( op
[j
].type
==OPT_FLAG
){
1718 *((int*)op
[j
].arg
) = v
;
1719 }else if( op
[j
].type
==OPT_FFLAG
){
1720 (*(void(*)())(op
[j
].arg
))(v
);
1721 }else if( op
[j
].type
==OPT_FSTR
){
1722 (*(void(*)())(op
[j
].arg
))(&argv
[i
][2]);
1725 fprintf(err
,"%smissing argument on switch.\n",emsg
);
1734 ** Process a command line switch which has an argument.
1736 static int handleswitch(i
,err
)
1746 cp
= strchr(argv
[i
],'=');
1749 for(j
=0; op
[j
].label
; j
++){
1750 if( strcmp(argv
[i
],op
[j
].label
)==0 ) break;
1753 if( op
[j
].label
==0 ){
1755 fprintf(err
,"%sundefined option.\n",emsg
);
1761 switch( op
[j
].type
){
1765 fprintf(err
,"%soption requires an argument.\n",emsg
);
1772 dv
= strtod(cp
,&end
);
1775 fprintf(err
,"%sillegal character in floating-point argument.\n",emsg
);
1776 errline(i
,((unsigned long)end
)-(unsigned long)argv
[i
],err
);
1783 lv
= strtol(cp
,&end
,0);
1786 fprintf(err
,"%sillegal character in integer argument.\n",emsg
);
1787 errline(i
,((unsigned long)end
)-(unsigned long)argv
[i
],err
);
1797 switch( op
[j
].type
){
1802 *(double*)(op
[j
].arg
) = dv
;
1805 (*(void(*)())(op
[j
].arg
))(dv
);
1808 *(int*)(op
[j
].arg
) = lv
;
1811 (*(void(*)())(op
[j
].arg
))((int)lv
);
1814 *(char**)(op
[j
].arg
) = sv
;
1817 (*(void(*)())(op
[j
].arg
))(sv
);
1824 int OptInit(a
,o
,err
)
1826 struct s_options
*o
;
1833 if( argv
&& *argv
&& op
){
1835 for(i
=1; argv
[i
]; i
++){
1836 if( argv
[i
][0]=='+' || argv
[i
][0]=='-' ){
1837 errcnt
+= handleflags(i
,err
);
1838 }else if( strchr(argv
[i
],'=') ){
1839 errcnt
+= handleswitch(i
,err
);
1844 fprintf(err
,"Valid command line options for \"%s\" are:\n",*a
);
1855 if( argv
!=0 && argv
[0]!=0 ){
1856 for(i
=1; argv
[i
]; i
++){
1857 if( dashdash
|| !ISOPT(argv
[i
]) ) cnt
++;
1858 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
1869 return i
>=0 ? argv
[i
] : 0;
1877 if( i
>=0 ) errline(i
,0,errstream
);
1884 for(i
=0; op
[i
].label
; i
++){
1885 len
= strlen(op
[i
].label
) + 1;
1886 switch( op
[i
].type
){
1892 len
+= 9; /* length of "<integer>" */
1896 len
+= 6; /* length of "<real>" */
1900 len
+= 8; /* length of "<string>" */
1903 if( len
>max
) max
= len
;
1905 for(i
=0; op
[i
].label
; i
++){
1906 switch( op
[i
].type
){
1909 fprintf(errstream
," -%-*s %s\n",max
,op
[i
].label
,op
[i
].message
);
1913 fprintf(errstream
," %s=<integer>%*s %s\n",op
[i
].label
,
1914 (int)(max
-strlen(op
[i
].label
)-9),"",op
[i
].message
);
1918 fprintf(errstream
," %s=<real>%*s %s\n",op
[i
].label
,
1919 (int)(max
-strlen(op
[i
].label
)-6),"",op
[i
].message
);
1923 fprintf(errstream
," %s=<string>%*s %s\n",op
[i
].label
,
1924 (int)(max
-strlen(op
[i
].label
)-8),"",op
[i
].message
);
1929 /*********************** From the file "parse.c" ****************************/
1931 ** Input file parser for the LEMON parser generator.
1934 /* The state of the parser */
1936 char *filename
; /* Name of the input file */
1937 int tokenlineno
; /* Linenumber at which current token starts */
1938 int errorcnt
; /* Number of errors so far */
1939 char *tokenstart
; /* Text of current token */
1940 struct lemon
*gp
; /* Global state vector */
1943 WAITING_FOR_DECL_OR_RULE
,
1944 WAITING_FOR_DECL_KEYWORD
,
1945 WAITING_FOR_DECL_ARG
,
1946 WAITING_FOR_PRECEDENCE_SYMBOL
,
1956 RESYNC_AFTER_RULE_ERROR
,
1957 RESYNC_AFTER_DECL_ERROR
,
1958 WAITING_FOR_DESTRUCTOR_SYMBOL
,
1959 WAITING_FOR_DATATYPE_SYMBOL
,
1960 WAITING_FOR_FALLBACK_ID
,
1961 WAITING_FOR_WILDCARD_ID
1962 } state
; /* The state of the parser */
1963 struct symbol
*fallback
; /* The fallback token */
1964 struct symbol
*lhs
; /* Left-hand side of current rule */
1965 char *lhsalias
; /* Alias for the LHS */
1966 int nrhs
; /* Number of right-hand side symbols seen */
1967 struct symbol
*rhs
[MAXRHS
]; /* RHS symbols */
1968 char *alias
[MAXRHS
]; /* Aliases for each RHS symbol (or NULL) */
1969 struct rule
*prevrule
; /* Previous rule parsed */
1970 char *declkeyword
; /* Keyword of a declaration */
1971 char **declargslot
; /* Where the declaration argument should be put */
1972 int *decllnslot
; /* Where the declaration linenumber is put */
1973 enum e_assoc declassoc
; /* Assign this association to decl arguments */
1974 int preccounter
; /* Assign this precedence to decl arguments */
1975 struct rule
*firstrule
; /* Pointer to first rule in the grammar */
1976 struct rule
*lastrule
; /* Pointer to the most recently parsed rule */
1979 /* Parse a single token */
1980 static void parseonetoken(psp
)
1984 x
= Strsafe(psp
->tokenstart
); /* Save the token permanently */
1986 printf("%s:%d: Token=[%s] state=%d\n",psp
->filename
,psp
->tokenlineno
,
1989 switch( psp
->state
){
1992 psp
->preccounter
= 0;
1993 psp
->firstrule
= psp
->lastrule
= 0;
1995 /* Fall thru to next case */
1996 case WAITING_FOR_DECL_OR_RULE
:
1998 psp
->state
= WAITING_FOR_DECL_KEYWORD
;
1999 }else if( islower(x
[0]) ){
2000 psp
->lhs
= Symbol_new(x
);
2003 psp
->state
= WAITING_FOR_ARROW
;
2004 }else if( x
[0]=='{' ){
2005 if( psp
->prevrule
==0 ){
2006 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2007 "There is not prior rule opon which to attach the code \
2008 fragment which begins on this line.");
2010 }else if( psp
->prevrule
->code
!=0 ){
2011 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2012 "Code fragment beginning on this line is not the first \
2013 to follow the previous rule.");
2016 psp
->prevrule
->line
= psp
->tokenlineno
;
2017 psp
->prevrule
->code
= &x
[1];
2019 }else if( x
[0]=='[' ){
2020 psp
->state
= PRECEDENCE_MARK_1
;
2022 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2023 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2028 case PRECEDENCE_MARK_1
:
2029 if( !isupper(x
[0]) ){
2030 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2031 "The precedence symbol must be a terminal.");
2033 }else if( psp
->prevrule
==0 ){
2034 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2035 "There is no prior rule to assign precedence \"[%s]\".",x
);
2037 }else if( psp
->prevrule
->precsym
!=0 ){
2038 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2039 "Precedence mark on this line is not the first \
2040 to follow the previous rule.");
2043 psp
->prevrule
->precsym
= Symbol_new(x
);
2045 psp
->state
= PRECEDENCE_MARK_2
;
2047 case PRECEDENCE_MARK_2
:
2049 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2050 "Missing \"]\" on precedence mark.");
2053 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2055 case WAITING_FOR_ARROW
:
2056 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2057 psp
->state
= IN_RHS
;
2058 }else if( x
[0]=='(' ){
2059 psp
->state
= LHS_ALIAS_1
;
2061 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2062 "Expected to see a \":\" following the LHS symbol \"%s\".",
2065 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2069 if( isalpha(x
[0]) ){
2071 psp
->state
= LHS_ALIAS_2
;
2073 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2074 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2077 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2082 psp
->state
= LHS_ALIAS_3
;
2084 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2085 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2087 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2091 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2092 psp
->state
= IN_RHS
;
2094 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2095 "Missing \"->\" following: \"%s(%s)\".",
2096 psp
->lhs
->name
,psp
->lhsalias
);
2098 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2104 rp
= (struct rule
*)calloc( sizeof(struct rule
) +
2105 sizeof(struct symbol
*)*psp
->nrhs
+ sizeof(char*)*psp
->nrhs
, 1);
2107 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2108 "Can't allocate enough memory for this rule.");
2113 rp
->ruleline
= psp
->tokenlineno
;
2114 rp
->rhs
= (struct symbol
**)&rp
[1];
2115 rp
->rhsalias
= (char**)&(rp
->rhs
[psp
->nrhs
]);
2116 for(i
=0; i
<psp
->nrhs
; i
++){
2117 rp
->rhs
[i
] = psp
->rhs
[i
];
2118 rp
->rhsalias
[i
] = psp
->alias
[i
];
2121 rp
->lhsalias
= psp
->lhsalias
;
2122 rp
->nrhs
= psp
->nrhs
;
2125 rp
->index
= psp
->gp
->nrule
++;
2126 rp
->nextlhs
= rp
->lhs
->rule
;
2129 if( psp
->firstrule
==0 ){
2130 psp
->firstrule
= psp
->lastrule
= rp
;
2132 psp
->lastrule
->next
= rp
;
2137 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2138 }else if( isalpha(x
[0]) ){
2139 if( psp
->nrhs
>=MAXRHS
){
2140 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2141 "Too many symbols on RHS of rule beginning at \"%s\".",
2144 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2146 psp
->rhs
[psp
->nrhs
] = Symbol_new(x
);
2147 psp
->alias
[psp
->nrhs
] = 0;
2150 }else if( (x
[0]=='|' || x
[0]=='/') && psp
->nrhs
>0 ){
2151 struct symbol
*msp
= psp
->rhs
[psp
->nrhs
-1];
2152 if( msp
->type
!=MULTITERMINAL
){
2153 struct symbol
*origsp
= msp
;
2154 msp
= calloc(1,sizeof(*msp
));
2155 memset(msp
, 0, sizeof(*msp
));
2156 msp
->type
= MULTITERMINAL
;
2158 msp
->subsym
= calloc(1,sizeof(struct symbol
*));
2159 msp
->subsym
[0] = origsp
;
2160 msp
->name
= origsp
->name
;
2161 psp
->rhs
[psp
->nrhs
-1] = msp
;
2164 msp
->subsym
= realloc(msp
->subsym
, sizeof(struct symbol
*)*msp
->nsubsym
);
2165 msp
->subsym
[msp
->nsubsym
-1] = Symbol_new(&x
[1]);
2166 if( islower(x
[1]) || islower(msp
->subsym
[0]->name
[0]) ){
2167 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2168 "Cannot form a compound containing a non-terminal");
2171 }else if( x
[0]=='(' && psp
->nrhs
>0 ){
2172 psp
->state
= RHS_ALIAS_1
;
2174 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2175 "Illegal character on RHS of rule: \"%s\".",x
);
2177 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2181 if( isalpha(x
[0]) ){
2182 psp
->alias
[psp
->nrhs
-1] = x
;
2183 psp
->state
= RHS_ALIAS_2
;
2185 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2186 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2187 x
,psp
->rhs
[psp
->nrhs
-1]->name
);
2189 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2194 psp
->state
= IN_RHS
;
2196 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2197 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2199 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2202 case WAITING_FOR_DECL_KEYWORD
:
2203 if( isalpha(x
[0]) ){
2204 psp
->declkeyword
= x
;
2205 psp
->declargslot
= 0;
2206 psp
->decllnslot
= 0;
2207 psp
->state
= WAITING_FOR_DECL_ARG
;
2208 if( strcmp(x
,"name")==0 ){
2209 psp
->declargslot
= &(psp
->gp
->name
);
2210 }else if( strcmp(x
,"include")==0 ){
2211 psp
->declargslot
= &(psp
->gp
->include
);
2212 psp
->decllnslot
= &psp
->gp
->includeln
;
2213 }else if( strcmp(x
,"code")==0 ){
2214 psp
->declargslot
= &(psp
->gp
->extracode
);
2215 psp
->decllnslot
= &psp
->gp
->extracodeln
;
2216 }else if( strcmp(x
,"token_destructor")==0 ){
2217 psp
->declargslot
= &psp
->gp
->tokendest
;
2218 psp
->decllnslot
= &psp
->gp
->tokendestln
;
2219 }else if( strcmp(x
,"default_destructor")==0 ){
2220 psp
->declargslot
= &psp
->gp
->vardest
;
2221 psp
->decllnslot
= &psp
->gp
->vardestln
;
2222 }else if( strcmp(x
,"token_prefix")==0 ){
2223 psp
->declargslot
= &psp
->gp
->tokenprefix
;
2224 }else if( strcmp(x
,"syntax_error")==0 ){
2225 psp
->declargslot
= &(psp
->gp
->error
);
2226 psp
->decllnslot
= &psp
->gp
->errorln
;
2227 }else if( strcmp(x
,"parse_accept")==0 ){
2228 psp
->declargslot
= &(psp
->gp
->accept
);
2229 psp
->decllnslot
= &psp
->gp
->acceptln
;
2230 }else if( strcmp(x
,"parse_failure")==0 ){
2231 psp
->declargslot
= &(psp
->gp
->failure
);
2232 psp
->decllnslot
= &psp
->gp
->failureln
;
2233 }else if( strcmp(x
,"stack_overflow")==0 ){
2234 psp
->declargslot
= &(psp
->gp
->overflow
);
2235 psp
->decllnslot
= &psp
->gp
->overflowln
;
2236 }else if( strcmp(x
,"extra_argument")==0 ){
2237 psp
->declargslot
= &(psp
->gp
->arg
);
2238 }else if( strcmp(x
,"token_type")==0 ){
2239 psp
->declargslot
= &(psp
->gp
->tokentype
);
2240 }else if( strcmp(x
,"default_type")==0 ){
2241 psp
->declargslot
= &(psp
->gp
->vartype
);
2242 }else if( strcmp(x
,"stack_size")==0 ){
2243 psp
->declargslot
= &(psp
->gp
->stacksize
);
2244 }else if( strcmp(x
,"start_symbol")==0 ){
2245 psp
->declargslot
= &(psp
->gp
->start
);
2246 }else if( strcmp(x
,"left")==0 ){
2248 psp
->declassoc
= LEFT
;
2249 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2250 }else if( strcmp(x
,"right")==0 ){
2252 psp
->declassoc
= RIGHT
;
2253 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2254 }else if( strcmp(x
,"nonassoc")==0 ){
2256 psp
->declassoc
= NONE
;
2257 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2258 }else if( strcmp(x
,"destructor")==0 ){
2259 psp
->state
= WAITING_FOR_DESTRUCTOR_SYMBOL
;
2260 }else if( strcmp(x
,"type")==0 ){
2261 psp
->state
= WAITING_FOR_DATATYPE_SYMBOL
;
2262 }else if( strcmp(x
,"fallback")==0 ){
2264 psp
->state
= WAITING_FOR_FALLBACK_ID
;
2265 }else if( strcmp(x
,"wildcard")==0 ){
2266 psp
->state
= WAITING_FOR_WILDCARD_ID
;
2268 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2269 "Unknown declaration keyword: \"%%%s\".",x
);
2271 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2274 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2275 "Illegal declaration keyword: \"%s\".",x
);
2277 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2280 case WAITING_FOR_DESTRUCTOR_SYMBOL
:
2281 if( !isalpha(x
[0]) ){
2282 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2283 "Symbol name missing after %destructor keyword");
2285 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2287 struct symbol
*sp
= Symbol_new(x
);
2288 psp
->declargslot
= &sp
->destructor
;
2289 psp
->decllnslot
= &sp
->destructorln
;
2290 psp
->state
= WAITING_FOR_DECL_ARG
;
2293 case WAITING_FOR_DATATYPE_SYMBOL
:
2294 if( !isalpha(x
[0]) ){
2295 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2296 "Symbol name missing after %destructor keyword");
2298 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2300 struct symbol
*sp
= Symbol_new(x
);
2301 psp
->declargslot
= &sp
->datatype
;
2302 psp
->decllnslot
= 0;
2303 psp
->state
= WAITING_FOR_DECL_ARG
;
2306 case WAITING_FOR_PRECEDENCE_SYMBOL
:
2308 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2309 }else if( isupper(x
[0]) ){
2313 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2314 "Symbol \"%s\" has already be given a precedence.",x
);
2317 sp
->prec
= psp
->preccounter
;
2318 sp
->assoc
= psp
->declassoc
;
2321 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2322 "Can't assign a precedence to \"%s\".",x
);
2326 case WAITING_FOR_DECL_ARG
:
2327 if( (x
[0]=='{' || x
[0]=='\"' || isalnum(x
[0])) ){
2328 if( *(psp
->declargslot
)!=0 ){
2329 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2330 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2331 x
[0]=='\"' ? &x
[1] : x
,psp
->declkeyword
);
2333 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2335 *(psp
->declargslot
) = (x
[0]=='\"' || x
[0]=='{') ? &x
[1] : x
;
2336 if( psp
->decllnslot
) *psp
->decllnslot
= psp
->tokenlineno
;
2337 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2340 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2341 "Illegal argument to %%%s: %s",psp
->declkeyword
,x
);
2343 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2346 case WAITING_FOR_FALLBACK_ID
:
2348 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2349 }else if( !isupper(x
[0]) ){
2350 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2351 "%%fallback argument \"%s\" should be a token", x
);
2354 struct symbol
*sp
= Symbol_new(x
);
2355 if( psp
->fallback
==0 ){
2357 }else if( sp
->fallback
){
2358 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2359 "More than one fallback assigned to token %s", x
);
2362 sp
->fallback
= psp
->fallback
;
2363 psp
->gp
->has_fallback
= 1;
2367 case WAITING_FOR_WILDCARD_ID
:
2369 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2370 }else if( !isupper(x
[0]) ){
2371 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2372 "%%wildcard argument \"%s\" should be a token", x
);
2375 struct symbol
*sp
= Symbol_new(x
);
2376 if( psp
->gp
->wildcard
==0 ){
2377 psp
->gp
->wildcard
= sp
;
2379 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2380 "Extra wildcard to token: %s", x
);
2385 case RESYNC_AFTER_RULE_ERROR
:
2386 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2388 case RESYNC_AFTER_DECL_ERROR
:
2389 if( x
[0]=='.' ) psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2390 if( x
[0]=='%' ) psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2395 /* Run the proprocessor over the input file text. The global variables
2396 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2397 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2398 ** comments them out. Text in between is also commented out as appropriate.
2400 static void preprocess_input(char *z
){
2405 int start_lineno
= 1;
2406 for(i
=0; z
[i
]; i
++){
2407 if( z
[i
]=='\n' ) lineno
++;
2408 if( z
[i
]!='%' || (i
>0 && z
[i
-1]!='\n') ) continue;
2409 if( strncmp(&z
[i
],"%endif",6)==0 && isspace(z
[i
+6]) ){
2413 for(j
=start
; j
<i
; j
++) if( z
[j
]!='\n' ) z
[j
] = ' ';
2416 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2417 }else if( (strncmp(&z
[i
],"%ifdef",6)==0 && isspace(z
[i
+6]))
2418 || (strncmp(&z
[i
],"%ifndef",7)==0 && isspace(z
[i
+7])) ){
2422 for(j
=i
+7; isspace(z
[j
]); j
++){}
2423 for(n
=0; z
[j
+n
] && !isspace(z
[j
+n
]); n
++){}
2425 for(k
=0; k
<nDefine
; k
++){
2426 if( strncmp(azDefine
[k
],&z
[j
],n
)==0 && strlen(azDefine
[k
])==n
){
2431 if( z
[i
+3]=='n' ) exclude
= !exclude
;
2434 start_lineno
= lineno
;
2437 for(j
=i
; z
[j
] && z
[j
]!='\n'; j
++) z
[j
] = ' ';
2441 fprintf(stderr
,"unterminated %%ifdef starting on line %d\n", start_lineno
);
2446 /* In spite of its name, this function is really a scanner. It read
2447 ** in the entire input file (all at once) then tokenizes it. Each
2448 ** token is passed to the function "parseonetoken" which builds all
2449 ** the appropriate data structures in the global state vector "gp".
2463 memset(&ps
, '\0', sizeof(ps
));
2465 ps
.filename
= gp
->filename
;
2467 ps
.state
= INITIALIZE
;
2469 /* Begin by reading the input file */
2470 fp
= fopen(ps
.filename
,"rb");
2472 ErrorMsg(ps
.filename
,0,"Can't open this file for reading.");
2477 filesize
= ftell(fp
);
2479 filebuf
= (char *)malloc( filesize
+1 );
2481 ErrorMsg(ps
.filename
,0,"Can't allocate %d of memory to hold this file.",
2486 if( fread(filebuf
,1,filesize
,fp
)!=filesize
){
2487 ErrorMsg(ps
.filename
,0,"Can't read in all %d bytes of this file.",
2494 filebuf
[filesize
] = 0;
2496 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2497 preprocess_input(filebuf
);
2499 /* Now scan the text of the input file */
2501 for(cp
=filebuf
; (c
= *cp
)!=0; ){
2502 if( c
=='\n' ) lineno
++; /* Keep track of the line number */
2503 if( isspace(c
) ){ cp
++; continue; } /* Skip all white space */
2504 if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments */
2506 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2509 if( c
=='/' && cp
[1]=='*' ){ /* Skip C style comments */
2511 while( (c
= *cp
)!=0 && (c
!='/' || cp
[-1]!='*') ){
2512 if( c
=='\n' ) lineno
++;
2518 ps
.tokenstart
= cp
; /* Mark the beginning of the token */
2519 ps
.tokenlineno
= lineno
; /* Linenumber on which token begins */
2520 if( c
=='\"' ){ /* String literals */
2522 while( (c
= *cp
)!=0 && c
!='\"' ){
2523 if( c
=='\n' ) lineno
++;
2527 ErrorMsg(ps
.filename
,startline
,
2528 "String starting on this line is not terminated before the end of the file.");
2534 }else if( c
=='{' ){ /* A block of C code */
2537 for(level
=1; (c
= *cp
)!=0 && (level
>1 || c
!='}'); cp
++){
2538 if( c
=='\n' ) lineno
++;
2539 else if( c
=='{' ) level
++;
2540 else if( c
=='}' ) level
--;
2541 else if( c
=='/' && cp
[1]=='*' ){ /* Skip comments */
2545 while( (c
= *cp
)!=0 && (c
!='/' || prevc
!='*') ){
2546 if( c
=='\n' ) lineno
++;
2550 }else if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments too */
2552 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2554 }else if( c
=='\'' || c
=='\"' ){ /* String a character literals */
2555 int startchar
, prevc
;
2558 for(cp
++; (c
= *cp
)!=0 && (c
!=startchar
|| prevc
=='\\'); cp
++){
2559 if( c
=='\n' ) lineno
++;
2560 if( prevc
=='\\' ) prevc
= 0;
2566 ErrorMsg(ps
.filename
,ps
.tokenlineno
,
2567 "C code starting on this line is not terminated before the end of the file.");
2573 }else if( isalnum(c
) ){ /* Identifiers */
2574 while( (c
= *cp
)!=0 && (isalnum(c
) || c
=='_') ) cp
++;
2576 }else if( c
==':' && cp
[1]==':' && cp
[2]=='=' ){ /* The operator "::=" */
2579 }else if( (c
=='/' || c
=='|') && isalpha(cp
[1]) ){
2581 while( (c
= *cp
)!=0 && (isalnum(c
) || c
=='_') ) cp
++;
2583 }else{ /* All other (one character) operators */
2588 *cp
= 0; /* Null terminate the token */
2589 parseonetoken(&ps
); /* Parse the token */
2590 *cp
= c
; /* Restore the buffer */
2593 free(filebuf
); /* Release the buffer after parsing */
2594 gp
->rule
= ps
.firstrule
;
2595 gp
->errorcnt
= ps
.errorcnt
;
2597 /*************************** From the file "plink.c" *********************/
2599 ** Routines processing configuration follow-set propagation links
2600 ** in the LEMON parser generator.
2602 static struct plink
*plink_freelist
= 0;
2604 /* Allocate a new plink */
2605 struct plink
*Plink_new(){
2608 if( plink_freelist
==0 ){
2611 plink_freelist
= (struct plink
*)calloc( amt
, sizeof(struct plink
) );
2612 if( plink_freelist
==0 ){
2614 "Unable to allocate memory for a new follow-set propagation link.\n");
2617 for(i
=0; i
<amt
-1; i
++) plink_freelist
[i
].next
= &plink_freelist
[i
+1];
2618 plink_freelist
[amt
-1].next
= 0;
2620 new = plink_freelist
;
2621 plink_freelist
= plink_freelist
->next
;
2625 /* Add a plink to a plink list */
2626 void Plink_add(plpp
,cfp
)
2627 struct plink
**plpp
;
2637 /* Transfer every plink on the list "from" to the list "to" */
2638 void Plink_copy(to
,from
)
2642 struct plink
*nextpl
;
2644 nextpl
= from
->next
;
2651 /* Delete every plink on the list */
2652 void Plink_delete(plp
)
2655 struct plink
*nextpl
;
2659 plp
->next
= plink_freelist
;
2660 plink_freelist
= plp
;
2664 /*********************** From the file "report.c" **************************/
2666 ** Procedures for generating reports and tables in the LEMON parser generator.
2669 /* Generate a filename with the given suffix. Space to hold the
2670 ** name comes from malloc() and must be freed by the calling
2673 PRIVATE
char *file_makename(lemp
,suffix
)
2680 name
= malloc( strlen(lemp
->filename
) + strlen(suffix
) + 5 );
2682 fprintf(stderr
,"Can't allocate space for a filename.\n");
2685 strcpy(name
,lemp
->filename
);
2686 cp
= strrchr(name
,'.');
2688 strcat(name
,suffix
);
2692 /* Open a file with a name based on the name of the input file,
2693 ** but with a different (specified) suffix, and return a pointer
2695 PRIVATE
FILE *file_open(lemp
,suffix
,mode
)
2702 if( lemp
->outname
) free(lemp
->outname
);
2703 lemp
->outname
= file_makename(lemp
, suffix
);
2704 /* LLVM LOCAL begin */
2706 fp
= fopen(lemp
->outname
,mode
);
2708 if(*mode
== 'r') return NULL
;
2711 /* LLVM LOCAL end */
2712 if( fp
==0 && *mode
=='w' ){
2713 fprintf(stderr
,"Can't open file \"%s\".\n",lemp
->outname
);
2720 /* Duplicate the input file without comments and without actions
2727 int i
, j
, maxlen
, len
, ncolumns
, skip
;
2728 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp
->filename
);
2730 for(i
=0; i
<lemp
->nsymbol
; i
++){
2731 sp
= lemp
->symbols
[i
];
2732 len
= strlen(sp
->name
);
2733 if( len
>maxlen
) maxlen
= len
;
2735 ncolumns
= 76/(maxlen
+5);
2736 if( ncolumns
<1 ) ncolumns
= 1;
2737 skip
= (lemp
->nsymbol
+ ncolumns
- 1)/ncolumns
;
2738 for(i
=0; i
<skip
; i
++){
2740 for(j
=i
; j
<lemp
->nsymbol
; j
+=skip
){
2741 sp
= lemp
->symbols
[j
];
2742 assert( sp
->index
==j
);
2743 printf(" %3d %-*.*s",j
,maxlen
,maxlen
,sp
->name
);
2747 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
2748 printf("%s",rp
->lhs
->name
);
2749 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2751 for(i
=0; i
<rp
->nrhs
; i
++){
2753 printf(" %s", sp
->name
);
2754 if( sp
->type
==MULTITERMINAL
){
2755 for(j
=1; j
<sp
->nsubsym
; j
++){
2756 printf("|%s", sp
->subsym
[j
]->name
);
2759 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2762 if( rp
->precsym
) printf(" [%s]",rp
->precsym
->name
);
2763 /* if( rp->code ) printf("\n %s",rp->code); */
2768 void ConfigPrint(fp
,cfp
)
2776 fprintf(fp
,"%s ::=",rp
->lhs
->name
);
2777 for(i
=0; i
<=rp
->nrhs
; i
++){
2778 if( i
==cfp
->dot
) fprintf(fp
," *");
2779 if( i
==rp
->nrhs
) break;
2781 fprintf(fp
," %s", sp
->name
);
2782 if( sp
->type
==MULTITERMINAL
){
2783 for(j
=1; j
<sp
->nsubsym
; j
++){
2784 fprintf(fp
,"|%s",sp
->subsym
[j
]->name
);
2793 PRIVATE
void SetPrint(out
,set
,lemp
)
2801 fprintf(out
,"%12s[","");
2802 for(i
=0; i
<lemp
->nterminal
; i
++){
2803 if( SetFind(set
,i
) ){
2804 fprintf(out
,"%s%s",spacer
,lemp
->symbols
[i
]->name
);
2811 /* Print a plink chain */
2812 PRIVATE
void PlinkPrint(out
,plp
,tag
)
2818 fprintf(out
,"%12s%s (state %2d) ","",tag
,plp
->cfp
->stp
->statenum
);
2819 ConfigPrint(out
,plp
->cfp
);
2826 /* Print an action to the given file descriptor. Return FALSE if
2827 ** nothing was actually printed.
2829 int PrintAction(struct action
*ap
, FILE *fp
, int indent
){
2833 fprintf(fp
,"%*s shift %d",indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
2836 fprintf(fp
,"%*s reduce %d",indent
,ap
->sp
->name
,ap
->x
.rp
->index
);
2839 fprintf(fp
,"%*s accept",indent
,ap
->sp
->name
);
2842 fprintf(fp
,"%*s error",indent
,ap
->sp
->name
);
2846 fprintf(fp
,"%*s reduce %-3d ** Parsing conflict **",
2847 indent
,ap
->sp
->name
,ap
->x
.rp
->index
);
2850 fprintf(fp
,"%*s shift %d ** Parsing conflict **",
2851 indent
,ap
->sp
->name
,ap
->x
.stp
->statenum
);
2862 /* Generate the "y.output" log file */
2863 void ReportOutput(lemp
)
2872 fp
= file_open(lemp
,".out","wb");
2874 for(i
=0; i
<lemp
->nstate
; i
++){
2875 stp
= lemp
->sorted
[i
];
2876 fprintf(fp
,"State %d:\n",stp
->statenum
);
2877 if( lemp
->basisflag
) cfp
=stp
->bp
;
2881 if( cfp
->dot
==cfp
->rp
->nrhs
){
2882 sprintf(buf
,"(%d)",cfp
->rp
->index
);
2883 fprintf(fp
," %5s ",buf
);
2887 ConfigPrint(fp
,cfp
);
2890 SetPrint(fp
,cfp
->fws
,lemp
);
2891 PlinkPrint(fp
,cfp
->fplp
,"To ");
2892 PlinkPrint(fp
,cfp
->bplp
,"From");
2894 if( lemp
->basisflag
) cfp
=cfp
->bp
;
2898 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
2899 if( PrintAction(ap
,fp
,30) ) fprintf(fp
,"\n");
2903 fprintf(fp
, "----------------------------------------------------\n");
2904 fprintf(fp
, "Symbols:\n");
2905 for(i
=0; i
<lemp
->nsymbol
; i
++){
2909 sp
= lemp
->symbols
[i
];
2910 fprintf(fp
, " %3d: %s", i
, sp
->name
);
2911 if( sp
->type
==NONTERMINAL
){
2914 fprintf(fp
, " <lambda>");
2916 for(j
=0; j
<lemp
->nterminal
; j
++){
2917 if( sp
->firstset
&& SetFind(sp
->firstset
, j
) ){
2918 fprintf(fp
, " %s", lemp
->symbols
[j
]->name
);
2930 /* Search for the file "name" which is in the same directory as
2931 ** the exacutable */
2932 PRIVATE
char *pathsearch(argv0
,name
,modemask
)
2942 cp
= strrchr(argv0
,'\\');
2944 cp
= strrchr(argv0
,'/');
2949 path
= (char *)malloc( strlen(argv0
) + strlen(name
) + 2 );
2950 if( path
) sprintf(path
,"%s/%s",argv0
,name
);
2953 extern char *getenv();
2954 pathlist
= getenv("PATH");
2955 if( pathlist
==0 ) pathlist
= ".:/bin:/usr/bin";
2956 path
= (char *)malloc( strlen(pathlist
)+strlen(name
)+2 );
2959 cp
= strchr(pathlist
,':');
2960 if( cp
==0 ) cp
= &pathlist
[strlen(pathlist
)];
2963 sprintf(path
,"%s/%s",pathlist
,name
);
2965 if( c
==0 ) pathlist
= "";
2966 else pathlist
= &cp
[1];
2967 if( access(path
,modemask
)==0 ) break;
2974 /* Given an action, compute the integer value for that action
2975 ** which is to be put in the action table of the generated machine.
2976 ** Return negative if no action should be generated.
2978 PRIVATE
int compute_action(lemp
,ap
)
2984 case SHIFT
: act
= ap
->x
.stp
->statenum
; break;
2985 case REDUCE
: act
= ap
->x
.rp
->index
+ lemp
->nstate
; break;
2986 case ERROR
: act
= lemp
->nstate
+ lemp
->nrule
; break;
2987 case ACCEPT
: act
= lemp
->nstate
+ lemp
->nrule
+ 1; break;
2988 default: act
= -1; break;
2993 #define LINESIZE 1000
2994 /* The next cluster of routines are for reading the template file
2995 ** and writing the results to the generated parser */
2996 /* The first function transfers data from "in" to "out" until
2997 ** a line is seen which begins with "%%". The line number is
3000 ** if name!=0, then any word that begin with "Parse" is changed to
3001 ** begin with *name instead.
3003 PRIVATE
void tplt_xfer(name
,in
,out
,lineno
)
3010 char line
[LINESIZE
];
3011 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
3015 for(i
=0; line
[i
]; i
++){
3016 if( line
[i
]=='P' && strncmp(&line
[i
],"Parse",5)==0
3017 && (i
==0 || !isalpha(line
[i
-1]))
3019 if( i
>iStart
) fprintf(out
,"%.*s",i
-iStart
,&line
[iStart
]);
3020 fprintf(out
,"%s",name
);
3026 fprintf(out
,"%s",&line
[iStart
]);
3030 /* The next function finds the template file and opens it, returning
3031 ** a pointer to the opened file. */
3032 PRIVATE
FILE *tplt_open(lemp
)
3035 static char templatename
[] = "lempar.c";
3041 cp
= strrchr(lemp
->filename
,'.');
3043 sprintf(buf
,"%.*s.lt",(int)(cp
-lemp
->filename
),lemp
->filename
);
3045 sprintf(buf
,"%s.lt",lemp
->filename
);
3047 if( access(buf
,004)==0 ){
3049 }else if( access(templatename
,004)==0 ){
3050 tpltname
= templatename
;
3052 tpltname
= pathsearch(lemp
->filename
,templatename
,0);
3055 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
3060 in
= fopen(tpltname
,"rb");
3062 fprintf(stderr
,"Can't open the template file \"%s\".\n",templatename
);
3069 /* Print a #line directive line to the output file. */
3070 PRIVATE
void tplt_linedir(out
,lineno
,filename
)
3075 filename
= mybasename(filename
);
3076 fprintf(out
,"#line %d \"",lineno
);
3078 if( *filename
== '\\' ) putc('\\',out
);
3079 putc(*filename
,out
);
3082 fprintf(out
,"\"\n");
3085 /* Print a string to the file and keep the linenumber up to date */
3086 PRIVATE
void tplt_print(out
,lemp
,str
,strln
,lineno
)
3093 if( str
==0 ) return;
3094 tplt_linedir(out
,strln
,lemp
->filename
);
3097 if( *str
=='\n' ) (*lineno
)++;
3101 if( str
[-1]!='\n' ){
3105 tplt_linedir(out
,*lineno
+2,lemp
->outname
);
3111 ** The following routine emits code for the destructor for the
3114 void emit_destructor_code(out
,sp
,lemp
,lineno
)
3123 if( sp
->type
==TERMINAL
){
3124 cp
= lemp
->tokendest
;
3126 tplt_linedir(out
,lemp
->tokendestln
,lemp
->filename
);
3128 }else if( sp
->destructor
){
3129 cp
= sp
->destructor
;
3130 tplt_linedir(out
,sp
->destructorln
,lemp
->filename
);
3132 }else if( lemp
->vardest
){
3135 tplt_linedir(out
,lemp
->vardestln
,lemp
->filename
);
3138 assert( 0 ); /* Cannot happen */
3141 if( *cp
=='$' && cp
[1]=='$' ){
3142 fprintf(out
,"(yypminor->yy%d)",sp
->dtnum
);
3146 if( *cp
=='\n' ) linecnt
++;
3149 (*lineno
) += 3 + linecnt
;
3151 tplt_linedir(out
,*lineno
,lemp
->outname
);
3156 ** Return TRUE (non-zero) if the given symbol has a destructor.
3158 int has_destructor(sp
, lemp
)
3163 if( sp
->type
==TERMINAL
){
3164 ret
= lemp
->tokendest
!=0;
3166 ret
= lemp
->vardest
!=0 || sp
->destructor
!=0;
3172 ** Append text to a dynamically allocated string. If zText is 0 then
3173 ** reset the string to be empty again. Always return the complete text
3174 ** of the string (which is overwritten with each call).
3176 ** n bytes of zText are stored. If n==0 then all of zText up to the first
3177 ** \000 terminator is stored. zText can contain up to two instances of
3178 ** %d. The values of p1 and p2 are written into the first and second
3181 ** If n==-1, then the previous character is overwritten.
3183 PRIVATE
char *append_str(char *zText
, int n
, int p1
, int p2
){
3185 static int alloced
= 0;
3186 static int used
= 0;
3201 if( n
+sizeof(zInt
)*2+used
>= alloced
){
3202 alloced
= n
+ sizeof(zInt
)*2 + used
+ 200;
3203 z
= realloc(z
, alloced
);
3205 if( z
==0 ) return "";
3208 if( c
=='%' && n
>0 && zText
[0]=='d' ){
3209 sprintf(zInt
, "%d", p1
);
3211 strcpy(&z
[used
], zInt
);
3212 used
+= strlen(&z
[used
]);
3224 ** zCode is a string that is the action associated with a rule. Expand
3225 ** the symbols in this string so that the refer to elements of the parser
3228 PRIVATE
void translate_code(struct lemon
*lemp
, struct rule
*rp
){
3231 char lhsused
= 0; /* True if the LHS element has been used */
3232 char used
[MAXRHS
]; /* True for each RHS element which is used */
3234 for(i
=0; i
<rp
->nrhs
; i
++) used
[i
] = 0;
3239 rp
->line
= rp
->ruleline
;
3242 append_str(0,0,0,0);
3243 for(cp
=rp
->code
; *cp
; cp
++){
3244 if( isalpha(*cp
) && (cp
==rp
->code
|| (!isalnum(cp
[-1]) && cp
[-1]!='_')) ){
3246 for(xp
= &cp
[1]; isalnum(*xp
) || *xp
=='_'; xp
++);
3249 if( rp
->lhsalias
&& strcmp(cp
,rp
->lhsalias
)==0 ){
3250 append_str("yygotominor.yy%d",0,rp
->lhs
->dtnum
,0);
3254 for(i
=0; i
<rp
->nrhs
; i
++){
3255 if( rp
->rhsalias
[i
] && strcmp(cp
,rp
->rhsalias
[i
])==0 ){
3256 if( cp
!=rp
->code
&& cp
[-1]=='@' ){
3257 /* If the argument is of the form @X then substituted
3258 ** the token number of X, not the value of X */
3259 append_str("yymsp[%d].major",-1,i
-rp
->nrhs
+1,0);
3261 struct symbol
*sp
= rp
->rhs
[i
];
3263 if( sp
->type
==MULTITERMINAL
){
3264 dtnum
= sp
->subsym
[0]->dtnum
;
3268 append_str("yymsp[%d].minor.yy%d",0,i
-rp
->nrhs
+1, dtnum
);
3278 append_str(cp
, 1, 0, 0);
3281 /* Check to make sure the LHS has been used */
3282 if( rp
->lhsalias
&& !lhsused
){
3283 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3284 "Label \"%s\" for \"%s(%s)\" is never used.",
3285 rp
->lhsalias
,rp
->lhs
->name
,rp
->lhsalias
);
3289 /* Generate destructor code for RHS symbols which are not used in the
3291 for(i
=0; i
<rp
->nrhs
; i
++){
3292 if( rp
->rhsalias
[i
] && !used
[i
] ){
3293 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3294 "Label %s for \"%s(%s)\" is never used.",
3295 rp
->rhsalias
[i
],rp
->rhs
[i
]->name
,rp
->rhsalias
[i
]);
3297 }else if( rp
->rhsalias
[i
]==0 ){
3298 if( has_destructor(rp
->rhs
[i
],lemp
) ){
3299 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
3300 rp
->rhs
[i
]->index
,i
-rp
->nrhs
+1);
3302 /* No destructor defined for this term */
3307 cp
= append_str(0,0,0,0);
3308 rp
->code
= Strsafe(cp
?cp
:"");
3313 ** Generate code which executes when the rule "rp" is reduced. Write
3314 ** the code to "out". Make sure lineno stays up-to-date.
3316 PRIVATE
void emit_code(out
,rp
,lemp
,lineno
)
3325 /* Generate code to do the reduce action */
3327 tplt_linedir(out
,rp
->line
,lemp
->filename
);
3328 fprintf(out
,"{%s",rp
->code
);
3329 for(cp
=rp
->code
; *cp
; cp
++){
3330 if( *cp
=='\n' ) linecnt
++;
3332 (*lineno
) += 3 + linecnt
;
3334 tplt_linedir(out
,*lineno
,lemp
->outname
);
3335 } /* End if( rp->code ) */
3341 ** Print the definition of the union used for the parser's data stack.
3342 ** This union contains fields for every possible data type for tokens
3343 ** and nonterminals. In the process of computing and printing this
3344 ** union, also set the ".dtnum" field of every terminal and nonterminal
3347 void print_stack_union(out
,lemp
,plineno
,mhflag
)
3348 FILE *out
; /* The output stream */
3349 struct lemon
*lemp
; /* The main info structure for this parser */
3350 int *plineno
; /* Pointer to the line number */
3351 int mhflag
; /* True if generating makeheaders output */
3353 int lineno
= *plineno
; /* The line number of the output */
3354 char **types
; /* A hash table of datatypes */
3355 int arraysize
; /* Size of the "types" array */
3356 int maxdtlength
; /* Maximum length of any ".datatype" field. */
3357 char *stddt
; /* Standardized name for a datatype */
3358 int i
,j
; /* Loop counters */
3359 int hash
; /* For hashing the name of a type */
3360 char *name
; /* Name of the parser */
3362 /* Allocate and initialize types[] and allocate stddt[] */
3363 arraysize
= lemp
->nsymbol
* 2;
3364 types
= (char**)calloc( arraysize
, sizeof(char*) );
3365 for(i
=0; i
<arraysize
; i
++) types
[i
] = 0;
3367 if( lemp
->vartype
){
3368 maxdtlength
= strlen(lemp
->vartype
);
3370 for(i
=0; i
<lemp
->nsymbol
; i
++){
3372 struct symbol
*sp
= lemp
->symbols
[i
];
3373 if( sp
->datatype
==0 ) continue;
3374 len
= strlen(sp
->datatype
);
3375 if( len
>maxdtlength
) maxdtlength
= len
;
3377 stddt
= (char*)malloc( maxdtlength
*2 + 1 );
3378 if( types
==0 || stddt
==0 ){
3379 fprintf(stderr
,"Out of memory.\n");
3383 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3384 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3385 ** used for terminal symbols. If there is no %default_type defined then
3386 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3387 ** a datatype using the %type directive.
3389 for(i
=0; i
<lemp
->nsymbol
; i
++){
3390 struct symbol
*sp
= lemp
->symbols
[i
];
3392 if( sp
==lemp
->errsym
){
3393 sp
->dtnum
= arraysize
+1;
3396 if( sp
->type
!=NONTERMINAL
|| (sp
->datatype
==0 && lemp
->vartype
==0) ){
3401 if( cp
==0 ) cp
= lemp
->vartype
;
3403 while( isspace(*cp
) ) cp
++;
3404 while( *cp
) stddt
[j
++] = *cp
++;
3405 while( j
>0 && isspace(stddt
[j
-1]) ) j
--;
3408 for(j
=0; stddt
[j
]; j
++){
3409 hash
= hash
*53 + stddt
[j
];
3411 hash
= (hash
& 0x7fffffff)%arraysize
;
3412 while( types
[hash
] ){
3413 if( strcmp(types
[hash
],stddt
)==0 ){
3414 sp
->dtnum
= hash
+ 1;
3418 if( hash
>=arraysize
) hash
= 0;
3420 if( types
[hash
]==0 ){
3421 sp
->dtnum
= hash
+ 1;
3422 types
[hash
] = (char*)malloc( strlen(stddt
)+1 );
3423 if( types
[hash
]==0 ){
3424 fprintf(stderr
,"Out of memory.\n");
3427 strcpy(types
[hash
],stddt
);
3431 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3432 name
= lemp
->name
? lemp
->name
: "Parse";
3434 if( mhflag
){ fprintf(out
,"#if INTERFACE\n"); lineno
++; }
3435 fprintf(out
,"#define %sTOKENTYPE %s\n",name
,
3436 lemp
->tokentype
?lemp
->tokentype
:"void*"); lineno
++;
3437 if( mhflag
){ fprintf(out
,"#endif\n"); lineno
++; }
3438 fprintf(out
,"typedef union {\n"); lineno
++;
3439 fprintf(out
," %sTOKENTYPE yy0;\n",name
); lineno
++;
3440 for(i
=0; i
<arraysize
; i
++){
3441 if( types
[i
]==0 ) continue;
3442 fprintf(out
," %s yy%d;\n",types
[i
],i
+1); lineno
++;
3445 if( lemp
->errsym
->useCnt
){
3446 fprintf(out
," int yy%d;\n",lemp
->errsym
->dtnum
); lineno
++;
3450 fprintf(out
,"} YYMINORTYPE;\n"); lineno
++;
3455 ** Return the name of a C datatype able to represent values between
3456 ** lwr and upr, inclusive.
3458 static const char *minimum_size_type(int lwr
, int upr
){
3461 return "unsigned char";
3462 }else if( upr
<65535 ){
3463 return "unsigned short int";
3465 return "unsigned int";
3467 }else if( lwr
>=-127 && upr
<=127 ){
3468 return "signed char";
3469 }else if( lwr
>=-32767 && upr
<32767 ){
3477 ** Each state contains a set of token transaction and a set of
3478 ** nonterminal transactions. Each of these sets makes an instance
3479 ** of the following structure. An array of these structures is used
3480 ** to order the creation of entries in the yy_action[] table.
3483 struct state
*stp
; /* A pointer to a state */
3484 int isTkn
; /* True to use tokens. False for non-terminals */
3485 int nAction
; /* Number of actions */
3489 ** Compare to axset structures for sorting purposes
3491 static int axset_compare(const void *a
, const void *b
){
3492 struct axset
*p1
= (struct axset
*)a
;
3493 struct axset
*p2
= (struct axset
*)b
;
3494 return p2
->nAction
- p1
->nAction
;
3498 ** Write text on "out" that describes the rule "rp".
3500 static void writeRuleText(FILE *out
, struct rule
*rp
){
3502 fprintf(out
,"%s ::=", rp
->lhs
->name
);
3503 for(j
=0; j
<rp
->nrhs
; j
++){
3504 struct symbol
*sp
= rp
->rhs
[j
];
3505 fprintf(out
," %s", sp
->name
);
3506 if( sp
->type
==MULTITERMINAL
){
3508 for(k
=1; k
<sp
->nsubsym
; k
++){
3509 fprintf(out
,"|%s",sp
->subsym
[k
]->name
);
3516 /* Generate C source code for the parser */
3517 void ReportTable(lemp
, mhflag
)
3519 int mhflag
; /* Output in makeheaders format if true */
3522 char line
[LINESIZE
];
3527 struct acttab
*pActtab
;
3530 int mnTknOfst
, mxTknOfst
;
3531 int mnNtOfst
, mxNtOfst
;
3534 in
= tplt_open(lemp
);
3536 out
= file_open(lemp
,".c","wb");
3542 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3544 /* Generate the include code, if any */
3545 tplt_print(out
,lemp
,lemp
->include
,lemp
->includeln
,&lineno
);
3547 char *name
= file_makename(lemp
, ".h");
3548 fprintf(out
,"#include \"%s\"\n", name
); lineno
++;
3551 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3553 /* Generate #defines for all tokens */
3556 fprintf(out
,"#if INTERFACE\n"); lineno
++;
3557 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
3559 for(i
=1; i
<lemp
->nterminal
; i
++){
3560 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
3563 fprintf(out
,"#endif\n"); lineno
++;
3565 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3567 /* Generate the defines */
3568 fprintf(out
,"#define YYCODETYPE %s\n",
3569 minimum_size_type(0, lemp
->nsymbol
+5)); lineno
++;
3570 fprintf(out
,"#define YYNOCODE %d\n",lemp
->nsymbol
+1); lineno
++;
3571 fprintf(out
,"#define YYACTIONTYPE %s\n",
3572 minimum_size_type(0, lemp
->nstate
+lemp
->nrule
+5)); lineno
++;
3573 if( lemp
->wildcard
){
3574 fprintf(out
,"#define YYWILDCARD %d\n",
3575 lemp
->wildcard
->index
); lineno
++;
3577 print_stack_union(out
,lemp
,&lineno
,mhflag
);
3578 fprintf(out
, "#ifndef YYSTACKDEPTH\n"); lineno
++;
3579 if( lemp
->stacksize
){
3580 fprintf(out
,"#define YYSTACKDEPTH %s\n",lemp
->stacksize
); lineno
++;
3582 fprintf(out
,"#define YYSTACKDEPTH 100\n"); lineno
++;
3584 fprintf(out
, "#endif\n"); lineno
++;
3586 fprintf(out
,"#if INTERFACE\n"); lineno
++;
3588 name
= lemp
->name
? lemp
->name
: "Parse";
3589 if( lemp
->arg
&& lemp
->arg
[0] ){
3591 i
= strlen(lemp
->arg
);
3592 while( i
>=1 && isspace(lemp
->arg
[i
-1]) ) i
--;
3593 while( i
>=1 && (isalnum(lemp
->arg
[i
-1]) || lemp
->arg
[i
-1]=='_') ) i
--;
3594 fprintf(out
,"#define %sARG_SDECL %s;\n",name
,lemp
->arg
); lineno
++;
3595 fprintf(out
,"#define %sARG_PDECL ,%s\n",name
,lemp
->arg
); lineno
++;
3596 fprintf(out
,"#define %sARG_FETCH %s = yypParser->%s\n",
3597 name
,lemp
->arg
,&lemp
->arg
[i
]); lineno
++;
3598 fprintf(out
,"#define %sARG_STORE yypParser->%s = %s\n",
3599 name
,&lemp
->arg
[i
],&lemp
->arg
[i
]); lineno
++;
3601 fprintf(out
,"#define %sARG_SDECL\n",name
); lineno
++;
3602 fprintf(out
,"#define %sARG_PDECL\n",name
); lineno
++;
3603 fprintf(out
,"#define %sARG_FETCH\n",name
); lineno
++;
3604 fprintf(out
,"#define %sARG_STORE\n",name
); lineno
++;
3607 fprintf(out
,"#endif\n"); lineno
++;
3609 fprintf(out
,"#define YYNSTATE %d\n",lemp
->nstate
); lineno
++;
3610 fprintf(out
,"#define YYNRULE %d\n",lemp
->nrule
); lineno
++;
3611 if( lemp
->errsym
->useCnt
){
3612 fprintf(out
,"#define YYERRORSYMBOL %d\n",lemp
->errsym
->index
); lineno
++;
3613 fprintf(out
,"#define YYERRSYMDT yy%d\n",lemp
->errsym
->dtnum
); lineno
++;
3615 if( lemp
->has_fallback
){
3616 fprintf(out
,"#define YYFALLBACK 1\n"); lineno
++;
3618 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3620 /* Generate the action table and its associates:
3622 ** yy_action[] A single table containing all actions.
3623 ** yy_lookahead[] A table containing the lookahead for each entry in
3624 ** yy_action. Used to detect hash collisions.
3625 ** yy_shift_ofst[] For each state, the offset into yy_action for
3626 ** shifting terminals.
3627 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3628 ** shifting non-terminals after a reduce.
3629 ** yy_default[] Default action for each state.
3632 /* Compute the actions on all states and count them up */
3633 ax
= calloc(lemp
->nstate
*2, sizeof(ax
[0]));
3635 fprintf(stderr
,"malloc failed\n");
3638 for(i
=0; i
<lemp
->nstate
; i
++){
3639 stp
= lemp
->sorted
[i
];
3642 ax
[i
*2].nAction
= stp
->nTknAct
;
3643 ax
[i
*2+1].stp
= stp
;
3644 ax
[i
*2+1].isTkn
= 0;
3645 ax
[i
*2+1].nAction
= stp
->nNtAct
;
3647 mxTknOfst
= mnTknOfst
= 0;
3648 mxNtOfst
= mnNtOfst
= 0;
3650 /* Compute the action table. In order to try to keep the size of the
3651 ** action table to a minimum, the heuristic of placing the largest action
3652 ** sets first is used.
3654 qsort(ax
, lemp
->nstate
*2, sizeof(ax
[0]), axset_compare
);
3655 pActtab
= acttab_alloc();
3656 for(i
=0; i
<lemp
->nstate
*2 && ax
[i
].nAction
>0; i
++){
3659 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3661 if( ap
->sp
->index
>=lemp
->nterminal
) continue;
3662 action
= compute_action(lemp
, ap
);
3663 if( action
<0 ) continue;
3664 acttab_action(pActtab
, ap
->sp
->index
, action
);
3666 stp
->iTknOfst
= acttab_insert(pActtab
);
3667 if( stp
->iTknOfst
<mnTknOfst
) mnTknOfst
= stp
->iTknOfst
;
3668 if( stp
->iTknOfst
>mxTknOfst
) mxTknOfst
= stp
->iTknOfst
;
3670 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3672 if( ap
->sp
->index
<lemp
->nterminal
) continue;
3673 if( ap
->sp
->index
==lemp
->nsymbol
) continue;
3674 action
= compute_action(lemp
, ap
);
3675 if( action
<0 ) continue;
3676 acttab_action(pActtab
, ap
->sp
->index
, action
);
3678 stp
->iNtOfst
= acttab_insert(pActtab
);
3679 if( stp
->iNtOfst
<mnNtOfst
) mnNtOfst
= stp
->iNtOfst
;
3680 if( stp
->iNtOfst
>mxNtOfst
) mxNtOfst
= stp
->iNtOfst
;
3685 /* Output the yy_action table */
3686 fprintf(out
,"static const YYACTIONTYPE yy_action[] = {\n"); lineno
++;
3687 n
= acttab_size(pActtab
);
3688 for(i
=j
=0; i
<n
; i
++){
3689 int action
= acttab_yyaction(pActtab
, i
);
3690 if( action
<0 ) action
= lemp
->nstate
+ lemp
->nrule
+ 2;
3691 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3692 fprintf(out
, " %4d,", action
);
3693 if( j
==9 || i
==n
-1 ){
3694 fprintf(out
, "\n"); lineno
++;
3700 fprintf(out
, "};\n"); lineno
++;
3702 /* Output the yy_lookahead table */
3703 fprintf(out
,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno
++;
3704 for(i
=j
=0; i
<n
; i
++){
3705 int la
= acttab_yylookahead(pActtab
, i
);
3706 if( la
<0 ) la
= lemp
->nsymbol
;
3707 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3708 fprintf(out
, " %4d,", la
);
3709 if( j
==9 || i
==n
-1 ){
3710 fprintf(out
, "\n"); lineno
++;
3716 fprintf(out
, "};\n"); lineno
++;
3718 /* Output the yy_shift_ofst[] table */
3719 fprintf(out
, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst
-1); lineno
++;
3721 while( n
>0 && lemp
->sorted
[n
-1]->iTknOfst
==NO_OFFSET
) n
--;
3722 fprintf(out
, "#define YY_SHIFT_MAX %d\n", n
-1); lineno
++;
3723 fprintf(out
, "static const %s yy_shift_ofst[] = {\n",
3724 minimum_size_type(mnTknOfst
-1, mxTknOfst
)); lineno
++;
3725 for(i
=j
=0; i
<n
; i
++){
3727 stp
= lemp
->sorted
[i
];
3728 ofst
= stp
->iTknOfst
;
3729 if( ofst
==NO_OFFSET
) ofst
= mnTknOfst
- 1;
3730 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3731 fprintf(out
, " %4d,", ofst
);
3732 if( j
==9 || i
==n
-1 ){
3733 fprintf(out
, "\n"); lineno
++;
3739 fprintf(out
, "};\n"); lineno
++;
3741 /* Output the yy_reduce_ofst[] table */
3742 fprintf(out
, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst
-1); lineno
++;
3744 while( n
>0 && lemp
->sorted
[n
-1]->iNtOfst
==NO_OFFSET
) n
--;
3745 fprintf(out
, "#define YY_REDUCE_MAX %d\n", n
-1); lineno
++;
3746 fprintf(out
, "static const %s yy_reduce_ofst[] = {\n",
3747 minimum_size_type(mnNtOfst
-1, mxNtOfst
)); lineno
++;
3748 for(i
=j
=0; i
<n
; i
++){
3750 stp
= lemp
->sorted
[i
];
3751 ofst
= stp
->iNtOfst
;
3752 if( ofst
==NO_OFFSET
) ofst
= mnNtOfst
- 1;
3753 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3754 fprintf(out
, " %4d,", ofst
);
3755 if( j
==9 || i
==n
-1 ){
3756 fprintf(out
, "\n"); lineno
++;
3762 fprintf(out
, "};\n"); lineno
++;
3764 /* Output the default action table */
3765 fprintf(out
, "static const YYACTIONTYPE yy_default[] = {\n"); lineno
++;
3767 for(i
=j
=0; i
<n
; i
++){
3768 stp
= lemp
->sorted
[i
];
3769 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3770 fprintf(out
, " %4d,", stp
->iDflt
);
3771 if( j
==9 || i
==n
-1 ){
3772 fprintf(out
, "\n"); lineno
++;
3778 fprintf(out
, "};\n"); lineno
++;
3779 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3781 /* Generate the table of fallback tokens.
3783 if( lemp
->has_fallback
){
3784 for(i
=0; i
<lemp
->nterminal
; i
++){
3785 struct symbol
*p
= lemp
->symbols
[i
];
3786 if( p
->fallback
==0 ){
3787 fprintf(out
, " 0, /* %10s => nothing */\n", p
->name
);
3789 fprintf(out
, " %3d, /* %10s => %s */\n", p
->fallback
->index
,
3790 p
->name
, p
->fallback
->name
);
3795 tplt_xfer(lemp
->name
, in
, out
, &lineno
);
3797 /* Generate a table containing the symbolic name of every symbol
3799 for(i
=0; i
<lemp
->nsymbol
; i
++){
3800 sprintf(line
,"\"%s\",",lemp
->symbols
[i
]->name
);
3801 fprintf(out
," %-15s",line
);
3802 if( (i
&3)==3 ){ fprintf(out
,"\n"); lineno
++; }
3804 if( (i
&3)!=0 ){ fprintf(out
,"\n"); lineno
++; }
3805 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3807 /* Generate a table containing a text string that describes every
3808 ** rule in the rule set of the grammer. This information is used
3809 ** when tracing REDUCE actions.
3811 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
3812 assert( rp
->index
==i
);
3813 fprintf(out
," /* %3d */ \"", i
);
3814 writeRuleText(out
, rp
);
3815 fprintf(out
,"\",\n"); lineno
++;
3817 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3819 /* Generate code which executes every time a symbol is popped from
3820 ** the stack while processing errors or while destroying the parser.
3821 ** (In other words, generate the %destructor actions)
3823 if( lemp
->tokendest
){
3824 for(i
=0; i
<lemp
->nsymbol
; i
++){
3825 struct symbol
*sp
= lemp
->symbols
[i
];
3826 if( sp
==0 || sp
->type
!=TERMINAL
) continue;
3827 fprintf(out
," case %d: /* %s */\n",
3828 sp
->index
, sp
->name
); lineno
++;
3830 for(i
=0; i
<lemp
->nsymbol
&& lemp
->symbols
[i
]->type
!=TERMINAL
; i
++);
3831 if( i
<lemp
->nsymbol
){
3832 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
3833 fprintf(out
," break;\n"); lineno
++;
3836 if( lemp
->vardest
){
3837 struct symbol
*dflt_sp
= 0;
3838 for(i
=0; i
<lemp
->nsymbol
; i
++){
3839 struct symbol
*sp
= lemp
->symbols
[i
];
3840 if( sp
==0 || sp
->type
==TERMINAL
||
3841 sp
->index
<=0 || sp
->destructor
!=0 ) continue;
3842 fprintf(out
," case %d: /* %s */\n",
3843 sp
->index
, sp
->name
); lineno
++;
3847 emit_destructor_code(out
,dflt_sp
,lemp
,&lineno
);
3848 fprintf(out
," break;\n"); lineno
++;
3851 for(i
=0; i
<lemp
->nsymbol
; i
++){
3852 struct symbol
*sp
= lemp
->symbols
[i
];
3853 if( sp
==0 || sp
->type
==TERMINAL
|| sp
->destructor
==0 ) continue;
3854 fprintf(out
," case %d: /* %s */\n",
3855 sp
->index
, sp
->name
); lineno
++;
3857 /* Combine duplicate destructors into a single case */
3858 for(j
=i
+1; j
<lemp
->nsymbol
; j
++){
3859 struct symbol
*sp2
= lemp
->symbols
[j
];
3860 if( sp2
&& sp2
->type
!=TERMINAL
&& sp2
->destructor
3861 && sp2
->dtnum
==sp
->dtnum
3862 && strcmp(sp
->destructor
,sp2
->destructor
)==0 ){
3863 fprintf(out
," case %d: /* %s */\n",
3864 sp2
->index
, sp2
->name
); lineno
++;
3865 sp2
->destructor
= 0;
3869 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
3870 fprintf(out
," break;\n"); lineno
++;
3872 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3874 /* Generate code which executes whenever the parser stack overflows */
3875 tplt_print(out
,lemp
,lemp
->overflow
,lemp
->overflowln
,&lineno
);
3876 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3878 /* Generate the table of rule information
3880 ** Note: This code depends on the fact that rules are number
3881 ** sequentually beginning with 0.
3883 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3884 fprintf(out
," { %d, %d },\n",rp
->lhs
->index
,rp
->nrhs
); lineno
++;
3886 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3888 /* Generate code which execution during each REDUCE action */
3889 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3890 translate_code(lemp
, rp
);
3892 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3894 if( rp
->code
==0 ) continue;
3895 fprintf(out
," case %d: /* ", rp
->index
);
3896 writeRuleText(out
, rp
);
3897 fprintf(out
, " */\n"); lineno
++;
3898 for(rp2
=rp
->next
; rp2
; rp2
=rp2
->next
){
3899 if( rp2
->code
==rp
->code
){
3900 fprintf(out
," case %d: /* ", rp2
->index
);
3901 writeRuleText(out
, rp2
);
3902 fprintf(out
," */\n"); lineno
++;
3906 emit_code(out
,rp
,lemp
,&lineno
);
3907 fprintf(out
," break;\n"); lineno
++;
3909 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3911 /* Generate code which executes if a parse fails */
3912 tplt_print(out
,lemp
,lemp
->failure
,lemp
->failureln
,&lineno
);
3913 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3915 /* Generate code which executes when a syntax error occurs */
3916 tplt_print(out
,lemp
,lemp
->error
,lemp
->errorln
,&lineno
);
3917 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3919 /* Generate code which executes when the parser accepts its input */
3920 tplt_print(out
,lemp
,lemp
->accept
,lemp
->acceptln
,&lineno
);
3921 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3923 /* Append any addition code the user desires */
3924 tplt_print(out
,lemp
,lemp
->extracode
,lemp
->extracodeln
,&lineno
);
3933 /* Generate a header file for the parser */
3934 void ReportHeader(lemp
)
3939 char line
[LINESIZE
];
3940 char pattern
[LINESIZE
];
3943 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
3945 in
= file_open(lemp
,".h","rb");
3947 for(i
=1; i
<lemp
->nterminal
&& fgets(line
,LINESIZE
,in
); i
++){
3948 sprintf(pattern
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
3949 if( strcmp(line
,pattern
) ) break;
3952 if( i
==lemp
->nterminal
){
3953 /* No change in the file. Don't rewrite it. */
3957 out
= file_open(lemp
,".h","wb");
3959 for(i
=1; i
<lemp
->nterminal
; i
++){
3960 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
3969 /* Reduce the size of the action tables, if possible, by making use
3972 ** In this version, we take the most frequent REDUCE action and make
3973 ** it the default. Except, there is no default if the wildcard token
3974 ** is a possible look-ahead.
3976 void CompressTables(lemp
)
3980 struct action
*ap
, *ap2
;
3981 struct rule
*rp
, *rp2
, *rbest
;
3986 for(i
=0; i
<lemp
->nstate
; i
++){
3987 stp
= lemp
->sorted
[i
];
3992 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3993 if( ap
->type
==SHIFT
&& ap
->sp
==lemp
->wildcard
){
3996 if( ap
->type
!=REDUCE
) continue;
3998 if( rp
->lhsStart
) continue;
3999 if( rp
==rbest
) continue;
4001 for(ap2
=ap
->next
; ap2
; ap2
=ap2
->next
){
4002 if( ap2
->type
!=REDUCE
) continue;
4004 if( rp2
==rbest
) continue;
4013 /* Do not make a default if the number of rules to default
4014 ** is not at least 1 or if the wildcard token is a possible
4017 if( nbest
<1 || usesWildcard
) continue;
4020 /* Combine matching REDUCE actions into a single default */
4021 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4022 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) break;
4025 ap
->sp
= Symbol_new("{default}");
4026 for(ap
=ap
->next
; ap
; ap
=ap
->next
){
4027 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) ap
->type
= NOT_USED
;
4029 stp
->ap
= Action_sort(stp
->ap
);
4035 ** Compare two states for sorting purposes. The smaller state is the
4036 ** one with the most non-terminal actions. If they have the same number
4037 ** of non-terminal actions, then the smaller is the one with the most
4040 static int stateResortCompare(const void *a
, const void *b
){
4041 const struct state
*pA
= *(const struct state
**)a
;
4042 const struct state
*pB
= *(const struct state
**)b
;
4045 n
= pB
->nNtAct
- pA
->nNtAct
;
4047 n
= pB
->nTknAct
- pA
->nTknAct
;
4054 ** Renumber and resort states so that states with fewer choices
4055 ** occur at the end. Except, keep state 0 as the first state.
4057 void ResortStates(lemp
)
4064 for(i
=0; i
<lemp
->nstate
; i
++){
4065 stp
= lemp
->sorted
[i
];
4066 stp
->nTknAct
= stp
->nNtAct
= 0;
4067 stp
->iDflt
= lemp
->nstate
+ lemp
->nrule
;
4068 stp
->iTknOfst
= NO_OFFSET
;
4069 stp
->iNtOfst
= NO_OFFSET
;
4070 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
4071 if( compute_action(lemp
,ap
)>=0 ){
4072 if( ap
->sp
->index
<lemp
->nterminal
){
4074 }else if( ap
->sp
->index
<lemp
->nsymbol
){
4077 stp
->iDflt
= compute_action(lemp
, ap
);
4082 qsort(&lemp
->sorted
[1], lemp
->nstate
-1, sizeof(lemp
->sorted
[0]),
4083 stateResortCompare
);
4084 for(i
=0; i
<lemp
->nstate
; i
++){
4085 lemp
->sorted
[i
]->statenum
= i
;
4090 /***************** From the file "set.c" ************************************/
4092 ** Set manipulation routines for the LEMON parser generator.
4095 static int size
= 0;
4097 /* Set the set size */
4104 /* Allocate a new set */
4107 s
= (char*)calloc( size
, 1);
4109 extern void memory_error();
4115 /* Deallocate a set */
4122 /* Add a new element to the set. Return TRUE if the element was added
4123 ** and FALSE if it was already there. */
4129 assert( e
>=0 && e
<size
);
4135 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4142 for(i
=0; i
<size
; i
++){
4143 if( s2
[i
]==0 ) continue;
4151 /********************** From the file "table.c" ****************************/
4153 ** All code in this file has been automatically generated
4154 ** from a specification in the file
4156 ** by the associative array code building program "aagen".
4157 ** Do not edit this file! Instead, edit the specification
4158 ** file, then rerun aagen.
4161 ** Code for processing tables in the LEMON parser generator.
4164 PRIVATE
int strhash(x
)
4168 while( *x
) h
= h
*13 + *(x
++);
4172 /* Works like strdup, sort of. Save a string in malloced memory, but
4173 ** keep strings in a table so that the same string is not in more
4181 if( y
==0 ) return 0;
4182 z
= Strsafe_find(y
);
4183 if( z
==0 && (z
=malloc( strlen(y
)+1 ))!=0 ){
4191 /* There is one instance of the following structure for each
4192 ** associative array of type "x1".
4195 int size
; /* The number of available slots. */
4196 /* Must be a power of 2 greater than or */
4198 int count
; /* Number of currently slots filled */
4199 struct s_x1node
*tbl
; /* The data stored here */
4200 struct s_x1node
**ht
; /* Hash table for lookups */
4203 /* There is one instance of this structure for every data element
4204 ** in an associative array of type "x1".
4206 typedef struct s_x1node
{
4207 char *data
; /* The data */
4208 struct s_x1node
*next
; /* Next entry with the same hash */
4209 struct s_x1node
**from
; /* Previous link */
4212 /* There is only one instance of the array, which is the following */
4213 static struct s_x1
*x1a
;
4215 /* Allocate a new associative array */
4216 void Strsafe_init(){
4218 x1a
= (struct s_x1
*)malloc( sizeof(struct s_x1
) );
4222 x1a
->tbl
= (x1node
*)malloc(
4223 (sizeof(x1node
) + sizeof(x1node
*))*1024 );
4229 x1a
->ht
= (x1node
**)&(x1a
->tbl
[1024]);
4230 for(i
=0; i
<1024; i
++) x1a
->ht
[i
] = 0;
4234 /* Insert a new record into the array. Return TRUE if successful.
4235 ** Prior data with the same key is NOT overwritten */
4236 int Strsafe_insert(data
)
4243 if( x1a
==0 ) return 0;
4245 h
= ph
& (x1a
->size
-1);
4248 if( strcmp(np
->data
,data
)==0 ){
4249 /* An existing entry with the same key is found. */
4250 /* Fail because overwrite is not allows. */
4255 if( x1a
->count
>=x1a
->size
){
4256 /* Need to make the hash table bigger */
4259 array
.size
= size
= x1a
->size
*2;
4260 array
.count
= x1a
->count
;
4261 array
.tbl
= (x1node
*)malloc(
4262 (sizeof(x1node
) + sizeof(x1node
*))*size
);
4263 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4264 array
.ht
= (x1node
**)&(array
.tbl
[size
]);
4265 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4266 for(i
=0; i
<x1a
->count
; i
++){
4267 x1node
*oldnp
, *newnp
;
4268 oldnp
= &(x1a
->tbl
[i
]);
4269 h
= strhash(oldnp
->data
) & (size
-1);
4270 newnp
= &(array
.tbl
[i
]);
4271 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4272 newnp
->next
= array
.ht
[h
];
4273 newnp
->data
= oldnp
->data
;
4274 newnp
->from
= &(array
.ht
[h
]);
4275 array
.ht
[h
] = newnp
;
4280 /* Insert the new data */
4281 h
= ph
& (x1a
->size
-1);
4282 np
= &(x1a
->tbl
[x1a
->count
++]);
4284 if( x1a
->ht
[h
] ) x1a
->ht
[h
]->from
= &(np
->next
);
4285 np
->next
= x1a
->ht
[h
];
4287 np
->from
= &(x1a
->ht
[h
]);
4291 /* Return a pointer to data assigned to the given key. Return NULL
4292 ** if no such key. */
4293 char *Strsafe_find(key
)
4299 if( x1a
==0 ) return 0;
4300 h
= strhash(key
) & (x1a
->size
-1);
4303 if( strcmp(np
->data
,key
)==0 ) break;
4306 return np
? np
->data
: 0;
4309 /* Return a pointer to the (terminal or nonterminal) symbol "x".
4310 ** Create a new symbol if this is the first time "x" has been seen.
4312 struct symbol
*Symbol_new(x
)
4317 sp
= Symbol_find(x
);
4319 sp
= (struct symbol
*)calloc(1, sizeof(struct symbol
) );
4321 sp
->name
= Strsafe(x
);
4322 sp
->type
= isupper(*x
) ? TERMINAL
: NONTERMINAL
;
4328 sp
->lambda
= LEMON_FALSE
;
4332 Symbol_insert(sp
,sp
->name
);
4338 /* Compare two symbols for working purposes
4340 ** Symbols that begin with upper case letters (terminals or tokens)
4341 ** must sort before symbols that begin with lower case letters
4342 ** (non-terminals). Other than that, the order does not matter.
4344 ** We find experimentally that leaving the symbols in their original
4345 ** order (the order they appeared in the grammar file) gives the
4346 ** smallest parser tables in SQLite.
4348 int Symbolcmpp(struct symbol
**a
, struct symbol
**b
){
4349 int i1
= (**a
).index
+ 10000000*((**a
).name
[0]>'Z');
4350 int i2
= (**b
).index
+ 10000000*((**b
).name
[0]>'Z');
4354 /* There is one instance of the following structure for each
4355 ** associative array of type "x2".
4358 int size
; /* The number of available slots. */
4359 /* Must be a power of 2 greater than or */
4361 int count
; /* Number of currently slots filled */
4362 struct s_x2node
*tbl
; /* The data stored here */
4363 struct s_x2node
**ht
; /* Hash table for lookups */
4366 /* There is one instance of this structure for every data element
4367 ** in an associative array of type "x2".
4369 typedef struct s_x2node
{
4370 struct symbol
*data
; /* The data */
4371 char *key
; /* The key */
4372 struct s_x2node
*next
; /* Next entry with the same hash */
4373 struct s_x2node
**from
; /* Previous link */
4376 /* There is only one instance of the array, which is the following */
4377 static struct s_x2
*x2a
;
4379 /* Allocate a new associative array */
4382 x2a
= (struct s_x2
*)malloc( sizeof(struct s_x2
) );
4386 x2a
->tbl
= (x2node
*)malloc(
4387 (sizeof(x2node
) + sizeof(x2node
*))*128 );
4393 x2a
->ht
= (x2node
**)&(x2a
->tbl
[128]);
4394 for(i
=0; i
<128; i
++) x2a
->ht
[i
] = 0;
4398 /* Insert a new record into the array. Return TRUE if successful.
4399 ** Prior data with the same key is NOT overwritten */
4400 int Symbol_insert(data
,key
)
4401 struct symbol
*data
;
4408 if( x2a
==0 ) return 0;
4410 h
= ph
& (x2a
->size
-1);
4413 if( strcmp(np
->key
,key
)==0 ){
4414 /* An existing entry with the same key is found. */
4415 /* Fail because overwrite is not allows. */
4420 if( x2a
->count
>=x2a
->size
){
4421 /* Need to make the hash table bigger */
4424 array
.size
= size
= x2a
->size
*2;
4425 array
.count
= x2a
->count
;
4426 array
.tbl
= (x2node
*)malloc(
4427 (sizeof(x2node
) + sizeof(x2node
*))*size
);
4428 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4429 array
.ht
= (x2node
**)&(array
.tbl
[size
]);
4430 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4431 for(i
=0; i
<x2a
->count
; i
++){
4432 x2node
*oldnp
, *newnp
;
4433 oldnp
= &(x2a
->tbl
[i
]);
4434 h
= strhash(oldnp
->key
) & (size
-1);
4435 newnp
= &(array
.tbl
[i
]);
4436 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4437 newnp
->next
= array
.ht
[h
];
4438 newnp
->key
= oldnp
->key
;
4439 newnp
->data
= oldnp
->data
;
4440 newnp
->from
= &(array
.ht
[h
]);
4441 array
.ht
[h
] = newnp
;
4446 /* Insert the new data */
4447 h
= ph
& (x2a
->size
-1);
4448 np
= &(x2a
->tbl
[x2a
->count
++]);
4451 if( x2a
->ht
[h
] ) x2a
->ht
[h
]->from
= &(np
->next
);
4452 np
->next
= x2a
->ht
[h
];
4454 np
->from
= &(x2a
->ht
[h
]);
4458 /* Return a pointer to data assigned to the given key. Return NULL
4459 ** if no such key. */
4460 struct symbol
*Symbol_find(key
)
4466 if( x2a
==0 ) return 0;
4467 h
= strhash(key
) & (x2a
->size
-1);
4470 if( strcmp(np
->key
,key
)==0 ) break;
4473 return np
? np
->data
: 0;
4476 /* Return the n-th data. Return NULL if n is out of range. */
4477 struct symbol
*Symbol_Nth(n
)
4480 struct symbol
*data
;
4481 if( x2a
&& n
>0 && n
<=x2a
->count
){
4482 data
= x2a
->tbl
[n
-1].data
;
4489 /* Return the size of the array */
4492 return x2a
? x2a
->count
: 0;
4495 /* Return an array of pointers to all data in the table.
4496 ** The array is obtained from malloc. Return NULL if memory allocation
4497 ** problems, or if the array is empty. */
4498 struct symbol
**Symbol_arrayof()
4500 struct symbol
**array
;
4502 if( x2a
==0 ) return 0;
4504 array
= (struct symbol
**)calloc(size
, sizeof(struct symbol
*));
4506 for(i
=0; i
<size
; i
++) array
[i
] = x2a
->tbl
[i
].data
;
4511 /* Compare two configurations */
4517 x
= a
->rp
->index
- b
->rp
->index
;
4518 if( x
==0 ) x
= a
->dot
- b
->dot
;
4522 /* Compare two states */
4523 PRIVATE
int statecmp(a
,b
)
4528 for(rc
=0; rc
==0 && a
&& b
; a
=a
->bp
, b
=b
->bp
){
4529 rc
= a
->rp
->index
- b
->rp
->index
;
4530 if( rc
==0 ) rc
= a
->dot
- b
->dot
;
4540 PRIVATE
int statehash(a
)
4545 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
4551 /* Allocate a new state structure */
4552 struct state
*State_new()
4555 new = (struct state
*)calloc(1, sizeof(struct state
) );
4560 /* There is one instance of the following structure for each
4561 ** associative array of type "x3".
4564 int size
; /* The number of available slots. */
4565 /* Must be a power of 2 greater than or */
4567 int count
; /* Number of currently slots filled */
4568 struct s_x3node
*tbl
; /* The data stored here */
4569 struct s_x3node
**ht
; /* Hash table for lookups */
4572 /* There is one instance of this structure for every data element
4573 ** in an associative array of type "x3".
4575 typedef struct s_x3node
{
4576 struct state
*data
; /* The data */
4577 struct config
*key
; /* The key */
4578 struct s_x3node
*next
; /* Next entry with the same hash */
4579 struct s_x3node
**from
; /* Previous link */
4582 /* There is only one instance of the array, which is the following */
4583 static struct s_x3
*x3a
;
4585 /* Allocate a new associative array */
4588 x3a
= (struct s_x3
*)malloc( sizeof(struct s_x3
) );
4592 x3a
->tbl
= (x3node
*)malloc(
4593 (sizeof(x3node
) + sizeof(x3node
*))*128 );
4599 x3a
->ht
= (x3node
**)&(x3a
->tbl
[128]);
4600 for(i
=0; i
<128; i
++) x3a
->ht
[i
] = 0;
4604 /* Insert a new record into the array. Return TRUE if successful.
4605 ** Prior data with the same key is NOT overwritten */
4606 int State_insert(data
,key
)
4614 if( x3a
==0 ) return 0;
4615 ph
= statehash(key
);
4616 h
= ph
& (x3a
->size
-1);
4619 if( statecmp(np
->key
,key
)==0 ){
4620 /* An existing entry with the same key is found. */
4621 /* Fail because overwrite is not allows. */
4626 if( x3a
->count
>=x3a
->size
){
4627 /* Need to make the hash table bigger */
4630 array
.size
= size
= x3a
->size
*2;
4631 array
.count
= x3a
->count
;
4632 array
.tbl
= (x3node
*)malloc(
4633 (sizeof(x3node
) + sizeof(x3node
*))*size
);
4634 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4635 array
.ht
= (x3node
**)&(array
.tbl
[size
]);
4636 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4637 for(i
=0; i
<x3a
->count
; i
++){
4638 x3node
*oldnp
, *newnp
;
4639 oldnp
= &(x3a
->tbl
[i
]);
4640 h
= statehash(oldnp
->key
) & (size
-1);
4641 newnp
= &(array
.tbl
[i
]);
4642 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4643 newnp
->next
= array
.ht
[h
];
4644 newnp
->key
= oldnp
->key
;
4645 newnp
->data
= oldnp
->data
;
4646 newnp
->from
= &(array
.ht
[h
]);
4647 array
.ht
[h
] = newnp
;
4652 /* Insert the new data */
4653 h
= ph
& (x3a
->size
-1);
4654 np
= &(x3a
->tbl
[x3a
->count
++]);
4657 if( x3a
->ht
[h
] ) x3a
->ht
[h
]->from
= &(np
->next
);
4658 np
->next
= x3a
->ht
[h
];
4660 np
->from
= &(x3a
->ht
[h
]);
4664 /* Return a pointer to data assigned to the given key. Return NULL
4665 ** if no such key. */
4666 struct state
*State_find(key
)
4672 if( x3a
==0 ) return 0;
4673 h
= statehash(key
) & (x3a
->size
-1);
4676 if( statecmp(np
->key
,key
)==0 ) break;
4679 return np
? np
->data
: 0;
4682 /* Return an array of pointers to all data in the table.
4683 ** The array is obtained from malloc. Return NULL if memory allocation
4684 ** problems, or if the array is empty. */
4685 struct state
**State_arrayof()
4687 struct state
**array
;
4689 if( x3a
==0 ) return 0;
4691 array
= (struct state
**)malloc( sizeof(struct state
*)*size
);
4693 for(i
=0; i
<size
; i
++) array
[i
] = x3a
->tbl
[i
].data
;
4698 /* Hash a configuration */
4699 PRIVATE
int confighash(a
)
4703 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
4707 /* There is one instance of the following structure for each
4708 ** associative array of type "x4".
4711 int size
; /* The number of available slots. */
4712 /* Must be a power of 2 greater than or */
4714 int count
; /* Number of currently slots filled */
4715 struct s_x4node
*tbl
; /* The data stored here */
4716 struct s_x4node
**ht
; /* Hash table for lookups */
4719 /* There is one instance of this structure for every data element
4720 ** in an associative array of type "x4".
4722 typedef struct s_x4node
{
4723 struct config
*data
; /* The data */
4724 struct s_x4node
*next
; /* Next entry with the same hash */
4725 struct s_x4node
**from
; /* Previous link */
4728 /* There is only one instance of the array, which is the following */
4729 static struct s_x4
*x4a
;
4731 /* Allocate a new associative array */
4732 void Configtable_init(){
4734 x4a
= (struct s_x4
*)malloc( sizeof(struct s_x4
) );
4738 x4a
->tbl
= (x4node
*)malloc(
4739 (sizeof(x4node
) + sizeof(x4node
*))*64 );
4745 x4a
->ht
= (x4node
**)&(x4a
->tbl
[64]);
4746 for(i
=0; i
<64; i
++) x4a
->ht
[i
] = 0;
4750 /* Insert a new record into the array. Return TRUE if successful.
4751 ** Prior data with the same key is NOT overwritten */
4752 int Configtable_insert(data
)
4753 struct config
*data
;
4759 if( x4a
==0 ) return 0;
4760 ph
= confighash(data
);
4761 h
= ph
& (x4a
->size
-1);
4764 if( Configcmp(np
->data
,data
)==0 ){
4765 /* An existing entry with the same key is found. */
4766 /* Fail because overwrite is not allows. */
4771 if( x4a
->count
>=x4a
->size
){
4772 /* Need to make the hash table bigger */
4775 array
.size
= size
= x4a
->size
*2;
4776 array
.count
= x4a
->count
;
4777 array
.tbl
= (x4node
*)malloc(
4778 (sizeof(x4node
) + sizeof(x4node
*))*size
);
4779 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4780 array
.ht
= (x4node
**)&(array
.tbl
[size
]);
4781 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4782 for(i
=0; i
<x4a
->count
; i
++){
4783 x4node
*oldnp
, *newnp
;
4784 oldnp
= &(x4a
->tbl
[i
]);
4785 h
= confighash(oldnp
->data
) & (size
-1);
4786 newnp
= &(array
.tbl
[i
]);
4787 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4788 newnp
->next
= array
.ht
[h
];
4789 newnp
->data
= oldnp
->data
;
4790 newnp
->from
= &(array
.ht
[h
]);
4791 array
.ht
[h
] = newnp
;
4796 /* Insert the new data */
4797 h
= ph
& (x4a
->size
-1);
4798 np
= &(x4a
->tbl
[x4a
->count
++]);
4800 if( x4a
->ht
[h
] ) x4a
->ht
[h
]->from
= &(np
->next
);
4801 np
->next
= x4a
->ht
[h
];
4803 np
->from
= &(x4a
->ht
[h
]);
4807 /* Return a pointer to data assigned to the given key. Return NULL
4808 ** if no such key. */
4809 struct config
*Configtable_find(key
)
4815 if( x4a
==0 ) return 0;
4816 h
= confighash(key
) & (x4a
->size
-1);
4819 if( Configcmp(np
->data
,key
)==0 ) break;
4822 return np
? np
->data
: 0;
4825 /* Remove all data from the table. Pass each data to the function "f"
4826 ** as it is removed. ("f" may be null to avoid this step.) */
4827 void Configtable_clear(f
)
4828 int(*f
)(/* struct config * */);
4831 if( x4a
==0 || x4a
->count
==0 ) return;
4832 if( f
) for(i
=0; i
<x4a
->count
; i
++) (*f
)(x4a
->tbl
[i
].data
);
4833 for(i
=0; i
<x4a
->size
; i
++) x4a
->ht
[i
] = 0;
4838 /* LLVM LOCAL begin */
4841 #include <sys/wait.h>
4843 /* llvm-test supports only running program once,
4844 * we need to run it multiple times, because it only accepts
4845 * one input a time, and has a global state */
4846 int main(int argc
, char **argv
)
4850 /* test finishes too fast, run more times to get
4851 * meaningful timings */
4852 for(i
=1;i
<argc
;i
++) {
4856 char *argv_child
[] = {"lemon-child","-s",argv
[i
],NULL
};
4858 fprintf(stdout
,"Processing %s\n",mybasename(argv
[i
]));
4859 exit( lemon_main(3, argv_child
) );
4861 while(wait(&status
) == -1 && errno
== EINTR
) {}
4864 fprintf(stderr
,"Error while running on: %s\n",mybasename(argv
[i
]));
4871 /* LLVM LOCAL end */