Fix file mode.
[llvm-testsuite.git] / MultiSource / Applications / lemon / lemon.c
blobe65eebf85dd06c23ba0598b3fa235cb9870f4046
1 /*
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.
6 **
7 ** The author of this program disclaims copyright.
8 */
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <stdlib.h>
14 #include <assert.h>
16 #ifndef __WIN32__
17 # if defined(_WIN32) || defined(WIN32)
18 # define __WIN32__
19 # endif
20 #endif
22 #ifdef __WIN32__
23 extern int access();
24 #else
25 #include <unistd.h>
26 #endif
28 /* #define PRIVATE static */
29 #define PRIVATE
31 #ifdef TEST
32 #define MAXRHS 5 /* Set low to exercise exception code */
33 #else
34 #define MAXRHS 1000
35 #endif
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();
49 void FindFirstSets();
50 void FindStates();
51 void FindLinks();
52 void FindFollowSets();
53 void FindActions();
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" ******************************************/
71 struct s_options {
72 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
73 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
74 char *label;
75 char *arg;
76 char *message;
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: */
120 struct symbol {
121 char *name; /* Name of the symbol */
122 int index; /* Index number for this symbol */
123 enum {
124 TERMINAL,
125 NONTERMINAL,
126 MULTITERMINAL
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) */
131 enum e_assoc {
132 LEFT,
133 RIGHT,
134 NONE,
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
154 ** structure. */
155 struct rule {
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: */
177 struct config {
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 */
184 enum {
185 COMPLETE, /* The status is used during followset and */
186 INCOMPLETE /* shift computations */
187 } status;
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 */
193 struct action {
194 struct symbol *sp; /* The look-ahead symbol */
195 enum e_action {
196 SHIFT,
197 ACCEPT,
198 REDUCE,
199 ERROR,
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 */
206 } type;
207 union {
208 struct state *stp; /* The new state, if a shift */
209 struct rule *rp; /* The rule, if a reduce */
210 } x;
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. */
217 struct state {
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. */
231 struct plink {
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.) */
240 struct lemon {
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(); \
285 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
292 ** "table.q"
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 */
303 char *Strsafe();
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;
343 struct action *new;
345 if( freelist==0 ){
346 int i;
347 int amt = 100;
348 freelist = (struct action *)calloc(amt, sizeof(struct action));
349 if( freelist==0 ){
350 fprintf(stderr,"Unable to allocate memory for a new parser action.");
351 exit(1);
353 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
354 freelist[amt-1].next = 0;
356 new = freelist;
357 freelist = freelist->next;
358 return new;
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
363 ** the first
365 static int actioncmp(
366 struct action *ap1,
367 struct action *ap2
369 int rc;
370 rc = ap1->sp->index - ap2->sp->index;
371 if( rc==0 ){
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;
377 return rc;
380 /* Sort parser actions */
381 static struct action *Action_sort(
382 struct action *ap
384 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
385 (int(*)(const char*,const char*))actioncmp);
386 return ap;
389 void Action_add(app,type,sp,arg)
390 struct action **app;
391 enum e_action type;
392 struct symbol *sp;
393 char *arg;
395 struct action *new;
396 new = Action_new();
397 new->next = *app;
398 *app = new;
399 new->type = type;
400 new->sp = sp;
401 if( type==SHIFT ){
402 new->x.stp = (struct state *)arg;
403 }else{
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;
417 struct acttab {
418 int nAction; /* Number of used slots in aAction[] */
419 int nActionAlloc; /* Slots allocated for aAction[] */
420 struct {
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){
443 free( p->aAction );
444 free( p->aLookahead );
445 free( p );
448 /* Allocate a new acttab structure */
449 acttab *acttab_alloc(void){
450 acttab *p = calloc( 1, sizeof(*p) );
451 if( p==0 ){
452 fprintf(stderr,"Unable to allocate memory for a new acttab.");
453 exit(1);
455 memset(p, 0, sizeof(*p));
456 return 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");
468 exit(1);
471 if( p->nLookahead==0 ){
472 p->mxLookahead = lookahead;
473 p->mnLookahead = lookahead;
474 p->mnAction = action;
475 }else{
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;
484 p->nLookahead++;
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){
495 int i, j, k, n;
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);
508 if( p->aAction==0 ){
509 fprintf(stderr,"malloc failed\n");
510 exit(1);
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;
529 if( k<0 ) break;
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;
536 if( j==p->nAction ){
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;
548 n = 0;
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;
564 p->nLookahead = 0;
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
574 ** parser generator.
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)
587 struct lemon *xp;
589 struct rule *rp;
590 for(rp=xp->rule; rp; rp=rp->next){
591 if( rp->precsym==0 ){
592 int i, j;
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];
599 break;
602 }else if( sp->prec>=0 ){
603 rp->precsym = rp->rhs[i];
608 return;
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)
617 struct lemon *lemp;
619 int i, j;
620 struct rule *rp;
621 int progress;
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 */
632 progress = 0;
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;
639 if( i==rp->nrhs ){
640 rp->lhs->lambda = LEMON_TRUE;
641 progress = 1;
644 }while( progress );
646 /* Now compute all first sets */
648 struct symbol *s1, *s2;
649 progress = 0;
650 for(rp=lemp->rule; rp; rp=rp->next){
651 s1 = rp->lhs;
652 for(i=0; i<rp->nrhs; i++){
653 s2 = rp->rhs[i];
654 if( s2->type==TERMINAL ){
655 progress += SetAdd(s1->firstset,s2->index);
656 break;
657 }else if( s2->type==MULTITERMINAL ){
658 for(j=0; j<s2->nsubsym; j++){
659 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
661 break;
662 }else if( s1==s2 ){
663 if( s1->lambda==LEMON_FALSE ) break;
664 }else{
665 progress += SetUnion(s1->firstset,s2->firstset);
666 if( s2->lambda==LEMON_FALSE ) break;
670 }while( progress );
671 return;
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)
680 struct lemon *lemp;
682 struct symbol *sp;
683 struct rule *rp;
685 Configlist_init();
687 /* Find the start symbol */
688 if( lemp->start ){
689 sp = Symbol_find(lemp->start);
690 if( sp==0 ){
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);
695 lemp->errorcnt++;
696 sp = lemp->rule->lhs;
698 }else{
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){
706 int i;
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);
713 lemp->errorcnt++;
718 /* The basis configuration set for the first state
719 ** is all rules which have the start symbol as their
720 ** left-hand side */
721 for(rp=sp->rule; rp; rp=rp->nextlhs){
722 struct config *newcfp;
723 rp->lhsStart = 1;
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);
732 return;
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)
740 struct lemon *lemp;
742 struct config *cfp, *bp;
743 struct state *stp;
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);
752 if( stp ){
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();
763 Configlist_eat(cfp);
764 }else{
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 */
770 MemoryCheck(stp);
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 */
778 return stp;
782 ** Return true if two symbols are the same.
784 int same_symbol(a,b)
785 struct symbol *a;
786 struct symbol *b;
788 int i;
789 if( a==b ) return 1;
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;
796 return 1;
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)
803 struct lemon *lemp;
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 ){
844 int i;
845 for(i=0; i<sp->nsubsym; i++){
846 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
848 }else{
849 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
855 ** Construct the propagation links
857 void FindLinks(lemp)
858 struct lemon *lemp;
860 int i;
861 struct config *cfp, *other;
862 struct state *stp;
863 struct plink *plp;
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){
871 cfp->stp = stp;
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){
881 other = plp->cfp;
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)
894 struct lemon *lemp;
896 int i;
897 struct config *cfp;
898 struct plink *plp;
899 int progress;
900 int change;
902 for(i=0; i<lemp->nstate; i++){
903 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
904 cfp->status = INCOMPLETE;
909 progress = 0;
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);
915 if( change ){
916 plp->cfp->status = INCOMPLETE;
917 progress = 1;
920 cfp->status = COMPLETE;
923 }while( progress );
926 static int resolve_conflict();
928 /* Compute the reduce actions, and resolve conflicts.
930 void FindActions(lemp)
931 struct lemon *lemp;
933 int i,j;
934 struct config *cfp;
935 struct state *stp;
936 struct symbol *sp;
937 struct rule *rp;
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 */
959 if( lemp->start ){
960 sp = Symbol_find(lemp->start);
961 if( sp==0 ) sp = lemp->rule->lhs;
962 }else{
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;
973 struct state *stp;
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++){
989 struct action *ap;
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");
997 lemp->errorcnt++;
1001 /* Resolve a conflict between the two given actions. If the
1002 ** conflict can't be resolve, return non-zero.
1004 ** NO LONGER TRUE:
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)
1015 struct action *apx;
1016 struct action *apy;
1017 struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1019 struct symbol *spx, *spy;
1020 int errcnt = 0;
1021 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1022 if( apx->type==SHIFT && apy->type==SHIFT ){
1023 apy->type = SSCONFLICT;
1024 errcnt++;
1026 if( apx->type==SHIFT && apy->type==REDUCE ){
1027 spx = apx->sp;
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;
1032 errcnt++;
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;
1041 }else{
1042 assert( spx->prec==spy->prec && spx->assoc==NONE );
1043 apy->type = SRCONFLICT;
1044 errcnt++;
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;
1052 errcnt++;
1053 }else if( spx->prec>spy->prec ){
1054 apy->type = RD_RESOLVED;
1055 }else if( spx->prec<spy->prec ){
1056 apx->type = RD_RESOLVED;
1058 }else{
1059 assert(
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. */
1075 return errcnt;
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(){
1091 struct config *new;
1092 if( freelist==0 ){
1093 int i;
1094 int amt = 3;
1095 freelist = (struct config *)calloc( amt, sizeof(struct config) );
1096 if( freelist==0 ){
1097 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1098 exit(1);
1100 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1101 freelist[amt-1].next = 0;
1103 new = freelist;
1104 freelist = freelist->next;
1105 return new;
1108 /* The configuration "old" is no longer used */
1109 PRIVATE void deleteconfig(old)
1110 struct config *old;
1112 old->next = freelist;
1113 freelist = old;
1116 /* Initialized the configuration list builder */
1117 void Configlist_init(){
1118 current = 0;
1119 currentend = &current;
1120 basis = 0;
1121 basisend = &basis;
1122 Configtable_init();
1123 return;
1126 /* Initialized the configuration list builder */
1127 void Configlist_reset(){
1128 current = 0;
1129 currentend = &current;
1130 basis = 0;
1131 basisend = &basis;
1132 Configtable_clear(0);
1133 return;
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 );
1144 model.rp = rp;
1145 model.dot = dot;
1146 cfp = Configtable_find(&model);
1147 if( cfp==0 ){
1148 cfp = newconfig();
1149 cfp->rp = rp;
1150 cfp->dot = dot;
1151 cfp->fws = SetNew();
1152 cfp->stp = 0;
1153 cfp->fplp = cfp->bplp = 0;
1154 cfp->next = 0;
1155 cfp->bp = 0;
1156 *currentend = cfp;
1157 currentend = &cfp->next;
1158 Configtable_insert(cfp);
1160 return cfp;
1163 /* Add a basis configuration to the configuration list */
1164 struct config *Configlist_addbasis(rp,dot)
1165 struct rule *rp;
1166 int dot;
1168 struct config *cfp, model;
1170 assert( basisend!=0 );
1171 assert( currentend!=0 );
1172 model.rp = rp;
1173 model.dot = dot;
1174 cfp = Configtable_find(&model);
1175 if( cfp==0 ){
1176 cfp = newconfig();
1177 cfp->rp = rp;
1178 cfp->dot = dot;
1179 cfp->fws = SetNew();
1180 cfp->stp = 0;
1181 cfp->fplp = cfp->bplp = 0;
1182 cfp->next = 0;
1183 cfp->bp = 0;
1184 *currentend = cfp;
1185 currentend = &cfp->next;
1186 *basisend = cfp;
1187 basisend = &cfp->bp;
1188 Configtable_insert(cfp);
1190 return cfp;
1193 /* Compute the closure of the configuration list */
1194 void Configlist_closure(lemp)
1195 struct lemon *lemp;
1197 struct config *cfp, *newcfp;
1198 struct rule *rp, *newrp;
1199 struct symbol *sp, *xsp;
1200 int i, dot;
1202 assert( currentend!=0 );
1203 for(cfp=current; cfp; cfp=cfp->next){
1204 rp = cfp->rp;
1205 dot = cfp->dot;
1206 if( dot>=rp->nrhs ) continue;
1207 sp = rp->rhs[dot];
1208 if( sp->type==NONTERMINAL ){
1209 if( sp->rule==0 && sp!=lemp->errsym ){
1210 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1211 sp->name);
1212 lemp->errorcnt++;
1214 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1215 newcfp = Configlist_add(newrp,0);
1216 for(i=dot+1; i<rp->nrhs; i++){
1217 xsp = rp->rhs[i];
1218 if( xsp->type==TERMINAL ){
1219 SetAdd(newcfp->fws,xsp->index);
1220 break;
1221 }else if( xsp->type==MULTITERMINAL ){
1222 int k;
1223 for(k=0; k<xsp->nsubsym; k++){
1224 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1226 break;
1227 }else{
1228 SetUnion(newcfp->fws,xsp->firstset);
1229 if( xsp->lambda==LEMON_FALSE ) break;
1232 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1236 return;
1239 /* Sort the configuration list */
1240 void Configlist_sort(){
1241 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
1242 currentend = 0;
1243 return;
1246 /* Sort the basis configuration list */
1247 void Configlist_sortbasis(){
1248 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
1249 basisend = 0;
1250 return;
1253 /* Return a pointer to the head of the configuration list and
1254 ** reset the list */
1255 struct config *Configlist_return(){
1256 struct config *old;
1257 old = current;
1258 current = 0;
1259 currentend = 0;
1260 return old;
1263 /* Return a pointer to the head of the configuration list and
1264 ** reset the list */
1265 struct config *Configlist_basis(){
1266 struct config *old;
1267 old = basis;
1268 basis = 0;
1269 basisend = 0;
1270 return old;
1273 /* Free all elements of the given configuration list */
1274 void Configlist_eat(cfp)
1275 struct config *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);
1283 deleteconfig(cfp);
1285 return;
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)
1296 char *msg;
1297 int min;
1298 int max;
1300 int i,spot;
1301 char c;
1302 for(i=spot=min; i<=max; i++){
1303 c = msg[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;
1310 return spot;
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
1316 ** of the line.
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];
1324 int errmsgsize;
1325 int prefixsize;
1326 int availablewidth;
1327 va_list ap;
1328 int end, restart, base;
1330 va_start(ap, format);
1331 /* Prepare a prefix to be prepended to every output line */
1332 if( lineno>0 ){
1333 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1334 }else{
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);
1342 va_end(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 */
1350 base = 0;
1351 while( errmsg[base]!=0 ){
1352 end = restart = findbreak(&errmsg[base],0,availablewidth);
1353 restart += base;
1354 while( errmsg[restart]==' ' ) restart++;
1355 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1356 base = restart;
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");
1369 exit(1);
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){
1379 char **paz;
1380 nDefine++;
1381 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1382 if( azDefine==0 ){
1383 fprintf(stderr,"out of memory\n");
1384 exit(1);
1386 paz = &azDefine[nDefine-1];
1387 *paz = malloc( strlen(z)+1 );
1388 if( *paz==0 ){
1389 fprintf(stderr,"out of memory\n");
1390 exit(1);
1392 strcpy(*paz, z);
1393 for(z=*paz; *z && *z!='='; z++){}
1394 *z = 0;
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."},
1418 {OPT_FLAG,0,0,0}
1420 int i;
1421 struct lemon lem;
1423 OptInit(argv,options,stderr);
1424 if( version ){
1425 printf("Lemon version 1.0\n");
1426 exit(0);
1428 if( OptNArgs()!=1 ){
1429 fprintf(stderr,"Exactly one filename argument is required.\n");
1430 exit(1);
1432 memset(&lem, 0, sizeof(lem));
1433 lem.errorcnt = 0;
1435 /* Initialize the machine */
1436 Strsafe_init();
1437 Symbol_init();
1438 State_init();
1439 lem.argv0 = argv[0];
1440 lem.filename = OptArg(0);
1441 lem.basisflag = basisflag;
1442 Symbol_new("$");
1443 lem.errsym = Symbol_new("error");
1444 lem.errsym->useCnt = 0;
1446 /* Parse the input file */
1447 Parse(&lem);
1448 if( lem.errorcnt ) exit(lem.errorcnt);
1449 if( lem.nrule==0 ){
1450 fprintf(stderr,"Empty grammar.\n");
1451 exit(1);
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++);
1463 lem.nterminal = i;
1465 /* Generate a reprint of the grammar, if requested on the command line */
1466 if( rpflag ){
1467 Reprint(&lem);
1468 }else{
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
1476 ** nonterminal */
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 */
1481 lem.nstate = 0;
1482 FindStates(&lem);
1483 lem.sorted = State_arrayof();
1485 /* Tie up loose ends on the propagation links */
1486 FindLinks(&lem);
1488 /* Compute the follow set of every reducible configuration */
1489 FindFollowSets(&lem);
1491 /* Compute the action tables */
1492 FindActions(&lem);
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. */
1499 ResortStates(&lem);
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);
1512 if( statistics ){
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.
1525 ** USAGE:
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
1539 ** after sorting.
1541 ** ALGORITHM:
1542 ** Merge-sort.
1546 ** Return a pointer to the next structure in the linked list.
1548 #define NEXT(A) (*(char**)(((unsigned long)A)+offset))
1551 ** Inputs:
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.
1557 ** Return Value:
1558 ** A pointer to the head of a sorted list containing the elements
1559 ** of both a and b.
1561 ** Side effects:
1562 ** The "next" pointers for elements in the lists a and b are
1563 ** changed.
1565 static char *merge(
1566 char *a,
1567 char *b,
1568 int (*cmp)(const char*,const char*),
1569 int offset
1571 char *ptr, *head;
1573 if( a==0 ){
1574 head = b;
1575 }else if( b==0 ){
1576 head = a;
1577 }else{
1578 if( (*cmp)(a,b)<0 ){
1579 ptr = a;
1580 a = NEXT(a);
1581 }else{
1582 ptr = b;
1583 b = NEXT(b);
1585 head = ptr;
1586 while( a && b ){
1587 if( (*cmp)(a,b)<0 ){
1588 NEXT(ptr) = a;
1589 ptr = a;
1590 a = NEXT(a);
1591 }else{
1592 NEXT(ptr) = b;
1593 ptr = b;
1594 b = NEXT(b);
1597 if( a ) NEXT(ptr) = a;
1598 else NEXT(ptr) = b;
1600 return head;
1604 ** Inputs:
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.
1609 ** Return Value:
1610 ** A pointer to the head of a sorted list containing the elements
1611 ** orginally in list.
1613 ** Side effects:
1614 ** The "next" pointers for elements in list are changed.
1616 #define LISTSIZE 30
1617 static char *msort(
1618 char *list,
1619 char **next,
1620 int (*cmp)(const char*,const char*)
1622 unsigned long offset;
1623 char *ep;
1624 char *set[LISTSIZE];
1625 int i;
1626 offset = (unsigned long)next - (unsigned long)list;
1627 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1628 while( list ){
1629 ep = list;
1630 list = NEXT(list);
1631 NEXT(ep) = 0;
1632 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1633 ep = merge(ep,set[i],cmp,offset);
1634 set[i] = 0;
1636 set[i] = ep;
1638 ep = 0;
1639 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1640 return ep;
1642 /************************ From the file "option.c" **************************/
1643 static char **argv;
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)
1654 int n;
1655 int k;
1656 FILE *err;
1658 int spcnt, i;
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;
1665 spcnt += k;
1666 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1667 if( spcnt<20 ){
1668 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1669 }else{
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)
1679 int n;
1681 int i;
1682 int dashdash = 0;
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;
1687 n--;
1689 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1692 return -1;
1695 static char emsg[] = "Command line syntax error: ";
1698 ** Process a flag command line argument.
1700 static int handleflags(i,err)
1701 int i;
1702 FILE *err;
1704 int v;
1705 int errcnt = 0;
1706 int j;
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 ){
1712 if( err ){
1713 fprintf(err,"%sundefined option.\n",emsg);
1714 errline(i,1,err);
1716 errcnt++;
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]);
1723 }else{
1724 if( err ){
1725 fprintf(err,"%smissing argument on switch.\n",emsg);
1726 errline(i,1,err);
1728 errcnt++;
1730 return errcnt;
1734 ** Process a command line switch which has an argument.
1736 static int handleswitch(i,err)
1737 int i;
1738 FILE *err;
1740 int lv = 0;
1741 double dv = 0.0;
1742 char *sv = 0, *end;
1743 char *cp;
1744 int j;
1745 int errcnt = 0;
1746 cp = strchr(argv[i],'=');
1747 assert( cp!=0 );
1748 *cp = 0;
1749 for(j=0; op[j].label; j++){
1750 if( strcmp(argv[i],op[j].label)==0 ) break;
1752 *cp = '=';
1753 if( op[j].label==0 ){
1754 if( err ){
1755 fprintf(err,"%sundefined option.\n",emsg);
1756 errline(i,0,err);
1758 errcnt++;
1759 }else{
1760 cp++;
1761 switch( op[j].type ){
1762 case OPT_FLAG:
1763 case OPT_FFLAG:
1764 if( err ){
1765 fprintf(err,"%soption requires an argument.\n",emsg);
1766 errline(i,0,err);
1768 errcnt++;
1769 break;
1770 case OPT_DBL:
1771 case OPT_FDBL:
1772 dv = strtod(cp,&end);
1773 if( *end ){
1774 if( err ){
1775 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
1776 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
1778 errcnt++;
1780 break;
1781 case OPT_INT:
1782 case OPT_FINT:
1783 lv = strtol(cp,&end,0);
1784 if( *end ){
1785 if( err ){
1786 fprintf(err,"%sillegal character in integer argument.\n",emsg);
1787 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
1789 errcnt++;
1791 break;
1792 case OPT_STR:
1793 case OPT_FSTR:
1794 sv = cp;
1795 break;
1797 switch( op[j].type ){
1798 case OPT_FLAG:
1799 case OPT_FFLAG:
1800 break;
1801 case OPT_DBL:
1802 *(double*)(op[j].arg) = dv;
1803 break;
1804 case OPT_FDBL:
1805 (*(void(*)())(op[j].arg))(dv);
1806 break;
1807 case OPT_INT:
1808 *(int*)(op[j].arg) = lv;
1809 break;
1810 case OPT_FINT:
1811 (*(void(*)())(op[j].arg))((int)lv);
1812 break;
1813 case OPT_STR:
1814 *(char**)(op[j].arg) = sv;
1815 break;
1816 case OPT_FSTR:
1817 (*(void(*)())(op[j].arg))(sv);
1818 break;
1821 return errcnt;
1824 int OptInit(a,o,err)
1825 char **a;
1826 struct s_options *o;
1827 FILE *err;
1829 int errcnt = 0;
1830 argv = a;
1831 op = o;
1832 errstream = err;
1833 if( argv && *argv && op ){
1834 int i;
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);
1843 if( errcnt>0 ){
1844 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
1845 OptPrint();
1846 exit(1);
1848 return 0;
1851 int OptNArgs(){
1852 int cnt = 0;
1853 int dashdash = 0;
1854 int i;
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;
1861 return cnt;
1864 char *OptArg(n)
1865 int n;
1867 int i;
1868 i = argindex(n);
1869 return i>=0 ? argv[i] : 0;
1872 void OptErr(n)
1873 int n;
1875 int i;
1876 i = argindex(n);
1877 if( i>=0 ) errline(i,0,errstream);
1880 void OptPrint(){
1881 int i;
1882 int max, len;
1883 max = 0;
1884 for(i=0; op[i].label; i++){
1885 len = strlen(op[i].label) + 1;
1886 switch( op[i].type ){
1887 case OPT_FLAG:
1888 case OPT_FFLAG:
1889 break;
1890 case OPT_INT:
1891 case OPT_FINT:
1892 len += 9; /* length of "<integer>" */
1893 break;
1894 case OPT_DBL:
1895 case OPT_FDBL:
1896 len += 6; /* length of "<real>" */
1897 break;
1898 case OPT_STR:
1899 case OPT_FSTR:
1900 len += 8; /* length of "<string>" */
1901 break;
1903 if( len>max ) max = len;
1905 for(i=0; op[i].label; i++){
1906 switch( op[i].type ){
1907 case OPT_FLAG:
1908 case OPT_FFLAG:
1909 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1910 break;
1911 case OPT_INT:
1912 case OPT_FINT:
1913 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
1914 (int)(max-strlen(op[i].label)-9),"",op[i].message);
1915 break;
1916 case OPT_DBL:
1917 case OPT_FDBL:
1918 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
1919 (int)(max-strlen(op[i].label)-6),"",op[i].message);
1920 break;
1921 case OPT_STR:
1922 case OPT_FSTR:
1923 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
1924 (int)(max-strlen(op[i].label)-8),"",op[i].message);
1925 break;
1929 /*********************** From the file "parse.c" ****************************/
1931 ** Input file parser for the LEMON parser generator.
1934 /* The state of the parser */
1935 struct pstate {
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 */
1941 enum e_state {
1942 INITIALIZE,
1943 WAITING_FOR_DECL_OR_RULE,
1944 WAITING_FOR_DECL_KEYWORD,
1945 WAITING_FOR_DECL_ARG,
1946 WAITING_FOR_PRECEDENCE_SYMBOL,
1947 WAITING_FOR_ARROW,
1948 IN_RHS,
1949 LHS_ALIAS_1,
1950 LHS_ALIAS_2,
1951 LHS_ALIAS_3,
1952 RHS_ALIAS_1,
1953 RHS_ALIAS_2,
1954 PRECEDENCE_MARK_1,
1955 PRECEDENCE_MARK_2,
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)
1981 struct pstate *psp;
1983 char *x;
1984 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1985 #if 0
1986 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1987 x,psp->state);
1988 #endif
1989 switch( psp->state ){
1990 case INITIALIZE:
1991 psp->prevrule = 0;
1992 psp->preccounter = 0;
1993 psp->firstrule = psp->lastrule = 0;
1994 psp->gp->nrule = 0;
1995 /* Fall thru to next case */
1996 case WAITING_FOR_DECL_OR_RULE:
1997 if( x[0]=='%' ){
1998 psp->state = WAITING_FOR_DECL_KEYWORD;
1999 }else if( islower(x[0]) ){
2000 psp->lhs = Symbol_new(x);
2001 psp->nrhs = 0;
2002 psp->lhsalias = 0;
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.");
2009 psp->errorcnt++;
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.");
2014 psp->errorcnt++;
2015 }else{
2016 psp->prevrule->line = psp->tokenlineno;
2017 psp->prevrule->code = &x[1];
2019 }else if( x[0]=='[' ){
2020 psp->state = PRECEDENCE_MARK_1;
2021 }else{
2022 ErrorMsg(psp->filename,psp->tokenlineno,
2023 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2025 psp->errorcnt++;
2027 break;
2028 case PRECEDENCE_MARK_1:
2029 if( !isupper(x[0]) ){
2030 ErrorMsg(psp->filename,psp->tokenlineno,
2031 "The precedence symbol must be a terminal.");
2032 psp->errorcnt++;
2033 }else if( psp->prevrule==0 ){
2034 ErrorMsg(psp->filename,psp->tokenlineno,
2035 "There is no prior rule to assign precedence \"[%s]\".",x);
2036 psp->errorcnt++;
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.");
2041 psp->errorcnt++;
2042 }else{
2043 psp->prevrule->precsym = Symbol_new(x);
2045 psp->state = PRECEDENCE_MARK_2;
2046 break;
2047 case PRECEDENCE_MARK_2:
2048 if( x[0]!=']' ){
2049 ErrorMsg(psp->filename,psp->tokenlineno,
2050 "Missing \"]\" on precedence mark.");
2051 psp->errorcnt++;
2053 psp->state = WAITING_FOR_DECL_OR_RULE;
2054 break;
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;
2060 }else{
2061 ErrorMsg(psp->filename,psp->tokenlineno,
2062 "Expected to see a \":\" following the LHS symbol \"%s\".",
2063 psp->lhs->name);
2064 psp->errorcnt++;
2065 psp->state = RESYNC_AFTER_RULE_ERROR;
2067 break;
2068 case LHS_ALIAS_1:
2069 if( isalpha(x[0]) ){
2070 psp->lhsalias = x;
2071 psp->state = LHS_ALIAS_2;
2072 }else{
2073 ErrorMsg(psp->filename,psp->tokenlineno,
2074 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2075 x,psp->lhs->name);
2076 psp->errorcnt++;
2077 psp->state = RESYNC_AFTER_RULE_ERROR;
2079 break;
2080 case LHS_ALIAS_2:
2081 if( x[0]==')' ){
2082 psp->state = LHS_ALIAS_3;
2083 }else{
2084 ErrorMsg(psp->filename,psp->tokenlineno,
2085 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2086 psp->errorcnt++;
2087 psp->state = RESYNC_AFTER_RULE_ERROR;
2089 break;
2090 case LHS_ALIAS_3:
2091 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2092 psp->state = IN_RHS;
2093 }else{
2094 ErrorMsg(psp->filename,psp->tokenlineno,
2095 "Missing \"->\" following: \"%s(%s)\".",
2096 psp->lhs->name,psp->lhsalias);
2097 psp->errorcnt++;
2098 psp->state = RESYNC_AFTER_RULE_ERROR;
2100 break;
2101 case IN_RHS:
2102 if( x[0]=='.' ){
2103 struct rule *rp;
2104 rp = (struct rule *)calloc( sizeof(struct rule) +
2105 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
2106 if( rp==0 ){
2107 ErrorMsg(psp->filename,psp->tokenlineno,
2108 "Can't allocate enough memory for this rule.");
2109 psp->errorcnt++;
2110 psp->prevrule = 0;
2111 }else{
2112 int i;
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];
2120 rp->lhs = psp->lhs;
2121 rp->lhsalias = psp->lhsalias;
2122 rp->nrhs = psp->nrhs;
2123 rp->code = 0;
2124 rp->precsym = 0;
2125 rp->index = psp->gp->nrule++;
2126 rp->nextlhs = rp->lhs->rule;
2127 rp->lhs->rule = rp;
2128 rp->next = 0;
2129 if( psp->firstrule==0 ){
2130 psp->firstrule = psp->lastrule = rp;
2131 }else{
2132 psp->lastrule->next = rp;
2133 psp->lastrule = rp;
2135 psp->prevrule = 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\".",
2143 psp->errorcnt++;
2144 psp->state = RESYNC_AFTER_RULE_ERROR;
2145 }else{
2146 psp->rhs[psp->nrhs] = Symbol_new(x);
2147 psp->alias[psp->nrhs] = 0;
2148 psp->nrhs++;
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;
2157 msp->nsubsym = 1;
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;
2163 msp->nsubsym++;
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");
2169 psp->errorcnt++;
2171 }else if( x[0]=='(' && psp->nrhs>0 ){
2172 psp->state = RHS_ALIAS_1;
2173 }else{
2174 ErrorMsg(psp->filename,psp->tokenlineno,
2175 "Illegal character on RHS of rule: \"%s\".",x);
2176 psp->errorcnt++;
2177 psp->state = RESYNC_AFTER_RULE_ERROR;
2179 break;
2180 case RHS_ALIAS_1:
2181 if( isalpha(x[0]) ){
2182 psp->alias[psp->nrhs-1] = x;
2183 psp->state = RHS_ALIAS_2;
2184 }else{
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);
2188 psp->errorcnt++;
2189 psp->state = RESYNC_AFTER_RULE_ERROR;
2191 break;
2192 case RHS_ALIAS_2:
2193 if( x[0]==')' ){
2194 psp->state = IN_RHS;
2195 }else{
2196 ErrorMsg(psp->filename,psp->tokenlineno,
2197 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2198 psp->errorcnt++;
2199 psp->state = RESYNC_AFTER_RULE_ERROR;
2201 break;
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 ){
2247 psp->preccounter++;
2248 psp->declassoc = LEFT;
2249 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2250 }else if( strcmp(x,"right")==0 ){
2251 psp->preccounter++;
2252 psp->declassoc = RIGHT;
2253 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2254 }else if( strcmp(x,"nonassoc")==0 ){
2255 psp->preccounter++;
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 ){
2263 psp->fallback = 0;
2264 psp->state = WAITING_FOR_FALLBACK_ID;
2265 }else if( strcmp(x,"wildcard")==0 ){
2266 psp->state = WAITING_FOR_WILDCARD_ID;
2267 }else{
2268 ErrorMsg(psp->filename,psp->tokenlineno,
2269 "Unknown declaration keyword: \"%%%s\".",x);
2270 psp->errorcnt++;
2271 psp->state = RESYNC_AFTER_DECL_ERROR;
2273 }else{
2274 ErrorMsg(psp->filename,psp->tokenlineno,
2275 "Illegal declaration keyword: \"%s\".",x);
2276 psp->errorcnt++;
2277 psp->state = RESYNC_AFTER_DECL_ERROR;
2279 break;
2280 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2281 if( !isalpha(x[0]) ){
2282 ErrorMsg(psp->filename,psp->tokenlineno,
2283 "Symbol name missing after %destructor keyword");
2284 psp->errorcnt++;
2285 psp->state = RESYNC_AFTER_DECL_ERROR;
2286 }else{
2287 struct symbol *sp = Symbol_new(x);
2288 psp->declargslot = &sp->destructor;
2289 psp->decllnslot = &sp->destructorln;
2290 psp->state = WAITING_FOR_DECL_ARG;
2292 break;
2293 case WAITING_FOR_DATATYPE_SYMBOL:
2294 if( !isalpha(x[0]) ){
2295 ErrorMsg(psp->filename,psp->tokenlineno,
2296 "Symbol name missing after %destructor keyword");
2297 psp->errorcnt++;
2298 psp->state = RESYNC_AFTER_DECL_ERROR;
2299 }else{
2300 struct symbol *sp = Symbol_new(x);
2301 psp->declargslot = &sp->datatype;
2302 psp->decllnslot = 0;
2303 psp->state = WAITING_FOR_DECL_ARG;
2305 break;
2306 case WAITING_FOR_PRECEDENCE_SYMBOL:
2307 if( x[0]=='.' ){
2308 psp->state = WAITING_FOR_DECL_OR_RULE;
2309 }else if( isupper(x[0]) ){
2310 struct symbol *sp;
2311 sp = Symbol_new(x);
2312 if( sp->prec>=0 ){
2313 ErrorMsg(psp->filename,psp->tokenlineno,
2314 "Symbol \"%s\" has already be given a precedence.",x);
2315 psp->errorcnt++;
2316 }else{
2317 sp->prec = psp->preccounter;
2318 sp->assoc = psp->declassoc;
2320 }else{
2321 ErrorMsg(psp->filename,psp->tokenlineno,
2322 "Can't assign a precedence to \"%s\".",x);
2323 psp->errorcnt++;
2325 break;
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);
2332 psp->errorcnt++;
2333 psp->state = RESYNC_AFTER_DECL_ERROR;
2334 }else{
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;
2339 }else{
2340 ErrorMsg(psp->filename,psp->tokenlineno,
2341 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2342 psp->errorcnt++;
2343 psp->state = RESYNC_AFTER_DECL_ERROR;
2345 break;
2346 case WAITING_FOR_FALLBACK_ID:
2347 if( x[0]=='.' ){
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);
2352 psp->errorcnt++;
2353 }else{
2354 struct symbol *sp = Symbol_new(x);
2355 if( psp->fallback==0 ){
2356 psp->fallback = sp;
2357 }else if( sp->fallback ){
2358 ErrorMsg(psp->filename, psp->tokenlineno,
2359 "More than one fallback assigned to token %s", x);
2360 psp->errorcnt++;
2361 }else{
2362 sp->fallback = psp->fallback;
2363 psp->gp->has_fallback = 1;
2366 break;
2367 case WAITING_FOR_WILDCARD_ID:
2368 if( x[0]=='.' ){
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);
2373 psp->errorcnt++;
2374 }else{
2375 struct symbol *sp = Symbol_new(x);
2376 if( psp->gp->wildcard==0 ){
2377 psp->gp->wildcard = sp;
2378 }else{
2379 ErrorMsg(psp->filename, psp->tokenlineno,
2380 "Extra wildcard to token: %s", x);
2381 psp->errorcnt++;
2384 break;
2385 case RESYNC_AFTER_RULE_ERROR:
2386 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2387 ** break; */
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;
2391 break;
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){
2401 int i, j, k, n;
2402 int exclude = 0;
2403 int start = 0;
2404 int lineno = 1;
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]) ){
2410 if( exclude ){
2411 exclude--;
2412 if( exclude==0 ){
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])) ){
2419 if( exclude ){
2420 exclude++;
2421 }else{
2422 for(j=i+7; isspace(z[j]); j++){}
2423 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2424 exclude = 1;
2425 for(k=0; k<nDefine; k++){
2426 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2427 exclude = 0;
2428 break;
2431 if( z[i+3]=='n' ) exclude = !exclude;
2432 if( exclude ){
2433 start = i;
2434 start_lineno = lineno;
2437 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2440 if( exclude ){
2441 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2442 exit(1);
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".
2451 void Parse(gp)
2452 struct lemon *gp;
2454 struct pstate ps;
2455 FILE *fp;
2456 char *filebuf;
2457 int filesize;
2458 int lineno;
2459 int c;
2460 char *cp, *nextcp;
2461 int startline = 0;
2463 memset(&ps, '\0', sizeof(ps));
2464 ps.gp = gp;
2465 ps.filename = gp->filename;
2466 ps.errorcnt = 0;
2467 ps.state = INITIALIZE;
2469 /* Begin by reading the input file */
2470 fp = fopen(ps.filename,"rb");
2471 if( fp==0 ){
2472 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2473 gp->errorcnt++;
2474 return;
2476 fseek(fp,0,2);
2477 filesize = ftell(fp);
2478 rewind(fp);
2479 filebuf = (char *)malloc( filesize+1 );
2480 if( filebuf==0 ){
2481 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2482 filesize+1);
2483 gp->errorcnt++;
2484 return;
2486 if( fread(filebuf,1,filesize,fp)!=filesize ){
2487 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2488 filesize);
2489 free(filebuf);
2490 gp->errorcnt++;
2491 return;
2493 fclose(fp);
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 */
2500 lineno = 1;
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 */
2505 cp+=2;
2506 while( (c= *cp)!=0 && c!='\n' ) cp++;
2507 continue;
2509 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2510 cp+=2;
2511 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2512 if( c=='\n' ) lineno++;
2513 cp++;
2515 if( c ) cp++;
2516 continue;
2518 ps.tokenstart = cp; /* Mark the beginning of the token */
2519 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2520 if( c=='\"' ){ /* String literals */
2521 cp++;
2522 while( (c= *cp)!=0 && c!='\"' ){
2523 if( c=='\n' ) lineno++;
2524 cp++;
2526 if( c==0 ){
2527 ErrorMsg(ps.filename,startline,
2528 "String starting on this line is not terminated before the end of the file.");
2529 ps.errorcnt++;
2530 nextcp = cp;
2531 }else{
2532 nextcp = cp+1;
2534 }else if( c=='{' ){ /* A block of C code */
2535 int level;
2536 cp++;
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 */
2542 int prevc;
2543 cp = &cp[2];
2544 prevc = 0;
2545 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2546 if( c=='\n' ) lineno++;
2547 prevc = c;
2548 cp++;
2550 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2551 cp = &cp[2];
2552 while( (c= *cp)!=0 && c!='\n' ) cp++;
2553 if( c ) lineno++;
2554 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2555 int startchar, prevc;
2556 startchar = c;
2557 prevc = 0;
2558 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2559 if( c=='\n' ) lineno++;
2560 if( prevc=='\\' ) prevc = 0;
2561 else prevc = c;
2565 if( c==0 ){
2566 ErrorMsg(ps.filename,ps.tokenlineno,
2567 "C code starting on this line is not terminated before the end of the file.");
2568 ps.errorcnt++;
2569 nextcp = cp;
2570 }else{
2571 nextcp = cp+1;
2573 }else if( isalnum(c) ){ /* Identifiers */
2574 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2575 nextcp = cp;
2576 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2577 cp += 3;
2578 nextcp = cp;
2579 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2580 cp += 2;
2581 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2582 nextcp = cp;
2583 }else{ /* All other (one character) operators */
2584 cp++;
2585 nextcp = cp;
2587 c = *cp;
2588 *cp = 0; /* Null terminate the token */
2589 parseonetoken(&ps); /* Parse the token */
2590 *cp = c; /* Restore the buffer */
2591 cp = nextcp;
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(){
2606 struct plink *new;
2608 if( plink_freelist==0 ){
2609 int i;
2610 int amt = 100;
2611 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
2612 if( plink_freelist==0 ){
2613 fprintf(stderr,
2614 "Unable to allocate memory for a new follow-set propagation link.\n");
2615 exit(1);
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;
2622 return new;
2625 /* Add a plink to a plink list */
2626 void Plink_add(plpp,cfp)
2627 struct plink **plpp;
2628 struct config *cfp;
2630 struct plink *new;
2631 new = Plink_new();
2632 new->next = *plpp;
2633 *plpp = new;
2634 new->cfp = cfp;
2637 /* Transfer every plink on the list "from" to the list "to" */
2638 void Plink_copy(to,from)
2639 struct plink **to;
2640 struct plink *from;
2642 struct plink *nextpl;
2643 while( from ){
2644 nextpl = from->next;
2645 from->next = *to;
2646 *to = from;
2647 from = nextpl;
2651 /* Delete every plink on the list */
2652 void Plink_delete(plp)
2653 struct plink *plp;
2655 struct plink *nextpl;
2657 while( plp ){
2658 nextpl = plp->next;
2659 plp->next = plink_freelist;
2660 plink_freelist = plp;
2661 plp = nextpl;
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
2671 ** function.
2673 PRIVATE char *file_makename(lemp,suffix)
2674 struct lemon *lemp;
2675 char *suffix;
2677 char *name;
2678 char *cp;
2680 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2681 if( name==0 ){
2682 fprintf(stderr,"Can't allocate space for a filename.\n");
2683 exit(1);
2685 strcpy(name,lemp->filename);
2686 cp = strrchr(name,'.');
2687 if( cp ) *cp = 0;
2688 strcat(name,suffix);
2689 return name;
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
2694 ** to the stream */
2695 PRIVATE FILE *file_open(lemp,suffix,mode)
2696 struct lemon *lemp;
2697 char *suffix;
2698 char *mode;
2700 FILE *fp;
2702 if( lemp->outname ) free(lemp->outname);
2703 lemp->outname = file_makename(lemp, suffix);
2704 /* LLVM LOCAL begin */
2705 #if 0
2706 fp = fopen(lemp->outname,mode);
2707 #else
2708 if(*mode == 'r') return NULL;
2709 fp = stdout;
2710 #endif
2711 /* LLVM LOCAL end */
2712 if( fp==0 && *mode=='w' ){
2713 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2714 lemp->errorcnt++;
2715 return 0;
2717 return fp;
2720 /* Duplicate the input file without comments and without actions
2721 ** on rules */
2722 void Reprint(lemp)
2723 struct lemon *lemp;
2725 struct rule *rp;
2726 struct symbol *sp;
2727 int i, j, maxlen, len, ncolumns, skip;
2728 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2729 maxlen = 10;
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++){
2739 printf("//");
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);
2745 printf("\n");
2747 for(rp=lemp->rule; rp; rp=rp->next){
2748 printf("%s",rp->lhs->name);
2749 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2750 printf(" ::=");
2751 for(i=0; i<rp->nrhs; i++){
2752 sp = rp->rhs[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]); */
2761 printf(".");
2762 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2763 /* if( rp->code ) printf("\n %s",rp->code); */
2764 printf("\n");
2768 void ConfigPrint(fp,cfp)
2769 FILE *fp;
2770 struct config *cfp;
2772 struct rule *rp;
2773 struct symbol *sp;
2774 int i, j;
2775 rp = cfp->rp;
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;
2780 sp = rp->rhs[i];
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);
2790 /* #define TEST */
2791 #if 0
2792 /* Print a set */
2793 PRIVATE void SetPrint(out,set,lemp)
2794 FILE *out;
2795 char *set;
2796 struct lemon *lemp;
2798 int i;
2799 char *spacer;
2800 spacer = "";
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);
2805 spacer = " ";
2808 fprintf(out,"]\n");
2811 /* Print a plink chain */
2812 PRIVATE void PlinkPrint(out,plp,tag)
2813 FILE *out;
2814 struct plink *plp;
2815 char *tag;
2817 while( plp ){
2818 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
2819 ConfigPrint(out,plp->cfp);
2820 fprintf(out,"\n");
2821 plp = plp->next;
2824 #endif
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){
2830 int result = 1;
2831 switch( ap->type ){
2832 case SHIFT:
2833 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
2834 break;
2835 case REDUCE:
2836 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2837 break;
2838 case ACCEPT:
2839 fprintf(fp,"%*s accept",indent,ap->sp->name);
2840 break;
2841 case ERROR:
2842 fprintf(fp,"%*s error",indent,ap->sp->name);
2843 break;
2844 case SRCONFLICT:
2845 case RRCONFLICT:
2846 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2847 indent,ap->sp->name,ap->x.rp->index);
2848 break;
2849 case SSCONFLICT:
2850 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2851 indent,ap->sp->name,ap->x.stp->statenum);
2852 break;
2853 case SH_RESOLVED:
2854 case RD_RESOLVED:
2855 case NOT_USED:
2856 result = 0;
2857 break;
2859 return result;
2862 /* Generate the "y.output" log file */
2863 void ReportOutput(lemp)
2864 struct lemon *lemp;
2866 int i;
2867 struct state *stp;
2868 struct config *cfp;
2869 struct action *ap;
2870 FILE *fp;
2872 fp = file_open(lemp,".out","wb");
2873 if( fp==0 ) return;
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;
2878 else cfp=stp->cfp;
2879 while( cfp ){
2880 char buf[20];
2881 if( cfp->dot==cfp->rp->nrhs ){
2882 sprintf(buf,"(%d)",cfp->rp->index);
2883 fprintf(fp," %5s ",buf);
2884 }else{
2885 fprintf(fp," ");
2887 ConfigPrint(fp,cfp);
2888 fprintf(fp,"\n");
2889 #if 0
2890 SetPrint(fp,cfp->fws,lemp);
2891 PlinkPrint(fp,cfp->fplp,"To ");
2892 PlinkPrint(fp,cfp->bplp,"From");
2893 #endif
2894 if( lemp->basisflag ) cfp=cfp->bp;
2895 else cfp=cfp->next;
2897 fprintf(fp,"\n");
2898 for(ap=stp->ap; ap; ap=ap->next){
2899 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2901 fprintf(fp,"\n");
2903 fprintf(fp, "----------------------------------------------------\n");
2904 fprintf(fp, "Symbols:\n");
2905 for(i=0; i<lemp->nsymbol; i++){
2906 int j;
2907 struct symbol *sp;
2909 sp = lemp->symbols[i];
2910 fprintf(fp, " %3d: %s", i, sp->name);
2911 if( sp->type==NONTERMINAL ){
2912 fprintf(fp, ":");
2913 if( sp->lambda ){
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);
2922 fprintf(fp, "\n");
2924 #if 0
2925 fclose(fp);
2926 #endif
2927 return;
2930 /* Search for the file "name" which is in the same directory as
2931 ** the exacutable */
2932 PRIVATE char *pathsearch(argv0,name,modemask)
2933 char *argv0;
2934 char *name;
2935 int modemask;
2937 char *pathlist;
2938 char *path,*cp;
2939 char c;
2941 #ifdef __WIN32__
2942 cp = strrchr(argv0,'\\');
2943 #else
2944 cp = strrchr(argv0,'/');
2945 #endif
2946 if( cp ){
2947 c = *cp;
2948 *cp = 0;
2949 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2950 if( path ) sprintf(path,"%s/%s",argv0,name);
2951 *cp = c;
2952 }else{
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 );
2957 if( path!=0 ){
2958 while( *pathlist ){
2959 cp = strchr(pathlist,':');
2960 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2961 c = *cp;
2962 *cp = 0;
2963 sprintf(path,"%s/%s",pathlist,name);
2964 *cp = c;
2965 if( c==0 ) pathlist = "";
2966 else pathlist = &cp[1];
2967 if( access(path,modemask)==0 ) break;
2971 return path;
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)
2979 struct lemon *lemp;
2980 struct action *ap;
2982 int act;
2983 switch( ap->type ){
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;
2990 return act;
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
2998 ** tracked.
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)
3004 char *name;
3005 FILE *in;
3006 FILE *out;
3007 int *lineno;
3009 int i, iStart;
3010 char line[LINESIZE];
3011 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3012 (*lineno)++;
3013 iStart = 0;
3014 if( name ){
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);
3021 i += 4;
3022 iStart = i+1;
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)
3033 struct lemon *lemp;
3035 static char templatename[] = "lempar.c";
3036 char buf[1000];
3037 FILE *in;
3038 char *tpltname;
3039 char *cp;
3041 cp = strrchr(lemp->filename,'.');
3042 if( cp ){
3043 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
3044 }else{
3045 sprintf(buf,"%s.lt",lemp->filename);
3047 if( access(buf,004)==0 ){
3048 tpltname = buf;
3049 }else if( access(templatename,004)==0 ){
3050 tpltname = templatename;
3051 }else{
3052 tpltname = pathsearch(lemp->filename,templatename,0);
3054 if( tpltname==0 ){
3055 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3056 templatename);
3057 lemp->errorcnt++;
3058 return 0;
3060 in = fopen(tpltname,"rb");
3061 if( in==0 ){
3062 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3063 lemp->errorcnt++;
3064 return 0;
3066 return in;
3069 /* Print a #line directive line to the output file. */
3070 PRIVATE void tplt_linedir(out,lineno,filename)
3071 FILE *out;
3072 int lineno;
3073 char *filename;
3075 filename = mybasename(filename);
3076 fprintf(out,"#line %d \"",lineno);
3077 while( *filename ){
3078 if( *filename == '\\' ) putc('\\',out);
3079 putc(*filename,out);
3080 filename++;
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)
3087 FILE *out;
3088 struct lemon *lemp;
3089 char *str;
3090 int strln;
3091 int *lineno;
3093 if( str==0 ) return;
3094 tplt_linedir(out,strln,lemp->filename);
3095 (*lineno)++;
3096 while( *str ){
3097 if( *str=='\n' ) (*lineno)++;
3098 putc(*str,out);
3099 str++;
3101 if( str[-1]!='\n' ){
3102 putc('\n',out);
3103 (*lineno)++;
3105 tplt_linedir(out,*lineno+2,lemp->outname);
3106 (*lineno)+=2;
3107 return;
3111 ** The following routine emits code for the destructor for the
3112 ** symbol sp
3114 void emit_destructor_code(out,sp,lemp,lineno)
3115 FILE *out;
3116 struct symbol *sp;
3117 struct lemon *lemp;
3118 int *lineno;
3120 char *cp = 0;
3122 int linecnt = 0;
3123 if( sp->type==TERMINAL ){
3124 cp = lemp->tokendest;
3125 if( cp==0 ) return;
3126 tplt_linedir(out,lemp->tokendestln,lemp->filename);
3127 fprintf(out,"{");
3128 }else if( sp->destructor ){
3129 cp = sp->destructor;
3130 tplt_linedir(out,sp->destructorln,lemp->filename);
3131 fprintf(out,"{");
3132 }else if( lemp->vardest ){
3133 cp = lemp->vardest;
3134 if( cp==0 ) return;
3135 tplt_linedir(out,lemp->vardestln,lemp->filename);
3136 fprintf(out,"{");
3137 }else{
3138 assert( 0 ); /* Cannot happen */
3140 for(; *cp; cp++){
3141 if( *cp=='$' && cp[1]=='$' ){
3142 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3143 cp++;
3144 continue;
3146 if( *cp=='\n' ) linecnt++;
3147 fputc(*cp,out);
3149 (*lineno) += 3 + linecnt;
3150 fprintf(out,"}\n");
3151 tplt_linedir(out,*lineno,lemp->outname);
3152 return;
3156 ** Return TRUE (non-zero) if the given symbol has a destructor.
3158 int has_destructor(sp, lemp)
3159 struct symbol *sp;
3160 struct lemon *lemp;
3162 int ret;
3163 if( sp->type==TERMINAL ){
3164 ret = lemp->tokendest!=0;
3165 }else{
3166 ret = lemp->vardest!=0 || sp->destructor!=0;
3168 return ret;
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
3179 ** %d.
3181 ** If n==-1, then the previous character is overwritten.
3183 PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3184 static char *z = 0;
3185 static int alloced = 0;
3186 static int used = 0;
3187 int c;
3188 char zInt[40];
3190 if( zText==0 ){
3191 used = 0;
3192 return z;
3194 if( n<=0 ){
3195 if( n<0 ){
3196 used += n;
3197 assert( used>=0 );
3199 n = strlen(zText);
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 "";
3206 while( n-- > 0 ){
3207 c = *(zText++);
3208 if( c=='%' && n>0 && zText[0]=='d' ){
3209 sprintf(zInt, "%d", p1);
3210 p1 = p2;
3211 strcpy(&z[used], zInt);
3212 used += strlen(&z[used]);
3213 zText++;
3214 n--;
3215 }else{
3216 z[used++] = c;
3219 z[used] = 0;
3220 return z;
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
3226 ** stack.
3228 PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
3229 char *cp, *xp;
3230 int i;
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;
3235 lhsused = 0;
3237 if( rp->code==0 ){
3238 rp->code = "\n";
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]!='_')) ){
3245 char saved;
3246 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3247 saved = *xp;
3248 *xp = 0;
3249 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
3250 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
3251 cp = xp;
3252 lhsused = 1;
3253 }else{
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);
3260 }else{
3261 struct symbol *sp = rp->rhs[i];
3262 int dtnum;
3263 if( sp->type==MULTITERMINAL ){
3264 dtnum = sp->subsym[0]->dtnum;
3265 }else{
3266 dtnum = sp->dtnum;
3268 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
3270 cp = xp;
3271 used[i] = 1;
3272 break;
3276 *xp = saved;
3278 append_str(cp, 1, 0, 0);
3279 } /* End loop */
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);
3286 lemp->errorcnt++;
3289 /* Generate destructor code for RHS symbols which are not used in the
3290 ** reduce code */
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]);
3296 lemp->errorcnt++;
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);
3301 }else{
3302 /* No destructor defined for this term */
3306 if( rp->code ){
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)
3317 FILE *out;
3318 struct rule *rp;
3319 struct lemon *lemp;
3320 int *lineno;
3322 char *cp;
3323 int linecnt = 0;
3325 /* Generate code to do the reduce action */
3326 if( rp->code ){
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++;
3331 } /* End loop */
3332 (*lineno) += 3 + linecnt;
3333 fprintf(out,"}\n");
3334 tplt_linedir(out,*lineno,lemp->outname);
3335 } /* End if( rp->code ) */
3337 return;
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
3345 ** symbol.
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;
3366 maxdtlength = 0;
3367 if( lemp->vartype ){
3368 maxdtlength = strlen(lemp->vartype);
3370 for(i=0; i<lemp->nsymbol; i++){
3371 int len;
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");
3380 exit(1);
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];
3391 char *cp;
3392 if( sp==lemp->errsym ){
3393 sp->dtnum = arraysize+1;
3394 continue;
3396 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
3397 sp->dtnum = 0;
3398 continue;
3400 cp = sp->datatype;
3401 if( cp==0 ) cp = lemp->vartype;
3402 j = 0;
3403 while( isspace(*cp) ) cp++;
3404 while( *cp ) stddt[j++] = *cp++;
3405 while( j>0 && isspace(stddt[j-1]) ) j--;
3406 stddt[j] = 0;
3407 hash = 0;
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;
3415 break;
3417 hash++;
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");
3425 exit(1);
3427 strcpy(types[hash],stddt);
3431 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3432 name = lemp->name ? lemp->name : "Parse";
3433 lineno = *plineno;
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++;
3443 free(types[i]);
3445 if( lemp->errsym->useCnt ){
3446 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3448 free(stddt);
3449 free(types);
3450 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3451 *plineno = 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){
3459 if( lwr>=0 ){
3460 if( upr<=255 ){
3461 return "unsigned char";
3462 }else if( upr<65535 ){
3463 return "unsigned short int";
3464 }else{
3465 return "unsigned int";
3467 }else if( lwr>=-127 && upr<=127 ){
3468 return "signed char";
3469 }else if( lwr>=-32767 && upr<32767 ){
3470 return "short";
3471 }else{
3472 return "int";
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.
3482 struct axset {
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){
3501 int j;
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 ){
3507 int k;
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)
3518 struct lemon *lemp;
3519 int mhflag; /* Output in makeheaders format if true */
3521 FILE *out, *in;
3522 char line[LINESIZE];
3523 int lineno;
3524 struct state *stp;
3525 struct action *ap;
3526 struct rule *rp;
3527 struct acttab *pActtab;
3528 int i, j, n;
3529 char *name;
3530 int mnTknOfst, mxTknOfst;
3531 int mnNtOfst, mxNtOfst;
3532 struct axset *ax;
3534 in = tplt_open(lemp);
3535 if( in==0 ) return;
3536 out = file_open(lemp,".c","wb");
3537 if( out==0 ){
3538 fclose(in);
3539 return;
3541 lineno = 1;
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);
3546 if( mhflag ){
3547 char *name = file_makename(lemp, ".h");
3548 fprintf(out,"#include \"%s\"\n", name); lineno++;
3549 free(name);
3551 tplt_xfer(lemp->name,in,out,&lineno);
3553 /* Generate #defines for all tokens */
3554 if( mhflag ){
3555 char *prefix;
3556 fprintf(out,"#if INTERFACE\n"); lineno++;
3557 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3558 else prefix = "";
3559 for(i=1; i<lemp->nterminal; i++){
3560 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3561 lineno++;
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++;
3581 }else{
3582 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3584 fprintf(out, "#endif\n"); lineno++;
3585 if( mhflag ){
3586 fprintf(out,"#if INTERFACE\n"); lineno++;
3588 name = lemp->name ? lemp->name : "Parse";
3589 if( lemp->arg && lemp->arg[0] ){
3590 int i;
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++;
3600 }else{
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++;
3606 if( mhflag ){
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]));
3634 if( ax==0 ){
3635 fprintf(stderr,"malloc failed\n");
3636 exit(1);
3638 for(i=0; i<lemp->nstate; i++){
3639 stp = lemp->sorted[i];
3640 ax[i*2].stp = stp;
3641 ax[i*2].isTkn = 1;
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++){
3657 stp = ax[i].stp;
3658 if( ax[i].isTkn ){
3659 for(ap=stp->ap; ap; ap=ap->next){
3660 int action;
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;
3669 }else{
3670 for(ap=stp->ap; ap; ap=ap->next){
3671 int action;
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;
3683 free(ax);
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++;
3695 j = 0;
3696 }else{
3697 j++;
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++;
3711 j = 0;
3712 }else{
3713 j++;
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++;
3720 n = lemp->nstate;
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++){
3726 int ofst;
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++;
3734 j = 0;
3735 }else{
3736 j++;
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++;
3743 n = lemp->nstate;
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++){
3749 int ofst;
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++;
3757 j = 0;
3758 }else{
3759 j++;
3762 fprintf(out, "};\n"); lineno++;
3764 /* Output the default action table */
3765 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
3766 n = lemp->nstate;
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++;
3773 j = 0;
3774 }else{
3775 j++;
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);
3788 }else{
3789 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3790 p->name, p->fallback->name);
3792 lineno++;
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++;
3844 dflt_sp = sp;
3846 if( dflt_sp!=0 ){
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){
3893 struct rule *rp2;
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++;
3903 rp2->code = 0;
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);
3926 fclose(in);
3927 #if 0
3928 fclose(out);
3929 #endif
3930 return;
3933 /* Generate a header file for the parser */
3934 void ReportHeader(lemp)
3935 struct lemon *lemp;
3937 FILE *out, *in;
3938 char *prefix;
3939 char line[LINESIZE];
3940 char pattern[LINESIZE];
3941 int i;
3943 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3944 else prefix = "";
3945 in = file_open(lemp,".h","rb");
3946 if( in ){
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;
3951 fclose(in);
3952 if( i==lemp->nterminal ){
3953 /* No change in the file. Don't rewrite it. */
3954 return;
3957 out = file_open(lemp,".h","wb");
3958 if( out ){
3959 for(i=1; i<lemp->nterminal; i++){
3960 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3962 #if 0
3963 fclose(out);
3964 #endif
3966 return;
3969 /* Reduce the size of the action tables, if possible, by making use
3970 ** of defaults.
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)
3977 struct lemon *lemp;
3979 struct state *stp;
3980 struct action *ap, *ap2;
3981 struct rule *rp, *rp2, *rbest;
3982 int nbest, n;
3983 int i;
3984 int usesWildcard;
3986 for(i=0; i<lemp->nstate; i++){
3987 stp = lemp->sorted[i];
3988 nbest = 0;
3989 rbest = 0;
3990 usesWildcard = 0;
3992 for(ap=stp->ap; ap; ap=ap->next){
3993 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
3994 usesWildcard = 1;
3996 if( ap->type!=REDUCE ) continue;
3997 rp = ap->x.rp;
3998 if( rp->lhsStart ) continue;
3999 if( rp==rbest ) continue;
4000 n = 1;
4001 for(ap2=ap->next; ap2; ap2=ap2->next){
4002 if( ap2->type!=REDUCE ) continue;
4003 rp2 = ap2->x.rp;
4004 if( rp2==rbest ) continue;
4005 if( rp2==rp ) n++;
4007 if( n>nbest ){
4008 nbest = n;
4009 rbest = rp;
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
4015 ** lookahead.
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;
4024 assert( ap );
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
4038 ** token actions.
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;
4043 int n;
4045 n = pB->nNtAct - pA->nNtAct;
4046 if( n==0 ){
4047 n = pB->nTknAct - pA->nTknAct;
4049 return n;
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)
4058 struct lemon *lemp;
4060 int i;
4061 struct state *stp;
4062 struct action *ap;
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 ){
4073 stp->nTknAct++;
4074 }else if( ap->sp->index<lemp->nsymbol ){
4075 stp->nNtAct++;
4076 }else{
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 */
4098 void SetSize(n)
4099 int n;
4101 size = n+1;
4104 /* Allocate a new set */
4105 char *SetNew(){
4106 char *s;
4107 s = (char*)calloc( size, 1);
4108 if( s==0 ){
4109 extern void memory_error();
4110 memory_error();
4112 return s;
4115 /* Deallocate a set */
4116 void SetFree(s)
4117 char *s;
4119 free(s);
4122 /* Add a new element to the set. Return TRUE if the element was added
4123 ** and FALSE if it was already there. */
4124 int SetAdd(s,e)
4125 char *s;
4126 int e;
4128 int rv;
4129 assert( e>=0 && e<size );
4130 rv = s[e];
4131 s[e] = 1;
4132 return !rv;
4135 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
4136 int SetUnion(s1,s2)
4137 char *s1;
4138 char *s2;
4140 int i, progress;
4141 progress = 0;
4142 for(i=0; i<size; i++){
4143 if( s2[i]==0 ) continue;
4144 if( s1[i]==0 ){
4145 progress = 1;
4146 s1[i] = 1;
4149 return progress;
4151 /********************** From the file "table.c" ****************************/
4153 ** All code in this file has been automatically generated
4154 ** from a specification in the file
4155 ** "table.q"
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)
4165 char *x;
4167 int h = 0;
4168 while( *x) h = h*13 + *(x++);
4169 return h;
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
4174 ** than one place.
4176 char *Strsafe(y)
4177 char *y;
4179 char *z;
4181 if( y==0 ) return 0;
4182 z = Strsafe_find(y);
4183 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4184 strcpy(z,y);
4185 Strsafe_insert(z);
4187 MemoryCheck(z);
4188 return z;
4191 /* There is one instance of the following structure for each
4192 ** associative array of type "x1".
4194 struct s_x1 {
4195 int size; /* The number of available slots. */
4196 /* Must be a power of 2 greater than or */
4197 /* equal to 1 */
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 */
4210 } x1node;
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(){
4217 if( x1a ) return;
4218 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4219 if( x1a ){
4220 x1a->size = 1024;
4221 x1a->count = 0;
4222 x1a->tbl = (x1node*)malloc(
4223 (sizeof(x1node) + sizeof(x1node*))*1024 );
4224 if( x1a->tbl==0 ){
4225 free(x1a);
4226 x1a = 0;
4227 }else{
4228 int i;
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)
4237 char *data;
4239 x1node *np;
4240 int h;
4241 int ph;
4243 if( x1a==0 ) return 0;
4244 ph = strhash(data);
4245 h = ph & (x1a->size-1);
4246 np = x1a->ht[h];
4247 while( np ){
4248 if( strcmp(np->data,data)==0 ){
4249 /* An existing entry with the same key is found. */
4250 /* Fail because overwrite is not allows. */
4251 return 0;
4253 np = np->next;
4255 if( x1a->count>=x1a->size ){
4256 /* Need to make the hash table bigger */
4257 int i,size;
4258 struct s_x1 array;
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;
4277 free(x1a->tbl);
4278 *x1a = array;
4280 /* Insert the new data */
4281 h = ph & (x1a->size-1);
4282 np = &(x1a->tbl[x1a->count++]);
4283 np->data = data;
4284 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4285 np->next = x1a->ht[h];
4286 x1a->ht[h] = np;
4287 np->from = &(x1a->ht[h]);
4288 return 1;
4291 /* Return a pointer to data assigned to the given key. Return NULL
4292 ** if no such key. */
4293 char *Strsafe_find(key)
4294 char *key;
4296 int h;
4297 x1node *np;
4299 if( x1a==0 ) return 0;
4300 h = strhash(key) & (x1a->size-1);
4301 np = x1a->ht[h];
4302 while( np ){
4303 if( strcmp(np->data,key)==0 ) break;
4304 np = np->next;
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)
4313 char *x;
4315 struct symbol *sp;
4317 sp = Symbol_find(x);
4318 if( sp==0 ){
4319 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
4320 MemoryCheck(sp);
4321 sp->name = Strsafe(x);
4322 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4323 sp->rule = 0;
4324 sp->fallback = 0;
4325 sp->prec = -1;
4326 sp->assoc = UNK;
4327 sp->firstset = 0;
4328 sp->lambda = LEMON_FALSE;
4329 sp->destructor = 0;
4330 sp->datatype = 0;
4331 sp->useCnt = 0;
4332 Symbol_insert(sp,sp->name);
4334 sp->useCnt++;
4335 return sp;
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');
4351 return i1-i2;
4354 /* There is one instance of the following structure for each
4355 ** associative array of type "x2".
4357 struct s_x2 {
4358 int size; /* The number of available slots. */
4359 /* Must be a power of 2 greater than or */
4360 /* equal to 1 */
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 */
4374 } x2node;
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 */
4380 void Symbol_init(){
4381 if( x2a ) return;
4382 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4383 if( x2a ){
4384 x2a->size = 128;
4385 x2a->count = 0;
4386 x2a->tbl = (x2node*)malloc(
4387 (sizeof(x2node) + sizeof(x2node*))*128 );
4388 if( x2a->tbl==0 ){
4389 free(x2a);
4390 x2a = 0;
4391 }else{
4392 int i;
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;
4402 char *key;
4404 x2node *np;
4405 int h;
4406 int ph;
4408 if( x2a==0 ) return 0;
4409 ph = strhash(key);
4410 h = ph & (x2a->size-1);
4411 np = x2a->ht[h];
4412 while( np ){
4413 if( strcmp(np->key,key)==0 ){
4414 /* An existing entry with the same key is found. */
4415 /* Fail because overwrite is not allows. */
4416 return 0;
4418 np = np->next;
4420 if( x2a->count>=x2a->size ){
4421 /* Need to make the hash table bigger */
4422 int i,size;
4423 struct s_x2 array;
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;
4443 free(x2a->tbl);
4444 *x2a = array;
4446 /* Insert the new data */
4447 h = ph & (x2a->size-1);
4448 np = &(x2a->tbl[x2a->count++]);
4449 np->key = key;
4450 np->data = data;
4451 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4452 np->next = x2a->ht[h];
4453 x2a->ht[h] = np;
4454 np->from = &(x2a->ht[h]);
4455 return 1;
4458 /* Return a pointer to data assigned to the given key. Return NULL
4459 ** if no such key. */
4460 struct symbol *Symbol_find(key)
4461 char *key;
4463 int h;
4464 x2node *np;
4466 if( x2a==0 ) return 0;
4467 h = strhash(key) & (x2a->size-1);
4468 np = x2a->ht[h];
4469 while( np ){
4470 if( strcmp(np->key,key)==0 ) break;
4471 np = np->next;
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)
4478 int n;
4480 struct symbol *data;
4481 if( x2a && n>0 && n<=x2a->count ){
4482 data = x2a->tbl[n-1].data;
4483 }else{
4484 data = 0;
4486 return data;
4489 /* Return the size of the array */
4490 int Symbol_count()
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;
4501 int i,size;
4502 if( x2a==0 ) return 0;
4503 size = x2a->count;
4504 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
4505 if( array ){
4506 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4508 return array;
4511 /* Compare two configurations */
4512 int Configcmp(a,b)
4513 struct config *a;
4514 struct config *b;
4516 int x;
4517 x = a->rp->index - b->rp->index;
4518 if( x==0 ) x = a->dot - b->dot;
4519 return x;
4522 /* Compare two states */
4523 PRIVATE int statecmp(a,b)
4524 struct config *a;
4525 struct config *b;
4527 int rc;
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;
4532 if( rc==0 ){
4533 if( a ) rc = 1;
4534 if( b ) rc = -1;
4536 return rc;
4539 /* Hash a state */
4540 PRIVATE int statehash(a)
4541 struct config *a;
4543 int h=0;
4544 while( a ){
4545 h = h*571 + a->rp->index*37 + a->dot;
4546 a = a->bp;
4548 return h;
4551 /* Allocate a new state structure */
4552 struct state *State_new()
4554 struct state *new;
4555 new = (struct state *)calloc(1, sizeof(struct state) );
4556 MemoryCheck(new);
4557 return new;
4560 /* There is one instance of the following structure for each
4561 ** associative array of type "x3".
4563 struct s_x3 {
4564 int size; /* The number of available slots. */
4565 /* Must be a power of 2 greater than or */
4566 /* equal to 1 */
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 */
4580 } x3node;
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 */
4586 void State_init(){
4587 if( x3a ) return;
4588 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4589 if( x3a ){
4590 x3a->size = 128;
4591 x3a->count = 0;
4592 x3a->tbl = (x3node*)malloc(
4593 (sizeof(x3node) + sizeof(x3node*))*128 );
4594 if( x3a->tbl==0 ){
4595 free(x3a);
4596 x3a = 0;
4597 }else{
4598 int i;
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)
4607 struct state *data;
4608 struct config *key;
4610 x3node *np;
4611 int h;
4612 int ph;
4614 if( x3a==0 ) return 0;
4615 ph = statehash(key);
4616 h = ph & (x3a->size-1);
4617 np = x3a->ht[h];
4618 while( np ){
4619 if( statecmp(np->key,key)==0 ){
4620 /* An existing entry with the same key is found. */
4621 /* Fail because overwrite is not allows. */
4622 return 0;
4624 np = np->next;
4626 if( x3a->count>=x3a->size ){
4627 /* Need to make the hash table bigger */
4628 int i,size;
4629 struct s_x3 array;
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;
4649 free(x3a->tbl);
4650 *x3a = array;
4652 /* Insert the new data */
4653 h = ph & (x3a->size-1);
4654 np = &(x3a->tbl[x3a->count++]);
4655 np->key = key;
4656 np->data = data;
4657 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4658 np->next = x3a->ht[h];
4659 x3a->ht[h] = np;
4660 np->from = &(x3a->ht[h]);
4661 return 1;
4664 /* Return a pointer to data assigned to the given key. Return NULL
4665 ** if no such key. */
4666 struct state *State_find(key)
4667 struct config *key;
4669 int h;
4670 x3node *np;
4672 if( x3a==0 ) return 0;
4673 h = statehash(key) & (x3a->size-1);
4674 np = x3a->ht[h];
4675 while( np ){
4676 if( statecmp(np->key,key)==0 ) break;
4677 np = np->next;
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;
4688 int i,size;
4689 if( x3a==0 ) return 0;
4690 size = x3a->count;
4691 array = (struct state **)malloc( sizeof(struct state *)*size );
4692 if( array ){
4693 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4695 return array;
4698 /* Hash a configuration */
4699 PRIVATE int confighash(a)
4700 struct config *a;
4702 int h=0;
4703 h = h*571 + a->rp->index*37 + a->dot;
4704 return h;
4707 /* There is one instance of the following structure for each
4708 ** associative array of type "x4".
4710 struct s_x4 {
4711 int size; /* The number of available slots. */
4712 /* Must be a power of 2 greater than or */
4713 /* equal to 1 */
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 */
4726 } x4node;
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(){
4733 if( x4a ) return;
4734 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4735 if( x4a ){
4736 x4a->size = 64;
4737 x4a->count = 0;
4738 x4a->tbl = (x4node*)malloc(
4739 (sizeof(x4node) + sizeof(x4node*))*64 );
4740 if( x4a->tbl==0 ){
4741 free(x4a);
4742 x4a = 0;
4743 }else{
4744 int i;
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;
4755 x4node *np;
4756 int h;
4757 int ph;
4759 if( x4a==0 ) return 0;
4760 ph = confighash(data);
4761 h = ph & (x4a->size-1);
4762 np = x4a->ht[h];
4763 while( np ){
4764 if( Configcmp(np->data,data)==0 ){
4765 /* An existing entry with the same key is found. */
4766 /* Fail because overwrite is not allows. */
4767 return 0;
4769 np = np->next;
4771 if( x4a->count>=x4a->size ){
4772 /* Need to make the hash table bigger */
4773 int i,size;
4774 struct s_x4 array;
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;
4793 free(x4a->tbl);
4794 *x4a = array;
4796 /* Insert the new data */
4797 h = ph & (x4a->size-1);
4798 np = &(x4a->tbl[x4a->count++]);
4799 np->data = data;
4800 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4801 np->next = x4a->ht[h];
4802 x4a->ht[h] = np;
4803 np->from = &(x4a->ht[h]);
4804 return 1;
4807 /* Return a pointer to data assigned to the given key. Return NULL
4808 ** if no such key. */
4809 struct config *Configtable_find(key)
4810 struct config *key;
4812 int h;
4813 x4node *np;
4815 if( x4a==0 ) return 0;
4816 h = confighash(key) & (x4a->size-1);
4817 np = x4a->ht[h];
4818 while( np ){
4819 if( Configcmp(np->data,key)==0 ) break;
4820 np = np->next;
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 * */);
4830 int i;
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;
4834 x4a->count = 0;
4835 return;
4838 /* LLVM LOCAL begin */
4840 #include <unistd.h>
4841 #include <sys/wait.h>
4842 #include <errno.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)
4848 int j,i = 0;
4849 for(j=0;j<20;j++) {
4850 /* test finishes too fast, run more times to get
4851 * meaningful timings */
4852 for(i=1;i<argc;i++) {
4853 int status;
4854 pid_t p = fork();
4855 if(p == 0) {
4856 char *argv_child[] = {"lemon-child","-s",argv[i],NULL};
4857 /* child */
4858 fprintf(stdout,"Processing %s\n",mybasename(argv[i]));
4859 exit( lemon_main(3, argv_child) );
4861 while(wait(&status) == -1 && errno == EINTR) {}
4862 if(status) {
4863 fflush(stdout);
4864 fprintf(stderr,"Error while running on: %s\n",mybasename(argv[i]));
4868 return 0;
4871 /* LLVM LOCAL end */