blob: 3e641a4d460a6c43ba953e60970c4df384049fc5 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
10#include <varargs.h>
11#include <string.h>
12#include <ctype.h>
13
14extern void qsort();
15extern double strtod();
16extern long strtol();
17extern void free();
18extern int access();
19extern int atoi();
20
21#ifndef __WIN32__
22# if defined(_WIN32) || defined(WIN32)
23# define __WIN32__
24# endif
25#endif
26
27/* #define PRIVATE static */
28#define PRIVATE
29
30#ifdef TEST
31#define MAXRHS 5 /* Set low to exercise exception code */
32#else
33#define MAXRHS 1000
34#endif
35
36char *msort();
37extern void *malloc();
38
39/******** From the file "action.h" *************************************/
40struct action *Action_new();
41struct action *Action_sort();
42void Action_add();
43
44/********* From the file "assert.h" ************************************/
45void myassert();
46#ifndef NDEBUG
47# define assert(X) if(!(X))myassert(__FILE__,__LINE__)
48#else
49# define assert(X)
50#endif
51
52/********** From the file "build.h" ************************************/
53void FindRulePrecedences();
54void FindFirstSets();
55void FindStates();
56void FindLinks();
57void FindFollowSets();
58void FindActions();
59
60/********* From the file "configlist.h" *********************************/
61void Configlist_init(/* void */);
62struct config *Configlist_add(/* struct rule *, int */);
63struct config *Configlist_addbasis(/* struct rule *, int */);
64void Configlist_closure(/* void */);
65void Configlist_sort(/* void */);
66void Configlist_sortbasis(/* void */);
67struct config *Configlist_return(/* void */);
68struct config *Configlist_basis(/* void */);
69void Configlist_eat(/* struct config * */);
70void Configlist_reset(/* void */);
71
72/********* From the file "error.h" ***************************************/
73void ErrorMsg( /* char *, int, char *, ... */ );
74
75/****** From the file "option.h" ******************************************/
76struct s_options {
77 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
78 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
79 char *label;
80 char *arg;
81 char *message;
82};
drhb0c86772000-06-02 23:21:26 +000083int OptInit(/* char**,struct s_options*,FILE* */);
84int OptNArgs(/* void */);
85char *OptArg(/* int */);
86void OptErr(/* int */);
87void OptPrint(/* void */);
drh75897232000-05-29 14:26:00 +000088
89/******** From the file "parse.h" *****************************************/
90void Parse(/* struct lemon *lemp */);
91
92/********* From the file "plink.h" ***************************************/
93struct plink *Plink_new(/* void */);
94void Plink_add(/* struct plink **, struct config * */);
95void Plink_copy(/* struct plink **, struct plink * */);
96void Plink_delete(/* struct plink * */);
97
98/********** From the file "report.h" *************************************/
99void Reprint(/* struct lemon * */);
100void ReportOutput(/* struct lemon * */);
101void ReportTable(/* struct lemon * */);
102void ReportHeader(/* struct lemon * */);
103void CompressTables(/* struct lemon * */);
104
105/********** From the file "set.h" ****************************************/
106void SetSize(/* int N */); /* All sets will be of size N */
107char *SetNew(/* void */); /* A new set for element 0..N */
108void SetFree(/* char* */); /* Deallocate a set */
109
110int SetAdd(/* char*,int */); /* Add element to a set */
111int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
112
113#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
114
115/********** From the file "struct.h" *************************************/
116/*
117** Principal data structures for the LEMON parser generator.
118*/
119
120typedef enum {FALSE=0, TRUE} Boolean;
121
122/* Symbols (terminals and nonterminals) of the grammar are stored
123** in the following: */
124struct symbol {
125 char *name; /* Name of the symbol */
126 int index; /* Index number for this symbol */
127 enum {
128 TERMINAL,
129 NONTERMINAL
130 } type; /* Symbols are all either TERMINALS or NTs */
131 struct rule *rule; /* Linked list of rules of this (if an NT) */
132 int prec; /* Precedence if defined (-1 otherwise) */
133 enum e_assoc {
134 LEFT,
135 RIGHT,
136 NONE,
137 UNK
138 } assoc; /* Associativity if predecence is defined */
139 char *firstset; /* First-set for all rules of this symbol */
140 Boolean lambda; /* True if NT and can generate an empty string */
141 char *destructor; /* Code which executes whenever this symbol is
142 ** popped from the stack during error processing */
143 int destructorln; /* Line number of destructor code */
144 char *datatype; /* The data type of information held by this
145 ** object. Only used if type==NONTERMINAL */
146 int dtnum; /* The data type number. In the parser, the value
147 ** stack is a union. The .yy%d element of this
148 ** union is the correct data type for this object */
149};
150
151/* Each production rule in the grammar is stored in the following
152** structure. */
153struct rule {
154 struct symbol *lhs; /* Left-hand side of the rule */
155 char *lhsalias; /* Alias for the LHS (NULL if none) */
156 int ruleline; /* Line number for the rule */
157 int nrhs; /* Number of RHS symbols */
158 struct symbol **rhs; /* The RHS symbols */
159 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
160 int line; /* Line number at which code begins */
161 char *code; /* The code executed when this rule is reduced */
162 struct symbol *precsym; /* Precedence symbol for this rule */
163 int index; /* An index number for this rule */
164 Boolean canReduce; /* True if this rule is ever reduced */
165 struct rule *nextlhs; /* Next rule with the same LHS */
166 struct rule *next; /* Next rule in the global list */
167};
168
169/* A configuration is a production rule of the grammar together with
170** a mark (dot) showing how much of that rule has been processed so far.
171** Configurations also contain a follow-set which is a list of terminal
172** symbols which are allowed to immediately follow the end of the rule.
173** Every configuration is recorded as an instance of the following: */
174struct config {
175 struct rule *rp; /* The rule upon which the configuration is based */
176 int dot; /* The parse point */
177 char *fws; /* Follow-set for this configuration only */
178 struct plink *fplp; /* Follow-set forward propagation links */
179 struct plink *bplp; /* Follow-set backwards propagation links */
180 struct state *stp; /* Pointer to state which contains this */
181 enum {
182 COMPLETE, /* The status is used during followset and */
183 INCOMPLETE /* shift computations */
184 } status;
185 struct config *next; /* Next configuration in the state */
186 struct config *bp; /* The next basis configuration */
187};
188
189/* Every shift or reduce operation is stored as one of the following */
190struct action {
191 struct symbol *sp; /* The look-ahead symbol */
192 enum e_action {
193 SHIFT,
194 ACCEPT,
195 REDUCE,
196 ERROR,
197 CONFLICT, /* Was a reduce, but part of a conflict */
198 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
199 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
200 NOT_USED /* Deleted by compression */
201 } type;
202 union {
203 struct state *stp; /* The new state, if a shift */
204 struct rule *rp; /* The rule, if a reduce */
205 } x;
206 struct action *next; /* Next action for this state */
207 struct action *collide; /* Next action with the same hash */
208};
209
210/* Each state of the generated parser's finite state machine
211** is encoded as an instance of the following structure. */
212struct state {
213 struct config *bp; /* The basis configurations for this state */
214 struct config *cfp; /* All configurations in this set */
215 int index; /* Sequencial number for this state */
216 struct action *ap; /* Array of actions for this state */
217 int naction; /* Number of actions for this state */
218 int tabstart; /* First index of the action table */
219 int tabdfltact; /* Default action */
220};
221
222/* A followset propagation link indicates that the contents of one
223** configuration followset should be propagated to another whenever
224** the first changes. */
225struct plink {
226 struct config *cfp; /* The configuration to which linked */
227 struct plink *next; /* The next propagate link */
228};
229
230/* The state vector for the entire parser generator is recorded as
231** follows. (LEMON uses no global variables and makes little use of
232** static variables. Fields in the following structure can be thought
233** of as begin global variables in the program.) */
234struct lemon {
235 struct state **sorted; /* Table of states sorted by state number */
236 struct rule *rule; /* List of all rules */
237 int nstate; /* Number of states */
238 int nrule; /* Number of rules */
239 int nsymbol; /* Number of terminal and nonterminal symbols */
240 int nterminal; /* Number of terminal symbols */
241 struct symbol **symbols; /* Sorted array of pointers to symbols */
242 int errorcnt; /* Number of errors */
243 struct symbol *errsym; /* The error symbol */
244 char *name; /* Name of the generated parser */
245 char *arg; /* Declaration of the 3th argument to parser */
246 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000247 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000248 char *start; /* Name of the start symbol for the grammar */
249 char *stacksize; /* Size of the parser stack */
250 char *include; /* Code to put at the start of the C file */
251 int includeln; /* Line number for start of include code */
252 char *error; /* Code to execute when an error is seen */
253 int errorln; /* Line number for start of error code */
254 char *overflow; /* Code to execute on a stack overflow */
255 int overflowln; /* Line number for start of overflow code */
256 char *failure; /* Code to execute on parser failure */
257 int failureln; /* Line number for start of failure code */
258 char *accept; /* Code to execute when the parser excepts */
259 int acceptln; /* Line number for the start of accept code */
260 char *extracode; /* Code appended to the generated file */
261 int extracodeln; /* Line number for the start of the extra code */
262 char *tokendest; /* Code to execute to destroy token data */
263 int tokendestln; /* Line number for token destroyer code */
drh960e8c62001-04-03 16:53:21 +0000264 char *vardest; /* Code for the default non-terminal destructor */
265 int vardestln; /* Line number for default non-term destructor code*/
drh75897232000-05-29 14:26:00 +0000266 char *filename; /* Name of the input file */
267 char *outname; /* Name of the current output file */
268 char *tokenprefix; /* A prefix added to token names in the .h file */
269 int nconflict; /* Number of parsing conflicts */
270 int tablesize; /* Size of the parse tables */
271 int basisflag; /* Print only basis configurations */
272 char *argv0; /* Name of the program */
273};
274
275#define MemoryCheck(X) if((X)==0){ \
276 extern void memory_error(); \
277 memory_error(); \
278}
279
280/**************** From the file "table.h" *********************************/
281/*
282** All code in this file has been automatically generated
283** from a specification in the file
284** "table.q"
285** by the associative array code building program "aagen".
286** Do not edit this file! Instead, edit the specification
287** file, then rerun aagen.
288*/
289/*
290** Code for processing tables in the LEMON parser generator.
291*/
292
293/* Routines for handling a strings */
294
295char *Strsafe();
296
297void Strsafe_init(/* void */);
298int Strsafe_insert(/* char * */);
299char *Strsafe_find(/* char * */);
300
301/* Routines for handling symbols of the grammar */
302
303struct symbol *Symbol_new();
304int Symbolcmpp(/* struct symbol **, struct symbol ** */);
305void Symbol_init(/* void */);
306int Symbol_insert(/* struct symbol *, char * */);
307struct symbol *Symbol_find(/* char * */);
308struct symbol *Symbol_Nth(/* int */);
309int Symbol_count(/* */);
310struct symbol **Symbol_arrayof(/* */);
311
312/* Routines to manage the state table */
313
314int Configcmp(/* struct config *, struct config * */);
315struct state *State_new();
316void State_init(/* void */);
317int State_insert(/* struct state *, struct config * */);
318struct state *State_find(/* struct config * */);
319struct state **State_arrayof(/* */);
320
321/* Routines used for efficiency in Configlist_add */
322
323void Configtable_init(/* void */);
324int Configtable_insert(/* struct config * */);
325struct config *Configtable_find(/* struct config * */);
326void Configtable_clear(/* int(*)(struct config *) */);
327/****************** From the file "action.c" *******************************/
328/*
329** Routines processing parser actions in the LEMON parser generator.
330*/
331
332/* Allocate a new parser action */
333struct action *Action_new(){
334 static struct action *freelist = 0;
335 struct action *new;
336
337 if( freelist==0 ){
338 int i;
339 int amt = 100;
340 freelist = (struct action *)malloc( sizeof(struct action)*amt );
341 if( freelist==0 ){
342 fprintf(stderr,"Unable to allocate memory for a new parser action.");
343 exit(1);
344 }
345 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
346 freelist[amt-1].next = 0;
347 }
348 new = freelist;
349 freelist = freelist->next;
350 return new;
351}
352
353/* Compare two actions */
354static int actioncmp(ap1,ap2)
355struct action *ap1;
356struct action *ap2;
357{
358 int rc;
359 rc = ap1->sp->index - ap2->sp->index;
360 if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
361 if( rc==0 ){
drh61bc2722000-08-20 11:42:46 +0000362 assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
363 assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
drh75897232000-05-29 14:26:00 +0000364 rc = ap1->x.rp->index - ap2->x.rp->index;
365 }
366 return rc;
367}
368
369/* Sort parser actions */
370struct action *Action_sort(ap)
371struct action *ap;
372{
373 ap = (struct action *)msort(ap,&ap->next,actioncmp);
374 return ap;
375}
376
377void Action_add(app,type,sp,arg)
378struct action **app;
379enum e_action type;
380struct symbol *sp;
381char *arg;
382{
383 struct action *new;
384 new = Action_new();
385 new->next = *app;
386 *app = new;
387 new->type = type;
388 new->sp = sp;
389 if( type==SHIFT ){
390 new->x.stp = (struct state *)arg;
391 }else{
392 new->x.rp = (struct rule *)arg;
393 }
394}
395/********************** From the file "assert.c" ****************************/
396/*
397** A more efficient way of handling assertions.
398*/
399void myassert(file,line)
400char *file;
401int line;
402{
403 fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
404 exit(1);
405}
406/********************** From the file "build.c" *****************************/
407/*
408** Routines to construction the finite state machine for the LEMON
409** parser generator.
410*/
411
412/* Find a precedence symbol of every rule in the grammar.
413**
414** Those rules which have a precedence symbol coded in the input
415** grammar using the "[symbol]" construct will already have the
416** rp->precsym field filled. Other rules take as their precedence
417** symbol the first RHS symbol with a defined precedence. If there
418** are not RHS symbols with a defined precedence, the precedence
419** symbol field is left blank.
420*/
421void FindRulePrecedences(xp)
422struct lemon *xp;
423{
424 struct rule *rp;
425 for(rp=xp->rule; rp; rp=rp->next){
426 if( rp->precsym==0 ){
427 int i;
428 for(i=0; i<rp->nrhs; i++){
429 if( rp->rhs[i]->prec>=0 ){
430 rp->precsym = rp->rhs[i];
431 break;
432 }
433 }
434 }
435 }
436 return;
437}
438
439/* Find all nonterminals which will generate the empty string.
440** Then go back and compute the first sets of every nonterminal.
441** The first set is the set of all terminal symbols which can begin
442** a string generated by that nonterminal.
443*/
444void FindFirstSets(lemp)
445struct lemon *lemp;
446{
447 int i;
448 struct rule *rp;
449 int progress;
450
451 for(i=0; i<lemp->nsymbol; i++){
452 lemp->symbols[i]->lambda = FALSE;
453 }
454 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
455 lemp->symbols[i]->firstset = SetNew();
456 }
457
458 /* First compute all lambdas */
459 do{
460 progress = 0;
461 for(rp=lemp->rule; rp; rp=rp->next){
462 if( rp->lhs->lambda ) continue;
463 for(i=0; i<rp->nrhs; i++){
464 if( rp->rhs[i]->lambda==FALSE ) break;
465 }
466 if( i==rp->nrhs ){
467 rp->lhs->lambda = TRUE;
468 progress = 1;
469 }
470 }
471 }while( progress );
472
473 /* Now compute all first sets */
474 do{
475 struct symbol *s1, *s2;
476 progress = 0;
477 for(rp=lemp->rule; rp; rp=rp->next){
478 s1 = rp->lhs;
479 for(i=0; i<rp->nrhs; i++){
480 s2 = rp->rhs[i];
481 if( s2->type==TERMINAL ){
482 progress += SetAdd(s1->firstset,s2->index);
483 break;
484 }else if( s1==s2 ){
485 if( s1->lambda==FALSE ) break;
486 }else{
487 progress += SetUnion(s1->firstset,s2->firstset);
488 if( s2->lambda==FALSE ) break;
489 }
490 }
491 }
492 }while( progress );
493 return;
494}
495
496/* Compute all LR(0) states for the grammar. Links
497** are added to between some states so that the LR(1) follow sets
498** can be computed later.
499*/
500PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
501void FindStates(lemp)
502struct lemon *lemp;
503{
504 struct symbol *sp;
505 struct rule *rp;
506
507 Configlist_init();
508
509 /* Find the start symbol */
510 if( lemp->start ){
511 sp = Symbol_find(lemp->start);
512 if( sp==0 ){
513 ErrorMsg(lemp->filename,0,
514"The specified start symbol \"%s\" is not \
515in a nonterminal of the grammar. \"%s\" will be used as the start \
516symbol instead.",lemp->start,lemp->rule->lhs->name);
517 lemp->errorcnt++;
518 sp = lemp->rule->lhs;
519 }
520 }else{
521 sp = lemp->rule->lhs;
522 }
523
524 /* Make sure the start symbol doesn't occur on the right-hand side of
525 ** any rule. Report an error if it does. (YACC would generate a new
526 ** start symbol in this case.) */
527 for(rp=lemp->rule; rp; rp=rp->next){
528 int i;
529 for(i=0; i<rp->nrhs; i++){
530 if( rp->rhs[i]==sp ){
531 ErrorMsg(lemp->filename,0,
532"The start symbol \"%s\" occurs on the \
533right-hand side of a rule. This will result in a parser which \
534does not work properly.",sp->name);
535 lemp->errorcnt++;
536 }
537 }
538 }
539
540 /* The basis configuration set for the first state
541 ** is all rules which have the start symbol as their
542 ** left-hand side */
543 for(rp=sp->rule; rp; rp=rp->nextlhs){
544 struct config *newcfp;
545 newcfp = Configlist_addbasis(rp,0);
546 SetAdd(newcfp->fws,0);
547 }
548
549 /* Compute the first state. All other states will be
550 ** computed automatically during the computation of the first one.
551 ** The returned pointer to the first state is not used. */
552 (void)getstate(lemp);
553 return;
554}
555
556/* Return a pointer to a state which is described by the configuration
557** list which has been built from calls to Configlist_add.
558*/
559PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
560PRIVATE struct state *getstate(lemp)
561struct lemon *lemp;
562{
563 struct config *cfp, *bp;
564 struct state *stp;
565
566 /* Extract the sorted basis of the new state. The basis was constructed
567 ** by prior calls to "Configlist_addbasis()". */
568 Configlist_sortbasis();
569 bp = Configlist_basis();
570
571 /* Get a state with the same basis */
572 stp = State_find(bp);
573 if( stp ){
574 /* A state with the same basis already exists! Copy all the follow-set
575 ** propagation links from the state under construction into the
576 ** preexisting state, then return a pointer to the preexisting state */
577 struct config *x, *y;
578 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
579 Plink_copy(&y->bplp,x->bplp);
580 Plink_delete(x->fplp);
581 x->fplp = x->bplp = 0;
582 }
583 cfp = Configlist_return();
584 Configlist_eat(cfp);
585 }else{
586 /* This really is a new state. Construct all the details */
587 Configlist_closure(lemp); /* Compute the configuration closure */
588 Configlist_sort(); /* Sort the configuration closure */
589 cfp = Configlist_return(); /* Get a pointer to the config list */
590 stp = State_new(); /* A new state structure */
591 MemoryCheck(stp);
592 stp->bp = bp; /* Remember the configuration basis */
593 stp->cfp = cfp; /* Remember the configuration closure */
594 stp->index = lemp->nstate++; /* Every state gets a sequence number */
595 stp->ap = 0; /* No actions, yet. */
596 State_insert(stp,stp->bp); /* Add to the state table */
597 buildshifts(lemp,stp); /* Recursively compute successor states */
598 }
599 return stp;
600}
601
602/* Construct all successor states to the given state. A "successor"
603** state is any state which can be reached by a shift action.
604*/
605PRIVATE void buildshifts(lemp,stp)
606struct lemon *lemp;
607struct state *stp; /* The state from which successors are computed */
608{
609 struct config *cfp; /* For looping thru the config closure of "stp" */
610 struct config *bcfp; /* For the inner loop on config closure of "stp" */
611 struct config *new; /* */
612 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
613 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
614 struct state *newstp; /* A pointer to a successor state */
615
616 /* Each configuration becomes complete after it contibutes to a successor
617 ** state. Initially, all configurations are incomplete */
618 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
619
620 /* Loop through all configurations of the state "stp" */
621 for(cfp=stp->cfp; cfp; cfp=cfp->next){
622 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
623 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
624 Configlist_reset(); /* Reset the new config set */
625 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
626
627 /* For every configuration in the state "stp" which has the symbol "sp"
628 ** following its dot, add the same configuration to the basis set under
629 ** construction but with the dot shifted one symbol to the right. */
630 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
631 if( bcfp->status==COMPLETE ) continue; /* Already used */
632 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
633 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
634 if( bsp!=sp ) continue; /* Must be same as for "cfp" */
635 bcfp->status = COMPLETE; /* Mark this config as used */
636 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
637 Plink_add(&new->bplp,bcfp);
638 }
639
640 /* Get a pointer to the state described by the basis configuration set
641 ** constructed in the preceding loop */
642 newstp = getstate(lemp);
643
644 /* The state "newstp" is reached from the state "stp" by a shift action
645 ** on the symbol "sp" */
646 Action_add(&stp->ap,SHIFT,sp,newstp);
647 }
648}
649
650/*
651** Construct the propagation links
652*/
653void FindLinks(lemp)
654struct lemon *lemp;
655{
656 int i;
657 struct config *cfp, *other;
658 struct state *stp;
659 struct plink *plp;
660
661 /* Housekeeping detail:
662 ** Add to every propagate link a pointer back to the state to
663 ** which the link is attached. */
664 for(i=0; i<lemp->nstate; i++){
665 stp = lemp->sorted[i];
666 for(cfp=stp->cfp; cfp; cfp=cfp->next){
667 cfp->stp = stp;
668 }
669 }
670
671 /* Convert all backlinks into forward links. Only the forward
672 ** links are used in the follow-set computation. */
673 for(i=0; i<lemp->nstate; i++){
674 stp = lemp->sorted[i];
675 for(cfp=stp->cfp; cfp; cfp=cfp->next){
676 for(plp=cfp->bplp; plp; plp=plp->next){
677 other = plp->cfp;
678 Plink_add(&other->fplp,cfp);
679 }
680 }
681 }
682}
683
684/* Compute all followsets.
685**
686** A followset is the set of all symbols which can come immediately
687** after a configuration.
688*/
689void FindFollowSets(lemp)
690struct lemon *lemp;
691{
692 int i;
693 struct config *cfp;
694 struct plink *plp;
695 int progress;
696 int change;
697
698 for(i=0; i<lemp->nstate; i++){
699 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
700 cfp->status = INCOMPLETE;
701 }
702 }
703
704 do{
705 progress = 0;
706 for(i=0; i<lemp->nstate; i++){
707 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
708 if( cfp->status==COMPLETE ) continue;
709 for(plp=cfp->fplp; plp; plp=plp->next){
710 change = SetUnion(plp->cfp->fws,cfp->fws);
711 if( change ){
712 plp->cfp->status = INCOMPLETE;
713 progress = 1;
714 }
715 }
716 cfp->status = COMPLETE;
717 }
718 }
719 }while( progress );
720}
721
722static int resolve_conflict();
723
724/* Compute the reduce actions, and resolve conflicts.
725*/
726void FindActions(lemp)
727struct lemon *lemp;
728{
729 int i,j;
730 struct config *cfp;
731 struct state *stp;
732 struct symbol *sp;
733 struct rule *rp;
734
735 /* Add all of the reduce actions
736 ** A reduce action is added for each element of the followset of
737 ** a configuration which has its dot at the extreme right.
738 */
739 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
740 stp = lemp->sorted[i];
741 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
742 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
743 for(j=0; j<lemp->nterminal; j++){
744 if( SetFind(cfp->fws,j) ){
745 /* Add a reduce action to the state "stp" which will reduce by the
746 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
747 Action_add(&stp->ap,REDUCE,lemp->symbols[j],cfp->rp);
748 }
749 }
750 }
751 }
752 }
753
754 /* Add the accepting token */
755 if( lemp->start ){
756 sp = Symbol_find(lemp->start);
757 if( sp==0 ) sp = lemp->rule->lhs;
758 }else{
759 sp = lemp->rule->lhs;
760 }
761 /* Add to the first state (which is always the starting state of the
762 ** finite state machine) an action to ACCEPT if the lookahead is the
763 ** start nonterminal. */
764 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
765
766 /* Resolve conflicts */
767 for(i=0; i<lemp->nstate; i++){
768 struct action *ap, *nap;
769 struct state *stp;
770 stp = lemp->sorted[i];
771 assert( stp->ap );
772 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000773 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000774 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
775 /* The two actions "ap" and "nap" have the same lookahead.
776 ** Figure out which one should be used */
777 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
778 }
779 }
780 }
781
782 /* Report an error for each rule that can never be reduced. */
783 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = FALSE;
784 for(i=0; i<lemp->nstate; i++){
785 struct action *ap;
786 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
787 if( ap->type==REDUCE ) ap->x.rp->canReduce = TRUE;
788 }
789 }
790 for(rp=lemp->rule; rp; rp=rp->next){
791 if( rp->canReduce ) continue;
792 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
793 lemp->errorcnt++;
794 }
795}
796
797/* Resolve a conflict between the two given actions. If the
798** conflict can't be resolve, return non-zero.
799**
800** NO LONGER TRUE:
801** To resolve a conflict, first look to see if either action
802** is on an error rule. In that case, take the action which
803** is not associated with the error rule. If neither or both
804** actions are associated with an error rule, then try to
805** use precedence to resolve the conflict.
806**
807** If either action is a SHIFT, then it must be apx. This
808** function won't work if apx->type==REDUCE and apy->type==SHIFT.
809*/
810static int resolve_conflict(apx,apy,errsym)
811struct action *apx;
812struct action *apy;
813struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
814{
815 struct symbol *spx, *spy;
816 int errcnt = 0;
817 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
818 if( apx->type==SHIFT && apy->type==REDUCE ){
819 spx = apx->sp;
820 spy = apy->x.rp->precsym;
821 if( spy==0 || spx->prec<0 || spy->prec<0 ){
822 /* Not enough precedence information. */
823 apy->type = CONFLICT;
824 errcnt++;
825 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
826 apy->type = RD_RESOLVED;
827 }else if( spx->prec<spy->prec ){
828 apx->type = SH_RESOLVED;
829 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
830 apy->type = RD_RESOLVED; /* associativity */
831 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
832 apx->type = SH_RESOLVED;
833 }else{
834 assert( spx->prec==spy->prec && spx->assoc==NONE );
835 apy->type = CONFLICT;
836 errcnt++;
837 }
838 }else if( apx->type==REDUCE && apy->type==REDUCE ){
839 spx = apx->x.rp->precsym;
840 spy = apy->x.rp->precsym;
841 if( spx==0 || spy==0 || spx->prec<0 ||
842 spy->prec<0 || spx->prec==spy->prec ){
843 apy->type = CONFLICT;
844 errcnt++;
845 }else if( spx->prec>spy->prec ){
846 apy->type = RD_RESOLVED;
847 }else if( spx->prec<spy->prec ){
848 apx->type = RD_RESOLVED;
849 }
850 }else{
drhb59499c2002-02-23 18:45:13 +0000851 assert(
852 apx->type==SH_RESOLVED ||
853 apx->type==RD_RESOLVED ||
854 apx->type==CONFLICT ||
855 apy->type==SH_RESOLVED ||
856 apy->type==RD_RESOLVED ||
857 apy->type==CONFLICT
858 );
859 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
860 ** REDUCEs on the list. If we reach this point it must be because
861 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +0000862 }
863 return errcnt;
864}
865/********************* From the file "configlist.c" *************************/
866/*
867** Routines to processing a configuration list and building a state
868** in the LEMON parser generator.
869*/
870
871static struct config *freelist = 0; /* List of free configurations */
872static struct config *current = 0; /* Top of list of configurations */
873static struct config **currentend = 0; /* Last on list of configs */
874static struct config *basis = 0; /* Top of list of basis configs */
875static struct config **basisend = 0; /* End of list of basis configs */
876
877/* Return a pointer to a new configuration */
878PRIVATE struct config *newconfig(){
879 struct config *new;
880 if( freelist==0 ){
881 int i;
882 int amt = 3;
883 freelist = (struct config *)malloc( sizeof(struct config)*amt );
884 if( freelist==0 ){
885 fprintf(stderr,"Unable to allocate memory for a new configuration.");
886 exit(1);
887 }
888 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
889 freelist[amt-1].next = 0;
890 }
891 new = freelist;
892 freelist = freelist->next;
893 return new;
894}
895
896/* The configuration "old" is no longer used */
897PRIVATE void deleteconfig(old)
898struct config *old;
899{
900 old->next = freelist;
901 freelist = old;
902}
903
904/* Initialized the configuration list builder */
905void Configlist_init(){
906 current = 0;
907 currentend = &current;
908 basis = 0;
909 basisend = &basis;
910 Configtable_init();
911 return;
912}
913
914/* Initialized the configuration list builder */
915void Configlist_reset(){
916 current = 0;
917 currentend = &current;
918 basis = 0;
919 basisend = &basis;
920 Configtable_clear(0);
921 return;
922}
923
924/* Add another configuration to the configuration list */
925struct config *Configlist_add(rp,dot)
926struct rule *rp; /* The rule */
927int dot; /* Index into the RHS of the rule where the dot goes */
928{
929 struct config *cfp, model;
930
931 assert( currentend!=0 );
932 model.rp = rp;
933 model.dot = dot;
934 cfp = Configtable_find(&model);
935 if( cfp==0 ){
936 cfp = newconfig();
937 cfp->rp = rp;
938 cfp->dot = dot;
939 cfp->fws = SetNew();
940 cfp->stp = 0;
941 cfp->fplp = cfp->bplp = 0;
942 cfp->next = 0;
943 cfp->bp = 0;
944 *currentend = cfp;
945 currentend = &cfp->next;
946 Configtable_insert(cfp);
947 }
948 return cfp;
949}
950
951/* Add a basis configuration to the configuration list */
952struct config *Configlist_addbasis(rp,dot)
953struct rule *rp;
954int dot;
955{
956 struct config *cfp, model;
957
958 assert( basisend!=0 );
959 assert( currentend!=0 );
960 model.rp = rp;
961 model.dot = dot;
962 cfp = Configtable_find(&model);
963 if( cfp==0 ){
964 cfp = newconfig();
965 cfp->rp = rp;
966 cfp->dot = dot;
967 cfp->fws = SetNew();
968 cfp->stp = 0;
969 cfp->fplp = cfp->bplp = 0;
970 cfp->next = 0;
971 cfp->bp = 0;
972 *currentend = cfp;
973 currentend = &cfp->next;
974 *basisend = cfp;
975 basisend = &cfp->bp;
976 Configtable_insert(cfp);
977 }
978 return cfp;
979}
980
981/* Compute the closure of the configuration list */
982void Configlist_closure(lemp)
983struct lemon *lemp;
984{
985 struct config *cfp, *newcfp;
986 struct rule *rp, *newrp;
987 struct symbol *sp, *xsp;
988 int i, dot;
989
990 assert( currentend!=0 );
991 for(cfp=current; cfp; cfp=cfp->next){
992 rp = cfp->rp;
993 dot = cfp->dot;
994 if( dot>=rp->nrhs ) continue;
995 sp = rp->rhs[dot];
996 if( sp->type==NONTERMINAL ){
997 if( sp->rule==0 && sp!=lemp->errsym ){
998 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
999 sp->name);
1000 lemp->errorcnt++;
1001 }
1002 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1003 newcfp = Configlist_add(newrp,0);
1004 for(i=dot+1; i<rp->nrhs; i++){
1005 xsp = rp->rhs[i];
1006 if( xsp->type==TERMINAL ){
1007 SetAdd(newcfp->fws,xsp->index);
1008 break;
1009 }else{
1010 SetUnion(newcfp->fws,xsp->firstset);
1011 if( xsp->lambda==FALSE ) break;
1012 }
1013 }
1014 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1015 }
1016 }
1017 }
1018 return;
1019}
1020
1021/* Sort the configuration list */
1022void Configlist_sort(){
1023 current = (struct config *)msort(current,&(current->next),Configcmp);
1024 currentend = 0;
1025 return;
1026}
1027
1028/* Sort the basis configuration list */
1029void Configlist_sortbasis(){
1030 basis = (struct config *)msort(current,&(current->bp),Configcmp);
1031 basisend = 0;
1032 return;
1033}
1034
1035/* Return a pointer to the head of the configuration list and
1036** reset the list */
1037struct config *Configlist_return(){
1038 struct config *old;
1039 old = current;
1040 current = 0;
1041 currentend = 0;
1042 return old;
1043}
1044
1045/* Return a pointer to the head of the configuration list and
1046** reset the list */
1047struct config *Configlist_basis(){
1048 struct config *old;
1049 old = basis;
1050 basis = 0;
1051 basisend = 0;
1052 return old;
1053}
1054
1055/* Free all elements of the given configuration list */
1056void Configlist_eat(cfp)
1057struct config *cfp;
1058{
1059 struct config *nextcfp;
1060 for(; cfp; cfp=nextcfp){
1061 nextcfp = cfp->next;
1062 assert( cfp->fplp==0 );
1063 assert( cfp->bplp==0 );
1064 if( cfp->fws ) SetFree(cfp->fws);
1065 deleteconfig(cfp);
1066 }
1067 return;
1068}
1069/***************** From the file "error.c" *********************************/
1070/*
1071** Code for printing error message.
1072*/
1073
1074/* Find a good place to break "msg" so that its length is at least "min"
1075** but no more than "max". Make the point as close to max as possible.
1076*/
1077static int findbreak(msg,min,max)
1078char *msg;
1079int min;
1080int max;
1081{
1082 int i,spot;
1083 char c;
1084 for(i=spot=min; i<=max; i++){
1085 c = msg[i];
1086 if( c=='\t' ) msg[i] = ' ';
1087 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1088 if( c==0 ){ spot = i; break; }
1089 if( c=='-' && i<max-1 ) spot = i+1;
1090 if( c==' ' ) spot = i;
1091 }
1092 return spot;
1093}
1094
1095/*
1096** The error message is split across multiple lines if necessary. The
1097** splits occur at a space, if there is a space available near the end
1098** of the line.
1099*/
1100#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1101#define LINEWIDTH 79 /* Max width of any output line */
1102#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
1103void ErrorMsg(va_alist)
1104va_dcl
1105{
1106 char *filename;
1107 int lineno;
1108 char *format;
1109 char errmsg[ERRMSGSIZE];
1110 char prefix[PREFIXLIMIT+10];
1111 int errmsgsize;
1112 int prefixsize;
1113 int availablewidth;
1114 va_list ap;
1115 int end, restart, base;
1116
1117 va_start(ap);
1118 filename = va_arg(ap,char*);
1119 lineno = va_arg(ap,int);
1120 format = va_arg(ap,char*);
1121 /* Prepare a prefix to be prepended to every output line */
1122 if( lineno>0 ){
1123 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1124 }else{
1125 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1126 }
1127 prefixsize = strlen(prefix);
1128 availablewidth = LINEWIDTH - prefixsize;
1129
1130 /* Generate the error message */
1131 vsprintf(errmsg,format,ap);
1132 va_end(ap);
1133 errmsgsize = strlen(errmsg);
1134 /* Remove trailing '\n's from the error message. */
1135 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1136 errmsg[--errmsgsize] = 0;
1137 }
1138
1139 /* Print the error message */
1140 base = 0;
1141 while( errmsg[base]!=0 ){
1142 end = restart = findbreak(&errmsg[base],0,availablewidth);
1143 restart += base;
1144 while( errmsg[restart]==' ' ) restart++;
1145 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1146 base = restart;
1147 }
1148}
1149/**************** From the file "main.c" ************************************/
1150/*
1151** Main program file for the LEMON parser generator.
1152*/
1153
1154/* Report an out-of-memory condition and abort. This function
1155** is used mostly by the "MemoryCheck" macro in struct.h
1156*/
1157void memory_error(){
1158 fprintf(stderr,"Out of memory. Aborting...\n");
1159 exit(1);
1160}
1161
1162
1163/* The main program. Parse the command line and do it... */
1164int main(argc,argv)
1165int argc;
1166char **argv;
1167{
1168 static int version = 0;
1169 static int rpflag = 0;
1170 static int basisflag = 0;
1171 static int compress = 0;
1172 static int quiet = 0;
1173 static int statistics = 0;
1174 static int mhflag = 0;
1175 static struct s_options options[] = {
1176 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1177 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1178 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1179 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1180 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1181 {OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."},
1182 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1183 {OPT_FLAG,0,0,0}
1184 };
1185 int i;
1186 struct lemon lem;
1187
drhb0c86772000-06-02 23:21:26 +00001188 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001189 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001190 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001191 exit(0);
1192 }
drhb0c86772000-06-02 23:21:26 +00001193 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001194 fprintf(stderr,"Exactly one filename argument is required.\n");
1195 exit(1);
1196 }
1197 lem.errorcnt = 0;
1198
1199 /* Initialize the machine */
1200 Strsafe_init();
1201 Symbol_init();
1202 State_init();
1203 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001204 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001205 lem.basisflag = basisflag;
1206 lem.nconflict = 0;
1207 lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
drh960e8c62001-04-03 16:53:21 +00001208 lem.vartype = 0;
drh75897232000-05-29 14:26:00 +00001209 lem.stacksize = 0;
1210 lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
1211 lem.tokenprefix = lem.outname = lem.extracode = 0;
drh960e8c62001-04-03 16:53:21 +00001212 lem.vardest = 0;
drh75897232000-05-29 14:26:00 +00001213 lem.tablesize = 0;
1214 Symbol_new("$");
1215 lem.errsym = Symbol_new("error");
1216
1217 /* Parse the input file */
1218 Parse(&lem);
1219 if( lem.errorcnt ) exit(lem.errorcnt);
1220 if( lem.rule==0 ){
1221 fprintf(stderr,"Empty grammar.\n");
1222 exit(1);
1223 }
1224
1225 /* Count and index the symbols of the grammar */
1226 lem.nsymbol = Symbol_count();
1227 Symbol_new("{default}");
1228 lem.symbols = Symbol_arrayof();
1229 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1230 (int(*)())Symbolcmpp);
1231 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1232 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1233 lem.nterminal = i;
1234
1235 /* Generate a reprint of the grammar, if requested on the command line */
1236 if( rpflag ){
1237 Reprint(&lem);
1238 }else{
1239 /* Initialize the size for all follow and first sets */
1240 SetSize(lem.nterminal);
1241
1242 /* Find the precedence for every production rule (that has one) */
1243 FindRulePrecedences(&lem);
1244
1245 /* Compute the lambda-nonterminals and the first-sets for every
1246 ** nonterminal */
1247 FindFirstSets(&lem);
1248
1249 /* Compute all LR(0) states. Also record follow-set propagation
1250 ** links so that the follow-set can be computed later */
1251 lem.nstate = 0;
1252 FindStates(&lem);
1253 lem.sorted = State_arrayof();
1254
1255 /* Tie up loose ends on the propagation links */
1256 FindLinks(&lem);
1257
1258 /* Compute the follow set of every reducible configuration */
1259 FindFollowSets(&lem);
1260
1261 /* Compute the action tables */
1262 FindActions(&lem);
1263
1264 /* Compress the action tables */
1265 if( compress==0 ) CompressTables(&lem);
1266
1267 /* Generate a report of the parser generated. (the "y.output" file) */
1268 if( !quiet ) ReportOutput(&lem);
1269
1270 /* Generate the source code for the parser */
1271 ReportTable(&lem, mhflag);
1272
1273 /* Produce a header file for use by the scanner. (This step is
1274 ** omitted if the "-m" option is used because makeheaders will
1275 ** generate the file for us.) */
1276 if( !mhflag ) ReportHeader(&lem);
1277 }
1278 if( statistics ){
1279 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1280 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1281 printf(" %d states, %d parser table entries, %d conflicts\n",
1282 lem.nstate, lem.tablesize, lem.nconflict);
1283 }
1284 if( lem.nconflict ){
1285 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1286 }
1287 exit(lem.errorcnt + lem.nconflict);
1288}
1289/******************** From the file "msort.c" *******************************/
1290/*
1291** A generic merge-sort program.
1292**
1293** USAGE:
1294** Let "ptr" be a pointer to some structure which is at the head of
1295** a null-terminated list. Then to sort the list call:
1296**
1297** ptr = msort(ptr,&(ptr->next),cmpfnc);
1298**
1299** In the above, "cmpfnc" is a pointer to a function which compares
1300** two instances of the structure and returns an integer, as in
1301** strcmp. The second argument is a pointer to the pointer to the
1302** second element of the linked list. This address is used to compute
1303** the offset to the "next" field within the structure. The offset to
1304** the "next" field must be constant for all structures in the list.
1305**
1306** The function returns a new pointer which is the head of the list
1307** after sorting.
1308**
1309** ALGORITHM:
1310** Merge-sort.
1311*/
1312
1313/*
1314** Return a pointer to the next structure in the linked list.
1315*/
drhba99af52001-10-25 20:37:16 +00001316#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001317
1318/*
1319** Inputs:
1320** a: A sorted, null-terminated linked list. (May be null).
1321** b: A sorted, null-terminated linked list. (May be null).
1322** cmp: A pointer to the comparison function.
1323** offset: Offset in the structure to the "next" field.
1324**
1325** Return Value:
1326** A pointer to the head of a sorted list containing the elements
1327** of both a and b.
1328**
1329** Side effects:
1330** The "next" pointers for elements in the lists a and b are
1331** changed.
1332*/
1333static char *merge(a,b,cmp,offset)
1334char *a;
1335char *b;
1336int (*cmp)();
1337int offset;
1338{
1339 char *ptr, *head;
1340
1341 if( a==0 ){
1342 head = b;
1343 }else if( b==0 ){
1344 head = a;
1345 }else{
1346 if( (*cmp)(a,b)<0 ){
1347 ptr = a;
1348 a = NEXT(a);
1349 }else{
1350 ptr = b;
1351 b = NEXT(b);
1352 }
1353 head = ptr;
1354 while( a && b ){
1355 if( (*cmp)(a,b)<0 ){
1356 NEXT(ptr) = a;
1357 ptr = a;
1358 a = NEXT(a);
1359 }else{
1360 NEXT(ptr) = b;
1361 ptr = b;
1362 b = NEXT(b);
1363 }
1364 }
1365 if( a ) NEXT(ptr) = a;
1366 else NEXT(ptr) = b;
1367 }
1368 return head;
1369}
1370
1371/*
1372** Inputs:
1373** list: Pointer to a singly-linked list of structures.
1374** next: Pointer to pointer to the second element of the list.
1375** cmp: A comparison function.
1376**
1377** Return Value:
1378** A pointer to the head of a sorted list containing the elements
1379** orginally in list.
1380**
1381** Side effects:
1382** The "next" pointers for elements in list are changed.
1383*/
1384#define LISTSIZE 30
1385char *msort(list,next,cmp)
1386char *list;
1387char **next;
1388int (*cmp)();
1389{
drhba99af52001-10-25 20:37:16 +00001390 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001391 char *ep;
1392 char *set[LISTSIZE];
1393 int i;
drhba99af52001-10-25 20:37:16 +00001394 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001395 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1396 while( list ){
1397 ep = list;
1398 list = NEXT(list);
1399 NEXT(ep) = 0;
1400 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1401 ep = merge(ep,set[i],cmp,offset);
1402 set[i] = 0;
1403 }
1404 set[i] = ep;
1405 }
1406 ep = 0;
1407 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1408 return ep;
1409}
1410/************************ From the file "option.c" **************************/
1411static char **argv;
1412static struct s_options *op;
1413static FILE *errstream;
1414
1415#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1416
1417/*
1418** Print the command line with a carrot pointing to the k-th character
1419** of the n-th field.
1420*/
1421static void errline(n,k,err)
1422int n;
1423int k;
1424FILE *err;
1425{
1426 int spcnt, i;
1427 spcnt = 0;
1428 if( argv[0] ) fprintf(err,"%s",argv[0]);
1429 spcnt = strlen(argv[0]) + 1;
1430 for(i=1; i<n && argv[i]; i++){
1431 fprintf(err," %s",argv[i]);
1432 spcnt += strlen(argv[i]+1);
1433 }
1434 spcnt += k;
1435 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1436 if( spcnt<20 ){
1437 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1438 }else{
1439 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1440 }
1441}
1442
1443/*
1444** Return the index of the N-th non-switch argument. Return -1
1445** if N is out of range.
1446*/
1447static int argindex(n)
1448int n;
1449{
1450 int i;
1451 int dashdash = 0;
1452 if( argv!=0 && *argv!=0 ){
1453 for(i=1; argv[i]; i++){
1454 if( dashdash || !ISOPT(argv[i]) ){
1455 if( n==0 ) return i;
1456 n--;
1457 }
1458 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1459 }
1460 }
1461 return -1;
1462}
1463
1464static char emsg[] = "Command line syntax error: ";
1465
1466/*
1467** Process a flag command line argument.
1468*/
1469static int handleflags(i,err)
1470int i;
1471FILE *err;
1472{
1473 int v;
1474 int errcnt = 0;
1475 int j;
1476 for(j=0; op[j].label; j++){
1477 if( strcmp(&argv[i][1],op[j].label)==0 ) break;
1478 }
1479 v = argv[i][0]=='-' ? 1 : 0;
1480 if( op[j].label==0 ){
1481 if( err ){
1482 fprintf(err,"%sundefined option.\n",emsg);
1483 errline(i,1,err);
1484 }
1485 errcnt++;
1486 }else if( op[j].type==OPT_FLAG ){
1487 *((int*)op[j].arg) = v;
1488 }else if( op[j].type==OPT_FFLAG ){
1489 (*(void(*)())(op[j].arg))(v);
1490 }else{
1491 if( err ){
1492 fprintf(err,"%smissing argument on switch.\n",emsg);
1493 errline(i,1,err);
1494 }
1495 errcnt++;
1496 }
1497 return errcnt;
1498}
1499
1500/*
1501** Process a command line switch which has an argument.
1502*/
1503static int handleswitch(i,err)
1504int i;
1505FILE *err;
1506{
1507 int lv = 0;
1508 double dv = 0.0;
1509 char *sv = 0, *end;
1510 char *cp;
1511 int j;
1512 int errcnt = 0;
1513 cp = strchr(argv[i],'=');
1514 *cp = 0;
1515 for(j=0; op[j].label; j++){
1516 if( strcmp(argv[i],op[j].label)==0 ) break;
1517 }
1518 *cp = '=';
1519 if( op[j].label==0 ){
1520 if( err ){
1521 fprintf(err,"%sundefined option.\n",emsg);
1522 errline(i,0,err);
1523 }
1524 errcnt++;
1525 }else{
1526 cp++;
1527 switch( op[j].type ){
1528 case OPT_FLAG:
1529 case OPT_FFLAG:
1530 if( err ){
1531 fprintf(err,"%soption requires an argument.\n",emsg);
1532 errline(i,0,err);
1533 }
1534 errcnt++;
1535 break;
1536 case OPT_DBL:
1537 case OPT_FDBL:
1538 dv = strtod(cp,&end);
1539 if( *end ){
1540 if( err ){
1541 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001542 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001543 }
1544 errcnt++;
1545 }
1546 break;
1547 case OPT_INT:
1548 case OPT_FINT:
1549 lv = strtol(cp,&end,0);
1550 if( *end ){
1551 if( err ){
1552 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001553 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001554 }
1555 errcnt++;
1556 }
1557 break;
1558 case OPT_STR:
1559 case OPT_FSTR:
1560 sv = cp;
1561 break;
1562 }
1563 switch( op[j].type ){
1564 case OPT_FLAG:
1565 case OPT_FFLAG:
1566 break;
1567 case OPT_DBL:
1568 *(double*)(op[j].arg) = dv;
1569 break;
1570 case OPT_FDBL:
1571 (*(void(*)())(op[j].arg))(dv);
1572 break;
1573 case OPT_INT:
1574 *(int*)(op[j].arg) = lv;
1575 break;
1576 case OPT_FINT:
1577 (*(void(*)())(op[j].arg))((int)lv);
1578 break;
1579 case OPT_STR:
1580 *(char**)(op[j].arg) = sv;
1581 break;
1582 case OPT_FSTR:
1583 (*(void(*)())(op[j].arg))(sv);
1584 break;
1585 }
1586 }
1587 return errcnt;
1588}
1589
drhb0c86772000-06-02 23:21:26 +00001590int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001591char **a;
1592struct s_options *o;
1593FILE *err;
1594{
1595 int errcnt = 0;
1596 argv = a;
1597 op = o;
1598 errstream = err;
1599 if( argv && *argv && op ){
1600 int i;
1601 for(i=1; argv[i]; i++){
1602 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1603 errcnt += handleflags(i,err);
1604 }else if( strchr(argv[i],'=') ){
1605 errcnt += handleswitch(i,err);
1606 }
1607 }
1608 }
1609 if( errcnt>0 ){
1610 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001611 OptPrint();
drh75897232000-05-29 14:26:00 +00001612 exit(1);
1613 }
1614 return 0;
1615}
1616
drhb0c86772000-06-02 23:21:26 +00001617int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001618 int cnt = 0;
1619 int dashdash = 0;
1620 int i;
1621 if( argv!=0 && argv[0]!=0 ){
1622 for(i=1; argv[i]; i++){
1623 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1624 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1625 }
1626 }
1627 return cnt;
1628}
1629
drhb0c86772000-06-02 23:21:26 +00001630char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001631int n;
1632{
1633 int i;
1634 i = argindex(n);
1635 return i>=0 ? argv[i] : 0;
1636}
1637
drhb0c86772000-06-02 23:21:26 +00001638void OptErr(n)
drh75897232000-05-29 14:26:00 +00001639int n;
1640{
1641 int i;
1642 i = argindex(n);
1643 if( i>=0 ) errline(i,0,errstream);
1644}
1645
drhb0c86772000-06-02 23:21:26 +00001646void OptPrint(){
drh75897232000-05-29 14:26:00 +00001647 int i;
1648 int max, len;
1649 max = 0;
1650 for(i=0; op[i].label; i++){
1651 len = strlen(op[i].label) + 1;
1652 switch( op[i].type ){
1653 case OPT_FLAG:
1654 case OPT_FFLAG:
1655 break;
1656 case OPT_INT:
1657 case OPT_FINT:
1658 len += 9; /* length of "<integer>" */
1659 break;
1660 case OPT_DBL:
1661 case OPT_FDBL:
1662 len += 6; /* length of "<real>" */
1663 break;
1664 case OPT_STR:
1665 case OPT_FSTR:
1666 len += 8; /* length of "<string>" */
1667 break;
1668 }
1669 if( len>max ) max = len;
1670 }
1671 for(i=0; op[i].label; i++){
1672 switch( op[i].type ){
1673 case OPT_FLAG:
1674 case OPT_FFLAG:
1675 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1676 break;
1677 case OPT_INT:
1678 case OPT_FINT:
1679 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
1680 max-strlen(op[i].label)-9,"",op[i].message);
1681 break;
1682 case OPT_DBL:
1683 case OPT_FDBL:
1684 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
1685 max-strlen(op[i].label)-6,"",op[i].message);
1686 break;
1687 case OPT_STR:
1688 case OPT_FSTR:
1689 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
1690 max-strlen(op[i].label)-8,"",op[i].message);
1691 break;
1692 }
1693 }
1694}
1695/*********************** From the file "parse.c" ****************************/
1696/*
1697** Input file parser for the LEMON parser generator.
1698*/
1699
1700/* The state of the parser */
1701struct pstate {
1702 char *filename; /* Name of the input file */
1703 int tokenlineno; /* Linenumber at which current token starts */
1704 int errorcnt; /* Number of errors so far */
1705 char *tokenstart; /* Text of current token */
1706 struct lemon *gp; /* Global state vector */
1707 enum e_state {
1708 INITIALIZE,
1709 WAITING_FOR_DECL_OR_RULE,
1710 WAITING_FOR_DECL_KEYWORD,
1711 WAITING_FOR_DECL_ARG,
1712 WAITING_FOR_PRECEDENCE_SYMBOL,
1713 WAITING_FOR_ARROW,
1714 IN_RHS,
1715 LHS_ALIAS_1,
1716 LHS_ALIAS_2,
1717 LHS_ALIAS_3,
1718 RHS_ALIAS_1,
1719 RHS_ALIAS_2,
1720 PRECEDENCE_MARK_1,
1721 PRECEDENCE_MARK_2,
1722 RESYNC_AFTER_RULE_ERROR,
1723 RESYNC_AFTER_DECL_ERROR,
1724 WAITING_FOR_DESTRUCTOR_SYMBOL,
1725 WAITING_FOR_DATATYPE_SYMBOL
1726 } state; /* The state of the parser */
1727 struct symbol *lhs; /* Left-hand side of current rule */
1728 char *lhsalias; /* Alias for the LHS */
1729 int nrhs; /* Number of right-hand side symbols seen */
1730 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1731 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1732 struct rule *prevrule; /* Previous rule parsed */
1733 char *declkeyword; /* Keyword of a declaration */
1734 char **declargslot; /* Where the declaration argument should be put */
1735 int *decllnslot; /* Where the declaration linenumber is put */
1736 enum e_assoc declassoc; /* Assign this association to decl arguments */
1737 int preccounter; /* Assign this precedence to decl arguments */
1738 struct rule *firstrule; /* Pointer to first rule in the grammar */
1739 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1740};
1741
1742/* Parse a single token */
1743static void parseonetoken(psp)
1744struct pstate *psp;
1745{
1746 char *x;
1747 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1748#if 0
1749 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1750 x,psp->state);
1751#endif
1752 switch( psp->state ){
1753 case INITIALIZE:
1754 psp->prevrule = 0;
1755 psp->preccounter = 0;
1756 psp->firstrule = psp->lastrule = 0;
1757 psp->gp->nrule = 0;
1758 /* Fall thru to next case */
1759 case WAITING_FOR_DECL_OR_RULE:
1760 if( x[0]=='%' ){
1761 psp->state = WAITING_FOR_DECL_KEYWORD;
1762 }else if( islower(x[0]) ){
1763 psp->lhs = Symbol_new(x);
1764 psp->nrhs = 0;
1765 psp->lhsalias = 0;
1766 psp->state = WAITING_FOR_ARROW;
1767 }else if( x[0]=='{' ){
1768 if( psp->prevrule==0 ){
1769 ErrorMsg(psp->filename,psp->tokenlineno,
1770"There is not prior rule opon which to attach the code \
1771fragment which begins on this line.");
1772 psp->errorcnt++;
1773 }else if( psp->prevrule->code!=0 ){
1774 ErrorMsg(psp->filename,psp->tokenlineno,
1775"Code fragment beginning on this line is not the first \
1776to follow the previous rule.");
1777 psp->errorcnt++;
1778 }else{
1779 psp->prevrule->line = psp->tokenlineno;
1780 psp->prevrule->code = &x[1];
1781 }
1782 }else if( x[0]=='[' ){
1783 psp->state = PRECEDENCE_MARK_1;
1784 }else{
1785 ErrorMsg(psp->filename,psp->tokenlineno,
1786 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
1787 x);
1788 psp->errorcnt++;
1789 }
1790 break;
1791 case PRECEDENCE_MARK_1:
1792 if( !isupper(x[0]) ){
1793 ErrorMsg(psp->filename,psp->tokenlineno,
1794 "The precedence symbol must be a terminal.");
1795 psp->errorcnt++;
1796 }else if( psp->prevrule==0 ){
1797 ErrorMsg(psp->filename,psp->tokenlineno,
1798 "There is no prior rule to assign precedence \"[%s]\".",x);
1799 psp->errorcnt++;
1800 }else if( psp->prevrule->precsym!=0 ){
1801 ErrorMsg(psp->filename,psp->tokenlineno,
1802"Precedence mark on this line is not the first \
1803to follow the previous rule.");
1804 psp->errorcnt++;
1805 }else{
1806 psp->prevrule->precsym = Symbol_new(x);
1807 }
1808 psp->state = PRECEDENCE_MARK_2;
1809 break;
1810 case PRECEDENCE_MARK_2:
1811 if( x[0]!=']' ){
1812 ErrorMsg(psp->filename,psp->tokenlineno,
1813 "Missing \"]\" on precedence mark.");
1814 psp->errorcnt++;
1815 }
1816 psp->state = WAITING_FOR_DECL_OR_RULE;
1817 break;
1818 case WAITING_FOR_ARROW:
1819 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
1820 psp->state = IN_RHS;
1821 }else if( x[0]=='(' ){
1822 psp->state = LHS_ALIAS_1;
1823 }else{
1824 ErrorMsg(psp->filename,psp->tokenlineno,
1825 "Expected to see a \":\" following the LHS symbol \"%s\".",
1826 psp->lhs->name);
1827 psp->errorcnt++;
1828 psp->state = RESYNC_AFTER_RULE_ERROR;
1829 }
1830 break;
1831 case LHS_ALIAS_1:
1832 if( isalpha(x[0]) ){
1833 psp->lhsalias = x;
1834 psp->state = LHS_ALIAS_2;
1835 }else{
1836 ErrorMsg(psp->filename,psp->tokenlineno,
1837 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
1838 x,psp->lhs->name);
1839 psp->errorcnt++;
1840 psp->state = RESYNC_AFTER_RULE_ERROR;
1841 }
1842 break;
1843 case LHS_ALIAS_2:
1844 if( x[0]==')' ){
1845 psp->state = LHS_ALIAS_3;
1846 }else{
1847 ErrorMsg(psp->filename,psp->tokenlineno,
1848 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
1849 psp->errorcnt++;
1850 psp->state = RESYNC_AFTER_RULE_ERROR;
1851 }
1852 break;
1853 case LHS_ALIAS_3:
1854 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
1855 psp->state = IN_RHS;
1856 }else{
1857 ErrorMsg(psp->filename,psp->tokenlineno,
1858 "Missing \"->\" following: \"%s(%s)\".",
1859 psp->lhs->name,psp->lhsalias);
1860 psp->errorcnt++;
1861 psp->state = RESYNC_AFTER_RULE_ERROR;
1862 }
1863 break;
1864 case IN_RHS:
1865 if( x[0]=='.' ){
1866 struct rule *rp;
1867 rp = (struct rule *)malloc( sizeof(struct rule) +
1868 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
1869 if( rp==0 ){
1870 ErrorMsg(psp->filename,psp->tokenlineno,
1871 "Can't allocate enough memory for this rule.");
1872 psp->errorcnt++;
1873 psp->prevrule = 0;
1874 }else{
1875 int i;
1876 rp->ruleline = psp->tokenlineno;
1877 rp->rhs = (struct symbol**)&rp[1];
1878 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
1879 for(i=0; i<psp->nrhs; i++){
1880 rp->rhs[i] = psp->rhs[i];
1881 rp->rhsalias[i] = psp->alias[i];
1882 }
1883 rp->lhs = psp->lhs;
1884 rp->lhsalias = psp->lhsalias;
1885 rp->nrhs = psp->nrhs;
1886 rp->code = 0;
1887 rp->precsym = 0;
1888 rp->index = psp->gp->nrule++;
1889 rp->nextlhs = rp->lhs->rule;
1890 rp->lhs->rule = rp;
1891 rp->next = 0;
1892 if( psp->firstrule==0 ){
1893 psp->firstrule = psp->lastrule = rp;
1894 }else{
1895 psp->lastrule->next = rp;
1896 psp->lastrule = rp;
1897 }
1898 psp->prevrule = rp;
1899 }
1900 psp->state = WAITING_FOR_DECL_OR_RULE;
1901 }else if( isalpha(x[0]) ){
1902 if( psp->nrhs>=MAXRHS ){
1903 ErrorMsg(psp->filename,psp->tokenlineno,
1904 "Too many symbol on RHS or rule beginning at \"%s\".",
1905 x);
1906 psp->errorcnt++;
1907 psp->state = RESYNC_AFTER_RULE_ERROR;
1908 }else{
1909 psp->rhs[psp->nrhs] = Symbol_new(x);
1910 psp->alias[psp->nrhs] = 0;
1911 psp->nrhs++;
1912 }
1913 }else if( x[0]=='(' && psp->nrhs>0 ){
1914 psp->state = RHS_ALIAS_1;
1915 }else{
1916 ErrorMsg(psp->filename,psp->tokenlineno,
1917 "Illegal character on RHS of rule: \"%s\".",x);
1918 psp->errorcnt++;
1919 psp->state = RESYNC_AFTER_RULE_ERROR;
1920 }
1921 break;
1922 case RHS_ALIAS_1:
1923 if( isalpha(x[0]) ){
1924 psp->alias[psp->nrhs-1] = x;
1925 psp->state = RHS_ALIAS_2;
1926 }else{
1927 ErrorMsg(psp->filename,psp->tokenlineno,
1928 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
1929 x,psp->rhs[psp->nrhs-1]->name);
1930 psp->errorcnt++;
1931 psp->state = RESYNC_AFTER_RULE_ERROR;
1932 }
1933 break;
1934 case RHS_ALIAS_2:
1935 if( x[0]==')' ){
1936 psp->state = IN_RHS;
1937 }else{
1938 ErrorMsg(psp->filename,psp->tokenlineno,
1939 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
1940 psp->errorcnt++;
1941 psp->state = RESYNC_AFTER_RULE_ERROR;
1942 }
1943 break;
1944 case WAITING_FOR_DECL_KEYWORD:
1945 if( isalpha(x[0]) ){
1946 psp->declkeyword = x;
1947 psp->declargslot = 0;
1948 psp->decllnslot = 0;
1949 psp->state = WAITING_FOR_DECL_ARG;
1950 if( strcmp(x,"name")==0 ){
1951 psp->declargslot = &(psp->gp->name);
1952 }else if( strcmp(x,"include")==0 ){
1953 psp->declargslot = &(psp->gp->include);
1954 psp->decllnslot = &psp->gp->includeln;
1955 }else if( strcmp(x,"code")==0 ){
1956 psp->declargslot = &(psp->gp->extracode);
1957 psp->decllnslot = &psp->gp->extracodeln;
1958 }else if( strcmp(x,"token_destructor")==0 ){
1959 psp->declargslot = &psp->gp->tokendest;
1960 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00001961 }else if( strcmp(x,"default_destructor")==0 ){
1962 psp->declargslot = &psp->gp->vardest;
1963 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00001964 }else if( strcmp(x,"token_prefix")==0 ){
1965 psp->declargslot = &psp->gp->tokenprefix;
1966 }else if( strcmp(x,"syntax_error")==0 ){
1967 psp->declargslot = &(psp->gp->error);
1968 psp->decllnslot = &psp->gp->errorln;
1969 }else if( strcmp(x,"parse_accept")==0 ){
1970 psp->declargslot = &(psp->gp->accept);
1971 psp->decllnslot = &psp->gp->acceptln;
1972 }else if( strcmp(x,"parse_failure")==0 ){
1973 psp->declargslot = &(psp->gp->failure);
1974 psp->decllnslot = &psp->gp->failureln;
1975 }else if( strcmp(x,"stack_overflow")==0 ){
1976 psp->declargslot = &(psp->gp->overflow);
1977 psp->decllnslot = &psp->gp->overflowln;
1978 }else if( strcmp(x,"extra_argument")==0 ){
1979 psp->declargslot = &(psp->gp->arg);
1980 }else if( strcmp(x,"token_type")==0 ){
1981 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00001982 }else if( strcmp(x,"default_type")==0 ){
1983 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00001984 }else if( strcmp(x,"stack_size")==0 ){
1985 psp->declargslot = &(psp->gp->stacksize);
1986 }else if( strcmp(x,"start_symbol")==0 ){
1987 psp->declargslot = &(psp->gp->start);
1988 }else if( strcmp(x,"left")==0 ){
1989 psp->preccounter++;
1990 psp->declassoc = LEFT;
1991 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
1992 }else if( strcmp(x,"right")==0 ){
1993 psp->preccounter++;
1994 psp->declassoc = RIGHT;
1995 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
1996 }else if( strcmp(x,"nonassoc")==0 ){
1997 psp->preccounter++;
1998 psp->declassoc = NONE;
1999 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2000 }else if( strcmp(x,"destructor")==0 ){
2001 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2002 }else if( strcmp(x,"type")==0 ){
2003 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
2004 }else{
2005 ErrorMsg(psp->filename,psp->tokenlineno,
2006 "Unknown declaration keyword: \"%%%s\".",x);
2007 psp->errorcnt++;
2008 psp->state = RESYNC_AFTER_DECL_ERROR;
2009 }
2010 }else{
2011 ErrorMsg(psp->filename,psp->tokenlineno,
2012 "Illegal declaration keyword: \"%s\".",x);
2013 psp->errorcnt++;
2014 psp->state = RESYNC_AFTER_DECL_ERROR;
2015 }
2016 break;
2017 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2018 if( !isalpha(x[0]) ){
2019 ErrorMsg(psp->filename,psp->tokenlineno,
2020 "Symbol name missing after %destructor keyword");
2021 psp->errorcnt++;
2022 psp->state = RESYNC_AFTER_DECL_ERROR;
2023 }else{
2024 struct symbol *sp = Symbol_new(x);
2025 psp->declargslot = &sp->destructor;
2026 psp->decllnslot = &sp->destructorln;
2027 psp->state = WAITING_FOR_DECL_ARG;
2028 }
2029 break;
2030 case WAITING_FOR_DATATYPE_SYMBOL:
2031 if( !isalpha(x[0]) ){
2032 ErrorMsg(psp->filename,psp->tokenlineno,
2033 "Symbol name missing after %destructor keyword");
2034 psp->errorcnt++;
2035 psp->state = RESYNC_AFTER_DECL_ERROR;
2036 }else{
2037 struct symbol *sp = Symbol_new(x);
2038 psp->declargslot = &sp->datatype;
2039 psp->decllnslot = 0;
2040 psp->state = WAITING_FOR_DECL_ARG;
2041 }
2042 break;
2043 case WAITING_FOR_PRECEDENCE_SYMBOL:
2044 if( x[0]=='.' ){
2045 psp->state = WAITING_FOR_DECL_OR_RULE;
2046 }else if( isupper(x[0]) ){
2047 struct symbol *sp;
2048 sp = Symbol_new(x);
2049 if( sp->prec>=0 ){
2050 ErrorMsg(psp->filename,psp->tokenlineno,
2051 "Symbol \"%s\" has already be given a precedence.",x);
2052 psp->errorcnt++;
2053 }else{
2054 sp->prec = psp->preccounter;
2055 sp->assoc = psp->declassoc;
2056 }
2057 }else{
2058 ErrorMsg(psp->filename,psp->tokenlineno,
2059 "Can't assign a precedence to \"%s\".",x);
2060 psp->errorcnt++;
2061 }
2062 break;
2063 case WAITING_FOR_DECL_ARG:
2064 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2065 if( *(psp->declargslot)!=0 ){
2066 ErrorMsg(psp->filename,psp->tokenlineno,
2067 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2068 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2069 psp->errorcnt++;
2070 psp->state = RESYNC_AFTER_DECL_ERROR;
2071 }else{
2072 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2073 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2074 psp->state = WAITING_FOR_DECL_OR_RULE;
2075 }
2076 }else{
2077 ErrorMsg(psp->filename,psp->tokenlineno,
2078 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2079 psp->errorcnt++;
2080 psp->state = RESYNC_AFTER_DECL_ERROR;
2081 }
2082 break;
2083 case RESYNC_AFTER_RULE_ERROR:
2084/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2085** break; */
2086 case RESYNC_AFTER_DECL_ERROR:
2087 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2088 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2089 break;
2090 }
2091}
2092
2093/* In spite of its name, this function is really a scanner. It read
2094** in the entire input file (all at once) then tokenizes it. Each
2095** token is passed to the function "parseonetoken" which builds all
2096** the appropriate data structures in the global state vector "gp".
2097*/
2098void Parse(gp)
2099struct lemon *gp;
2100{
2101 struct pstate ps;
2102 FILE *fp;
2103 char *filebuf;
2104 int filesize;
2105 int lineno;
2106 int c;
2107 char *cp, *nextcp;
2108 int startline = 0;
2109
2110 ps.gp = gp;
2111 ps.filename = gp->filename;
2112 ps.errorcnt = 0;
2113 ps.state = INITIALIZE;
2114
2115 /* Begin by reading the input file */
2116 fp = fopen(ps.filename,"rb");
2117 if( fp==0 ){
2118 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2119 gp->errorcnt++;
2120 return;
2121 }
2122 fseek(fp,0,2);
2123 filesize = ftell(fp);
2124 rewind(fp);
2125 filebuf = (char *)malloc( filesize+1 );
2126 if( filebuf==0 ){
2127 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2128 filesize+1);
2129 gp->errorcnt++;
2130 return;
2131 }
2132 if( fread(filebuf,1,filesize,fp)!=filesize ){
2133 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2134 filesize);
2135 free(filebuf);
2136 gp->errorcnt++;
2137 return;
2138 }
2139 fclose(fp);
2140 filebuf[filesize] = 0;
2141
2142 /* Now scan the text of the input file */
2143 lineno = 1;
2144 for(cp=filebuf; (c= *cp)!=0; ){
2145 if( c=='\n' ) lineno++; /* Keep track of the line number */
2146 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2147 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2148 cp+=2;
2149 while( (c= *cp)!=0 && c!='\n' ) cp++;
2150 continue;
2151 }
2152 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2153 cp+=2;
2154 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2155 if( c=='\n' ) lineno++;
2156 cp++;
2157 }
2158 if( c ) cp++;
2159 continue;
2160 }
2161 ps.tokenstart = cp; /* Mark the beginning of the token */
2162 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2163 if( c=='\"' ){ /* String literals */
2164 cp++;
2165 while( (c= *cp)!=0 && c!='\"' ){
2166 if( c=='\n' ) lineno++;
2167 cp++;
2168 }
2169 if( c==0 ){
2170 ErrorMsg(ps.filename,startline,
2171"String starting on this line is not terminated before the end of the file.");
2172 ps.errorcnt++;
2173 nextcp = cp;
2174 }else{
2175 nextcp = cp+1;
2176 }
2177 }else if( c=='{' ){ /* A block of C code */
2178 int level;
2179 cp++;
2180 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2181 if( c=='\n' ) lineno++;
2182 else if( c=='{' ) level++;
2183 else if( c=='}' ) level--;
2184 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2185 int prevc;
2186 cp = &cp[2];
2187 prevc = 0;
2188 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2189 if( c=='\n' ) lineno++;
2190 prevc = c;
2191 cp++;
2192 }
2193 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2194 cp = &cp[2];
2195 while( (c= *cp)!=0 && c!='\n' ) cp++;
2196 if( c ) lineno++;
2197 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2198 int startchar, prevc;
2199 startchar = c;
2200 prevc = 0;
2201 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2202 if( c=='\n' ) lineno++;
2203 if( prevc=='\\' ) prevc = 0;
2204 else prevc = c;
2205 }
2206 }
2207 }
2208 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002209 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002210"C code starting on this line is not terminated before the end of the file.");
2211 ps.errorcnt++;
2212 nextcp = cp;
2213 }else{
2214 nextcp = cp+1;
2215 }
2216 }else if( isalnum(c) ){ /* Identifiers */
2217 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2218 nextcp = cp;
2219 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2220 cp += 3;
2221 nextcp = cp;
2222 }else{ /* All other (one character) operators */
2223 cp++;
2224 nextcp = cp;
2225 }
2226 c = *cp;
2227 *cp = 0; /* Null terminate the token */
2228 parseonetoken(&ps); /* Parse the token */
2229 *cp = c; /* Restore the buffer */
2230 cp = nextcp;
2231 }
2232 free(filebuf); /* Release the buffer after parsing */
2233 gp->rule = ps.firstrule;
2234 gp->errorcnt = ps.errorcnt;
2235}
2236/*************************** From the file "plink.c" *********************/
2237/*
2238** Routines processing configuration follow-set propagation links
2239** in the LEMON parser generator.
2240*/
2241static struct plink *plink_freelist = 0;
2242
2243/* Allocate a new plink */
2244struct plink *Plink_new(){
2245 struct plink *new;
2246
2247 if( plink_freelist==0 ){
2248 int i;
2249 int amt = 100;
2250 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2251 if( plink_freelist==0 ){
2252 fprintf(stderr,
2253 "Unable to allocate memory for a new follow-set propagation link.\n");
2254 exit(1);
2255 }
2256 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2257 plink_freelist[amt-1].next = 0;
2258 }
2259 new = plink_freelist;
2260 plink_freelist = plink_freelist->next;
2261 return new;
2262}
2263
2264/* Add a plink to a plink list */
2265void Plink_add(plpp,cfp)
2266struct plink **plpp;
2267struct config *cfp;
2268{
2269 struct plink *new;
2270 new = Plink_new();
2271 new->next = *plpp;
2272 *plpp = new;
2273 new->cfp = cfp;
2274}
2275
2276/* Transfer every plink on the list "from" to the list "to" */
2277void Plink_copy(to,from)
2278struct plink **to;
2279struct plink *from;
2280{
2281 struct plink *nextpl;
2282 while( from ){
2283 nextpl = from->next;
2284 from->next = *to;
2285 *to = from;
2286 from = nextpl;
2287 }
2288}
2289
2290/* Delete every plink on the list */
2291void Plink_delete(plp)
2292struct plink *plp;
2293{
2294 struct plink *nextpl;
2295
2296 while( plp ){
2297 nextpl = plp->next;
2298 plp->next = plink_freelist;
2299 plink_freelist = plp;
2300 plp = nextpl;
2301 }
2302}
2303/*********************** From the file "report.c" **************************/
2304/*
2305** Procedures for generating reports and tables in the LEMON parser generator.
2306*/
2307
2308/* Generate a filename with the given suffix. Space to hold the
2309** name comes from malloc() and must be freed by the calling
2310** function.
2311*/
2312PRIVATE char *file_makename(lemp,suffix)
2313struct lemon *lemp;
2314char *suffix;
2315{
2316 char *name;
2317 char *cp;
2318
2319 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2320 if( name==0 ){
2321 fprintf(stderr,"Can't allocate space for a filename.\n");
2322 exit(1);
2323 }
2324 strcpy(name,lemp->filename);
2325 cp = strrchr(name,'.');
2326 if( cp ) *cp = 0;
2327 strcat(name,suffix);
2328 return name;
2329}
2330
2331/* Open a file with a name based on the name of the input file,
2332** but with a different (specified) suffix, and return a pointer
2333** to the stream */
2334PRIVATE FILE *file_open(lemp,suffix,mode)
2335struct lemon *lemp;
2336char *suffix;
2337char *mode;
2338{
2339 FILE *fp;
2340
2341 if( lemp->outname ) free(lemp->outname);
2342 lemp->outname = file_makename(lemp, suffix);
2343 fp = fopen(lemp->outname,mode);
2344 if( fp==0 && *mode=='w' ){
2345 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2346 lemp->errorcnt++;
2347 return 0;
2348 }
2349 return fp;
2350}
2351
2352/* Duplicate the input file without comments and without actions
2353** on rules */
2354void Reprint(lemp)
2355struct lemon *lemp;
2356{
2357 struct rule *rp;
2358 struct symbol *sp;
2359 int i, j, maxlen, len, ncolumns, skip;
2360 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2361 maxlen = 10;
2362 for(i=0; i<lemp->nsymbol; i++){
2363 sp = lemp->symbols[i];
2364 len = strlen(sp->name);
2365 if( len>maxlen ) maxlen = len;
2366 }
2367 ncolumns = 76/(maxlen+5);
2368 if( ncolumns<1 ) ncolumns = 1;
2369 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2370 for(i=0; i<skip; i++){
2371 printf("//");
2372 for(j=i; j<lemp->nsymbol; j+=skip){
2373 sp = lemp->symbols[j];
2374 assert( sp->index==j );
2375 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2376 }
2377 printf("\n");
2378 }
2379 for(rp=lemp->rule; rp; rp=rp->next){
2380 printf("%s",rp->lhs->name);
2381/* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2382 printf(" ::=");
2383 for(i=0; i<rp->nrhs; i++){
2384 printf(" %s",rp->rhs[i]->name);
2385/* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2386 }
2387 printf(".");
2388 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2389/* if( rp->code ) printf("\n %s",rp->code); */
2390 printf("\n");
2391 }
2392}
2393
2394void ConfigPrint(fp,cfp)
2395FILE *fp;
2396struct config *cfp;
2397{
2398 struct rule *rp;
2399 int i;
2400 rp = cfp->rp;
2401 fprintf(fp,"%s ::=",rp->lhs->name);
2402 for(i=0; i<=rp->nrhs; i++){
2403 if( i==cfp->dot ) fprintf(fp," *");
2404 if( i==rp->nrhs ) break;
2405 fprintf(fp," %s",rp->rhs[i]->name);
2406 }
2407}
2408
2409/* #define TEST */
2410#ifdef TEST
2411/* Print a set */
2412PRIVATE void SetPrint(out,set,lemp)
2413FILE *out;
2414char *set;
2415struct lemon *lemp;
2416{
2417 int i;
2418 char *spacer;
2419 spacer = "";
2420 fprintf(out,"%12s[","");
2421 for(i=0; i<lemp->nterminal; i++){
2422 if( SetFind(set,i) ){
2423 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2424 spacer = " ";
2425 }
2426 }
2427 fprintf(out,"]\n");
2428}
2429
2430/* Print a plink chain */
2431PRIVATE void PlinkPrint(out,plp,tag)
2432FILE *out;
2433struct plink *plp;
2434char *tag;
2435{
2436 while( plp ){
2437 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index);
2438 ConfigPrint(out,plp->cfp);
2439 fprintf(out,"\n");
2440 plp = plp->next;
2441 }
2442}
2443#endif
2444
2445/* Print an action to the given file descriptor. Return FALSE if
2446** nothing was actually printed.
2447*/
2448int PrintAction(struct action *ap, FILE *fp, int indent){
2449 int result = 1;
2450 switch( ap->type ){
2451 case SHIFT:
2452 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index);
2453 break;
2454 case REDUCE:
2455 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2456 break;
2457 case ACCEPT:
2458 fprintf(fp,"%*s accept",indent,ap->sp->name);
2459 break;
2460 case ERROR:
2461 fprintf(fp,"%*s error",indent,ap->sp->name);
2462 break;
2463 case CONFLICT:
2464 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2465 indent,ap->sp->name,ap->x.rp->index);
2466 break;
2467 case SH_RESOLVED:
2468 case RD_RESOLVED:
2469 case NOT_USED:
2470 result = 0;
2471 break;
2472 }
2473 return result;
2474}
2475
2476/* Generate the "y.output" log file */
2477void ReportOutput(lemp)
2478struct lemon *lemp;
2479{
2480 int i;
2481 struct state *stp;
2482 struct config *cfp;
2483 struct action *ap;
2484 FILE *fp;
2485
2486 fp = file_open(lemp,".out","w");
2487 if( fp==0 ) return;
2488 fprintf(fp," \b");
2489 for(i=0; i<lemp->nstate; i++){
2490 stp = lemp->sorted[i];
2491 fprintf(fp,"State %d:\n",stp->index);
2492 if( lemp->basisflag ) cfp=stp->bp;
2493 else cfp=stp->cfp;
2494 while( cfp ){
2495 char buf[20];
2496 if( cfp->dot==cfp->rp->nrhs ){
2497 sprintf(buf,"(%d)",cfp->rp->index);
2498 fprintf(fp," %5s ",buf);
2499 }else{
2500 fprintf(fp," ");
2501 }
2502 ConfigPrint(fp,cfp);
2503 fprintf(fp,"\n");
2504#ifdef TEST
2505 SetPrint(fp,cfp->fws,lemp);
2506 PlinkPrint(fp,cfp->fplp,"To ");
2507 PlinkPrint(fp,cfp->bplp,"From");
2508#endif
2509 if( lemp->basisflag ) cfp=cfp->bp;
2510 else cfp=cfp->next;
2511 }
2512 fprintf(fp,"\n");
2513 for(ap=stp->ap; ap; ap=ap->next){
2514 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2515 }
2516 fprintf(fp,"\n");
2517 }
2518 fclose(fp);
2519 return;
2520}
2521
2522/* Search for the file "name" which is in the same directory as
2523** the exacutable */
2524PRIVATE char *pathsearch(argv0,name,modemask)
2525char *argv0;
2526char *name;
2527int modemask;
2528{
2529 char *pathlist;
2530 char *path,*cp;
2531 char c;
2532 extern int access();
2533
2534#ifdef __WIN32__
2535 cp = strrchr(argv0,'\\');
2536#else
2537 cp = strrchr(argv0,'/');
2538#endif
2539 if( cp ){
2540 c = *cp;
2541 *cp = 0;
2542 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2543 if( path ) sprintf(path,"%s/%s",argv0,name);
2544 *cp = c;
2545 }else{
2546 extern char *getenv();
2547 pathlist = getenv("PATH");
2548 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2549 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2550 if( path!=0 ){
2551 while( *pathlist ){
2552 cp = strchr(pathlist,':');
2553 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2554 c = *cp;
2555 *cp = 0;
2556 sprintf(path,"%s/%s",pathlist,name);
2557 *cp = c;
2558 if( c==0 ) pathlist = "";
2559 else pathlist = &cp[1];
2560 if( access(path,modemask)==0 ) break;
2561 }
2562 }
2563 }
2564 return path;
2565}
2566
2567/* Given an action, compute the integer value for that action
2568** which is to be put in the action table of the generated machine.
2569** Return negative if no action should be generated.
2570*/
2571PRIVATE int compute_action(lemp,ap)
2572struct lemon *lemp;
2573struct action *ap;
2574{
2575 int act;
2576 switch( ap->type ){
2577 case SHIFT: act = ap->x.stp->index; break;
2578 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2579 case ERROR: act = lemp->nstate + lemp->nrule; break;
2580 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2581 default: act = -1; break;
2582 }
2583 return act;
2584}
2585
2586#define LINESIZE 1000
2587/* The next cluster of routines are for reading the template file
2588** and writing the results to the generated parser */
2589/* The first function transfers data from "in" to "out" until
2590** a line is seen which begins with "%%". The line number is
2591** tracked.
2592**
2593** if name!=0, then any word that begin with "Parse" is changed to
2594** begin with *name instead.
2595*/
2596PRIVATE void tplt_xfer(name,in,out,lineno)
2597char *name;
2598FILE *in;
2599FILE *out;
2600int *lineno;
2601{
2602 int i, iStart;
2603 char line[LINESIZE];
2604 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2605 (*lineno)++;
2606 iStart = 0;
2607 if( name ){
2608 for(i=0; line[i]; i++){
2609 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2610 && (i==0 || !isalpha(line[i-1]))
2611 ){
2612 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2613 fprintf(out,"%s",name);
2614 i += 4;
2615 iStart = i+1;
2616 }
2617 }
2618 }
2619 fprintf(out,"%s",&line[iStart]);
2620 }
2621}
2622
2623/* The next function finds the template file and opens it, returning
2624** a pointer to the opened file. */
2625PRIVATE FILE *tplt_open(lemp)
2626struct lemon *lemp;
2627{
2628 static char templatename[] = "lempar.c";
2629 char buf[1000];
2630 FILE *in;
2631 char *tpltname;
2632 char *cp;
2633
2634 cp = strrchr(lemp->filename,'.');
2635 if( cp ){
drhba99af52001-10-25 20:37:16 +00002636 sprintf(buf,"%.*s.lt",(unsigned long)cp-(unsigned long)lemp->filename,lemp->filename);
drh75897232000-05-29 14:26:00 +00002637 }else{
2638 sprintf(buf,"%s.lt",lemp->filename);
2639 }
2640 if( access(buf,004)==0 ){
2641 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00002642 }else if( access(templatename,004)==0 ){
2643 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00002644 }else{
2645 tpltname = pathsearch(lemp->argv0,templatename,0);
2646 }
2647 if( tpltname==0 ){
2648 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
2649 templatename);
2650 lemp->errorcnt++;
2651 return 0;
2652 }
2653 in = fopen(tpltname,"r");
2654 if( in==0 ){
2655 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
2656 lemp->errorcnt++;
2657 return 0;
2658 }
2659 return in;
2660}
2661
2662/* Print a string to the file and keep the linenumber up to date */
2663PRIVATE void tplt_print(out,lemp,str,strln,lineno)
2664FILE *out;
2665struct lemon *lemp;
2666char *str;
2667int strln;
2668int *lineno;
2669{
2670 if( str==0 ) return;
2671 fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++;
2672 while( *str ){
2673 if( *str=='\n' ) (*lineno)++;
2674 putc(*str,out);
2675 str++;
2676 }
2677 fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2;
2678 return;
2679}
2680
2681/*
2682** The following routine emits code for the destructor for the
2683** symbol sp
2684*/
2685void emit_destructor_code(out,sp,lemp,lineno)
2686FILE *out;
2687struct symbol *sp;
2688struct lemon *lemp;
2689int *lineno;
2690{
2691 char *cp;
2692
2693 int linecnt = 0;
2694 if( sp->type==TERMINAL ){
2695 cp = lemp->tokendest;
2696 if( cp==0 ) return;
2697 fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename);
drh960e8c62001-04-03 16:53:21 +00002698 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00002699 cp = sp->destructor;
drh75897232000-05-29 14:26:00 +00002700 fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename);
drh960e8c62001-04-03 16:53:21 +00002701 }else if( lemp->vardest ){
2702 cp = lemp->vardest;
2703 if( cp==0 ) return;
2704 fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename);
drh75897232000-05-29 14:26:00 +00002705 }
2706 for(; *cp; cp++){
2707 if( *cp=='$' && cp[1]=='$' ){
2708 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
2709 cp++;
2710 continue;
2711 }
2712 if( *cp=='\n' ) linecnt++;
2713 fputc(*cp,out);
2714 }
2715 (*lineno) += 3 + linecnt;
2716 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2717 return;
2718}
2719
2720/*
drh960e8c62001-04-03 16:53:21 +00002721** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00002722*/
2723int has_destructor(sp, lemp)
2724struct symbol *sp;
2725struct lemon *lemp;
2726{
2727 int ret;
2728 if( sp->type==TERMINAL ){
2729 ret = lemp->tokendest!=0;
2730 }else{
drh960e8c62001-04-03 16:53:21 +00002731 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00002732 }
2733 return ret;
2734}
2735
2736/*
2737** Generate code which executes when the rule "rp" is reduced. Write
2738** the code to "out". Make sure lineno stays up-to-date.
2739*/
2740PRIVATE void emit_code(out,rp,lemp,lineno)
2741FILE *out;
2742struct rule *rp;
2743struct lemon *lemp;
2744int *lineno;
2745{
2746 char *cp, *xp;
2747 int linecnt = 0;
2748 int i;
2749 char lhsused = 0; /* True if the LHS element has been used */
2750 char used[MAXRHS]; /* True for each RHS element which is used */
2751
2752 for(i=0; i<rp->nrhs; i++) used[i] = 0;
2753 lhsused = 0;
2754
2755 /* Generate code to do the reduce action */
2756 if( rp->code ){
2757 fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
2758 for(cp=rp->code; *cp; cp++){
2759 if( isalpha(*cp) && (cp==rp->code || !isalnum(cp[-1])) ){
2760 char saved;
2761 for(xp= &cp[1]; isalnum(*xp); xp++);
2762 saved = *xp;
2763 *xp = 0;
2764 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
2765 fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum);
2766 cp = xp;
2767 lhsused = 1;
2768 }else{
2769 for(i=0; i<rp->nrhs; i++){
2770 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
2771 fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum);
2772 cp = xp;
2773 used[i] = 1;
2774 break;
2775 }
2776 }
2777 }
2778 *xp = saved;
2779 }
2780 if( *cp=='\n' ) linecnt++;
2781 fputc(*cp,out);
2782 } /* End loop */
2783 (*lineno) += 3 + linecnt;
2784 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2785 } /* End if( rp->code ) */
2786
2787 /* Check to make sure the LHS has been used */
2788 if( rp->lhsalias && !lhsused ){
2789 ErrorMsg(lemp->filename,rp->ruleline,
2790 "Label \"%s\" for \"%s(%s)\" is never used.",
2791 rp->lhsalias,rp->lhs->name,rp->lhsalias);
2792 lemp->errorcnt++;
2793 }
2794
2795 /* Generate destructor code for RHS symbols which are not used in the
2796 ** reduce code */
2797 for(i=0; i<rp->nrhs; i++){
2798 if( rp->rhsalias[i] && !used[i] ){
2799 ErrorMsg(lemp->filename,rp->ruleline,
drh960e8c62001-04-03 16:53:21 +00002800 "Label %s for \"%s(%s)\" is never used.",
drh75897232000-05-29 14:26:00 +00002801 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
2802 lemp->errorcnt++;
2803 }else if( rp->rhsalias[i]==0 ){
2804 if( has_destructor(rp->rhs[i],lemp) ){
2805 fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n",
2806 rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++;
2807 }else{
2808 fprintf(out," /* No destructor defined for %s */\n",
2809 rp->rhs[i]->name);
2810 (*lineno)++;
2811 }
2812 }
2813 }
2814 return;
2815}
2816
2817/*
2818** Print the definition of the union used for the parser's data stack.
2819** This union contains fields for every possible data type for tokens
2820** and nonterminals. In the process of computing and printing this
2821** union, also set the ".dtnum" field of every terminal and nonterminal
2822** symbol.
2823*/
2824void print_stack_union(out,lemp,plineno,mhflag)
2825FILE *out; /* The output stream */
2826struct lemon *lemp; /* The main info structure for this parser */
2827int *plineno; /* Pointer to the line number */
2828int mhflag; /* True if generating makeheaders output */
2829{
2830 int lineno = *plineno; /* The line number of the output */
2831 char **types; /* A hash table of datatypes */
2832 int arraysize; /* Size of the "types" array */
2833 int maxdtlength; /* Maximum length of any ".datatype" field. */
2834 char *stddt; /* Standardized name for a datatype */
2835 int i,j; /* Loop counters */
2836 int hash; /* For hashing the name of a type */
2837 char *name; /* Name of the parser */
2838
2839 /* Allocate and initialize types[] and allocate stddt[] */
2840 arraysize = lemp->nsymbol * 2;
2841 types = (char**)malloc( arraysize * sizeof(char*) );
2842 for(i=0; i<arraysize; i++) types[i] = 0;
2843 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00002844 if( lemp->vartype ){
2845 maxdtlength = strlen(lemp->vartype);
2846 }
drh75897232000-05-29 14:26:00 +00002847 for(i=0; i<lemp->nsymbol; i++){
2848 int len;
2849 struct symbol *sp = lemp->symbols[i];
2850 if( sp->datatype==0 ) continue;
2851 len = strlen(sp->datatype);
2852 if( len>maxdtlength ) maxdtlength = len;
2853 }
2854 stddt = (char*)malloc( maxdtlength*2 + 1 );
2855 if( types==0 || stddt==0 ){
2856 fprintf(stderr,"Out of memory.\n");
2857 exit(1);
2858 }
2859
2860 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
2861 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00002862 ** used for terminal symbols. If there is no %default_type defined then
2863 ** 0 is also used as the .dtnum value for nonterminals which do not specify
2864 ** a datatype using the %type directive.
2865 */
drh75897232000-05-29 14:26:00 +00002866 for(i=0; i<lemp->nsymbol; i++){
2867 struct symbol *sp = lemp->symbols[i];
2868 char *cp;
2869 if( sp==lemp->errsym ){
2870 sp->dtnum = arraysize+1;
2871 continue;
2872 }
drh960e8c62001-04-03 16:53:21 +00002873 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00002874 sp->dtnum = 0;
2875 continue;
2876 }
2877 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00002878 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00002879 j = 0;
2880 while( isspace(*cp) ) cp++;
2881 while( *cp ) stddt[j++] = *cp++;
2882 while( j>0 && isspace(stddt[j-1]) ) j--;
2883 stddt[j] = 0;
2884 hash = 0;
2885 for(j=0; stddt[j]; j++){
2886 hash = hash*53 + stddt[j];
2887 }
2888 if( hash<0 ) hash = -hash;
2889 hash = hash%arraysize;
2890 while( types[hash] ){
2891 if( strcmp(types[hash],stddt)==0 ){
2892 sp->dtnum = hash + 1;
2893 break;
2894 }
2895 hash++;
2896 if( hash>=arraysize ) hash = 0;
2897 }
2898 if( types[hash]==0 ){
2899 sp->dtnum = hash + 1;
2900 types[hash] = (char*)malloc( strlen(stddt)+1 );
2901 if( types[hash]==0 ){
2902 fprintf(stderr,"Out of memory.\n");
2903 exit(1);
2904 }
2905 strcpy(types[hash],stddt);
2906 }
2907 }
2908
2909 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
2910 name = lemp->name ? lemp->name : "Parse";
2911 lineno = *plineno;
2912 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
2913 fprintf(out,"#define %sTOKENTYPE %s\n",name,
2914 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
2915 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
2916 fprintf(out,"typedef union {\n"); lineno++;
2917 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
2918 for(i=0; i<arraysize; i++){
2919 if( types[i]==0 ) continue;
2920 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
2921 free(types[i]);
2922 }
2923 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
2924 free(stddt);
2925 free(types);
2926 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
2927 *plineno = lineno;
2928}
2929
2930/* Generate C source code for the parser */
2931void ReportTable(lemp, mhflag)
2932struct lemon *lemp;
2933int mhflag; /* Output in makeheaders format if true */
2934{
2935 FILE *out, *in;
2936 char line[LINESIZE];
2937 int lineno;
2938 struct state *stp;
2939 struct action *ap;
2940 struct rule *rp;
2941 int i;
2942 int tablecnt;
2943 char *name;
2944
2945 in = tplt_open(lemp);
2946 if( in==0 ) return;
2947 out = file_open(lemp,".c","w");
2948 if( out==0 ){
2949 fclose(in);
2950 return;
2951 }
2952 lineno = 1;
2953 tplt_xfer(lemp->name,in,out,&lineno);
2954
2955 /* Generate the include code, if any */
2956 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
2957 if( mhflag ){
2958 char *name = file_makename(lemp, ".h");
2959 fprintf(out,"#include \"%s\"\n", name); lineno++;
2960 free(name);
2961 }
2962 tplt_xfer(lemp->name,in,out,&lineno);
2963
2964 /* Generate #defines for all tokens */
2965 if( mhflag ){
2966 char *prefix;
2967 fprintf(out,"#if INTERFACE\n"); lineno++;
2968 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
2969 else prefix = "";
2970 for(i=1; i<lemp->nterminal; i++){
2971 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
2972 lineno++;
2973 }
2974 fprintf(out,"#endif\n"); lineno++;
2975 }
2976 tplt_xfer(lemp->name,in,out,&lineno);
2977
2978 /* Generate the defines */
2979 fprintf(out,"/* \001 */\n");
2980 fprintf(out,"#define YYCODETYPE %s\n",
2981 lemp->nsymbol>250?"int":"unsigned char"); lineno++;
2982 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
2983 fprintf(out,"#define YYACTIONTYPE %s\n",
2984 lemp->nstate+lemp->nrule>250?"int":"unsigned char"); lineno++;
2985 print_stack_union(out,lemp,&lineno,mhflag);
2986 if( lemp->stacksize ){
2987 if( atoi(lemp->stacksize)<=0 ){
2988 ErrorMsg(lemp->filename,0,
2989"Illegal stack size: [%s]. The stack size should be an integer constant.",
2990 lemp->stacksize);
2991 lemp->errorcnt++;
2992 lemp->stacksize = "100";
2993 }
2994 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
2995 }else{
2996 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
2997 }
2998 if( mhflag ){
2999 fprintf(out,"#if INTERFACE\n"); lineno++;
3000 }
3001 name = lemp->name ? lemp->name : "Parse";
3002 if( lemp->arg && lemp->arg[0] ){
3003 int i;
3004 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003005 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3006 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh75897232000-05-29 14:26:00 +00003007 fprintf(out,"#define %sARGDECL ,%s\n",name,&lemp->arg[i]); lineno++;
3008 fprintf(out,"#define %sXARGDECL %s;\n",name,lemp->arg); lineno++;
3009 fprintf(out,"#define %sANSIARGDECL ,%s\n",name,lemp->arg); lineno++;
3010 }else{
3011 fprintf(out,"#define %sARGDECL\n",name); lineno++;
3012 fprintf(out,"#define %sXARGDECL\n",name); lineno++;
3013 fprintf(out,"#define %sANSIARGDECL\n",name); lineno++;
3014 }
3015 if( mhflag ){
3016 fprintf(out,"#endif\n"); lineno++;
3017 }
3018 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3019 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3020 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3021 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3022 tplt_xfer(lemp->name,in,out,&lineno);
3023
3024 /* Generate the action table.
3025 **
3026 ** Each entry in the action table is an element of the following
3027 ** structure:
3028 ** struct yyActionEntry {
3029 ** YYCODETYPE lookahead;
3030 ** YYACTIONTYPE action;
3031 ** struct yyActionEntry *next;
3032 ** }
3033 **
3034 ** The entries are grouped into hash tables, one hash table for each
3035 ** parser state. The hash table has a size which is the smallest
3036 ** power of two needed to hold all entries.
3037 */
3038 tablecnt = 0;
3039
3040 /* Loop over parser states */
3041 for(i=0; i<lemp->nstate; i++){
3042 int tablesize; /* size of the hash table */
3043 int j,k; /* Loop counter */
3044 int collide[2048]; /* The collision chain for the table */
3045 struct action *table[2048]; /* Build the hash table here */
3046
3047 /* Find the number of actions and initialize the hash table */
3048 stp = lemp->sorted[i];
3049 stp->tabstart = tablecnt;
3050 stp->naction = 0;
3051 for(ap=stp->ap; ap; ap=ap->next){
3052 if( ap->sp->index!=lemp->nsymbol && compute_action(lemp,ap)>=0 ){
3053 stp->naction++;
3054 }
3055 }
3056 tablesize = 1;
3057 while( tablesize<stp->naction ) tablesize += tablesize;
3058 assert( tablesize<= sizeof(table)/sizeof(table[0]) );
3059 for(j=0; j<tablesize; j++){
3060 table[j] = 0;
3061 collide[j] = -1;
3062 }
3063
3064 /* Hash the actions into the hash table */
3065 stp->tabdfltact = lemp->nstate + lemp->nrule;
3066 for(ap=stp->ap; ap; ap=ap->next){
3067 int action = compute_action(lemp,ap);
3068 int h;
3069 if( ap->sp->index==lemp->nsymbol ){
3070 stp->tabdfltact = action;
3071 }else if( action>=0 ){
3072 h = ap->sp->index & (tablesize-1);
3073 ap->collide = table[h];
3074 table[h] = ap;
3075 }
3076 }
3077
3078 /* Resolve collisions */
3079 for(j=k=0; j<tablesize; j++){
3080 if( table[j] && table[j]->collide ){
3081 while( table[k] ) k++;
3082 table[k] = table[j]->collide;
3083 collide[j] = k;
3084 table[j]->collide = 0;
3085 if( k<j ) j = k-1;
3086 }
3087 }
3088
3089 /* Print the hash table */
3090 fprintf(out,"/* State %d */\n",stp->index); lineno++;
3091 for(j=0; j<tablesize; j++){
3092 if( table[j]==0 ){
3093 fprintf(out,
3094 " {YYNOCODE,0,0}, /* Unused */\n");
3095 }else{
3096 fprintf(out," {%4d,%4d, ",
3097 table[j]->sp->index,
3098 compute_action(lemp,table[j]));
3099 if( collide[j]>=0 ){
3100 fprintf(out,"&yyActionTable[%4d] }, /* ",
3101 collide[j] + tablecnt);
3102 }else{
3103 fprintf(out,"0 }, /* ");
3104 }
3105 PrintAction(table[j],out,22);
3106 fprintf(out," */\n");
3107 }
3108 lineno++;
3109 }
3110
3111 /* Update the table count */
3112 tablecnt += tablesize;
3113 }
3114 tplt_xfer(lemp->name,in,out,&lineno);
3115 lemp->tablesize = tablecnt;
3116
3117 /* Generate the state table
3118 **
3119 ** Each entry is an element of the following structure:
3120 ** struct yyStateEntry {
3121 ** struct yyActionEntry *hashtbl;
3122 ** int mask;
3123 ** YYACTIONTYPE actionDefault;
3124 ** }
3125 */
3126 for(i=0; i<lemp->nstate; i++){
3127 int tablesize;
3128 stp = lemp->sorted[i];
3129 tablesize = 1;
3130 while( tablesize<stp->naction ) tablesize += tablesize;
3131 fprintf(out," { &yyActionTable[%d], %d, %d},\n",
3132 stp->tabstart,
3133 tablesize - 1,
3134 stp->tabdfltact); lineno++;
3135 }
3136 tplt_xfer(lemp->name,in,out,&lineno);
3137
3138 /* Generate a table containing the symbolic name of every symbol */
3139 for(i=0; i<lemp->nsymbol; i++){
3140 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3141 fprintf(out," %-15s",line);
3142 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3143 }
3144 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3145 tplt_xfer(lemp->name,in,out,&lineno);
3146
3147 /* Generate code which executes every time a symbol is popped from
3148 ** the stack while processing errors or while destroying the parser.
3149 ** (In other words, generate the %destructor actions) */
3150 if( lemp->tokendest ){
3151 for(i=0; i<lemp->nsymbol; i++){
3152 struct symbol *sp = lemp->symbols[i];
3153 if( sp==0 || sp->type!=TERMINAL ) continue;
3154 fprintf(out," case %d:\n",sp->index); lineno++;
3155 }
3156 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3157 if( i<lemp->nsymbol ){
3158 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3159 fprintf(out," break;\n"); lineno++;
3160 }
3161 }
3162 for(i=0; i<lemp->nsymbol; i++){
3163 struct symbol *sp = lemp->symbols[i];
3164 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3165 fprintf(out," case %d:\n",sp->index); lineno++;
3166 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3167 fprintf(out," break;\n"); lineno++;
3168 }
drh960e8c62001-04-03 16:53:21 +00003169 if( lemp->vardest ){
3170 struct symbol *dflt_sp = 0;
3171 for(i=0; i<lemp->nsymbol; i++){
3172 struct symbol *sp = lemp->symbols[i];
3173 if( sp==0 || sp->type==TERMINAL ||
3174 sp->index<=0 || sp->destructor!=0 ) continue;
3175 fprintf(out," case %d:\n",sp->index); lineno++;
3176 dflt_sp = sp;
3177 }
3178 if( dflt_sp!=0 ){
3179 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3180 fprintf(out," break;\n"); lineno++;
3181 }
3182 }
drh75897232000-05-29 14:26:00 +00003183 tplt_xfer(lemp->name,in,out,&lineno);
3184
3185 /* Generate code which executes whenever the parser stack overflows */
3186 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3187 tplt_xfer(lemp->name,in,out,&lineno);
3188
3189 /* Generate the table of rule information
3190 **
3191 ** Note: This code depends on the fact that rules are number
3192 ** sequentually beginning with 0.
3193 */
3194 for(rp=lemp->rule; rp; rp=rp->next){
3195 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3196 }
3197 tplt_xfer(lemp->name,in,out,&lineno);
3198
3199 /* Generate code which execution during each REDUCE action */
3200 for(rp=lemp->rule; rp; rp=rp->next){
3201 fprintf(out," case %d:\n",rp->index); lineno++;
3202 fprintf(out," YYTRACE(\"%s ::=",rp->lhs->name);
3203 for(i=0; i<rp->nrhs; i++) fprintf(out," %s",rp->rhs[i]->name);
3204 fprintf(out,"\")\n"); lineno++;
3205 emit_code(out,rp,lemp,&lineno);
3206 fprintf(out," break;\n"); lineno++;
3207 }
3208 tplt_xfer(lemp->name,in,out,&lineno);
3209
3210 /* Generate code which executes if a parse fails */
3211 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3212 tplt_xfer(lemp->name,in,out,&lineno);
3213
3214 /* Generate code which executes when a syntax error occurs */
3215 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3216 tplt_xfer(lemp->name,in,out,&lineno);
3217
3218 /* Generate code which executes when the parser accepts its input */
3219 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3220 tplt_xfer(lemp->name,in,out,&lineno);
3221
3222 /* Append any addition code the user desires */
3223 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3224
3225 fclose(in);
3226 fclose(out);
3227 return;
3228}
3229
3230/* Generate a header file for the parser */
3231void ReportHeader(lemp)
3232struct lemon *lemp;
3233{
3234 FILE *out, *in;
3235 char *prefix;
3236 char line[LINESIZE];
3237 char pattern[LINESIZE];
3238 int i;
3239
3240 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3241 else prefix = "";
3242 in = file_open(lemp,".h","r");
3243 if( in ){
3244 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3245 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3246 if( strcmp(line,pattern) ) break;
3247 }
3248 fclose(in);
3249 if( i==lemp->nterminal ){
3250 /* No change in the file. Don't rewrite it. */
3251 return;
3252 }
3253 }
3254 out = file_open(lemp,".h","w");
3255 if( out ){
3256 for(i=1; i<lemp->nterminal; i++){
3257 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3258 }
3259 fclose(out);
3260 }
3261 return;
3262}
3263
3264/* Reduce the size of the action tables, if possible, by making use
3265** of defaults.
3266**
drhb59499c2002-02-23 18:45:13 +00003267** In this version, we take the most frequent REDUCE action and make
3268** it the default. Only default a reduce if there are more than one.
drh75897232000-05-29 14:26:00 +00003269*/
3270void CompressTables(lemp)
3271struct lemon *lemp;
3272{
3273 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003274 struct action *ap, *ap2;
3275 struct rule *rp, *rp2, *rbest;
3276 int nbest, n;
drh75897232000-05-29 14:26:00 +00003277 int i;
3278 int cnt;
3279
3280 for(i=0; i<lemp->nstate; i++){
3281 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003282 nbest = 0;
3283 rbest = 0;
drh75897232000-05-29 14:26:00 +00003284
drhb59499c2002-02-23 18:45:13 +00003285 for(ap=stp->ap; ap; ap=ap->next){
3286 if( ap->type!=REDUCE ) continue;
3287 rp = ap->x.rp;
3288 if( rp==rbest ) continue;
3289 n = 1;
3290 for(ap2=ap->next; ap2; ap2=ap2->next){
3291 if( ap2->type!=REDUCE ) continue;
3292 rp2 = ap2->x.rp;
3293 if( rp2==rbest ) continue;
3294 if( rp2==rp ) n++;
3295 }
3296 if( n>nbest ){
3297 nbest = n;
3298 rbest = rp;
drh75897232000-05-29 14:26:00 +00003299 }
3300 }
drhb59499c2002-02-23 18:45:13 +00003301
3302 /* Do not make a default if the number of rules to default
3303 ** is not at least 2 */
3304 if( nbest<2 ) continue;
drh75897232000-05-29 14:26:00 +00003305
drhb59499c2002-02-23 18:45:13 +00003306
3307 /* Combine matching REDUCE actions into a single default */
3308 for(ap=stp->ap; ap; ap=ap->next){
3309 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3310 }
drh75897232000-05-29 14:26:00 +00003311 assert( ap );
3312 ap->sp = Symbol_new("{default}");
3313 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003314 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003315 }
3316 stp->ap = Action_sort(stp->ap);
3317 }
3318}
drhb59499c2002-02-23 18:45:13 +00003319
drh75897232000-05-29 14:26:00 +00003320/***************** From the file "set.c" ************************************/
3321/*
3322** Set manipulation routines for the LEMON parser generator.
3323*/
3324
3325static int size = 0;
3326
3327/* Set the set size */
3328void SetSize(n)
3329int n;
3330{
3331 size = n+1;
3332}
3333
3334/* Allocate a new set */
3335char *SetNew(){
3336 char *s;
3337 int i;
3338 s = (char*)malloc( size );
3339 if( s==0 ){
3340 extern void memory_error();
3341 memory_error();
3342 }
3343 for(i=0; i<size; i++) s[i] = 0;
3344 return s;
3345}
3346
3347/* Deallocate a set */
3348void SetFree(s)
3349char *s;
3350{
3351 free(s);
3352}
3353
3354/* Add a new element to the set. Return TRUE if the element was added
3355** and FALSE if it was already there. */
3356int SetAdd(s,e)
3357char *s;
3358int e;
3359{
3360 int rv;
3361 rv = s[e];
3362 s[e] = 1;
3363 return !rv;
3364}
3365
3366/* Add every element of s2 to s1. Return TRUE if s1 changes. */
3367int SetUnion(s1,s2)
3368char *s1;
3369char *s2;
3370{
3371 int i, progress;
3372 progress = 0;
3373 for(i=0; i<size; i++){
3374 if( s2[i]==0 ) continue;
3375 if( s1[i]==0 ){
3376 progress = 1;
3377 s1[i] = 1;
3378 }
3379 }
3380 return progress;
3381}
3382/********************** From the file "table.c" ****************************/
3383/*
3384** All code in this file has been automatically generated
3385** from a specification in the file
3386** "table.q"
3387** by the associative array code building program "aagen".
3388** Do not edit this file! Instead, edit the specification
3389** file, then rerun aagen.
3390*/
3391/*
3392** Code for processing tables in the LEMON parser generator.
3393*/
3394
3395PRIVATE int strhash(x)
3396char *x;
3397{
3398 int h = 0;
3399 while( *x) h = h*13 + *(x++);
3400 return h;
3401}
3402
3403/* Works like strdup, sort of. Save a string in malloced memory, but
3404** keep strings in a table so that the same string is not in more
3405** than one place.
3406*/
3407char *Strsafe(y)
3408char *y;
3409{
3410 char *z;
3411
3412 z = Strsafe_find(y);
3413 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
3414 strcpy(z,y);
3415 Strsafe_insert(z);
3416 }
3417 MemoryCheck(z);
3418 return z;
3419}
3420
3421/* There is one instance of the following structure for each
3422** associative array of type "x1".
3423*/
3424struct s_x1 {
3425 int size; /* The number of available slots. */
3426 /* Must be a power of 2 greater than or */
3427 /* equal to 1 */
3428 int count; /* Number of currently slots filled */
3429 struct s_x1node *tbl; /* The data stored here */
3430 struct s_x1node **ht; /* Hash table for lookups */
3431};
3432
3433/* There is one instance of this structure for every data element
3434** in an associative array of type "x1".
3435*/
3436typedef struct s_x1node {
3437 char *data; /* The data */
3438 struct s_x1node *next; /* Next entry with the same hash */
3439 struct s_x1node **from; /* Previous link */
3440} x1node;
3441
3442/* There is only one instance of the array, which is the following */
3443static struct s_x1 *x1a;
3444
3445/* Allocate a new associative array */
3446void Strsafe_init(){
3447 if( x1a ) return;
3448 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
3449 if( x1a ){
3450 x1a->size = 1024;
3451 x1a->count = 0;
3452 x1a->tbl = (x1node*)malloc(
3453 (sizeof(x1node) + sizeof(x1node*))*1024 );
3454 if( x1a->tbl==0 ){
3455 free(x1a);
3456 x1a = 0;
3457 }else{
3458 int i;
3459 x1a->ht = (x1node**)&(x1a->tbl[1024]);
3460 for(i=0; i<1024; i++) x1a->ht[i] = 0;
3461 }
3462 }
3463}
3464/* Insert a new record into the array. Return TRUE if successful.
3465** Prior data with the same key is NOT overwritten */
3466int Strsafe_insert(data)
3467char *data;
3468{
3469 x1node *np;
3470 int h;
3471 int ph;
3472
3473 if( x1a==0 ) return 0;
3474 ph = strhash(data);
3475 h = ph & (x1a->size-1);
3476 np = x1a->ht[h];
3477 while( np ){
3478 if( strcmp(np->data,data)==0 ){
3479 /* An existing entry with the same key is found. */
3480 /* Fail because overwrite is not allows. */
3481 return 0;
3482 }
3483 np = np->next;
3484 }
3485 if( x1a->count>=x1a->size ){
3486 /* Need to make the hash table bigger */
3487 int i,size;
3488 struct s_x1 array;
3489 array.size = size = x1a->size*2;
3490 array.count = x1a->count;
3491 array.tbl = (x1node*)malloc(
3492 (sizeof(x1node) + sizeof(x1node*))*size );
3493 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3494 array.ht = (x1node**)&(array.tbl[size]);
3495 for(i=0; i<size; i++) array.ht[i] = 0;
3496 for(i=0; i<x1a->count; i++){
3497 x1node *oldnp, *newnp;
3498 oldnp = &(x1a->tbl[i]);
3499 h = strhash(oldnp->data) & (size-1);
3500 newnp = &(array.tbl[i]);
3501 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3502 newnp->next = array.ht[h];
3503 newnp->data = oldnp->data;
3504 newnp->from = &(array.ht[h]);
3505 array.ht[h] = newnp;
3506 }
3507 free(x1a->tbl);
3508 *x1a = array;
3509 }
3510 /* Insert the new data */
3511 h = ph & (x1a->size-1);
3512 np = &(x1a->tbl[x1a->count++]);
3513 np->data = data;
3514 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
3515 np->next = x1a->ht[h];
3516 x1a->ht[h] = np;
3517 np->from = &(x1a->ht[h]);
3518 return 1;
3519}
3520
3521/* Return a pointer to data assigned to the given key. Return NULL
3522** if no such key. */
3523char *Strsafe_find(key)
3524char *key;
3525{
3526 int h;
3527 x1node *np;
3528
3529 if( x1a==0 ) return 0;
3530 h = strhash(key) & (x1a->size-1);
3531 np = x1a->ht[h];
3532 while( np ){
3533 if( strcmp(np->data,key)==0 ) break;
3534 np = np->next;
3535 }
3536 return np ? np->data : 0;
3537}
3538
3539/* Return a pointer to the (terminal or nonterminal) symbol "x".
3540** Create a new symbol if this is the first time "x" has been seen.
3541*/
3542struct symbol *Symbol_new(x)
3543char *x;
3544{
3545 struct symbol *sp;
3546
3547 sp = Symbol_find(x);
3548 if( sp==0 ){
3549 sp = (struct symbol *)malloc( sizeof(struct symbol) );
3550 MemoryCheck(sp);
3551 sp->name = Strsafe(x);
3552 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
3553 sp->rule = 0;
3554 sp->prec = -1;
3555 sp->assoc = UNK;
3556 sp->firstset = 0;
3557 sp->lambda = FALSE;
3558 sp->destructor = 0;
3559 sp->datatype = 0;
3560 Symbol_insert(sp,sp->name);
3561 }
3562 return sp;
3563}
3564
3565/* Compare two symbols */
3566int Symbolcmpp(a,b)
3567struct symbol **a;
3568struct symbol **b;
3569{
3570 return strcmp((**a).name,(**b).name);
3571}
3572
3573/* There is one instance of the following structure for each
3574** associative array of type "x2".
3575*/
3576struct s_x2 {
3577 int size; /* The number of available slots. */
3578 /* Must be a power of 2 greater than or */
3579 /* equal to 1 */
3580 int count; /* Number of currently slots filled */
3581 struct s_x2node *tbl; /* The data stored here */
3582 struct s_x2node **ht; /* Hash table for lookups */
3583};
3584
3585/* There is one instance of this structure for every data element
3586** in an associative array of type "x2".
3587*/
3588typedef struct s_x2node {
3589 struct symbol *data; /* The data */
3590 char *key; /* The key */
3591 struct s_x2node *next; /* Next entry with the same hash */
3592 struct s_x2node **from; /* Previous link */
3593} x2node;
3594
3595/* There is only one instance of the array, which is the following */
3596static struct s_x2 *x2a;
3597
3598/* Allocate a new associative array */
3599void Symbol_init(){
3600 if( x2a ) return;
3601 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
3602 if( x2a ){
3603 x2a->size = 128;
3604 x2a->count = 0;
3605 x2a->tbl = (x2node*)malloc(
3606 (sizeof(x2node) + sizeof(x2node*))*128 );
3607 if( x2a->tbl==0 ){
3608 free(x2a);
3609 x2a = 0;
3610 }else{
3611 int i;
3612 x2a->ht = (x2node**)&(x2a->tbl[128]);
3613 for(i=0; i<128; i++) x2a->ht[i] = 0;
3614 }
3615 }
3616}
3617/* Insert a new record into the array. Return TRUE if successful.
3618** Prior data with the same key is NOT overwritten */
3619int Symbol_insert(data,key)
3620struct symbol *data;
3621char *key;
3622{
3623 x2node *np;
3624 int h;
3625 int ph;
3626
3627 if( x2a==0 ) return 0;
3628 ph = strhash(key);
3629 h = ph & (x2a->size-1);
3630 np = x2a->ht[h];
3631 while( np ){
3632 if( strcmp(np->key,key)==0 ){
3633 /* An existing entry with the same key is found. */
3634 /* Fail because overwrite is not allows. */
3635 return 0;
3636 }
3637 np = np->next;
3638 }
3639 if( x2a->count>=x2a->size ){
3640 /* Need to make the hash table bigger */
3641 int i,size;
3642 struct s_x2 array;
3643 array.size = size = x2a->size*2;
3644 array.count = x2a->count;
3645 array.tbl = (x2node*)malloc(
3646 (sizeof(x2node) + sizeof(x2node*))*size );
3647 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3648 array.ht = (x2node**)&(array.tbl[size]);
3649 for(i=0; i<size; i++) array.ht[i] = 0;
3650 for(i=0; i<x2a->count; i++){
3651 x2node *oldnp, *newnp;
3652 oldnp = &(x2a->tbl[i]);
3653 h = strhash(oldnp->key) & (size-1);
3654 newnp = &(array.tbl[i]);
3655 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3656 newnp->next = array.ht[h];
3657 newnp->key = oldnp->key;
3658 newnp->data = oldnp->data;
3659 newnp->from = &(array.ht[h]);
3660 array.ht[h] = newnp;
3661 }
3662 free(x2a->tbl);
3663 *x2a = array;
3664 }
3665 /* Insert the new data */
3666 h = ph & (x2a->size-1);
3667 np = &(x2a->tbl[x2a->count++]);
3668 np->key = key;
3669 np->data = data;
3670 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
3671 np->next = x2a->ht[h];
3672 x2a->ht[h] = np;
3673 np->from = &(x2a->ht[h]);
3674 return 1;
3675}
3676
3677/* Return a pointer to data assigned to the given key. Return NULL
3678** if no such key. */
3679struct symbol *Symbol_find(key)
3680char *key;
3681{
3682 int h;
3683 x2node *np;
3684
3685 if( x2a==0 ) return 0;
3686 h = strhash(key) & (x2a->size-1);
3687 np = x2a->ht[h];
3688 while( np ){
3689 if( strcmp(np->key,key)==0 ) break;
3690 np = np->next;
3691 }
3692 return np ? np->data : 0;
3693}
3694
3695/* Return the n-th data. Return NULL if n is out of range. */
3696struct symbol *Symbol_Nth(n)
3697int n;
3698{
3699 struct symbol *data;
3700 if( x2a && n>0 && n<=x2a->count ){
3701 data = x2a->tbl[n-1].data;
3702 }else{
3703 data = 0;
3704 }
3705 return data;
3706}
3707
3708/* Return the size of the array */
3709int Symbol_count()
3710{
3711 return x2a ? x2a->count : 0;
3712}
3713
3714/* Return an array of pointers to all data in the table.
3715** The array is obtained from malloc. Return NULL if memory allocation
3716** problems, or if the array is empty. */
3717struct symbol **Symbol_arrayof()
3718{
3719 struct symbol **array;
3720 int i,size;
3721 if( x2a==0 ) return 0;
3722 size = x2a->count;
3723 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
3724 if( array ){
3725 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
3726 }
3727 return array;
3728}
3729
3730/* Compare two configurations */
3731int Configcmp(a,b)
3732struct config *a;
3733struct config *b;
3734{
3735 int x;
3736 x = a->rp->index - b->rp->index;
3737 if( x==0 ) x = a->dot - b->dot;
3738 return x;
3739}
3740
3741/* Compare two states */
3742PRIVATE int statecmp(a,b)
3743struct config *a;
3744struct config *b;
3745{
3746 int rc;
3747 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
3748 rc = a->rp->index - b->rp->index;
3749 if( rc==0 ) rc = a->dot - b->dot;
3750 }
3751 if( rc==0 ){
3752 if( a ) rc = 1;
3753 if( b ) rc = -1;
3754 }
3755 return rc;
3756}
3757
3758/* Hash a state */
3759PRIVATE int statehash(a)
3760struct config *a;
3761{
3762 int h=0;
3763 while( a ){
3764 h = h*571 + a->rp->index*37 + a->dot;
3765 a = a->bp;
3766 }
3767 return h;
3768}
3769
3770/* Allocate a new state structure */
3771struct state *State_new()
3772{
3773 struct state *new;
3774 new = (struct state *)malloc( sizeof(struct state) );
3775 MemoryCheck(new);
3776 return new;
3777}
3778
3779/* There is one instance of the following structure for each
3780** associative array of type "x3".
3781*/
3782struct s_x3 {
3783 int size; /* The number of available slots. */
3784 /* Must be a power of 2 greater than or */
3785 /* equal to 1 */
3786 int count; /* Number of currently slots filled */
3787 struct s_x3node *tbl; /* The data stored here */
3788 struct s_x3node **ht; /* Hash table for lookups */
3789};
3790
3791/* There is one instance of this structure for every data element
3792** in an associative array of type "x3".
3793*/
3794typedef struct s_x3node {
3795 struct state *data; /* The data */
3796 struct config *key; /* The key */
3797 struct s_x3node *next; /* Next entry with the same hash */
3798 struct s_x3node **from; /* Previous link */
3799} x3node;
3800
3801/* There is only one instance of the array, which is the following */
3802static struct s_x3 *x3a;
3803
3804/* Allocate a new associative array */
3805void State_init(){
3806 if( x3a ) return;
3807 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
3808 if( x3a ){
3809 x3a->size = 128;
3810 x3a->count = 0;
3811 x3a->tbl = (x3node*)malloc(
3812 (sizeof(x3node) + sizeof(x3node*))*128 );
3813 if( x3a->tbl==0 ){
3814 free(x3a);
3815 x3a = 0;
3816 }else{
3817 int i;
3818 x3a->ht = (x3node**)&(x3a->tbl[128]);
3819 for(i=0; i<128; i++) x3a->ht[i] = 0;
3820 }
3821 }
3822}
3823/* Insert a new record into the array. Return TRUE if successful.
3824** Prior data with the same key is NOT overwritten */
3825int State_insert(data,key)
3826struct state *data;
3827struct config *key;
3828{
3829 x3node *np;
3830 int h;
3831 int ph;
3832
3833 if( x3a==0 ) return 0;
3834 ph = statehash(key);
3835 h = ph & (x3a->size-1);
3836 np = x3a->ht[h];
3837 while( np ){
3838 if( statecmp(np->key,key)==0 ){
3839 /* An existing entry with the same key is found. */
3840 /* Fail because overwrite is not allows. */
3841 return 0;
3842 }
3843 np = np->next;
3844 }
3845 if( x3a->count>=x3a->size ){
3846 /* Need to make the hash table bigger */
3847 int i,size;
3848 struct s_x3 array;
3849 array.size = size = x3a->size*2;
3850 array.count = x3a->count;
3851 array.tbl = (x3node*)malloc(
3852 (sizeof(x3node) + sizeof(x3node*))*size );
3853 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3854 array.ht = (x3node**)&(array.tbl[size]);
3855 for(i=0; i<size; i++) array.ht[i] = 0;
3856 for(i=0; i<x3a->count; i++){
3857 x3node *oldnp, *newnp;
3858 oldnp = &(x3a->tbl[i]);
3859 h = statehash(oldnp->key) & (size-1);
3860 newnp = &(array.tbl[i]);
3861 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3862 newnp->next = array.ht[h];
3863 newnp->key = oldnp->key;
3864 newnp->data = oldnp->data;
3865 newnp->from = &(array.ht[h]);
3866 array.ht[h] = newnp;
3867 }
3868 free(x3a->tbl);
3869 *x3a = array;
3870 }
3871 /* Insert the new data */
3872 h = ph & (x3a->size-1);
3873 np = &(x3a->tbl[x3a->count++]);
3874 np->key = key;
3875 np->data = data;
3876 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
3877 np->next = x3a->ht[h];
3878 x3a->ht[h] = np;
3879 np->from = &(x3a->ht[h]);
3880 return 1;
3881}
3882
3883/* Return a pointer to data assigned to the given key. Return NULL
3884** if no such key. */
3885struct state *State_find(key)
3886struct config *key;
3887{
3888 int h;
3889 x3node *np;
3890
3891 if( x3a==0 ) return 0;
3892 h = statehash(key) & (x3a->size-1);
3893 np = x3a->ht[h];
3894 while( np ){
3895 if( statecmp(np->key,key)==0 ) break;
3896 np = np->next;
3897 }
3898 return np ? np->data : 0;
3899}
3900
3901/* Return an array of pointers to all data in the table.
3902** The array is obtained from malloc. Return NULL if memory allocation
3903** problems, or if the array is empty. */
3904struct state **State_arrayof()
3905{
3906 struct state **array;
3907 int i,size;
3908 if( x3a==0 ) return 0;
3909 size = x3a->count;
3910 array = (struct state **)malloc( sizeof(struct state *)*size );
3911 if( array ){
3912 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
3913 }
3914 return array;
3915}
3916
3917/* Hash a configuration */
3918PRIVATE int confighash(a)
3919struct config *a;
3920{
3921 int h=0;
3922 h = h*571 + a->rp->index*37 + a->dot;
3923 return h;
3924}
3925
3926/* There is one instance of the following structure for each
3927** associative array of type "x4".
3928*/
3929struct s_x4 {
3930 int size; /* The number of available slots. */
3931 /* Must be a power of 2 greater than or */
3932 /* equal to 1 */
3933 int count; /* Number of currently slots filled */
3934 struct s_x4node *tbl; /* The data stored here */
3935 struct s_x4node **ht; /* Hash table for lookups */
3936};
3937
3938/* There is one instance of this structure for every data element
3939** in an associative array of type "x4".
3940*/
3941typedef struct s_x4node {
3942 struct config *data; /* The data */
3943 struct s_x4node *next; /* Next entry with the same hash */
3944 struct s_x4node **from; /* Previous link */
3945} x4node;
3946
3947/* There is only one instance of the array, which is the following */
3948static struct s_x4 *x4a;
3949
3950/* Allocate a new associative array */
3951void Configtable_init(){
3952 if( x4a ) return;
3953 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
3954 if( x4a ){
3955 x4a->size = 64;
3956 x4a->count = 0;
3957 x4a->tbl = (x4node*)malloc(
3958 (sizeof(x4node) + sizeof(x4node*))*64 );
3959 if( x4a->tbl==0 ){
3960 free(x4a);
3961 x4a = 0;
3962 }else{
3963 int i;
3964 x4a->ht = (x4node**)&(x4a->tbl[64]);
3965 for(i=0; i<64; i++) x4a->ht[i] = 0;
3966 }
3967 }
3968}
3969/* Insert a new record into the array. Return TRUE if successful.
3970** Prior data with the same key is NOT overwritten */
3971int Configtable_insert(data)
3972struct config *data;
3973{
3974 x4node *np;
3975 int h;
3976 int ph;
3977
3978 if( x4a==0 ) return 0;
3979 ph = confighash(data);
3980 h = ph & (x4a->size-1);
3981 np = x4a->ht[h];
3982 while( np ){
3983 if( Configcmp(np->data,data)==0 ){
3984 /* An existing entry with the same key is found. */
3985 /* Fail because overwrite is not allows. */
3986 return 0;
3987 }
3988 np = np->next;
3989 }
3990 if( x4a->count>=x4a->size ){
3991 /* Need to make the hash table bigger */
3992 int i,size;
3993 struct s_x4 array;
3994 array.size = size = x4a->size*2;
3995 array.count = x4a->count;
3996 array.tbl = (x4node*)malloc(
3997 (sizeof(x4node) + sizeof(x4node*))*size );
3998 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3999 array.ht = (x4node**)&(array.tbl[size]);
4000 for(i=0; i<size; i++) array.ht[i] = 0;
4001 for(i=0; i<x4a->count; i++){
4002 x4node *oldnp, *newnp;
4003 oldnp = &(x4a->tbl[i]);
4004 h = confighash(oldnp->data) & (size-1);
4005 newnp = &(array.tbl[i]);
4006 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4007 newnp->next = array.ht[h];
4008 newnp->data = oldnp->data;
4009 newnp->from = &(array.ht[h]);
4010 array.ht[h] = newnp;
4011 }
4012 free(x4a->tbl);
4013 *x4a = array;
4014 }
4015 /* Insert the new data */
4016 h = ph & (x4a->size-1);
4017 np = &(x4a->tbl[x4a->count++]);
4018 np->data = data;
4019 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4020 np->next = x4a->ht[h];
4021 x4a->ht[h] = np;
4022 np->from = &(x4a->ht[h]);
4023 return 1;
4024}
4025
4026/* Return a pointer to data assigned to the given key. Return NULL
4027** if no such key. */
4028struct config *Configtable_find(key)
4029struct config *key;
4030{
4031 int h;
4032 x4node *np;
4033
4034 if( x4a==0 ) return 0;
4035 h = confighash(key) & (x4a->size-1);
4036 np = x4a->ht[h];
4037 while( np ){
4038 if( Configcmp(np->data,key)==0 ) break;
4039 np = np->next;
4040 }
4041 return np ? np->data : 0;
4042}
4043
4044/* Remove all data from the table. Pass each data to the function "f"
4045** as it is removed. ("f" may be null to avoid this step.) */
4046void Configtable_clear(f)
4047int(*f)(/* struct config * */);
4048{
4049 int i;
4050 if( x4a==0 || x4a->count==0 ) return;
4051 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4052 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4053 x4a->count = 0;
4054 return;
4055}