blob: c3b15b7e63b396f4955e441d2dc848fce20a0268 [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);
773 for(ap=stp->ap; ap && ap->next; ap=nap){
774 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{
851 /* Can't happen. Shifts have to come before Reduces on the
852 ** list because the reduces were added last. Hence, if apx->type==REDUCE
853 ** then it is impossible for apy->type==SHIFT */
854 }
855 return errcnt;
856}
857/********************* From the file "configlist.c" *************************/
858/*
859** Routines to processing a configuration list and building a state
860** in the LEMON parser generator.
861*/
862
863static struct config *freelist = 0; /* List of free configurations */
864static struct config *current = 0; /* Top of list of configurations */
865static struct config **currentend = 0; /* Last on list of configs */
866static struct config *basis = 0; /* Top of list of basis configs */
867static struct config **basisend = 0; /* End of list of basis configs */
868
869/* Return a pointer to a new configuration */
870PRIVATE struct config *newconfig(){
871 struct config *new;
872 if( freelist==0 ){
873 int i;
874 int amt = 3;
875 freelist = (struct config *)malloc( sizeof(struct config)*amt );
876 if( freelist==0 ){
877 fprintf(stderr,"Unable to allocate memory for a new configuration.");
878 exit(1);
879 }
880 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
881 freelist[amt-1].next = 0;
882 }
883 new = freelist;
884 freelist = freelist->next;
885 return new;
886}
887
888/* The configuration "old" is no longer used */
889PRIVATE void deleteconfig(old)
890struct config *old;
891{
892 old->next = freelist;
893 freelist = old;
894}
895
896/* Initialized the configuration list builder */
897void Configlist_init(){
898 current = 0;
899 currentend = &current;
900 basis = 0;
901 basisend = &basis;
902 Configtable_init();
903 return;
904}
905
906/* Initialized the configuration list builder */
907void Configlist_reset(){
908 current = 0;
909 currentend = &current;
910 basis = 0;
911 basisend = &basis;
912 Configtable_clear(0);
913 return;
914}
915
916/* Add another configuration to the configuration list */
917struct config *Configlist_add(rp,dot)
918struct rule *rp; /* The rule */
919int dot; /* Index into the RHS of the rule where the dot goes */
920{
921 struct config *cfp, model;
922
923 assert( currentend!=0 );
924 model.rp = rp;
925 model.dot = dot;
926 cfp = Configtable_find(&model);
927 if( cfp==0 ){
928 cfp = newconfig();
929 cfp->rp = rp;
930 cfp->dot = dot;
931 cfp->fws = SetNew();
932 cfp->stp = 0;
933 cfp->fplp = cfp->bplp = 0;
934 cfp->next = 0;
935 cfp->bp = 0;
936 *currentend = cfp;
937 currentend = &cfp->next;
938 Configtable_insert(cfp);
939 }
940 return cfp;
941}
942
943/* Add a basis configuration to the configuration list */
944struct config *Configlist_addbasis(rp,dot)
945struct rule *rp;
946int dot;
947{
948 struct config *cfp, model;
949
950 assert( basisend!=0 );
951 assert( currentend!=0 );
952 model.rp = rp;
953 model.dot = dot;
954 cfp = Configtable_find(&model);
955 if( cfp==0 ){
956 cfp = newconfig();
957 cfp->rp = rp;
958 cfp->dot = dot;
959 cfp->fws = SetNew();
960 cfp->stp = 0;
961 cfp->fplp = cfp->bplp = 0;
962 cfp->next = 0;
963 cfp->bp = 0;
964 *currentend = cfp;
965 currentend = &cfp->next;
966 *basisend = cfp;
967 basisend = &cfp->bp;
968 Configtable_insert(cfp);
969 }
970 return cfp;
971}
972
973/* Compute the closure of the configuration list */
974void Configlist_closure(lemp)
975struct lemon *lemp;
976{
977 struct config *cfp, *newcfp;
978 struct rule *rp, *newrp;
979 struct symbol *sp, *xsp;
980 int i, dot;
981
982 assert( currentend!=0 );
983 for(cfp=current; cfp; cfp=cfp->next){
984 rp = cfp->rp;
985 dot = cfp->dot;
986 if( dot>=rp->nrhs ) continue;
987 sp = rp->rhs[dot];
988 if( sp->type==NONTERMINAL ){
989 if( sp->rule==0 && sp!=lemp->errsym ){
990 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
991 sp->name);
992 lemp->errorcnt++;
993 }
994 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
995 newcfp = Configlist_add(newrp,0);
996 for(i=dot+1; i<rp->nrhs; i++){
997 xsp = rp->rhs[i];
998 if( xsp->type==TERMINAL ){
999 SetAdd(newcfp->fws,xsp->index);
1000 break;
1001 }else{
1002 SetUnion(newcfp->fws,xsp->firstset);
1003 if( xsp->lambda==FALSE ) break;
1004 }
1005 }
1006 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1007 }
1008 }
1009 }
1010 return;
1011}
1012
1013/* Sort the configuration list */
1014void Configlist_sort(){
1015 current = (struct config *)msort(current,&(current->next),Configcmp);
1016 currentend = 0;
1017 return;
1018}
1019
1020/* Sort the basis configuration list */
1021void Configlist_sortbasis(){
1022 basis = (struct config *)msort(current,&(current->bp),Configcmp);
1023 basisend = 0;
1024 return;
1025}
1026
1027/* Return a pointer to the head of the configuration list and
1028** reset the list */
1029struct config *Configlist_return(){
1030 struct config *old;
1031 old = current;
1032 current = 0;
1033 currentend = 0;
1034 return old;
1035}
1036
1037/* Return a pointer to the head of the configuration list and
1038** reset the list */
1039struct config *Configlist_basis(){
1040 struct config *old;
1041 old = basis;
1042 basis = 0;
1043 basisend = 0;
1044 return old;
1045}
1046
1047/* Free all elements of the given configuration list */
1048void Configlist_eat(cfp)
1049struct config *cfp;
1050{
1051 struct config *nextcfp;
1052 for(; cfp; cfp=nextcfp){
1053 nextcfp = cfp->next;
1054 assert( cfp->fplp==0 );
1055 assert( cfp->bplp==0 );
1056 if( cfp->fws ) SetFree(cfp->fws);
1057 deleteconfig(cfp);
1058 }
1059 return;
1060}
1061/***************** From the file "error.c" *********************************/
1062/*
1063** Code for printing error message.
1064*/
1065
1066/* Find a good place to break "msg" so that its length is at least "min"
1067** but no more than "max". Make the point as close to max as possible.
1068*/
1069static int findbreak(msg,min,max)
1070char *msg;
1071int min;
1072int max;
1073{
1074 int i,spot;
1075 char c;
1076 for(i=spot=min; i<=max; i++){
1077 c = msg[i];
1078 if( c=='\t' ) msg[i] = ' ';
1079 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1080 if( c==0 ){ spot = i; break; }
1081 if( c=='-' && i<max-1 ) spot = i+1;
1082 if( c==' ' ) spot = i;
1083 }
1084 return spot;
1085}
1086
1087/*
1088** The error message is split across multiple lines if necessary. The
1089** splits occur at a space, if there is a space available near the end
1090** of the line.
1091*/
1092#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1093#define LINEWIDTH 79 /* Max width of any output line */
1094#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
1095void ErrorMsg(va_alist)
1096va_dcl
1097{
1098 char *filename;
1099 int lineno;
1100 char *format;
1101 char errmsg[ERRMSGSIZE];
1102 char prefix[PREFIXLIMIT+10];
1103 int errmsgsize;
1104 int prefixsize;
1105 int availablewidth;
1106 va_list ap;
1107 int end, restart, base;
1108
1109 va_start(ap);
1110 filename = va_arg(ap,char*);
1111 lineno = va_arg(ap,int);
1112 format = va_arg(ap,char*);
1113 /* Prepare a prefix to be prepended to every output line */
1114 if( lineno>0 ){
1115 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1116 }else{
1117 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1118 }
1119 prefixsize = strlen(prefix);
1120 availablewidth = LINEWIDTH - prefixsize;
1121
1122 /* Generate the error message */
1123 vsprintf(errmsg,format,ap);
1124 va_end(ap);
1125 errmsgsize = strlen(errmsg);
1126 /* Remove trailing '\n's from the error message. */
1127 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1128 errmsg[--errmsgsize] = 0;
1129 }
1130
1131 /* Print the error message */
1132 base = 0;
1133 while( errmsg[base]!=0 ){
1134 end = restart = findbreak(&errmsg[base],0,availablewidth);
1135 restart += base;
1136 while( errmsg[restart]==' ' ) restart++;
1137 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1138 base = restart;
1139 }
1140}
1141/**************** From the file "main.c" ************************************/
1142/*
1143** Main program file for the LEMON parser generator.
1144*/
1145
1146/* Report an out-of-memory condition and abort. This function
1147** is used mostly by the "MemoryCheck" macro in struct.h
1148*/
1149void memory_error(){
1150 fprintf(stderr,"Out of memory. Aborting...\n");
1151 exit(1);
1152}
1153
1154
1155/* The main program. Parse the command line and do it... */
1156int main(argc,argv)
1157int argc;
1158char **argv;
1159{
1160 static int version = 0;
1161 static int rpflag = 0;
1162 static int basisflag = 0;
1163 static int compress = 0;
1164 static int quiet = 0;
1165 static int statistics = 0;
1166 static int mhflag = 0;
1167 static struct s_options options[] = {
1168 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1169 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
1170 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1171 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1172 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
1173 {OPT_FLAG, "s", (char*)&statistics, "Print parser stats to standard output."},
1174 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1175 {OPT_FLAG,0,0,0}
1176 };
1177 int i;
1178 struct lemon lem;
1179
drhb0c86772000-06-02 23:21:26 +00001180 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001181 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001182 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001183 exit(0);
1184 }
drhb0c86772000-06-02 23:21:26 +00001185 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001186 fprintf(stderr,"Exactly one filename argument is required.\n");
1187 exit(1);
1188 }
1189 lem.errorcnt = 0;
1190
1191 /* Initialize the machine */
1192 Strsafe_init();
1193 Symbol_init();
1194 State_init();
1195 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001196 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001197 lem.basisflag = basisflag;
1198 lem.nconflict = 0;
1199 lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
drh960e8c62001-04-03 16:53:21 +00001200 lem.vartype = 0;
drh75897232000-05-29 14:26:00 +00001201 lem.stacksize = 0;
1202 lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
1203 lem.tokenprefix = lem.outname = lem.extracode = 0;
drh960e8c62001-04-03 16:53:21 +00001204 lem.vardest = 0;
drh75897232000-05-29 14:26:00 +00001205 lem.tablesize = 0;
1206 Symbol_new("$");
1207 lem.errsym = Symbol_new("error");
1208
1209 /* Parse the input file */
1210 Parse(&lem);
1211 if( lem.errorcnt ) exit(lem.errorcnt);
1212 if( lem.rule==0 ){
1213 fprintf(stderr,"Empty grammar.\n");
1214 exit(1);
1215 }
1216
1217 /* Count and index the symbols of the grammar */
1218 lem.nsymbol = Symbol_count();
1219 Symbol_new("{default}");
1220 lem.symbols = Symbol_arrayof();
1221 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1222 (int(*)())Symbolcmpp);
1223 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1224 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1225 lem.nterminal = i;
1226
1227 /* Generate a reprint of the grammar, if requested on the command line */
1228 if( rpflag ){
1229 Reprint(&lem);
1230 }else{
1231 /* Initialize the size for all follow and first sets */
1232 SetSize(lem.nterminal);
1233
1234 /* Find the precedence for every production rule (that has one) */
1235 FindRulePrecedences(&lem);
1236
1237 /* Compute the lambda-nonterminals and the first-sets for every
1238 ** nonterminal */
1239 FindFirstSets(&lem);
1240
1241 /* Compute all LR(0) states. Also record follow-set propagation
1242 ** links so that the follow-set can be computed later */
1243 lem.nstate = 0;
1244 FindStates(&lem);
1245 lem.sorted = State_arrayof();
1246
1247 /* Tie up loose ends on the propagation links */
1248 FindLinks(&lem);
1249
1250 /* Compute the follow set of every reducible configuration */
1251 FindFollowSets(&lem);
1252
1253 /* Compute the action tables */
1254 FindActions(&lem);
1255
1256 /* Compress the action tables */
1257 if( compress==0 ) CompressTables(&lem);
1258
1259 /* Generate a report of the parser generated. (the "y.output" file) */
1260 if( !quiet ) ReportOutput(&lem);
1261
1262 /* Generate the source code for the parser */
1263 ReportTable(&lem, mhflag);
1264
1265 /* Produce a header file for use by the scanner. (This step is
1266 ** omitted if the "-m" option is used because makeheaders will
1267 ** generate the file for us.) */
1268 if( !mhflag ) ReportHeader(&lem);
1269 }
1270 if( statistics ){
1271 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1272 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1273 printf(" %d states, %d parser table entries, %d conflicts\n",
1274 lem.nstate, lem.tablesize, lem.nconflict);
1275 }
1276 if( lem.nconflict ){
1277 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1278 }
1279 exit(lem.errorcnt + lem.nconflict);
1280}
1281/******************** From the file "msort.c" *******************************/
1282/*
1283** A generic merge-sort program.
1284**
1285** USAGE:
1286** Let "ptr" be a pointer to some structure which is at the head of
1287** a null-terminated list. Then to sort the list call:
1288**
1289** ptr = msort(ptr,&(ptr->next),cmpfnc);
1290**
1291** In the above, "cmpfnc" is a pointer to a function which compares
1292** two instances of the structure and returns an integer, as in
1293** strcmp. The second argument is a pointer to the pointer to the
1294** second element of the linked list. This address is used to compute
1295** the offset to the "next" field within the structure. The offset to
1296** the "next" field must be constant for all structures in the list.
1297**
1298** The function returns a new pointer which is the head of the list
1299** after sorting.
1300**
1301** ALGORITHM:
1302** Merge-sort.
1303*/
1304
1305/*
1306** Return a pointer to the next structure in the linked list.
1307*/
1308#define NEXT(A) (*(char**)(((int)A)+offset))
1309
1310/*
1311** Inputs:
1312** a: A sorted, null-terminated linked list. (May be null).
1313** b: A sorted, null-terminated linked list. (May be null).
1314** cmp: A pointer to the comparison function.
1315** offset: Offset in the structure to the "next" field.
1316**
1317** Return Value:
1318** A pointer to the head of a sorted list containing the elements
1319** of both a and b.
1320**
1321** Side effects:
1322** The "next" pointers for elements in the lists a and b are
1323** changed.
1324*/
1325static char *merge(a,b,cmp,offset)
1326char *a;
1327char *b;
1328int (*cmp)();
1329int offset;
1330{
1331 char *ptr, *head;
1332
1333 if( a==0 ){
1334 head = b;
1335 }else if( b==0 ){
1336 head = a;
1337 }else{
1338 if( (*cmp)(a,b)<0 ){
1339 ptr = a;
1340 a = NEXT(a);
1341 }else{
1342 ptr = b;
1343 b = NEXT(b);
1344 }
1345 head = ptr;
1346 while( a && b ){
1347 if( (*cmp)(a,b)<0 ){
1348 NEXT(ptr) = a;
1349 ptr = a;
1350 a = NEXT(a);
1351 }else{
1352 NEXT(ptr) = b;
1353 ptr = b;
1354 b = NEXT(b);
1355 }
1356 }
1357 if( a ) NEXT(ptr) = a;
1358 else NEXT(ptr) = b;
1359 }
1360 return head;
1361}
1362
1363/*
1364** Inputs:
1365** list: Pointer to a singly-linked list of structures.
1366** next: Pointer to pointer to the second element of the list.
1367** cmp: A comparison function.
1368**
1369** Return Value:
1370** A pointer to the head of a sorted list containing the elements
1371** orginally in list.
1372**
1373** Side effects:
1374** The "next" pointers for elements in list are changed.
1375*/
1376#define LISTSIZE 30
1377char *msort(list,next,cmp)
1378char *list;
1379char **next;
1380int (*cmp)();
1381{
1382 int offset;
1383 char *ep;
1384 char *set[LISTSIZE];
1385 int i;
1386 offset = (int)next - (int)list;
1387 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1388 while( list ){
1389 ep = list;
1390 list = NEXT(list);
1391 NEXT(ep) = 0;
1392 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1393 ep = merge(ep,set[i],cmp,offset);
1394 set[i] = 0;
1395 }
1396 set[i] = ep;
1397 }
1398 ep = 0;
1399 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1400 return ep;
1401}
1402/************************ From the file "option.c" **************************/
1403static char **argv;
1404static struct s_options *op;
1405static FILE *errstream;
1406
1407#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1408
1409/*
1410** Print the command line with a carrot pointing to the k-th character
1411** of the n-th field.
1412*/
1413static void errline(n,k,err)
1414int n;
1415int k;
1416FILE *err;
1417{
1418 int spcnt, i;
1419 spcnt = 0;
1420 if( argv[0] ) fprintf(err,"%s",argv[0]);
1421 spcnt = strlen(argv[0]) + 1;
1422 for(i=1; i<n && argv[i]; i++){
1423 fprintf(err," %s",argv[i]);
1424 spcnt += strlen(argv[i]+1);
1425 }
1426 spcnt += k;
1427 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1428 if( spcnt<20 ){
1429 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1430 }else{
1431 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1432 }
1433}
1434
1435/*
1436** Return the index of the N-th non-switch argument. Return -1
1437** if N is out of range.
1438*/
1439static int argindex(n)
1440int n;
1441{
1442 int i;
1443 int dashdash = 0;
1444 if( argv!=0 && *argv!=0 ){
1445 for(i=1; argv[i]; i++){
1446 if( dashdash || !ISOPT(argv[i]) ){
1447 if( n==0 ) return i;
1448 n--;
1449 }
1450 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1451 }
1452 }
1453 return -1;
1454}
1455
1456static char emsg[] = "Command line syntax error: ";
1457
1458/*
1459** Process a flag command line argument.
1460*/
1461static int handleflags(i,err)
1462int i;
1463FILE *err;
1464{
1465 int v;
1466 int errcnt = 0;
1467 int j;
1468 for(j=0; op[j].label; j++){
1469 if( strcmp(&argv[i][1],op[j].label)==0 ) break;
1470 }
1471 v = argv[i][0]=='-' ? 1 : 0;
1472 if( op[j].label==0 ){
1473 if( err ){
1474 fprintf(err,"%sundefined option.\n",emsg);
1475 errline(i,1,err);
1476 }
1477 errcnt++;
1478 }else if( op[j].type==OPT_FLAG ){
1479 *((int*)op[j].arg) = v;
1480 }else if( op[j].type==OPT_FFLAG ){
1481 (*(void(*)())(op[j].arg))(v);
1482 }else{
1483 if( err ){
1484 fprintf(err,"%smissing argument on switch.\n",emsg);
1485 errline(i,1,err);
1486 }
1487 errcnt++;
1488 }
1489 return errcnt;
1490}
1491
1492/*
1493** Process a command line switch which has an argument.
1494*/
1495static int handleswitch(i,err)
1496int i;
1497FILE *err;
1498{
1499 int lv = 0;
1500 double dv = 0.0;
1501 char *sv = 0, *end;
1502 char *cp;
1503 int j;
1504 int errcnt = 0;
1505 cp = strchr(argv[i],'=');
1506 *cp = 0;
1507 for(j=0; op[j].label; j++){
1508 if( strcmp(argv[i],op[j].label)==0 ) break;
1509 }
1510 *cp = '=';
1511 if( op[j].label==0 ){
1512 if( err ){
1513 fprintf(err,"%sundefined option.\n",emsg);
1514 errline(i,0,err);
1515 }
1516 errcnt++;
1517 }else{
1518 cp++;
1519 switch( op[j].type ){
1520 case OPT_FLAG:
1521 case OPT_FFLAG:
1522 if( err ){
1523 fprintf(err,"%soption requires an argument.\n",emsg);
1524 errline(i,0,err);
1525 }
1526 errcnt++;
1527 break;
1528 case OPT_DBL:
1529 case OPT_FDBL:
1530 dv = strtod(cp,&end);
1531 if( *end ){
1532 if( err ){
1533 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
1534 errline(i,((int)end)-(int)argv[i],err);
1535 }
1536 errcnt++;
1537 }
1538 break;
1539 case OPT_INT:
1540 case OPT_FINT:
1541 lv = strtol(cp,&end,0);
1542 if( *end ){
1543 if( err ){
1544 fprintf(err,"%sillegal character in integer argument.\n",emsg);
1545 errline(i,((int)end)-(int)argv[i],err);
1546 }
1547 errcnt++;
1548 }
1549 break;
1550 case OPT_STR:
1551 case OPT_FSTR:
1552 sv = cp;
1553 break;
1554 }
1555 switch( op[j].type ){
1556 case OPT_FLAG:
1557 case OPT_FFLAG:
1558 break;
1559 case OPT_DBL:
1560 *(double*)(op[j].arg) = dv;
1561 break;
1562 case OPT_FDBL:
1563 (*(void(*)())(op[j].arg))(dv);
1564 break;
1565 case OPT_INT:
1566 *(int*)(op[j].arg) = lv;
1567 break;
1568 case OPT_FINT:
1569 (*(void(*)())(op[j].arg))((int)lv);
1570 break;
1571 case OPT_STR:
1572 *(char**)(op[j].arg) = sv;
1573 break;
1574 case OPT_FSTR:
1575 (*(void(*)())(op[j].arg))(sv);
1576 break;
1577 }
1578 }
1579 return errcnt;
1580}
1581
drhb0c86772000-06-02 23:21:26 +00001582int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001583char **a;
1584struct s_options *o;
1585FILE *err;
1586{
1587 int errcnt = 0;
1588 argv = a;
1589 op = o;
1590 errstream = err;
1591 if( argv && *argv && op ){
1592 int i;
1593 for(i=1; argv[i]; i++){
1594 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1595 errcnt += handleflags(i,err);
1596 }else if( strchr(argv[i],'=') ){
1597 errcnt += handleswitch(i,err);
1598 }
1599 }
1600 }
1601 if( errcnt>0 ){
1602 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001603 OptPrint();
drh75897232000-05-29 14:26:00 +00001604 exit(1);
1605 }
1606 return 0;
1607}
1608
drhb0c86772000-06-02 23:21:26 +00001609int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001610 int cnt = 0;
1611 int dashdash = 0;
1612 int i;
1613 if( argv!=0 && argv[0]!=0 ){
1614 for(i=1; argv[i]; i++){
1615 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1616 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1617 }
1618 }
1619 return cnt;
1620}
1621
drhb0c86772000-06-02 23:21:26 +00001622char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001623int n;
1624{
1625 int i;
1626 i = argindex(n);
1627 return i>=0 ? argv[i] : 0;
1628}
1629
drhb0c86772000-06-02 23:21:26 +00001630void OptErr(n)
drh75897232000-05-29 14:26:00 +00001631int n;
1632{
1633 int i;
1634 i = argindex(n);
1635 if( i>=0 ) errline(i,0,errstream);
1636}
1637
drhb0c86772000-06-02 23:21:26 +00001638void OptPrint(){
drh75897232000-05-29 14:26:00 +00001639 int i;
1640 int max, len;
1641 max = 0;
1642 for(i=0; op[i].label; i++){
1643 len = strlen(op[i].label) + 1;
1644 switch( op[i].type ){
1645 case OPT_FLAG:
1646 case OPT_FFLAG:
1647 break;
1648 case OPT_INT:
1649 case OPT_FINT:
1650 len += 9; /* length of "<integer>" */
1651 break;
1652 case OPT_DBL:
1653 case OPT_FDBL:
1654 len += 6; /* length of "<real>" */
1655 break;
1656 case OPT_STR:
1657 case OPT_FSTR:
1658 len += 8; /* length of "<string>" */
1659 break;
1660 }
1661 if( len>max ) max = len;
1662 }
1663 for(i=0; op[i].label; i++){
1664 switch( op[i].type ){
1665 case OPT_FLAG:
1666 case OPT_FFLAG:
1667 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1668 break;
1669 case OPT_INT:
1670 case OPT_FINT:
1671 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
1672 max-strlen(op[i].label)-9,"",op[i].message);
1673 break;
1674 case OPT_DBL:
1675 case OPT_FDBL:
1676 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
1677 max-strlen(op[i].label)-6,"",op[i].message);
1678 break;
1679 case OPT_STR:
1680 case OPT_FSTR:
1681 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
1682 max-strlen(op[i].label)-8,"",op[i].message);
1683 break;
1684 }
1685 }
1686}
1687/*********************** From the file "parse.c" ****************************/
1688/*
1689** Input file parser for the LEMON parser generator.
1690*/
1691
1692/* The state of the parser */
1693struct pstate {
1694 char *filename; /* Name of the input file */
1695 int tokenlineno; /* Linenumber at which current token starts */
1696 int errorcnt; /* Number of errors so far */
1697 char *tokenstart; /* Text of current token */
1698 struct lemon *gp; /* Global state vector */
1699 enum e_state {
1700 INITIALIZE,
1701 WAITING_FOR_DECL_OR_RULE,
1702 WAITING_FOR_DECL_KEYWORD,
1703 WAITING_FOR_DECL_ARG,
1704 WAITING_FOR_PRECEDENCE_SYMBOL,
1705 WAITING_FOR_ARROW,
1706 IN_RHS,
1707 LHS_ALIAS_1,
1708 LHS_ALIAS_2,
1709 LHS_ALIAS_3,
1710 RHS_ALIAS_1,
1711 RHS_ALIAS_2,
1712 PRECEDENCE_MARK_1,
1713 PRECEDENCE_MARK_2,
1714 RESYNC_AFTER_RULE_ERROR,
1715 RESYNC_AFTER_DECL_ERROR,
1716 WAITING_FOR_DESTRUCTOR_SYMBOL,
1717 WAITING_FOR_DATATYPE_SYMBOL
1718 } state; /* The state of the parser */
1719 struct symbol *lhs; /* Left-hand side of current rule */
1720 char *lhsalias; /* Alias for the LHS */
1721 int nrhs; /* Number of right-hand side symbols seen */
1722 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1723 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1724 struct rule *prevrule; /* Previous rule parsed */
1725 char *declkeyword; /* Keyword of a declaration */
1726 char **declargslot; /* Where the declaration argument should be put */
1727 int *decllnslot; /* Where the declaration linenumber is put */
1728 enum e_assoc declassoc; /* Assign this association to decl arguments */
1729 int preccounter; /* Assign this precedence to decl arguments */
1730 struct rule *firstrule; /* Pointer to first rule in the grammar */
1731 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1732};
1733
1734/* Parse a single token */
1735static void parseonetoken(psp)
1736struct pstate *psp;
1737{
1738 char *x;
1739 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1740#if 0
1741 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1742 x,psp->state);
1743#endif
1744 switch( psp->state ){
1745 case INITIALIZE:
1746 psp->prevrule = 0;
1747 psp->preccounter = 0;
1748 psp->firstrule = psp->lastrule = 0;
1749 psp->gp->nrule = 0;
1750 /* Fall thru to next case */
1751 case WAITING_FOR_DECL_OR_RULE:
1752 if( x[0]=='%' ){
1753 psp->state = WAITING_FOR_DECL_KEYWORD;
1754 }else if( islower(x[0]) ){
1755 psp->lhs = Symbol_new(x);
1756 psp->nrhs = 0;
1757 psp->lhsalias = 0;
1758 psp->state = WAITING_FOR_ARROW;
1759 }else if( x[0]=='{' ){
1760 if( psp->prevrule==0 ){
1761 ErrorMsg(psp->filename,psp->tokenlineno,
1762"There is not prior rule opon which to attach the code \
1763fragment which begins on this line.");
1764 psp->errorcnt++;
1765 }else if( psp->prevrule->code!=0 ){
1766 ErrorMsg(psp->filename,psp->tokenlineno,
1767"Code fragment beginning on this line is not the first \
1768to follow the previous rule.");
1769 psp->errorcnt++;
1770 }else{
1771 psp->prevrule->line = psp->tokenlineno;
1772 psp->prevrule->code = &x[1];
1773 }
1774 }else if( x[0]=='[' ){
1775 psp->state = PRECEDENCE_MARK_1;
1776 }else{
1777 ErrorMsg(psp->filename,psp->tokenlineno,
1778 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
1779 x);
1780 psp->errorcnt++;
1781 }
1782 break;
1783 case PRECEDENCE_MARK_1:
1784 if( !isupper(x[0]) ){
1785 ErrorMsg(psp->filename,psp->tokenlineno,
1786 "The precedence symbol must be a terminal.");
1787 psp->errorcnt++;
1788 }else if( psp->prevrule==0 ){
1789 ErrorMsg(psp->filename,psp->tokenlineno,
1790 "There is no prior rule to assign precedence \"[%s]\".",x);
1791 psp->errorcnt++;
1792 }else if( psp->prevrule->precsym!=0 ){
1793 ErrorMsg(psp->filename,psp->tokenlineno,
1794"Precedence mark on this line is not the first \
1795to follow the previous rule.");
1796 psp->errorcnt++;
1797 }else{
1798 psp->prevrule->precsym = Symbol_new(x);
1799 }
1800 psp->state = PRECEDENCE_MARK_2;
1801 break;
1802 case PRECEDENCE_MARK_2:
1803 if( x[0]!=']' ){
1804 ErrorMsg(psp->filename,psp->tokenlineno,
1805 "Missing \"]\" on precedence mark.");
1806 psp->errorcnt++;
1807 }
1808 psp->state = WAITING_FOR_DECL_OR_RULE;
1809 break;
1810 case WAITING_FOR_ARROW:
1811 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
1812 psp->state = IN_RHS;
1813 }else if( x[0]=='(' ){
1814 psp->state = LHS_ALIAS_1;
1815 }else{
1816 ErrorMsg(psp->filename,psp->tokenlineno,
1817 "Expected to see a \":\" following the LHS symbol \"%s\".",
1818 psp->lhs->name);
1819 psp->errorcnt++;
1820 psp->state = RESYNC_AFTER_RULE_ERROR;
1821 }
1822 break;
1823 case LHS_ALIAS_1:
1824 if( isalpha(x[0]) ){
1825 psp->lhsalias = x;
1826 psp->state = LHS_ALIAS_2;
1827 }else{
1828 ErrorMsg(psp->filename,psp->tokenlineno,
1829 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
1830 x,psp->lhs->name);
1831 psp->errorcnt++;
1832 psp->state = RESYNC_AFTER_RULE_ERROR;
1833 }
1834 break;
1835 case LHS_ALIAS_2:
1836 if( x[0]==')' ){
1837 psp->state = LHS_ALIAS_3;
1838 }else{
1839 ErrorMsg(psp->filename,psp->tokenlineno,
1840 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
1841 psp->errorcnt++;
1842 psp->state = RESYNC_AFTER_RULE_ERROR;
1843 }
1844 break;
1845 case LHS_ALIAS_3:
1846 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
1847 psp->state = IN_RHS;
1848 }else{
1849 ErrorMsg(psp->filename,psp->tokenlineno,
1850 "Missing \"->\" following: \"%s(%s)\".",
1851 psp->lhs->name,psp->lhsalias);
1852 psp->errorcnt++;
1853 psp->state = RESYNC_AFTER_RULE_ERROR;
1854 }
1855 break;
1856 case IN_RHS:
1857 if( x[0]=='.' ){
1858 struct rule *rp;
1859 rp = (struct rule *)malloc( sizeof(struct rule) +
1860 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
1861 if( rp==0 ){
1862 ErrorMsg(psp->filename,psp->tokenlineno,
1863 "Can't allocate enough memory for this rule.");
1864 psp->errorcnt++;
1865 psp->prevrule = 0;
1866 }else{
1867 int i;
1868 rp->ruleline = psp->tokenlineno;
1869 rp->rhs = (struct symbol**)&rp[1];
1870 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
1871 for(i=0; i<psp->nrhs; i++){
1872 rp->rhs[i] = psp->rhs[i];
1873 rp->rhsalias[i] = psp->alias[i];
1874 }
1875 rp->lhs = psp->lhs;
1876 rp->lhsalias = psp->lhsalias;
1877 rp->nrhs = psp->nrhs;
1878 rp->code = 0;
1879 rp->precsym = 0;
1880 rp->index = psp->gp->nrule++;
1881 rp->nextlhs = rp->lhs->rule;
1882 rp->lhs->rule = rp;
1883 rp->next = 0;
1884 if( psp->firstrule==0 ){
1885 psp->firstrule = psp->lastrule = rp;
1886 }else{
1887 psp->lastrule->next = rp;
1888 psp->lastrule = rp;
1889 }
1890 psp->prevrule = rp;
1891 }
1892 psp->state = WAITING_FOR_DECL_OR_RULE;
1893 }else if( isalpha(x[0]) ){
1894 if( psp->nrhs>=MAXRHS ){
1895 ErrorMsg(psp->filename,psp->tokenlineno,
1896 "Too many symbol on RHS or rule beginning at \"%s\".",
1897 x);
1898 psp->errorcnt++;
1899 psp->state = RESYNC_AFTER_RULE_ERROR;
1900 }else{
1901 psp->rhs[psp->nrhs] = Symbol_new(x);
1902 psp->alias[psp->nrhs] = 0;
1903 psp->nrhs++;
1904 }
1905 }else if( x[0]=='(' && psp->nrhs>0 ){
1906 psp->state = RHS_ALIAS_1;
1907 }else{
1908 ErrorMsg(psp->filename,psp->tokenlineno,
1909 "Illegal character on RHS of rule: \"%s\".",x);
1910 psp->errorcnt++;
1911 psp->state = RESYNC_AFTER_RULE_ERROR;
1912 }
1913 break;
1914 case RHS_ALIAS_1:
1915 if( isalpha(x[0]) ){
1916 psp->alias[psp->nrhs-1] = x;
1917 psp->state = RHS_ALIAS_2;
1918 }else{
1919 ErrorMsg(psp->filename,psp->tokenlineno,
1920 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
1921 x,psp->rhs[psp->nrhs-1]->name);
1922 psp->errorcnt++;
1923 psp->state = RESYNC_AFTER_RULE_ERROR;
1924 }
1925 break;
1926 case RHS_ALIAS_2:
1927 if( x[0]==')' ){
1928 psp->state = IN_RHS;
1929 }else{
1930 ErrorMsg(psp->filename,psp->tokenlineno,
1931 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
1932 psp->errorcnt++;
1933 psp->state = RESYNC_AFTER_RULE_ERROR;
1934 }
1935 break;
1936 case WAITING_FOR_DECL_KEYWORD:
1937 if( isalpha(x[0]) ){
1938 psp->declkeyword = x;
1939 psp->declargslot = 0;
1940 psp->decllnslot = 0;
1941 psp->state = WAITING_FOR_DECL_ARG;
1942 if( strcmp(x,"name")==0 ){
1943 psp->declargslot = &(psp->gp->name);
1944 }else if( strcmp(x,"include")==0 ){
1945 psp->declargslot = &(psp->gp->include);
1946 psp->decllnslot = &psp->gp->includeln;
1947 }else if( strcmp(x,"code")==0 ){
1948 psp->declargslot = &(psp->gp->extracode);
1949 psp->decllnslot = &psp->gp->extracodeln;
1950 }else if( strcmp(x,"token_destructor")==0 ){
1951 psp->declargslot = &psp->gp->tokendest;
1952 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00001953 }else if( strcmp(x,"default_destructor")==0 ){
1954 psp->declargslot = &psp->gp->vardest;
1955 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00001956 }else if( strcmp(x,"token_prefix")==0 ){
1957 psp->declargslot = &psp->gp->tokenprefix;
1958 }else if( strcmp(x,"syntax_error")==0 ){
1959 psp->declargslot = &(psp->gp->error);
1960 psp->decllnslot = &psp->gp->errorln;
1961 }else if( strcmp(x,"parse_accept")==0 ){
1962 psp->declargslot = &(psp->gp->accept);
1963 psp->decllnslot = &psp->gp->acceptln;
1964 }else if( strcmp(x,"parse_failure")==0 ){
1965 psp->declargslot = &(psp->gp->failure);
1966 psp->decllnslot = &psp->gp->failureln;
1967 }else if( strcmp(x,"stack_overflow")==0 ){
1968 psp->declargslot = &(psp->gp->overflow);
1969 psp->decllnslot = &psp->gp->overflowln;
1970 }else if( strcmp(x,"extra_argument")==0 ){
1971 psp->declargslot = &(psp->gp->arg);
1972 }else if( strcmp(x,"token_type")==0 ){
1973 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00001974 }else if( strcmp(x,"default_type")==0 ){
1975 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00001976 }else if( strcmp(x,"stack_size")==0 ){
1977 psp->declargslot = &(psp->gp->stacksize);
1978 }else if( strcmp(x,"start_symbol")==0 ){
1979 psp->declargslot = &(psp->gp->start);
1980 }else if( strcmp(x,"left")==0 ){
1981 psp->preccounter++;
1982 psp->declassoc = LEFT;
1983 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
1984 }else if( strcmp(x,"right")==0 ){
1985 psp->preccounter++;
1986 psp->declassoc = RIGHT;
1987 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
1988 }else if( strcmp(x,"nonassoc")==0 ){
1989 psp->preccounter++;
1990 psp->declassoc = NONE;
1991 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
1992 }else if( strcmp(x,"destructor")==0 ){
1993 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
1994 }else if( strcmp(x,"type")==0 ){
1995 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
1996 }else{
1997 ErrorMsg(psp->filename,psp->tokenlineno,
1998 "Unknown declaration keyword: \"%%%s\".",x);
1999 psp->errorcnt++;
2000 psp->state = RESYNC_AFTER_DECL_ERROR;
2001 }
2002 }else{
2003 ErrorMsg(psp->filename,psp->tokenlineno,
2004 "Illegal declaration keyword: \"%s\".",x);
2005 psp->errorcnt++;
2006 psp->state = RESYNC_AFTER_DECL_ERROR;
2007 }
2008 break;
2009 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2010 if( !isalpha(x[0]) ){
2011 ErrorMsg(psp->filename,psp->tokenlineno,
2012 "Symbol name missing after %destructor keyword");
2013 psp->errorcnt++;
2014 psp->state = RESYNC_AFTER_DECL_ERROR;
2015 }else{
2016 struct symbol *sp = Symbol_new(x);
2017 psp->declargslot = &sp->destructor;
2018 psp->decllnslot = &sp->destructorln;
2019 psp->state = WAITING_FOR_DECL_ARG;
2020 }
2021 break;
2022 case WAITING_FOR_DATATYPE_SYMBOL:
2023 if( !isalpha(x[0]) ){
2024 ErrorMsg(psp->filename,psp->tokenlineno,
2025 "Symbol name missing after %destructor keyword");
2026 psp->errorcnt++;
2027 psp->state = RESYNC_AFTER_DECL_ERROR;
2028 }else{
2029 struct symbol *sp = Symbol_new(x);
2030 psp->declargslot = &sp->datatype;
2031 psp->decllnslot = 0;
2032 psp->state = WAITING_FOR_DECL_ARG;
2033 }
2034 break;
2035 case WAITING_FOR_PRECEDENCE_SYMBOL:
2036 if( x[0]=='.' ){
2037 psp->state = WAITING_FOR_DECL_OR_RULE;
2038 }else if( isupper(x[0]) ){
2039 struct symbol *sp;
2040 sp = Symbol_new(x);
2041 if( sp->prec>=0 ){
2042 ErrorMsg(psp->filename,psp->tokenlineno,
2043 "Symbol \"%s\" has already be given a precedence.",x);
2044 psp->errorcnt++;
2045 }else{
2046 sp->prec = psp->preccounter;
2047 sp->assoc = psp->declassoc;
2048 }
2049 }else{
2050 ErrorMsg(psp->filename,psp->tokenlineno,
2051 "Can't assign a precedence to \"%s\".",x);
2052 psp->errorcnt++;
2053 }
2054 break;
2055 case WAITING_FOR_DECL_ARG:
2056 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2057 if( *(psp->declargslot)!=0 ){
2058 ErrorMsg(psp->filename,psp->tokenlineno,
2059 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2060 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2061 psp->errorcnt++;
2062 psp->state = RESYNC_AFTER_DECL_ERROR;
2063 }else{
2064 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2065 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2066 psp->state = WAITING_FOR_DECL_OR_RULE;
2067 }
2068 }else{
2069 ErrorMsg(psp->filename,psp->tokenlineno,
2070 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2071 psp->errorcnt++;
2072 psp->state = RESYNC_AFTER_DECL_ERROR;
2073 }
2074 break;
2075 case RESYNC_AFTER_RULE_ERROR:
2076/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2077** break; */
2078 case RESYNC_AFTER_DECL_ERROR:
2079 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2080 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2081 break;
2082 }
2083}
2084
2085/* In spite of its name, this function is really a scanner. It read
2086** in the entire input file (all at once) then tokenizes it. Each
2087** token is passed to the function "parseonetoken" which builds all
2088** the appropriate data structures in the global state vector "gp".
2089*/
2090void Parse(gp)
2091struct lemon *gp;
2092{
2093 struct pstate ps;
2094 FILE *fp;
2095 char *filebuf;
2096 int filesize;
2097 int lineno;
2098 int c;
2099 char *cp, *nextcp;
2100 int startline = 0;
2101
2102 ps.gp = gp;
2103 ps.filename = gp->filename;
2104 ps.errorcnt = 0;
2105 ps.state = INITIALIZE;
2106
2107 /* Begin by reading the input file */
2108 fp = fopen(ps.filename,"rb");
2109 if( fp==0 ){
2110 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2111 gp->errorcnt++;
2112 return;
2113 }
2114 fseek(fp,0,2);
2115 filesize = ftell(fp);
2116 rewind(fp);
2117 filebuf = (char *)malloc( filesize+1 );
2118 if( filebuf==0 ){
2119 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2120 filesize+1);
2121 gp->errorcnt++;
2122 return;
2123 }
2124 if( fread(filebuf,1,filesize,fp)!=filesize ){
2125 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2126 filesize);
2127 free(filebuf);
2128 gp->errorcnt++;
2129 return;
2130 }
2131 fclose(fp);
2132 filebuf[filesize] = 0;
2133
2134 /* Now scan the text of the input file */
2135 lineno = 1;
2136 for(cp=filebuf; (c= *cp)!=0; ){
2137 if( c=='\n' ) lineno++; /* Keep track of the line number */
2138 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2139 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2140 cp+=2;
2141 while( (c= *cp)!=0 && c!='\n' ) cp++;
2142 continue;
2143 }
2144 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2145 cp+=2;
2146 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2147 if( c=='\n' ) lineno++;
2148 cp++;
2149 }
2150 if( c ) cp++;
2151 continue;
2152 }
2153 ps.tokenstart = cp; /* Mark the beginning of the token */
2154 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2155 if( c=='\"' ){ /* String literals */
2156 cp++;
2157 while( (c= *cp)!=0 && c!='\"' ){
2158 if( c=='\n' ) lineno++;
2159 cp++;
2160 }
2161 if( c==0 ){
2162 ErrorMsg(ps.filename,startline,
2163"String starting on this line is not terminated before the end of the file.");
2164 ps.errorcnt++;
2165 nextcp = cp;
2166 }else{
2167 nextcp = cp+1;
2168 }
2169 }else if( c=='{' ){ /* A block of C code */
2170 int level;
2171 cp++;
2172 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2173 if( c=='\n' ) lineno++;
2174 else if( c=='{' ) level++;
2175 else if( c=='}' ) level--;
2176 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2177 int prevc;
2178 cp = &cp[2];
2179 prevc = 0;
2180 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2181 if( c=='\n' ) lineno++;
2182 prevc = c;
2183 cp++;
2184 }
2185 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2186 cp = &cp[2];
2187 while( (c= *cp)!=0 && c!='\n' ) cp++;
2188 if( c ) lineno++;
2189 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2190 int startchar, prevc;
2191 startchar = c;
2192 prevc = 0;
2193 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2194 if( c=='\n' ) lineno++;
2195 if( prevc=='\\' ) prevc = 0;
2196 else prevc = c;
2197 }
2198 }
2199 }
2200 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002201 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002202"C code starting on this line is not terminated before the end of the file.");
2203 ps.errorcnt++;
2204 nextcp = cp;
2205 }else{
2206 nextcp = cp+1;
2207 }
2208 }else if( isalnum(c) ){ /* Identifiers */
2209 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2210 nextcp = cp;
2211 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2212 cp += 3;
2213 nextcp = cp;
2214 }else{ /* All other (one character) operators */
2215 cp++;
2216 nextcp = cp;
2217 }
2218 c = *cp;
2219 *cp = 0; /* Null terminate the token */
2220 parseonetoken(&ps); /* Parse the token */
2221 *cp = c; /* Restore the buffer */
2222 cp = nextcp;
2223 }
2224 free(filebuf); /* Release the buffer after parsing */
2225 gp->rule = ps.firstrule;
2226 gp->errorcnt = ps.errorcnt;
2227}
2228/*************************** From the file "plink.c" *********************/
2229/*
2230** Routines processing configuration follow-set propagation links
2231** in the LEMON parser generator.
2232*/
2233static struct plink *plink_freelist = 0;
2234
2235/* Allocate a new plink */
2236struct plink *Plink_new(){
2237 struct plink *new;
2238
2239 if( plink_freelist==0 ){
2240 int i;
2241 int amt = 100;
2242 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2243 if( plink_freelist==0 ){
2244 fprintf(stderr,
2245 "Unable to allocate memory for a new follow-set propagation link.\n");
2246 exit(1);
2247 }
2248 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2249 plink_freelist[amt-1].next = 0;
2250 }
2251 new = plink_freelist;
2252 plink_freelist = plink_freelist->next;
2253 return new;
2254}
2255
2256/* Add a plink to a plink list */
2257void Plink_add(plpp,cfp)
2258struct plink **plpp;
2259struct config *cfp;
2260{
2261 struct plink *new;
2262 new = Plink_new();
2263 new->next = *plpp;
2264 *plpp = new;
2265 new->cfp = cfp;
2266}
2267
2268/* Transfer every plink on the list "from" to the list "to" */
2269void Plink_copy(to,from)
2270struct plink **to;
2271struct plink *from;
2272{
2273 struct plink *nextpl;
2274 while( from ){
2275 nextpl = from->next;
2276 from->next = *to;
2277 *to = from;
2278 from = nextpl;
2279 }
2280}
2281
2282/* Delete every plink on the list */
2283void Plink_delete(plp)
2284struct plink *plp;
2285{
2286 struct plink *nextpl;
2287
2288 while( plp ){
2289 nextpl = plp->next;
2290 plp->next = plink_freelist;
2291 plink_freelist = plp;
2292 plp = nextpl;
2293 }
2294}
2295/*********************** From the file "report.c" **************************/
2296/*
2297** Procedures for generating reports and tables in the LEMON parser generator.
2298*/
2299
2300/* Generate a filename with the given suffix. Space to hold the
2301** name comes from malloc() and must be freed by the calling
2302** function.
2303*/
2304PRIVATE char *file_makename(lemp,suffix)
2305struct lemon *lemp;
2306char *suffix;
2307{
2308 char *name;
2309 char *cp;
2310
2311 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2312 if( name==0 ){
2313 fprintf(stderr,"Can't allocate space for a filename.\n");
2314 exit(1);
2315 }
2316 strcpy(name,lemp->filename);
2317 cp = strrchr(name,'.');
2318 if( cp ) *cp = 0;
2319 strcat(name,suffix);
2320 return name;
2321}
2322
2323/* Open a file with a name based on the name of the input file,
2324** but with a different (specified) suffix, and return a pointer
2325** to the stream */
2326PRIVATE FILE *file_open(lemp,suffix,mode)
2327struct lemon *lemp;
2328char *suffix;
2329char *mode;
2330{
2331 FILE *fp;
2332
2333 if( lemp->outname ) free(lemp->outname);
2334 lemp->outname = file_makename(lemp, suffix);
2335 fp = fopen(lemp->outname,mode);
2336 if( fp==0 && *mode=='w' ){
2337 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2338 lemp->errorcnt++;
2339 return 0;
2340 }
2341 return fp;
2342}
2343
2344/* Duplicate the input file without comments and without actions
2345** on rules */
2346void Reprint(lemp)
2347struct lemon *lemp;
2348{
2349 struct rule *rp;
2350 struct symbol *sp;
2351 int i, j, maxlen, len, ncolumns, skip;
2352 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2353 maxlen = 10;
2354 for(i=0; i<lemp->nsymbol; i++){
2355 sp = lemp->symbols[i];
2356 len = strlen(sp->name);
2357 if( len>maxlen ) maxlen = len;
2358 }
2359 ncolumns = 76/(maxlen+5);
2360 if( ncolumns<1 ) ncolumns = 1;
2361 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2362 for(i=0; i<skip; i++){
2363 printf("//");
2364 for(j=i; j<lemp->nsymbol; j+=skip){
2365 sp = lemp->symbols[j];
2366 assert( sp->index==j );
2367 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2368 }
2369 printf("\n");
2370 }
2371 for(rp=lemp->rule; rp; rp=rp->next){
2372 printf("%s",rp->lhs->name);
2373/* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2374 printf(" ::=");
2375 for(i=0; i<rp->nrhs; i++){
2376 printf(" %s",rp->rhs[i]->name);
2377/* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2378 }
2379 printf(".");
2380 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2381/* if( rp->code ) printf("\n %s",rp->code); */
2382 printf("\n");
2383 }
2384}
2385
2386void ConfigPrint(fp,cfp)
2387FILE *fp;
2388struct config *cfp;
2389{
2390 struct rule *rp;
2391 int i;
2392 rp = cfp->rp;
2393 fprintf(fp,"%s ::=",rp->lhs->name);
2394 for(i=0; i<=rp->nrhs; i++){
2395 if( i==cfp->dot ) fprintf(fp," *");
2396 if( i==rp->nrhs ) break;
2397 fprintf(fp," %s",rp->rhs[i]->name);
2398 }
2399}
2400
2401/* #define TEST */
2402#ifdef TEST
2403/* Print a set */
2404PRIVATE void SetPrint(out,set,lemp)
2405FILE *out;
2406char *set;
2407struct lemon *lemp;
2408{
2409 int i;
2410 char *spacer;
2411 spacer = "";
2412 fprintf(out,"%12s[","");
2413 for(i=0; i<lemp->nterminal; i++){
2414 if( SetFind(set,i) ){
2415 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2416 spacer = " ";
2417 }
2418 }
2419 fprintf(out,"]\n");
2420}
2421
2422/* Print a plink chain */
2423PRIVATE void PlinkPrint(out,plp,tag)
2424FILE *out;
2425struct plink *plp;
2426char *tag;
2427{
2428 while( plp ){
2429 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index);
2430 ConfigPrint(out,plp->cfp);
2431 fprintf(out,"\n");
2432 plp = plp->next;
2433 }
2434}
2435#endif
2436
2437/* Print an action to the given file descriptor. Return FALSE if
2438** nothing was actually printed.
2439*/
2440int PrintAction(struct action *ap, FILE *fp, int indent){
2441 int result = 1;
2442 switch( ap->type ){
2443 case SHIFT:
2444 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index);
2445 break;
2446 case REDUCE:
2447 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2448 break;
2449 case ACCEPT:
2450 fprintf(fp,"%*s accept",indent,ap->sp->name);
2451 break;
2452 case ERROR:
2453 fprintf(fp,"%*s error",indent,ap->sp->name);
2454 break;
2455 case CONFLICT:
2456 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2457 indent,ap->sp->name,ap->x.rp->index);
2458 break;
2459 case SH_RESOLVED:
2460 case RD_RESOLVED:
2461 case NOT_USED:
2462 result = 0;
2463 break;
2464 }
2465 return result;
2466}
2467
2468/* Generate the "y.output" log file */
2469void ReportOutput(lemp)
2470struct lemon *lemp;
2471{
2472 int i;
2473 struct state *stp;
2474 struct config *cfp;
2475 struct action *ap;
2476 FILE *fp;
2477
2478 fp = file_open(lemp,".out","w");
2479 if( fp==0 ) return;
2480 fprintf(fp," \b");
2481 for(i=0; i<lemp->nstate; i++){
2482 stp = lemp->sorted[i];
2483 fprintf(fp,"State %d:\n",stp->index);
2484 if( lemp->basisflag ) cfp=stp->bp;
2485 else cfp=stp->cfp;
2486 while( cfp ){
2487 char buf[20];
2488 if( cfp->dot==cfp->rp->nrhs ){
2489 sprintf(buf,"(%d)",cfp->rp->index);
2490 fprintf(fp," %5s ",buf);
2491 }else{
2492 fprintf(fp," ");
2493 }
2494 ConfigPrint(fp,cfp);
2495 fprintf(fp,"\n");
2496#ifdef TEST
2497 SetPrint(fp,cfp->fws,lemp);
2498 PlinkPrint(fp,cfp->fplp,"To ");
2499 PlinkPrint(fp,cfp->bplp,"From");
2500#endif
2501 if( lemp->basisflag ) cfp=cfp->bp;
2502 else cfp=cfp->next;
2503 }
2504 fprintf(fp,"\n");
2505 for(ap=stp->ap; ap; ap=ap->next){
2506 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2507 }
2508 fprintf(fp,"\n");
2509 }
2510 fclose(fp);
2511 return;
2512}
2513
2514/* Search for the file "name" which is in the same directory as
2515** the exacutable */
2516PRIVATE char *pathsearch(argv0,name,modemask)
2517char *argv0;
2518char *name;
2519int modemask;
2520{
2521 char *pathlist;
2522 char *path,*cp;
2523 char c;
2524 extern int access();
2525
2526#ifdef __WIN32__
2527 cp = strrchr(argv0,'\\');
2528#else
2529 cp = strrchr(argv0,'/');
2530#endif
2531 if( cp ){
2532 c = *cp;
2533 *cp = 0;
2534 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2535 if( path ) sprintf(path,"%s/%s",argv0,name);
2536 *cp = c;
2537 }else{
2538 extern char *getenv();
2539 pathlist = getenv("PATH");
2540 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2541 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2542 if( path!=0 ){
2543 while( *pathlist ){
2544 cp = strchr(pathlist,':');
2545 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2546 c = *cp;
2547 *cp = 0;
2548 sprintf(path,"%s/%s",pathlist,name);
2549 *cp = c;
2550 if( c==0 ) pathlist = "";
2551 else pathlist = &cp[1];
2552 if( access(path,modemask)==0 ) break;
2553 }
2554 }
2555 }
2556 return path;
2557}
2558
2559/* Given an action, compute the integer value for that action
2560** which is to be put in the action table of the generated machine.
2561** Return negative if no action should be generated.
2562*/
2563PRIVATE int compute_action(lemp,ap)
2564struct lemon *lemp;
2565struct action *ap;
2566{
2567 int act;
2568 switch( ap->type ){
2569 case SHIFT: act = ap->x.stp->index; break;
2570 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2571 case ERROR: act = lemp->nstate + lemp->nrule; break;
2572 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2573 default: act = -1; break;
2574 }
2575 return act;
2576}
2577
2578#define LINESIZE 1000
2579/* The next cluster of routines are for reading the template file
2580** and writing the results to the generated parser */
2581/* The first function transfers data from "in" to "out" until
2582** a line is seen which begins with "%%". The line number is
2583** tracked.
2584**
2585** if name!=0, then any word that begin with "Parse" is changed to
2586** begin with *name instead.
2587*/
2588PRIVATE void tplt_xfer(name,in,out,lineno)
2589char *name;
2590FILE *in;
2591FILE *out;
2592int *lineno;
2593{
2594 int i, iStart;
2595 char line[LINESIZE];
2596 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2597 (*lineno)++;
2598 iStart = 0;
2599 if( name ){
2600 for(i=0; line[i]; i++){
2601 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2602 && (i==0 || !isalpha(line[i-1]))
2603 ){
2604 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2605 fprintf(out,"%s",name);
2606 i += 4;
2607 iStart = i+1;
2608 }
2609 }
2610 }
2611 fprintf(out,"%s",&line[iStart]);
2612 }
2613}
2614
2615/* The next function finds the template file and opens it, returning
2616** a pointer to the opened file. */
2617PRIVATE FILE *tplt_open(lemp)
2618struct lemon *lemp;
2619{
2620 static char templatename[] = "lempar.c";
2621 char buf[1000];
2622 FILE *in;
2623 char *tpltname;
2624 char *cp;
2625
2626 cp = strrchr(lemp->filename,'.');
2627 if( cp ){
2628 sprintf(buf,"%.*s.lt",(int)cp-(int)lemp->filename,lemp->filename);
2629 }else{
2630 sprintf(buf,"%s.lt",lemp->filename);
2631 }
2632 if( access(buf,004)==0 ){
2633 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00002634 }else if( access(templatename,004)==0 ){
2635 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00002636 }else{
2637 tpltname = pathsearch(lemp->argv0,templatename,0);
2638 }
2639 if( tpltname==0 ){
2640 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
2641 templatename);
2642 lemp->errorcnt++;
2643 return 0;
2644 }
2645 in = fopen(tpltname,"r");
2646 if( in==0 ){
2647 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
2648 lemp->errorcnt++;
2649 return 0;
2650 }
2651 return in;
2652}
2653
2654/* Print a string to the file and keep the linenumber up to date */
2655PRIVATE void tplt_print(out,lemp,str,strln,lineno)
2656FILE *out;
2657struct lemon *lemp;
2658char *str;
2659int strln;
2660int *lineno;
2661{
2662 if( str==0 ) return;
2663 fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++;
2664 while( *str ){
2665 if( *str=='\n' ) (*lineno)++;
2666 putc(*str,out);
2667 str++;
2668 }
2669 fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2;
2670 return;
2671}
2672
2673/*
2674** The following routine emits code for the destructor for the
2675** symbol sp
2676*/
2677void emit_destructor_code(out,sp,lemp,lineno)
2678FILE *out;
2679struct symbol *sp;
2680struct lemon *lemp;
2681int *lineno;
2682{
2683 char *cp;
2684
2685 int linecnt = 0;
2686 if( sp->type==TERMINAL ){
2687 cp = lemp->tokendest;
2688 if( cp==0 ) return;
2689 fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename);
drh960e8c62001-04-03 16:53:21 +00002690 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00002691 cp = sp->destructor;
drh75897232000-05-29 14:26:00 +00002692 fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename);
drh960e8c62001-04-03 16:53:21 +00002693 }else if( lemp->vardest ){
2694 cp = lemp->vardest;
2695 if( cp==0 ) return;
2696 fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename);
drh75897232000-05-29 14:26:00 +00002697 }
2698 for(; *cp; cp++){
2699 if( *cp=='$' && cp[1]=='$' ){
2700 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
2701 cp++;
2702 continue;
2703 }
2704 if( *cp=='\n' ) linecnt++;
2705 fputc(*cp,out);
2706 }
2707 (*lineno) += 3 + linecnt;
2708 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2709 return;
2710}
2711
2712/*
drh960e8c62001-04-03 16:53:21 +00002713** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00002714*/
2715int has_destructor(sp, lemp)
2716struct symbol *sp;
2717struct lemon *lemp;
2718{
2719 int ret;
2720 if( sp->type==TERMINAL ){
2721 ret = lemp->tokendest!=0;
2722 }else{
drh960e8c62001-04-03 16:53:21 +00002723 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00002724 }
2725 return ret;
2726}
2727
2728/*
2729** Generate code which executes when the rule "rp" is reduced. Write
2730** the code to "out". Make sure lineno stays up-to-date.
2731*/
2732PRIVATE void emit_code(out,rp,lemp,lineno)
2733FILE *out;
2734struct rule *rp;
2735struct lemon *lemp;
2736int *lineno;
2737{
2738 char *cp, *xp;
2739 int linecnt = 0;
2740 int i;
2741 char lhsused = 0; /* True if the LHS element has been used */
2742 char used[MAXRHS]; /* True for each RHS element which is used */
2743
2744 for(i=0; i<rp->nrhs; i++) used[i] = 0;
2745 lhsused = 0;
2746
2747 /* Generate code to do the reduce action */
2748 if( rp->code ){
2749 fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
2750 for(cp=rp->code; *cp; cp++){
2751 if( isalpha(*cp) && (cp==rp->code || !isalnum(cp[-1])) ){
2752 char saved;
2753 for(xp= &cp[1]; isalnum(*xp); xp++);
2754 saved = *xp;
2755 *xp = 0;
2756 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
2757 fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum);
2758 cp = xp;
2759 lhsused = 1;
2760 }else{
2761 for(i=0; i<rp->nrhs; i++){
2762 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
2763 fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum);
2764 cp = xp;
2765 used[i] = 1;
2766 break;
2767 }
2768 }
2769 }
2770 *xp = saved;
2771 }
2772 if( *cp=='\n' ) linecnt++;
2773 fputc(*cp,out);
2774 } /* End loop */
2775 (*lineno) += 3 + linecnt;
2776 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2777 } /* End if( rp->code ) */
2778
2779 /* Check to make sure the LHS has been used */
2780 if( rp->lhsalias && !lhsused ){
2781 ErrorMsg(lemp->filename,rp->ruleline,
2782 "Label \"%s\" for \"%s(%s)\" is never used.",
2783 rp->lhsalias,rp->lhs->name,rp->lhsalias);
2784 lemp->errorcnt++;
2785 }
2786
2787 /* Generate destructor code for RHS symbols which are not used in the
2788 ** reduce code */
2789 for(i=0; i<rp->nrhs; i++){
2790 if( rp->rhsalias[i] && !used[i] ){
2791 ErrorMsg(lemp->filename,rp->ruleline,
drh960e8c62001-04-03 16:53:21 +00002792 "Label %s for \"%s(%s)\" is never used.",
drh75897232000-05-29 14:26:00 +00002793 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
2794 lemp->errorcnt++;
2795 }else if( rp->rhsalias[i]==0 ){
2796 if( has_destructor(rp->rhs[i],lemp) ){
2797 fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n",
2798 rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++;
2799 }else{
2800 fprintf(out," /* No destructor defined for %s */\n",
2801 rp->rhs[i]->name);
2802 (*lineno)++;
2803 }
2804 }
2805 }
2806 return;
2807}
2808
2809/*
2810** Print the definition of the union used for the parser's data stack.
2811** This union contains fields for every possible data type for tokens
2812** and nonterminals. In the process of computing and printing this
2813** union, also set the ".dtnum" field of every terminal and nonterminal
2814** symbol.
2815*/
2816void print_stack_union(out,lemp,plineno,mhflag)
2817FILE *out; /* The output stream */
2818struct lemon *lemp; /* The main info structure for this parser */
2819int *plineno; /* Pointer to the line number */
2820int mhflag; /* True if generating makeheaders output */
2821{
2822 int lineno = *plineno; /* The line number of the output */
2823 char **types; /* A hash table of datatypes */
2824 int arraysize; /* Size of the "types" array */
2825 int maxdtlength; /* Maximum length of any ".datatype" field. */
2826 char *stddt; /* Standardized name for a datatype */
2827 int i,j; /* Loop counters */
2828 int hash; /* For hashing the name of a type */
2829 char *name; /* Name of the parser */
2830
2831 /* Allocate and initialize types[] and allocate stddt[] */
2832 arraysize = lemp->nsymbol * 2;
2833 types = (char**)malloc( arraysize * sizeof(char*) );
2834 for(i=0; i<arraysize; i++) types[i] = 0;
2835 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00002836 if( lemp->vartype ){
2837 maxdtlength = strlen(lemp->vartype);
2838 }
drh75897232000-05-29 14:26:00 +00002839 for(i=0; i<lemp->nsymbol; i++){
2840 int len;
2841 struct symbol *sp = lemp->symbols[i];
2842 if( sp->datatype==0 ) continue;
2843 len = strlen(sp->datatype);
2844 if( len>maxdtlength ) maxdtlength = len;
2845 }
2846 stddt = (char*)malloc( maxdtlength*2 + 1 );
2847 if( types==0 || stddt==0 ){
2848 fprintf(stderr,"Out of memory.\n");
2849 exit(1);
2850 }
2851
2852 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
2853 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00002854 ** used for terminal symbols. If there is no %default_type defined then
2855 ** 0 is also used as the .dtnum value for nonterminals which do not specify
2856 ** a datatype using the %type directive.
2857 */
drh75897232000-05-29 14:26:00 +00002858 for(i=0; i<lemp->nsymbol; i++){
2859 struct symbol *sp = lemp->symbols[i];
2860 char *cp;
2861 if( sp==lemp->errsym ){
2862 sp->dtnum = arraysize+1;
2863 continue;
2864 }
drh960e8c62001-04-03 16:53:21 +00002865 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00002866 sp->dtnum = 0;
2867 continue;
2868 }
2869 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00002870 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00002871 j = 0;
2872 while( isspace(*cp) ) cp++;
2873 while( *cp ) stddt[j++] = *cp++;
2874 while( j>0 && isspace(stddt[j-1]) ) j--;
2875 stddt[j] = 0;
2876 hash = 0;
2877 for(j=0; stddt[j]; j++){
2878 hash = hash*53 + stddt[j];
2879 }
2880 if( hash<0 ) hash = -hash;
2881 hash = hash%arraysize;
2882 while( types[hash] ){
2883 if( strcmp(types[hash],stddt)==0 ){
2884 sp->dtnum = hash + 1;
2885 break;
2886 }
2887 hash++;
2888 if( hash>=arraysize ) hash = 0;
2889 }
2890 if( types[hash]==0 ){
2891 sp->dtnum = hash + 1;
2892 types[hash] = (char*)malloc( strlen(stddt)+1 );
2893 if( types[hash]==0 ){
2894 fprintf(stderr,"Out of memory.\n");
2895 exit(1);
2896 }
2897 strcpy(types[hash],stddt);
2898 }
2899 }
2900
2901 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
2902 name = lemp->name ? lemp->name : "Parse";
2903 lineno = *plineno;
2904 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
2905 fprintf(out,"#define %sTOKENTYPE %s\n",name,
2906 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
2907 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
2908 fprintf(out,"typedef union {\n"); lineno++;
2909 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
2910 for(i=0; i<arraysize; i++){
2911 if( types[i]==0 ) continue;
2912 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
2913 free(types[i]);
2914 }
2915 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
2916 free(stddt);
2917 free(types);
2918 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
2919 *plineno = lineno;
2920}
2921
2922/* Generate C source code for the parser */
2923void ReportTable(lemp, mhflag)
2924struct lemon *lemp;
2925int mhflag; /* Output in makeheaders format if true */
2926{
2927 FILE *out, *in;
2928 char line[LINESIZE];
2929 int lineno;
2930 struct state *stp;
2931 struct action *ap;
2932 struct rule *rp;
2933 int i;
2934 int tablecnt;
2935 char *name;
2936
2937 in = tplt_open(lemp);
2938 if( in==0 ) return;
2939 out = file_open(lemp,".c","w");
2940 if( out==0 ){
2941 fclose(in);
2942 return;
2943 }
2944 lineno = 1;
2945 tplt_xfer(lemp->name,in,out,&lineno);
2946
2947 /* Generate the include code, if any */
2948 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
2949 if( mhflag ){
2950 char *name = file_makename(lemp, ".h");
2951 fprintf(out,"#include \"%s\"\n", name); lineno++;
2952 free(name);
2953 }
2954 tplt_xfer(lemp->name,in,out,&lineno);
2955
2956 /* Generate #defines for all tokens */
2957 if( mhflag ){
2958 char *prefix;
2959 fprintf(out,"#if INTERFACE\n"); lineno++;
2960 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
2961 else prefix = "";
2962 for(i=1; i<lemp->nterminal; i++){
2963 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
2964 lineno++;
2965 }
2966 fprintf(out,"#endif\n"); lineno++;
2967 }
2968 tplt_xfer(lemp->name,in,out,&lineno);
2969
2970 /* Generate the defines */
2971 fprintf(out,"/* \001 */\n");
2972 fprintf(out,"#define YYCODETYPE %s\n",
2973 lemp->nsymbol>250?"int":"unsigned char"); lineno++;
2974 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
2975 fprintf(out,"#define YYACTIONTYPE %s\n",
2976 lemp->nstate+lemp->nrule>250?"int":"unsigned char"); lineno++;
2977 print_stack_union(out,lemp,&lineno,mhflag);
2978 if( lemp->stacksize ){
2979 if( atoi(lemp->stacksize)<=0 ){
2980 ErrorMsg(lemp->filename,0,
2981"Illegal stack size: [%s]. The stack size should be an integer constant.",
2982 lemp->stacksize);
2983 lemp->errorcnt++;
2984 lemp->stacksize = "100";
2985 }
2986 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
2987 }else{
2988 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
2989 }
2990 if( mhflag ){
2991 fprintf(out,"#if INTERFACE\n"); lineno++;
2992 }
2993 name = lemp->name ? lemp->name : "Parse";
2994 if( lemp->arg && lemp->arg[0] ){
2995 int i;
2996 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00002997 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
2998 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh75897232000-05-29 14:26:00 +00002999 fprintf(out,"#define %sARGDECL ,%s\n",name,&lemp->arg[i]); lineno++;
3000 fprintf(out,"#define %sXARGDECL %s;\n",name,lemp->arg); lineno++;
3001 fprintf(out,"#define %sANSIARGDECL ,%s\n",name,lemp->arg); lineno++;
3002 }else{
3003 fprintf(out,"#define %sARGDECL\n",name); lineno++;
3004 fprintf(out,"#define %sXARGDECL\n",name); lineno++;
3005 fprintf(out,"#define %sANSIARGDECL\n",name); lineno++;
3006 }
3007 if( mhflag ){
3008 fprintf(out,"#endif\n"); lineno++;
3009 }
3010 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3011 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3012 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3013 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3014 tplt_xfer(lemp->name,in,out,&lineno);
3015
3016 /* Generate the action table.
3017 **
3018 ** Each entry in the action table is an element of the following
3019 ** structure:
3020 ** struct yyActionEntry {
3021 ** YYCODETYPE lookahead;
3022 ** YYACTIONTYPE action;
3023 ** struct yyActionEntry *next;
3024 ** }
3025 **
3026 ** The entries are grouped into hash tables, one hash table for each
3027 ** parser state. The hash table has a size which is the smallest
3028 ** power of two needed to hold all entries.
3029 */
3030 tablecnt = 0;
3031
3032 /* Loop over parser states */
3033 for(i=0; i<lemp->nstate; i++){
3034 int tablesize; /* size of the hash table */
3035 int j,k; /* Loop counter */
3036 int collide[2048]; /* The collision chain for the table */
3037 struct action *table[2048]; /* Build the hash table here */
3038
3039 /* Find the number of actions and initialize the hash table */
3040 stp = lemp->sorted[i];
3041 stp->tabstart = tablecnt;
3042 stp->naction = 0;
3043 for(ap=stp->ap; ap; ap=ap->next){
3044 if( ap->sp->index!=lemp->nsymbol && compute_action(lemp,ap)>=0 ){
3045 stp->naction++;
3046 }
3047 }
3048 tablesize = 1;
3049 while( tablesize<stp->naction ) tablesize += tablesize;
3050 assert( tablesize<= sizeof(table)/sizeof(table[0]) );
3051 for(j=0; j<tablesize; j++){
3052 table[j] = 0;
3053 collide[j] = -1;
3054 }
3055
3056 /* Hash the actions into the hash table */
3057 stp->tabdfltact = lemp->nstate + lemp->nrule;
3058 for(ap=stp->ap; ap; ap=ap->next){
3059 int action = compute_action(lemp,ap);
3060 int h;
3061 if( ap->sp->index==lemp->nsymbol ){
3062 stp->tabdfltact = action;
3063 }else if( action>=0 ){
3064 h = ap->sp->index & (tablesize-1);
3065 ap->collide = table[h];
3066 table[h] = ap;
3067 }
3068 }
3069
3070 /* Resolve collisions */
3071 for(j=k=0; j<tablesize; j++){
3072 if( table[j] && table[j]->collide ){
3073 while( table[k] ) k++;
3074 table[k] = table[j]->collide;
3075 collide[j] = k;
3076 table[j]->collide = 0;
3077 if( k<j ) j = k-1;
3078 }
3079 }
3080
3081 /* Print the hash table */
3082 fprintf(out,"/* State %d */\n",stp->index); lineno++;
3083 for(j=0; j<tablesize; j++){
3084 if( table[j]==0 ){
3085 fprintf(out,
3086 " {YYNOCODE,0,0}, /* Unused */\n");
3087 }else{
3088 fprintf(out," {%4d,%4d, ",
3089 table[j]->sp->index,
3090 compute_action(lemp,table[j]));
3091 if( collide[j]>=0 ){
3092 fprintf(out,"&yyActionTable[%4d] }, /* ",
3093 collide[j] + tablecnt);
3094 }else{
3095 fprintf(out,"0 }, /* ");
3096 }
3097 PrintAction(table[j],out,22);
3098 fprintf(out," */\n");
3099 }
3100 lineno++;
3101 }
3102
3103 /* Update the table count */
3104 tablecnt += tablesize;
3105 }
3106 tplt_xfer(lemp->name,in,out,&lineno);
3107 lemp->tablesize = tablecnt;
3108
3109 /* Generate the state table
3110 **
3111 ** Each entry is an element of the following structure:
3112 ** struct yyStateEntry {
3113 ** struct yyActionEntry *hashtbl;
3114 ** int mask;
3115 ** YYACTIONTYPE actionDefault;
3116 ** }
3117 */
3118 for(i=0; i<lemp->nstate; i++){
3119 int tablesize;
3120 stp = lemp->sorted[i];
3121 tablesize = 1;
3122 while( tablesize<stp->naction ) tablesize += tablesize;
3123 fprintf(out," { &yyActionTable[%d], %d, %d},\n",
3124 stp->tabstart,
3125 tablesize - 1,
3126 stp->tabdfltact); lineno++;
3127 }
3128 tplt_xfer(lemp->name,in,out,&lineno);
3129
3130 /* Generate a table containing the symbolic name of every symbol */
3131 for(i=0; i<lemp->nsymbol; i++){
3132 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3133 fprintf(out," %-15s",line);
3134 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3135 }
3136 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3137 tplt_xfer(lemp->name,in,out,&lineno);
3138
3139 /* Generate code which executes every time a symbol is popped from
3140 ** the stack while processing errors or while destroying the parser.
3141 ** (In other words, generate the %destructor actions) */
3142 if( lemp->tokendest ){
3143 for(i=0; i<lemp->nsymbol; i++){
3144 struct symbol *sp = lemp->symbols[i];
3145 if( sp==0 || sp->type!=TERMINAL ) continue;
3146 fprintf(out," case %d:\n",sp->index); lineno++;
3147 }
3148 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3149 if( i<lemp->nsymbol ){
3150 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3151 fprintf(out," break;\n"); lineno++;
3152 }
3153 }
3154 for(i=0; i<lemp->nsymbol; i++){
3155 struct symbol *sp = lemp->symbols[i];
3156 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3157 fprintf(out," case %d:\n",sp->index); lineno++;
3158 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3159 fprintf(out," break;\n"); lineno++;
3160 }
drh960e8c62001-04-03 16:53:21 +00003161 if( lemp->vardest ){
3162 struct symbol *dflt_sp = 0;
3163 for(i=0; i<lemp->nsymbol; i++){
3164 struct symbol *sp = lemp->symbols[i];
3165 if( sp==0 || sp->type==TERMINAL ||
3166 sp->index<=0 || sp->destructor!=0 ) continue;
3167 fprintf(out," case %d:\n",sp->index); lineno++;
3168 dflt_sp = sp;
3169 }
3170 if( dflt_sp!=0 ){
3171 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3172 fprintf(out," break;\n"); lineno++;
3173 }
3174 }
drh75897232000-05-29 14:26:00 +00003175 tplt_xfer(lemp->name,in,out,&lineno);
3176
3177 /* Generate code which executes whenever the parser stack overflows */
3178 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3179 tplt_xfer(lemp->name,in,out,&lineno);
3180
3181 /* Generate the table of rule information
3182 **
3183 ** Note: This code depends on the fact that rules are number
3184 ** sequentually beginning with 0.
3185 */
3186 for(rp=lemp->rule; rp; rp=rp->next){
3187 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3188 }
3189 tplt_xfer(lemp->name,in,out,&lineno);
3190
3191 /* Generate code which execution during each REDUCE action */
3192 for(rp=lemp->rule; rp; rp=rp->next){
3193 fprintf(out," case %d:\n",rp->index); lineno++;
3194 fprintf(out," YYTRACE(\"%s ::=",rp->lhs->name);
3195 for(i=0; i<rp->nrhs; i++) fprintf(out," %s",rp->rhs[i]->name);
3196 fprintf(out,"\")\n"); lineno++;
3197 emit_code(out,rp,lemp,&lineno);
3198 fprintf(out," break;\n"); lineno++;
3199 }
3200 tplt_xfer(lemp->name,in,out,&lineno);
3201
3202 /* Generate code which executes if a parse fails */
3203 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3204 tplt_xfer(lemp->name,in,out,&lineno);
3205
3206 /* Generate code which executes when a syntax error occurs */
3207 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3208 tplt_xfer(lemp->name,in,out,&lineno);
3209
3210 /* Generate code which executes when the parser accepts its input */
3211 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3212 tplt_xfer(lemp->name,in,out,&lineno);
3213
3214 /* Append any addition code the user desires */
3215 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3216
3217 fclose(in);
3218 fclose(out);
3219 return;
3220}
3221
3222/* Generate a header file for the parser */
3223void ReportHeader(lemp)
3224struct lemon *lemp;
3225{
3226 FILE *out, *in;
3227 char *prefix;
3228 char line[LINESIZE];
3229 char pattern[LINESIZE];
3230 int i;
3231
3232 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3233 else prefix = "";
3234 in = file_open(lemp,".h","r");
3235 if( in ){
3236 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3237 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3238 if( strcmp(line,pattern) ) break;
3239 }
3240 fclose(in);
3241 if( i==lemp->nterminal ){
3242 /* No change in the file. Don't rewrite it. */
3243 return;
3244 }
3245 }
3246 out = file_open(lemp,".h","w");
3247 if( out ){
3248 for(i=1; i<lemp->nterminal; i++){
3249 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3250 }
3251 fclose(out);
3252 }
3253 return;
3254}
3255
3256/* Reduce the size of the action tables, if possible, by making use
3257** of defaults.
3258**
3259** In this version, if all REDUCE actions use the same rule, make
3260** them the default. Only default them if there are more than one.
3261*/
3262void CompressTables(lemp)
3263struct lemon *lemp;
3264{
3265 struct state *stp;
3266 struct action *ap;
3267 struct rule *rp;
3268 int i;
3269 int cnt;
3270
3271 for(i=0; i<lemp->nstate; i++){
3272 stp = lemp->sorted[i];
3273
3274 /* Find the first REDUCE action */
3275 for(ap=stp->ap; ap && ap->type!=REDUCE; ap=ap->next);
3276 if( ap==0 ) continue;
3277
3278 /* Remember the rule used */
3279 rp = ap->x.rp;
3280
3281 /* See if all other REDUCE acitons use the same rule */
3282 cnt = 1;
3283 for(ap=ap->next; ap; ap=ap->next){
3284 if( ap->type==REDUCE ){
3285 if( ap->x.rp!=rp ) break;
3286 cnt++;
3287 }
3288 }
3289 if( ap || cnt==1 ) continue;
3290
3291 /* Combine all REDUCE actions into a single default */
3292 for(ap=stp->ap; ap && ap->type!=REDUCE; ap=ap->next);
3293 assert( ap );
3294 ap->sp = Symbol_new("{default}");
3295 for(ap=ap->next; ap; ap=ap->next){
3296 if( ap->type==REDUCE ) ap->type = NOT_USED;
3297 }
3298 stp->ap = Action_sort(stp->ap);
3299 }
3300}
3301/***************** From the file "set.c" ************************************/
3302/*
3303** Set manipulation routines for the LEMON parser generator.
3304*/
3305
3306static int size = 0;
3307
3308/* Set the set size */
3309void SetSize(n)
3310int n;
3311{
3312 size = n+1;
3313}
3314
3315/* Allocate a new set */
3316char *SetNew(){
3317 char *s;
3318 int i;
3319 s = (char*)malloc( size );
3320 if( s==0 ){
3321 extern void memory_error();
3322 memory_error();
3323 }
3324 for(i=0; i<size; i++) s[i] = 0;
3325 return s;
3326}
3327
3328/* Deallocate a set */
3329void SetFree(s)
3330char *s;
3331{
3332 free(s);
3333}
3334
3335/* Add a new element to the set. Return TRUE if the element was added
3336** and FALSE if it was already there. */
3337int SetAdd(s,e)
3338char *s;
3339int e;
3340{
3341 int rv;
3342 rv = s[e];
3343 s[e] = 1;
3344 return !rv;
3345}
3346
3347/* Add every element of s2 to s1. Return TRUE if s1 changes. */
3348int SetUnion(s1,s2)
3349char *s1;
3350char *s2;
3351{
3352 int i, progress;
3353 progress = 0;
3354 for(i=0; i<size; i++){
3355 if( s2[i]==0 ) continue;
3356 if( s1[i]==0 ){
3357 progress = 1;
3358 s1[i] = 1;
3359 }
3360 }
3361 return progress;
3362}
3363/********************** From the file "table.c" ****************************/
3364/*
3365** All code in this file has been automatically generated
3366** from a specification in the file
3367** "table.q"
3368** by the associative array code building program "aagen".
3369** Do not edit this file! Instead, edit the specification
3370** file, then rerun aagen.
3371*/
3372/*
3373** Code for processing tables in the LEMON parser generator.
3374*/
3375
3376PRIVATE int strhash(x)
3377char *x;
3378{
3379 int h = 0;
3380 while( *x) h = h*13 + *(x++);
3381 return h;
3382}
3383
3384/* Works like strdup, sort of. Save a string in malloced memory, but
3385** keep strings in a table so that the same string is not in more
3386** than one place.
3387*/
3388char *Strsafe(y)
3389char *y;
3390{
3391 char *z;
3392
3393 z = Strsafe_find(y);
3394 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
3395 strcpy(z,y);
3396 Strsafe_insert(z);
3397 }
3398 MemoryCheck(z);
3399 return z;
3400}
3401
3402/* There is one instance of the following structure for each
3403** associative array of type "x1".
3404*/
3405struct s_x1 {
3406 int size; /* The number of available slots. */
3407 /* Must be a power of 2 greater than or */
3408 /* equal to 1 */
3409 int count; /* Number of currently slots filled */
3410 struct s_x1node *tbl; /* The data stored here */
3411 struct s_x1node **ht; /* Hash table for lookups */
3412};
3413
3414/* There is one instance of this structure for every data element
3415** in an associative array of type "x1".
3416*/
3417typedef struct s_x1node {
3418 char *data; /* The data */
3419 struct s_x1node *next; /* Next entry with the same hash */
3420 struct s_x1node **from; /* Previous link */
3421} x1node;
3422
3423/* There is only one instance of the array, which is the following */
3424static struct s_x1 *x1a;
3425
3426/* Allocate a new associative array */
3427void Strsafe_init(){
3428 if( x1a ) return;
3429 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
3430 if( x1a ){
3431 x1a->size = 1024;
3432 x1a->count = 0;
3433 x1a->tbl = (x1node*)malloc(
3434 (sizeof(x1node) + sizeof(x1node*))*1024 );
3435 if( x1a->tbl==0 ){
3436 free(x1a);
3437 x1a = 0;
3438 }else{
3439 int i;
3440 x1a->ht = (x1node**)&(x1a->tbl[1024]);
3441 for(i=0; i<1024; i++) x1a->ht[i] = 0;
3442 }
3443 }
3444}
3445/* Insert a new record into the array. Return TRUE if successful.
3446** Prior data with the same key is NOT overwritten */
3447int Strsafe_insert(data)
3448char *data;
3449{
3450 x1node *np;
3451 int h;
3452 int ph;
3453
3454 if( x1a==0 ) return 0;
3455 ph = strhash(data);
3456 h = ph & (x1a->size-1);
3457 np = x1a->ht[h];
3458 while( np ){
3459 if( strcmp(np->data,data)==0 ){
3460 /* An existing entry with the same key is found. */
3461 /* Fail because overwrite is not allows. */
3462 return 0;
3463 }
3464 np = np->next;
3465 }
3466 if( x1a->count>=x1a->size ){
3467 /* Need to make the hash table bigger */
3468 int i,size;
3469 struct s_x1 array;
3470 array.size = size = x1a->size*2;
3471 array.count = x1a->count;
3472 array.tbl = (x1node*)malloc(
3473 (sizeof(x1node) + sizeof(x1node*))*size );
3474 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3475 array.ht = (x1node**)&(array.tbl[size]);
3476 for(i=0; i<size; i++) array.ht[i] = 0;
3477 for(i=0; i<x1a->count; i++){
3478 x1node *oldnp, *newnp;
3479 oldnp = &(x1a->tbl[i]);
3480 h = strhash(oldnp->data) & (size-1);
3481 newnp = &(array.tbl[i]);
3482 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3483 newnp->next = array.ht[h];
3484 newnp->data = oldnp->data;
3485 newnp->from = &(array.ht[h]);
3486 array.ht[h] = newnp;
3487 }
3488 free(x1a->tbl);
3489 *x1a = array;
3490 }
3491 /* Insert the new data */
3492 h = ph & (x1a->size-1);
3493 np = &(x1a->tbl[x1a->count++]);
3494 np->data = data;
3495 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
3496 np->next = x1a->ht[h];
3497 x1a->ht[h] = np;
3498 np->from = &(x1a->ht[h]);
3499 return 1;
3500}
3501
3502/* Return a pointer to data assigned to the given key. Return NULL
3503** if no such key. */
3504char *Strsafe_find(key)
3505char *key;
3506{
3507 int h;
3508 x1node *np;
3509
3510 if( x1a==0 ) return 0;
3511 h = strhash(key) & (x1a->size-1);
3512 np = x1a->ht[h];
3513 while( np ){
3514 if( strcmp(np->data,key)==0 ) break;
3515 np = np->next;
3516 }
3517 return np ? np->data : 0;
3518}
3519
3520/* Return a pointer to the (terminal or nonterminal) symbol "x".
3521** Create a new symbol if this is the first time "x" has been seen.
3522*/
3523struct symbol *Symbol_new(x)
3524char *x;
3525{
3526 struct symbol *sp;
3527
3528 sp = Symbol_find(x);
3529 if( sp==0 ){
3530 sp = (struct symbol *)malloc( sizeof(struct symbol) );
3531 MemoryCheck(sp);
3532 sp->name = Strsafe(x);
3533 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
3534 sp->rule = 0;
3535 sp->prec = -1;
3536 sp->assoc = UNK;
3537 sp->firstset = 0;
3538 sp->lambda = FALSE;
3539 sp->destructor = 0;
3540 sp->datatype = 0;
3541 Symbol_insert(sp,sp->name);
3542 }
3543 return sp;
3544}
3545
3546/* Compare two symbols */
3547int Symbolcmpp(a,b)
3548struct symbol **a;
3549struct symbol **b;
3550{
3551 return strcmp((**a).name,(**b).name);
3552}
3553
3554/* There is one instance of the following structure for each
3555** associative array of type "x2".
3556*/
3557struct s_x2 {
3558 int size; /* The number of available slots. */
3559 /* Must be a power of 2 greater than or */
3560 /* equal to 1 */
3561 int count; /* Number of currently slots filled */
3562 struct s_x2node *tbl; /* The data stored here */
3563 struct s_x2node **ht; /* Hash table for lookups */
3564};
3565
3566/* There is one instance of this structure for every data element
3567** in an associative array of type "x2".
3568*/
3569typedef struct s_x2node {
3570 struct symbol *data; /* The data */
3571 char *key; /* The key */
3572 struct s_x2node *next; /* Next entry with the same hash */
3573 struct s_x2node **from; /* Previous link */
3574} x2node;
3575
3576/* There is only one instance of the array, which is the following */
3577static struct s_x2 *x2a;
3578
3579/* Allocate a new associative array */
3580void Symbol_init(){
3581 if( x2a ) return;
3582 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
3583 if( x2a ){
3584 x2a->size = 128;
3585 x2a->count = 0;
3586 x2a->tbl = (x2node*)malloc(
3587 (sizeof(x2node) + sizeof(x2node*))*128 );
3588 if( x2a->tbl==0 ){
3589 free(x2a);
3590 x2a = 0;
3591 }else{
3592 int i;
3593 x2a->ht = (x2node**)&(x2a->tbl[128]);
3594 for(i=0; i<128; i++) x2a->ht[i] = 0;
3595 }
3596 }
3597}
3598/* Insert a new record into the array. Return TRUE if successful.
3599** Prior data with the same key is NOT overwritten */
3600int Symbol_insert(data,key)
3601struct symbol *data;
3602char *key;
3603{
3604 x2node *np;
3605 int h;
3606 int ph;
3607
3608 if( x2a==0 ) return 0;
3609 ph = strhash(key);
3610 h = ph & (x2a->size-1);
3611 np = x2a->ht[h];
3612 while( np ){
3613 if( strcmp(np->key,key)==0 ){
3614 /* An existing entry with the same key is found. */
3615 /* Fail because overwrite is not allows. */
3616 return 0;
3617 }
3618 np = np->next;
3619 }
3620 if( x2a->count>=x2a->size ){
3621 /* Need to make the hash table bigger */
3622 int i,size;
3623 struct s_x2 array;
3624 array.size = size = x2a->size*2;
3625 array.count = x2a->count;
3626 array.tbl = (x2node*)malloc(
3627 (sizeof(x2node) + sizeof(x2node*))*size );
3628 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3629 array.ht = (x2node**)&(array.tbl[size]);
3630 for(i=0; i<size; i++) array.ht[i] = 0;
3631 for(i=0; i<x2a->count; i++){
3632 x2node *oldnp, *newnp;
3633 oldnp = &(x2a->tbl[i]);
3634 h = strhash(oldnp->key) & (size-1);
3635 newnp = &(array.tbl[i]);
3636 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3637 newnp->next = array.ht[h];
3638 newnp->key = oldnp->key;
3639 newnp->data = oldnp->data;
3640 newnp->from = &(array.ht[h]);
3641 array.ht[h] = newnp;
3642 }
3643 free(x2a->tbl);
3644 *x2a = array;
3645 }
3646 /* Insert the new data */
3647 h = ph & (x2a->size-1);
3648 np = &(x2a->tbl[x2a->count++]);
3649 np->key = key;
3650 np->data = data;
3651 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
3652 np->next = x2a->ht[h];
3653 x2a->ht[h] = np;
3654 np->from = &(x2a->ht[h]);
3655 return 1;
3656}
3657
3658/* Return a pointer to data assigned to the given key. Return NULL
3659** if no such key. */
3660struct symbol *Symbol_find(key)
3661char *key;
3662{
3663 int h;
3664 x2node *np;
3665
3666 if( x2a==0 ) return 0;
3667 h = strhash(key) & (x2a->size-1);
3668 np = x2a->ht[h];
3669 while( np ){
3670 if( strcmp(np->key,key)==0 ) break;
3671 np = np->next;
3672 }
3673 return np ? np->data : 0;
3674}
3675
3676/* Return the n-th data. Return NULL if n is out of range. */
3677struct symbol *Symbol_Nth(n)
3678int n;
3679{
3680 struct symbol *data;
3681 if( x2a && n>0 && n<=x2a->count ){
3682 data = x2a->tbl[n-1].data;
3683 }else{
3684 data = 0;
3685 }
3686 return data;
3687}
3688
3689/* Return the size of the array */
3690int Symbol_count()
3691{
3692 return x2a ? x2a->count : 0;
3693}
3694
3695/* Return an array of pointers to all data in the table.
3696** The array is obtained from malloc. Return NULL if memory allocation
3697** problems, or if the array is empty. */
3698struct symbol **Symbol_arrayof()
3699{
3700 struct symbol **array;
3701 int i,size;
3702 if( x2a==0 ) return 0;
3703 size = x2a->count;
3704 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
3705 if( array ){
3706 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
3707 }
3708 return array;
3709}
3710
3711/* Compare two configurations */
3712int Configcmp(a,b)
3713struct config *a;
3714struct config *b;
3715{
3716 int x;
3717 x = a->rp->index - b->rp->index;
3718 if( x==0 ) x = a->dot - b->dot;
3719 return x;
3720}
3721
3722/* Compare two states */
3723PRIVATE int statecmp(a,b)
3724struct config *a;
3725struct config *b;
3726{
3727 int rc;
3728 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
3729 rc = a->rp->index - b->rp->index;
3730 if( rc==0 ) rc = a->dot - b->dot;
3731 }
3732 if( rc==0 ){
3733 if( a ) rc = 1;
3734 if( b ) rc = -1;
3735 }
3736 return rc;
3737}
3738
3739/* Hash a state */
3740PRIVATE int statehash(a)
3741struct config *a;
3742{
3743 int h=0;
3744 while( a ){
3745 h = h*571 + a->rp->index*37 + a->dot;
3746 a = a->bp;
3747 }
3748 return h;
3749}
3750
3751/* Allocate a new state structure */
3752struct state *State_new()
3753{
3754 struct state *new;
3755 new = (struct state *)malloc( sizeof(struct state) );
3756 MemoryCheck(new);
3757 return new;
3758}
3759
3760/* There is one instance of the following structure for each
3761** associative array of type "x3".
3762*/
3763struct s_x3 {
3764 int size; /* The number of available slots. */
3765 /* Must be a power of 2 greater than or */
3766 /* equal to 1 */
3767 int count; /* Number of currently slots filled */
3768 struct s_x3node *tbl; /* The data stored here */
3769 struct s_x3node **ht; /* Hash table for lookups */
3770};
3771
3772/* There is one instance of this structure for every data element
3773** in an associative array of type "x3".
3774*/
3775typedef struct s_x3node {
3776 struct state *data; /* The data */
3777 struct config *key; /* The key */
3778 struct s_x3node *next; /* Next entry with the same hash */
3779 struct s_x3node **from; /* Previous link */
3780} x3node;
3781
3782/* There is only one instance of the array, which is the following */
3783static struct s_x3 *x3a;
3784
3785/* Allocate a new associative array */
3786void State_init(){
3787 if( x3a ) return;
3788 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
3789 if( x3a ){
3790 x3a->size = 128;
3791 x3a->count = 0;
3792 x3a->tbl = (x3node*)malloc(
3793 (sizeof(x3node) + sizeof(x3node*))*128 );
3794 if( x3a->tbl==0 ){
3795 free(x3a);
3796 x3a = 0;
3797 }else{
3798 int i;
3799 x3a->ht = (x3node**)&(x3a->tbl[128]);
3800 for(i=0; i<128; i++) x3a->ht[i] = 0;
3801 }
3802 }
3803}
3804/* Insert a new record into the array. Return TRUE if successful.
3805** Prior data with the same key is NOT overwritten */
3806int State_insert(data,key)
3807struct state *data;
3808struct config *key;
3809{
3810 x3node *np;
3811 int h;
3812 int ph;
3813
3814 if( x3a==0 ) return 0;
3815 ph = statehash(key);
3816 h = ph & (x3a->size-1);
3817 np = x3a->ht[h];
3818 while( np ){
3819 if( statecmp(np->key,key)==0 ){
3820 /* An existing entry with the same key is found. */
3821 /* Fail because overwrite is not allows. */
3822 return 0;
3823 }
3824 np = np->next;
3825 }
3826 if( x3a->count>=x3a->size ){
3827 /* Need to make the hash table bigger */
3828 int i,size;
3829 struct s_x3 array;
3830 array.size = size = x3a->size*2;
3831 array.count = x3a->count;
3832 array.tbl = (x3node*)malloc(
3833 (sizeof(x3node) + sizeof(x3node*))*size );
3834 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3835 array.ht = (x3node**)&(array.tbl[size]);
3836 for(i=0; i<size; i++) array.ht[i] = 0;
3837 for(i=0; i<x3a->count; i++){
3838 x3node *oldnp, *newnp;
3839 oldnp = &(x3a->tbl[i]);
3840 h = statehash(oldnp->key) & (size-1);
3841 newnp = &(array.tbl[i]);
3842 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3843 newnp->next = array.ht[h];
3844 newnp->key = oldnp->key;
3845 newnp->data = oldnp->data;
3846 newnp->from = &(array.ht[h]);
3847 array.ht[h] = newnp;
3848 }
3849 free(x3a->tbl);
3850 *x3a = array;
3851 }
3852 /* Insert the new data */
3853 h = ph & (x3a->size-1);
3854 np = &(x3a->tbl[x3a->count++]);
3855 np->key = key;
3856 np->data = data;
3857 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
3858 np->next = x3a->ht[h];
3859 x3a->ht[h] = np;
3860 np->from = &(x3a->ht[h]);
3861 return 1;
3862}
3863
3864/* Return a pointer to data assigned to the given key. Return NULL
3865** if no such key. */
3866struct state *State_find(key)
3867struct config *key;
3868{
3869 int h;
3870 x3node *np;
3871
3872 if( x3a==0 ) return 0;
3873 h = statehash(key) & (x3a->size-1);
3874 np = x3a->ht[h];
3875 while( np ){
3876 if( statecmp(np->key,key)==0 ) break;
3877 np = np->next;
3878 }
3879 return np ? np->data : 0;
3880}
3881
3882/* Return an array of pointers to all data in the table.
3883** The array is obtained from malloc. Return NULL if memory allocation
3884** problems, or if the array is empty. */
3885struct state **State_arrayof()
3886{
3887 struct state **array;
3888 int i,size;
3889 if( x3a==0 ) return 0;
3890 size = x3a->count;
3891 array = (struct state **)malloc( sizeof(struct state *)*size );
3892 if( array ){
3893 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
3894 }
3895 return array;
3896}
3897
3898/* Hash a configuration */
3899PRIVATE int confighash(a)
3900struct config *a;
3901{
3902 int h=0;
3903 h = h*571 + a->rp->index*37 + a->dot;
3904 return h;
3905}
3906
3907/* There is one instance of the following structure for each
3908** associative array of type "x4".
3909*/
3910struct s_x4 {
3911 int size; /* The number of available slots. */
3912 /* Must be a power of 2 greater than or */
3913 /* equal to 1 */
3914 int count; /* Number of currently slots filled */
3915 struct s_x4node *tbl; /* The data stored here */
3916 struct s_x4node **ht; /* Hash table for lookups */
3917};
3918
3919/* There is one instance of this structure for every data element
3920** in an associative array of type "x4".
3921*/
3922typedef struct s_x4node {
3923 struct config *data; /* The data */
3924 struct s_x4node *next; /* Next entry with the same hash */
3925 struct s_x4node **from; /* Previous link */
3926} x4node;
3927
3928/* There is only one instance of the array, which is the following */
3929static struct s_x4 *x4a;
3930
3931/* Allocate a new associative array */
3932void Configtable_init(){
3933 if( x4a ) return;
3934 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
3935 if( x4a ){
3936 x4a->size = 64;
3937 x4a->count = 0;
3938 x4a->tbl = (x4node*)malloc(
3939 (sizeof(x4node) + sizeof(x4node*))*64 );
3940 if( x4a->tbl==0 ){
3941 free(x4a);
3942 x4a = 0;
3943 }else{
3944 int i;
3945 x4a->ht = (x4node**)&(x4a->tbl[64]);
3946 for(i=0; i<64; i++) x4a->ht[i] = 0;
3947 }
3948 }
3949}
3950/* Insert a new record into the array. Return TRUE if successful.
3951** Prior data with the same key is NOT overwritten */
3952int Configtable_insert(data)
3953struct config *data;
3954{
3955 x4node *np;
3956 int h;
3957 int ph;
3958
3959 if( x4a==0 ) return 0;
3960 ph = confighash(data);
3961 h = ph & (x4a->size-1);
3962 np = x4a->ht[h];
3963 while( np ){
3964 if( Configcmp(np->data,data)==0 ){
3965 /* An existing entry with the same key is found. */
3966 /* Fail because overwrite is not allows. */
3967 return 0;
3968 }
3969 np = np->next;
3970 }
3971 if( x4a->count>=x4a->size ){
3972 /* Need to make the hash table bigger */
3973 int i,size;
3974 struct s_x4 array;
3975 array.size = size = x4a->size*2;
3976 array.count = x4a->count;
3977 array.tbl = (x4node*)malloc(
3978 (sizeof(x4node) + sizeof(x4node*))*size );
3979 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3980 array.ht = (x4node**)&(array.tbl[size]);
3981 for(i=0; i<size; i++) array.ht[i] = 0;
3982 for(i=0; i<x4a->count; i++){
3983 x4node *oldnp, *newnp;
3984 oldnp = &(x4a->tbl[i]);
3985 h = confighash(oldnp->data) & (size-1);
3986 newnp = &(array.tbl[i]);
3987 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3988 newnp->next = array.ht[h];
3989 newnp->data = oldnp->data;
3990 newnp->from = &(array.ht[h]);
3991 array.ht[h] = newnp;
3992 }
3993 free(x4a->tbl);
3994 *x4a = array;
3995 }
3996 /* Insert the new data */
3997 h = ph & (x4a->size-1);
3998 np = &(x4a->tbl[x4a->count++]);
3999 np->data = data;
4000 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4001 np->next = x4a->ht[h];
4002 x4a->ht[h] = np;
4003 np->from = &(x4a->ht[h]);
4004 return 1;
4005}
4006
4007/* Return a pointer to data assigned to the given key. Return NULL
4008** if no such key. */
4009struct config *Configtable_find(key)
4010struct config *key;
4011{
4012 int h;
4013 x4node *np;
4014
4015 if( x4a==0 ) return 0;
4016 h = confighash(key) & (x4a->size-1);
4017 np = x4a->ht[h];
4018 while( np ){
4019 if( Configcmp(np->data,key)==0 ) break;
4020 np = np->next;
4021 }
4022 return np ? np->data : 0;
4023}
4024
4025/* Remove all data from the table. Pass each data to the function "f"
4026** as it is removed. ("f" may be null to avoid this step.) */
4027void Configtable_clear(f)
4028int(*f)(/* struct config * */);
4029{
4030 int i;
4031 if( x4a==0 || x4a->count==0 ) return;
4032 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4033 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4034 x4a->count = 0;
4035 return;
4036}