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