blob: 18293fc78269bf05c5a4dc691b20a2cc2462eb05 [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{
2879 char *cp;
2880
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);
drh75897232000-05-29 14:26:00 +00002893 }
2894 for(; *cp; cp++){
2895 if( *cp=='$' && cp[1]=='$' ){
2896 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
2897 cp++;
2898 continue;
2899 }
2900 if( *cp=='\n' ) linecnt++;
2901 fputc(*cp,out);
2902 }
2903 (*lineno) += 3 + linecnt;
2904 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2905 return;
2906}
2907
2908/*
drh960e8c62001-04-03 16:53:21 +00002909** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00002910*/
2911int has_destructor(sp, lemp)
2912struct symbol *sp;
2913struct lemon *lemp;
2914{
2915 int ret;
2916 if( sp->type==TERMINAL ){
2917 ret = lemp->tokendest!=0;
2918 }else{
drh960e8c62001-04-03 16:53:21 +00002919 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00002920 }
2921 return ret;
2922}
2923
2924/*
2925** Generate code which executes when the rule "rp" is reduced. Write
2926** the code to "out". Make sure lineno stays up-to-date.
2927*/
2928PRIVATE void emit_code(out,rp,lemp,lineno)
2929FILE *out;
2930struct rule *rp;
2931struct lemon *lemp;
2932int *lineno;
2933{
2934 char *cp, *xp;
2935 int linecnt = 0;
2936 int i;
2937 char lhsused = 0; /* True if the LHS element has been used */
2938 char used[MAXRHS]; /* True for each RHS element which is used */
2939
2940 for(i=0; i<rp->nrhs; i++) used[i] = 0;
2941 lhsused = 0;
2942
2943 /* Generate code to do the reduce action */
2944 if( rp->code ){
2945 fprintf(out,"#line %d \"%s\"\n{",rp->line,lemp->filename);
2946 for(cp=rp->code; *cp; cp++){
drh7218ac72002-03-10 21:21:00 +00002947 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
drh75897232000-05-29 14:26:00 +00002948 char saved;
drh7218ac72002-03-10 21:21:00 +00002949 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
drh75897232000-05-29 14:26:00 +00002950 saved = *xp;
2951 *xp = 0;
2952 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
2953 fprintf(out,"yygotominor.yy%d",rp->lhs->dtnum);
2954 cp = xp;
2955 lhsused = 1;
2956 }else{
2957 for(i=0; i<rp->nrhs; i++){
2958 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
2959 fprintf(out,"yymsp[%d].minor.yy%d",i-rp->nrhs+1,rp->rhs[i]->dtnum);
2960 cp = xp;
2961 used[i] = 1;
2962 break;
2963 }
2964 }
2965 }
2966 *xp = saved;
2967 }
2968 if( *cp=='\n' ) linecnt++;
2969 fputc(*cp,out);
2970 } /* End loop */
2971 (*lineno) += 3 + linecnt;
2972 fprintf(out,"}\n#line %d \"%s\"\n",*lineno,lemp->outname);
2973 } /* End if( rp->code ) */
2974
2975 /* Check to make sure the LHS has been used */
2976 if( rp->lhsalias && !lhsused ){
2977 ErrorMsg(lemp->filename,rp->ruleline,
2978 "Label \"%s\" for \"%s(%s)\" is never used.",
2979 rp->lhsalias,rp->lhs->name,rp->lhsalias);
2980 lemp->errorcnt++;
2981 }
2982
2983 /* Generate destructor code for RHS symbols which are not used in the
2984 ** reduce code */
2985 for(i=0; i<rp->nrhs; i++){
2986 if( rp->rhsalias[i] && !used[i] ){
2987 ErrorMsg(lemp->filename,rp->ruleline,
drh960e8c62001-04-03 16:53:21 +00002988 "Label %s for \"%s(%s)\" is never used.",
drh75897232000-05-29 14:26:00 +00002989 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
2990 lemp->errorcnt++;
2991 }else if( rp->rhsalias[i]==0 ){
2992 if( has_destructor(rp->rhs[i],lemp) ){
2993 fprintf(out," yy_destructor(%d,&yymsp[%d].minor);\n",
2994 rp->rhs[i]->index,i-rp->nrhs+1); (*lineno)++;
2995 }else{
2996 fprintf(out," /* No destructor defined for %s */\n",
2997 rp->rhs[i]->name);
2998 (*lineno)++;
2999 }
3000 }
3001 }
3002 return;
3003}
3004
3005/*
3006** Print the definition of the union used for the parser's data stack.
3007** This union contains fields for every possible data type for tokens
3008** and nonterminals. In the process of computing and printing this
3009** union, also set the ".dtnum" field of every terminal and nonterminal
3010** symbol.
3011*/
3012void print_stack_union(out,lemp,plineno,mhflag)
3013FILE *out; /* The output stream */
3014struct lemon *lemp; /* The main info structure for this parser */
3015int *plineno; /* Pointer to the line number */
3016int mhflag; /* True if generating makeheaders output */
3017{
3018 int lineno = *plineno; /* The line number of the output */
3019 char **types; /* A hash table of datatypes */
3020 int arraysize; /* Size of the "types" array */
3021 int maxdtlength; /* Maximum length of any ".datatype" field. */
3022 char *stddt; /* Standardized name for a datatype */
3023 int i,j; /* Loop counters */
3024 int hash; /* For hashing the name of a type */
3025 char *name; /* Name of the parser */
3026
3027 /* Allocate and initialize types[] and allocate stddt[] */
3028 arraysize = lemp->nsymbol * 2;
3029 types = (char**)malloc( arraysize * sizeof(char*) );
3030 for(i=0; i<arraysize; i++) types[i] = 0;
3031 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003032 if( lemp->vartype ){
3033 maxdtlength = strlen(lemp->vartype);
3034 }
drh75897232000-05-29 14:26:00 +00003035 for(i=0; i<lemp->nsymbol; i++){
3036 int len;
3037 struct symbol *sp = lemp->symbols[i];
3038 if( sp->datatype==0 ) continue;
3039 len = strlen(sp->datatype);
3040 if( len>maxdtlength ) maxdtlength = len;
3041 }
3042 stddt = (char*)malloc( maxdtlength*2 + 1 );
3043 if( types==0 || stddt==0 ){
3044 fprintf(stderr,"Out of memory.\n");
3045 exit(1);
3046 }
3047
3048 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3049 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003050 ** used for terminal symbols. If there is no %default_type defined then
3051 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3052 ** a datatype using the %type directive.
3053 */
drh75897232000-05-29 14:26:00 +00003054 for(i=0; i<lemp->nsymbol; i++){
3055 struct symbol *sp = lemp->symbols[i];
3056 char *cp;
3057 if( sp==lemp->errsym ){
3058 sp->dtnum = arraysize+1;
3059 continue;
3060 }
drh960e8c62001-04-03 16:53:21 +00003061 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003062 sp->dtnum = 0;
3063 continue;
3064 }
3065 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003066 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003067 j = 0;
3068 while( isspace(*cp) ) cp++;
3069 while( *cp ) stddt[j++] = *cp++;
3070 while( j>0 && isspace(stddt[j-1]) ) j--;
3071 stddt[j] = 0;
3072 hash = 0;
3073 for(j=0; stddt[j]; j++){
3074 hash = hash*53 + stddt[j];
3075 }
drh3b2129c2003-05-13 00:34:21 +00003076 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003077 while( types[hash] ){
3078 if( strcmp(types[hash],stddt)==0 ){
3079 sp->dtnum = hash + 1;
3080 break;
3081 }
3082 hash++;
3083 if( hash>=arraysize ) hash = 0;
3084 }
3085 if( types[hash]==0 ){
3086 sp->dtnum = hash + 1;
3087 types[hash] = (char*)malloc( strlen(stddt)+1 );
3088 if( types[hash]==0 ){
3089 fprintf(stderr,"Out of memory.\n");
3090 exit(1);
3091 }
3092 strcpy(types[hash],stddt);
3093 }
3094 }
3095
3096 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3097 name = lemp->name ? lemp->name : "Parse";
3098 lineno = *plineno;
3099 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3100 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3101 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3102 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3103 fprintf(out,"typedef union {\n"); lineno++;
3104 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3105 for(i=0; i<arraysize; i++){
3106 if( types[i]==0 ) continue;
3107 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3108 free(types[i]);
3109 }
3110 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3111 free(stddt);
3112 free(types);
3113 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3114 *plineno = lineno;
3115}
3116
drhb29b0a52002-02-23 19:39:46 +00003117/*
3118** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003119** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003120*/
drh8b582012003-10-21 13:16:03 +00003121static const char *minimum_size_type(int lwr, int upr){
3122 if( lwr>=0 ){
3123 if( upr<=255 ){
3124 return "unsigned char";
3125 }else if( upr<65535 ){
3126 return "unsigned short int";
3127 }else{
3128 return "unsigned int";
3129 }
3130 }else if( lwr>=-127 && upr<=127 ){
3131 return "signed char";
3132 }else if( lwr>=-32767 && upr<32767 ){
3133 return "short";
drhb29b0a52002-02-23 19:39:46 +00003134 }else{
drh8b582012003-10-21 13:16:03 +00003135 return "int";
drhb29b0a52002-02-23 19:39:46 +00003136 }
3137}
3138
drhfdbf9282003-10-21 16:34:41 +00003139/*
3140** Each state contains a set of token transaction and a set of
3141** nonterminal transactions. Each of these sets makes an instance
3142** of the following structure. An array of these structures is used
3143** to order the creation of entries in the yy_action[] table.
3144*/
3145struct axset {
3146 struct state *stp; /* A pointer to a state */
3147 int isTkn; /* True to use tokens. False for non-terminals */
3148 int nAction; /* Number of actions */
3149};
3150
3151/*
3152** Compare to axset structures for sorting purposes
3153*/
3154static int axset_compare(const void *a, const void *b){
3155 struct axset *p1 = (struct axset*)a;
3156 struct axset *p2 = (struct axset*)b;
3157 return p2->nAction - p1->nAction;
3158}
3159
drh75897232000-05-29 14:26:00 +00003160/* Generate C source code for the parser */
3161void ReportTable(lemp, mhflag)
3162struct lemon *lemp;
3163int mhflag; /* Output in makeheaders format if true */
3164{
3165 FILE *out, *in;
3166 char line[LINESIZE];
3167 int lineno;
3168 struct state *stp;
3169 struct action *ap;
3170 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003171 struct acttab *pActtab;
3172 int i, j, n;
drh75897232000-05-29 14:26:00 +00003173 char *name;
drh8b582012003-10-21 13:16:03 +00003174 int mnTknOfst, mxTknOfst;
3175 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003176 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003177
3178 in = tplt_open(lemp);
3179 if( in==0 ) return;
3180 out = file_open(lemp,".c","w");
3181 if( out==0 ){
3182 fclose(in);
3183 return;
3184 }
3185 lineno = 1;
3186 tplt_xfer(lemp->name,in,out,&lineno);
3187
3188 /* Generate the include code, if any */
3189 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3190 if( mhflag ){
3191 char *name = file_makename(lemp, ".h");
3192 fprintf(out,"#include \"%s\"\n", name); lineno++;
3193 free(name);
3194 }
3195 tplt_xfer(lemp->name,in,out,&lineno);
3196
3197 /* Generate #defines for all tokens */
3198 if( mhflag ){
3199 char *prefix;
3200 fprintf(out,"#if INTERFACE\n"); lineno++;
3201 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3202 else prefix = "";
3203 for(i=1; i<lemp->nterminal; i++){
3204 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3205 lineno++;
3206 }
3207 fprintf(out,"#endif\n"); lineno++;
3208 }
3209 tplt_xfer(lemp->name,in,out,&lineno);
3210
3211 /* Generate the defines */
3212 fprintf(out,"/* \001 */\n");
3213 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003214 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003215 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3216 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003217 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003218 print_stack_union(out,lemp,&lineno,mhflag);
3219 if( lemp->stacksize ){
3220 if( atoi(lemp->stacksize)<=0 ){
3221 ErrorMsg(lemp->filename,0,
3222"Illegal stack size: [%s]. The stack size should be an integer constant.",
3223 lemp->stacksize);
3224 lemp->errorcnt++;
3225 lemp->stacksize = "100";
3226 }
3227 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3228 }else{
3229 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3230 }
3231 if( mhflag ){
3232 fprintf(out,"#if INTERFACE\n"); lineno++;
3233 }
3234 name = lemp->name ? lemp->name : "Parse";
3235 if( lemp->arg && lemp->arg[0] ){
3236 int i;
3237 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003238 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3239 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003240 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3241 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3242 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3243 name,lemp->arg,&lemp->arg[i]); lineno++;
3244 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3245 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003246 }else{
drh1f245e42002-03-11 13:55:50 +00003247 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3248 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3249 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3250 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003251 }
3252 if( mhflag ){
3253 fprintf(out,"#endif\n"); lineno++;
3254 }
3255 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3256 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3257 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3258 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drh0bd1f4e2002-06-06 18:54:39 +00003259 if( lemp->has_fallback ){
3260 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3261 }
drh75897232000-05-29 14:26:00 +00003262 tplt_xfer(lemp->name,in,out,&lineno);
3263
drh8b582012003-10-21 13:16:03 +00003264 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003265 **
drh8b582012003-10-21 13:16:03 +00003266 ** yy_action[] A single table containing all actions.
3267 ** yy_lookahead[] A table containing the lookahead for each entry in
3268 ** yy_action. Used to detect hash collisions.
3269 ** yy_shift_ofst[] For each state, the offset into yy_action for
3270 ** shifting terminals.
3271 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3272 ** shifting non-terminals after a reduce.
3273 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003274 */
drh75897232000-05-29 14:26:00 +00003275
drh8b582012003-10-21 13:16:03 +00003276 /* Compute the actions on all states and count them up */
drhfdbf9282003-10-21 16:34:41 +00003277 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3278 if( ax==0 ){
3279 fprintf(stderr,"malloc failed\n");
3280 exit(1);
3281 }
drh75897232000-05-29 14:26:00 +00003282 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003283 stp = lemp->sorted[i];
drh8b582012003-10-21 13:16:03 +00003284 stp->nTknAct = stp->nNtAct = 0;
3285 stp->iDflt = lemp->nstate + lemp->nrule;
3286 stp->iTknOfst = NO_OFFSET;
3287 stp->iNtOfst = NO_OFFSET;
3288 for(ap=stp->ap; ap; ap=ap->next){
3289 if( compute_action(lemp,ap)>=0 ){
3290 if( ap->sp->index<lemp->nterminal ){
3291 stp->nTknAct++;
3292 }else if( ap->sp->index<lemp->nsymbol ){
3293 stp->nNtAct++;
3294 }else{
3295 stp->iDflt = compute_action(lemp, ap);
3296 }
3297 }
3298 }
drhfdbf9282003-10-21 16:34:41 +00003299 ax[i*2].stp = stp;
3300 ax[i*2].isTkn = 1;
3301 ax[i*2].nAction = stp->nTknAct;
3302 ax[i*2+1].stp = stp;
3303 ax[i*2+1].isTkn = 0;
3304 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003305 }
drh8b582012003-10-21 13:16:03 +00003306 mxTknOfst = mnTknOfst = 0;
3307 mxNtOfst = mnNtOfst = 0;
3308
drhfdbf9282003-10-21 16:34:41 +00003309 /* Compute the action table. In order to try to keep the size of the
3310 ** action table to a minimum, the heuristic of placing the largest action
3311 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003312 */
drhfdbf9282003-10-21 16:34:41 +00003313 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003314 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003315 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3316 stp = ax[i].stp;
3317 if( ax[i].isTkn ){
3318 for(ap=stp->ap; ap; ap=ap->next){
3319 int action;
3320 if( ap->sp->index>=lemp->nterminal ) continue;
3321 action = compute_action(lemp, ap);
3322 if( action<0 ) continue;
3323 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003324 }
drhfdbf9282003-10-21 16:34:41 +00003325 stp->iTknOfst = acttab_insert(pActtab);
3326 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3327 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3328 }else{
3329 for(ap=stp->ap; ap; ap=ap->next){
3330 int action;
3331 if( ap->sp->index<lemp->nterminal ) continue;
3332 if( ap->sp->index==lemp->nsymbol ) continue;
3333 action = compute_action(lemp, ap);
3334 if( action<0 ) continue;
3335 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003336 }
drhfdbf9282003-10-21 16:34:41 +00003337 stp->iNtOfst = acttab_insert(pActtab);
3338 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3339 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003340 }
3341 }
drhfdbf9282003-10-21 16:34:41 +00003342 free(ax);
drh8b582012003-10-21 13:16:03 +00003343
3344 /* Output the yy_action table */
3345 fprintf(out,"static YYACTIONTYPE yy_action[] = {\n"); lineno++;
3346 n = acttab_size(pActtab);
3347 for(i=j=0; i<n; i++){
3348 int action = acttab_yyaction(pActtab, i);
3349 if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003350 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003351 fprintf(out, " %4d,", action);
3352 if( j==9 || i==n-1 ){
3353 fprintf(out, "\n"); lineno++;
3354 j = 0;
3355 }else{
3356 j++;
3357 }
3358 }
3359 fprintf(out, "};\n"); lineno++;
3360
3361 /* Output the yy_lookahead table */
3362 fprintf(out,"static YYCODETYPE yy_lookahead[] = {\n"); lineno++;
3363 for(i=j=0; i<n; i++){
3364 int la = acttab_yylookahead(pActtab, i);
3365 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003366 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003367 fprintf(out, " %4d,", la);
3368 if( j==9 || i==n-1 ){
3369 fprintf(out, "\n"); lineno++;
3370 j = 0;
3371 }else{
3372 j++;
3373 }
3374 }
3375 fprintf(out, "};\n"); lineno++;
3376
3377 /* Output the yy_shift_ofst[] table */
3378 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
3379 fprintf(out, "static %s yy_shift_ofst[] = {\n",
3380 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
3381 n = lemp->nstate;
3382 for(i=j=0; i<n; i++){
3383 int ofst;
3384 stp = lemp->sorted[i];
3385 ofst = stp->iTknOfst;
3386 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003387 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003388 fprintf(out, " %4d,", ofst);
3389 if( j==9 || i==n-1 ){
3390 fprintf(out, "\n"); lineno++;
3391 j = 0;
3392 }else{
3393 j++;
3394 }
3395 }
3396 fprintf(out, "};\n"); lineno++;
3397
3398 /* Output the yy_reduce_ofst[] table */
3399 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
3400 fprintf(out, "static %s yy_reduce_ofst[] = {\n",
3401 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
3402 n = lemp->nstate;
3403 for(i=j=0; i<n; i++){
3404 int ofst;
3405 stp = lemp->sorted[i];
3406 ofst = stp->iNtOfst;
3407 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003408 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003409 fprintf(out, " %4d,", ofst);
3410 if( j==9 || i==n-1 ){
3411 fprintf(out, "\n"); lineno++;
3412 j = 0;
3413 }else{
3414 j++;
3415 }
3416 }
3417 fprintf(out, "};\n"); lineno++;
3418
3419 /* Output the default action table */
3420 fprintf(out, "static YYACTIONTYPE yy_default[] = {\n"); lineno++;
3421 n = lemp->nstate;
3422 for(i=j=0; i<n; i++){
3423 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003424 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003425 fprintf(out, " %4d,", stp->iDflt);
3426 if( j==9 || i==n-1 ){
3427 fprintf(out, "\n"); lineno++;
3428 j = 0;
3429 }else{
3430 j++;
3431 }
3432 }
3433 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003434 tplt_xfer(lemp->name,in,out,&lineno);
3435
drh0bd1f4e2002-06-06 18:54:39 +00003436 /* Generate the table of fallback tokens.
3437 */
3438 if( lemp->has_fallback ){
3439 for(i=0; i<lemp->nterminal; i++){
3440 struct symbol *p = lemp->symbols[i];
3441 if( p->fallback==0 ){
3442 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3443 }else{
3444 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3445 p->name, p->fallback->name);
3446 }
3447 lineno++;
3448 }
3449 }
3450 tplt_xfer(lemp->name, in, out, &lineno);
3451
3452 /* Generate a table containing the symbolic name of every symbol
3453 */
drh75897232000-05-29 14:26:00 +00003454 for(i=0; i<lemp->nsymbol; i++){
3455 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3456 fprintf(out," %-15s",line);
3457 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3458 }
3459 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3460 tplt_xfer(lemp->name,in,out,&lineno);
3461
drh0bd1f4e2002-06-06 18:54:39 +00003462 /* Generate a table containing a text string that describes every
3463 ** rule in the rule set of the grammer. This information is used
3464 ** when tracing REDUCE actions.
3465 */
3466 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3467 assert( rp->index==i );
3468 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
3469 for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name);
3470 fprintf(out,"\",\n"); lineno++;
3471 }
3472 tplt_xfer(lemp->name,in,out,&lineno);
3473
drh75897232000-05-29 14:26:00 +00003474 /* Generate code which executes every time a symbol is popped from
3475 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003476 ** (In other words, generate the %destructor actions)
3477 */
drh75897232000-05-29 14:26:00 +00003478 if( lemp->tokendest ){
3479 for(i=0; i<lemp->nsymbol; i++){
3480 struct symbol *sp = lemp->symbols[i];
3481 if( sp==0 || sp->type!=TERMINAL ) continue;
3482 fprintf(out," case %d:\n",sp->index); lineno++;
3483 }
3484 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3485 if( i<lemp->nsymbol ){
3486 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3487 fprintf(out," break;\n"); lineno++;
3488 }
3489 }
3490 for(i=0; i<lemp->nsymbol; i++){
3491 struct symbol *sp = lemp->symbols[i];
3492 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3493 fprintf(out," case %d:\n",sp->index); lineno++;
3494 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3495 fprintf(out," break;\n"); lineno++;
3496 }
drh960e8c62001-04-03 16:53:21 +00003497 if( lemp->vardest ){
3498 struct symbol *dflt_sp = 0;
3499 for(i=0; i<lemp->nsymbol; i++){
3500 struct symbol *sp = lemp->symbols[i];
3501 if( sp==0 || sp->type==TERMINAL ||
3502 sp->index<=0 || sp->destructor!=0 ) continue;
3503 fprintf(out," case %d:\n",sp->index); lineno++;
3504 dflt_sp = sp;
3505 }
3506 if( dflt_sp!=0 ){
3507 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3508 fprintf(out," break;\n"); lineno++;
3509 }
3510 }
drh75897232000-05-29 14:26:00 +00003511 tplt_xfer(lemp->name,in,out,&lineno);
3512
3513 /* Generate code which executes whenever the parser stack overflows */
3514 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3515 tplt_xfer(lemp->name,in,out,&lineno);
3516
3517 /* Generate the table of rule information
3518 **
3519 ** Note: This code depends on the fact that rules are number
3520 ** sequentually beginning with 0.
3521 */
3522 for(rp=lemp->rule; rp; rp=rp->next){
3523 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3524 }
3525 tplt_xfer(lemp->name,in,out,&lineno);
3526
3527 /* Generate code which execution during each REDUCE action */
3528 for(rp=lemp->rule; rp; rp=rp->next){
3529 fprintf(out," case %d:\n",rp->index); lineno++;
drh75897232000-05-29 14:26:00 +00003530 emit_code(out,rp,lemp,&lineno);
3531 fprintf(out," break;\n"); lineno++;
3532 }
3533 tplt_xfer(lemp->name,in,out,&lineno);
3534
3535 /* Generate code which executes if a parse fails */
3536 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3537 tplt_xfer(lemp->name,in,out,&lineno);
3538
3539 /* Generate code which executes when a syntax error occurs */
3540 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3541 tplt_xfer(lemp->name,in,out,&lineno);
3542
3543 /* Generate code which executes when the parser accepts its input */
3544 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3545 tplt_xfer(lemp->name,in,out,&lineno);
3546
3547 /* Append any addition code the user desires */
3548 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3549
3550 fclose(in);
3551 fclose(out);
3552 return;
3553}
3554
3555/* Generate a header file for the parser */
3556void ReportHeader(lemp)
3557struct lemon *lemp;
3558{
3559 FILE *out, *in;
3560 char *prefix;
3561 char line[LINESIZE];
3562 char pattern[LINESIZE];
3563 int i;
3564
3565 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3566 else prefix = "";
3567 in = file_open(lemp,".h","r");
3568 if( in ){
3569 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3570 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3571 if( strcmp(line,pattern) ) break;
3572 }
3573 fclose(in);
3574 if( i==lemp->nterminal ){
3575 /* No change in the file. Don't rewrite it. */
3576 return;
3577 }
3578 }
3579 out = file_open(lemp,".h","w");
3580 if( out ){
3581 for(i=1; i<lemp->nterminal; i++){
3582 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3583 }
3584 fclose(out);
3585 }
3586 return;
3587}
3588
3589/* Reduce the size of the action tables, if possible, by making use
3590** of defaults.
3591**
drhb59499c2002-02-23 18:45:13 +00003592** In this version, we take the most frequent REDUCE action and make
3593** it the default. Only default a reduce if there are more than one.
drh75897232000-05-29 14:26:00 +00003594*/
3595void CompressTables(lemp)
3596struct lemon *lemp;
3597{
3598 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003599 struct action *ap, *ap2;
3600 struct rule *rp, *rp2, *rbest;
3601 int nbest, n;
drh75897232000-05-29 14:26:00 +00003602 int i;
drh75897232000-05-29 14:26:00 +00003603
3604 for(i=0; i<lemp->nstate; i++){
3605 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003606 nbest = 0;
3607 rbest = 0;
drh75897232000-05-29 14:26:00 +00003608
drhb59499c2002-02-23 18:45:13 +00003609 for(ap=stp->ap; ap; ap=ap->next){
3610 if( ap->type!=REDUCE ) continue;
3611 rp = ap->x.rp;
3612 if( rp==rbest ) continue;
3613 n = 1;
3614 for(ap2=ap->next; ap2; ap2=ap2->next){
3615 if( ap2->type!=REDUCE ) continue;
3616 rp2 = ap2->x.rp;
3617 if( rp2==rbest ) continue;
3618 if( rp2==rp ) n++;
3619 }
3620 if( n>nbest ){
3621 nbest = n;
3622 rbest = rp;
drh75897232000-05-29 14:26:00 +00003623 }
3624 }
drhb59499c2002-02-23 18:45:13 +00003625
3626 /* Do not make a default if the number of rules to default
3627 ** is not at least 2 */
3628 if( nbest<2 ) continue;
drh75897232000-05-29 14:26:00 +00003629
drhb59499c2002-02-23 18:45:13 +00003630
3631 /* Combine matching REDUCE actions into a single default */
3632 for(ap=stp->ap; ap; ap=ap->next){
3633 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3634 }
drh75897232000-05-29 14:26:00 +00003635 assert( ap );
3636 ap->sp = Symbol_new("{default}");
3637 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003638 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003639 }
3640 stp->ap = Action_sort(stp->ap);
3641 }
3642}
drhb59499c2002-02-23 18:45:13 +00003643
drh75897232000-05-29 14:26:00 +00003644/***************** From the file "set.c" ************************************/
3645/*
3646** Set manipulation routines for the LEMON parser generator.
3647*/
3648
3649static int size = 0;
3650
3651/* Set the set size */
3652void SetSize(n)
3653int n;
3654{
3655 size = n+1;
3656}
3657
3658/* Allocate a new set */
3659char *SetNew(){
3660 char *s;
3661 int i;
3662 s = (char*)malloc( size );
3663 if( s==0 ){
3664 extern void memory_error();
3665 memory_error();
3666 }
3667 for(i=0; i<size; i++) s[i] = 0;
3668 return s;
3669}
3670
3671/* Deallocate a set */
3672void SetFree(s)
3673char *s;
3674{
3675 free(s);
3676}
3677
3678/* Add a new element to the set. Return TRUE if the element was added
3679** and FALSE if it was already there. */
3680int SetAdd(s,e)
3681char *s;
3682int e;
3683{
3684 int rv;
3685 rv = s[e];
3686 s[e] = 1;
3687 return !rv;
3688}
3689
3690/* Add every element of s2 to s1. Return TRUE if s1 changes. */
3691int SetUnion(s1,s2)
3692char *s1;
3693char *s2;
3694{
3695 int i, progress;
3696 progress = 0;
3697 for(i=0; i<size; i++){
3698 if( s2[i]==0 ) continue;
3699 if( s1[i]==0 ){
3700 progress = 1;
3701 s1[i] = 1;
3702 }
3703 }
3704 return progress;
3705}
3706/********************** From the file "table.c" ****************************/
3707/*
3708** All code in this file has been automatically generated
3709** from a specification in the file
3710** "table.q"
3711** by the associative array code building program "aagen".
3712** Do not edit this file! Instead, edit the specification
3713** file, then rerun aagen.
3714*/
3715/*
3716** Code for processing tables in the LEMON parser generator.
3717*/
3718
3719PRIVATE int strhash(x)
3720char *x;
3721{
3722 int h = 0;
3723 while( *x) h = h*13 + *(x++);
3724 return h;
3725}
3726
3727/* Works like strdup, sort of. Save a string in malloced memory, but
3728** keep strings in a table so that the same string is not in more
3729** than one place.
3730*/
3731char *Strsafe(y)
3732char *y;
3733{
3734 char *z;
3735
3736 z = Strsafe_find(y);
3737 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
3738 strcpy(z,y);
3739 Strsafe_insert(z);
3740 }
3741 MemoryCheck(z);
3742 return z;
3743}
3744
3745/* There is one instance of the following structure for each
3746** associative array of type "x1".
3747*/
3748struct s_x1 {
3749 int size; /* The number of available slots. */
3750 /* Must be a power of 2 greater than or */
3751 /* equal to 1 */
3752 int count; /* Number of currently slots filled */
3753 struct s_x1node *tbl; /* The data stored here */
3754 struct s_x1node **ht; /* Hash table for lookups */
3755};
3756
3757/* There is one instance of this structure for every data element
3758** in an associative array of type "x1".
3759*/
3760typedef struct s_x1node {
3761 char *data; /* The data */
3762 struct s_x1node *next; /* Next entry with the same hash */
3763 struct s_x1node **from; /* Previous link */
3764} x1node;
3765
3766/* There is only one instance of the array, which is the following */
3767static struct s_x1 *x1a;
3768
3769/* Allocate a new associative array */
3770void Strsafe_init(){
3771 if( x1a ) return;
3772 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
3773 if( x1a ){
3774 x1a->size = 1024;
3775 x1a->count = 0;
3776 x1a->tbl = (x1node*)malloc(
3777 (sizeof(x1node) + sizeof(x1node*))*1024 );
3778 if( x1a->tbl==0 ){
3779 free(x1a);
3780 x1a = 0;
3781 }else{
3782 int i;
3783 x1a->ht = (x1node**)&(x1a->tbl[1024]);
3784 for(i=0; i<1024; i++) x1a->ht[i] = 0;
3785 }
3786 }
3787}
3788/* Insert a new record into the array. Return TRUE if successful.
3789** Prior data with the same key is NOT overwritten */
3790int Strsafe_insert(data)
3791char *data;
3792{
3793 x1node *np;
3794 int h;
3795 int ph;
3796
3797 if( x1a==0 ) return 0;
3798 ph = strhash(data);
3799 h = ph & (x1a->size-1);
3800 np = x1a->ht[h];
3801 while( np ){
3802 if( strcmp(np->data,data)==0 ){
3803 /* An existing entry with the same key is found. */
3804 /* Fail because overwrite is not allows. */
3805 return 0;
3806 }
3807 np = np->next;
3808 }
3809 if( x1a->count>=x1a->size ){
3810 /* Need to make the hash table bigger */
3811 int i,size;
3812 struct s_x1 array;
3813 array.size = size = x1a->size*2;
3814 array.count = x1a->count;
3815 array.tbl = (x1node*)malloc(
3816 (sizeof(x1node) + sizeof(x1node*))*size );
3817 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3818 array.ht = (x1node**)&(array.tbl[size]);
3819 for(i=0; i<size; i++) array.ht[i] = 0;
3820 for(i=0; i<x1a->count; i++){
3821 x1node *oldnp, *newnp;
3822 oldnp = &(x1a->tbl[i]);
3823 h = strhash(oldnp->data) & (size-1);
3824 newnp = &(array.tbl[i]);
3825 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3826 newnp->next = array.ht[h];
3827 newnp->data = oldnp->data;
3828 newnp->from = &(array.ht[h]);
3829 array.ht[h] = newnp;
3830 }
3831 free(x1a->tbl);
3832 *x1a = array;
3833 }
3834 /* Insert the new data */
3835 h = ph & (x1a->size-1);
3836 np = &(x1a->tbl[x1a->count++]);
3837 np->data = data;
3838 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
3839 np->next = x1a->ht[h];
3840 x1a->ht[h] = np;
3841 np->from = &(x1a->ht[h]);
3842 return 1;
3843}
3844
3845/* Return a pointer to data assigned to the given key. Return NULL
3846** if no such key. */
3847char *Strsafe_find(key)
3848char *key;
3849{
3850 int h;
3851 x1node *np;
3852
3853 if( x1a==0 ) return 0;
3854 h = strhash(key) & (x1a->size-1);
3855 np = x1a->ht[h];
3856 while( np ){
3857 if( strcmp(np->data,key)==0 ) break;
3858 np = np->next;
3859 }
3860 return np ? np->data : 0;
3861}
3862
3863/* Return a pointer to the (terminal or nonterminal) symbol "x".
3864** Create a new symbol if this is the first time "x" has been seen.
3865*/
3866struct symbol *Symbol_new(x)
3867char *x;
3868{
3869 struct symbol *sp;
3870
3871 sp = Symbol_find(x);
3872 if( sp==0 ){
3873 sp = (struct symbol *)malloc( sizeof(struct symbol) );
3874 MemoryCheck(sp);
3875 sp->name = Strsafe(x);
3876 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
3877 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00003878 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00003879 sp->prec = -1;
3880 sp->assoc = UNK;
3881 sp->firstset = 0;
drhb27b83a2002-08-14 23:18:57 +00003882 sp->lambda = B_FALSE;
drh75897232000-05-29 14:26:00 +00003883 sp->destructor = 0;
3884 sp->datatype = 0;
3885 Symbol_insert(sp,sp->name);
3886 }
3887 return sp;
3888}
3889
drh60d31652004-02-22 00:08:04 +00003890/* Compare two symbols for working purposes
3891**
3892** Symbols that begin with upper case letters (terminals or tokens)
3893** must sort before symbols that begin with lower case letters
3894** (non-terminals). Other than that, the order does not matter.
3895**
3896** We find experimentally that leaving the symbols in their original
3897** order (the order they appeared in the grammar file) gives the
3898** smallest parser tables in SQLite.
3899*/
3900int Symbolcmpp(struct symbol **a, struct symbol **b){
3901 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
3902 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
3903 return i1-i2;
drh75897232000-05-29 14:26:00 +00003904}
3905
3906/* There is one instance of the following structure for each
3907** associative array of type "x2".
3908*/
3909struct s_x2 {
3910 int size; /* The number of available slots. */
3911 /* Must be a power of 2 greater than or */
3912 /* equal to 1 */
3913 int count; /* Number of currently slots filled */
3914 struct s_x2node *tbl; /* The data stored here */
3915 struct s_x2node **ht; /* Hash table for lookups */
3916};
3917
3918/* There is one instance of this structure for every data element
3919** in an associative array of type "x2".
3920*/
3921typedef struct s_x2node {
3922 struct symbol *data; /* The data */
3923 char *key; /* The key */
3924 struct s_x2node *next; /* Next entry with the same hash */
3925 struct s_x2node **from; /* Previous link */
3926} x2node;
3927
3928/* There is only one instance of the array, which is the following */
3929static struct s_x2 *x2a;
3930
3931/* Allocate a new associative array */
3932void Symbol_init(){
3933 if( x2a ) return;
3934 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
3935 if( x2a ){
3936 x2a->size = 128;
3937 x2a->count = 0;
3938 x2a->tbl = (x2node*)malloc(
3939 (sizeof(x2node) + sizeof(x2node*))*128 );
3940 if( x2a->tbl==0 ){
3941 free(x2a);
3942 x2a = 0;
3943 }else{
3944 int i;
3945 x2a->ht = (x2node**)&(x2a->tbl[128]);
3946 for(i=0; i<128; i++) x2a->ht[i] = 0;
3947 }
3948 }
3949}
3950/* Insert a new record into the array. Return TRUE if successful.
3951** Prior data with the same key is NOT overwritten */
3952int Symbol_insert(data,key)
3953struct symbol *data;
3954char *key;
3955{
3956 x2node *np;
3957 int h;
3958 int ph;
3959
3960 if( x2a==0 ) return 0;
3961 ph = strhash(key);
3962 h = ph & (x2a->size-1);
3963 np = x2a->ht[h];
3964 while( np ){
3965 if( strcmp(np->key,key)==0 ){
3966 /* An existing entry with the same key is found. */
3967 /* Fail because overwrite is not allows. */
3968 return 0;
3969 }
3970 np = np->next;
3971 }
3972 if( x2a->count>=x2a->size ){
3973 /* Need to make the hash table bigger */
3974 int i,size;
3975 struct s_x2 array;
3976 array.size = size = x2a->size*2;
3977 array.count = x2a->count;
3978 array.tbl = (x2node*)malloc(
3979 (sizeof(x2node) + sizeof(x2node*))*size );
3980 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
3981 array.ht = (x2node**)&(array.tbl[size]);
3982 for(i=0; i<size; i++) array.ht[i] = 0;
3983 for(i=0; i<x2a->count; i++){
3984 x2node *oldnp, *newnp;
3985 oldnp = &(x2a->tbl[i]);
3986 h = strhash(oldnp->key) & (size-1);
3987 newnp = &(array.tbl[i]);
3988 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
3989 newnp->next = array.ht[h];
3990 newnp->key = oldnp->key;
3991 newnp->data = oldnp->data;
3992 newnp->from = &(array.ht[h]);
3993 array.ht[h] = newnp;
3994 }
3995 free(x2a->tbl);
3996 *x2a = array;
3997 }
3998 /* Insert the new data */
3999 h = ph & (x2a->size-1);
4000 np = &(x2a->tbl[x2a->count++]);
4001 np->key = key;
4002 np->data = data;
4003 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4004 np->next = x2a->ht[h];
4005 x2a->ht[h] = np;
4006 np->from = &(x2a->ht[h]);
4007 return 1;
4008}
4009
4010/* Return a pointer to data assigned to the given key. Return NULL
4011** if no such key. */
4012struct symbol *Symbol_find(key)
4013char *key;
4014{
4015 int h;
4016 x2node *np;
4017
4018 if( x2a==0 ) return 0;
4019 h = strhash(key) & (x2a->size-1);
4020 np = x2a->ht[h];
4021 while( np ){
4022 if( strcmp(np->key,key)==0 ) break;
4023 np = np->next;
4024 }
4025 return np ? np->data : 0;
4026}
4027
4028/* Return the n-th data. Return NULL if n is out of range. */
4029struct symbol *Symbol_Nth(n)
4030int n;
4031{
4032 struct symbol *data;
4033 if( x2a && n>0 && n<=x2a->count ){
4034 data = x2a->tbl[n-1].data;
4035 }else{
4036 data = 0;
4037 }
4038 return data;
4039}
4040
4041/* Return the size of the array */
4042int Symbol_count()
4043{
4044 return x2a ? x2a->count : 0;
4045}
4046
4047/* Return an array of pointers to all data in the table.
4048** The array is obtained from malloc. Return NULL if memory allocation
4049** problems, or if the array is empty. */
4050struct symbol **Symbol_arrayof()
4051{
4052 struct symbol **array;
4053 int i,size;
4054 if( x2a==0 ) return 0;
4055 size = x2a->count;
4056 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4057 if( array ){
4058 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4059 }
4060 return array;
4061}
4062
4063/* Compare two configurations */
4064int Configcmp(a,b)
4065struct config *a;
4066struct config *b;
4067{
4068 int x;
4069 x = a->rp->index - b->rp->index;
4070 if( x==0 ) x = a->dot - b->dot;
4071 return x;
4072}
4073
4074/* Compare two states */
4075PRIVATE int statecmp(a,b)
4076struct config *a;
4077struct config *b;
4078{
4079 int rc;
4080 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4081 rc = a->rp->index - b->rp->index;
4082 if( rc==0 ) rc = a->dot - b->dot;
4083 }
4084 if( rc==0 ){
4085 if( a ) rc = 1;
4086 if( b ) rc = -1;
4087 }
4088 return rc;
4089}
4090
4091/* Hash a state */
4092PRIVATE int statehash(a)
4093struct config *a;
4094{
4095 int h=0;
4096 while( a ){
4097 h = h*571 + a->rp->index*37 + a->dot;
4098 a = a->bp;
4099 }
4100 return h;
4101}
4102
4103/* Allocate a new state structure */
4104struct state *State_new()
4105{
4106 struct state *new;
4107 new = (struct state *)malloc( sizeof(struct state) );
4108 MemoryCheck(new);
4109 return new;
4110}
4111
4112/* There is one instance of the following structure for each
4113** associative array of type "x3".
4114*/
4115struct s_x3 {
4116 int size; /* The number of available slots. */
4117 /* Must be a power of 2 greater than or */
4118 /* equal to 1 */
4119 int count; /* Number of currently slots filled */
4120 struct s_x3node *tbl; /* The data stored here */
4121 struct s_x3node **ht; /* Hash table for lookups */
4122};
4123
4124/* There is one instance of this structure for every data element
4125** in an associative array of type "x3".
4126*/
4127typedef struct s_x3node {
4128 struct state *data; /* The data */
4129 struct config *key; /* The key */
4130 struct s_x3node *next; /* Next entry with the same hash */
4131 struct s_x3node **from; /* Previous link */
4132} x3node;
4133
4134/* There is only one instance of the array, which is the following */
4135static struct s_x3 *x3a;
4136
4137/* Allocate a new associative array */
4138void State_init(){
4139 if( x3a ) return;
4140 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4141 if( x3a ){
4142 x3a->size = 128;
4143 x3a->count = 0;
4144 x3a->tbl = (x3node*)malloc(
4145 (sizeof(x3node) + sizeof(x3node*))*128 );
4146 if( x3a->tbl==0 ){
4147 free(x3a);
4148 x3a = 0;
4149 }else{
4150 int i;
4151 x3a->ht = (x3node**)&(x3a->tbl[128]);
4152 for(i=0; i<128; i++) x3a->ht[i] = 0;
4153 }
4154 }
4155}
4156/* Insert a new record into the array. Return TRUE if successful.
4157** Prior data with the same key is NOT overwritten */
4158int State_insert(data,key)
4159struct state *data;
4160struct config *key;
4161{
4162 x3node *np;
4163 int h;
4164 int ph;
4165
4166 if( x3a==0 ) return 0;
4167 ph = statehash(key);
4168 h = ph & (x3a->size-1);
4169 np = x3a->ht[h];
4170 while( np ){
4171 if( statecmp(np->key,key)==0 ){
4172 /* An existing entry with the same key is found. */
4173 /* Fail because overwrite is not allows. */
4174 return 0;
4175 }
4176 np = np->next;
4177 }
4178 if( x3a->count>=x3a->size ){
4179 /* Need to make the hash table bigger */
4180 int i,size;
4181 struct s_x3 array;
4182 array.size = size = x3a->size*2;
4183 array.count = x3a->count;
4184 array.tbl = (x3node*)malloc(
4185 (sizeof(x3node) + sizeof(x3node*))*size );
4186 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4187 array.ht = (x3node**)&(array.tbl[size]);
4188 for(i=0; i<size; i++) array.ht[i] = 0;
4189 for(i=0; i<x3a->count; i++){
4190 x3node *oldnp, *newnp;
4191 oldnp = &(x3a->tbl[i]);
4192 h = statehash(oldnp->key) & (size-1);
4193 newnp = &(array.tbl[i]);
4194 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4195 newnp->next = array.ht[h];
4196 newnp->key = oldnp->key;
4197 newnp->data = oldnp->data;
4198 newnp->from = &(array.ht[h]);
4199 array.ht[h] = newnp;
4200 }
4201 free(x3a->tbl);
4202 *x3a = array;
4203 }
4204 /* Insert the new data */
4205 h = ph & (x3a->size-1);
4206 np = &(x3a->tbl[x3a->count++]);
4207 np->key = key;
4208 np->data = data;
4209 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4210 np->next = x3a->ht[h];
4211 x3a->ht[h] = np;
4212 np->from = &(x3a->ht[h]);
4213 return 1;
4214}
4215
4216/* Return a pointer to data assigned to the given key. Return NULL
4217** if no such key. */
4218struct state *State_find(key)
4219struct config *key;
4220{
4221 int h;
4222 x3node *np;
4223
4224 if( x3a==0 ) return 0;
4225 h = statehash(key) & (x3a->size-1);
4226 np = x3a->ht[h];
4227 while( np ){
4228 if( statecmp(np->key,key)==0 ) break;
4229 np = np->next;
4230 }
4231 return np ? np->data : 0;
4232}
4233
4234/* Return an array of pointers to all data in the table.
4235** The array is obtained from malloc. Return NULL if memory allocation
4236** problems, or if the array is empty. */
4237struct state **State_arrayof()
4238{
4239 struct state **array;
4240 int i,size;
4241 if( x3a==0 ) return 0;
4242 size = x3a->count;
4243 array = (struct state **)malloc( sizeof(struct state *)*size );
4244 if( array ){
4245 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4246 }
4247 return array;
4248}
4249
4250/* Hash a configuration */
4251PRIVATE int confighash(a)
4252struct config *a;
4253{
4254 int h=0;
4255 h = h*571 + a->rp->index*37 + a->dot;
4256 return h;
4257}
4258
4259/* There is one instance of the following structure for each
4260** associative array of type "x4".
4261*/
4262struct s_x4 {
4263 int size; /* The number of available slots. */
4264 /* Must be a power of 2 greater than or */
4265 /* equal to 1 */
4266 int count; /* Number of currently slots filled */
4267 struct s_x4node *tbl; /* The data stored here */
4268 struct s_x4node **ht; /* Hash table for lookups */
4269};
4270
4271/* There is one instance of this structure for every data element
4272** in an associative array of type "x4".
4273*/
4274typedef struct s_x4node {
4275 struct config *data; /* The data */
4276 struct s_x4node *next; /* Next entry with the same hash */
4277 struct s_x4node **from; /* Previous link */
4278} x4node;
4279
4280/* There is only one instance of the array, which is the following */
4281static struct s_x4 *x4a;
4282
4283/* Allocate a new associative array */
4284void Configtable_init(){
4285 if( x4a ) return;
4286 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4287 if( x4a ){
4288 x4a->size = 64;
4289 x4a->count = 0;
4290 x4a->tbl = (x4node*)malloc(
4291 (sizeof(x4node) + sizeof(x4node*))*64 );
4292 if( x4a->tbl==0 ){
4293 free(x4a);
4294 x4a = 0;
4295 }else{
4296 int i;
4297 x4a->ht = (x4node**)&(x4a->tbl[64]);
4298 for(i=0; i<64; i++) x4a->ht[i] = 0;
4299 }
4300 }
4301}
4302/* Insert a new record into the array. Return TRUE if successful.
4303** Prior data with the same key is NOT overwritten */
4304int Configtable_insert(data)
4305struct config *data;
4306{
4307 x4node *np;
4308 int h;
4309 int ph;
4310
4311 if( x4a==0 ) return 0;
4312 ph = confighash(data);
4313 h = ph & (x4a->size-1);
4314 np = x4a->ht[h];
4315 while( np ){
4316 if( Configcmp(np->data,data)==0 ){
4317 /* An existing entry with the same key is found. */
4318 /* Fail because overwrite is not allows. */
4319 return 0;
4320 }
4321 np = np->next;
4322 }
4323 if( x4a->count>=x4a->size ){
4324 /* Need to make the hash table bigger */
4325 int i,size;
4326 struct s_x4 array;
4327 array.size = size = x4a->size*2;
4328 array.count = x4a->count;
4329 array.tbl = (x4node*)malloc(
4330 (sizeof(x4node) + sizeof(x4node*))*size );
4331 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4332 array.ht = (x4node**)&(array.tbl[size]);
4333 for(i=0; i<size; i++) array.ht[i] = 0;
4334 for(i=0; i<x4a->count; i++){
4335 x4node *oldnp, *newnp;
4336 oldnp = &(x4a->tbl[i]);
4337 h = confighash(oldnp->data) & (size-1);
4338 newnp = &(array.tbl[i]);
4339 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4340 newnp->next = array.ht[h];
4341 newnp->data = oldnp->data;
4342 newnp->from = &(array.ht[h]);
4343 array.ht[h] = newnp;
4344 }
4345 free(x4a->tbl);
4346 *x4a = array;
4347 }
4348 /* Insert the new data */
4349 h = ph & (x4a->size-1);
4350 np = &(x4a->tbl[x4a->count++]);
4351 np->data = data;
4352 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4353 np->next = x4a->ht[h];
4354 x4a->ht[h] = np;
4355 np->from = &(x4a->ht[h]);
4356 return 1;
4357}
4358
4359/* Return a pointer to data assigned to the given key. Return NULL
4360** if no such key. */
4361struct config *Configtable_find(key)
4362struct config *key;
4363{
4364 int h;
4365 x4node *np;
4366
4367 if( x4a==0 ) return 0;
4368 h = confighash(key) & (x4a->size-1);
4369 np = x4a->ht[h];
4370 while( np ){
4371 if( Configcmp(np->data,key)==0 ) break;
4372 np = np->next;
4373 }
4374 return np ? np->data : 0;
4375}
4376
4377/* Remove all data from the table. Pass each data to the function "f"
4378** as it is removed. ("f" may be null to avoid this step.) */
4379void Configtable_clear(f)
4380int(*f)(/* struct config * */);
4381{
4382 int i;
4383 if( x4a==0 || x4a->count==0 ) return;
4384 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4385 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4386 x4a->count = 0;
4387 return;
4388}