blob: 45f010d2323b06db5834f4a4a6f6fd6c2818e7c3 [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();
drh60d31652004-02-22 00:08:04 +00001390 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001391 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1392 (int(*)())Symbolcmpp);
1393 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1394 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1395 lem.nterminal = i;
1396
1397 /* Generate a reprint of the grammar, if requested on the command line */
1398 if( rpflag ){
1399 Reprint(&lem);
1400 }else{
1401 /* Initialize the size for all follow and first sets */
1402 SetSize(lem.nterminal);
1403
1404 /* Find the precedence for every production rule (that has one) */
1405 FindRulePrecedences(&lem);
1406
1407 /* Compute the lambda-nonterminals and the first-sets for every
1408 ** nonterminal */
1409 FindFirstSets(&lem);
1410
1411 /* Compute all LR(0) states. Also record follow-set propagation
1412 ** links so that the follow-set can be computed later */
1413 lem.nstate = 0;
1414 FindStates(&lem);
1415 lem.sorted = State_arrayof();
1416
1417 /* Tie up loose ends on the propagation links */
1418 FindLinks(&lem);
1419
1420 /* Compute the follow set of every reducible configuration */
1421 FindFollowSets(&lem);
1422
1423 /* Compute the action tables */
1424 FindActions(&lem);
1425
1426 /* Compress the action tables */
1427 if( compress==0 ) CompressTables(&lem);
1428
1429 /* Generate a report of the parser generated. (the "y.output" file) */
1430 if( !quiet ) ReportOutput(&lem);
1431
1432 /* Generate the source code for the parser */
1433 ReportTable(&lem, mhflag);
1434
1435 /* Produce a header file for use by the scanner. (This step is
1436 ** omitted if the "-m" option is used because makeheaders will
1437 ** generate the file for us.) */
1438 if( !mhflag ) ReportHeader(&lem);
1439 }
1440 if( statistics ){
1441 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1442 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1443 printf(" %d states, %d parser table entries, %d conflicts\n",
1444 lem.nstate, lem.tablesize, lem.nconflict);
1445 }
1446 if( lem.nconflict ){
1447 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1448 }
1449 exit(lem.errorcnt + lem.nconflict);
1450}
1451/******************** From the file "msort.c" *******************************/
1452/*
1453** A generic merge-sort program.
1454**
1455** USAGE:
1456** Let "ptr" be a pointer to some structure which is at the head of
1457** a null-terminated list. Then to sort the list call:
1458**
1459** ptr = msort(ptr,&(ptr->next),cmpfnc);
1460**
1461** In the above, "cmpfnc" is a pointer to a function which compares
1462** two instances of the structure and returns an integer, as in
1463** strcmp. The second argument is a pointer to the pointer to the
1464** second element of the linked list. This address is used to compute
1465** the offset to the "next" field within the structure. The offset to
1466** the "next" field must be constant for all structures in the list.
1467**
1468** The function returns a new pointer which is the head of the list
1469** after sorting.
1470**
1471** ALGORITHM:
1472** Merge-sort.
1473*/
1474
1475/*
1476** Return a pointer to the next structure in the linked list.
1477*/
drhba99af52001-10-25 20:37:16 +00001478#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001479
1480/*
1481** Inputs:
1482** a: A sorted, null-terminated linked list. (May be null).
1483** b: A sorted, null-terminated linked list. (May be null).
1484** cmp: A pointer to the comparison function.
1485** offset: Offset in the structure to the "next" field.
1486**
1487** Return Value:
1488** A pointer to the head of a sorted list containing the elements
1489** of both a and b.
1490**
1491** Side effects:
1492** The "next" pointers for elements in the lists a and b are
1493** changed.
1494*/
1495static char *merge(a,b,cmp,offset)
1496char *a;
1497char *b;
1498int (*cmp)();
1499int offset;
1500{
1501 char *ptr, *head;
1502
1503 if( a==0 ){
1504 head = b;
1505 }else if( b==0 ){
1506 head = a;
1507 }else{
1508 if( (*cmp)(a,b)<0 ){
1509 ptr = a;
1510 a = NEXT(a);
1511 }else{
1512 ptr = b;
1513 b = NEXT(b);
1514 }
1515 head = ptr;
1516 while( a && b ){
1517 if( (*cmp)(a,b)<0 ){
1518 NEXT(ptr) = a;
1519 ptr = a;
1520 a = NEXT(a);
1521 }else{
1522 NEXT(ptr) = b;
1523 ptr = b;
1524 b = NEXT(b);
1525 }
1526 }
1527 if( a ) NEXT(ptr) = a;
1528 else NEXT(ptr) = b;
1529 }
1530 return head;
1531}
1532
1533/*
1534** Inputs:
1535** list: Pointer to a singly-linked list of structures.
1536** next: Pointer to pointer to the second element of the list.
1537** cmp: A comparison function.
1538**
1539** Return Value:
1540** A pointer to the head of a sorted list containing the elements
1541** orginally in list.
1542**
1543** Side effects:
1544** The "next" pointers for elements in list are changed.
1545*/
1546#define LISTSIZE 30
1547char *msort(list,next,cmp)
1548char *list;
1549char **next;
1550int (*cmp)();
1551{
drhba99af52001-10-25 20:37:16 +00001552 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001553 char *ep;
1554 char *set[LISTSIZE];
1555 int i;
drhba99af52001-10-25 20:37:16 +00001556 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001557 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1558 while( list ){
1559 ep = list;
1560 list = NEXT(list);
1561 NEXT(ep) = 0;
1562 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1563 ep = merge(ep,set[i],cmp,offset);
1564 set[i] = 0;
1565 }
1566 set[i] = ep;
1567 }
1568 ep = 0;
1569 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1570 return ep;
1571}
1572/************************ From the file "option.c" **************************/
1573static char **argv;
1574static struct s_options *op;
1575static FILE *errstream;
1576
1577#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1578
1579/*
1580** Print the command line with a carrot pointing to the k-th character
1581** of the n-th field.
1582*/
1583static void errline(n,k,err)
1584int n;
1585int k;
1586FILE *err;
1587{
1588 int spcnt, i;
1589 spcnt = 0;
1590 if( argv[0] ) fprintf(err,"%s",argv[0]);
1591 spcnt = strlen(argv[0]) + 1;
1592 for(i=1; i<n && argv[i]; i++){
1593 fprintf(err," %s",argv[i]);
1594 spcnt += strlen(argv[i]+1);
1595 }
1596 spcnt += k;
1597 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1598 if( spcnt<20 ){
1599 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1600 }else{
1601 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1602 }
1603}
1604
1605/*
1606** Return the index of the N-th non-switch argument. Return -1
1607** if N is out of range.
1608*/
1609static int argindex(n)
1610int n;
1611{
1612 int i;
1613 int dashdash = 0;
1614 if( argv!=0 && *argv!=0 ){
1615 for(i=1; argv[i]; i++){
1616 if( dashdash || !ISOPT(argv[i]) ){
1617 if( n==0 ) return i;
1618 n--;
1619 }
1620 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1621 }
1622 }
1623 return -1;
1624}
1625
1626static char emsg[] = "Command line syntax error: ";
1627
1628/*
1629** Process a flag command line argument.
1630*/
1631static int handleflags(i,err)
1632int i;
1633FILE *err;
1634{
1635 int v;
1636 int errcnt = 0;
1637 int j;
1638 for(j=0; op[j].label; j++){
1639 if( strcmp(&argv[i][1],op[j].label)==0 ) break;
1640 }
1641 v = argv[i][0]=='-' ? 1 : 0;
1642 if( op[j].label==0 ){
1643 if( err ){
1644 fprintf(err,"%sundefined option.\n",emsg);
1645 errline(i,1,err);
1646 }
1647 errcnt++;
1648 }else if( op[j].type==OPT_FLAG ){
1649 *((int*)op[j].arg) = v;
1650 }else if( op[j].type==OPT_FFLAG ){
1651 (*(void(*)())(op[j].arg))(v);
1652 }else{
1653 if( err ){
1654 fprintf(err,"%smissing argument on switch.\n",emsg);
1655 errline(i,1,err);
1656 }
1657 errcnt++;
1658 }
1659 return errcnt;
1660}
1661
1662/*
1663** Process a command line switch which has an argument.
1664*/
1665static int handleswitch(i,err)
1666int i;
1667FILE *err;
1668{
1669 int lv = 0;
1670 double dv = 0.0;
1671 char *sv = 0, *end;
1672 char *cp;
1673 int j;
1674 int errcnt = 0;
1675 cp = strchr(argv[i],'=');
1676 *cp = 0;
1677 for(j=0; op[j].label; j++){
1678 if( strcmp(argv[i],op[j].label)==0 ) break;
1679 }
1680 *cp = '=';
1681 if( op[j].label==0 ){
1682 if( err ){
1683 fprintf(err,"%sundefined option.\n",emsg);
1684 errline(i,0,err);
1685 }
1686 errcnt++;
1687 }else{
1688 cp++;
1689 switch( op[j].type ){
1690 case OPT_FLAG:
1691 case OPT_FFLAG:
1692 if( err ){
1693 fprintf(err,"%soption requires an argument.\n",emsg);
1694 errline(i,0,err);
1695 }
1696 errcnt++;
1697 break;
1698 case OPT_DBL:
1699 case OPT_FDBL:
1700 dv = strtod(cp,&end);
1701 if( *end ){
1702 if( err ){
1703 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001704 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001705 }
1706 errcnt++;
1707 }
1708 break;
1709 case OPT_INT:
1710 case OPT_FINT:
1711 lv = strtol(cp,&end,0);
1712 if( *end ){
1713 if( err ){
1714 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001715 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001716 }
1717 errcnt++;
1718 }
1719 break;
1720 case OPT_STR:
1721 case OPT_FSTR:
1722 sv = cp;
1723 break;
1724 }
1725 switch( op[j].type ){
1726 case OPT_FLAG:
1727 case OPT_FFLAG:
1728 break;
1729 case OPT_DBL:
1730 *(double*)(op[j].arg) = dv;
1731 break;
1732 case OPT_FDBL:
1733 (*(void(*)())(op[j].arg))(dv);
1734 break;
1735 case OPT_INT:
1736 *(int*)(op[j].arg) = lv;
1737 break;
1738 case OPT_FINT:
1739 (*(void(*)())(op[j].arg))((int)lv);
1740 break;
1741 case OPT_STR:
1742 *(char**)(op[j].arg) = sv;
1743 break;
1744 case OPT_FSTR:
1745 (*(void(*)())(op[j].arg))(sv);
1746 break;
1747 }
1748 }
1749 return errcnt;
1750}
1751
drhb0c86772000-06-02 23:21:26 +00001752int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001753char **a;
1754struct s_options *o;
1755FILE *err;
1756{
1757 int errcnt = 0;
1758 argv = a;
1759 op = o;
1760 errstream = err;
1761 if( argv && *argv && op ){
1762 int i;
1763 for(i=1; argv[i]; i++){
1764 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1765 errcnt += handleflags(i,err);
1766 }else if( strchr(argv[i],'=') ){
1767 errcnt += handleswitch(i,err);
1768 }
1769 }
1770 }
1771 if( errcnt>0 ){
1772 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001773 OptPrint();
drh75897232000-05-29 14:26:00 +00001774 exit(1);
1775 }
1776 return 0;
1777}
1778
drhb0c86772000-06-02 23:21:26 +00001779int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001780 int cnt = 0;
1781 int dashdash = 0;
1782 int i;
1783 if( argv!=0 && argv[0]!=0 ){
1784 for(i=1; argv[i]; i++){
1785 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1786 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1787 }
1788 }
1789 return cnt;
1790}
1791
drhb0c86772000-06-02 23:21:26 +00001792char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001793int n;
1794{
1795 int i;
1796 i = argindex(n);
1797 return i>=0 ? argv[i] : 0;
1798}
1799
drhb0c86772000-06-02 23:21:26 +00001800void OptErr(n)
drh75897232000-05-29 14:26:00 +00001801int n;
1802{
1803 int i;
1804 i = argindex(n);
1805 if( i>=0 ) errline(i,0,errstream);
1806}
1807
drhb0c86772000-06-02 23:21:26 +00001808void OptPrint(){
drh75897232000-05-29 14:26:00 +00001809 int i;
1810 int max, len;
1811 max = 0;
1812 for(i=0; op[i].label; i++){
1813 len = strlen(op[i].label) + 1;
1814 switch( op[i].type ){
1815 case OPT_FLAG:
1816 case OPT_FFLAG:
1817 break;
1818 case OPT_INT:
1819 case OPT_FINT:
1820 len += 9; /* length of "<integer>" */
1821 break;
1822 case OPT_DBL:
1823 case OPT_FDBL:
1824 len += 6; /* length of "<real>" */
1825 break;
1826 case OPT_STR:
1827 case OPT_FSTR:
1828 len += 8; /* length of "<string>" */
1829 break;
1830 }
1831 if( len>max ) max = len;
1832 }
1833 for(i=0; op[i].label; i++){
1834 switch( op[i].type ){
1835 case OPT_FLAG:
1836 case OPT_FFLAG:
1837 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1838 break;
1839 case OPT_INT:
1840 case OPT_FINT:
1841 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001842 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001843 break;
1844 case OPT_DBL:
1845 case OPT_FDBL:
1846 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001847 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001848 break;
1849 case OPT_STR:
1850 case OPT_FSTR:
1851 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001852 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001853 break;
1854 }
1855 }
1856}
1857/*********************** From the file "parse.c" ****************************/
1858/*
1859** Input file parser for the LEMON parser generator.
1860*/
1861
1862/* The state of the parser */
1863struct pstate {
1864 char *filename; /* Name of the input file */
1865 int tokenlineno; /* Linenumber at which current token starts */
1866 int errorcnt; /* Number of errors so far */
1867 char *tokenstart; /* Text of current token */
1868 struct lemon *gp; /* Global state vector */
1869 enum e_state {
1870 INITIALIZE,
1871 WAITING_FOR_DECL_OR_RULE,
1872 WAITING_FOR_DECL_KEYWORD,
1873 WAITING_FOR_DECL_ARG,
1874 WAITING_FOR_PRECEDENCE_SYMBOL,
1875 WAITING_FOR_ARROW,
1876 IN_RHS,
1877 LHS_ALIAS_1,
1878 LHS_ALIAS_2,
1879 LHS_ALIAS_3,
1880 RHS_ALIAS_1,
1881 RHS_ALIAS_2,
1882 PRECEDENCE_MARK_1,
1883 PRECEDENCE_MARK_2,
1884 RESYNC_AFTER_RULE_ERROR,
1885 RESYNC_AFTER_DECL_ERROR,
1886 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001887 WAITING_FOR_DATATYPE_SYMBOL,
1888 WAITING_FOR_FALLBACK_ID
drh75897232000-05-29 14:26:00 +00001889 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001890 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001891 struct symbol *lhs; /* Left-hand side of current rule */
1892 char *lhsalias; /* Alias for the LHS */
1893 int nrhs; /* Number of right-hand side symbols seen */
1894 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1895 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1896 struct rule *prevrule; /* Previous rule parsed */
1897 char *declkeyword; /* Keyword of a declaration */
1898 char **declargslot; /* Where the declaration argument should be put */
1899 int *decllnslot; /* Where the declaration linenumber is put */
1900 enum e_assoc declassoc; /* Assign this association to decl arguments */
1901 int preccounter; /* Assign this precedence to decl arguments */
1902 struct rule *firstrule; /* Pointer to first rule in the grammar */
1903 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1904};
1905
1906/* Parse a single token */
1907static void parseonetoken(psp)
1908struct pstate *psp;
1909{
1910 char *x;
1911 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1912#if 0
1913 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1914 x,psp->state);
1915#endif
1916 switch( psp->state ){
1917 case INITIALIZE:
1918 psp->prevrule = 0;
1919 psp->preccounter = 0;
1920 psp->firstrule = psp->lastrule = 0;
1921 psp->gp->nrule = 0;
1922 /* Fall thru to next case */
1923 case WAITING_FOR_DECL_OR_RULE:
1924 if( x[0]=='%' ){
1925 psp->state = WAITING_FOR_DECL_KEYWORD;
1926 }else if( islower(x[0]) ){
1927 psp->lhs = Symbol_new(x);
1928 psp->nrhs = 0;
1929 psp->lhsalias = 0;
1930 psp->state = WAITING_FOR_ARROW;
1931 }else if( x[0]=='{' ){
1932 if( psp->prevrule==0 ){
1933 ErrorMsg(psp->filename,psp->tokenlineno,
1934"There is not prior rule opon which to attach the code \
1935fragment which begins on this line.");
1936 psp->errorcnt++;
1937 }else if( psp->prevrule->code!=0 ){
1938 ErrorMsg(psp->filename,psp->tokenlineno,
1939"Code fragment beginning on this line is not the first \
1940to follow the previous rule.");
1941 psp->errorcnt++;
1942 }else{
1943 psp->prevrule->line = psp->tokenlineno;
1944 psp->prevrule->code = &x[1];
1945 }
1946 }else if( x[0]=='[' ){
1947 psp->state = PRECEDENCE_MARK_1;
1948 }else{
1949 ErrorMsg(psp->filename,psp->tokenlineno,
1950 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
1951 x);
1952 psp->errorcnt++;
1953 }
1954 break;
1955 case PRECEDENCE_MARK_1:
1956 if( !isupper(x[0]) ){
1957 ErrorMsg(psp->filename,psp->tokenlineno,
1958 "The precedence symbol must be a terminal.");
1959 psp->errorcnt++;
1960 }else if( psp->prevrule==0 ){
1961 ErrorMsg(psp->filename,psp->tokenlineno,
1962 "There is no prior rule to assign precedence \"[%s]\".",x);
1963 psp->errorcnt++;
1964 }else if( psp->prevrule->precsym!=0 ){
1965 ErrorMsg(psp->filename,psp->tokenlineno,
1966"Precedence mark on this line is not the first \
1967to follow the previous rule.");
1968 psp->errorcnt++;
1969 }else{
1970 psp->prevrule->precsym = Symbol_new(x);
1971 }
1972 psp->state = PRECEDENCE_MARK_2;
1973 break;
1974 case PRECEDENCE_MARK_2:
1975 if( x[0]!=']' ){
1976 ErrorMsg(psp->filename,psp->tokenlineno,
1977 "Missing \"]\" on precedence mark.");
1978 psp->errorcnt++;
1979 }
1980 psp->state = WAITING_FOR_DECL_OR_RULE;
1981 break;
1982 case WAITING_FOR_ARROW:
1983 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
1984 psp->state = IN_RHS;
1985 }else if( x[0]=='(' ){
1986 psp->state = LHS_ALIAS_1;
1987 }else{
1988 ErrorMsg(psp->filename,psp->tokenlineno,
1989 "Expected to see a \":\" following the LHS symbol \"%s\".",
1990 psp->lhs->name);
1991 psp->errorcnt++;
1992 psp->state = RESYNC_AFTER_RULE_ERROR;
1993 }
1994 break;
1995 case LHS_ALIAS_1:
1996 if( isalpha(x[0]) ){
1997 psp->lhsalias = x;
1998 psp->state = LHS_ALIAS_2;
1999 }else{
2000 ErrorMsg(psp->filename,psp->tokenlineno,
2001 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2002 x,psp->lhs->name);
2003 psp->errorcnt++;
2004 psp->state = RESYNC_AFTER_RULE_ERROR;
2005 }
2006 break;
2007 case LHS_ALIAS_2:
2008 if( x[0]==')' ){
2009 psp->state = LHS_ALIAS_3;
2010 }else{
2011 ErrorMsg(psp->filename,psp->tokenlineno,
2012 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2013 psp->errorcnt++;
2014 psp->state = RESYNC_AFTER_RULE_ERROR;
2015 }
2016 break;
2017 case LHS_ALIAS_3:
2018 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2019 psp->state = IN_RHS;
2020 }else{
2021 ErrorMsg(psp->filename,psp->tokenlineno,
2022 "Missing \"->\" following: \"%s(%s)\".",
2023 psp->lhs->name,psp->lhsalias);
2024 psp->errorcnt++;
2025 psp->state = RESYNC_AFTER_RULE_ERROR;
2026 }
2027 break;
2028 case IN_RHS:
2029 if( x[0]=='.' ){
2030 struct rule *rp;
2031 rp = (struct rule *)malloc( sizeof(struct rule) +
2032 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
2033 if( rp==0 ){
2034 ErrorMsg(psp->filename,psp->tokenlineno,
2035 "Can't allocate enough memory for this rule.");
2036 psp->errorcnt++;
2037 psp->prevrule = 0;
2038 }else{
2039 int i;
2040 rp->ruleline = psp->tokenlineno;
2041 rp->rhs = (struct symbol**)&rp[1];
2042 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2043 for(i=0; i<psp->nrhs; i++){
2044 rp->rhs[i] = psp->rhs[i];
2045 rp->rhsalias[i] = psp->alias[i];
2046 }
2047 rp->lhs = psp->lhs;
2048 rp->lhsalias = psp->lhsalias;
2049 rp->nrhs = psp->nrhs;
2050 rp->code = 0;
2051 rp->precsym = 0;
2052 rp->index = psp->gp->nrule++;
2053 rp->nextlhs = rp->lhs->rule;
2054 rp->lhs->rule = rp;
2055 rp->next = 0;
2056 if( psp->firstrule==0 ){
2057 psp->firstrule = psp->lastrule = rp;
2058 }else{
2059 psp->lastrule->next = rp;
2060 psp->lastrule = rp;
2061 }
2062 psp->prevrule = rp;
2063 }
2064 psp->state = WAITING_FOR_DECL_OR_RULE;
2065 }else if( isalpha(x[0]) ){
2066 if( psp->nrhs>=MAXRHS ){
2067 ErrorMsg(psp->filename,psp->tokenlineno,
2068 "Too many symbol on RHS or rule beginning at \"%s\".",
2069 x);
2070 psp->errorcnt++;
2071 psp->state = RESYNC_AFTER_RULE_ERROR;
2072 }else{
2073 psp->rhs[psp->nrhs] = Symbol_new(x);
2074 psp->alias[psp->nrhs] = 0;
2075 psp->nrhs++;
2076 }
2077 }else if( x[0]=='(' && psp->nrhs>0 ){
2078 psp->state = RHS_ALIAS_1;
2079 }else{
2080 ErrorMsg(psp->filename,psp->tokenlineno,
2081 "Illegal character on RHS of rule: \"%s\".",x);
2082 psp->errorcnt++;
2083 psp->state = RESYNC_AFTER_RULE_ERROR;
2084 }
2085 break;
2086 case RHS_ALIAS_1:
2087 if( isalpha(x[0]) ){
2088 psp->alias[psp->nrhs-1] = x;
2089 psp->state = RHS_ALIAS_2;
2090 }else{
2091 ErrorMsg(psp->filename,psp->tokenlineno,
2092 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2093 x,psp->rhs[psp->nrhs-1]->name);
2094 psp->errorcnt++;
2095 psp->state = RESYNC_AFTER_RULE_ERROR;
2096 }
2097 break;
2098 case RHS_ALIAS_2:
2099 if( x[0]==')' ){
2100 psp->state = IN_RHS;
2101 }else{
2102 ErrorMsg(psp->filename,psp->tokenlineno,
2103 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2104 psp->errorcnt++;
2105 psp->state = RESYNC_AFTER_RULE_ERROR;
2106 }
2107 break;
2108 case WAITING_FOR_DECL_KEYWORD:
2109 if( isalpha(x[0]) ){
2110 psp->declkeyword = x;
2111 psp->declargslot = 0;
2112 psp->decllnslot = 0;
2113 psp->state = WAITING_FOR_DECL_ARG;
2114 if( strcmp(x,"name")==0 ){
2115 psp->declargslot = &(psp->gp->name);
2116 }else if( strcmp(x,"include")==0 ){
2117 psp->declargslot = &(psp->gp->include);
2118 psp->decllnslot = &psp->gp->includeln;
2119 }else if( strcmp(x,"code")==0 ){
2120 psp->declargslot = &(psp->gp->extracode);
2121 psp->decllnslot = &psp->gp->extracodeln;
2122 }else if( strcmp(x,"token_destructor")==0 ){
2123 psp->declargslot = &psp->gp->tokendest;
2124 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00002125 }else if( strcmp(x,"default_destructor")==0 ){
2126 psp->declargslot = &psp->gp->vardest;
2127 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00002128 }else if( strcmp(x,"token_prefix")==0 ){
2129 psp->declargslot = &psp->gp->tokenprefix;
2130 }else if( strcmp(x,"syntax_error")==0 ){
2131 psp->declargslot = &(psp->gp->error);
2132 psp->decllnslot = &psp->gp->errorln;
2133 }else if( strcmp(x,"parse_accept")==0 ){
2134 psp->declargslot = &(psp->gp->accept);
2135 psp->decllnslot = &psp->gp->acceptln;
2136 }else if( strcmp(x,"parse_failure")==0 ){
2137 psp->declargslot = &(psp->gp->failure);
2138 psp->decllnslot = &psp->gp->failureln;
2139 }else if( strcmp(x,"stack_overflow")==0 ){
2140 psp->declargslot = &(psp->gp->overflow);
2141 psp->decllnslot = &psp->gp->overflowln;
2142 }else if( strcmp(x,"extra_argument")==0 ){
2143 psp->declargslot = &(psp->gp->arg);
2144 }else if( strcmp(x,"token_type")==0 ){
2145 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00002146 }else if( strcmp(x,"default_type")==0 ){
2147 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00002148 }else if( strcmp(x,"stack_size")==0 ){
2149 psp->declargslot = &(psp->gp->stacksize);
2150 }else if( strcmp(x,"start_symbol")==0 ){
2151 psp->declargslot = &(psp->gp->start);
2152 }else if( strcmp(x,"left")==0 ){
2153 psp->preccounter++;
2154 psp->declassoc = LEFT;
2155 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2156 }else if( strcmp(x,"right")==0 ){
2157 psp->preccounter++;
2158 psp->declassoc = RIGHT;
2159 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2160 }else if( strcmp(x,"nonassoc")==0 ){
2161 psp->preccounter++;
2162 psp->declassoc = NONE;
2163 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2164 }else if( strcmp(x,"destructor")==0 ){
2165 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2166 }else if( strcmp(x,"type")==0 ){
2167 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002168 }else if( strcmp(x,"fallback")==0 ){
2169 psp->fallback = 0;
2170 psp->state = WAITING_FOR_FALLBACK_ID;
drh75897232000-05-29 14:26:00 +00002171 }else{
2172 ErrorMsg(psp->filename,psp->tokenlineno,
2173 "Unknown declaration keyword: \"%%%s\".",x);
2174 psp->errorcnt++;
2175 psp->state = RESYNC_AFTER_DECL_ERROR;
2176 }
2177 }else{
2178 ErrorMsg(psp->filename,psp->tokenlineno,
2179 "Illegal declaration keyword: \"%s\".",x);
2180 psp->errorcnt++;
2181 psp->state = RESYNC_AFTER_DECL_ERROR;
2182 }
2183 break;
2184 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2185 if( !isalpha(x[0]) ){
2186 ErrorMsg(psp->filename,psp->tokenlineno,
2187 "Symbol name missing after %destructor keyword");
2188 psp->errorcnt++;
2189 psp->state = RESYNC_AFTER_DECL_ERROR;
2190 }else{
2191 struct symbol *sp = Symbol_new(x);
2192 psp->declargslot = &sp->destructor;
2193 psp->decllnslot = &sp->destructorln;
2194 psp->state = WAITING_FOR_DECL_ARG;
2195 }
2196 break;
2197 case WAITING_FOR_DATATYPE_SYMBOL:
2198 if( !isalpha(x[0]) ){
2199 ErrorMsg(psp->filename,psp->tokenlineno,
2200 "Symbol name missing after %destructor keyword");
2201 psp->errorcnt++;
2202 psp->state = RESYNC_AFTER_DECL_ERROR;
2203 }else{
2204 struct symbol *sp = Symbol_new(x);
2205 psp->declargslot = &sp->datatype;
2206 psp->decllnslot = 0;
2207 psp->state = WAITING_FOR_DECL_ARG;
2208 }
2209 break;
2210 case WAITING_FOR_PRECEDENCE_SYMBOL:
2211 if( x[0]=='.' ){
2212 psp->state = WAITING_FOR_DECL_OR_RULE;
2213 }else if( isupper(x[0]) ){
2214 struct symbol *sp;
2215 sp = Symbol_new(x);
2216 if( sp->prec>=0 ){
2217 ErrorMsg(psp->filename,psp->tokenlineno,
2218 "Symbol \"%s\" has already be given a precedence.",x);
2219 psp->errorcnt++;
2220 }else{
2221 sp->prec = psp->preccounter;
2222 sp->assoc = psp->declassoc;
2223 }
2224 }else{
2225 ErrorMsg(psp->filename,psp->tokenlineno,
2226 "Can't assign a precedence to \"%s\".",x);
2227 psp->errorcnt++;
2228 }
2229 break;
2230 case WAITING_FOR_DECL_ARG:
2231 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2232 if( *(psp->declargslot)!=0 ){
2233 ErrorMsg(psp->filename,psp->tokenlineno,
2234 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2235 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2236 psp->errorcnt++;
2237 psp->state = RESYNC_AFTER_DECL_ERROR;
2238 }else{
2239 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2240 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2241 psp->state = WAITING_FOR_DECL_OR_RULE;
2242 }
2243 }else{
2244 ErrorMsg(psp->filename,psp->tokenlineno,
2245 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2246 psp->errorcnt++;
2247 psp->state = RESYNC_AFTER_DECL_ERROR;
2248 }
2249 break;
drh0bd1f4e2002-06-06 18:54:39 +00002250 case WAITING_FOR_FALLBACK_ID:
2251 if( x[0]=='.' ){
2252 psp->state = WAITING_FOR_DECL_OR_RULE;
2253 }else if( !isupper(x[0]) ){
2254 ErrorMsg(psp->filename, psp->tokenlineno,
2255 "%%fallback argument \"%s\" should be a token", x);
2256 psp->errorcnt++;
2257 }else{
2258 struct symbol *sp = Symbol_new(x);
2259 if( psp->fallback==0 ){
2260 psp->fallback = sp;
2261 }else if( sp->fallback ){
2262 ErrorMsg(psp->filename, psp->tokenlineno,
2263 "More than one fallback assigned to token %s", x);
2264 psp->errorcnt++;
2265 }else{
2266 sp->fallback = psp->fallback;
2267 psp->gp->has_fallback = 1;
2268 }
2269 }
2270 break;
drh75897232000-05-29 14:26:00 +00002271 case RESYNC_AFTER_RULE_ERROR:
2272/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2273** break; */
2274 case RESYNC_AFTER_DECL_ERROR:
2275 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2276 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2277 break;
2278 }
2279}
2280
2281/* In spite of its name, this function is really a scanner. It read
2282** in the entire input file (all at once) then tokenizes it. Each
2283** token is passed to the function "parseonetoken" which builds all
2284** the appropriate data structures in the global state vector "gp".
2285*/
2286void Parse(gp)
2287struct lemon *gp;
2288{
2289 struct pstate ps;
2290 FILE *fp;
2291 char *filebuf;
2292 int filesize;
2293 int lineno;
2294 int c;
2295 char *cp, *nextcp;
2296 int startline = 0;
2297
2298 ps.gp = gp;
2299 ps.filename = gp->filename;
2300 ps.errorcnt = 0;
2301 ps.state = INITIALIZE;
2302
2303 /* Begin by reading the input file */
2304 fp = fopen(ps.filename,"rb");
2305 if( fp==0 ){
2306 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2307 gp->errorcnt++;
2308 return;
2309 }
2310 fseek(fp,0,2);
2311 filesize = ftell(fp);
2312 rewind(fp);
2313 filebuf = (char *)malloc( filesize+1 );
2314 if( filebuf==0 ){
2315 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2316 filesize+1);
2317 gp->errorcnt++;
2318 return;
2319 }
2320 if( fread(filebuf,1,filesize,fp)!=filesize ){
2321 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2322 filesize);
2323 free(filebuf);
2324 gp->errorcnt++;
2325 return;
2326 }
2327 fclose(fp);
2328 filebuf[filesize] = 0;
2329
2330 /* Now scan the text of the input file */
2331 lineno = 1;
2332 for(cp=filebuf; (c= *cp)!=0; ){
2333 if( c=='\n' ) lineno++; /* Keep track of the line number */
2334 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2335 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2336 cp+=2;
2337 while( (c= *cp)!=0 && c!='\n' ) cp++;
2338 continue;
2339 }
2340 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2341 cp+=2;
2342 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2343 if( c=='\n' ) lineno++;
2344 cp++;
2345 }
2346 if( c ) cp++;
2347 continue;
2348 }
2349 ps.tokenstart = cp; /* Mark the beginning of the token */
2350 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2351 if( c=='\"' ){ /* String literals */
2352 cp++;
2353 while( (c= *cp)!=0 && c!='\"' ){
2354 if( c=='\n' ) lineno++;
2355 cp++;
2356 }
2357 if( c==0 ){
2358 ErrorMsg(ps.filename,startline,
2359"String starting on this line is not terminated before the end of the file.");
2360 ps.errorcnt++;
2361 nextcp = cp;
2362 }else{
2363 nextcp = cp+1;
2364 }
2365 }else if( c=='{' ){ /* A block of C code */
2366 int level;
2367 cp++;
2368 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2369 if( c=='\n' ) lineno++;
2370 else if( c=='{' ) level++;
2371 else if( c=='}' ) level--;
2372 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2373 int prevc;
2374 cp = &cp[2];
2375 prevc = 0;
2376 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2377 if( c=='\n' ) lineno++;
2378 prevc = c;
2379 cp++;
2380 }
2381 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2382 cp = &cp[2];
2383 while( (c= *cp)!=0 && c!='\n' ) cp++;
2384 if( c ) lineno++;
2385 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2386 int startchar, prevc;
2387 startchar = c;
2388 prevc = 0;
2389 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2390 if( c=='\n' ) lineno++;
2391 if( prevc=='\\' ) prevc = 0;
2392 else prevc = c;
2393 }
2394 }
2395 }
2396 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002397 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002398"C code starting on this line is not terminated before the end of the file.");
2399 ps.errorcnt++;
2400 nextcp = cp;
2401 }else{
2402 nextcp = cp+1;
2403 }
2404 }else if( isalnum(c) ){ /* Identifiers */
2405 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2406 nextcp = cp;
2407 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2408 cp += 3;
2409 nextcp = cp;
2410 }else{ /* All other (one character) operators */
2411 cp++;
2412 nextcp = cp;
2413 }
2414 c = *cp;
2415 *cp = 0; /* Null terminate the token */
2416 parseonetoken(&ps); /* Parse the token */
2417 *cp = c; /* Restore the buffer */
2418 cp = nextcp;
2419 }
2420 free(filebuf); /* Release the buffer after parsing */
2421 gp->rule = ps.firstrule;
2422 gp->errorcnt = ps.errorcnt;
2423}
2424/*************************** From the file "plink.c" *********************/
2425/*
2426** Routines processing configuration follow-set propagation links
2427** in the LEMON parser generator.
2428*/
2429static struct plink *plink_freelist = 0;
2430
2431/* Allocate a new plink */
2432struct plink *Plink_new(){
2433 struct plink *new;
2434
2435 if( plink_freelist==0 ){
2436 int i;
2437 int amt = 100;
2438 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2439 if( plink_freelist==0 ){
2440 fprintf(stderr,
2441 "Unable to allocate memory for a new follow-set propagation link.\n");
2442 exit(1);
2443 }
2444 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2445 plink_freelist[amt-1].next = 0;
2446 }
2447 new = plink_freelist;
2448 plink_freelist = plink_freelist->next;
2449 return new;
2450}
2451
2452/* Add a plink to a plink list */
2453void Plink_add(plpp,cfp)
2454struct plink **plpp;
2455struct config *cfp;
2456{
2457 struct plink *new;
2458 new = Plink_new();
2459 new->next = *plpp;
2460 *plpp = new;
2461 new->cfp = cfp;
2462}
2463
2464/* Transfer every plink on the list "from" to the list "to" */
2465void Plink_copy(to,from)
2466struct plink **to;
2467struct plink *from;
2468{
2469 struct plink *nextpl;
2470 while( from ){
2471 nextpl = from->next;
2472 from->next = *to;
2473 *to = from;
2474 from = nextpl;
2475 }
2476}
2477
2478/* Delete every plink on the list */
2479void Plink_delete(plp)
2480struct plink *plp;
2481{
2482 struct plink *nextpl;
2483
2484 while( plp ){
2485 nextpl = plp->next;
2486 plp->next = plink_freelist;
2487 plink_freelist = plp;
2488 plp = nextpl;
2489 }
2490}
2491/*********************** From the file "report.c" **************************/
2492/*
2493** Procedures for generating reports and tables in the LEMON parser generator.
2494*/
2495
2496/* Generate a filename with the given suffix. Space to hold the
2497** name comes from malloc() and must be freed by the calling
2498** function.
2499*/
2500PRIVATE char *file_makename(lemp,suffix)
2501struct lemon *lemp;
2502char *suffix;
2503{
2504 char *name;
2505 char *cp;
2506
2507 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2508 if( name==0 ){
2509 fprintf(stderr,"Can't allocate space for a filename.\n");
2510 exit(1);
2511 }
2512 strcpy(name,lemp->filename);
2513 cp = strrchr(name,'.');
2514 if( cp ) *cp = 0;
2515 strcat(name,suffix);
2516 return name;
2517}
2518
2519/* Open a file with a name based on the name of the input file,
2520** but with a different (specified) suffix, and return a pointer
2521** to the stream */
2522PRIVATE FILE *file_open(lemp,suffix,mode)
2523struct lemon *lemp;
2524char *suffix;
2525char *mode;
2526{
2527 FILE *fp;
2528
2529 if( lemp->outname ) free(lemp->outname);
2530 lemp->outname = file_makename(lemp, suffix);
2531 fp = fopen(lemp->outname,mode);
2532 if( fp==0 && *mode=='w' ){
2533 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2534 lemp->errorcnt++;
2535 return 0;
2536 }
2537 return fp;
2538}
2539
2540/* Duplicate the input file without comments and without actions
2541** on rules */
2542void Reprint(lemp)
2543struct lemon *lemp;
2544{
2545 struct rule *rp;
2546 struct symbol *sp;
2547 int i, j, maxlen, len, ncolumns, skip;
2548 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2549 maxlen = 10;
2550 for(i=0; i<lemp->nsymbol; i++){
2551 sp = lemp->symbols[i];
2552 len = strlen(sp->name);
2553 if( len>maxlen ) maxlen = len;
2554 }
2555 ncolumns = 76/(maxlen+5);
2556 if( ncolumns<1 ) ncolumns = 1;
2557 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2558 for(i=0; i<skip; i++){
2559 printf("//");
2560 for(j=i; j<lemp->nsymbol; j+=skip){
2561 sp = lemp->symbols[j];
2562 assert( sp->index==j );
2563 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2564 }
2565 printf("\n");
2566 }
2567 for(rp=lemp->rule; rp; rp=rp->next){
2568 printf("%s",rp->lhs->name);
2569/* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2570 printf(" ::=");
2571 for(i=0; i<rp->nrhs; i++){
2572 printf(" %s",rp->rhs[i]->name);
2573/* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2574 }
2575 printf(".");
2576 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2577/* if( rp->code ) printf("\n %s",rp->code); */
2578 printf("\n");
2579 }
2580}
2581
2582void ConfigPrint(fp,cfp)
2583FILE *fp;
2584struct config *cfp;
2585{
2586 struct rule *rp;
2587 int i;
2588 rp = cfp->rp;
2589 fprintf(fp,"%s ::=",rp->lhs->name);
2590 for(i=0; i<=rp->nrhs; i++){
2591 if( i==cfp->dot ) fprintf(fp," *");
2592 if( i==rp->nrhs ) break;
2593 fprintf(fp," %s",rp->rhs[i]->name);
2594 }
2595}
2596
2597/* #define TEST */
2598#ifdef TEST
2599/* Print a set */
2600PRIVATE void SetPrint(out,set,lemp)
2601FILE *out;
2602char *set;
2603struct lemon *lemp;
2604{
2605 int i;
2606 char *spacer;
2607 spacer = "";
2608 fprintf(out,"%12s[","");
2609 for(i=0; i<lemp->nterminal; i++){
2610 if( SetFind(set,i) ){
2611 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2612 spacer = " ";
2613 }
2614 }
2615 fprintf(out,"]\n");
2616}
2617
2618/* Print a plink chain */
2619PRIVATE void PlinkPrint(out,plp,tag)
2620FILE *out;
2621struct plink *plp;
2622char *tag;
2623{
2624 while( plp ){
2625 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->index);
2626 ConfigPrint(out,plp->cfp);
2627 fprintf(out,"\n");
2628 plp = plp->next;
2629 }
2630}
2631#endif
2632
2633/* Print an action to the given file descriptor. Return FALSE if
2634** nothing was actually printed.
2635*/
2636int PrintAction(struct action *ap, FILE *fp, int indent){
2637 int result = 1;
2638 switch( ap->type ){
2639 case SHIFT:
2640 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->index);
2641 break;
2642 case REDUCE:
2643 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2644 break;
2645 case ACCEPT:
2646 fprintf(fp,"%*s accept",indent,ap->sp->name);
2647 break;
2648 case ERROR:
2649 fprintf(fp,"%*s error",indent,ap->sp->name);
2650 break;
2651 case CONFLICT:
2652 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2653 indent,ap->sp->name,ap->x.rp->index);
2654 break;
2655 case SH_RESOLVED:
2656 case RD_RESOLVED:
2657 case NOT_USED:
2658 result = 0;
2659 break;
2660 }
2661 return result;
2662}
2663
2664/* Generate the "y.output" log file */
2665void ReportOutput(lemp)
2666struct lemon *lemp;
2667{
2668 int i;
2669 struct state *stp;
2670 struct config *cfp;
2671 struct action *ap;
2672 FILE *fp;
2673
2674 fp = file_open(lemp,".out","w");
2675 if( fp==0 ) return;
2676 fprintf(fp," \b");
2677 for(i=0; i<lemp->nstate; i++){
2678 stp = lemp->sorted[i];
2679 fprintf(fp,"State %d:\n",stp->index);
2680 if( lemp->basisflag ) cfp=stp->bp;
2681 else cfp=stp->cfp;
2682 while( cfp ){
2683 char buf[20];
2684 if( cfp->dot==cfp->rp->nrhs ){
2685 sprintf(buf,"(%d)",cfp->rp->index);
2686 fprintf(fp," %5s ",buf);
2687 }else{
2688 fprintf(fp," ");
2689 }
2690 ConfigPrint(fp,cfp);
2691 fprintf(fp,"\n");
2692#ifdef TEST
2693 SetPrint(fp,cfp->fws,lemp);
2694 PlinkPrint(fp,cfp->fplp,"To ");
2695 PlinkPrint(fp,cfp->bplp,"From");
2696#endif
2697 if( lemp->basisflag ) cfp=cfp->bp;
2698 else cfp=cfp->next;
2699 }
2700 fprintf(fp,"\n");
2701 for(ap=stp->ap; ap; ap=ap->next){
2702 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2703 }
2704 fprintf(fp,"\n");
2705 }
2706 fclose(fp);
2707 return;
2708}
2709
2710/* Search for the file "name" which is in the same directory as
2711** the exacutable */
2712PRIVATE char *pathsearch(argv0,name,modemask)
2713char *argv0;
2714char *name;
2715int modemask;
2716{
2717 char *pathlist;
2718 char *path,*cp;
2719 char c;
2720 extern int access();
2721
2722#ifdef __WIN32__
2723 cp = strrchr(argv0,'\\');
2724#else
2725 cp = strrchr(argv0,'/');
2726#endif
2727 if( cp ){
2728 c = *cp;
2729 *cp = 0;
2730 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2731 if( path ) sprintf(path,"%s/%s",argv0,name);
2732 *cp = c;
2733 }else{
2734 extern char *getenv();
2735 pathlist = getenv("PATH");
2736 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2737 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2738 if( path!=0 ){
2739 while( *pathlist ){
2740 cp = strchr(pathlist,':');
2741 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2742 c = *cp;
2743 *cp = 0;
2744 sprintf(path,"%s/%s",pathlist,name);
2745 *cp = c;
2746 if( c==0 ) pathlist = "";
2747 else pathlist = &cp[1];
2748 if( access(path,modemask)==0 ) break;
2749 }
2750 }
2751 }
2752 return path;
2753}
2754
2755/* Given an action, compute the integer value for that action
2756** which is to be put in the action table of the generated machine.
2757** Return negative if no action should be generated.
2758*/
2759PRIVATE int compute_action(lemp,ap)
2760struct lemon *lemp;
2761struct action *ap;
2762{
2763 int act;
2764 switch( ap->type ){
2765 case SHIFT: act = ap->x.stp->index; break;
2766 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2767 case ERROR: act = lemp->nstate + lemp->nrule; break;
2768 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2769 default: act = -1; break;
2770 }
2771 return act;
2772}
2773
2774#define LINESIZE 1000
2775/* The next cluster of routines are for reading the template file
2776** and writing the results to the generated parser */
2777/* The first function transfers data from "in" to "out" until
2778** a line is seen which begins with "%%". The line number is
2779** tracked.
2780**
2781** if name!=0, then any word that begin with "Parse" is changed to
2782** begin with *name instead.
2783*/
2784PRIVATE void tplt_xfer(name,in,out,lineno)
2785char *name;
2786FILE *in;
2787FILE *out;
2788int *lineno;
2789{
2790 int i, iStart;
2791 char line[LINESIZE];
2792 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2793 (*lineno)++;
2794 iStart = 0;
2795 if( name ){
2796 for(i=0; line[i]; i++){
2797 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2798 && (i==0 || !isalpha(line[i-1]))
2799 ){
2800 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2801 fprintf(out,"%s",name);
2802 i += 4;
2803 iStart = i+1;
2804 }
2805 }
2806 }
2807 fprintf(out,"%s",&line[iStart]);
2808 }
2809}
2810
2811/* The next function finds the template file and opens it, returning
2812** a pointer to the opened file. */
2813PRIVATE FILE *tplt_open(lemp)
2814struct lemon *lemp;
2815{
2816 static char templatename[] = "lempar.c";
2817 char buf[1000];
2818 FILE *in;
2819 char *tpltname;
2820 char *cp;
2821
2822 cp = strrchr(lemp->filename,'.');
2823 if( cp ){
drh8b582012003-10-21 13:16:03 +00002824 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00002825 }else{
2826 sprintf(buf,"%s.lt",lemp->filename);
2827 }
2828 if( access(buf,004)==0 ){
2829 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00002830 }else if( access(templatename,004)==0 ){
2831 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00002832 }else{
2833 tpltname = pathsearch(lemp->argv0,templatename,0);
2834 }
2835 if( tpltname==0 ){
2836 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
2837 templatename);
2838 lemp->errorcnt++;
2839 return 0;
2840 }
2841 in = fopen(tpltname,"r");
2842 if( in==0 ){
2843 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
2844 lemp->errorcnt++;
2845 return 0;
2846 }
2847 return in;
2848}
2849
2850/* Print a string to the file and keep the linenumber up to date */
2851PRIVATE void tplt_print(out,lemp,str,strln,lineno)
2852FILE *out;
2853struct lemon *lemp;
2854char *str;
2855int strln;
2856int *lineno;
2857{
2858 if( str==0 ) return;
2859 fprintf(out,"#line %d \"%s\"\n",strln,lemp->filename); (*lineno)++;
2860 while( *str ){
2861 if( *str=='\n' ) (*lineno)++;
2862 putc(*str,out);
2863 str++;
2864 }
2865 fprintf(out,"\n#line %d \"%s\"\n",*lineno+2,lemp->outname); (*lineno)+=2;
2866 return;
2867}
2868
2869/*
2870** The following routine emits code for the destructor for the
2871** symbol sp
2872*/
2873void emit_destructor_code(out,sp,lemp,lineno)
2874FILE *out;
2875struct symbol *sp;
2876struct lemon *lemp;
2877int *lineno;
2878{
drhcc83b6e2004-04-23 23:38:42 +00002879 char *cp = 0;
drh75897232000-05-29 14:26:00 +00002880
2881 int linecnt = 0;
2882 if( sp->type==TERMINAL ){
2883 cp = lemp->tokendest;
2884 if( cp==0 ) return;
2885 fprintf(out,"#line %d \"%s\"\n{",lemp->tokendestln,lemp->filename);
drh960e8c62001-04-03 16:53:21 +00002886 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00002887 cp = sp->destructor;
drh75897232000-05-29 14:26:00 +00002888 fprintf(out,"#line %d \"%s\"\n{",sp->destructorln,lemp->filename);
drh960e8c62001-04-03 16:53:21 +00002889 }else if( lemp->vardest ){
2890 cp = lemp->vardest;
2891 if( cp==0 ) return;
2892 fprintf(out,"#line %d \"%s\"\n{",lemp->vardestln,lemp->filename);
drhcc83b6e2004-04-23 23:38:42 +00002893 }else{
2894 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00002895 }
2896 for(; *cp; cp++){
2897 if( *cp=='$' && cp[1]=='$' ){
2898 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
2899 cp++;
2900 continue;
2901 }
2902 if( *cp=='\n' ) linecnt++;
2903 fputc(*cp,out);
2904 }
2905 (*lineno) += 3 + linecnt;
2906 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2907 return;
2908}
2909
2910/*
drh960e8c62001-04-03 16:53:21 +00002911** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00002912*/
2913int has_destructor(sp, lemp)
2914struct symbol *sp;
2915struct lemon *lemp;
2916{
2917 int ret;
2918 if( sp->type==TERMINAL ){
2919 ret = lemp->tokendest!=0;
2920 }else{
drh960e8c62001-04-03 16:53:21 +00002921 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00002922 }
2923 return ret;
2924}
2925
2926/*
2927** Generate code which executes when the rule "rp" is reduced. Write
2928** the code to "out". Make sure lineno stays up-to-date.
2929*/
2930PRIVATE void emit_code(out,rp,lemp,lineno)
2931FILE *out;
2932struct rule *rp;
2933struct lemon *lemp;
2934int *lineno;
2935{
2936 char *cp, *xp;
2937 int linecnt = 0;
2938 int i;
2939 char lhsused = 0; /* True if the LHS element has been used */
2940 char used[MAXRHS]; /* True for each RHS element which is used */
2941
2942 for(i=0; i<rp->nrhs; i++) used[i] = 0;
2943 lhsused = 0;
2944
2945 /* Generate code to do the reduce action */
2946 if( rp->code ){
2947 fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
2948 for(cp=rp->code; *cp; cp++){
drh7218ac72002-03-10 21:21:00 +00002949 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
drh75897232000-05-29 14:26:00 +00002950 char saved;
drh7218ac72002-03-10 21:21:00 +00002951 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
drh75897232000-05-29 14:26:00 +00002952 saved = *xp;
2953 *xp = 0;
2954 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
2955 fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum);
2956 cp = xp;
2957 lhsused = 1;
2958 }else{
2959 for(i=0; i<rp->nrhs; i++){
2960 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
2961 fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum);
2962 cp = xp;
2963 used[i] = 1;
2964 break;
2965 }
2966 }
2967 }
2968 *xp = saved;
2969 }
2970 if( *cp=='\n' ) linecnt++;
2971 fputc(*cp,out);
2972 } /* End loop */
2973 (*lineno) += 3 + linecnt;
2974 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2975 } /* End if( rp->code ) */
2976
2977 /* Check to make sure the LHS has been used */
2978 if( rp->lhsalias && !lhsused ){
2979 ErrorMsg(lemp->filename,rp->ruleline,
2980 "Label \"%s\" for \"%s(%s)\" is never used.",
2981 rp->lhsalias,rp->lhs->name,rp->lhsalias);
2982 lemp->errorcnt++;
2983 }
2984
2985 /* Generate destructor code for RHS symbols which are not used in the
2986 ** reduce code */
2987 for(i=0; i<rp->nrhs; i++){
2988 if( rp->rhsalias[i] && !used[i] ){
2989 ErrorMsg(lemp->filename,rp->ruleline,
drh960e8c62001-04-03 16:53:21 +00002990 "Label %s for \"%s(%s)\" is never used.",
drh75897232000-05-29 14:26:00 +00002991 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
2992 lemp->errorcnt++;
2993 }else if( rp->rhsalias[i]==0 ){
2994 if( has_destructor(rp->rhs[i],lemp) ){
2995 fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n",
2996 rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++;
2997 }else{
2998 fprintf(out," /* No destructor defined for %s */\n",
2999 rp->rhs[i]->name);
3000 (*lineno)++;
3001 }
3002 }
3003 }
3004 return;
3005}
3006
3007/*
3008** Print the definition of the union used for the parser's data stack.
3009** This union contains fields for every possible data type for tokens
3010** and nonterminals. In the process of computing and printing this
3011** union, also set the ".dtnum" field of every terminal and nonterminal
3012** symbol.
3013*/
3014void print_stack_union(out,lemp,plineno,mhflag)
3015FILE *out; /* The output stream */
3016struct lemon *lemp; /* The main info structure for this parser */
3017int *plineno; /* Pointer to the line number */
3018int mhflag; /* True if generating makeheaders output */
3019{
3020 int lineno = *plineno; /* The line number of the output */
3021 char **types; /* A hash table of datatypes */
3022 int arraysize; /* Size of the "types" array */
3023 int maxdtlength; /* Maximum length of any ".datatype" field. */
3024 char *stddt; /* Standardized name for a datatype */
3025 int i,j; /* Loop counters */
3026 int hash; /* For hashing the name of a type */
3027 char *name; /* Name of the parser */
3028
3029 /* Allocate and initialize types[] and allocate stddt[] */
3030 arraysize = lemp->nsymbol * 2;
3031 types = (char**)malloc( arraysize * sizeof(char*) );
3032 for(i=0; i<arraysize; i++) types[i] = 0;
3033 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003034 if( lemp->vartype ){
3035 maxdtlength = strlen(lemp->vartype);
3036 }
drh75897232000-05-29 14:26:00 +00003037 for(i=0; i<lemp->nsymbol; i++){
3038 int len;
3039 struct symbol *sp = lemp->symbols[i];
3040 if( sp->datatype==0 ) continue;
3041 len = strlen(sp->datatype);
3042 if( len>maxdtlength ) maxdtlength = len;
3043 }
3044 stddt = (char*)malloc( maxdtlength*2 + 1 );
3045 if( types==0 || stddt==0 ){
3046 fprintf(stderr,"Out of memory.\n");
3047 exit(1);
3048 }
3049
3050 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3051 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003052 ** used for terminal symbols. If there is no %default_type defined then
3053 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3054 ** a datatype using the %type directive.
3055 */
drh75897232000-05-29 14:26:00 +00003056 for(i=0; i<lemp->nsymbol; i++){
3057 struct symbol *sp = lemp->symbols[i];
3058 char *cp;
3059 if( sp==lemp->errsym ){
3060 sp->dtnum = arraysize+1;
3061 continue;
3062 }
drh960e8c62001-04-03 16:53:21 +00003063 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003064 sp->dtnum = 0;
3065 continue;
3066 }
3067 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003068 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003069 j = 0;
3070 while( isspace(*cp) ) cp++;
3071 while( *cp ) stddt[j++] = *cp++;
3072 while( j>0 && isspace(stddt[j-1]) ) j--;
3073 stddt[j] = 0;
3074 hash = 0;
3075 for(j=0; stddt[j]; j++){
3076 hash = hash*53 + stddt[j];
3077 }
drh3b2129c2003-05-13 00:34:21 +00003078 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003079 while( types[hash] ){
3080 if( strcmp(types[hash],stddt)==0 ){
3081 sp->dtnum = hash + 1;
3082 break;
3083 }
3084 hash++;
3085 if( hash>=arraysize ) hash = 0;
3086 }
3087 if( types[hash]==0 ){
3088 sp->dtnum = hash + 1;
3089 types[hash] = (char*)malloc( strlen(stddt)+1 );
3090 if( types[hash]==0 ){
3091 fprintf(stderr,"Out of memory.\n");
3092 exit(1);
3093 }
3094 strcpy(types[hash],stddt);
3095 }
3096 }
3097
3098 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3099 name = lemp->name ? lemp->name : "Parse";
3100 lineno = *plineno;
3101 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3102 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3103 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3104 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3105 fprintf(out,"typedef union {\n"); lineno++;
3106 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3107 for(i=0; i<arraysize; i++){
3108 if( types[i]==0 ) continue;
3109 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3110 free(types[i]);
3111 }
3112 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3113 free(stddt);
3114 free(types);
3115 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3116 *plineno = lineno;
3117}
3118
drhb29b0a52002-02-23 19:39:46 +00003119/*
3120** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003121** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003122*/
drh8b582012003-10-21 13:16:03 +00003123static const char *minimum_size_type(int lwr, int upr){
3124 if( lwr>=0 ){
3125 if( upr<=255 ){
3126 return "unsigned char";
3127 }else if( upr<65535 ){
3128 return "unsigned short int";
3129 }else{
3130 return "unsigned int";
3131 }
3132 }else if( lwr>=-127 && upr<=127 ){
3133 return "signed char";
3134 }else if( lwr>=-32767 && upr<32767 ){
3135 return "short";
drhb29b0a52002-02-23 19:39:46 +00003136 }else{
drh8b582012003-10-21 13:16:03 +00003137 return "int";
drhb29b0a52002-02-23 19:39:46 +00003138 }
3139}
3140
drhfdbf9282003-10-21 16:34:41 +00003141/*
3142** Each state contains a set of token transaction and a set of
3143** nonterminal transactions. Each of these sets makes an instance
3144** of the following structure. An array of these structures is used
3145** to order the creation of entries in the yy_action[] table.
3146*/
3147struct axset {
3148 struct state *stp; /* A pointer to a state */
3149 int isTkn; /* True to use tokens. False for non-terminals */
3150 int nAction; /* Number of actions */
3151};
3152
3153/*
3154** Compare to axset structures for sorting purposes
3155*/
3156static int axset_compare(const void *a, const void *b){
3157 struct axset *p1 = (struct axset*)a;
3158 struct axset *p2 = (struct axset*)b;
3159 return p2->nAction - p1->nAction;
3160}
3161
drh75897232000-05-29 14:26:00 +00003162/* Generate C source code for the parser */
3163void ReportTable(lemp, mhflag)
3164struct lemon *lemp;
3165int mhflag; /* Output in makeheaders format if true */
3166{
3167 FILE *out, *in;
3168 char line[LINESIZE];
3169 int lineno;
3170 struct state *stp;
3171 struct action *ap;
3172 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003173 struct acttab *pActtab;
3174 int i, j, n;
drh75897232000-05-29 14:26:00 +00003175 char *name;
drh8b582012003-10-21 13:16:03 +00003176 int mnTknOfst, mxTknOfst;
3177 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003178 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003179
3180 in = tplt_open(lemp);
3181 if( in==0 ) return;
3182 out = file_open(lemp,".c","w");
3183 if( out==0 ){
3184 fclose(in);
3185 return;
3186 }
3187 lineno = 1;
3188 tplt_xfer(lemp->name,in,out,&lineno);
3189
3190 /* Generate the include code, if any */
3191 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3192 if( mhflag ){
3193 char *name = file_makename(lemp, ".h");
3194 fprintf(out,"#include \"%s\"\n", name); lineno++;
3195 free(name);
3196 }
3197 tplt_xfer(lemp->name,in,out,&lineno);
3198
3199 /* Generate #defines for all tokens */
3200 if( mhflag ){
3201 char *prefix;
3202 fprintf(out,"#if INTERFACE\n"); lineno++;
3203 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3204 else prefix = "";
3205 for(i=1; i<lemp->nterminal; i++){
3206 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3207 lineno++;
3208 }
3209 fprintf(out,"#endif\n"); lineno++;
3210 }
3211 tplt_xfer(lemp->name,in,out,&lineno);
3212
3213 /* Generate the defines */
3214 fprintf(out,"/* \001 */\n");
3215 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003216 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003217 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3218 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003219 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003220 print_stack_union(out,lemp,&lineno,mhflag);
3221 if( lemp->stacksize ){
3222 if( atoi(lemp->stacksize)<=0 ){
3223 ErrorMsg(lemp->filename,0,
3224"Illegal stack size: [%s]. The stack size should be an integer constant.",
3225 lemp->stacksize);
3226 lemp->errorcnt++;
3227 lemp->stacksize = "100";
3228 }
3229 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3230 }else{
3231 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3232 }
3233 if( mhflag ){
3234 fprintf(out,"#if INTERFACE\n"); lineno++;
3235 }
3236 name = lemp->name ? lemp->name : "Parse";
3237 if( lemp->arg && lemp->arg[0] ){
3238 int i;
3239 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003240 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3241 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003242 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3243 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3244 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3245 name,lemp->arg,&lemp->arg[i]); lineno++;
3246 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3247 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003248 }else{
drh1f245e42002-03-11 13:55:50 +00003249 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3250 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3251 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3252 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003253 }
3254 if( mhflag ){
3255 fprintf(out,"#endif\n"); lineno++;
3256 }
3257 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3258 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3259 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3260 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drh0bd1f4e2002-06-06 18:54:39 +00003261 if( lemp->has_fallback ){
3262 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3263 }
drh75897232000-05-29 14:26:00 +00003264 tplt_xfer(lemp->name,in,out,&lineno);
3265
drh8b582012003-10-21 13:16:03 +00003266 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003267 **
drh8b582012003-10-21 13:16:03 +00003268 ** yy_action[] A single table containing all actions.
3269 ** yy_lookahead[] A table containing the lookahead for each entry in
3270 ** yy_action. Used to detect hash collisions.
3271 ** yy_shift_ofst[] For each state, the offset into yy_action for
3272 ** shifting terminals.
3273 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3274 ** shifting non-terminals after a reduce.
3275 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003276 */
drh75897232000-05-29 14:26:00 +00003277
drh8b582012003-10-21 13:16:03 +00003278 /* Compute the actions on all states and count them up */
drhfdbf9282003-10-21 16:34:41 +00003279 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3280 if( ax==0 ){
3281 fprintf(stderr,"malloc failed\n");
3282 exit(1);
3283 }
drh75897232000-05-29 14:26:00 +00003284 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003285 stp = lemp->sorted[i];
drh8b582012003-10-21 13:16:03 +00003286 stp->nTknAct = stp->nNtAct = 0;
3287 stp->iDflt = lemp->nstate + lemp->nrule;
3288 stp->iTknOfst = NO_OFFSET;
3289 stp->iNtOfst = NO_OFFSET;
3290 for(ap=stp->ap; ap; ap=ap->next){
3291 if( compute_action(lemp,ap)>=0 ){
3292 if( ap->sp->index<lemp->nterminal ){
3293 stp->nTknAct++;
3294 }else if( ap->sp->index<lemp->nsymbol ){
3295 stp->nNtAct++;
3296 }else{
3297 stp->iDflt = compute_action(lemp, ap);
3298 }
3299 }
3300 }
drhfdbf9282003-10-21 16:34:41 +00003301 ax[i*2].stp = stp;
3302 ax[i*2].isTkn = 1;
3303 ax[i*2].nAction = stp->nTknAct;
3304 ax[i*2+1].stp = stp;
3305 ax[i*2+1].isTkn = 0;
3306 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003307 }
drh8b582012003-10-21 13:16:03 +00003308 mxTknOfst = mnTknOfst = 0;
3309 mxNtOfst = mnNtOfst = 0;
3310
drhfdbf9282003-10-21 16:34:41 +00003311 /* Compute the action table. In order to try to keep the size of the
3312 ** action table to a minimum, the heuristic of placing the largest action
3313 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003314 */
drhfdbf9282003-10-21 16:34:41 +00003315 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003316 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003317 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3318 stp = ax[i].stp;
3319 if( ax[i].isTkn ){
3320 for(ap=stp->ap; ap; ap=ap->next){
3321 int action;
3322 if( ap->sp->index>=lemp->nterminal ) continue;
3323 action = compute_action(lemp, ap);
3324 if( action<0 ) continue;
3325 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003326 }
drhfdbf9282003-10-21 16:34:41 +00003327 stp->iTknOfst = acttab_insert(pActtab);
3328 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3329 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3330 }else{
3331 for(ap=stp->ap; ap; ap=ap->next){
3332 int action;
3333 if( ap->sp->index<lemp->nterminal ) continue;
3334 if( ap->sp->index==lemp->nsymbol ) continue;
3335 action = compute_action(lemp, ap);
3336 if( action<0 ) continue;
3337 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003338 }
drhfdbf9282003-10-21 16:34:41 +00003339 stp->iNtOfst = acttab_insert(pActtab);
3340 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3341 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003342 }
3343 }
drhfdbf9282003-10-21 16:34:41 +00003344 free(ax);
drh8b582012003-10-21 13:16:03 +00003345
3346 /* Output the yy_action table */
3347 fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++;
3348 n = acttab_size(pActtab);
3349 for(i=j=0; i<n; i++){
3350 int action = acttab_yyaction(pActtab, i);
3351 if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003352 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003353 fprintf(out, " %4d,", action);
3354 if( j==9 || i==n-1 ){
3355 fprintf(out, "\n"); lineno++;
3356 j = 0;
3357 }else{
3358 j++;
3359 }
3360 }
3361 fprintf(out, "};\n"); lineno++;
3362
3363 /* Output the yy_lookahead table */
3364 fprintf(out,"static YYCODETYPE yy_lookahead[] = {\n"); lineno++;
3365 for(i=j=0; i<n; i++){
3366 int la = acttab_yylookahead(pActtab, i);
3367 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003368 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003369 fprintf(out, " %4d,", la);
3370 if( j==9 || i==n-1 ){
3371 fprintf(out, "\n"); lineno++;
3372 j = 0;
3373 }else{
3374 j++;
3375 }
3376 }
3377 fprintf(out, "};\n"); lineno++;
3378
3379 /* Output the yy_shift_ofst[] table */
3380 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
3381 fprintf(out, "static %s yy_shift_ofst[] = {\n",
3382 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
3383 n = lemp->nstate;
3384 for(i=j=0; i<n; i++){
3385 int ofst;
3386 stp = lemp->sorted[i];
3387 ofst = stp->iTknOfst;
3388 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003389 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003390 fprintf(out, " %4d,", ofst);
3391 if( j==9 || i==n-1 ){
3392 fprintf(out, "\n"); lineno++;
3393 j = 0;
3394 }else{
3395 j++;
3396 }
3397 }
3398 fprintf(out, "};\n"); lineno++;
3399
3400 /* Output the yy_reduce_ofst[] table */
3401 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
3402 fprintf(out, "static %s yy_reduce_ofst[] = {\n",
3403 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
3404 n = lemp->nstate;
3405 for(i=j=0; i<n; i++){
3406 int ofst;
3407 stp = lemp->sorted[i];
3408 ofst = stp->iNtOfst;
3409 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003410 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003411 fprintf(out, " %4d,", ofst);
3412 if( j==9 || i==n-1 ){
3413 fprintf(out, "\n"); lineno++;
3414 j = 0;
3415 }else{
3416 j++;
3417 }
3418 }
3419 fprintf(out, "};\n"); lineno++;
3420
3421 /* Output the default action table */
3422 fprintf(out, "static YYACTIONTYPE yy_default[] = {\n"); lineno++;
3423 n = lemp->nstate;
3424 for(i=j=0; i<n; i++){
3425 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003426 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003427 fprintf(out, " %4d,", stp->iDflt);
3428 if( j==9 || i==n-1 ){
3429 fprintf(out, "\n"); lineno++;
3430 j = 0;
3431 }else{
3432 j++;
3433 }
3434 }
3435 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003436 tplt_xfer(lemp->name,in,out,&lineno);
3437
drh0bd1f4e2002-06-06 18:54:39 +00003438 /* Generate the table of fallback tokens.
3439 */
3440 if( lemp->has_fallback ){
3441 for(i=0; i<lemp->nterminal; i++){
3442 struct symbol *p = lemp->symbols[i];
3443 if( p->fallback==0 ){
3444 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3445 }else{
3446 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3447 p->name, p->fallback->name);
3448 }
3449 lineno++;
3450 }
3451 }
3452 tplt_xfer(lemp->name, in, out, &lineno);
3453
3454 /* Generate a table containing the symbolic name of every symbol
3455 */
drh75897232000-05-29 14:26:00 +00003456 for(i=0; i<lemp->nsymbol; i++){
3457 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3458 fprintf(out," %-15s",line);
3459 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3460 }
3461 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3462 tplt_xfer(lemp->name,in,out,&lineno);
3463
drh0bd1f4e2002-06-06 18:54:39 +00003464 /* Generate a table containing a text string that describes every
3465 ** rule in the rule set of the grammer. This information is used
3466 ** when tracing REDUCE actions.
3467 */
3468 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3469 assert( rp->index==i );
3470 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
3471 for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name);
3472 fprintf(out,"\",\n"); lineno++;
3473 }
3474 tplt_xfer(lemp->name,in,out,&lineno);
3475
drh75897232000-05-29 14:26:00 +00003476 /* Generate code which executes every time a symbol is popped from
3477 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003478 ** (In other words, generate the %destructor actions)
3479 */
drh75897232000-05-29 14:26:00 +00003480 if( lemp->tokendest ){
3481 for(i=0; i<lemp->nsymbol; i++){
3482 struct symbol *sp = lemp->symbols[i];
3483 if( sp==0 || sp->type!=TERMINAL ) continue;
3484 fprintf(out," case %d:\n",sp->index); lineno++;
3485 }
3486 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3487 if( i<lemp->nsymbol ){
3488 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3489 fprintf(out," break;\n"); lineno++;
3490 }
3491 }
3492 for(i=0; i<lemp->nsymbol; i++){
3493 struct symbol *sp = lemp->symbols[i];
3494 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3495 fprintf(out," case %d:\n",sp->index); lineno++;
3496 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3497 fprintf(out," break;\n"); lineno++;
3498 }
drh960e8c62001-04-03 16:53:21 +00003499 if( lemp->vardest ){
3500 struct symbol *dflt_sp = 0;
3501 for(i=0; i<lemp->nsymbol; i++){
3502 struct symbol *sp = lemp->symbols[i];
3503 if( sp==0 || sp->type==TERMINAL ||
3504 sp->index<=0 || sp->destructor!=0 ) continue;
3505 fprintf(out," case %d:\n",sp->index); lineno++;
3506 dflt_sp = sp;
3507 }
3508 if( dflt_sp!=0 ){
3509 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3510 fprintf(out," break;\n"); lineno++;
3511 }
3512 }
drh75897232000-05-29 14:26:00 +00003513 tplt_xfer(lemp->name,in,out,&lineno);
3514
3515 /* Generate code which executes whenever the parser stack overflows */
3516 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3517 tplt_xfer(lemp->name,in,out,&lineno);
3518
3519 /* Generate the table of rule information
3520 **
3521 ** Note: This code depends on the fact that rules are number
3522 ** sequentually beginning with 0.
3523 */
3524 for(rp=lemp->rule; rp; rp=rp->next){
3525 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3526 }
3527 tplt_xfer(lemp->name,in,out,&lineno);
3528
3529 /* Generate code which execution during each REDUCE action */
3530 for(rp=lemp->rule; rp; rp=rp->next){
3531 fprintf(out," case %d:\n",rp->index); lineno++;
drh75897232000-05-29 14:26:00 +00003532 emit_code(out,rp,lemp,&lineno);
3533 fprintf(out," break;\n"); lineno++;
3534 }
3535 tplt_xfer(lemp->name,in,out,&lineno);
3536
3537 /* Generate code which executes if a parse fails */
3538 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3539 tplt_xfer(lemp->name,in,out,&lineno);
3540
3541 /* Generate code which executes when a syntax error occurs */
3542 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3543 tplt_xfer(lemp->name,in,out,&lineno);
3544
3545 /* Generate code which executes when the parser accepts its input */
3546 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3547 tplt_xfer(lemp->name,in,out,&lineno);
3548
3549 /* Append any addition code the user desires */
3550 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3551
3552 fclose(in);
3553 fclose(out);
3554 return;
3555}
3556
3557/* Generate a header file for the parser */
3558void ReportHeader(lemp)
3559struct lemon *lemp;
3560{
3561 FILE *out, *in;
3562 char *prefix;
3563 char line[LINESIZE];
3564 char pattern[LINESIZE];
3565 int i;
3566
3567 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3568 else prefix = "";
3569 in = file_open(lemp,".h","r");
3570 if( in ){
3571 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3572 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3573 if( strcmp(line,pattern) ) break;
3574 }
3575 fclose(in);
3576 if( i==lemp->nterminal ){
3577 /* No change in the file. Don't rewrite it. */
3578 return;
3579 }
3580 }
3581 out = file_open(lemp,".h","w");
3582 if( out ){
3583 for(i=1; i<lemp->nterminal; i++){
3584 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3585 }
3586 fclose(out);
3587 }
3588 return;
3589}
3590
3591/* Reduce the size of the action tables, if possible, by making use
3592** of defaults.
3593**
drhb59499c2002-02-23 18:45:13 +00003594** In this version, we take the most frequent REDUCE action and make
3595** it the default. Only default a reduce if there are more than one.
drh75897232000-05-29 14:26:00 +00003596*/
3597void CompressTables(lemp)
3598struct lemon *lemp;
3599{
3600 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003601 struct action *ap, *ap2;
3602 struct rule *rp, *rp2, *rbest;
3603 int nbest, n;
drh75897232000-05-29 14:26:00 +00003604 int i;
drh75897232000-05-29 14:26:00 +00003605
3606 for(i=0; i<lemp->nstate; i++){
3607 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003608 nbest = 0;
3609 rbest = 0;
drh75897232000-05-29 14:26:00 +00003610
drhb59499c2002-02-23 18:45:13 +00003611 for(ap=stp->ap; ap; ap=ap->next){
3612 if( ap->type!=REDUCE ) continue;
3613 rp = ap->x.rp;
3614 if( rp==rbest ) continue;
3615 n = 1;
3616 for(ap2=ap->next; ap2; ap2=ap2->next){
3617 if( ap2->type!=REDUCE ) continue;
3618 rp2 = ap2->x.rp;
3619 if( rp2==rbest ) continue;
3620 if( rp2==rp ) n++;
3621 }
3622 if( n>nbest ){
3623 nbest = n;
3624 rbest = rp;
drh75897232000-05-29 14:26:00 +00003625 }
3626 }
drhb59499c2002-02-23 18:45:13 +00003627
3628 /* Do not make a default if the number of rules to default
3629 ** is not at least 2 */
3630 if( nbest<2 ) continue;
drh75897232000-05-29 14:26:00 +00003631
drhb59499c2002-02-23 18:45:13 +00003632
3633 /* Combine matching REDUCE actions into a single default */
3634 for(ap=stp->ap; ap; ap=ap->next){
3635 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3636 }
drh75897232000-05-29 14:26:00 +00003637 assert( ap );
3638 ap->sp = Symbol_new("{default}");
3639 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003640 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003641 }
3642 stp->ap = Action_sort(stp->ap);
3643 }
3644}
drhb59499c2002-02-23 18:45:13 +00003645
drh75897232000-05-29 14:26:00 +00003646/***************** From the file "set.c" ************************************/
3647/*
3648** Set manipulation routines for the LEMON parser generator.
3649*/
3650
3651static int size = 0;
3652
3653/* Set the set size */
3654void SetSize(n)
3655int n;
3656{
3657 size = n+1;
3658}
3659
3660/* Allocate a new set */
3661char *SetNew(){
3662 char *s;
3663 int i;
3664 s = (char*)malloc( size );
3665 if( s==0 ){
3666 extern void memory_error();
3667 memory_error();
3668 }
3669 for(i=0; i<size; i++) s[i] = 0;
3670 return s;
3671}
3672
3673/* Deallocate a set */
3674void SetFree(s)
3675char *s;
3676{
3677 free(s);
3678}
3679
3680/* Add a new element to the set. Return TRUE if the element was added
3681** and FALSE if it was already there. */
3682int SetAdd(s,e)
3683char *s;
3684int e;
3685{
3686 int rv;
3687 rv = s[e];
3688 s[e] = 1;
3689 return !rv;
3690}
3691
3692/* Add every element of s2 to s1. Return TRUE if s1 changes. */
3693int SetUnion(s1,s2)
3694char *s1;
3695char *s2;
3696{
3697 int i, progress;
3698 progress = 0;
3699 for(i=0; i<size; i++){
3700 if( s2[i]==0 ) continue;
3701 if( s1[i]==0 ){
3702 progress = 1;
3703 s1[i] = 1;
3704 }
3705 }
3706 return progress;
3707}
3708/********************** From the file "table.c" ****************************/
3709/*
3710** All code in this file has been automatically generated
3711** from a specification in the file
3712** "table.q"
3713** by the associative array code building program "aagen".
3714** Do not edit this file! Instead, edit the specification
3715** file, then rerun aagen.
3716*/
3717/*
3718** Code for processing tables in the LEMON parser generator.
3719*/
3720
3721PRIVATE int strhash(x)
3722char *x;
3723{
3724 int h = 0;
3725 while( *x) h = h*13 + *(x++);
3726 return h;
3727}
3728
3729/* Works like strdup, sort of. Save a string in malloced memory, but
3730** keep strings in a table so that the same string is not in more
3731** than one place.
3732*/
3733char *Strsafe(y)
3734char *y;
3735{
3736 char *z;
3737
3738 z = Strsafe_find(y);
3739 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
3740 strcpy(z,y);
3741 Strsafe_insert(z);
3742 }
3743 MemoryCheck(z);
3744 return z;
3745}
3746
3747/* There is one instance of the following structure for each
3748** associative array of type "x1".
3749*/
3750struct s_x1 {
3751 int size; /* The number of available slots. */
3752 /* Must be a power of 2 greater than or */
3753 /* equal to 1 */
3754 int count; /* Number of currently slots filled */
3755 struct s_x1node *tbl; /* The data stored here */
3756 struct s_x1node **ht; /* Hash table for lookups */
3757};
3758
3759/* There is one instance of this structure for every data element
3760** in an associative array of type "x1".
3761*/
3762typedef struct s_x1node {
3763 char *data; /* The data */
3764 struct s_x1node *next; /* Next entry with the same hash */
3765 struct s_x1node **from; /* Previous link */
3766} x1node;
3767
3768/* There is only one instance of the array, which is the following */
3769static struct s_x1 *x1a;
3770
3771/* Allocate a new associative array */
3772void Strsafe_init(){
3773 if( x1a ) return;
3774 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
3775 if( x1a ){
3776 x1a->size = 1024;
3777 x1a->count = 0;
3778 x1a->tbl = (x1node*)malloc(
3779 (sizeof(x1node) + sizeof(x1node*))*1024 );
3780 if( x1a->tbl==0 ){
3781 free(x1a);
3782 x1a = 0;
3783 }else{
3784 int i;
3785 x1a->ht = (x1node**)&(x1a->tbl[1024]);
3786 for(i=0; i<1024; i++) x1a->ht[i] = 0;
3787 }
3788 }
3789}
3790/* Insert a new record into the array. Return TRUE if successful.
3791** Prior data with the same key is NOT overwritten */
3792int Strsafe_insert(data)
3793char *data;
3794{
3795 x1node *np;
3796 int h;
3797 int ph;
3798
3799 if( x1a==0 ) return 0;
3800 ph = strhash(data);
3801 h = ph & (x1a->size-1);
3802 np = x1a->ht[h];
3803 while( np ){
3804 if( strcmp(np->data,data)==0 ){
3805 /* An existing entry with the same key is found. */
3806 /* Fail because overwrite is not allows. */
3807 return 0;
3808 }
3809 np = np->next;
3810 }
3811 if( x1a->count>=x1a->size ){
3812 /* Need to make the hash table bigger */
3813 int i,size;
3814 struct s_x1 array;
3815 array.size = size = x1a->size*2;
3816 array.count = x1a->count;
3817 array.tbl = (x1node*)malloc(
3818 (sizeof(x1node) + sizeof(x1node*))*size );
3819 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3820 array.ht = (x1node**)&(array.tbl[size]);
3821 for(i=0; i<size; i++) array.ht[i] = 0;
3822 for(i=0; i<x1a->count; i++){
3823 x1node *oldnp, *newnp;
3824 oldnp = &(x1a->tbl[i]);
3825 h = strhash(oldnp->data) & (size-1);
3826 newnp = &(array.tbl[i]);
3827 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3828 newnp->next = array.ht[h];
3829 newnp->data = oldnp->data;
3830 newnp->from = &(array.ht[h]);
3831 array.ht[h] = newnp;
3832 }
3833 free(x1a->tbl);
3834 *x1a = array;
3835 }
3836 /* Insert the new data */
3837 h = ph & (x1a->size-1);
3838 np = &(x1a->tbl[x1a->count++]);
3839 np->data = data;
3840 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
3841 np->next = x1a->ht[h];
3842 x1a->ht[h] = np;
3843 np->from = &(x1a->ht[h]);
3844 return 1;
3845}
3846
3847/* Return a pointer to data assigned to the given key. Return NULL
3848** if no such key. */
3849char *Strsafe_find(key)
3850char *key;
3851{
3852 int h;
3853 x1node *np;
3854
3855 if( x1a==0 ) return 0;
3856 h = strhash(key) & (x1a->size-1);
3857 np = x1a->ht[h];
3858 while( np ){
3859 if( strcmp(np->data,key)==0 ) break;
3860 np = np->next;
3861 }
3862 return np ? np->data : 0;
3863}
3864
3865/* Return a pointer to the (terminal or nonterminal) symbol "x".
3866** Create a new symbol if this is the first time "x" has been seen.
3867*/
3868struct symbol *Symbol_new(x)
3869char *x;
3870{
3871 struct symbol *sp;
3872
3873 sp = Symbol_find(x);
3874 if( sp==0 ){
3875 sp = (struct symbol *)malloc( sizeof(struct symbol) );
3876 MemoryCheck(sp);
3877 sp->name = Strsafe(x);
3878 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
3879 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00003880 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00003881 sp->prec = -1;
3882 sp->assoc = UNK;
3883 sp->firstset = 0;
drhb27b83a2002-08-14 23:18:57 +00003884 sp->lambda = B_FALSE;
drh75897232000-05-29 14:26:00 +00003885 sp->destructor = 0;
3886 sp->datatype = 0;
3887 Symbol_insert(sp,sp->name);
3888 }
3889 return sp;
3890}
3891
drh60d31652004-02-22 00:08:04 +00003892/* Compare two symbols for working purposes
3893**
3894** Symbols that begin with upper case letters (terminals or tokens)
3895** must sort before symbols that begin with lower case letters
3896** (non-terminals). Other than that, the order does not matter.
3897**
3898** We find experimentally that leaving the symbols in their original
3899** order (the order they appeared in the grammar file) gives the
3900** smallest parser tables in SQLite.
3901*/
3902int Symbolcmpp(struct symbol **a, struct symbol **b){
3903 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
3904 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
3905 return i1-i2;
drh75897232000-05-29 14:26:00 +00003906}
3907
3908/* There is one instance of the following structure for each
3909** associative array of type "x2".
3910*/
3911struct s_x2 {
3912 int size; /* The number of available slots. */
3913 /* Must be a power of 2 greater than or */
3914 /* equal to 1 */
3915 int count; /* Number of currently slots filled */
3916 struct s_x2node *tbl; /* The data stored here */
3917 struct s_x2node **ht; /* Hash table for lookups */
3918};
3919
3920/* There is one instance of this structure for every data element
3921** in an associative array of type "x2".
3922*/
3923typedef struct s_x2node {
3924 struct symbol *data; /* The data */
3925 char *key; /* The key */
3926 struct s_x2node *next; /* Next entry with the same hash */
3927 struct s_x2node **from; /* Previous link */
3928} x2node;
3929
3930/* There is only one instance of the array, which is the following */
3931static struct s_x2 *x2a;
3932
3933/* Allocate a new associative array */
3934void Symbol_init(){
3935 if( x2a ) return;
3936 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
3937 if( x2a ){
3938 x2a->size = 128;
3939 x2a->count = 0;
3940 x2a->tbl = (x2node*)malloc(
3941 (sizeof(x2node) + sizeof(x2node*))*128 );
3942 if( x2a->tbl==0 ){
3943 free(x2a);
3944 x2a = 0;
3945 }else{
3946 int i;
3947 x2a->ht = (x2node**)&(x2a->tbl[128]);
3948 for(i=0; i<128; i++) x2a->ht[i] = 0;
3949 }
3950 }
3951}
3952/* Insert a new record into the array. Return TRUE if successful.
3953** Prior data with the same key is NOT overwritten */
3954int Symbol_insert(data,key)
3955struct symbol *data;
3956char *key;
3957{
3958 x2node *np;
3959 int h;
3960 int ph;
3961
3962 if( x2a==0 ) return 0;
3963 ph = strhash(key);
3964 h = ph & (x2a->size-1);
3965 np = x2a->ht[h];
3966 while( np ){
3967 if( strcmp(np->key,key)==0 ){
3968 /* An existing entry with the same key is found. */
3969 /* Fail because overwrite is not allows. */
3970 return 0;
3971 }
3972 np = np->next;
3973 }
3974 if( x2a->count>=x2a->size ){
3975 /* Need to make the hash table bigger */
3976 int i,size;
3977 struct s_x2 array;
3978 array.size = size = x2a->size*2;
3979 array.count = x2a->count;
3980 array.tbl = (x2node*)malloc(
3981 (sizeof(x2node) + sizeof(x2node*))*size );
3982 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3983 array.ht = (x2node**)&(array.tbl[size]);
3984 for(i=0; i<size; i++) array.ht[i] = 0;
3985 for(i=0; i<x2a->count; i++){
3986 x2node *oldnp, *newnp;
3987 oldnp = &(x2a->tbl[i]);
3988 h = strhash(oldnp->key) & (size-1);
3989 newnp = &(array.tbl[i]);
3990 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3991 newnp->next = array.ht[h];
3992 newnp->key = oldnp->key;
3993 newnp->data = oldnp->data;
3994 newnp->from = &(array.ht[h]);
3995 array.ht[h] = newnp;
3996 }
3997 free(x2a->tbl);
3998 *x2a = array;
3999 }
4000 /* Insert the new data */
4001 h = ph & (x2a->size-1);
4002 np = &(x2a->tbl[x2a->count++]);
4003 np->key = key;
4004 np->data = data;
4005 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4006 np->next = x2a->ht[h];
4007 x2a->ht[h] = np;
4008 np->from = &(x2a->ht[h]);
4009 return 1;
4010}
4011
4012/* Return a pointer to data assigned to the given key. Return NULL
4013** if no such key. */
4014struct symbol *Symbol_find(key)
4015char *key;
4016{
4017 int h;
4018 x2node *np;
4019
4020 if( x2a==0 ) return 0;
4021 h = strhash(key) & (x2a->size-1);
4022 np = x2a->ht[h];
4023 while( np ){
4024 if( strcmp(np->key,key)==0 ) break;
4025 np = np->next;
4026 }
4027 return np ? np->data : 0;
4028}
4029
4030/* Return the n-th data. Return NULL if n is out of range. */
4031struct symbol *Symbol_Nth(n)
4032int n;
4033{
4034 struct symbol *data;
4035 if( x2a && n>0 && n<=x2a->count ){
4036 data = x2a->tbl[n-1].data;
4037 }else{
4038 data = 0;
4039 }
4040 return data;
4041}
4042
4043/* Return the size of the array */
4044int Symbol_count()
4045{
4046 return x2a ? x2a->count : 0;
4047}
4048
4049/* Return an array of pointers to all data in the table.
4050** The array is obtained from malloc. Return NULL if memory allocation
4051** problems, or if the array is empty. */
4052struct symbol **Symbol_arrayof()
4053{
4054 struct symbol **array;
4055 int i,size;
4056 if( x2a==0 ) return 0;
4057 size = x2a->count;
4058 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4059 if( array ){
4060 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4061 }
4062 return array;
4063}
4064
4065/* Compare two configurations */
4066int Configcmp(a,b)
4067struct config *a;
4068struct config *b;
4069{
4070 int x;
4071 x = a->rp->index - b->rp->index;
4072 if( x==0 ) x = a->dot - b->dot;
4073 return x;
4074}
4075
4076/* Compare two states */
4077PRIVATE int statecmp(a,b)
4078struct config *a;
4079struct config *b;
4080{
4081 int rc;
4082 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4083 rc = a->rp->index - b->rp->index;
4084 if( rc==0 ) rc = a->dot - b->dot;
4085 }
4086 if( rc==0 ){
4087 if( a ) rc = 1;
4088 if( b ) rc = -1;
4089 }
4090 return rc;
4091}
4092
4093/* Hash a state */
4094PRIVATE int statehash(a)
4095struct config *a;
4096{
4097 int h=0;
4098 while( a ){
4099 h = h*571 + a->rp->index*37 + a->dot;
4100 a = a->bp;
4101 }
4102 return h;
4103}
4104
4105/* Allocate a new state structure */
4106struct state *State_new()
4107{
4108 struct state *new;
4109 new = (struct state *)malloc( sizeof(struct state) );
4110 MemoryCheck(new);
4111 return new;
4112}
4113
4114/* There is one instance of the following structure for each
4115** associative array of type "x3".
4116*/
4117struct s_x3 {
4118 int size; /* The number of available slots. */
4119 /* Must be a power of 2 greater than or */
4120 /* equal to 1 */
4121 int count; /* Number of currently slots filled */
4122 struct s_x3node *tbl; /* The data stored here */
4123 struct s_x3node **ht; /* Hash table for lookups */
4124};
4125
4126/* There is one instance of this structure for every data element
4127** in an associative array of type "x3".
4128*/
4129typedef struct s_x3node {
4130 struct state *data; /* The data */
4131 struct config *key; /* The key */
4132 struct s_x3node *next; /* Next entry with the same hash */
4133 struct s_x3node **from; /* Previous link */
4134} x3node;
4135
4136/* There is only one instance of the array, which is the following */
4137static struct s_x3 *x3a;
4138
4139/* Allocate a new associative array */
4140void State_init(){
4141 if( x3a ) return;
4142 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4143 if( x3a ){
4144 x3a->size = 128;
4145 x3a->count = 0;
4146 x3a->tbl = (x3node*)malloc(
4147 (sizeof(x3node) + sizeof(x3node*))*128 );
4148 if( x3a->tbl==0 ){
4149 free(x3a);
4150 x3a = 0;
4151 }else{
4152 int i;
4153 x3a->ht = (x3node**)&(x3a->tbl[128]);
4154 for(i=0; i<128; i++) x3a->ht[i] = 0;
4155 }
4156 }
4157}
4158/* Insert a new record into the array. Return TRUE if successful.
4159** Prior data with the same key is NOT overwritten */
4160int State_insert(data,key)
4161struct state *data;
4162struct config *key;
4163{
4164 x3node *np;
4165 int h;
4166 int ph;
4167
4168 if( x3a==0 ) return 0;
4169 ph = statehash(key);
4170 h = ph & (x3a->size-1);
4171 np = x3a->ht[h];
4172 while( np ){
4173 if( statecmp(np->key,key)==0 ){
4174 /* An existing entry with the same key is found. */
4175 /* Fail because overwrite is not allows. */
4176 return 0;
4177 }
4178 np = np->next;
4179 }
4180 if( x3a->count>=x3a->size ){
4181 /* Need to make the hash table bigger */
4182 int i,size;
4183 struct s_x3 array;
4184 array.size = size = x3a->size*2;
4185 array.count = x3a->count;
4186 array.tbl = (x3node*)malloc(
4187 (sizeof(x3node) + sizeof(x3node*))*size );
4188 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4189 array.ht = (x3node**)&(array.tbl[size]);
4190 for(i=0; i<size; i++) array.ht[i] = 0;
4191 for(i=0; i<x3a->count; i++){
4192 x3node *oldnp, *newnp;
4193 oldnp = &(x3a->tbl[i]);
4194 h = statehash(oldnp->key) & (size-1);
4195 newnp = &(array.tbl[i]);
4196 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4197 newnp->next = array.ht[h];
4198 newnp->key = oldnp->key;
4199 newnp->data = oldnp->data;
4200 newnp->from = &(array.ht[h]);
4201 array.ht[h] = newnp;
4202 }
4203 free(x3a->tbl);
4204 *x3a = array;
4205 }
4206 /* Insert the new data */
4207 h = ph & (x3a->size-1);
4208 np = &(x3a->tbl[x3a->count++]);
4209 np->key = key;
4210 np->data = data;
4211 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4212 np->next = x3a->ht[h];
4213 x3a->ht[h] = np;
4214 np->from = &(x3a->ht[h]);
4215 return 1;
4216}
4217
4218/* Return a pointer to data assigned to the given key. Return NULL
4219** if no such key. */
4220struct state *State_find(key)
4221struct config *key;
4222{
4223 int h;
4224 x3node *np;
4225
4226 if( x3a==0 ) return 0;
4227 h = statehash(key) & (x3a->size-1);
4228 np = x3a->ht[h];
4229 while( np ){
4230 if( statecmp(np->key,key)==0 ) break;
4231 np = np->next;
4232 }
4233 return np ? np->data : 0;
4234}
4235
4236/* Return an array of pointers to all data in the table.
4237** The array is obtained from malloc. Return NULL if memory allocation
4238** problems, or if the array is empty. */
4239struct state **State_arrayof()
4240{
4241 struct state **array;
4242 int i,size;
4243 if( x3a==0 ) return 0;
4244 size = x3a->count;
4245 array = (struct state **)malloc( sizeof(struct state *)*size );
4246 if( array ){
4247 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4248 }
4249 return array;
4250}
4251
4252/* Hash a configuration */
4253PRIVATE int confighash(a)
4254struct config *a;
4255{
4256 int h=0;
4257 h = h*571 + a->rp->index*37 + a->dot;
4258 return h;
4259}
4260
4261/* There is one instance of the following structure for each
4262** associative array of type "x4".
4263*/
4264struct s_x4 {
4265 int size; /* The number of available slots. */
4266 /* Must be a power of 2 greater than or */
4267 /* equal to 1 */
4268 int count; /* Number of currently slots filled */
4269 struct s_x4node *tbl; /* The data stored here */
4270 struct s_x4node **ht; /* Hash table for lookups */
4271};
4272
4273/* There is one instance of this structure for every data element
4274** in an associative array of type "x4".
4275*/
4276typedef struct s_x4node {
4277 struct config *data; /* The data */
4278 struct s_x4node *next; /* Next entry with the same hash */
4279 struct s_x4node **from; /* Previous link */
4280} x4node;
4281
4282/* There is only one instance of the array, which is the following */
4283static struct s_x4 *x4a;
4284
4285/* Allocate a new associative array */
4286void Configtable_init(){
4287 if( x4a ) return;
4288 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4289 if( x4a ){
4290 x4a->size = 64;
4291 x4a->count = 0;
4292 x4a->tbl = (x4node*)malloc(
4293 (sizeof(x4node) + sizeof(x4node*))*64 );
4294 if( x4a->tbl==0 ){
4295 free(x4a);
4296 x4a = 0;
4297 }else{
4298 int i;
4299 x4a->ht = (x4node**)&(x4a->tbl[64]);
4300 for(i=0; i<64; i++) x4a->ht[i] = 0;
4301 }
4302 }
4303}
4304/* Insert a new record into the array. Return TRUE if successful.
4305** Prior data with the same key is NOT overwritten */
4306int Configtable_insert(data)
4307struct config *data;
4308{
4309 x4node *np;
4310 int h;
4311 int ph;
4312
4313 if( x4a==0 ) return 0;
4314 ph = confighash(data);
4315 h = ph & (x4a->size-1);
4316 np = x4a->ht[h];
4317 while( np ){
4318 if( Configcmp(np->data,data)==0 ){
4319 /* An existing entry with the same key is found. */
4320 /* Fail because overwrite is not allows. */
4321 return 0;
4322 }
4323 np = np->next;
4324 }
4325 if( x4a->count>=x4a->size ){
4326 /* Need to make the hash table bigger */
4327 int i,size;
4328 struct s_x4 array;
4329 array.size = size = x4a->size*2;
4330 array.count = x4a->count;
4331 array.tbl = (x4node*)malloc(
4332 (sizeof(x4node) + sizeof(x4node*))*size );
4333 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4334 array.ht = (x4node**)&(array.tbl[size]);
4335 for(i=0; i<size; i++) array.ht[i] = 0;
4336 for(i=0; i<x4a->count; i++){
4337 x4node *oldnp, *newnp;
4338 oldnp = &(x4a->tbl[i]);
4339 h = confighash(oldnp->data) & (size-1);
4340 newnp = &(array.tbl[i]);
4341 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4342 newnp->next = array.ht[h];
4343 newnp->data = oldnp->data;
4344 newnp->from = &(array.ht[h]);
4345 array.ht[h] = newnp;
4346 }
4347 free(x4a->tbl);
4348 *x4a = array;
4349 }
4350 /* Insert the new data */
4351 h = ph & (x4a->size-1);
4352 np = &(x4a->tbl[x4a->count++]);
4353 np->data = data;
4354 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4355 np->next = x4a->ht[h];
4356 x4a->ht[h] = np;
4357 np->from = &(x4a->ht[h]);
4358 return 1;
4359}
4360
4361/* Return a pointer to data assigned to the given key. Return NULL
4362** if no such key. */
4363struct config *Configtable_find(key)
4364struct config *key;
4365{
4366 int h;
4367 x4node *np;
4368
4369 if( x4a==0 ) return 0;
4370 h = confighash(key) & (x4a->size-1);
4371 np = x4a->ht[h];
4372 while( np ){
4373 if( Configcmp(np->data,key)==0 ) break;
4374 np = np->next;
4375 }
4376 return np ? np->data : 0;
4377}
4378
4379/* Remove all data from the table. Pass each data to the function "f"
4380** as it is removed. ("f" may be null to avoid this step.) */
4381void Configtable_clear(f)
4382int(*f)(/* struct config * */);
4383{
4384 int i;
4385 if( x4a==0 || x4a->count==0 ) return;
4386 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4387 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4388 x4a->count = 0;
4389 return;
4390}