6 ** This file contains all sources (including headers) to the LEMON
7 ** LALR(1) parser generator. The sources have been combined into a
8 ** single file to make it easy to include LEMON in the source tree
9 ** and Makefile of another program.
11 ** The author of this program disclaims copyright.
19 #include <unistd.h> /* access() */
21 #define UNUSED(x) ( (void)(x) )
24 # if defined(_WIN32) || defined(WIN32)
30 #define NORETURN __attribute__ ((__noreturn__))
35 /* #define PRIVATE static */
36 #define PRIVATE static
39 #define MAXRHS 5 /* Set low to exercise exception code */
44 void *msort(void *list
, void **next
, int(*cmp
)(void *, void *));
46 static void memory_error() NORETURN
;
48 /******** From the file "action.h" *************************************/
49 struct action
*Action_new();
50 struct action
*Action_sort();
53 /********* From the file "assert.h" ************************************/
54 void myassert() NORETURN
;
56 # define assert(X) if(!(X))myassert(__FILE__,__LINE__)
61 /********** From the file "build.h" ************************************/
62 void FindRulePrecedences();
66 void FindFollowSets();
69 /********* From the file "configlist.h" *********************************/
70 void Configlist_init(/* void */);
71 struct config
*Configlist_add(/* struct rule *, int */);
72 struct config
*Configlist_addbasis(/* struct rule *, int */);
73 void Configlist_closure(/* void */);
74 void Configlist_sort(/* void */);
75 void Configlist_sortbasis(/* void */);
76 struct config
*Configlist_return(/* void */);
77 struct config
*Configlist_basis(/* void */);
78 void Configlist_eat(/* struct config * */);
79 void Configlist_reset(/* void */);
81 /********* From the file "error.h" ***************************************/
82 void ErrorMsg(const char *, int,const char *, ...);
84 /****** From the file "option.h" ******************************************/
86 enum { OPT_FLAG
=1, OPT_INT
, OPT_DBL
, OPT_STR
,
87 OPT_FFLAG
, OPT_FINT
, OPT_FDBL
, OPT_FSTR
} type
;
92 int OptInit(/* char**,struct s_options*,FILE* */);
93 int OptNArgs(/* void */);
94 char *OptArg(/* int */);
95 void OptErr(/* int */);
96 void OptPrint(/* void */);
98 /******** From the file "parse.h" *****************************************/
99 void Parse(/* struct lemon *lemp */);
101 /********* From the file "plink.h" ***************************************/
102 struct plink
*Plink_new(/* void */);
103 void Plink_add(/* struct plink **, struct config * */);
104 void Plink_copy(/* struct plink **, struct plink * */);
105 void Plink_delete(/* struct plink * */);
107 /********** From the file "report.h" *************************************/
108 void Reprint(/* struct lemon * */);
109 void ReportOutput(/* struct lemon * */);
110 void ReportTable(/* struct lemon * */);
111 void ReportHeader(/* struct lemon * */);
112 void CompressTables(/* struct lemon * */);
114 /********** From the file "set.h" ****************************************/
115 void SetSize(/* int N */); /* All sets will be of size N */
116 char *SetNew(/* void */); /* A new set for element 0..N */
117 void SetFree(/* char* */); /* Deallocate a set */
119 int SetAdd(/* char*,int */); /* Add element to a set */
120 int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
122 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
124 /********** From the file "struct.h" *************************************/
126 ** Principal data structures for the LEMON parser generator.
129 typedef enum {Bo_FALSE
=0, Bo_TRUE
} Boolean
;
131 /* Symbols (terminals and nonterminals) of the grammar are stored
132 ** in the following: */
134 char *name
; /* Name of the symbol */
135 int index
; /* Index number for this symbol */
139 } type
; /* Symbols are all either TERMINALS or NTs */
140 struct rule
*rule
; /* Linked list of rules of this (if an NT) */
141 struct symbol
*fallback
; /* fallback token in case this token doesn't parse */
142 int prec
; /* Precedence if defined (-1 otherwise) */
148 } assoc
; /* Associativity if predecence is defined */
149 char *firstset
; /* First-set for all rules of this symbol */
150 Boolean lambda
; /* True if NT and can generate an empty string */
151 char *destructor
; /* Code which executes whenever this symbol is
152 ** popped from the stack during error processing */
153 int destructorln
; /* Line number of destructor code */
154 char *datatype
; /* The data type of information held by this
155 ** object. Only used if type==NONTERMINAL */
156 int dtnum
; /* The data type number. In the parser, the value
157 ** stack is a union. The .yy%d element of this
158 ** union is the correct data type for this object */
161 /* Each production rule in the grammar is stored in the following
164 struct symbol
*lhs
; /* Left-hand side of the rule */
165 char *lhsalias
; /* Alias for the LHS (NULL if none) */
166 int ruleline
; /* Line number for the rule */
167 int nrhs
; /* Number of RHS symbols */
168 struct symbol
**rhs
; /* The RHS symbols */
169 char **rhsalias
; /* An alias for each RHS symbol (NULL if none) */
170 int line
; /* Line number at which code begins */
171 char *code
; /* The code executed when this rule is reduced */
172 struct symbol
*precsym
; /* Precedence symbol for this rule */
173 int index
; /* An index number for this rule */
174 Boolean canReduce
; /* True if this rule is ever reduced */
175 struct rule
*nextlhs
; /* Next rule with the same LHS */
176 struct rule
*next
; /* Next rule in the global list */
179 /* A configuration is a production rule of the grammar together with
180 ** a mark (dot) showing how much of that rule has been processed so far.
181 ** Configurations also contain a follow-set which is a list of terminal
182 ** symbols which are allowed to immediately follow the end of the rule.
183 ** Every configuration is recorded as an instance of the following: */
185 struct rule
*rp
; /* The rule upon which the configuration is based */
186 int dot
; /* The parse point */
187 char *fws
; /* Follow-set for this configuration only */
188 struct plink
*fplp
; /* Follow-set forward propagation links */
189 struct plink
*bplp
; /* Follow-set backwards propagation links */
190 struct state
*stp
; /* Pointer to state which contains this */
192 COMPLETE
, /* The status is used during followset and */
193 INCOMPLETE
/* shift computations */
195 struct config
*next
; /* Next configuration in the state */
196 struct config
*bp
; /* The next basis configuration */
199 /* Every shift or reduce operation is stored as one of the following */
201 struct symbol
*sp
; /* The look-ahead symbol */
207 CONFLICT
, /* Was a reduce, but part of a conflict */
208 SH_RESOLVED
, /* Was a shift. Precedence resolved conflict */
209 RD_RESOLVED
, /* Was reduce. Precedence resolved conflict */
210 NOT_USED
/* Deleted by compression */
213 struct state
*stp
; /* The new state, if a shift */
214 struct rule
*rp
; /* The rule, if a reduce */
216 struct action
*next
; /* Next action for this state */
217 struct action
*collide
; /* Next action with the same hash */
220 /* Each state of the generated parser's finite state machine
221 ** is encoded as an instance of the following structure. */
223 struct config
*bp
; /* The basis configurations for this state */
224 struct config
*cfp
; /* All configurations in this set */
225 int index
; /* Sequencial number for this state */
226 struct action
*ap
; /* Array of actions for this state */
227 int nTknAct
, nNtAct
; /* Number of actions on terminals and nonterminals */
228 int iTknOfst
, iNtOfst
; /* yy_action[] offset for terminals and nonterms */
229 int iDflt
; /* Default action */
231 #define NO_OFFSET (-2147483647)
233 /* A followset propagation link indicates that the contents of one
234 ** configuration followset should be propagated to another whenever
235 ** the first changes. */
237 struct config
*cfp
; /* The configuration to which linked */
238 struct plink
*next
; /* The next propagate link */
241 /* The state vector for the entire parser generator is recorded as
242 ** follows. (LEMON uses no global variables and makes little use of
243 ** static variables. Fields in the following structure can be thought
244 ** of as begin global variables in the program.) */
246 struct state
**sorted
; /* Table of states sorted by state number */
247 struct rule
*rule
; /* List of all rules */
248 int nstate
; /* Number of states */
249 int nrule
; /* Number of rules */
250 int nsymbol
; /* Number of terminal and nonterminal symbols */
251 int nterminal
; /* Number of terminal symbols */
252 struct symbol
**symbols
; /* Sorted array of pointers to symbols */
253 int errorcnt
; /* Number of errors */
254 struct symbol
*errsym
; /* The error symbol */
255 char *name
; /* Name of the generated parser */
256 char *arg
; /* Declaration of the 3th argument to parser */
257 char *tokentype
; /* Type of terminal symbols in the parser stack */
258 char *vartype
; /* The default type of non-terminal symbols */
259 char *start
; /* Name of the start symbol for the grammar */
260 char *stacksize
; /* Size of the parser stack */
261 char *include
; /* Code to put at the start of the C file */
262 int includeln
; /* Line number for start of include code */
263 char *error
; /* Code to execute when an error is seen */
264 int errorln
; /* Line number for start of error code */
265 char *overflow
; /* Code to execute on a stack overflow */
266 int overflowln
; /* Line number for start of overflow code */
267 char *failure
; /* Code to execute on parser failure */
268 int failureln
; /* Line number for start of failure code */
269 char *accept
; /* Code to execute when the parser excepts */
270 int acceptln
; /* Line number for the start of accept code */
271 char *extracode
; /* Code appended to the generated file */
272 int extracodeln
; /* Line number for the start of the extra code */
273 char *tokendest
; /* Code to execute to destroy token data */
274 int tokendestln
; /* Line number for token destroyer code */
275 char *vardest
; /* Code for the default non-terminal destructor */
276 int vardestln
; /* Line number for default non-term destructor code*/
277 char *filename
; /* Name of the input file */
278 char *tmplname
; /* Name of the template file */
279 char *outname
; /* Name of the current output file */
280 char *tokenprefix
; /* A prefix added to token names in the .h file */
281 int nconflict
; /* Number of parsing conflicts */
282 int tablesize
; /* Size of the parse tables */
283 int basisflag
; /* Print only basis configurations */
284 int has_fallback
; /* True if any %fallback is seen in the grammer */
285 char *argv0
; /* Name of the program */
288 #define MemoryCheck(X) if((X)==0){ \
292 /**************** From the file "table.h" *********************************/
294 ** All code in this file has been automatically generated
295 ** from a specification in the file
297 ** by the associative array code building program "aagen".
298 ** Do not edit this file! Instead, edit the specification
299 ** file, then rerun aagen.
302 ** Code for processing tables in the LEMON parser generator.
305 /* Routines for handling a strings */
309 void Strsafe_init(/* void */);
310 int Strsafe_insert(/* char * */);
311 char *Strsafe_find(/* char * */);
313 /* Routines for handling symbols of the grammar */
315 struct symbol
*Symbol_new();
316 int Symbolcmpp(/* struct symbol **, struct symbol ** */);
317 void Symbol_init(/* void */);
318 int Symbol_insert(/* struct symbol *, char * */);
319 struct symbol
*Symbol_find(/* char * */);
320 struct symbol
*Symbol_Nth(/* int */);
321 int Symbol_count(/* */);
322 int State_count(void);
323 struct symbol
**Symbol_arrayof(/* */);
325 /* Routines to manage the state table */
327 int Configcmp(/* struct config *, struct config * */);
328 struct state
*State_new();
329 void State_init(/* void */);
330 int State_insert(/* struct state *, struct config * */);
331 struct state
*State_find(/* struct config * */);
332 struct state
**State_arrayof(/* */);
334 /* Routines used for efficiency in Configlist_add */
336 void Configtable_init(/* void */);
337 int Configtable_insert(/* struct config * */);
338 struct config
*Configtable_find(/* struct config * */);
339 void Configtable_clear(/* int(*)(struct config *) */);
340 /****************** From the file "action.c" *******************************/
342 ** Routines processing parser actions in the LEMON parser generator.
345 /* Allocate a new parser action */
346 struct action
*Action_new(){
347 static struct action
*freelist
= NULL
;
350 if( freelist
==NULL
){
353 freelist
= (struct action
*)malloc( sizeof(struct action
)*amt
);
355 fprintf(stderr
,"Unable to allocate memory for a new parser action.");
358 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
359 freelist
[amt
-1].next
= 0;
362 freelist
= freelist
->next
;
366 /* Compare two actions */
367 static int actioncmp(ap1
,ap2
)
372 rc
= ap1
->sp
->index
- ap2
->sp
->index
;
373 if( rc
==0 ) rc
= (int)ap1
->type
- (int)ap2
->type
;
375 assert( ap1
->type
==REDUCE
|| ap1
->type
==RD_RESOLVED
|| ap1
->type
==CONFLICT
);
376 assert( ap2
->type
==REDUCE
|| ap2
->type
==RD_RESOLVED
|| ap2
->type
==CONFLICT
);
377 rc
= ap1
->x
.rp
->index
- ap2
->x
.rp
->index
;
382 /* Sort parser actions */
383 struct action
*Action_sort(ap
)
386 ap
= (struct action
*)msort(ap
,(void **)&ap
->next
,actioncmp
);
390 void Action_add(app
,type
,sp
,arg
)
403 new->x
.stp
= (struct state
*)arg
;
405 new->x
.rp
= (struct rule
*)arg
;
408 /********************** New code to implement the "acttab" module ***********/
410 ** This module implements routines use to construct the yy_action[] table.
414 ** The state of the yy_action table under construction is an instance of
415 ** the following structure
417 typedef struct acttab acttab
;
419 int nAction
; /* Number of used slots in aAction[] */
420 int nActionAlloc
; /* Slots allocated for aAction[] */
422 int lookahead
; /* Value of the lookahead token */
423 int action
; /* Action to take on the given lookahead */
424 } *aAction
, /* The yy_action[] table under construction */
425 *aLookahead
; /* A single new transaction set */
426 int mnLookahead
; /* Minimum aLookahead[].lookahead */
427 int mnAction
; /* Action associated with mnLookahead */
428 int mxLookahead
; /* Maximum aLookahead[].lookahead */
429 int nLookahead
; /* Used slots in aLookahead[] */
430 int nLookaheadAlloc
; /* Slots allocated in aLookahead[] */
433 /* Return the number of entries in the yy_action table */
434 #define acttab_size(X) ((X)->nAction)
436 /* The value for the N-th entry in yy_action */
437 #define acttab_yyaction(X,N) ((X)->aAction[N].action)
439 /* The value for the N-th entry in yy_lookahead */
440 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
442 /* Free all memory associated with the given acttab */
444 PRIVATE void acttab_free(acttab *p){
446 free( p->aLookahead );
451 /* Allocate a new acttab structure */
452 PRIVATE acttab
*acttab_alloc(void){
453 acttab
*p
= malloc( sizeof(*p
) );
455 fprintf(stderr
,"Unable to allocate memory for a new acttab.");
458 memset(p
, 0, sizeof(*p
));
462 /* Add a new action to the current transaction set
464 PRIVATE
void acttab_action(acttab
*p
, int lookahead
, int action
){
465 if( p
->nLookahead
>=p
->nLookaheadAlloc
){
466 p
->nLookaheadAlloc
+= 25;
467 p
->aLookahead
= realloc( p
->aLookahead
,
468 sizeof(p
->aLookahead
[0])*p
->nLookaheadAlloc
);
469 if( p
->aLookahead
==0 ){
470 fprintf(stderr
,"malloc failed\n");
474 if( p
->nLookahead
==0 ){
475 p
->mxLookahead
= lookahead
;
476 p
->mnLookahead
= lookahead
;
477 p
->mnAction
= action
;
479 if( p
->mxLookahead
<lookahead
) p
->mxLookahead
= lookahead
;
480 if( p
->mnLookahead
>lookahead
){
481 p
->mnLookahead
= lookahead
;
482 p
->mnAction
= action
;
485 p
->aLookahead
[p
->nLookahead
].lookahead
= lookahead
;
486 p
->aLookahead
[p
->nLookahead
].action
= action
;
491 ** Add the transaction set built up with prior calls to acttab_action()
492 ** into the current action table. Then reset the transaction set back
493 ** to an empty set in preparation for a new round of acttab_action() calls.
495 ** Return the offset into the action table of the new transaction.
497 PRIVATE
int acttab_insert(acttab
*p
){
499 assert( p
->nLookahead
>0 );
501 /* Make sure we have enough space to hold the expanded action table
502 ** in the worst case. The worst case occurs if the transaction set
503 ** must be appended to the current action table
505 n
= p
->mxLookahead
+ 1;
506 if( p
->nAction
+ n
>= p
->nActionAlloc
){
507 int oldAlloc
= p
->nActionAlloc
;
508 p
->nActionAlloc
= p
->nAction
+ n
+ p
->nActionAlloc
+ 20;
509 p
->aAction
= realloc( p
->aAction
,
510 sizeof(p
->aAction
[0])*p
->nActionAlloc
);
512 fprintf(stderr
,"malloc failed\n");
515 for(i
=oldAlloc
; i
<p
->nActionAlloc
; i
++){
516 p
->aAction
[i
].lookahead
= -1;
517 p
->aAction
[i
].action
= -1;
521 /* Scan the existing action table looking for an offset where we can
522 ** insert the current transaction set. Fall out of the loop when that
523 ** offset is found. In the worst case, we fall out of the loop when
524 ** i reaches p->nAction, which means we append the new transaction set.
526 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
528 for(i
=0; i
<p
->nAction
+p
->mnLookahead
; i
++){
529 if( p
->aAction
[i
].lookahead
<0 ){
530 for(j
=0; j
<p
->nLookahead
; j
++){
531 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
533 if( p
->aAction
[k
].lookahead
>=0 ) break;
535 if( j
<p
->nLookahead
) continue;
536 for(j
=0; j
<p
->nAction
; j
++){
537 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) break;
540 break; /* Fits in empty slots */
542 }else if( p
->aAction
[i
].lookahead
==p
->mnLookahead
){
543 if( p
->aAction
[i
].action
!=p
->mnAction
) continue;
544 for(j
=0; j
<p
->nLookahead
; j
++){
545 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
546 if( k
<0 || k
>=p
->nAction
) break;
547 if( p
->aLookahead
[j
].lookahead
!=p
->aAction
[k
].lookahead
) break;
548 if( p
->aLookahead
[j
].action
!=p
->aAction
[k
].action
) break;
550 if( j
<p
->nLookahead
) continue;
552 for(j
=0; j
<p
->nAction
; j
++){
553 if( p
->aAction
[j
].lookahead
<0 ) continue;
554 if( p
->aAction
[j
].lookahead
==j
+p
->mnLookahead
-i
) n
++;
556 if( n
==p
->nLookahead
){
557 break; /* Same as a prior transaction set */
561 /* Insert transaction set at index i. */
562 for(j
=0; j
<p
->nLookahead
; j
++){
563 k
= p
->aLookahead
[j
].lookahead
- p
->mnLookahead
+ i
;
564 p
->aAction
[k
] = p
->aLookahead
[j
];
565 if( k
>=p
->nAction
) p
->nAction
= k
+1;
569 /* Return the offset that is added to the lookahead in order to get the
570 ** index into yy_action of the action */
571 return i
- p
->mnLookahead
;
574 /********************** From the file "assert.c" ****************************/
576 ** A more efficient way of handling assertions.
578 void myassert(file
,line
)
582 fprintf(stderr
,"Assertion failed on line %d of file \"%s\"\n",line
,file
);
585 /********************** From the file "build.c" *****************************/
587 ** Routines to construction the finite state machine for the LEMON
591 /* Find a precedence symbol of every rule in the grammar.
593 ** Those rules which have a precedence symbol coded in the input
594 ** grammar using the "[symbol]" construct will already have the
595 ** rp->precsym field filled. Other rules take as their precedence
596 ** symbol the first RHS symbol with a defined precedence. If there
597 ** are not RHS symbols with a defined precedence, the precedence
598 ** symbol field is left blank.
600 void FindRulePrecedences(xp
)
604 for(rp
=xp
->rule
; rp
; rp
=rp
->next
){
605 if( rp
->precsym
==0 ){
607 for(i
=0; i
<rp
->nrhs
; i
++){
608 if( rp
->rhs
[i
]->prec
>=0 ){
609 rp
->precsym
= rp
->rhs
[i
];
618 /* Find all nonterminals which will generate the empty string.
619 ** Then go back and compute the first sets of every nonterminal.
620 ** The first set is the set of all terminal symbols which can begin
621 ** a string generated by that nonterminal.
623 void FindFirstSets(lemp
)
630 for(i
=0; i
<lemp
->nsymbol
; i
++){
631 lemp
->symbols
[i
]->lambda
= Bo_FALSE
;
633 for(i
=lemp
->nterminal
; i
<lemp
->nsymbol
; i
++){
634 lemp
->symbols
[i
]->firstset
= SetNew();
637 /* First compute all lambdas */
640 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
641 if( rp
->lhs
->lambda
) continue;
642 for(i
=0; i
<rp
->nrhs
; i
++){
643 if( rp
->rhs
[i
]->lambda
==Bo_FALSE
) break;
646 rp
->lhs
->lambda
= Bo_TRUE
;
652 /* Now compute all first sets */
654 struct symbol
*s1
, *s2
;
656 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
658 for(i
=0; i
<rp
->nrhs
; i
++){
660 if( s2
->type
==TERMINAL
){
661 progress
+= SetAdd(s1
->firstset
,s2
->index
);
664 if( s1
->lambda
==Bo_FALSE
) break;
666 progress
+= SetUnion(s1
->firstset
,s2
->firstset
);
667 if( s2
->lambda
==Bo_FALSE
) break;
675 /* Compute all LR(0) states for the grammar. Links
676 ** are added to between some states so that the LR(1) follow sets
677 ** can be computed later.
679 PRIVATE
struct state
*getstate(/* struct lemon * */); /* forward reference */
680 void FindStates(lemp
)
688 /* Find the start symbol */
690 sp
= Symbol_find(lemp
->start
);
692 ErrorMsg(lemp
->filename
,0,
693 "The specified start symbol \"%s\" is not \
694 in a nonterminal of the grammar. \"%s\" will be used as the start \
695 symbol instead.",lemp
->start
,lemp
->rule
->lhs
->name
);
697 sp
= lemp
->rule
->lhs
;
700 sp
= lemp
->rule
->lhs
;
703 /* Make sure the start symbol doesn't occur on the right-hand side of
704 ** any rule. Report an error if it does. (YACC would generate a new
705 ** start symbol in this case.) */
706 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
708 for(i
=0; i
<rp
->nrhs
; i
++){
709 if( rp
->rhs
[i
]==sp
){
710 ErrorMsg(lemp
->filename
,0,
711 "The start symbol \"%s\" occurs on the \
712 right-hand side of a rule. This will result in a parser which \
713 does not work properly.",sp
->name
);
719 /* The basis configuration set for the first state
720 ** is all rules which have the start symbol as their
722 for(rp
=sp
->rule
; rp
; rp
=rp
->nextlhs
){
723 struct config
*newcfp
;
724 newcfp
= Configlist_addbasis(rp
,0);
725 SetAdd(newcfp
->fws
,0);
728 /* Compute the first state. All other states will be
729 ** computed automatically during the computation of the first one.
730 ** The returned pointer to the first state is not used. */
731 (void)getstate(lemp
);
735 /* Return a pointer to a state which is described by the configuration
736 ** list which has been built from calls to Configlist_add.
738 PRIVATE
void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
739 PRIVATE
struct state
*getstate(lemp
)
742 struct config
*cfp
, *bp
;
745 /* Extract the sorted basis of the new state. The basis was constructed
746 ** by prior calls to "Configlist_addbasis()". */
747 Configlist_sortbasis();
748 bp
= Configlist_basis();
750 /* Get a state with the same basis */
751 stp
= State_find(bp
);
753 /* A state with the same basis already exists! Copy all the follow-set
754 ** propagation links from the state under construction into the
755 ** preexisting state, then return a pointer to the preexisting state */
756 struct config
*x
, *y
;
757 for(x
=bp
, y
=stp
->bp
; x
&& y
; x
=x
->bp
, y
=y
->bp
){
758 Plink_copy(&y
->bplp
,x
->bplp
);
759 Plink_delete(x
->fplp
);
760 x
->fplp
= x
->bplp
= 0;
762 cfp
= Configlist_return();
765 /* This really is a new state. Construct all the details */
766 Configlist_closure(lemp
); /* Compute the configuration closure */
767 Configlist_sort(); /* Sort the configuration closure */
768 cfp
= Configlist_return(); /* Get a pointer to the config list */
769 stp
= State_new(); /* A new state structure */
771 stp
->bp
= bp
; /* Remember the configuration basis */
772 stp
->cfp
= cfp
; /* Remember the configuration closure */
773 stp
->index
= 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 */
781 /* Construct all successor states to the given state. A "successor"
782 ** state is any state which can be reached by a shift action.
784 PRIVATE
void buildshifts(lemp
,stp
)
786 struct state
*stp
; /* The state from which successors are computed */
788 struct config
*cfp
; /* For looping thru the config closure of "stp" */
789 struct config
*bcfp
; /* For the inner loop on config closure of "stp" */
790 struct config
*new; /* */
791 struct symbol
*sp
; /* Symbol following the dot in configuration "cfp" */
792 struct symbol
*bsp
; /* Symbol following the dot in configuration "bcfp" */
793 struct state
*newstp
; /* A pointer to a successor state */
795 /* Each configuration becomes complete after it contibutes to a successor
796 ** state. Initially, all configurations are incomplete */
797 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
) cfp
->status
= INCOMPLETE
;
799 /* Loop through all configurations of the state "stp" */
800 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
801 if( cfp
->status
==COMPLETE
) continue; /* Already used by inner loop */
802 if( cfp
->dot
>=cfp
->rp
->nrhs
) continue; /* Can't shift this config */
803 Configlist_reset(); /* Reset the new config set */
804 sp
= cfp
->rp
->rhs
[cfp
->dot
]; /* Symbol after the dot */
806 /* For every configuration in the state "stp" which has the symbol "sp"
807 ** following its dot, add the same configuration to the basis set under
808 ** construction but with the dot shifted one symbol to the right. */
809 for(bcfp
=cfp
; bcfp
; bcfp
=bcfp
->next
){
810 if( bcfp
->status
==COMPLETE
) continue; /* Already used */
811 if( bcfp
->dot
>=bcfp
->rp
->nrhs
) continue; /* Can't shift this one */
812 bsp
= bcfp
->rp
->rhs
[bcfp
->dot
]; /* Get symbol after dot */
813 if( bsp
!=sp
) continue; /* Must be same as for "cfp" */
814 bcfp
->status
= COMPLETE
; /* Mark this config as used */
815 new = Configlist_addbasis(bcfp
->rp
,bcfp
->dot
+1);
816 Plink_add(&new->bplp
,bcfp
);
819 /* Get a pointer to the state described by the basis configuration set
820 ** constructed in the preceding loop */
821 newstp
= getstate(lemp
);
823 /* The state "newstp" is reached from the state "stp" by a shift action
824 ** on the symbol "sp" */
825 Action_add(&stp
->ap
,SHIFT
,sp
,newstp
);
830 ** Construct the propagation links
836 struct config
*cfp
, *other
;
840 /* Housekeeping detail:
841 ** Add to every propagate link a pointer back to the state to
842 ** which the link is attached. */
843 for(i
=0; i
<lemp
->nstate
; i
++){
844 stp
= lemp
->sorted
[i
];
845 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
850 /* Convert all backlinks into forward links. Only the forward
851 ** links are used in the follow-set computation. */
852 for(i
=0; i
<lemp
->nstate
; i
++){
853 stp
= lemp
->sorted
[i
];
854 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
855 for(plp
=cfp
->bplp
; plp
; plp
=plp
->next
){
857 Plink_add(&other
->fplp
,cfp
);
863 /* Compute all followsets.
865 ** A followset is the set of all symbols which can come immediately
866 ** after a configuration.
868 void FindFollowSets(lemp
)
878 for(i
=0; i
<lemp
->nstate
; i
++){
879 stp
= lemp
->sorted
[i
];
880 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
881 cfp
->status
= INCOMPLETE
;
887 for(i
=0; i
<lemp
->nstate
; i
++){
888 stp
= lemp
->sorted
[i
];
889 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){
890 if( cfp
->status
==COMPLETE
) continue;
891 for(plp
=cfp
->fplp
; plp
; plp
=plp
->next
){
892 change
= SetUnion(plp
->cfp
->fws
,cfp
->fws
);
894 plp
->cfp
->status
= INCOMPLETE
;
898 cfp
->status
= COMPLETE
;
904 static int resolve_conflict();
906 /* Compute the reduce actions, and resolve conflicts.
908 void FindActions(lemp
)
916 /* Add all of the reduce actions
917 ** A reduce action is added for each element of the followset of
918 ** a configuration which has its dot at the extreme right.
920 for(i
=0; i
<lemp
->nstate
; i
++){ /* Loop over all states */
922 stp
= lemp
->sorted
[i
];
923 for(cfp
=stp
->cfp
; cfp
; cfp
=cfp
->next
){ /* Loop over all configurations */
924 if( cfp
->rp
->nrhs
==cfp
->dot
){ /* Is dot at extreme right? */
925 for(j
=0; j
<lemp
->nterminal
; j
++){
926 if( SetFind(cfp
->fws
,j
) ){
927 /* Add a reduce action to the state "stp" which will reduce by the
928 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
929 Action_add(&stp
->ap
,REDUCE
,lemp
->symbols
[j
],cfp
->rp
);
936 /* Add the accepting token */
938 sp
= Symbol_find(lemp
->start
);
939 if( sp
==0 ) sp
= lemp
->rule
->lhs
;
941 sp
= lemp
->rule
->lhs
;
943 /* Add to the first state (which is always the starting state of the
944 ** finite state machine) an action to ACCEPT if the lookahead is the
945 ** start nonterminal. */
946 if (lemp
->nstate
) { /*(should always be true)*/
948 stp
= lemp
->sorted
[0];
949 Action_add(&stp
->ap
,ACCEPT
,sp
,0);
952 /* Resolve conflicts */
953 for(i
=0; i
<lemp
->nstate
; i
++){
954 struct action
*ap
, *nap
;
956 stp
= lemp
->sorted
[i
];
958 stp
->ap
= Action_sort(stp
->ap
);
959 for(ap
=stp
->ap
; ap
&& ap
->next
; ap
=ap
->next
){
960 for(nap
=ap
->next
; nap
&& nap
->sp
==ap
->sp
; nap
=nap
->next
){
961 /* The two actions "ap" and "nap" have the same lookahead.
962 ** Figure out which one should be used */
963 lemp
->nconflict
+= resolve_conflict(ap
,nap
,lemp
->errsym
);
968 /* Report an error for each rule that can never be reduced. */
969 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
) rp
->canReduce
= Bo_FALSE
;
970 for(i
=0; i
<lemp
->nstate
; i
++){
972 for(ap
=lemp
->sorted
[i
]->ap
; ap
; ap
=ap
->next
){
973 if( ap
->type
==REDUCE
) ap
->x
.rp
->canReduce
= Bo_TRUE
;
976 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
977 if( rp
->canReduce
) continue;
978 ErrorMsg(lemp
->filename
,rp
->ruleline
,"This rule can not be reduced.\n");
983 /* Resolve a conflict between the two given actions. If the
984 ** conflict can't be resolve, return non-zero.
987 ** To resolve a conflict, first look to see if either action
988 ** is on an error rule. In that case, take the action which
989 ** is not associated with the error rule. If neither or both
990 ** actions are associated with an error rule, then try to
991 ** use precedence to resolve the conflict.
993 ** If either action is a SHIFT, then it must be apx. This
994 ** function won't work if apx->type==REDUCE and apy->type==SHIFT.
996 static int resolve_conflict(apx
,apy
,errsym
)
999 struct symbol
*errsym
; /* The error symbol (if defined. NULL otherwise) */
1001 struct symbol
*spx
, *spy
;
1004 assert( apx
->sp
==apy
->sp
); /* Otherwise there would be no conflict */
1005 if( apx
->type
==SHIFT
&& apy
->type
==REDUCE
){
1007 spy
= apy
->x
.rp
->precsym
;
1008 if( spy
==0 || spx
->prec
<0 || spy
->prec
<0 ){
1009 /* Not enough precedence information. */
1010 apy
->type
= CONFLICT
;
1012 }else if( spx
->prec
>spy
->prec
){ /* Lower precedence wins */
1013 apy
->type
= RD_RESOLVED
;
1014 }else if( spx
->prec
<spy
->prec
){
1015 apx
->type
= SH_RESOLVED
;
1016 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==RIGHT
){ /* Use operator */
1017 apy
->type
= RD_RESOLVED
; /* associativity */
1018 }else if( spx
->prec
==spy
->prec
&& spx
->assoc
==LEFT
){ /* to break tie */
1019 apx
->type
= SH_RESOLVED
;
1021 assert( spx
->prec
==spy
->prec
&& spx
->assoc
==NONE
);
1022 apy
->type
= CONFLICT
;
1025 }else if( apx
->type
==REDUCE
&& apy
->type
==REDUCE
){
1026 spx
= apx
->x
.rp
->precsym
;
1027 spy
= apy
->x
.rp
->precsym
;
1028 if( spx
==0 || spy
==0 || spx
->prec
<0 ||
1029 spy
->prec
<0 || spx
->prec
==spy
->prec
){
1030 apy
->type
= CONFLICT
;
1032 }else if( spx
->prec
>spy
->prec
){
1033 apy
->type
= RD_RESOLVED
;
1034 }else if( spx
->prec
<spy
->prec
){
1035 apx
->type
= RD_RESOLVED
;
1039 apx
->type
==SH_RESOLVED
||
1040 apx
->type
==RD_RESOLVED
||
1041 apx
->type
==CONFLICT
||
1042 apy
->type
==SH_RESOLVED
||
1043 apy
->type
==RD_RESOLVED
||
1046 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1047 ** REDUCEs on the list. If we reach this point it must be because
1048 ** the parser conflict had already been resolved. */
1052 /********************* From the file "configlist.c" *************************/
1054 ** Routines to processing a configuration list and building a state
1055 ** in the LEMON parser generator.
1058 static struct config
*freelist
= 0; /* List of free configurations */
1059 static struct config
*current
= 0; /* Top of list of configurations */
1060 static struct config
**currentend
= 0; /* Last on list of configs */
1061 static struct config
*basis
= 0; /* Top of list of basis configs */
1062 static struct config
**basisend
= 0; /* End of list of basis configs */
1064 /* Return a pointer to a new configuration */
1065 PRIVATE
struct config
*newconfig(){
1070 freelist
= (struct config
*)malloc( sizeof(struct config
)*amt
);
1072 fprintf(stderr
,"Unable to allocate memory for a new configuration.");
1075 for(i
=0; i
<amt
-1; i
++) freelist
[i
].next
= &freelist
[i
+1];
1076 freelist
[amt
-1].next
= 0;
1079 freelist
= freelist
->next
;
1083 /* The configuration "old" is no longer used */
1084 PRIVATE
void deleteconfig(old
)
1087 old
->next
= freelist
;
1091 /* Initialized the configuration list builder */
1092 void Configlist_init(){
1094 currentend
= ¤t
;
1101 /* Initialized the configuration list builder */
1102 void Configlist_reset(){
1104 currentend
= ¤t
;
1107 Configtable_clear(0);
1111 /* Add another configuration to the configuration list */
1112 struct config
*Configlist_add(rp
,dot
)
1113 struct rule
*rp
; /* The rule */
1114 int dot
; /* Index into the RHS of the rule where the dot goes */
1116 struct config
*cfp
, model
;
1118 assert( currentend
!=0 );
1121 cfp
= Configtable_find(&model
);
1126 cfp
->fws
= SetNew();
1128 cfp
->fplp
= cfp
->bplp
= 0;
1132 currentend
= &cfp
->next
;
1133 Configtable_insert(cfp
);
1138 /* Add a basis configuration to the configuration list */
1139 struct config
*Configlist_addbasis(rp
,dot
)
1143 struct config
*cfp
, model
;
1145 assert( basisend
!=0 );
1146 assert( currentend
!=0 );
1149 cfp
= Configtable_find(&model
);
1154 cfp
->fws
= SetNew();
1156 cfp
->fplp
= cfp
->bplp
= 0;
1160 currentend
= &cfp
->next
;
1162 basisend
= &cfp
->bp
;
1163 Configtable_insert(cfp
);
1168 /* Compute the closure of the configuration list */
1169 void Configlist_closure(lemp
)
1172 struct config
*cfp
, *newcfp
;
1173 struct rule
*rp
, *newrp
;
1174 struct symbol
*sp
, *xsp
;
1177 assert( currentend
!=0 );
1178 for(cfp
=current
; cfp
; cfp
=cfp
->next
){
1181 if( dot
>=rp
->nrhs
) continue;
1183 if( sp
->type
==NONTERMINAL
){
1184 if( sp
->rule
==0 && sp
!=lemp
->errsym
){
1185 ErrorMsg(lemp
->filename
,rp
->line
,"Nonterminal \"%s\" has no rules.",
1189 for(newrp
=sp
->rule
; newrp
; newrp
=newrp
->nextlhs
){
1190 newcfp
= Configlist_add(newrp
,0);
1191 for(i
=dot
+1; i
<rp
->nrhs
; i
++){
1193 if( xsp
->type
==TERMINAL
){
1194 SetAdd(newcfp
->fws
,xsp
->index
);
1197 SetUnion(newcfp
->fws
,xsp
->firstset
);
1198 if( xsp
->lambda
==Bo_FALSE
) break;
1201 if( i
==rp
->nrhs
) Plink_add(&cfp
->fplp
,newcfp
);
1208 /* Sort the configuration list */
1209 void Configlist_sort(){
1210 current
= (struct config
*)msort(current
,(void **)&(current
->next
),Configcmp
);
1215 /* Sort the basis configuration list */
1216 void Configlist_sortbasis(){
1217 basis
= (struct config
*)msort(current
,(void **)&(current
->bp
),Configcmp
);
1222 /* Return a pointer to the head of the configuration list and
1223 ** reset the list */
1224 struct config
*Configlist_return(){
1232 /* Return a pointer to the head of the configuration list and
1233 ** reset the list */
1234 struct config
*Configlist_basis(){
1242 /* Free all elements of the given configuration list */
1243 void Configlist_eat(cfp
)
1246 struct config
*nextcfp
;
1247 for(; cfp
; cfp
=nextcfp
){
1248 nextcfp
= cfp
->next
;
1249 assert( cfp
->fplp
==0 );
1250 assert( cfp
->bplp
==0 );
1251 if( cfp
->fws
) SetFree(cfp
->fws
);
1256 /***************** From the file "error.c" *********************************/
1258 ** Code for printing error message.
1261 /* Find a good place to break "msg" so that its length is at least "min"
1262 ** but no more than "max". Make the point as close to max as possible.
1264 static int findbreak(msg
,min
,max
)
1271 for(i
=spot
=min
; i
<=max
; i
++){
1273 if( c
=='\t' ) msg
[i
] = ' ';
1274 if( c
=='\n' ){ msg
[i
] = ' '; spot
= i
; break; }
1275 if( c
==0 ){ spot
= i
; break; }
1276 if( c
=='-' && i
<max
-1 ) spot
= i
+1;
1277 if( c
==' ' ) spot
= i
;
1283 ** The error message is split across multiple lines if necessary. The
1284 ** splits occur at a space, if there is a space available near the end
1287 #define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1288 #define LINEWIDTH 79 /* Max width of any output line */
1289 #define PREFIXLIMIT 30 /* Max width of the prefix on each line */
1290 void ErrorMsg(const char *filename
, int lineno
, const char *format
, ...){
1291 char errmsg
[ERRMSGSIZE
];
1292 char prefix
[PREFIXLIMIT
+10];
1297 int end
, restart
, base
;
1299 va_start(ap
, format
);
1300 /* Prepare a prefix to be prepended to every output line */
1302 sprintf(prefix
,"%.*s:%d: ",PREFIXLIMIT
-10,filename
,lineno
);
1304 sprintf(prefix
,"%.*s: ",PREFIXLIMIT
-10,filename
);
1306 prefixsize
= strlen(prefix
);
1307 availablewidth
= LINEWIDTH
- prefixsize
;
1309 /* Generate the error message */
1310 vsprintf(errmsg
,format
,ap
);
1312 errmsgsize
= strlen(errmsg
);
1313 /* Remove trailing '\n's from the error message. */
1314 while( errmsgsize
>0 && errmsg
[errmsgsize
-1]=='\n' ){
1315 errmsg
[--errmsgsize
] = 0;
1318 /* Print the error message */
1320 while( errmsg
[base
]!=0 ){
1321 end
= restart
= findbreak(&errmsg
[base
],0,availablewidth
);
1323 while( errmsg
[restart
]==' ' ) restart
++;
1324 fprintf(stdout
,"%s%.*s\n",prefix
,end
,&errmsg
[base
]);
1328 /**************** From the file "main.c" ************************************/
1330 ** Main program file for the LEMON parser generator.
1333 /* Report an out-of-memory condition and abort. This function
1334 ** is used mostly by the "MemoryCheck" macro in struct.h
1336 void memory_error() {
1337 fprintf(stderr
,"Out of memory. Aborting...\n");
1342 /* The main program. Parse the command line and do it... */
1347 static int version
= 0;
1348 static int rpflag
= 0;
1349 static int basisflag
= 0;
1350 static int compress
= 0;
1351 static int quiet
= 0;
1352 static int statistics
= 0;
1353 static int mhflag
= 0;
1354 static struct s_options options
[] = {
1355 {OPT_FLAG
, "b", (char*)&basisflag
, "Print only the basis in report."},
1356 {OPT_FLAG
, "c", (char*)&compress
, "Don't compress the action table."},
1357 {OPT_FLAG
, "g", (char*)&rpflag
, "Print grammar without actions."},
1358 {OPT_FLAG
, "m", (char*)&mhflag
, "Output a makeheaders compatible file"},
1359 {OPT_FLAG
, "q", (char*)&quiet
, "(Quiet) Don't print the report file."},
1360 {OPT_FLAG
, "s", (char*)&statistics
, "Print parser stats to standard output."},
1361 {OPT_FLAG
, "x", (char*)&version
, "Print the version number."},
1366 char *def_tmpl_name
= "lempar.c";
1369 OptInit(argv
,options
,stderr
);
1371 printf("Lemon version 1.0\n");
1374 if( OptNArgs() < 1 ){
1375 fprintf(stderr
,"Exactly one filename argument is required.\n");
1380 /* Initialize the machine */
1384 lem
.argv0
= argv
[0];
1385 lem
.filename
= OptArg(0);
1386 lem
.tmplname
= (OptNArgs() == 2) ? OptArg(1) : def_tmpl_name
;
1387 lem
.basisflag
= basisflag
;
1388 lem
.has_fallback
= 0;
1390 lem
.name
= lem
.include
= lem
.arg
= lem
.tokentype
= lem
.start
= 0;
1393 lem
.error
= lem
.overflow
= lem
.failure
= lem
.accept
= lem
.tokendest
=
1394 lem
.tokenprefix
= lem
.outname
= lem
.extracode
= 0;
1398 lem
.errsym
= Symbol_new("error");
1400 /* Parse the input file */
1402 if( lem
.errorcnt
) exit(lem
.errorcnt
);
1404 fprintf(stderr
,"Empty grammar.\n");
1408 /* Count and index the symbols of the grammar */
1409 Symbol_new("{default}");
1410 lem
.nsymbol
= Symbol_count();
1411 lem
.symbols
= Symbol_arrayof();
1412 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1413 qsort(lem
.symbols
,lem
.nsymbol
,sizeof(struct symbol
*),
1414 (int(*)())Symbolcmpp
);
1415 for(i
=0; i
<lem
.nsymbol
; i
++) lem
.symbols
[i
]->index
= i
;
1416 for(i
=1; i
<lem
.nsymbol
&& isupper(lem
.symbols
[i
]->name
[0]); i
++);
1417 lem
.nsymbol
--; /*(do not count "{default}")*/
1420 /* Generate a reprint of the grammar, if requested on the command line */
1424 /* Initialize the size for all follow and first sets */
1425 SetSize(lem
.nterminal
);
1427 /* Find the precedence for every production rule (that has one) */
1428 FindRulePrecedences(&lem
);
1430 /* Compute the lambda-nonterminals and the first-sets for every
1432 FindFirstSets(&lem
);
1434 /* Compute all LR(0) states. Also record follow-set propagation
1435 ** links so that the follow-set can be computed later */
1438 lem
.nstate
= State_count();
1439 lem
.sorted
= State_arrayof();
1441 /* Tie up loose ends on the propagation links */
1444 /* Compute the follow set of every reducible configuration */
1445 FindFollowSets(&lem
);
1447 /* Compute the action tables */
1450 /* Compress the action tables */
1451 if( compress
==0 ) CompressTables(&lem
);
1453 /* Generate a report of the parser generated. (the "y.output" file) */
1454 if( !quiet
) ReportOutput(&lem
);
1456 /* Generate the source code for the parser */
1457 ReportTable(&lem
, mhflag
);
1459 /* Produce a header file for use by the scanner. (This step is
1460 ** omitted if the "-m" option is used because makeheaders will
1461 ** generate the file for us.) */
1462 if( !mhflag
) ReportHeader(&lem
);
1465 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1466 lem
.nterminal
, lem
.nsymbol
- lem
.nterminal
, lem
.nrule
);
1467 printf(" %d states, %d parser table entries, %d conflicts\n",
1468 lem
.nstate
, lem
.tablesize
, lem
.nconflict
);
1470 if( lem
.nconflict
){
1471 fprintf(stderr
,"%d parsing conflicts.\n",lem
.nconflict
);
1473 exit(lem
.errorcnt
+ lem
.nconflict
);
1475 /******************** From the file "msort.c" *******************************/
1477 ** A generic merge-sort program.
1480 ** Let "ptr" be a pointer to some structure which is at the head of
1481 ** a null-terminated list. Then to sort the list call:
1483 ** ptr = msort(ptr,&(ptr->next),cmpfnc);
1485 ** In the above, "cmpfnc" is a pointer to a function which compares
1486 ** two instances of the structure and returns an integer, as in
1487 ** strcmp. The second argument is a pointer to the pointer to the
1488 ** second element of the linked list. This address is used to compute
1489 ** the offset to the "next" field within the structure. The offset to
1490 ** the "next" field must be constant for all structures in the list.
1492 ** The function returns a new pointer which is the head of the list
1500 ** Return a pointer to the next structure in the linked list.
1502 #define NEXT(A) (*(char**)(((unsigned long)A)+offset))
1506 ** a: A sorted, null-terminated linked list. (May be null).
1507 ** b: A sorted, null-terminated linked list. (May be null).
1508 ** cmp: A pointer to the comparison function.
1509 ** offset: Offset in the structure to the "next" field.
1512 ** A pointer to the head of a sorted list containing the elements
1516 ** The "next" pointers for elements in the lists a and b are
1519 static char *merge(a
,b
,cmp
,offset
)
1532 if( (*cmp
)(a
,b
)<0 ){
1541 if( (*cmp
)(a
,b
)<0 ){
1551 if( a
) NEXT(ptr
) = a
;
1559 ** list: Pointer to a singly-linked list of structures.
1560 ** next: Pointer to pointer to the second element of the list.
1561 ** cmp: A comparison function.
1564 ** A pointer to the head of a sorted list containing the elements
1565 ** orginally in list.
1568 ** The "next" pointers for elements in list are changed.
1571 void *msort(void *list
, void **next
, int(*cmp
)(void *, void *))
1573 unsigned long offset
;
1575 char *set
[LISTSIZE
];
1577 offset
= (unsigned long)next
- (unsigned long)list
;
1578 for(i
=0; i
<LISTSIZE
; i
++) set
[i
] = 0;
1583 for(i
=0; i
<LISTSIZE
-1 && set
[i
]!=0; i
++){
1584 ep
= merge(ep
,set
[i
],cmp
,offset
);
1590 for(i
=0; i
<LISTSIZE
; i
++) if( set
[i
] ) ep
= merge(ep
,set
[i
],cmp
,offset
);
1593 /************************ From the file "option.c" **************************/
1595 static struct s_options
*op
;
1596 static FILE *errstream
;
1598 #define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1601 ** Print the command line with a carrot pointing to the k-th character
1602 ** of the n-th field.
1604 static void errline(n
,k
,err
)
1611 fprintf(err
,"%s",argv
[0]);
1612 spcnt
+= strlen(argv
[0]) + 1;
1614 for(i
=1; i
<n
&& argv
[i
]; i
++){
1615 fprintf(err
," %s",argv
[i
]);
1616 spcnt
+= strlen(argv
[i
]) + 1;
1619 for(; argv
[i
]; i
++) fprintf(err
," %s",argv
[i
]);
1621 fprintf(err
,"\n%*s^-- here\n",spcnt
,"");
1623 fprintf(err
,"\n%*shere --^\n",spcnt
-7,"");
1628 ** Return the index of the N-th non-switch argument. Return -1
1629 ** if N is out of range.
1631 static int argindex(n
)
1636 if( argv
!=0 && *argv
!=0 ){
1637 for(i
=1; argv
[i
]; i
++){
1638 if( dashdash
|| !ISOPT(argv
[i
]) ){
1639 if( n
==0 ) return i
;
1642 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
1648 static char emsg
[] = "Command line syntax error: ";
1651 ** Process a flag command line argument.
1653 static int handleflags(i
,err
)
1660 for(j
=0; op
[j
].label
; j
++){
1661 if( strcmp(&argv
[i
][1],op
[j
].label
)==0 ) break;
1663 v
= argv
[i
][0]=='-' ? 1 : 0;
1664 if( op
[j
].label
==0 ){
1666 fprintf(err
,"%sundefined option.\n",emsg
);
1670 }else if( op
[j
].type
==OPT_FLAG
){
1671 *((int*)op
[j
].arg
) = v
;
1672 }else if( op
[j
].type
==OPT_FFLAG
){
1673 (*(void(*)())(intptr_t)(op
[j
].arg
))(v
);
1676 fprintf(err
,"%smissing argument on switch.\n",emsg
);
1685 ** Process a command line switch which has an argument.
1687 static int handleswitch(i
,err
)
1697 cp
= strchr(argv
[i
],'=');
1699 for(j
=0; op
[j
].label
; j
++){
1700 if( strcmp(argv
[i
],op
[j
].label
)==0 ) break;
1703 if( op
[j
].label
==0 ){
1705 fprintf(err
,"%sundefined option.\n",emsg
);
1711 switch( op
[j
].type
){
1715 fprintf(err
,"%soption requires an argument.\n",emsg
);
1722 dv
= strtod(cp
,&end
);
1725 fprintf(err
,"%sillegal character in floating-point argument.\n",emsg
);
1726 errline(i
,((unsigned long)end
)-(unsigned long)argv
[i
],err
);
1733 lv
= strtol(cp
,&end
,0);
1736 fprintf(err
,"%sillegal character in integer argument.\n",emsg
);
1737 errline(i
,((unsigned long)end
)-(unsigned long)argv
[i
],err
);
1747 switch( op
[j
].type
){
1752 *(double*)(op
[j
].arg
) = dv
;
1755 (*(void(*)())(intptr_t)(op
[j
].arg
))(dv
);
1758 *(int*)(op
[j
].arg
) = lv
;
1761 (*(void(*)())(intptr_t)(op
[j
].arg
))((int)lv
);
1764 *(char**)(op
[j
].arg
) = sv
;
1767 (*(void(*)())(intptr_t)(op
[j
].arg
))(sv
);
1774 int OptInit(a
,o
,err
)
1776 struct s_options
*o
;
1783 if( argv
&& *argv
&& op
){
1785 for(i
=1; argv
[i
]; i
++){
1786 if( argv
[i
][0]=='+' || argv
[i
][0]=='-' ){
1787 errcnt
+= handleflags(i
,err
);
1788 }else if( strchr(argv
[i
],'=') ){
1789 errcnt
+= handleswitch(i
,err
);
1794 fprintf(err
,"Valid command line options for \"%s\" are:\n",*a
);
1805 if( argv
!=0 && argv
[0]!=0 ){
1806 for(i
=1; argv
[i
]; i
++){
1807 if( dashdash
|| !ISOPT(argv
[i
]) ) cnt
++;
1808 if( strcmp(argv
[i
],"--")==0 ) dashdash
= 1;
1819 return i
>=0 ? argv
[i
] : 0;
1827 if( i
>=0 ) errline(i
,0,errstream
);
1834 for(i
=0; op
[i
].label
; i
++){
1835 len
= strlen(op
[i
].label
) + 1;
1836 switch( op
[i
].type
){
1842 len
+= 9; /* length of "<integer>" */
1846 len
+= 6; /* length of "<real>" */
1850 len
+= 8; /* length of "<string>" */
1853 if( len
>max
) max
= len
;
1855 for(i
=0; op
[i
].label
; i
++){
1856 switch( op
[i
].type
){
1859 fprintf(errstream
," -%-*s %s\n",max
,op
[i
].label
,op
[i
].message
);
1863 fprintf(errstream
," %s=<integer>%*s %s\n",op
[i
].label
,
1864 (int)(max
-strlen(op
[i
].label
)-9),"",op
[i
].message
);
1868 fprintf(errstream
," %s=<real>%*s %s\n",op
[i
].label
,
1869 (int)(max
-strlen(op
[i
].label
)-6),"",op
[i
].message
);
1873 fprintf(errstream
," %s=<string>%*s %s\n",op
[i
].label
,
1874 (int)(max
-strlen(op
[i
].label
)-8),"",op
[i
].message
);
1879 /*********************** From the file "parse.c" ****************************/
1881 ** Input file parser for the LEMON parser generator.
1884 /* The state of the parser */
1886 char *filename
; /* Name of the input file */
1887 int tokenlineno
; /* Linenumber at which current token starts */
1888 int errorcnt
; /* Number of errors so far */
1889 char *tokenstart
; /* Text of current token */
1890 struct lemon
*gp
; /* Global state vector */
1893 WAITING_FOR_DECL_OR_RULE
,
1894 WAITING_FOR_DECL_KEYWORD
,
1895 WAITING_FOR_DECL_ARG
,
1896 WAITING_FOR_PRECEDENCE_SYMBOL
,
1906 RESYNC_AFTER_RULE_ERROR
,
1907 RESYNC_AFTER_DECL_ERROR
,
1908 WAITING_FOR_DESTRUCTOR_SYMBOL
,
1909 WAITING_FOR_DATATYPE_SYMBOL
,
1910 WAITING_FOR_FALLBACK_ID
1911 } state
; /* The state of the parser */
1912 struct symbol
*fallback
; /* The fallback token */
1913 struct symbol
*lhs
; /* Left-hand side of current rule */
1914 char *lhsalias
; /* Alias for the LHS */
1915 int nrhs
; /* Number of right-hand side symbols seen */
1916 struct symbol
*rhs
[MAXRHS
]; /* RHS symbols */
1917 char *alias
[MAXRHS
]; /* Aliases for each RHS symbol (or NULL) */
1918 struct rule
*prevrule
; /* Previous rule parsed */
1919 char *declkeyword
; /* Keyword of a declaration */
1920 char **declargslot
; /* Where the declaration argument should be put */
1921 int *decllnslot
; /* Where the declaration linenumber is put */
1922 enum e_assoc declassoc
; /* Assign this association to decl arguments */
1923 int preccounter
; /* Assign this precedence to decl arguments */
1924 struct rule
*firstrule
; /* Pointer to first rule in the grammar */
1925 struct rule
*lastrule
; /* Pointer to the most recently parsed rule */
1928 /* Parse a single token */
1929 static void parseonetoken(psp
)
1933 x
= Strsafe(psp
->tokenstart
); /* Save the token permanently */
1935 printf("%s:%d: Token=[%s] state=%d\n",psp
->filename
,psp
->tokenlineno
,
1938 switch( psp
->state
){
1941 psp
->preccounter
= 0;
1942 psp
->firstrule
= psp
->lastrule
= 0;
1944 /* Fall thru to next case */
1945 case WAITING_FOR_DECL_OR_RULE
:
1947 psp
->state
= WAITING_FOR_DECL_KEYWORD
;
1948 }else if( islower(x
[0]) ){
1949 psp
->lhs
= Symbol_new(x
);
1952 psp
->state
= WAITING_FOR_ARROW
;
1953 }else if( x
[0]=='{' ){
1954 if( psp
->prevrule
==0 ){
1955 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1956 "There is not prior rule opon which to attach the code \
1957 fragment which begins on this line.");
1959 }else if( psp
->prevrule
->code
!=0 ){
1960 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1961 "Code fragment beginning on this line is not the first \
1962 to follow the previous rule.");
1965 psp
->prevrule
->line
= psp
->tokenlineno
;
1966 psp
->prevrule
->code
= &x
[1];
1968 }else if( x
[0]=='[' ){
1969 psp
->state
= PRECEDENCE_MARK_1
;
1971 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1972 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
1977 case PRECEDENCE_MARK_1
:
1978 if( !isupper(x
[0]) ){
1979 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1980 "The precedence symbol must be a terminal.");
1982 }else if( psp
->prevrule
==0 ){
1983 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1984 "There is no prior rule to assign precedence \"[%s]\".",x
);
1986 }else if( psp
->prevrule
->precsym
!=0 ){
1987 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1988 "Precedence mark on this line is not the first \
1989 to follow the previous rule.");
1992 psp
->prevrule
->precsym
= Symbol_new(x
);
1994 psp
->state
= PRECEDENCE_MARK_2
;
1996 case PRECEDENCE_MARK_2
:
1998 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
1999 "Missing \"]\" on precedence mark.");
2002 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2004 case WAITING_FOR_ARROW
:
2005 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2006 psp
->state
= IN_RHS
;
2007 }else if( x
[0]=='(' ){
2008 psp
->state
= LHS_ALIAS_1
;
2010 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2011 "Expected to see a \":\" following the LHS symbol \"%s\".",
2014 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2018 if( isalpha(x
[0]) ){
2020 psp
->state
= LHS_ALIAS_2
;
2022 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2023 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2026 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2031 psp
->state
= LHS_ALIAS_3
;
2033 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2034 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2036 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2040 if( x
[0]==':' && x
[1]==':' && x
[2]=='=' ){
2041 psp
->state
= IN_RHS
;
2043 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2044 "Missing \"->\" following: \"%s(%s)\".",
2045 psp
->lhs
->name
,psp
->lhsalias
);
2047 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2053 rp
= (struct rule
*)malloc( sizeof(struct rule
) +
2054 sizeof(struct symbol
*)*psp
->nrhs
+ sizeof(char*)*psp
->nrhs
);
2056 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2057 "Can't allocate enough memory for this rule.");
2062 rp
->ruleline
= psp
->tokenlineno
;
2063 rp
->rhs
= (struct symbol
**)&rp
[1];
2064 rp
->rhsalias
= (char**)&(rp
->rhs
[psp
->nrhs
]);
2065 for(i
=0; i
<psp
->nrhs
; i
++){
2066 rp
->rhs
[i
] = psp
->rhs
[i
];
2067 rp
->rhsalias
[i
] = psp
->alias
[i
];
2070 rp
->lhsalias
= psp
->lhsalias
;
2071 rp
->nrhs
= psp
->nrhs
;
2074 rp
->index
= psp
->gp
->nrule
++;
2075 rp
->nextlhs
= rp
->lhs
->rule
;
2078 if( psp
->firstrule
==0 ){
2079 psp
->firstrule
= psp
->lastrule
= rp
;
2081 psp
->lastrule
->next
= rp
;
2086 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2087 }else if( isalpha(x
[0]) ){
2088 if( psp
->nrhs
>=MAXRHS
){
2089 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2090 "Too many symbol on RHS or rule beginning at \"%s\".",
2093 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2095 psp
->rhs
[psp
->nrhs
] = Symbol_new(x
);
2096 psp
->alias
[psp
->nrhs
] = 0;
2099 }else if( x
[0]=='(' && psp
->nrhs
>0 ){
2100 psp
->state
= RHS_ALIAS_1
;
2102 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2103 "Illegal character on RHS of rule: \"%s\".",x
);
2105 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2109 if( isalpha(x
[0]) ){
2110 psp
->alias
[psp
->nrhs
-1] = x
;
2111 psp
->state
= RHS_ALIAS_2
;
2113 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2114 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2115 x
,psp
->rhs
[psp
->nrhs
-1]->name
);
2117 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2122 psp
->state
= IN_RHS
;
2124 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2125 "Missing \")\" following LHS alias name \"%s\".",psp
->lhsalias
);
2127 psp
->state
= RESYNC_AFTER_RULE_ERROR
;
2130 case WAITING_FOR_DECL_KEYWORD
:
2131 if( isalpha(x
[0]) ){
2132 psp
->declkeyword
= x
;
2133 psp
->declargslot
= 0;
2134 psp
->decllnslot
= 0;
2135 psp
->state
= WAITING_FOR_DECL_ARG
;
2136 if( strcmp(x
,"name")==0 ){
2137 psp
->declargslot
= &(psp
->gp
->name
);
2138 }else if( strcmp(x
,"include")==0 ){
2139 psp
->declargslot
= &(psp
->gp
->include
);
2140 psp
->decllnslot
= &psp
->gp
->includeln
;
2141 }else if( strcmp(x
,"code")==0 ){
2142 psp
->declargslot
= &(psp
->gp
->extracode
);
2143 psp
->decllnslot
= &psp
->gp
->extracodeln
;
2144 }else if( strcmp(x
,"token_destructor")==0 ){
2145 psp
->declargslot
= &psp
->gp
->tokendest
;
2146 psp
->decllnslot
= &psp
->gp
->tokendestln
;
2147 }else if( strcmp(x
,"default_destructor")==0 ){
2148 psp
->declargslot
= &psp
->gp
->vardest
;
2149 psp
->decllnslot
= &psp
->gp
->vardestln
;
2150 }else if( strcmp(x
,"token_prefix")==0 ){
2151 psp
->declargslot
= &psp
->gp
->tokenprefix
;
2152 }else if( strcmp(x
,"syntax_error")==0 ){
2153 psp
->declargslot
= &(psp
->gp
->error
);
2154 psp
->decllnslot
= &psp
->gp
->errorln
;
2155 }else if( strcmp(x
,"parse_accept")==0 ){
2156 psp
->declargslot
= &(psp
->gp
->accept
);
2157 psp
->decllnslot
= &psp
->gp
->acceptln
;
2158 }else if( strcmp(x
,"parse_failure")==0 ){
2159 psp
->declargslot
= &(psp
->gp
->failure
);
2160 psp
->decllnslot
= &psp
->gp
->failureln
;
2161 }else if( strcmp(x
,"stack_overflow")==0 ){
2162 psp
->declargslot
= &(psp
->gp
->overflow
);
2163 psp
->decllnslot
= &psp
->gp
->overflowln
;
2164 }else if( strcmp(x
,"extra_argument")==0 ){
2165 psp
->declargslot
= &(psp
->gp
->arg
);
2166 }else if( strcmp(x
,"token_type")==0 ){
2167 psp
->declargslot
= &(psp
->gp
->tokentype
);
2168 }else if( strcmp(x
,"default_type")==0 ){
2169 psp
->declargslot
= &(psp
->gp
->vartype
);
2170 }else if( strcmp(x
,"stack_size")==0 ){
2171 psp
->declargslot
= &(psp
->gp
->stacksize
);
2172 }else if( strcmp(x
,"start_symbol")==0 ){
2173 psp
->declargslot
= &(psp
->gp
->start
);
2174 }else if( strcmp(x
,"left")==0 ){
2176 psp
->declassoc
= LEFT
;
2177 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2178 }else if( strcmp(x
,"right")==0 ){
2180 psp
->declassoc
= RIGHT
;
2181 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2182 }else if( strcmp(x
,"nonassoc")==0 ){
2184 psp
->declassoc
= NONE
;
2185 psp
->state
= WAITING_FOR_PRECEDENCE_SYMBOL
;
2186 }else if( strcmp(x
,"destructor")==0 ){
2187 psp
->state
= WAITING_FOR_DESTRUCTOR_SYMBOL
;
2188 }else if( strcmp(x
,"type")==0 ){
2189 psp
->state
= WAITING_FOR_DATATYPE_SYMBOL
;
2190 }else if( strcmp(x
,"fallback")==0 ){
2192 psp
->state
= WAITING_FOR_FALLBACK_ID
;
2194 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2195 "Unknown declaration keyword: \"%%%s\".",x
);
2197 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2200 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2201 "Illegal declaration keyword: \"%s\".",x
);
2203 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2206 case WAITING_FOR_DESTRUCTOR_SYMBOL
:
2207 if( !isalpha(x
[0]) ){
2208 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2209 "Symbol name missing after %destructor keyword");
2211 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2213 struct symbol
*sp
= Symbol_new(x
);
2214 psp
->declargslot
= &sp
->destructor
;
2215 psp
->decllnslot
= &sp
->destructorln
;
2216 psp
->state
= WAITING_FOR_DECL_ARG
;
2219 case WAITING_FOR_DATATYPE_SYMBOL
:
2220 if( !isalpha(x
[0]) ){
2221 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2222 "Symbol name missing after %destructor keyword");
2224 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2226 struct symbol
*sp
= Symbol_new(x
);
2227 psp
->declargslot
= &sp
->datatype
;
2228 psp
->decllnslot
= 0;
2229 psp
->state
= WAITING_FOR_DECL_ARG
;
2232 case WAITING_FOR_PRECEDENCE_SYMBOL
:
2234 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2235 }else if( isupper(x
[0]) ){
2239 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2240 "Symbol \"%s\" has already be given a precedence.",x
);
2243 sp
->prec
= psp
->preccounter
;
2244 sp
->assoc
= psp
->declassoc
;
2247 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2248 "Can't assign a precedence to \"%s\".",x
);
2252 case WAITING_FOR_DECL_ARG
:
2253 if( (x
[0]=='{' || x
[0]=='\"' || isalnum(x
[0])) ){
2254 if( *(psp
->declargslot
)!=0 ){
2255 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2256 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2257 x
[0]=='\"' ? &x
[1] : x
,psp
->declkeyword
);
2259 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2261 *(psp
->declargslot
) = (x
[0]=='\"' || x
[0]=='{') ? &x
[1] : x
;
2262 if( psp
->decllnslot
) *psp
->decllnslot
= psp
->tokenlineno
;
2263 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2266 ErrorMsg(psp
->filename
,psp
->tokenlineno
,
2267 "Illegal argument to %%%s: %s",psp
->declkeyword
,x
);
2269 psp
->state
= RESYNC_AFTER_DECL_ERROR
;
2272 case WAITING_FOR_FALLBACK_ID
:
2274 psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2275 }else if( !isupper(x
[0]) ){
2276 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2277 "%%fallback argument \"%s\" should be a token", x
);
2280 struct symbol
*sp
= Symbol_new(x
);
2281 if( psp
->fallback
==0 ){
2283 }else if( sp
->fallback
){
2284 ErrorMsg(psp
->filename
, psp
->tokenlineno
,
2285 "More than one fallback assigned to token %s", x
);
2288 sp
->fallback
= psp
->fallback
;
2289 psp
->gp
->has_fallback
= 1;
2293 case RESYNC_AFTER_RULE_ERROR
:
2294 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2296 case RESYNC_AFTER_DECL_ERROR
:
2297 if( x
[0]=='.' ) psp
->state
= WAITING_FOR_DECL_OR_RULE
;
2298 if( x
[0]=='%' ) psp
->state
= WAITING_FOR_DECL_KEYWORD
;
2303 /* In spite of its name, this function is really a scanner. It read
2304 ** in the entire input file (all at once) then tokenizes it. Each
2305 ** token is passed to the function "parseonetoken" which builds all
2306 ** the appropriate data structures in the global state vector "gp".
2321 ps
.filename
= gp
->filename
;
2323 ps
.state
= INITIALIZE
;
2325 /* Begin by reading the input file */
2326 fp
= fopen(ps
.filename
,"rb");
2328 ErrorMsg(ps
.filename
,0,"Can't open this file for reading.");
2333 filesize
= ftell(fp
);
2335 filebuf
= (char *)malloc( filesize
+1 );
2337 ErrorMsg(ps
.filename
,0,"Can't allocate %d of memory to hold this file.",
2343 if( fread(filebuf
,1,filesize
,fp
)!=filesize
){
2344 ErrorMsg(ps
.filename
,0,"Can't read in all %d bytes of this file.",
2352 filebuf
[filesize
] = 0;
2354 /* Now scan the text of the input file */
2356 for(cp
=filebuf
; (c
= *cp
)!=0; ){
2357 if( c
=='\n' ) lineno
++; /* Keep track of the line number */
2358 if( isspace(c
) ){ cp
++; continue; } /* Skip all white space */
2359 if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments */
2361 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2364 if( c
=='/' && cp
[1]=='*' ){ /* Skip C style comments */
2366 while( (c
= *cp
)!=0 && (c
!='/' || cp
[-1]!='*') ){
2367 if( c
=='\n' ) lineno
++;
2373 ps
.tokenstart
= cp
; /* Mark the beginning of the token */
2374 ps
.tokenlineno
= lineno
; /* Linenumber on which token begins */
2375 if( c
=='\"' ){ /* String literals */
2377 while( (c
= *cp
)!=0 && c
!='\"' ){
2378 if( c
=='\n' ) lineno
++;
2382 ErrorMsg(ps
.filename
,startline
,
2383 "String starting on this line is not terminated before the end of the file.");
2389 }else if( c
=='{' ){ /* A block of C code */
2392 for(level
=1; (c
= *cp
)!=0 && (level
>1 || c
!='}'); cp
++){
2393 if( c
=='\n' ) lineno
++;
2394 else if( c
=='{' ) level
++;
2395 else if( c
=='}' ) level
--;
2396 else if( c
=='/' && cp
[1]=='*' ){ /* Skip comments */
2400 while( (c
= *cp
)!=0 && (c
!='/' || prevc
!='*') ){
2401 if( c
=='\n' ) lineno
++;
2405 }else if( c
=='/' && cp
[1]=='/' ){ /* Skip C++ style comments too */
2407 while( (c
= *cp
)!=0 && c
!='\n' ) cp
++;
2409 }else if( c
=='\'' || c
=='\"' ){ /* String a character literals */
2410 int startchar
, prevc
;
2413 for(cp
++; (c
= *cp
)!=0 && (c
!=startchar
|| prevc
=='\\'); cp
++){
2414 if( c
=='\n' ) lineno
++;
2415 if( prevc
=='\\' ) prevc
= 0;
2421 ErrorMsg(ps
.filename
,ps
.tokenlineno
,
2422 "C code starting on this line is not terminated before the end of the file.");
2428 }else if( isalnum(c
) ){ /* Identifiers */
2429 while( (c
= *cp
)!=0 && (isalnum(c
) || c
=='_') ) cp
++;
2431 }else if( c
==':' && cp
[1]==':' && cp
[2]=='=' ){ /* The operator "::=" */
2434 }else{ /* All other (one character) operators */
2439 *cp
= 0; /* Null terminate the token */
2440 parseonetoken(&ps
); /* Parse the token */
2441 *cp
= c
; /* Restore the buffer */
2444 free(filebuf
); /* Release the buffer after parsing */
2445 gp
->rule
= ps
.firstrule
;
2446 gp
->errorcnt
= ps
.errorcnt
;
2448 /*************************** From the file "plink.c" *********************/
2450 ** Routines processing configuration follow-set propagation links
2451 ** in the LEMON parser generator.
2453 static struct plink
*plink_freelist
= 0;
2455 /* Allocate a new plink */
2456 struct plink
*Plink_new(){
2459 if( plink_freelist
==0 ){
2462 plink_freelist
= (struct plink
*)malloc( sizeof(struct plink
)*amt
);
2463 if( plink_freelist
==0 ){
2465 "Unable to allocate memory for a new follow-set propagation link.\n");
2468 for(i
=0; i
<amt
-1; i
++) plink_freelist
[i
].next
= &plink_freelist
[i
+1];
2469 plink_freelist
[amt
-1].next
= 0;
2471 new = plink_freelist
;
2472 plink_freelist
= plink_freelist
->next
;
2476 /* Add a plink to a plink list */
2477 void Plink_add(plpp
,cfp
)
2478 struct plink
**plpp
;
2488 /* Transfer every plink on the list "from" to the list "to" */
2489 void Plink_copy(to
,from
)
2493 struct plink
*nextpl
;
2495 nextpl
= from
->next
;
2502 /* Delete every plink on the list */
2503 void Plink_delete(plp
)
2506 struct plink
*nextpl
;
2510 plp
->next
= plink_freelist
;
2511 plink_freelist
= plp
;
2515 /*********************** From the file "report.c" **************************/
2517 ** Procedures for generating reports and tables in the LEMON parser generator.
2520 /* Generate a filename with the given suffix. Space to hold the
2521 ** name comes from malloc() and must be freed by the calling
2524 PRIVATE
char *file_makename(lemp
,suffix
)
2531 name
= malloc( strlen(lemp
->filename
) + strlen(suffix
) + 5 );
2533 fprintf(stderr
,"Can't allocate space for a filename.\n");
2536 /* skip directory, JK */
2537 if (NULL
== (cp
= strrchr(lemp
->filename
, '/'))) {
2538 cp
= lemp
->filename
;
2543 cp
= strrchr(name
,'.');
2545 strcat(name
,suffix
);
2549 /* Open a file with a name based on the name of the input file,
2550 ** but with a different (specified) suffix, and return a pointer
2552 PRIVATE
FILE *file_open(lemp
,suffix
,mode
)
2559 if( lemp
->outname
) free(lemp
->outname
);
2560 lemp
->outname
= file_makename(lemp
, suffix
);
2561 fp
= fopen(lemp
->outname
,mode
);
2562 if( fp
==0 && *mode
=='w' ){
2563 fprintf(stderr
,"Can't open file \"%s\".\n",lemp
->outname
);
2570 /* Duplicate the input file without comments and without actions
2577 int i
, j
, maxlen
, len
, ncolumns
, skip
;
2578 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp
->filename
);
2580 for(i
=0; i
<lemp
->nsymbol
; i
++){
2581 sp
= lemp
->symbols
[i
];
2582 len
= strlen(sp
->name
);
2583 if( len
>maxlen
) maxlen
= len
;
2585 ncolumns
= 76/(maxlen
+5);
2586 if( ncolumns
<1 ) ncolumns
= 1;
2587 skip
= (lemp
->nsymbol
+ ncolumns
- 1)/ncolumns
;
2588 for(i
=0; i
<skip
; i
++){
2590 for(j
=i
; j
<lemp
->nsymbol
; j
+=skip
){
2591 sp
= lemp
->symbols
[j
];
2592 assert( sp
->index
==j
);
2593 printf(" %3d %-*.*s",j
,maxlen
,maxlen
,sp
->name
);
2597 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
2598 printf("%s",rp
->lhs
->name
);
2599 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2601 for(i
=0; i
<rp
->nrhs
; i
++){
2602 printf(" %s",rp
->rhs
[i
]->name
);
2603 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2606 if( rp
->precsym
) printf(" [%s]",rp
->precsym
->name
);
2607 /* if( rp->code ) printf("\n %s",rp->code); */
2612 PRIVATE
void ConfigPrint(fp
,cfp
)
2619 fprintf(fp
,"%s ::=",rp
->lhs
->name
);
2620 for(i
=0; i
<=rp
->nrhs
; i
++){
2621 if( i
==cfp
->dot
) fprintf(fp
," *");
2622 if( i
==rp
->nrhs
) break;
2623 fprintf(fp
," %s",rp
->rhs
[i
]->name
);
2630 PRIVATE
void SetPrint(out
,set
,lemp
)
2638 fprintf(out
,"%12s[","");
2639 for(i
=0; i
<lemp
->nterminal
; i
++){
2640 if( SetFind(set
,i
) ){
2641 fprintf(out
,"%s%s",spacer
,lemp
->symbols
[i
]->name
);
2648 /* Print a plink chain */
2649 void PlinkPrint(out
,plp
,tag
)
2655 fprintf(out
,"%12s%s (state %2d) ","",tag
,plp
->cfp
->stp
->index
);
2656 ConfigPrint(out
,plp
->cfp
);
2663 /* Print an action to the given file descriptor. Return FALSE if
2664 ** nothing was actually printed.
2666 PRIVATE
int PrintAction(struct action
*ap
, FILE *fp
, int indent
){
2670 fprintf(fp
,"%*s shift %d",indent
,ap
->sp
->name
,ap
->x
.stp
->index
);
2673 fprintf(fp
,"%*s reduce %d",indent
,ap
->sp
->name
,ap
->x
.rp
->index
);
2676 fprintf(fp
,"%*s accept",indent
,ap
->sp
->name
);
2679 fprintf(fp
,"%*s error",indent
,ap
->sp
->name
);
2682 fprintf(fp
,"%*s reduce %-3d ** Parsing conflict **",
2683 indent
,ap
->sp
->name
,ap
->x
.rp
->index
);
2694 /* Generate the "y.output" log file */
2695 void ReportOutput(lemp
)
2704 fp
= file_open(lemp
,".out","w");
2707 for(i
=0; i
<lemp
->nstate
; i
++){
2708 stp
= lemp
->sorted
[i
];
2709 fprintf(fp
,"State %d:\n",stp
->index
);
2710 if( lemp
->basisflag
) cfp
=stp
->bp
;
2714 if( cfp
->dot
==cfp
->rp
->nrhs
){
2715 sprintf(buf
,"(%d)",cfp
->rp
->index
);
2716 fprintf(fp
," %5s ",buf
);
2720 ConfigPrint(fp
,cfp
);
2723 SetPrint(fp
,cfp
->fws
,lemp
);
2724 PlinkPrint(fp
,cfp
->fplp
,"To ");
2725 PlinkPrint(fp
,cfp
->bplp
,"From");
2727 if( lemp
->basisflag
) cfp
=cfp
->bp
;
2731 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
2732 if( PrintAction(ap
,fp
,30) ) fprintf(fp
,"\n");
2740 /* Search for the file "name" which is in the same directory as
2741 ** the exacutable */
2742 PRIVATE
char *pathsearch(argv0
,name
,modemask
)
2752 cp
= strrchr(argv0
,'\\');
2754 cp
= strrchr(argv0
,'/');
2759 path
= (char *)malloc( strlen(argv0
) + strlen(name
) + 2 );
2760 if( path
) sprintf(path
,"%s/%s",argv0
,name
);
2763 pathlist
= getenv("PATH");
2764 if( pathlist
==0 ) pathlist
= ".:/bin:/usr/bin";
2765 path
= (char *)malloc( strlen(pathlist
)+strlen(name
)+2 );
2768 cp
= strchr(pathlist
,':');
2769 if( cp
==0 ) cp
= &pathlist
[strlen(pathlist
)];
2772 sprintf(path
,"%s/%s",pathlist
,name
);
2774 if( c
==0 ) pathlist
= "";
2775 else pathlist
= &cp
[1];
2776 if( access(path
,modemask
)==0 ) break;
2783 /* Given an action, compute the integer value for that action
2784 ** which is to be put in the action table of the generated machine.
2785 ** Return negative if no action should be generated.
2787 PRIVATE
int compute_action(lemp
,ap
)
2793 case SHIFT
: act
= ap
->x
.stp
->index
; break;
2794 case REDUCE
: act
= ap
->x
.rp
->index
+ lemp
->nstate
; break;
2795 case ERROR
: act
= lemp
->nstate
+ lemp
->nrule
; break;
2796 case ACCEPT
: act
= lemp
->nstate
+ lemp
->nrule
+ 1; break;
2797 default: act
= -1; break;
2802 #define LINESIZE 1000
2803 /* The next cluster of routines are for reading the template file
2804 ** and writing the results to the generated parser */
2805 /* The first function transfers data from "in" to "out" until
2806 ** a line is seen which begins with "%%". The line number is
2809 ** if name!=0, then any word that begin with "Parse" is changed to
2810 ** begin with *name instead.
2812 PRIVATE
void tplt_xfer(name
,in
,out
,lineno
)
2819 char line
[LINESIZE
];
2820 while( fgets(line
,LINESIZE
,in
) && (line
[0]!='%' || line
[1]!='%') ){
2824 for(i
=0; line
[i
]; i
++){
2825 if( line
[i
]=='P' && strncmp(&line
[i
],"Parse",5)==0
2826 && (i
==0 || !isalpha(line
[i
-1]))
2828 if( i
>iStart
) fprintf(out
,"%.*s",i
-iStart
,&line
[iStart
]);
2829 fprintf(out
,"%s",name
);
2835 fprintf(out
,"%s",&line
[iStart
]);
2839 /* The next function finds the template file and opens it, returning
2840 ** a pointer to the opened file. */
2841 PRIVATE
FILE *tplt_open(lemp
)
2848 char *tpltname_alloc
= NULL
;
2851 cp
= strrchr(lemp
->filename
,'.');
2853 sprintf(buf
,"%.*s.lt",(int)(cp
-lemp
->filename
),lemp
->filename
);
2855 sprintf(buf
,"%s.lt",lemp
->filename
);
2857 if( access(buf
,004)==0 ){
2859 }else if( access(lemp
->tmplname
,004)==0 ){
2860 tpltname
= lemp
->tmplname
;
2862 tpltname
= tpltname_alloc
= pathsearch(lemp
->argv0
,lemp
->tmplname
,0);
2865 fprintf(stderr
,"Can't find the parser driver template file \"%s\".\n",
2870 in
= fopen(tpltname
,"r");
2872 fprintf(stderr
,"Can't open the template file \"%s\".\n",tpltname
);
2875 if (tpltname_alloc
) free(tpltname_alloc
);
2879 /* Print a string to the file and keep the linenumber up to date */
2880 PRIVATE
void tplt_print(out
,lemp
,str
,strln
,lineno
)
2887 if( str
==0 ) return;
2888 fprintf(out
,"#line %d \"%s\"\n",strln
,lemp
->filename
); (*lineno
)++;
2890 if( *str
=='\n' ) (*lineno
)++;
2894 fprintf(out
,"\n#line %d \"%s\"\n",*lineno
+2,lemp
->outname
); (*lineno
)+=2;
2899 ** The following routine emits code for the destructor for the
2902 PRIVATE
void emit_destructor_code(out
,sp
,lemp
,lineno
)
2911 if( sp
->type
==TERMINAL
){
2912 cp
= lemp
->tokendest
;
2914 fprintf(out
,"#line %d \"%s\"\n{",lemp
->tokendestln
,lemp
->filename
);
2915 }else if( sp
->destructor
){
2916 cp
= sp
->destructor
;
2917 fprintf(out
,"#line %d \"%s\"\n{",sp
->destructorln
,lemp
->filename
);
2921 fprintf(out
,"#line %d \"%s\"\n{",lemp
->vardestln
,lemp
->filename
);
2924 if( *cp
=='$' && cp
[1]=='$' ){
2925 fprintf(out
,"(yypminor->yy%d)",sp
->dtnum
);
2929 if( *cp
=='\n' ) linecnt
++;
2932 (*lineno
) += 3 + linecnt
;
2933 fprintf(out
,"}\n#line %d \"%s\"\n",*lineno
,lemp
->outname
);
2938 ** Return TRUE (non-zero) if the given symbol has a destructor.
2940 PRIVATE
int has_destructor(sp
, lemp
)
2945 if( sp
->type
==TERMINAL
){
2946 ret
= lemp
->tokendest
!=0;
2948 ret
= lemp
->vardest
!=0 || sp
->destructor
!=0;
2954 ** Generate code which executes when the rule "rp" is reduced. Write
2955 ** the code to "out". Make sure lineno stays up-to-date.
2957 PRIVATE
void emit_code(out
,rp
,lemp
,lineno
)
2966 char lhsused
= 0; /* True if the LHS element has been used */
2967 char used
[MAXRHS
]; /* True for each RHS element which is used */
2969 for(i
=0; i
<rp
->nrhs
; i
++) used
[i
] = 0;
2972 /* Generate code to do the reduce action */
2974 fprintf(out
,"#line %d \"%s\"\n{",rp
->line
,lemp
->filename
);
2975 for(cp
=rp
->code
; *cp
; cp
++){
2976 if( isalpha(*cp
) && (cp
==rp
->code
|| (!isalnum(cp
[-1]) && cp
[-1]!='_')) ){
2978 for(xp
= &cp
[1]; isalnum(*xp
) || *xp
=='_'; xp
++);
2981 if( rp
->lhsalias
&& strcmp(cp
,rp
->lhsalias
)==0 ){
2982 fprintf(out
,"yygotominor.yy%d",rp
->lhs
->dtnum
);
2986 for(i
=0; i
<rp
->nrhs
; i
++){
2987 if( rp
->rhsalias
[i
] && strcmp(cp
,rp
->rhsalias
[i
])==0 ){
2988 fprintf(out
,"yymsp[%d].minor.yy%d",i
-rp
->nrhs
+1,rp
->rhs
[i
]->dtnum
);
2997 if( *cp
=='\n' ) linecnt
++;
3000 (*lineno
) += 3 + linecnt
;
3001 fprintf(out
,"}\n#line %d \"%s\"\n",*lineno
,lemp
->outname
);
3002 } /* End if( rp->code ) */
3004 /* Check to make sure the LHS has been used */
3005 if( rp
->lhsalias
&& !lhsused
){
3006 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3007 "Label \"%s\" for \"%s(%s)\" is never used.",
3008 rp
->lhsalias
,rp
->lhs
->name
,rp
->lhsalias
);
3012 /* Generate destructor code for RHS symbols which are not used in the
3014 for(i
=0; i
<rp
->nrhs
; i
++){
3015 if( rp
->rhsalias
[i
] && !used
[i
] ){
3016 ErrorMsg(lemp
->filename
,rp
->ruleline
,
3017 "Label %s for \"%s(%s)\" is never used.",
3018 rp
->rhsalias
[i
],rp
->rhs
[i
]->name
,rp
->rhsalias
[i
]);
3020 }else if( rp
->rhsalias
[i
]==0 ){
3021 if( has_destructor(rp
->rhs
[i
],lemp
) ){
3022 fprintf(out
," yy_destructor(%d,&yymsp[%d].minor);\n",
3023 rp
->rhs
[i
]->index
,i
-rp
->nrhs
+1); (*lineno
)++;
3025 fprintf(out
," /* No destructor defined for %s */\n",
3035 ** Print the definition of the union used for the parser's data stack.
3036 ** This union contains fields for every possible data type for tokens
3037 ** and nonterminals. In the process of computing and printing this
3038 ** union, also set the ".dtnum" field of every terminal and nonterminal
3041 PRIVATE
void print_stack_union(out
,lemp
,plineno
,mhflag
)
3042 FILE *out
; /* The output stream */
3043 struct lemon
*lemp
; /* The main info structure for this parser */
3044 int *plineno
; /* Pointer to the line number */
3045 int mhflag
; /* True if generating makeheaders output */
3047 int lineno
; /* The line number of the output */
3048 char **types
; /* A hash table of datatypes */
3049 int arraysize
; /* Size of the "types" array */
3050 int maxdtlength
; /* Maximum length of any ".datatype" field. */
3051 char *stddt
; /* Standardized name for a datatype */
3052 int i
,j
; /* Loop counters */
3053 int hash
; /* For hashing the name of a type */
3054 char *name
; /* Name of the parser */
3056 /* Allocate and initialize types[] and allocate stddt[] */
3057 arraysize
= lemp
->nsymbol
* 2;
3058 types
= (char**)malloc( arraysize
* sizeof(char*) );
3059 for(i
=0; i
<arraysize
; i
++) types
[i
] = 0;
3061 if( lemp
->vartype
){
3062 maxdtlength
= strlen(lemp
->vartype
);
3064 for(i
=0; i
<lemp
->nsymbol
; i
++){
3066 struct symbol
*sp
= lemp
->symbols
[i
];
3067 if( sp
->datatype
==0 ) continue;
3068 len
= strlen(sp
->datatype
);
3069 if( len
>maxdtlength
) maxdtlength
= len
;
3071 stddt
= (char*)malloc( maxdtlength
*2 + 1 );
3072 if( types
==0 || stddt
==0 ){
3073 fprintf(stderr
,"Out of memory.\n");
3077 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3078 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
3079 ** used for terminal symbols. If there is no %default_type defined then
3080 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3081 ** a datatype using the %type directive.
3083 for(i
=0; i
<lemp
->nsymbol
; i
++){
3084 struct symbol
*sp
= lemp
->symbols
[i
];
3086 if( sp
==lemp
->errsym
){
3087 sp
->dtnum
= arraysize
+1;
3090 if( sp
->type
!=NONTERMINAL
|| (sp
->datatype
==0 && lemp
->vartype
==0) ){
3095 if( cp
==0 ) cp
= lemp
->vartype
;
3097 while( isspace(*cp
) ) cp
++;
3098 while( *cp
) stddt
[j
++] = *cp
++;
3099 while( j
>0 && isspace(stddt
[j
-1]) ) j
--;
3102 for(j
=0; stddt
[j
]; j
++){
3103 hash
= (unsigned int)hash
*53u + (unsigned int) stddt
[j
];
3105 hash
= (hash
& 0x7fffffff)%arraysize
;
3106 while( types
[hash
] ){
3107 if( strcmp(types
[hash
],stddt
)==0 ){
3108 sp
->dtnum
= hash
+ 1;
3112 if( hash
>=arraysize
) hash
= 0;
3114 if( types
[hash
]==0 ){
3115 sp
->dtnum
= hash
+ 1;
3116 types
[hash
] = (char*)malloc( strlen(stddt
)+1 );
3117 if( types
[hash
]==0 ){
3118 fprintf(stderr
,"Out of memory.\n");
3121 strcpy(types
[hash
],stddt
);
3125 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3126 name
= lemp
->name
? lemp
->name
: "Parse";
3128 if( mhflag
){ fprintf(out
,"#if INTERFACE\n"); lineno
++; }
3129 fprintf(out
,"#define %sTOKENTYPE %s\n",name
,
3130 lemp
->tokentype
?lemp
->tokentype
:"void*"); lineno
++;
3131 if( mhflag
){ fprintf(out
,"#endif\n"); lineno
++; }
3132 fprintf(out
,"typedef union {\n"); lineno
++;
3133 fprintf(out
," %sTOKENTYPE yy0;\n",name
); lineno
++;
3134 for(i
=0; i
<arraysize
; i
++){
3135 if( types
[i
]==0 ) continue;
3136 fprintf(out
," %s yy%d;\n",types
[i
],i
+1); lineno
++;
3139 fprintf(out
," int yy%d;\n",lemp
->errsym
->dtnum
); lineno
++;
3142 fprintf(out
,"} YYMINORTYPE;\n"); lineno
++;
3147 ** Return the name of a C datatype able to represent values between
3148 ** lwr and upr, inclusive.
3150 static const char *minimum_size_type(int lwr
, int upr
){
3153 return "unsigned char";
3154 }else if( upr
<65535 ){
3155 return "unsigned short int";
3157 return "unsigned int";
3159 }else if( lwr
>=-127 && upr
<=127 ){
3160 return "signed char";
3161 }else if( lwr
>=-32767 && upr
<32767 ){
3169 ** Each state contains a set of token transaction and a set of
3170 ** nonterminal transactions. Each of these sets makes an instance
3171 ** of the following structure. An array of these structures is used
3172 ** to order the creation of entries in the yy_action[] table.
3175 struct state
*stp
; /* A pointer to a state */
3176 int isTkn
; /* True to use tokens. False for non-terminals */
3177 int nAction
; /* Number of actions */
3181 ** Compare to axset structures for sorting purposes
3183 static int axset_compare(const void *a
, const void *b
){
3184 struct axset
*p1
= (struct axset
*)a
;
3185 struct axset
*p2
= (struct axset
*)b
;
3186 return p2
->nAction
- p1
->nAction
;
3189 /* Generate C source code for the parser */
3190 void ReportTable(lemp
, mhflag
)
3192 int mhflag
; /* Output in makeheaders format if true */
3195 char line
[LINESIZE
];
3200 struct acttab
*pActtab
;
3202 int mnTknOfst
, mxTknOfst
;
3203 int mnNtOfst
, mxNtOfst
;
3207 in
= tplt_open(lemp
);
3209 out
= file_open(lemp
,".c","w");
3215 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3217 /* Generate the include code, if any */
3218 tplt_print(out
,lemp
,lemp
->include
,lemp
->includeln
,&lineno
);
3220 name
= file_makename(lemp
, ".h");
3221 fprintf(out
,"#include \"%s\"\n", name
); lineno
++;
3224 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3226 /* Generate #defines for all tokens */
3229 fprintf(out
,"#if INTERFACE\n"); lineno
++;
3230 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
3232 for(i
=1; i
<lemp
->nterminal
; i
++){
3233 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
3236 fprintf(out
,"#endif\n"); lineno
++;
3238 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3240 /* Generate the defines */
3241 fprintf(out
,"/* \001 */\n");
3242 fprintf(out
,"#define YYCODETYPE %s\n",
3243 minimum_size_type(0, lemp
->nsymbol
+5)); lineno
++;
3244 fprintf(out
,"#define YYNOCODE %d\n",lemp
->nsymbol
+1); lineno
++;
3245 fprintf(out
,"#define YYACTIONTYPE %s\n",
3246 minimum_size_type(0, lemp
->nstate
+lemp
->nrule
+5)); lineno
++;
3247 print_stack_union(out
,lemp
,&lineno
,mhflag
);
3248 if( lemp
->stacksize
){
3249 if( atoi(lemp
->stacksize
)<=0 ){
3250 ErrorMsg(lemp
->filename
,0,
3251 "Illegal stack size: [%s]. The stack size should be an integer constant.",
3254 lemp
->stacksize
= "100";
3256 fprintf(out
,"#define YYSTACKDEPTH %s\n",lemp
->stacksize
); lineno
++;
3258 fprintf(out
,"#define YYSTACKDEPTH 100\n"); lineno
++;
3261 fprintf(out
,"#if INTERFACE\n"); lineno
++;
3263 name
= lemp
->name
? lemp
->name
: "Parse";
3264 if( lemp
->arg
&& lemp
->arg
[0] ){
3265 i
= strlen(lemp
->arg
);
3266 while( i
>=1 && isspace(lemp
->arg
[i
-1]) ) i
--;
3267 while( i
>=1 && (isalnum(lemp
->arg
[i
-1]) || lemp
->arg
[i
-1]=='_') ) i
--;
3268 fprintf(out
,"#define %sARG_SDECL %s;\n",name
,lemp
->arg
); lineno
++;
3269 fprintf(out
,"#define %sARG_PDECL ,%s\n",name
,lemp
->arg
); lineno
++;
3270 fprintf(out
,"#define %sARG_FETCH %s = yypParser->%s\n",
3271 name
,lemp
->arg
,&lemp
->arg
[i
]); lineno
++;
3272 fprintf(out
,"#define %sARG_STORE yypParser->%s = %s\n",
3273 name
,&lemp
->arg
[i
],&lemp
->arg
[i
]); lineno
++;
3275 fprintf(out
,"#define %sARG_SDECL\n",name
); lineno
++;
3276 fprintf(out
,"#define %sARG_PDECL\n",name
); lineno
++;
3277 fprintf(out
,"#define %sARG_FETCH\n",name
); lineno
++;
3278 fprintf(out
,"#define %sARG_STORE\n",name
); lineno
++;
3281 fprintf(out
,"#endif\n"); lineno
++;
3283 fprintf(out
,"#define YYNSTATE %d\n",lemp
->nstate
); lineno
++;
3284 fprintf(out
,"#define YYNRULE %d\n",lemp
->nrule
); lineno
++;
3285 fprintf(out
,"#define YYERRORSYMBOL %d\n",lemp
->errsym
->index
); lineno
++;
3286 fprintf(out
,"#define YYERRSYMDT yy%d\n",lemp
->errsym
->dtnum
); lineno
++;
3287 if( lemp
->has_fallback
){
3288 fprintf(out
,"#define YYFALLBACK 1\n"); lineno
++;
3290 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3292 /* Generate the action table and its associates:
3294 ** yy_action[] A single table containing all actions.
3295 ** yy_lookahead[] A table containing the lookahead for each entry in
3296 ** yy_action. Used to detect hash collisions.
3297 ** yy_shift_ofst[] For each state, the offset into yy_action for
3298 ** shifting terminals.
3299 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3300 ** shifting non-terminals after a reduce.
3301 ** yy_default[] Default action for each state.
3304 /* Compute the actions on all states and count them up */
3305 ax
= malloc( sizeof(ax
[0])*lemp
->nstate
*2 );
3307 fprintf(stderr
,"malloc failed\n");
3310 for(i
=0; i
<lemp
->nstate
; i
++){
3311 stp
= lemp
->sorted
[i
];
3312 stp
->nTknAct
= stp
->nNtAct
= 0;
3313 stp
->iDflt
= lemp
->nstate
+ lemp
->nrule
;
3314 stp
->iTknOfst
= NO_OFFSET
;
3315 stp
->iNtOfst
= NO_OFFSET
;
3316 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3317 if( compute_action(lemp
,ap
)>=0 ){
3318 if( ap
->sp
->index
<lemp
->nterminal
){
3320 }else if( ap
->sp
->index
<lemp
->nsymbol
){
3323 stp
->iDflt
= compute_action(lemp
, ap
);
3329 ax
[i
*2].nAction
= stp
->nTknAct
;
3330 ax
[i
*2+1].stp
= stp
;
3331 ax
[i
*2+1].isTkn
= 0;
3332 ax
[i
*2+1].nAction
= stp
->nNtAct
;
3334 mxTknOfst
= mnTknOfst
= 0;
3335 mxNtOfst
= mnNtOfst
= 0;
3337 /* Compute the action table. In order to try to keep the size of the
3338 ** action table to a minimum, the heuristic of placing the largest action
3339 ** sets first is used.
3341 qsort(ax
, lemp
->nstate
*2, sizeof(ax
[0]), axset_compare
);
3342 pActtab
= acttab_alloc();
3343 for(i
=0; i
<lemp
->nstate
*2 && ax
[i
].nAction
>0; i
++){
3346 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3348 if( ap
->sp
->index
>=lemp
->nterminal
) continue;
3349 action
= compute_action(lemp
, ap
);
3350 if( action
<0 ) continue;
3351 acttab_action(pActtab
, ap
->sp
->index
, action
);
3353 stp
->iTknOfst
= acttab_insert(pActtab
);
3354 if( stp
->iTknOfst
<mnTknOfst
) mnTknOfst
= stp
->iTknOfst
;
3355 if( stp
->iTknOfst
>mxTknOfst
) mxTknOfst
= stp
->iTknOfst
;
3357 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3359 if( ap
->sp
->index
<lemp
->nterminal
) continue;
3360 if( ap
->sp
->index
==lemp
->nsymbol
) continue;
3361 action
= compute_action(lemp
, ap
);
3362 if( action
<0 ) continue;
3363 acttab_action(pActtab
, ap
->sp
->index
, action
);
3365 stp
->iNtOfst
= acttab_insert(pActtab
);
3366 if( stp
->iNtOfst
<mnNtOfst
) mnNtOfst
= stp
->iNtOfst
;
3367 if( stp
->iNtOfst
>mxNtOfst
) mxNtOfst
= stp
->iNtOfst
;
3372 /* Output the yy_action table */
3373 fprintf(out
,"static YYACTIONTYPE yy_action[] = {\n"); lineno
++;
3374 n
= acttab_size(pActtab
);
3375 for(i
=j
=0; i
<n
; i
++){
3376 int action
= acttab_yyaction(pActtab
, i
);
3377 if( action
<0 ) action
= lemp
->nsymbol
+ lemp
->nrule
+ 2;
3378 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3379 fprintf(out
, " %4d,", action
);
3380 if( j
==9 || i
==n
-1 ){
3381 fprintf(out
, "\n"); lineno
++;
3387 fprintf(out
, "};\n"); lineno
++;
3389 /* Output the yy_lookahead table */
3390 fprintf(out
,"static YYCODETYPE yy_lookahead[] = {\n"); lineno
++;
3391 for(i
=j
=0; i
<n
; i
++){
3392 int la
= acttab_yylookahead(pActtab
, i
);
3393 if( la
<0 ) la
= lemp
->nsymbol
;
3394 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3395 fprintf(out
, " %4d,", la
);
3396 if( j
==9 || i
==n
-1 ){
3397 fprintf(out
, "\n"); lineno
++;
3403 fprintf(out
, "};\n"); lineno
++;
3405 /* Output the yy_shift_ofst[] table */
3406 fprintf(out
, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst
-1); lineno
++;
3407 fprintf(out
, "static %s yy_shift_ofst[] = {\n",
3408 minimum_size_type(mnTknOfst
-1, mxTknOfst
)); lineno
++;
3410 for(i
=j
=0; i
<n
; i
++){
3412 stp
= lemp
->sorted
[i
];
3413 ofst
= stp
->iTknOfst
;
3414 if( ofst
==NO_OFFSET
) ofst
= mnTknOfst
- 1;
3415 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3416 fprintf(out
, " %4d,", ofst
);
3417 if( j
==9 || i
==n
-1 ){
3418 fprintf(out
, "\n"); lineno
++;
3424 fprintf(out
, "};\n"); lineno
++;
3426 /* Output the yy_reduce_ofst[] table */
3427 fprintf(out
, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst
-1); lineno
++;
3428 fprintf(out
, "static %s yy_reduce_ofst[] = {\n",
3429 minimum_size_type(mnNtOfst
-1, mxNtOfst
)); lineno
++;
3431 for(i
=j
=0; i
<n
; i
++){
3433 stp
= lemp
->sorted
[i
];
3434 ofst
= stp
->iNtOfst
;
3435 if( ofst
==NO_OFFSET
) ofst
= mnNtOfst
- 1;
3436 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3437 fprintf(out
, " %4d,", ofst
);
3438 if( j
==9 || i
==n
-1 ){
3439 fprintf(out
, "\n"); lineno
++;
3445 fprintf(out
, "};\n"); lineno
++;
3447 /* Output the default action table */
3448 fprintf(out
, "static YYACTIONTYPE yy_default[] = {\n"); lineno
++;
3450 for(i
=j
=0; i
<n
; i
++){
3451 stp
= lemp
->sorted
[i
];
3452 if( j
==0 ) fprintf(out
," /* %5d */ ", i
);
3453 fprintf(out
, " %4d,", stp
->iDflt
);
3454 if( j
==9 || i
==n
-1 ){
3455 fprintf(out
, "\n"); lineno
++;
3461 fprintf(out
, "};\n"); lineno
++;
3462 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3464 /* Generate the table of fallback tokens.
3466 if( lemp
->has_fallback
){
3467 for(i
=0; i
<lemp
->nterminal
; i
++){
3468 struct symbol
*p
= lemp
->symbols
[i
];
3469 if( p
->fallback
==0 ){
3470 fprintf(out
, " 0, /* %10s => nothing */\n", p
->name
);
3472 fprintf(out
, " %3d, /* %10s => %s */\n", p
->fallback
->index
,
3473 p
->name
, p
->fallback
->name
);
3478 tplt_xfer(lemp
->name
, in
, out
, &lineno
);
3480 /* Generate a table containing the symbolic name of every symbol
3482 for(i
=0; i
<lemp
->nsymbol
; i
++){
3483 sprintf(line
,"\"%s\",",lemp
->symbols
[i
]->name
);
3484 fprintf(out
," %-15s",line
);
3485 if( (i
&3)==3 ){ fprintf(out
,"\n"); lineno
++; }
3487 if( (i
&3)!=0 ){ fprintf(out
,"\n"); lineno
++; }
3488 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3490 /* Generate a table containing a text string that describes every
3491 ** rule in the rule set of the grammer. This information is used
3492 ** when tracing REDUCE actions.
3494 for(i
=0, rp
=lemp
->rule
; rp
; rp
=rp
->next
, i
++){
3495 assert( rp
->index
==i
);
3496 fprintf(out
," /* %3d */ \"%s ::=", i
, rp
->lhs
->name
);
3497 for(j
=0; j
<rp
->nrhs
; j
++) fprintf(out
," %s",rp
->rhs
[j
]->name
);
3498 fprintf(out
,"\",\n"); lineno
++;
3500 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3502 /* Generate code which executes every time a symbol is popped from
3503 ** the stack while processing errors or while destroying the parser.
3504 ** (In other words, generate the %destructor actions)
3506 if( lemp
->tokendest
){
3507 for(i
=0; i
<lemp
->nsymbol
; i
++){
3508 struct symbol
*sp
= lemp
->symbols
[i
];
3509 if( sp
==0 || sp
->type
!=TERMINAL
) continue;
3510 fprintf(out
," case %d:\n",sp
->index
); lineno
++;
3512 for(i
=0; i
<lemp
->nsymbol
&& lemp
->symbols
[i
]->type
!=TERMINAL
; i
++);
3513 if( i
<lemp
->nsymbol
){
3514 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
3515 fprintf(out
," break;\n"); lineno
++;
3518 for(i
=0; i
<lemp
->nsymbol
; i
++){
3519 struct symbol
*sp
= lemp
->symbols
[i
];
3520 if( sp
==0 || sp
->type
==TERMINAL
|| sp
->destructor
==0 ) continue;
3521 fprintf(out
," case %d:\n",sp
->index
); lineno
++;
3522 emit_destructor_code(out
,lemp
->symbols
[i
],lemp
,&lineno
);
3523 fprintf(out
," break;\n"); lineno
++;
3525 if( lemp
->vardest
){
3526 struct symbol
*dflt_sp
= 0;
3527 for(i
=0; i
<lemp
->nsymbol
; i
++){
3528 struct symbol
*sp
= lemp
->symbols
[i
];
3529 if( sp
==0 || sp
->type
==TERMINAL
||
3530 sp
->index
<=0 || sp
->destructor
!=0 ) continue;
3531 fprintf(out
," case %d:\n",sp
->index
); lineno
++;
3535 emit_destructor_code(out
,dflt_sp
,lemp
,&lineno
);
3536 fprintf(out
," break;\n"); lineno
++;
3539 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3541 /* Generate code which executes whenever the parser stack overflows */
3542 tplt_print(out
,lemp
,lemp
->overflow
,lemp
->overflowln
,&lineno
);
3543 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3545 /* Generate the table of rule information
3547 ** Note: This code depends on the fact that rules are number
3548 ** sequentually beginning with 0.
3550 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3551 fprintf(out
," { %d, %d },\n",rp
->lhs
->index
,rp
->nrhs
); lineno
++;
3553 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3555 /* Generate code which execution during each REDUCE action */
3556 for(rp
=lemp
->rule
; rp
; rp
=rp
->next
){
3557 fprintf(out
," case %d:\n",rp
->index
); lineno
++;
3558 emit_code(out
,rp
,lemp
,&lineno
);
3559 fprintf(out
," break;\n"); lineno
++;
3561 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3563 /* Generate code which executes if a parse fails */
3564 tplt_print(out
,lemp
,lemp
->failure
,lemp
->failureln
,&lineno
);
3565 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3567 /* Generate code which executes when a syntax error occurs */
3568 tplt_print(out
,lemp
,lemp
->error
,lemp
->errorln
,&lineno
);
3569 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3571 /* Generate code which executes when the parser accepts its input */
3572 tplt_print(out
,lemp
,lemp
->accept
,lemp
->acceptln
,&lineno
);
3573 tplt_xfer(lemp
->name
,in
,out
,&lineno
);
3575 /* Append any addition code the user desires */
3576 tplt_print(out
,lemp
,lemp
->extracode
,lemp
->extracodeln
,&lineno
);
3583 /* Generate a header file for the parser */
3584 void ReportHeader(lemp
)
3589 char line
[LINESIZE
];
3590 char pattern
[LINESIZE
];
3593 if( lemp
->tokenprefix
) prefix
= lemp
->tokenprefix
;
3595 in
= file_open(lemp
,".h","r");
3597 for(i
=1; i
<lemp
->nterminal
&& fgets(line
,LINESIZE
,in
); i
++){
3598 sprintf(pattern
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
3599 if( strcmp(line
,pattern
) ) break;
3602 if( i
==lemp
->nterminal
){
3603 /* No change in the file. Don't rewrite it. */
3607 out
= file_open(lemp
,".h","w");
3609 for(i
=1; i
<lemp
->nterminal
; i
++){
3610 fprintf(out
,"#define %s%-30s %2d\n",prefix
,lemp
->symbols
[i
]->name
,i
);
3617 /* Reduce the size of the action tables, if possible, by making use
3620 ** In this version, we take the most frequent REDUCE action and make
3621 ** it the default. Only default a reduce if there are more than one.
3623 void CompressTables(lemp
)
3627 struct action
*ap
, *ap2
;
3628 struct rule
*rp
, *rp2
, *rbest
;
3632 for(i
=0; i
<lemp
->nstate
; i
++){
3633 stp
= lemp
->sorted
[i
];
3637 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3638 if( ap
->type
!=REDUCE
) continue;
3640 if( rp
==rbest
) continue;
3642 for(ap2
=ap
->next
; ap2
; ap2
=ap2
->next
){
3643 if( ap2
->type
!=REDUCE
) continue;
3645 if( rp2
==rbest
) continue;
3654 /* Do not make a default if the number of rules to default
3655 ** is not at least 2 */
3656 if( nbest
<2 ) continue;
3659 /* Combine matching REDUCE actions into a single default */
3660 for(ap
=stp
->ap
; ap
; ap
=ap
->next
){
3661 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) break;
3664 ap
->sp
= Symbol_new("{default}");
3665 for(ap
=ap
->next
; ap
; ap
=ap
->next
){
3666 if( ap
->type
==REDUCE
&& ap
->x
.rp
==rbest
) ap
->type
= NOT_USED
;
3668 stp
->ap
= Action_sort(stp
->ap
);
3672 /***************** From the file "set.c" ************************************/
3674 ** Set manipulation routines for the LEMON parser generator.
3677 static int global_size
= 0;
3679 /* Set the set size */
3686 /* Allocate a new set */
3690 s
= (char*)malloc( global_size
);
3694 for(i
=0; i
<global_size
; i
++) s
[i
] = 0;
3698 /* Deallocate a set */
3705 /* Add a new element to the set. Return TRUE if the element was added
3706 ** and FALSE if it was already there. */
3717 /* Add every element of s2 to s1. Return TRUE if s1 changes. */
3724 for(i
=0; i
<global_size
; i
++){
3725 if( s2
[i
]==0 ) continue;
3733 /********************** From the file "table.c" ****************************/
3735 ** All code in this file has been automatically generated
3736 ** from a specification in the file
3738 ** by the associative array code building program "aagen".
3739 ** Do not edit this file! Instead, edit the specification
3740 ** file, then rerun aagen.
3743 ** Code for processing tables in the LEMON parser generator.
3746 PRIVATE
int strhash(x
)
3750 while( *x
) h
= h
*13u + (unsigned int) *(x
++);
3754 /* Works like strdup, sort of. Save a string in malloced memory, but
3755 ** keep strings in a table so that the same string is not in more
3763 z
= Strsafe_find(y
);
3764 if( z
==0 && (z
=malloc( strlen(y
)+1 ))!=0 ){
3772 /* There is one instance of the following structure for each
3773 ** associative array of type "x1".
3776 int size
; /* The number of available slots. */
3777 /* Must be a power of 2 greater than or */
3779 int count
; /* Number of currently slots filled */
3780 struct s_x1node
*tbl
; /* The data stored here */
3781 struct s_x1node
**ht
; /* Hash table for lookups */
3784 /* There is one instance of this structure for every data element
3785 ** in an associative array of type "x1".
3787 typedef struct s_x1node
{
3788 char *data
; /* The data */
3789 struct s_x1node
*next
; /* Next entry with the same hash */
3790 struct s_x1node
**from
; /* Previous link */
3793 /* There is only one instance of the array, which is the following */
3794 static struct s_x1
*x1a
;
3796 /* Allocate a new associative array */
3797 void Strsafe_init(){
3799 x1a
= (struct s_x1
*)malloc( sizeof(struct s_x1
) );
3803 x1a
->tbl
= (x1node
*)malloc(
3804 (sizeof(x1node
) + sizeof(x1node
*))*1024 );
3810 x1a
->ht
= (x1node
**)&(x1a
->tbl
[1024]);
3811 for(i
=0; i
<1024; i
++) x1a
->ht
[i
] = 0;
3815 /* Insert a new record into the array. Return TRUE if successful.
3816 ** Prior data with the same key is NOT overwritten */
3817 int Strsafe_insert(data
)
3824 if( x1a
==0 ) return 0;
3826 h
= ph
& (x1a
->size
-1);
3829 if( strcmp(np
->data
,data
)==0 ){
3830 /* An existing entry with the same key is found. */
3831 /* Fail because overwrite is not allows. */
3836 if( x1a
->count
>=x1a
->size
){
3837 /* Need to make the hash table bigger */
3840 array
.size
= size
= x1a
->size
*2;
3841 array
.count
= x1a
->count
;
3842 array
.tbl
= (x1node
*)malloc(
3843 (sizeof(x1node
) + sizeof(x1node
*))*size
);
3844 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
3845 array
.ht
= (x1node
**)&(array
.tbl
[size
]);
3846 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
3847 for(i
=0; i
<x1a
->count
; i
++){
3848 x1node
*oldnp
, *newnp
;
3849 oldnp
= &(x1a
->tbl
[i
]);
3850 h
= strhash(oldnp
->data
) & (size
-1);
3851 newnp
= &(array
.tbl
[i
]);
3852 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
3853 newnp
->next
= array
.ht
[h
];
3854 newnp
->data
= oldnp
->data
;
3855 newnp
->from
= &(array
.ht
[h
]);
3856 array
.ht
[h
] = newnp
;
3859 /* *x1a = array; *//* copy 'array' */
3860 memcpy(x1a
, &array
, sizeof(array
));
3862 /* Insert the new data */
3863 h
= ph
& (x1a
->size
-1);
3864 np
= &(x1a
->tbl
[x1a
->count
++]);
3866 if( x1a
->ht
[h
] ) x1a
->ht
[h
]->from
= &(np
->next
);
3867 np
->next
= x1a
->ht
[h
];
3869 np
->from
= &(x1a
->ht
[h
]);
3873 /* Return a pointer to data assigned to the given key. Return NULL
3874 ** if no such key. */
3875 char *Strsafe_find(key
)
3881 if( x1a
==0 ) return 0;
3882 h
= strhash(key
) & (x1a
->size
-1);
3885 if( strcmp(np
->data
,key
)==0 ) break;
3888 return np
? np
->data
: 0;
3891 /* Return a pointer to the (terminal or nonterminal) symbol "x".
3892 ** Create a new symbol if this is the first time "x" has been seen.
3894 struct symbol
*Symbol_new(x
)
3899 sp
= Symbol_find(x
);
3901 sp
= (struct symbol
*)malloc( sizeof(struct symbol
) );
3903 sp
->name
= Strsafe(x
);
3904 sp
->type
= isupper(*x
) ? TERMINAL
: NONTERMINAL
;
3910 sp
->lambda
= Bo_FALSE
;
3913 Symbol_insert(sp
,sp
->name
);
3918 /* Compare two symbols for working purposes
3920 ** Symbols that begin with upper case letters (terminals or tokens)
3921 ** must sort before symbols that begin with lower case letters
3922 ** (non-terminals). Other than that, the order does not matter.
3924 ** We find experimentally that leaving the symbols in their original
3925 ** order (the order they appeared in the grammar file) gives the
3926 ** smallest parser tables in SQLite.
3928 int Symbolcmpp(struct symbol
**a
, struct symbol
**b
){
3929 int i1
= (**a
).index
+ 10000000*((**a
).name
[0]>'Z');
3930 int i2
= (**b
).index
+ 10000000*((**b
).name
[0]>'Z');
3934 /* There is one instance of the following structure for each
3935 ** associative array of type "x2".
3938 int size
; /* The number of available slots. */
3939 /* Must be a power of 2 greater than or */
3941 int count
; /* Number of currently slots filled */
3942 struct s_x2node
*tbl
; /* The data stored here */
3943 struct s_x2node
**ht
; /* Hash table for lookups */
3946 /* There is one instance of this structure for every data element
3947 ** in an associative array of type "x2".
3949 typedef struct s_x2node
{
3950 struct symbol
*data
; /* The data */
3951 char *key
; /* The key */
3952 struct s_x2node
*next
; /* Next entry with the same hash */
3953 struct s_x2node
**from
; /* Previous link */
3956 /* There is only one instance of the array, which is the following */
3957 static struct s_x2
*x2a
;
3959 /* Allocate a new associative array */
3962 x2a
= (struct s_x2
*)malloc( sizeof(struct s_x2
) );
3966 x2a
->tbl
= (x2node
*)malloc(
3967 (sizeof(x2node
) + sizeof(x2node
*))*128 );
3973 x2a
->ht
= (x2node
**)&(x2a
->tbl
[128]);
3974 for(i
=0; i
<128; i
++) x2a
->ht
[i
] = 0;
3978 /* Insert a new record into the array. Return TRUE if successful.
3979 ** Prior data with the same key is NOT overwritten */
3980 int Symbol_insert(data
,key
)
3981 struct symbol
*data
;
3988 if( x2a
==0 ) return 0;
3990 h
= ph
& (x2a
->size
-1);
3993 if( strcmp(np
->key
,key
)==0 ){
3994 /* An existing entry with the same key is found. */
3995 /* Fail because overwrite is not allows. */
4000 if( x2a
->count
>=x2a
->size
){
4001 /* Need to make the hash table bigger */
4004 array
.size
= size
= x2a
->size
*2;
4005 array
.count
= x2a
->count
;
4006 array
.tbl
= (x2node
*)malloc(
4007 (sizeof(x2node
) + sizeof(x2node
*))*size
);
4008 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4009 array
.ht
= (x2node
**)&(array
.tbl
[size
]);
4010 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4011 for(i
=0; i
<x2a
->count
; i
++){
4012 x2node
*oldnp
, *newnp
;
4013 oldnp
= &(x2a
->tbl
[i
]);
4014 h
= strhash(oldnp
->key
) & (size
-1);
4015 newnp
= &(array
.tbl
[i
]);
4016 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4017 newnp
->next
= array
.ht
[h
];
4018 newnp
->key
= oldnp
->key
;
4019 newnp
->data
= oldnp
->data
;
4020 newnp
->from
= &(array
.ht
[h
]);
4021 array
.ht
[h
] = newnp
;
4024 /* *x2a = array; *//* copy 'array' */
4025 memcpy(x2a
, &array
, sizeof(array
));
4027 /* Insert the new data */
4028 h
= ph
& (x2a
->size
-1);
4029 np
= &(x2a
->tbl
[x2a
->count
++]);
4032 if( x2a
->ht
[h
] ) x2a
->ht
[h
]->from
= &(np
->next
);
4033 np
->next
= x2a
->ht
[h
];
4035 np
->from
= &(x2a
->ht
[h
]);
4039 /* Return a pointer to data assigned to the given key. Return NULL
4040 ** if no such key. */
4041 struct symbol
*Symbol_find(key
)
4047 if( x2a
==0 ) return 0;
4048 h
= strhash(key
) & (x2a
->size
-1);
4051 if( strcmp(np
->key
,key
)==0 ) break;
4054 return np
? np
->data
: 0;
4057 /* Return the n-th data. Return NULL if n is out of range. */
4058 struct symbol
*Symbol_Nth(n
)
4061 struct symbol
*data
;
4062 if( x2a
&& n
>0 && n
<=x2a
->count
){
4063 data
= x2a
->tbl
[n
-1].data
;
4070 /* Return the size of the array */
4073 return x2a
? x2a
->count
: 0;
4076 /* Return an array of pointers to all data in the table.
4077 ** The array is obtained from malloc. Return NULL if memory allocation
4078 ** problems, or if the array is empty. */
4079 struct symbol
**Symbol_arrayof()
4081 struct symbol
**array
;
4083 if( x2a
==0 ) return 0;
4085 array
= (struct symbol
**)malloc( sizeof(struct symbol
*)*size
);
4087 for(i
=0; i
<size
; i
++) array
[i
] = x2a
->tbl
[i
].data
;
4092 /* Compare two configurations */
4098 x
= a
->rp
->index
- b
->rp
->index
;
4099 if( x
==0 ) x
= a
->dot
- b
->dot
;
4103 /* Compare two states */
4104 PRIVATE
int statecmp(a
,b
)
4109 for(rc
=0; rc
==0 && a
&& b
; a
=a
->bp
, b
=b
->bp
){
4110 rc
= a
->rp
->index
- b
->rp
->index
;
4111 if( rc
==0 ) rc
= a
->dot
- b
->dot
;
4121 PRIVATE
int statehash(a
)
4126 h
= h
*571u + (unsigned int)a
->rp
->index
*37u + (unsigned int)a
->dot
;
4132 /* Allocate a new state structure */
4133 struct state
*State_new()
4136 new = (struct state
*)malloc( sizeof(struct state
) );
4141 /* There is one instance of the following structure for each
4142 ** associative array of type "x3".
4145 int size
; /* The number of available slots. */
4146 /* Must be a power of 2 greater than or */
4148 int count
; /* Number of currently slots filled */
4149 struct s_x3node
*tbl
; /* The data stored here */
4150 struct s_x3node
**ht
; /* Hash table for lookups */
4153 /* There is one instance of this structure for every data element
4154 ** in an associative array of type "x3".
4156 typedef struct s_x3node
{
4157 struct state
*data
; /* The data */
4158 struct config
*key
; /* The key */
4159 struct s_x3node
*next
; /* Next entry with the same hash */
4160 struct s_x3node
**from
; /* Previous link */
4163 /* There is only one instance of the array, which is the following */
4164 static struct s_x3
*x3a
;
4166 /* Allocate a new associative array */
4169 x3a
= (struct s_x3
*)malloc( sizeof(struct s_x3
) );
4173 x3a
->tbl
= (x3node
*)malloc(
4174 (sizeof(x3node
) + sizeof(x3node
*))*128 );
4180 x3a
->ht
= (x3node
**)&(x3a
->tbl
[128]);
4181 for(i
=0; i
<128; i
++) x3a
->ht
[i
] = 0;
4185 /* Insert a new record into the array. Return TRUE if successful.
4186 ** Prior data with the same key is NOT overwritten */
4187 int State_insert(data
,key
)
4195 if( x3a
==0 ) return 0;
4196 ph
= statehash(key
);
4197 h
= ph
& (x3a
->size
-1);
4200 if( statecmp(np
->key
,key
)==0 ){
4201 /* An existing entry with the same key is found. */
4202 /* Fail because overwrite is not allows. */
4207 if( x3a
->count
>=x3a
->size
){
4208 /* Need to make the hash table bigger */
4211 array
.size
= size
= x3a
->size
*2;
4212 array
.count
= x3a
->count
;
4213 array
.tbl
= (x3node
*)malloc(
4214 (sizeof(x3node
) + sizeof(x3node
*))*size
);
4215 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4216 array
.ht
= (x3node
**)&(array
.tbl
[size
]);
4217 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4218 for(i
=0; i
<x3a
->count
; i
++){
4219 x3node
*oldnp
, *newnp
;
4220 oldnp
= &(x3a
->tbl
[i
]);
4221 h
= statehash(oldnp
->key
) & (size
-1);
4222 newnp
= &(array
.tbl
[i
]);
4223 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4224 newnp
->next
= array
.ht
[h
];
4225 newnp
->key
= oldnp
->key
;
4226 newnp
->data
= oldnp
->data
;
4227 newnp
->from
= &(array
.ht
[h
]);
4228 array
.ht
[h
] = newnp
;
4231 /* *x3a = array; *//* copy 'array' */
4232 memcpy(x3a
, &array
, sizeof(array
));
4234 /* Insert the new data */
4235 h
= ph
& (x3a
->size
-1);
4236 np
= &(x3a
->tbl
[x3a
->count
++]);
4239 if( x3a
->ht
[h
] ) x3a
->ht
[h
]->from
= &(np
->next
);
4240 np
->next
= x3a
->ht
[h
];
4242 np
->from
= &(x3a
->ht
[h
]);
4246 /* Return a pointer to data assigned to the given key. Return NULL
4247 ** if no such key. */
4248 struct state
*State_find(key
)
4254 if( x3a
==0 ) return 0;
4255 h
= statehash(key
) & (x3a
->size
-1);
4258 if( statecmp(np
->key
,key
)==0 ) break;
4261 return np
? np
->data
: 0;
4264 /* Return the size of the array */
4265 int State_count(void)
4267 return x3a
? x3a
->count
: 0;
4270 /* Return an array of pointers to all data in the table.
4271 ** The array is obtained from malloc. Return NULL if memory allocation
4272 ** problems, or if the array is empty. */
4273 struct state
**State_arrayof()
4275 struct state
**array
;
4277 if( x3a
==0 ) return 0;
4279 array
= (struct state
**)malloc( sizeof(struct state
*)*size
);
4281 for(i
=0; i
<size
; i
++) array
[i
] = x3a
->tbl
[i
].data
;
4286 /* Hash a configuration */
4287 PRIVATE
int confighash(a
)
4291 h
= h
*571 + a
->rp
->index
*37 + a
->dot
;
4295 /* There is one instance of the following structure for each
4296 ** associative array of type "x4".
4299 int size
; /* The number of available slots. */
4300 /* Must be a power of 2 greater than or */
4302 int count
; /* Number of currently slots filled */
4303 struct s_x4node
*tbl
; /* The data stored here */
4304 struct s_x4node
**ht
; /* Hash table for lookups */
4307 /* There is one instance of this structure for every data element
4308 ** in an associative array of type "x4".
4310 typedef struct s_x4node
{
4311 struct config
*data
; /* The data */
4312 struct s_x4node
*next
; /* Next entry with the same hash */
4313 struct s_x4node
**from
; /* Previous link */
4316 /* There is only one instance of the array, which is the following */
4317 static struct s_x4
*x4a
;
4319 /* Allocate a new associative array */
4320 void Configtable_init(){
4322 x4a
= (struct s_x4
*)malloc( sizeof(struct s_x4
) );
4326 x4a
->tbl
= (x4node
*)malloc(
4327 (sizeof(x4node
) + sizeof(x4node
*))*64 );
4333 x4a
->ht
= (x4node
**)&(x4a
->tbl
[64]);
4334 for(i
=0; i
<64; i
++) x4a
->ht
[i
] = 0;
4338 /* Insert a new record into the array. Return TRUE if successful.
4339 ** Prior data with the same key is NOT overwritten */
4340 int Configtable_insert(data
)
4341 struct config
*data
;
4347 if( x4a
==0 ) return 0;
4348 ph
= confighash(data
);
4349 h
= ph
& (x4a
->size
-1);
4352 if( Configcmp(np
->data
,data
)==0 ){
4353 /* An existing entry with the same key is found. */
4354 /* Fail because overwrite is not allows. */
4359 if( x4a
->count
>=x4a
->size
){
4360 /* Need to make the hash table bigger */
4363 array
.size
= size
= x4a
->size
*2;
4364 array
.count
= x4a
->count
;
4365 array
.tbl
= (x4node
*)malloc(
4366 (sizeof(x4node
) + sizeof(x4node
*))*size
);
4367 if( array
.tbl
==0 ) return 0; /* Fail due to malloc failure */
4368 array
.ht
= (x4node
**)&(array
.tbl
[size
]);
4369 for(i
=0; i
<size
; i
++) array
.ht
[i
] = 0;
4370 for(i
=0; i
<x4a
->count
; i
++){
4371 x4node
*oldnp
, *newnp
;
4372 oldnp
= &(x4a
->tbl
[i
]);
4373 h
= confighash(oldnp
->data
) & (size
-1);
4374 newnp
= &(array
.tbl
[i
]);
4375 if( array
.ht
[h
] ) array
.ht
[h
]->from
= &(newnp
->next
);
4376 newnp
->next
= array
.ht
[h
];
4377 newnp
->data
= oldnp
->data
;
4378 newnp
->from
= &(array
.ht
[h
]);
4379 array
.ht
[h
] = newnp
;
4382 /* *x4a = array; *//* copy 'array' */
4383 memcpy(x4a
, &array
, sizeof(array
));
4385 /* Insert the new data */
4386 h
= ph
& (x4a
->size
-1);
4387 np
= &(x4a
->tbl
[x4a
->count
++]);
4389 if( x4a
->ht
[h
] ) x4a
->ht
[h
]->from
= &(np
->next
);
4390 np
->next
= x4a
->ht
[h
];
4392 np
->from
= &(x4a
->ht
[h
]);
4396 /* Return a pointer to data assigned to the given key. Return NULL
4397 ** if no such key. */
4398 struct config
*Configtable_find(key
)
4404 if( x4a
==0 ) return 0;
4405 h
= confighash(key
) & (x4a
->size
-1);
4408 if( Configcmp(np
->data
,key
)==0 ) break;
4411 return np
? np
->data
: 0;
4414 /* Remove all data from the table. Pass each data to the function "f"
4415 ** as it is removed. ("f" may be null to avoid this step.) */
4416 void Configtable_clear(f
)
4417 int(*f
)(/* struct config * */);
4420 if( x4a
==0 || x4a
->count
==0 ) return;
4421 if( f
) for(i
=0; i
<x4a
->count
; i
++) (*f
)(x4a
->tbl
[i
].data
);
4422 for(i
=0; i
<x4a
->size
; i
++) x4a
->ht
[i
] = 0;