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