blob: f7c12814bc0174835a64750cb8caad5e19dcc2a3 [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
drh75897232000-05-29 14:26:00 +000015#ifndef __WIN32__
16# if defined(_WIN32) || defined(WIN32)
17# define __WIN32__
18# endif
19#endif
20
21/* #define PRIVATE static */
22#define PRIVATE
23
24#ifdef TEST
25#define MAXRHS 5 /* Set low to exercise exception code */
26#else
27#define MAXRHS 1000
28#endif
29
30char *msort();
31extern void *malloc();
32
33/******** From the file "action.h" *************************************/
34struct action *Action_new();
35struct action *Action_sort();
drh75897232000-05-29 14:26:00 +000036
37/********* From the file "assert.h" ************************************/
38void myassert();
39#ifndef NDEBUG
40# define assert(X) if(!(X))myassert(__FILE__,__LINE__)
41#else
42# define assert(X)
43#endif
44
45/********** From the file "build.h" ************************************/
46void FindRulePrecedences();
47void FindFirstSets();
48void FindStates();
49void FindLinks();
50void FindFollowSets();
51void FindActions();
52
53/********* From the file "configlist.h" *********************************/
54void Configlist_init(/* void */);
55struct config *Configlist_add(/* struct rule *, int */);
56struct config *Configlist_addbasis(/* struct rule *, int */);
57void Configlist_closure(/* void */);
58void Configlist_sort(/* void */);
59void Configlist_sortbasis(/* void */);
60struct config *Configlist_return(/* void */);
61struct config *Configlist_basis(/* void */);
62void Configlist_eat(/* struct config * */);
63void Configlist_reset(/* void */);
64
65/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000066void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000067
68/****** From the file "option.h" ******************************************/
69struct s_options {
70 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
71 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
72 char *label;
73 char *arg;
74 char *message;
75};
drhb0c86772000-06-02 23:21:26 +000076int OptInit(/* char**,struct s_options*,FILE* */);
77int OptNArgs(/* void */);
78char *OptArg(/* int */);
79void OptErr(/* int */);
80void OptPrint(/* void */);
drh75897232000-05-29 14:26:00 +000081
82/******** From the file "parse.h" *****************************************/
83void Parse(/* struct lemon *lemp */);
84
85/********* From the file "plink.h" ***************************************/
86struct plink *Plink_new(/* void */);
87void Plink_add(/* struct plink **, struct config * */);
88void Plink_copy(/* struct plink **, struct plink * */);
89void Plink_delete(/* struct plink * */);
90
91/********** From the file "report.h" *************************************/
92void Reprint(/* struct lemon * */);
93void ReportOutput(/* struct lemon * */);
94void ReportTable(/* struct lemon * */);
95void ReportHeader(/* struct lemon * */);
96void CompressTables(/* struct lemon * */);
drhada354d2005-11-05 15:03:59 +000097void ResortStates(/* struct lemon * */);
drh75897232000-05-29 14:26:00 +000098
99/********** From the file "set.h" ****************************************/
100void SetSize(/* int N */); /* All sets will be of size N */
101char *SetNew(/* void */); /* A new set for element 0..N */
102void SetFree(/* char* */); /* Deallocate a set */
103
104int SetAdd(/* char*,int */); /* Add element to a set */
105int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
106
107#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
108
109/********** From the file "struct.h" *************************************/
110/*
111** Principal data structures for the LEMON parser generator.
112*/
113
drhb27b83a2002-08-14 23:18:57 +0000114typedef enum {B_FALSE=0, B_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000115
116/* Symbols (terminals and nonterminals) of the grammar are stored
117** in the following: */
118struct symbol {
119 char *name; /* Name of the symbol */
120 int index; /* Index number for this symbol */
121 enum {
122 TERMINAL,
drhfd405312005-11-06 04:06:59 +0000123 NONTERMINAL,
124 MULTITERMINAL
drh75897232000-05-29 14:26:00 +0000125 } type; /* Symbols are all either TERMINALS or NTs */
126 struct rule *rule; /* Linked list of rules of this (if an NT) */
drh0bd1f4e2002-06-06 18:54:39 +0000127 struct symbol *fallback; /* fallback token in case this token doesn't parse */
drh75897232000-05-29 14:26:00 +0000128 int prec; /* Precedence if defined (-1 otherwise) */
129 enum e_assoc {
130 LEFT,
131 RIGHT,
132 NONE,
133 UNK
134 } assoc; /* Associativity if predecence is defined */
135 char *firstset; /* First-set for all rules of this symbol */
136 Boolean lambda; /* True if NT and can generate an empty string */
137 char *destructor; /* Code which executes whenever this symbol is
138 ** popped from the stack during error processing */
139 int destructorln; /* Line number of destructor code */
140 char *datatype; /* The data type of information held by this
141 ** object. Only used if type==NONTERMINAL */
142 int dtnum; /* The data type number. In the parser, the value
143 ** stack is a union. The .yy%d element of this
144 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000145 /* The following fields are used by MULTITERMINALs only */
146 int nsubsym; /* Number of constituent symbols in the MULTI */
147 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000148};
149
150/* Each production rule in the grammar is stored in the following
151** structure. */
152struct rule {
153 struct symbol *lhs; /* Left-hand side of the rule */
154 char *lhsalias; /* Alias for the LHS (NULL if none) */
155 int ruleline; /* Line number for the rule */
156 int nrhs; /* Number of RHS symbols */
157 struct symbol **rhs; /* The RHS symbols */
158 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
159 int line; /* Line number at which code begins */
160 char *code; /* The code executed when this rule is reduced */
161 struct symbol *precsym; /* Precedence symbol for this rule */
162 int index; /* An index number for this rule */
163 Boolean canReduce; /* True if this rule is ever reduced */
164 struct rule *nextlhs; /* Next rule with the same LHS */
165 struct rule *next; /* Next rule in the global list */
166};
167
168/* A configuration is a production rule of the grammar together with
169** a mark (dot) showing how much of that rule has been processed so far.
170** Configurations also contain a follow-set which is a list of terminal
171** symbols which are allowed to immediately follow the end of the rule.
172** Every configuration is recorded as an instance of the following: */
173struct config {
174 struct rule *rp; /* The rule upon which the configuration is based */
175 int dot; /* The parse point */
176 char *fws; /* Follow-set for this configuration only */
177 struct plink *fplp; /* Follow-set forward propagation links */
178 struct plink *bplp; /* Follow-set backwards propagation links */
179 struct state *stp; /* Pointer to state which contains this */
180 enum {
181 COMPLETE, /* The status is used during followset and */
182 INCOMPLETE /* shift computations */
183 } status;
184 struct config *next; /* Next configuration in the state */
185 struct config *bp; /* The next basis configuration */
186};
187
188/* Every shift or reduce operation is stored as one of the following */
189struct action {
190 struct symbol *sp; /* The look-ahead symbol */
191 enum e_action {
192 SHIFT,
193 ACCEPT,
194 REDUCE,
195 ERROR,
196 CONFLICT, /* Was a reduce, but part of a conflict */
197 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
198 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
199 NOT_USED /* Deleted by compression */
200 } type;
201 union {
202 struct state *stp; /* The new state, if a shift */
203 struct rule *rp; /* The rule, if a reduce */
204 } x;
205 struct action *next; /* Next action for this state */
206 struct action *collide; /* Next action with the same hash */
207};
208
209/* Each state of the generated parser's finite state machine
210** is encoded as an instance of the following structure. */
211struct state {
212 struct config *bp; /* The basis configurations for this state */
213 struct config *cfp; /* All configurations in this set */
drhada354d2005-11-05 15:03:59 +0000214 int statenum; /* Sequencial number for this state */
drh75897232000-05-29 14:26:00 +0000215 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000216 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
217 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
218 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000219};
drh8b582012003-10-21 13:16:03 +0000220#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000221
222/* A followset propagation link indicates that the contents of one
223** configuration followset should be propagated to another whenever
224** the first changes. */
225struct plink {
226 struct config *cfp; /* The configuration to which linked */
227 struct plink *next; /* The next propagate link */
228};
229
230/* The state vector for the entire parser generator is recorded as
231** follows. (LEMON uses no global variables and makes little use of
232** static variables. Fields in the following structure can be thought
233** of as begin global variables in the program.) */
234struct lemon {
235 struct state **sorted; /* Table of states sorted by state number */
236 struct rule *rule; /* List of all rules */
237 int nstate; /* Number of states */
238 int nrule; /* Number of rules */
239 int nsymbol; /* Number of terminal and nonterminal symbols */
240 int nterminal; /* Number of terminal symbols */
241 struct symbol **symbols; /* Sorted array of pointers to symbols */
242 int errorcnt; /* Number of errors */
243 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000244 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000245 char *name; /* Name of the generated parser */
246 char *arg; /* Declaration of the 3th argument to parser */
247 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000248 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000249 char *start; /* Name of the start symbol for the grammar */
250 char *stacksize; /* Size of the parser stack */
251 char *include; /* Code to put at the start of the C file */
252 int includeln; /* Line number for start of include code */
253 char *error; /* Code to execute when an error is seen */
254 int errorln; /* Line number for start of error code */
255 char *overflow; /* Code to execute on a stack overflow */
256 int overflowln; /* Line number for start of overflow code */
257 char *failure; /* Code to execute on parser failure */
258 int failureln; /* Line number for start of failure code */
259 char *accept; /* Code to execute when the parser excepts */
260 int acceptln; /* Line number for the start of accept code */
261 char *extracode; /* Code appended to the generated file */
262 int extracodeln; /* Line number for the start of the extra code */
263 char *tokendest; /* Code to execute to destroy token data */
264 int tokendestln; /* Line number for token destroyer code */
drh960e8c62001-04-03 16:53:21 +0000265 char *vardest; /* Code for the default non-terminal destructor */
266 int vardestln; /* Line number for default non-term destructor code*/
drh75897232000-05-29 14:26:00 +0000267 char *filename; /* Name of the input file */
268 char *outname; /* Name of the current output file */
269 char *tokenprefix; /* A prefix added to token names in the .h file */
270 int nconflict; /* Number of parsing conflicts */
271 int tablesize; /* Size of the parse tables */
272 int basisflag; /* Print only basis configurations */
drh0bd1f4e2002-06-06 18:54:39 +0000273 int has_fallback; /* True if any %fallback is seen in the grammer */
drh75897232000-05-29 14:26:00 +0000274 char *argv0; /* Name of the program */
275};
276
277#define MemoryCheck(X) if((X)==0){ \
278 extern void memory_error(); \
279 memory_error(); \
280}
281
282/**************** From the file "table.h" *********************************/
283/*
284** All code in this file has been automatically generated
285** from a specification in the file
286** "table.q"
287** by the associative array code building program "aagen".
288** Do not edit this file! Instead, edit the specification
289** file, then rerun aagen.
290*/
291/*
292** Code for processing tables in the LEMON parser generator.
293*/
294
295/* Routines for handling a strings */
296
297char *Strsafe();
298
299void Strsafe_init(/* void */);
300int Strsafe_insert(/* char * */);
301char *Strsafe_find(/* char * */);
302
303/* Routines for handling symbols of the grammar */
304
305struct symbol *Symbol_new();
306int Symbolcmpp(/* struct symbol **, struct symbol ** */);
307void Symbol_init(/* void */);
308int Symbol_insert(/* struct symbol *, char * */);
309struct symbol *Symbol_find(/* char * */);
310struct symbol *Symbol_Nth(/* int */);
311int Symbol_count(/* */);
312struct symbol **Symbol_arrayof(/* */);
313
314/* Routines to manage the state table */
315
316int Configcmp(/* struct config *, struct config * */);
317struct state *State_new();
318void State_init(/* void */);
319int State_insert(/* struct state *, struct config * */);
320struct state *State_find(/* struct config * */);
321struct state **State_arrayof(/* */);
322
323/* Routines used for efficiency in Configlist_add */
324
325void Configtable_init(/* void */);
326int Configtable_insert(/* struct config * */);
327struct config *Configtable_find(/* struct config * */);
328void Configtable_clear(/* int(*)(struct config *) */);
329/****************** From the file "action.c" *******************************/
330/*
331** Routines processing parser actions in the LEMON parser generator.
332*/
333
334/* Allocate a new parser action */
335struct action *Action_new(){
336 static struct action *freelist = 0;
337 struct action *new;
338
339 if( freelist==0 ){
340 int i;
341 int amt = 100;
342 freelist = (struct action *)malloc( sizeof(struct action)*amt );
343 if( freelist==0 ){
344 fprintf(stderr,"Unable to allocate memory for a new parser action.");
345 exit(1);
346 }
347 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
348 freelist[amt-1].next = 0;
349 }
350 new = freelist;
351 freelist = freelist->next;
352 return new;
353}
354
355/* Compare two actions */
356static int actioncmp(ap1,ap2)
357struct action *ap1;
358struct action *ap2;
359{
360 int rc;
361 rc = ap1->sp->index - ap2->sp->index;
362 if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
363 if( rc==0 ){
drh61bc2722000-08-20 11:42:46 +0000364 assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
365 assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
drh75897232000-05-29 14:26:00 +0000366 rc = ap1->x.rp->index - ap2->x.rp->index;
367 }
368 return rc;
369}
370
371/* Sort parser actions */
372struct action *Action_sort(ap)
373struct action *ap;
374{
drh218dc692004-05-31 23:13:45 +0000375 ap = (struct action *)msort((char *)ap,(char **)&ap->next,actioncmp);
drh75897232000-05-29 14:26:00 +0000376 return ap;
377}
378
379void Action_add(app,type,sp,arg)
380struct action **app;
381enum e_action type;
382struct symbol *sp;
383char *arg;
384{
385 struct action *new;
386 new = Action_new();
387 new->next = *app;
388 *app = new;
389 new->type = type;
390 new->sp = sp;
391 if( type==SHIFT ){
392 new->x.stp = (struct state *)arg;
393 }else{
394 new->x.rp = (struct rule *)arg;
395 }
396}
drh8b582012003-10-21 13:16:03 +0000397/********************** New code to implement the "acttab" module ***********/
398/*
399** This module implements routines use to construct the yy_action[] table.
400*/
401
402/*
403** The state of the yy_action table under construction is an instance of
404** the following structure
405*/
406typedef struct acttab acttab;
407struct acttab {
408 int nAction; /* Number of used slots in aAction[] */
409 int nActionAlloc; /* Slots allocated for aAction[] */
410 struct {
411 int lookahead; /* Value of the lookahead token */
412 int action; /* Action to take on the given lookahead */
413 } *aAction, /* The yy_action[] table under construction */
414 *aLookahead; /* A single new transaction set */
415 int mnLookahead; /* Minimum aLookahead[].lookahead */
416 int mnAction; /* Action associated with mnLookahead */
417 int mxLookahead; /* Maximum aLookahead[].lookahead */
418 int nLookahead; /* Used slots in aLookahead[] */
419 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
420};
421
422/* Return the number of entries in the yy_action table */
423#define acttab_size(X) ((X)->nAction)
424
425/* The value for the N-th entry in yy_action */
426#define acttab_yyaction(X,N) ((X)->aAction[N].action)
427
428/* The value for the N-th entry in yy_lookahead */
429#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
430
431/* Free all memory associated with the given acttab */
432void acttab_free(acttab *p){
433 free( p->aAction );
434 free( p->aLookahead );
435 free( p );
436}
437
438/* Allocate a new acttab structure */
439acttab *acttab_alloc(void){
440 acttab *p = malloc( sizeof(*p) );
441 if( p==0 ){
442 fprintf(stderr,"Unable to allocate memory for a new acttab.");
443 exit(1);
444 }
445 memset(p, 0, sizeof(*p));
446 return p;
447}
448
449/* Add a new action to the current transaction set
450*/
451void acttab_action(acttab *p, int lookahead, int action){
452 if( p->nLookahead>=p->nLookaheadAlloc ){
453 p->nLookaheadAlloc += 25;
454 p->aLookahead = realloc( p->aLookahead,
455 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
456 if( p->aLookahead==0 ){
457 fprintf(stderr,"malloc failed\n");
458 exit(1);
459 }
460 }
461 if( p->nLookahead==0 ){
462 p->mxLookahead = lookahead;
463 p->mnLookahead = lookahead;
464 p->mnAction = action;
465 }else{
466 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
467 if( p->mnLookahead>lookahead ){
468 p->mnLookahead = lookahead;
469 p->mnAction = action;
470 }
471 }
472 p->aLookahead[p->nLookahead].lookahead = lookahead;
473 p->aLookahead[p->nLookahead].action = action;
474 p->nLookahead++;
475}
476
477/*
478** Add the transaction set built up with prior calls to acttab_action()
479** into the current action table. Then reset the transaction set back
480** to an empty set in preparation for a new round of acttab_action() calls.
481**
482** Return the offset into the action table of the new transaction.
483*/
484int acttab_insert(acttab *p){
485 int i, j, k, n;
486 assert( p->nLookahead>0 );
487
488 /* Make sure we have enough space to hold the expanded action table
489 ** in the worst case. The worst case occurs if the transaction set
490 ** must be appended to the current action table
491 */
drh784d86f2004-02-19 18:41:53 +0000492 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000493 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000494 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000495 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
496 p->aAction = realloc( p->aAction,
497 sizeof(p->aAction[0])*p->nActionAlloc);
498 if( p->aAction==0 ){
499 fprintf(stderr,"malloc failed\n");
500 exit(1);
501 }
drhfdbf9282003-10-21 16:34:41 +0000502 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000503 p->aAction[i].lookahead = -1;
504 p->aAction[i].action = -1;
505 }
506 }
507
508 /* Scan the existing action table looking for an offset where we can
509 ** insert the current transaction set. Fall out of the loop when that
510 ** offset is found. In the worst case, we fall out of the loop when
511 ** i reaches p->nAction, which means we append the new transaction set.
512 **
513 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
514 */
drh784d86f2004-02-19 18:41:53 +0000515 for(i=0; i<p->nAction+p->mnLookahead; i++){
drh8b582012003-10-21 13:16:03 +0000516 if( p->aAction[i].lookahead<0 ){
517 for(j=0; j<p->nLookahead; j++){
518 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
519 if( k<0 ) break;
520 if( p->aAction[k].lookahead>=0 ) break;
521 }
drhfdbf9282003-10-21 16:34:41 +0000522 if( j<p->nLookahead ) continue;
523 for(j=0; j<p->nAction; j++){
524 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
525 }
526 if( j==p->nAction ){
527 break; /* Fits in empty slots */
528 }
drh8b582012003-10-21 13:16:03 +0000529 }else if( p->aAction[i].lookahead==p->mnLookahead ){
530 if( p->aAction[i].action!=p->mnAction ) continue;
531 for(j=0; j<p->nLookahead; j++){
532 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
533 if( k<0 || k>=p->nAction ) break;
534 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
535 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
536 }
537 if( j<p->nLookahead ) continue;
538 n = 0;
539 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000540 if( p->aAction[j].lookahead<0 ) continue;
541 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000542 }
drhfdbf9282003-10-21 16:34:41 +0000543 if( n==p->nLookahead ){
544 break; /* Same as a prior transaction set */
545 }
drh8b582012003-10-21 13:16:03 +0000546 }
547 }
548 /* Insert transaction set at index i. */
549 for(j=0; j<p->nLookahead; j++){
550 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
551 p->aAction[k] = p->aLookahead[j];
552 if( k>=p->nAction ) p->nAction = k+1;
553 }
554 p->nLookahead = 0;
555
556 /* Return the offset that is added to the lookahead in order to get the
557 ** index into yy_action of the action */
558 return i - p->mnLookahead;
559}
560
drh75897232000-05-29 14:26:00 +0000561/********************** From the file "assert.c" ****************************/
562/*
563** A more efficient way of handling assertions.
564*/
565void myassert(file,line)
566char *file;
567int line;
568{
569 fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
570 exit(1);
571}
572/********************** From the file "build.c" *****************************/
573/*
574** Routines to construction the finite state machine for the LEMON
575** parser generator.
576*/
577
578/* Find a precedence symbol of every rule in the grammar.
579**
580** Those rules which have a precedence symbol coded in the input
581** grammar using the "[symbol]" construct will already have the
582** rp->precsym field filled. Other rules take as their precedence
583** symbol the first RHS symbol with a defined precedence. If there
584** are not RHS symbols with a defined precedence, the precedence
585** symbol field is left blank.
586*/
587void FindRulePrecedences(xp)
588struct lemon *xp;
589{
590 struct rule *rp;
591 for(rp=xp->rule; rp; rp=rp->next){
592 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000593 int i, j;
594 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
595 struct symbol *sp = rp->rhs[i];
596 if( sp->type==MULTITERMINAL ){
597 for(j=0; j<sp->nsubsym; j++){
598 if( sp->subsym[j]->prec>=0 ){
599 rp->precsym = sp->subsym[j];
600 break;
601 }
602 }
603 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000604 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000605 }
606 }
607 }
608 }
609 return;
610}
611
612/* Find all nonterminals which will generate the empty string.
613** Then go back and compute the first sets of every nonterminal.
614** The first set is the set of all terminal symbols which can begin
615** a string generated by that nonterminal.
616*/
617void FindFirstSets(lemp)
618struct lemon *lemp;
619{
drhfd405312005-11-06 04:06:59 +0000620 int i, j;
drh75897232000-05-29 14:26:00 +0000621 struct rule *rp;
622 int progress;
623
624 for(i=0; i<lemp->nsymbol; i++){
drhb27b83a2002-08-14 23:18:57 +0000625 lemp->symbols[i]->lambda = B_FALSE;
drh75897232000-05-29 14:26:00 +0000626 }
627 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
628 lemp->symbols[i]->firstset = SetNew();
629 }
630
631 /* First compute all lambdas */
632 do{
633 progress = 0;
634 for(rp=lemp->rule; rp; rp=rp->next){
635 if( rp->lhs->lambda ) continue;
636 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000637 struct symbol *sp = rp->rhs[i];
638 if( sp->type!=TERMINAL || sp->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000639 }
640 if( i==rp->nrhs ){
drhb27b83a2002-08-14 23:18:57 +0000641 rp->lhs->lambda = B_TRUE;
drh75897232000-05-29 14:26:00 +0000642 progress = 1;
643 }
644 }
645 }while( progress );
646
647 /* Now compute all first sets */
648 do{
649 struct symbol *s1, *s2;
650 progress = 0;
651 for(rp=lemp->rule; rp; rp=rp->next){
652 s1 = rp->lhs;
653 for(i=0; i<rp->nrhs; i++){
654 s2 = rp->rhs[i];
655 if( s2->type==TERMINAL ){
656 progress += SetAdd(s1->firstset,s2->index);
657 break;
drhfd405312005-11-06 04:06:59 +0000658 }else if( s2->type==MULTITERMINAL ){
659 for(j=0; j<s2->nsubsym; j++){
660 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
661 }
662 break;
drh75897232000-05-29 14:26:00 +0000663 }else if( s1==s2 ){
drhb27b83a2002-08-14 23:18:57 +0000664 if( s1->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000665 }else{
666 progress += SetUnion(s1->firstset,s2->firstset);
drhb27b83a2002-08-14 23:18:57 +0000667 if( s2->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000668 }
669 }
670 }
671 }while( progress );
672 return;
673}
674
675/* Compute all LR(0) states for the grammar. Links
676** are added to between some states so that the LR(1) follow sets
677** can be computed later.
678*/
679PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
680void FindStates(lemp)
681struct lemon *lemp;
682{
683 struct symbol *sp;
684 struct rule *rp;
685
686 Configlist_init();
687
688 /* Find the start symbol */
689 if( lemp->start ){
690 sp = Symbol_find(lemp->start);
691 if( sp==0 ){
692 ErrorMsg(lemp->filename,0,
693"The specified start symbol \"%s\" is not \
694in a nonterminal of the grammar. \"%s\" will be used as the start \
695symbol instead.",lemp->start,lemp->rule->lhs->name);
696 lemp->errorcnt++;
697 sp = lemp->rule->lhs;
698 }
699 }else{
700 sp = lemp->rule->lhs;
701 }
702
703 /* Make sure the start symbol doesn't occur on the right-hand side of
704 ** any rule. Report an error if it does. (YACC would generate a new
705 ** start symbol in this case.) */
706 for(rp=lemp->rule; rp; rp=rp->next){
707 int i;
708 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000709 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000710 ErrorMsg(lemp->filename,0,
711"The start symbol \"%s\" occurs on the \
712right-hand side of a rule. This will result in a parser which \
713does not work properly.",sp->name);
714 lemp->errorcnt++;
715 }
716 }
717 }
718
719 /* The basis configuration set for the first state
720 ** is all rules which have the start symbol as their
721 ** left-hand side */
722 for(rp=sp->rule; rp; rp=rp->nextlhs){
723 struct config *newcfp;
724 newcfp = Configlist_addbasis(rp,0);
725 SetAdd(newcfp->fws,0);
726 }
727
728 /* Compute the first state. All other states will be
729 ** computed automatically during the computation of the first one.
730 ** The returned pointer to the first state is not used. */
731 (void)getstate(lemp);
732 return;
733}
734
735/* Return a pointer to a state which is described by the configuration
736** list which has been built from calls to Configlist_add.
737*/
738PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
739PRIVATE struct state *getstate(lemp)
740struct lemon *lemp;
741{
742 struct config *cfp, *bp;
743 struct state *stp;
744
745 /* Extract the sorted basis of the new state. The basis was constructed
746 ** by prior calls to "Configlist_addbasis()". */
747 Configlist_sortbasis();
748 bp = Configlist_basis();
749
750 /* Get a state with the same basis */
751 stp = State_find(bp);
752 if( stp ){
753 /* A state with the same basis already exists! Copy all the follow-set
754 ** propagation links from the state under construction into the
755 ** preexisting state, then return a pointer to the preexisting state */
756 struct config *x, *y;
757 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
758 Plink_copy(&y->bplp,x->bplp);
759 Plink_delete(x->fplp);
760 x->fplp = x->bplp = 0;
761 }
762 cfp = Configlist_return();
763 Configlist_eat(cfp);
764 }else{
765 /* This really is a new state. Construct all the details */
766 Configlist_closure(lemp); /* Compute the configuration closure */
767 Configlist_sort(); /* Sort the configuration closure */
768 cfp = Configlist_return(); /* Get a pointer to the config list */
769 stp = State_new(); /* A new state structure */
770 MemoryCheck(stp);
771 stp->bp = bp; /* Remember the configuration basis */
772 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000773 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000774 stp->ap = 0; /* No actions, yet. */
775 State_insert(stp,stp->bp); /* Add to the state table */
776 buildshifts(lemp,stp); /* Recursively compute successor states */
777 }
778 return stp;
779}
780
drhfd405312005-11-06 04:06:59 +0000781/*
782** Return true if two symbols are the same.
783*/
784int same_symbol(a,b)
785struct symbol *a;
786struct symbol *b;
787{
788 int i;
789 if( a==b ) return 1;
790 if( a->type!=MULTITERMINAL ) return 0;
791 if( b->type!=MULTITERMINAL ) return 0;
792 if( a->nsubsym!=b->nsubsym ) return 0;
793 for(i=0; i<a->nsubsym; i++){
794 if( a->subsym[i]!=b->subsym[i] ) return 0;
795 }
796 return 1;
797}
798
drh75897232000-05-29 14:26:00 +0000799/* Construct all successor states to the given state. A "successor"
800** state is any state which can be reached by a shift action.
801*/
802PRIVATE void buildshifts(lemp,stp)
803struct lemon *lemp;
804struct state *stp; /* The state from which successors are computed */
805{
806 struct config *cfp; /* For looping thru the config closure of "stp" */
807 struct config *bcfp; /* For the inner loop on config closure of "stp" */
808 struct config *new; /* */
809 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
810 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
811 struct state *newstp; /* A pointer to a successor state */
812
813 /* Each configuration becomes complete after it contibutes to a successor
814 ** state. Initially, all configurations are incomplete */
815 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
816
817 /* Loop through all configurations of the state "stp" */
818 for(cfp=stp->cfp; cfp; cfp=cfp->next){
819 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
820 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
821 Configlist_reset(); /* Reset the new config set */
822 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
823
824 /* For every configuration in the state "stp" which has the symbol "sp"
825 ** following its dot, add the same configuration to the basis set under
826 ** construction but with the dot shifted one symbol to the right. */
827 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
828 if( bcfp->status==COMPLETE ) continue; /* Already used */
829 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
830 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000831 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000832 bcfp->status = COMPLETE; /* Mark this config as used */
833 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
834 Plink_add(&new->bplp,bcfp);
835 }
836
837 /* Get a pointer to the state described by the basis configuration set
838 ** constructed in the preceding loop */
839 newstp = getstate(lemp);
840
841 /* The state "newstp" is reached from the state "stp" by a shift action
842 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000843 if( sp->type==MULTITERMINAL ){
844 int i;
845 for(i=0; i<sp->nsubsym; i++){
846 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
847 }
848 }else{
849 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
850 }
drh75897232000-05-29 14:26:00 +0000851 }
852}
853
854/*
855** Construct the propagation links
856*/
857void FindLinks(lemp)
858struct lemon *lemp;
859{
860 int i;
861 struct config *cfp, *other;
862 struct state *stp;
863 struct plink *plp;
864
865 /* Housekeeping detail:
866 ** Add to every propagate link a pointer back to the state to
867 ** which the link is attached. */
868 for(i=0; i<lemp->nstate; i++){
869 stp = lemp->sorted[i];
870 for(cfp=stp->cfp; cfp; cfp=cfp->next){
871 cfp->stp = stp;
872 }
873 }
874
875 /* Convert all backlinks into forward links. Only the forward
876 ** links are used in the follow-set computation. */
877 for(i=0; i<lemp->nstate; i++){
878 stp = lemp->sorted[i];
879 for(cfp=stp->cfp; cfp; cfp=cfp->next){
880 for(plp=cfp->bplp; plp; plp=plp->next){
881 other = plp->cfp;
882 Plink_add(&other->fplp,cfp);
883 }
884 }
885 }
886}
887
888/* Compute all followsets.
889**
890** A followset is the set of all symbols which can come immediately
891** after a configuration.
892*/
893void FindFollowSets(lemp)
894struct lemon *lemp;
895{
896 int i;
897 struct config *cfp;
898 struct plink *plp;
899 int progress;
900 int change;
901
902 for(i=0; i<lemp->nstate; i++){
903 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
904 cfp->status = INCOMPLETE;
905 }
906 }
907
908 do{
909 progress = 0;
910 for(i=0; i<lemp->nstate; i++){
911 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
912 if( cfp->status==COMPLETE ) continue;
913 for(plp=cfp->fplp; plp; plp=plp->next){
914 change = SetUnion(plp->cfp->fws,cfp->fws);
915 if( change ){
916 plp->cfp->status = INCOMPLETE;
917 progress = 1;
918 }
919 }
920 cfp->status = COMPLETE;
921 }
922 }
923 }while( progress );
924}
925
926static int resolve_conflict();
927
928/* Compute the reduce actions, and resolve conflicts.
929*/
930void FindActions(lemp)
931struct lemon *lemp;
932{
933 int i,j;
934 struct config *cfp;
935 struct state *stp;
936 struct symbol *sp;
937 struct rule *rp;
938
939 /* Add all of the reduce actions
940 ** A reduce action is added for each element of the followset of
941 ** a configuration which has its dot at the extreme right.
942 */
943 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
944 stp = lemp->sorted[i];
945 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
946 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
947 for(j=0; j<lemp->nterminal; j++){
948 if( SetFind(cfp->fws,j) ){
949 /* Add a reduce action to the state "stp" which will reduce by the
950 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000951 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000952 }
953 }
954 }
955 }
956 }
957
958 /* Add the accepting token */
959 if( lemp->start ){
960 sp = Symbol_find(lemp->start);
961 if( sp==0 ) sp = lemp->rule->lhs;
962 }else{
963 sp = lemp->rule->lhs;
964 }
965 /* Add to the first state (which is always the starting state of the
966 ** finite state machine) an action to ACCEPT if the lookahead is the
967 ** start nonterminal. */
968 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
969
970 /* Resolve conflicts */
971 for(i=0; i<lemp->nstate; i++){
972 struct action *ap, *nap;
973 struct state *stp;
974 stp = lemp->sorted[i];
975 assert( stp->ap );
976 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000977 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000978 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
979 /* The two actions "ap" and "nap" have the same lookahead.
980 ** Figure out which one should be used */
981 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
982 }
983 }
984 }
985
986 /* Report an error for each rule that can never be reduced. */
drhb27b83a2002-08-14 23:18:57 +0000987 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = B_FALSE;
drh75897232000-05-29 14:26:00 +0000988 for(i=0; i<lemp->nstate; i++){
989 struct action *ap;
990 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhb27b83a2002-08-14 23:18:57 +0000991 if( ap->type==REDUCE ) ap->x.rp->canReduce = B_TRUE;
drh75897232000-05-29 14:26:00 +0000992 }
993 }
994 for(rp=lemp->rule; rp; rp=rp->next){
995 if( rp->canReduce ) continue;
996 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
997 lemp->errorcnt++;
998 }
999}
1000
1001/* Resolve a conflict between the two given actions. If the
1002** conflict can't be resolve, return non-zero.
1003**
1004** NO LONGER TRUE:
1005** To resolve a conflict, first look to see if either action
1006** is on an error rule. In that case, take the action which
1007** is not associated with the error rule. If neither or both
1008** actions are associated with an error rule, then try to
1009** use precedence to resolve the conflict.
1010**
1011** If either action is a SHIFT, then it must be apx. This
1012** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1013*/
1014static int resolve_conflict(apx,apy,errsym)
1015struct action *apx;
1016struct action *apy;
1017struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1018{
1019 struct symbol *spx, *spy;
1020 int errcnt = 0;
1021 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
1022 if( apx->type==SHIFT && apy->type==REDUCE ){
1023 spx = apx->sp;
1024 spy = apy->x.rp->precsym;
1025 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1026 /* Not enough precedence information. */
1027 apy->type = CONFLICT;
1028 errcnt++;
1029 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1030 apy->type = RD_RESOLVED;
1031 }else if( spx->prec<spy->prec ){
1032 apx->type = SH_RESOLVED;
1033 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1034 apy->type = RD_RESOLVED; /* associativity */
1035 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1036 apx->type = SH_RESOLVED;
1037 }else{
1038 assert( spx->prec==spy->prec && spx->assoc==NONE );
1039 apy->type = CONFLICT;
1040 errcnt++;
1041 }
1042 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1043 spx = apx->x.rp->precsym;
1044 spy = apy->x.rp->precsym;
1045 if( spx==0 || spy==0 || spx->prec<0 ||
1046 spy->prec<0 || spx->prec==spy->prec ){
1047 apy->type = CONFLICT;
1048 errcnt++;
1049 }else if( spx->prec>spy->prec ){
1050 apy->type = RD_RESOLVED;
1051 }else if( spx->prec<spy->prec ){
1052 apx->type = RD_RESOLVED;
1053 }
1054 }else{
drhb59499c2002-02-23 18:45:13 +00001055 assert(
1056 apx->type==SH_RESOLVED ||
1057 apx->type==RD_RESOLVED ||
1058 apx->type==CONFLICT ||
1059 apy->type==SH_RESOLVED ||
1060 apy->type==RD_RESOLVED ||
1061 apy->type==CONFLICT
1062 );
1063 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1064 ** REDUCEs on the list. If we reach this point it must be because
1065 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001066 }
1067 return errcnt;
1068}
1069/********************* From the file "configlist.c" *************************/
1070/*
1071** Routines to processing a configuration list and building a state
1072** in the LEMON parser generator.
1073*/
1074
1075static struct config *freelist = 0; /* List of free configurations */
1076static struct config *current = 0; /* Top of list of configurations */
1077static struct config **currentend = 0; /* Last on list of configs */
1078static struct config *basis = 0; /* Top of list of basis configs */
1079static struct config **basisend = 0; /* End of list of basis configs */
1080
1081/* Return a pointer to a new configuration */
1082PRIVATE struct config *newconfig(){
1083 struct config *new;
1084 if( freelist==0 ){
1085 int i;
1086 int amt = 3;
1087 freelist = (struct config *)malloc( sizeof(struct config)*amt );
1088 if( freelist==0 ){
1089 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1090 exit(1);
1091 }
1092 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1093 freelist[amt-1].next = 0;
1094 }
1095 new = freelist;
1096 freelist = freelist->next;
1097 return new;
1098}
1099
1100/* The configuration "old" is no longer used */
1101PRIVATE void deleteconfig(old)
1102struct config *old;
1103{
1104 old->next = freelist;
1105 freelist = old;
1106}
1107
1108/* Initialized the configuration list builder */
1109void Configlist_init(){
1110 current = 0;
1111 currentend = &current;
1112 basis = 0;
1113 basisend = &basis;
1114 Configtable_init();
1115 return;
1116}
1117
1118/* Initialized the configuration list builder */
1119void Configlist_reset(){
1120 current = 0;
1121 currentend = &current;
1122 basis = 0;
1123 basisend = &basis;
1124 Configtable_clear(0);
1125 return;
1126}
1127
1128/* Add another configuration to the configuration list */
1129struct config *Configlist_add(rp,dot)
1130struct rule *rp; /* The rule */
1131int dot; /* Index into the RHS of the rule where the dot goes */
1132{
1133 struct config *cfp, model;
1134
1135 assert( currentend!=0 );
1136 model.rp = rp;
1137 model.dot = dot;
1138 cfp = Configtable_find(&model);
1139 if( cfp==0 ){
1140 cfp = newconfig();
1141 cfp->rp = rp;
1142 cfp->dot = dot;
1143 cfp->fws = SetNew();
1144 cfp->stp = 0;
1145 cfp->fplp = cfp->bplp = 0;
1146 cfp->next = 0;
1147 cfp->bp = 0;
1148 *currentend = cfp;
1149 currentend = &cfp->next;
1150 Configtable_insert(cfp);
1151 }
1152 return cfp;
1153}
1154
1155/* Add a basis configuration to the configuration list */
1156struct config *Configlist_addbasis(rp,dot)
1157struct rule *rp;
1158int dot;
1159{
1160 struct config *cfp, model;
1161
1162 assert( basisend!=0 );
1163 assert( currentend!=0 );
1164 model.rp = rp;
1165 model.dot = dot;
1166 cfp = Configtable_find(&model);
1167 if( cfp==0 ){
1168 cfp = newconfig();
1169 cfp->rp = rp;
1170 cfp->dot = dot;
1171 cfp->fws = SetNew();
1172 cfp->stp = 0;
1173 cfp->fplp = cfp->bplp = 0;
1174 cfp->next = 0;
1175 cfp->bp = 0;
1176 *currentend = cfp;
1177 currentend = &cfp->next;
1178 *basisend = cfp;
1179 basisend = &cfp->bp;
1180 Configtable_insert(cfp);
1181 }
1182 return cfp;
1183}
1184
1185/* Compute the closure of the configuration list */
1186void Configlist_closure(lemp)
1187struct lemon *lemp;
1188{
1189 struct config *cfp, *newcfp;
1190 struct rule *rp, *newrp;
1191 struct symbol *sp, *xsp;
1192 int i, dot;
1193
1194 assert( currentend!=0 );
1195 for(cfp=current; cfp; cfp=cfp->next){
1196 rp = cfp->rp;
1197 dot = cfp->dot;
1198 if( dot>=rp->nrhs ) continue;
1199 sp = rp->rhs[dot];
1200 if( sp->type==NONTERMINAL ){
1201 if( sp->rule==0 && sp!=lemp->errsym ){
1202 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1203 sp->name);
1204 lemp->errorcnt++;
1205 }
1206 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1207 newcfp = Configlist_add(newrp,0);
1208 for(i=dot+1; i<rp->nrhs; i++){
1209 xsp = rp->rhs[i];
1210 if( xsp->type==TERMINAL ){
1211 SetAdd(newcfp->fws,xsp->index);
1212 break;
drhfd405312005-11-06 04:06:59 +00001213 }else if( xsp->type==MULTITERMINAL ){
1214 int k;
1215 for(k=0; k<xsp->nsubsym; k++){
1216 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1217 }
1218 break;
drh75897232000-05-29 14:26:00 +00001219 }else{
1220 SetUnion(newcfp->fws,xsp->firstset);
drhb27b83a2002-08-14 23:18:57 +00001221 if( xsp->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001222 }
1223 }
1224 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1225 }
1226 }
1227 }
1228 return;
1229}
1230
1231/* Sort the configuration list */
1232void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001233 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001234 currentend = 0;
1235 return;
1236}
1237
1238/* Sort the basis configuration list */
1239void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001240 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001241 basisend = 0;
1242 return;
1243}
1244
1245/* Return a pointer to the head of the configuration list and
1246** reset the list */
1247struct config *Configlist_return(){
1248 struct config *old;
1249 old = current;
1250 current = 0;
1251 currentend = 0;
1252 return old;
1253}
1254
1255/* Return a pointer to the head of the configuration list and
1256** reset the list */
1257struct config *Configlist_basis(){
1258 struct config *old;
1259 old = basis;
1260 basis = 0;
1261 basisend = 0;
1262 return old;
1263}
1264
1265/* Free all elements of the given configuration list */
1266void Configlist_eat(cfp)
1267struct config *cfp;
1268{
1269 struct config *nextcfp;
1270 for(; cfp; cfp=nextcfp){
1271 nextcfp = cfp->next;
1272 assert( cfp->fplp==0 );
1273 assert( cfp->bplp==0 );
1274 if( cfp->fws ) SetFree(cfp->fws);
1275 deleteconfig(cfp);
1276 }
1277 return;
1278}
1279/***************** From the file "error.c" *********************************/
1280/*
1281** Code for printing error message.
1282*/
1283
1284/* Find a good place to break "msg" so that its length is at least "min"
1285** but no more than "max". Make the point as close to max as possible.
1286*/
1287static int findbreak(msg,min,max)
1288char *msg;
1289int min;
1290int max;
1291{
1292 int i,spot;
1293 char c;
1294 for(i=spot=min; i<=max; i++){
1295 c = msg[i];
1296 if( c=='\t' ) msg[i] = ' ';
1297 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1298 if( c==0 ){ spot = i; break; }
1299 if( c=='-' && i<max-1 ) spot = i+1;
1300 if( c==' ' ) spot = i;
1301 }
1302 return spot;
1303}
1304
1305/*
1306** The error message is split across multiple lines if necessary. The
1307** splits occur at a space, if there is a space available near the end
1308** of the line.
1309*/
1310#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1311#define LINEWIDTH 79 /* Max width of any output line */
1312#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001313void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001314 char errmsg[ERRMSGSIZE];
1315 char prefix[PREFIXLIMIT+10];
1316 int errmsgsize;
1317 int prefixsize;
1318 int availablewidth;
1319 va_list ap;
1320 int end, restart, base;
1321
drhf9a2e7b2003-04-15 01:49:48 +00001322 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001323 /* Prepare a prefix to be prepended to every output line */
1324 if( lineno>0 ){
1325 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1326 }else{
1327 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1328 }
1329 prefixsize = strlen(prefix);
1330 availablewidth = LINEWIDTH - prefixsize;
1331
1332 /* Generate the error message */
1333 vsprintf(errmsg,format,ap);
1334 va_end(ap);
1335 errmsgsize = strlen(errmsg);
1336 /* Remove trailing '\n's from the error message. */
1337 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1338 errmsg[--errmsgsize] = 0;
1339 }
1340
1341 /* Print the error message */
1342 base = 0;
1343 while( errmsg[base]!=0 ){
1344 end = restart = findbreak(&errmsg[base],0,availablewidth);
1345 restart += base;
1346 while( errmsg[restart]==' ' ) restart++;
1347 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1348 base = restart;
1349 }
1350}
1351/**************** From the file "main.c" ************************************/
1352/*
1353** Main program file for the LEMON parser generator.
1354*/
1355
1356/* Report an out-of-memory condition and abort. This function
1357** is used mostly by the "MemoryCheck" macro in struct.h
1358*/
1359void memory_error(){
1360 fprintf(stderr,"Out of memory. Aborting...\n");
1361 exit(1);
1362}
1363
drh6d08b4d2004-07-20 12:45:22 +00001364static int nDefine = 0; /* Number of -D options on the command line */
1365static char **azDefine = 0; /* Name of the -D macros */
1366
1367/* This routine is called with the argument to each -D command-line option.
1368** Add the macro defined to the azDefine array.
1369*/
1370static void handle_D_option(char *z){
1371 char **paz;
1372 nDefine++;
1373 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1374 if( azDefine==0 ){
1375 fprintf(stderr,"out of memory\n");
1376 exit(1);
1377 }
1378 paz = &azDefine[nDefine-1];
1379 *paz = malloc( strlen(z)+1 );
1380 if( *paz==0 ){
1381 fprintf(stderr,"out of memory\n");
1382 exit(1);
1383 }
1384 strcpy(*paz, z);
1385 for(z=*paz; *z && *z!='='; z++){}
1386 *z = 0;
1387}
1388
drh75897232000-05-29 14:26:00 +00001389
1390/* The main program. Parse the command line and do it... */
1391int main(argc,argv)
1392int argc;
1393char **argv;
1394{
1395 static int version = 0;
1396 static int rpflag = 0;
1397 static int basisflag = 0;
1398 static int compress = 0;
1399 static int quiet = 0;
1400 static int statistics = 0;
1401 static int mhflag = 0;
1402 static struct s_options options[] = {
1403 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1404 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001405 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001406 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1407 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1408 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001409 {OPT_FLAG, "s", (char*)&statistics,
1410 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001411 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1412 {OPT_FLAG,0,0,0}
1413 };
1414 int i;
1415 struct lemon lem;
1416
drhb0c86772000-06-02 23:21:26 +00001417 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001418 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001419 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001420 exit(0);
1421 }
drhb0c86772000-06-02 23:21:26 +00001422 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001423 fprintf(stderr,"Exactly one filename argument is required.\n");
1424 exit(1);
1425 }
1426 lem.errorcnt = 0;
1427
1428 /* Initialize the machine */
1429 Strsafe_init();
1430 Symbol_init();
1431 State_init();
1432 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001433 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001434 lem.basisflag = basisflag;
drh0bd1f4e2002-06-06 18:54:39 +00001435 lem.has_fallback = 0;
drh75897232000-05-29 14:26:00 +00001436 lem.nconflict = 0;
1437 lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
drh960e8c62001-04-03 16:53:21 +00001438 lem.vartype = 0;
drh75897232000-05-29 14:26:00 +00001439 lem.stacksize = 0;
1440 lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
1441 lem.tokenprefix = lem.outname = lem.extracode = 0;
drh960e8c62001-04-03 16:53:21 +00001442 lem.vardest = 0;
drh75897232000-05-29 14:26:00 +00001443 lem.tablesize = 0;
1444 Symbol_new("$");
1445 lem.errsym = Symbol_new("error");
drhe09daa92006-06-10 13:29:31 +00001446 lem.wildcard = 0;
drh75897232000-05-29 14:26:00 +00001447
1448 /* Parse the input file */
1449 Parse(&lem);
1450 if( lem.errorcnt ) exit(lem.errorcnt);
1451 if( lem.rule==0 ){
1452 fprintf(stderr,"Empty grammar.\n");
1453 exit(1);
1454 }
1455
1456 /* Count and index the symbols of the grammar */
1457 lem.nsymbol = Symbol_count();
1458 Symbol_new("{default}");
1459 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001460 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001461 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1462 (int(*)())Symbolcmpp);
1463 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1464 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1465 lem.nterminal = i;
1466
1467 /* Generate a reprint of the grammar, if requested on the command line */
1468 if( rpflag ){
1469 Reprint(&lem);
1470 }else{
1471 /* Initialize the size for all follow and first sets */
1472 SetSize(lem.nterminal);
1473
1474 /* Find the precedence for every production rule (that has one) */
1475 FindRulePrecedences(&lem);
1476
1477 /* Compute the lambda-nonterminals and the first-sets for every
1478 ** nonterminal */
1479 FindFirstSets(&lem);
1480
1481 /* Compute all LR(0) states. Also record follow-set propagation
1482 ** links so that the follow-set can be computed later */
1483 lem.nstate = 0;
1484 FindStates(&lem);
1485 lem.sorted = State_arrayof();
1486
1487 /* Tie up loose ends on the propagation links */
1488 FindLinks(&lem);
1489
1490 /* Compute the follow set of every reducible configuration */
1491 FindFollowSets(&lem);
1492
1493 /* Compute the action tables */
1494 FindActions(&lem);
1495
1496 /* Compress the action tables */
1497 if( compress==0 ) CompressTables(&lem);
1498
drhada354d2005-11-05 15:03:59 +00001499 /* Reorder and renumber the states so that states with fewer choices
1500 ** occur at the end. */
1501 ResortStates(&lem);
1502
drh75897232000-05-29 14:26:00 +00001503 /* Generate a report of the parser generated. (the "y.output" file) */
1504 if( !quiet ) ReportOutput(&lem);
1505
1506 /* Generate the source code for the parser */
1507 ReportTable(&lem, mhflag);
1508
1509 /* Produce a header file for use by the scanner. (This step is
1510 ** omitted if the "-m" option is used because makeheaders will
1511 ** generate the file for us.) */
1512 if( !mhflag ) ReportHeader(&lem);
1513 }
1514 if( statistics ){
1515 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1516 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1517 printf(" %d states, %d parser table entries, %d conflicts\n",
1518 lem.nstate, lem.tablesize, lem.nconflict);
1519 }
1520 if( lem.nconflict ){
1521 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1522 }
1523 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001524 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001525}
1526/******************** From the file "msort.c" *******************************/
1527/*
1528** A generic merge-sort program.
1529**
1530** USAGE:
1531** Let "ptr" be a pointer to some structure which is at the head of
1532** a null-terminated list. Then to sort the list call:
1533**
1534** ptr = msort(ptr,&(ptr->next),cmpfnc);
1535**
1536** In the above, "cmpfnc" is a pointer to a function which compares
1537** two instances of the structure and returns an integer, as in
1538** strcmp. The second argument is a pointer to the pointer to the
1539** second element of the linked list. This address is used to compute
1540** the offset to the "next" field within the structure. The offset to
1541** the "next" field must be constant for all structures in the list.
1542**
1543** The function returns a new pointer which is the head of the list
1544** after sorting.
1545**
1546** ALGORITHM:
1547** Merge-sort.
1548*/
1549
1550/*
1551** Return a pointer to the next structure in the linked list.
1552*/
drhba99af52001-10-25 20:37:16 +00001553#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001554
1555/*
1556** Inputs:
1557** a: A sorted, null-terminated linked list. (May be null).
1558** b: A sorted, null-terminated linked list. (May be null).
1559** cmp: A pointer to the comparison function.
1560** offset: Offset in the structure to the "next" field.
1561**
1562** Return Value:
1563** A pointer to the head of a sorted list containing the elements
1564** of both a and b.
1565**
1566** Side effects:
1567** The "next" pointers for elements in the lists a and b are
1568** changed.
1569*/
1570static char *merge(a,b,cmp,offset)
1571char *a;
1572char *b;
1573int (*cmp)();
1574int offset;
1575{
1576 char *ptr, *head;
1577
1578 if( a==0 ){
1579 head = b;
1580 }else if( b==0 ){
1581 head = a;
1582 }else{
1583 if( (*cmp)(a,b)<0 ){
1584 ptr = a;
1585 a = NEXT(a);
1586 }else{
1587 ptr = b;
1588 b = NEXT(b);
1589 }
1590 head = ptr;
1591 while( a && b ){
1592 if( (*cmp)(a,b)<0 ){
1593 NEXT(ptr) = a;
1594 ptr = a;
1595 a = NEXT(a);
1596 }else{
1597 NEXT(ptr) = b;
1598 ptr = b;
1599 b = NEXT(b);
1600 }
1601 }
1602 if( a ) NEXT(ptr) = a;
1603 else NEXT(ptr) = b;
1604 }
1605 return head;
1606}
1607
1608/*
1609** Inputs:
1610** list: Pointer to a singly-linked list of structures.
1611** next: Pointer to pointer to the second element of the list.
1612** cmp: A comparison function.
1613**
1614** Return Value:
1615** A pointer to the head of a sorted list containing the elements
1616** orginally in list.
1617**
1618** Side effects:
1619** The "next" pointers for elements in list are changed.
1620*/
1621#define LISTSIZE 30
1622char *msort(list,next,cmp)
1623char *list;
1624char **next;
1625int (*cmp)();
1626{
drhba99af52001-10-25 20:37:16 +00001627 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001628 char *ep;
1629 char *set[LISTSIZE];
1630 int i;
drhba99af52001-10-25 20:37:16 +00001631 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001632 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1633 while( list ){
1634 ep = list;
1635 list = NEXT(list);
1636 NEXT(ep) = 0;
1637 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1638 ep = merge(ep,set[i],cmp,offset);
1639 set[i] = 0;
1640 }
1641 set[i] = ep;
1642 }
1643 ep = 0;
1644 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1645 return ep;
1646}
1647/************************ From the file "option.c" **************************/
1648static char **argv;
1649static struct s_options *op;
1650static FILE *errstream;
1651
1652#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1653
1654/*
1655** Print the command line with a carrot pointing to the k-th character
1656** of the n-th field.
1657*/
1658static void errline(n,k,err)
1659int n;
1660int k;
1661FILE *err;
1662{
1663 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001664 if( argv[0] ) fprintf(err,"%s",argv[0]);
1665 spcnt = strlen(argv[0]) + 1;
1666 for(i=1; i<n && argv[i]; i++){
1667 fprintf(err," %s",argv[i]);
drhdc30dd32005-02-16 03:35:15 +00001668 spcnt += strlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001669 }
1670 spcnt += k;
1671 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1672 if( spcnt<20 ){
1673 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1674 }else{
1675 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1676 }
1677}
1678
1679/*
1680** Return the index of the N-th non-switch argument. Return -1
1681** if N is out of range.
1682*/
1683static int argindex(n)
1684int n;
1685{
1686 int i;
1687 int dashdash = 0;
1688 if( argv!=0 && *argv!=0 ){
1689 for(i=1; argv[i]; i++){
1690 if( dashdash || !ISOPT(argv[i]) ){
1691 if( n==0 ) return i;
1692 n--;
1693 }
1694 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1695 }
1696 }
1697 return -1;
1698}
1699
1700static char emsg[] = "Command line syntax error: ";
1701
1702/*
1703** Process a flag command line argument.
1704*/
1705static int handleflags(i,err)
1706int i;
1707FILE *err;
1708{
1709 int v;
1710 int errcnt = 0;
1711 int j;
1712 for(j=0; op[j].label; j++){
drh6d08b4d2004-07-20 12:45:22 +00001713 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001714 }
1715 v = argv[i][0]=='-' ? 1 : 0;
1716 if( op[j].label==0 ){
1717 if( err ){
1718 fprintf(err,"%sundefined option.\n",emsg);
1719 errline(i,1,err);
1720 }
1721 errcnt++;
1722 }else if( op[j].type==OPT_FLAG ){
1723 *((int*)op[j].arg) = v;
1724 }else if( op[j].type==OPT_FFLAG ){
1725 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001726 }else if( op[j].type==OPT_FSTR ){
1727 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001728 }else{
1729 if( err ){
1730 fprintf(err,"%smissing argument on switch.\n",emsg);
1731 errline(i,1,err);
1732 }
1733 errcnt++;
1734 }
1735 return errcnt;
1736}
1737
1738/*
1739** Process a command line switch which has an argument.
1740*/
1741static int handleswitch(i,err)
1742int i;
1743FILE *err;
1744{
1745 int lv = 0;
1746 double dv = 0.0;
1747 char *sv = 0, *end;
1748 char *cp;
1749 int j;
1750 int errcnt = 0;
1751 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001752 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001753 *cp = 0;
1754 for(j=0; op[j].label; j++){
1755 if( strcmp(argv[i],op[j].label)==0 ) break;
1756 }
1757 *cp = '=';
1758 if( op[j].label==0 ){
1759 if( err ){
1760 fprintf(err,"%sundefined option.\n",emsg);
1761 errline(i,0,err);
1762 }
1763 errcnt++;
1764 }else{
1765 cp++;
1766 switch( op[j].type ){
1767 case OPT_FLAG:
1768 case OPT_FFLAG:
1769 if( err ){
1770 fprintf(err,"%soption requires an argument.\n",emsg);
1771 errline(i,0,err);
1772 }
1773 errcnt++;
1774 break;
1775 case OPT_DBL:
1776 case OPT_FDBL:
1777 dv = strtod(cp,&end);
1778 if( *end ){
1779 if( err ){
1780 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001781 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001782 }
1783 errcnt++;
1784 }
1785 break;
1786 case OPT_INT:
1787 case OPT_FINT:
1788 lv = strtol(cp,&end,0);
1789 if( *end ){
1790 if( err ){
1791 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001792 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001793 }
1794 errcnt++;
1795 }
1796 break;
1797 case OPT_STR:
1798 case OPT_FSTR:
1799 sv = cp;
1800 break;
1801 }
1802 switch( op[j].type ){
1803 case OPT_FLAG:
1804 case OPT_FFLAG:
1805 break;
1806 case OPT_DBL:
1807 *(double*)(op[j].arg) = dv;
1808 break;
1809 case OPT_FDBL:
1810 (*(void(*)())(op[j].arg))(dv);
1811 break;
1812 case OPT_INT:
1813 *(int*)(op[j].arg) = lv;
1814 break;
1815 case OPT_FINT:
1816 (*(void(*)())(op[j].arg))((int)lv);
1817 break;
1818 case OPT_STR:
1819 *(char**)(op[j].arg) = sv;
1820 break;
1821 case OPT_FSTR:
1822 (*(void(*)())(op[j].arg))(sv);
1823 break;
1824 }
1825 }
1826 return errcnt;
1827}
1828
drhb0c86772000-06-02 23:21:26 +00001829int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001830char **a;
1831struct s_options *o;
1832FILE *err;
1833{
1834 int errcnt = 0;
1835 argv = a;
1836 op = o;
1837 errstream = err;
1838 if( argv && *argv && op ){
1839 int i;
1840 for(i=1; argv[i]; i++){
1841 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1842 errcnt += handleflags(i,err);
1843 }else if( strchr(argv[i],'=') ){
1844 errcnt += handleswitch(i,err);
1845 }
1846 }
1847 }
1848 if( errcnt>0 ){
1849 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001850 OptPrint();
drh75897232000-05-29 14:26:00 +00001851 exit(1);
1852 }
1853 return 0;
1854}
1855
drhb0c86772000-06-02 23:21:26 +00001856int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001857 int cnt = 0;
1858 int dashdash = 0;
1859 int i;
1860 if( argv!=0 && argv[0]!=0 ){
1861 for(i=1; argv[i]; i++){
1862 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1863 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1864 }
1865 }
1866 return cnt;
1867}
1868
drhb0c86772000-06-02 23:21:26 +00001869char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001870int n;
1871{
1872 int i;
1873 i = argindex(n);
1874 return i>=0 ? argv[i] : 0;
1875}
1876
drhb0c86772000-06-02 23:21:26 +00001877void OptErr(n)
drh75897232000-05-29 14:26:00 +00001878int n;
1879{
1880 int i;
1881 i = argindex(n);
1882 if( i>=0 ) errline(i,0,errstream);
1883}
1884
drhb0c86772000-06-02 23:21:26 +00001885void OptPrint(){
drh75897232000-05-29 14:26:00 +00001886 int i;
1887 int max, len;
1888 max = 0;
1889 for(i=0; op[i].label; i++){
1890 len = strlen(op[i].label) + 1;
1891 switch( op[i].type ){
1892 case OPT_FLAG:
1893 case OPT_FFLAG:
1894 break;
1895 case OPT_INT:
1896 case OPT_FINT:
1897 len += 9; /* length of "<integer>" */
1898 break;
1899 case OPT_DBL:
1900 case OPT_FDBL:
1901 len += 6; /* length of "<real>" */
1902 break;
1903 case OPT_STR:
1904 case OPT_FSTR:
1905 len += 8; /* length of "<string>" */
1906 break;
1907 }
1908 if( len>max ) max = len;
1909 }
1910 for(i=0; op[i].label; i++){
1911 switch( op[i].type ){
1912 case OPT_FLAG:
1913 case OPT_FFLAG:
1914 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1915 break;
1916 case OPT_INT:
1917 case OPT_FINT:
1918 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001919 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001920 break;
1921 case OPT_DBL:
1922 case OPT_FDBL:
1923 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001924 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001925 break;
1926 case OPT_STR:
1927 case OPT_FSTR:
1928 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001929 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001930 break;
1931 }
1932 }
1933}
1934/*********************** From the file "parse.c" ****************************/
1935/*
1936** Input file parser for the LEMON parser generator.
1937*/
1938
1939/* The state of the parser */
1940struct pstate {
1941 char *filename; /* Name of the input file */
1942 int tokenlineno; /* Linenumber at which current token starts */
1943 int errorcnt; /* Number of errors so far */
1944 char *tokenstart; /* Text of current token */
1945 struct lemon *gp; /* Global state vector */
1946 enum e_state {
1947 INITIALIZE,
1948 WAITING_FOR_DECL_OR_RULE,
1949 WAITING_FOR_DECL_KEYWORD,
1950 WAITING_FOR_DECL_ARG,
1951 WAITING_FOR_PRECEDENCE_SYMBOL,
1952 WAITING_FOR_ARROW,
1953 IN_RHS,
1954 LHS_ALIAS_1,
1955 LHS_ALIAS_2,
1956 LHS_ALIAS_3,
1957 RHS_ALIAS_1,
1958 RHS_ALIAS_2,
1959 PRECEDENCE_MARK_1,
1960 PRECEDENCE_MARK_2,
1961 RESYNC_AFTER_RULE_ERROR,
1962 RESYNC_AFTER_DECL_ERROR,
1963 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001964 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001965 WAITING_FOR_FALLBACK_ID,
1966 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001967 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001968 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001969 struct symbol *lhs; /* Left-hand side of current rule */
1970 char *lhsalias; /* Alias for the LHS */
1971 int nrhs; /* Number of right-hand side symbols seen */
1972 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1973 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1974 struct rule *prevrule; /* Previous rule parsed */
1975 char *declkeyword; /* Keyword of a declaration */
1976 char **declargslot; /* Where the declaration argument should be put */
1977 int *decllnslot; /* Where the declaration linenumber is put */
1978 enum e_assoc declassoc; /* Assign this association to decl arguments */
1979 int preccounter; /* Assign this precedence to decl arguments */
1980 struct rule *firstrule; /* Pointer to first rule in the grammar */
1981 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1982};
1983
1984/* Parse a single token */
1985static void parseonetoken(psp)
1986struct pstate *psp;
1987{
1988 char *x;
1989 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1990#if 0
1991 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1992 x,psp->state);
1993#endif
1994 switch( psp->state ){
1995 case INITIALIZE:
1996 psp->prevrule = 0;
1997 psp->preccounter = 0;
1998 psp->firstrule = psp->lastrule = 0;
1999 psp->gp->nrule = 0;
2000 /* Fall thru to next case */
2001 case WAITING_FOR_DECL_OR_RULE:
2002 if( x[0]=='%' ){
2003 psp->state = WAITING_FOR_DECL_KEYWORD;
2004 }else if( islower(x[0]) ){
2005 psp->lhs = Symbol_new(x);
2006 psp->nrhs = 0;
2007 psp->lhsalias = 0;
2008 psp->state = WAITING_FOR_ARROW;
2009 }else if( x[0]=='{' ){
2010 if( psp->prevrule==0 ){
2011 ErrorMsg(psp->filename,psp->tokenlineno,
2012"There is not prior rule opon which to attach the code \
2013fragment which begins on this line.");
2014 psp->errorcnt++;
2015 }else if( psp->prevrule->code!=0 ){
2016 ErrorMsg(psp->filename,psp->tokenlineno,
2017"Code fragment beginning on this line is not the first \
2018to follow the previous rule.");
2019 psp->errorcnt++;
2020 }else{
2021 psp->prevrule->line = psp->tokenlineno;
2022 psp->prevrule->code = &x[1];
2023 }
2024 }else if( x[0]=='[' ){
2025 psp->state = PRECEDENCE_MARK_1;
2026 }else{
2027 ErrorMsg(psp->filename,psp->tokenlineno,
2028 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2029 x);
2030 psp->errorcnt++;
2031 }
2032 break;
2033 case PRECEDENCE_MARK_1:
2034 if( !isupper(x[0]) ){
2035 ErrorMsg(psp->filename,psp->tokenlineno,
2036 "The precedence symbol must be a terminal.");
2037 psp->errorcnt++;
2038 }else if( psp->prevrule==0 ){
2039 ErrorMsg(psp->filename,psp->tokenlineno,
2040 "There is no prior rule to assign precedence \"[%s]\".",x);
2041 psp->errorcnt++;
2042 }else if( psp->prevrule->precsym!=0 ){
2043 ErrorMsg(psp->filename,psp->tokenlineno,
2044"Precedence mark on this line is not the first \
2045to follow the previous rule.");
2046 psp->errorcnt++;
2047 }else{
2048 psp->prevrule->precsym = Symbol_new(x);
2049 }
2050 psp->state = PRECEDENCE_MARK_2;
2051 break;
2052 case PRECEDENCE_MARK_2:
2053 if( x[0]!=']' ){
2054 ErrorMsg(psp->filename,psp->tokenlineno,
2055 "Missing \"]\" on precedence mark.");
2056 psp->errorcnt++;
2057 }
2058 psp->state = WAITING_FOR_DECL_OR_RULE;
2059 break;
2060 case WAITING_FOR_ARROW:
2061 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2062 psp->state = IN_RHS;
2063 }else if( x[0]=='(' ){
2064 psp->state = LHS_ALIAS_1;
2065 }else{
2066 ErrorMsg(psp->filename,psp->tokenlineno,
2067 "Expected to see a \":\" following the LHS symbol \"%s\".",
2068 psp->lhs->name);
2069 psp->errorcnt++;
2070 psp->state = RESYNC_AFTER_RULE_ERROR;
2071 }
2072 break;
2073 case LHS_ALIAS_1:
2074 if( isalpha(x[0]) ){
2075 psp->lhsalias = x;
2076 psp->state = LHS_ALIAS_2;
2077 }else{
2078 ErrorMsg(psp->filename,psp->tokenlineno,
2079 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2080 x,psp->lhs->name);
2081 psp->errorcnt++;
2082 psp->state = RESYNC_AFTER_RULE_ERROR;
2083 }
2084 break;
2085 case LHS_ALIAS_2:
2086 if( x[0]==')' ){
2087 psp->state = LHS_ALIAS_3;
2088 }else{
2089 ErrorMsg(psp->filename,psp->tokenlineno,
2090 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2091 psp->errorcnt++;
2092 psp->state = RESYNC_AFTER_RULE_ERROR;
2093 }
2094 break;
2095 case LHS_ALIAS_3:
2096 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2097 psp->state = IN_RHS;
2098 }else{
2099 ErrorMsg(psp->filename,psp->tokenlineno,
2100 "Missing \"->\" following: \"%s(%s)\".",
2101 psp->lhs->name,psp->lhsalias);
2102 psp->errorcnt++;
2103 psp->state = RESYNC_AFTER_RULE_ERROR;
2104 }
2105 break;
2106 case IN_RHS:
2107 if( x[0]=='.' ){
2108 struct rule *rp;
2109 rp = (struct rule *)malloc( sizeof(struct rule) +
2110 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
2111 if( rp==0 ){
2112 ErrorMsg(psp->filename,psp->tokenlineno,
2113 "Can't allocate enough memory for this rule.");
2114 psp->errorcnt++;
2115 psp->prevrule = 0;
2116 }else{
2117 int i;
2118 rp->ruleline = psp->tokenlineno;
2119 rp->rhs = (struct symbol**)&rp[1];
2120 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2121 for(i=0; i<psp->nrhs; i++){
2122 rp->rhs[i] = psp->rhs[i];
2123 rp->rhsalias[i] = psp->alias[i];
2124 }
2125 rp->lhs = psp->lhs;
2126 rp->lhsalias = psp->lhsalias;
2127 rp->nrhs = psp->nrhs;
2128 rp->code = 0;
2129 rp->precsym = 0;
2130 rp->index = psp->gp->nrule++;
2131 rp->nextlhs = rp->lhs->rule;
2132 rp->lhs->rule = rp;
2133 rp->next = 0;
2134 if( psp->firstrule==0 ){
2135 psp->firstrule = psp->lastrule = rp;
2136 }else{
2137 psp->lastrule->next = rp;
2138 psp->lastrule = rp;
2139 }
2140 psp->prevrule = rp;
2141 }
2142 psp->state = WAITING_FOR_DECL_OR_RULE;
2143 }else if( isalpha(x[0]) ){
2144 if( psp->nrhs>=MAXRHS ){
2145 ErrorMsg(psp->filename,psp->tokenlineno,
drhfd405312005-11-06 04:06:59 +00002146 "Too many symbols on RHS or rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002147 x);
2148 psp->errorcnt++;
2149 psp->state = RESYNC_AFTER_RULE_ERROR;
2150 }else{
2151 psp->rhs[psp->nrhs] = Symbol_new(x);
2152 psp->alias[psp->nrhs] = 0;
2153 psp->nrhs++;
2154 }
drhfd405312005-11-06 04:06:59 +00002155 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2156 struct symbol *msp = psp->rhs[psp->nrhs-1];
2157 if( msp->type!=MULTITERMINAL ){
2158 struct symbol *origsp = msp;
2159 msp = malloc(sizeof(*msp));
2160 memset(msp, 0, sizeof(*msp));
2161 msp->type = MULTITERMINAL;
2162 msp->nsubsym = 1;
2163 msp->subsym = malloc(sizeof(struct symbol*));
2164 msp->subsym[0] = origsp;
2165 msp->name = origsp->name;
2166 psp->rhs[psp->nrhs-1] = msp;
2167 }
2168 msp->nsubsym++;
2169 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2170 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2171 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2172 ErrorMsg(psp->filename,psp->tokenlineno,
2173 "Cannot form a compound containing a non-terminal");
2174 psp->errorcnt++;
2175 }
drh75897232000-05-29 14:26:00 +00002176 }else if( x[0]=='(' && psp->nrhs>0 ){
2177 psp->state = RHS_ALIAS_1;
2178 }else{
2179 ErrorMsg(psp->filename,psp->tokenlineno,
2180 "Illegal character on RHS of rule: \"%s\".",x);
2181 psp->errorcnt++;
2182 psp->state = RESYNC_AFTER_RULE_ERROR;
2183 }
2184 break;
2185 case RHS_ALIAS_1:
2186 if( isalpha(x[0]) ){
2187 psp->alias[psp->nrhs-1] = x;
2188 psp->state = RHS_ALIAS_2;
2189 }else{
2190 ErrorMsg(psp->filename,psp->tokenlineno,
2191 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2192 x,psp->rhs[psp->nrhs-1]->name);
2193 psp->errorcnt++;
2194 psp->state = RESYNC_AFTER_RULE_ERROR;
2195 }
2196 break;
2197 case RHS_ALIAS_2:
2198 if( x[0]==')' ){
2199 psp->state = IN_RHS;
2200 }else{
2201 ErrorMsg(psp->filename,psp->tokenlineno,
2202 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2203 psp->errorcnt++;
2204 psp->state = RESYNC_AFTER_RULE_ERROR;
2205 }
2206 break;
2207 case WAITING_FOR_DECL_KEYWORD:
2208 if( isalpha(x[0]) ){
2209 psp->declkeyword = x;
2210 psp->declargslot = 0;
2211 psp->decllnslot = 0;
2212 psp->state = WAITING_FOR_DECL_ARG;
2213 if( strcmp(x,"name")==0 ){
2214 psp->declargslot = &(psp->gp->name);
2215 }else if( strcmp(x,"include")==0 ){
2216 psp->declargslot = &(psp->gp->include);
2217 psp->decllnslot = &psp->gp->includeln;
2218 }else if( strcmp(x,"code")==0 ){
2219 psp->declargslot = &(psp->gp->extracode);
2220 psp->decllnslot = &psp->gp->extracodeln;
2221 }else if( strcmp(x,"token_destructor")==0 ){
2222 psp->declargslot = &psp->gp->tokendest;
2223 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00002224 }else if( strcmp(x,"default_destructor")==0 ){
2225 psp->declargslot = &psp->gp->vardest;
2226 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00002227 }else if( strcmp(x,"token_prefix")==0 ){
2228 psp->declargslot = &psp->gp->tokenprefix;
2229 }else if( strcmp(x,"syntax_error")==0 ){
2230 psp->declargslot = &(psp->gp->error);
2231 psp->decllnslot = &psp->gp->errorln;
2232 }else if( strcmp(x,"parse_accept")==0 ){
2233 psp->declargslot = &(psp->gp->accept);
2234 psp->decllnslot = &psp->gp->acceptln;
2235 }else if( strcmp(x,"parse_failure")==0 ){
2236 psp->declargslot = &(psp->gp->failure);
2237 psp->decllnslot = &psp->gp->failureln;
2238 }else if( strcmp(x,"stack_overflow")==0 ){
2239 psp->declargslot = &(psp->gp->overflow);
2240 psp->decllnslot = &psp->gp->overflowln;
2241 }else if( strcmp(x,"extra_argument")==0 ){
2242 psp->declargslot = &(psp->gp->arg);
2243 }else if( strcmp(x,"token_type")==0 ){
2244 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00002245 }else if( strcmp(x,"default_type")==0 ){
2246 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00002247 }else if( strcmp(x,"stack_size")==0 ){
2248 psp->declargslot = &(psp->gp->stacksize);
2249 }else if( strcmp(x,"start_symbol")==0 ){
2250 psp->declargslot = &(psp->gp->start);
2251 }else if( strcmp(x,"left")==0 ){
2252 psp->preccounter++;
2253 psp->declassoc = LEFT;
2254 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2255 }else if( strcmp(x,"right")==0 ){
2256 psp->preccounter++;
2257 psp->declassoc = RIGHT;
2258 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2259 }else if( strcmp(x,"nonassoc")==0 ){
2260 psp->preccounter++;
2261 psp->declassoc = NONE;
2262 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2263 }else if( strcmp(x,"destructor")==0 ){
2264 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2265 }else if( strcmp(x,"type")==0 ){
2266 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002267 }else if( strcmp(x,"fallback")==0 ){
2268 psp->fallback = 0;
2269 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002270 }else if( strcmp(x,"wildcard")==0 ){
2271 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002272 }else{
2273 ErrorMsg(psp->filename,psp->tokenlineno,
2274 "Unknown declaration keyword: \"%%%s\".",x);
2275 psp->errorcnt++;
2276 psp->state = RESYNC_AFTER_DECL_ERROR;
2277 }
2278 }else{
2279 ErrorMsg(psp->filename,psp->tokenlineno,
2280 "Illegal declaration keyword: \"%s\".",x);
2281 psp->errorcnt++;
2282 psp->state = RESYNC_AFTER_DECL_ERROR;
2283 }
2284 break;
2285 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2286 if( !isalpha(x[0]) ){
2287 ErrorMsg(psp->filename,psp->tokenlineno,
2288 "Symbol name missing after %destructor keyword");
2289 psp->errorcnt++;
2290 psp->state = RESYNC_AFTER_DECL_ERROR;
2291 }else{
2292 struct symbol *sp = Symbol_new(x);
2293 psp->declargslot = &sp->destructor;
2294 psp->decllnslot = &sp->destructorln;
2295 psp->state = WAITING_FOR_DECL_ARG;
2296 }
2297 break;
2298 case WAITING_FOR_DATATYPE_SYMBOL:
2299 if( !isalpha(x[0]) ){
2300 ErrorMsg(psp->filename,psp->tokenlineno,
2301 "Symbol name missing after %destructor keyword");
2302 psp->errorcnt++;
2303 psp->state = RESYNC_AFTER_DECL_ERROR;
2304 }else{
2305 struct symbol *sp = Symbol_new(x);
2306 psp->declargslot = &sp->datatype;
2307 psp->decllnslot = 0;
2308 psp->state = WAITING_FOR_DECL_ARG;
2309 }
2310 break;
2311 case WAITING_FOR_PRECEDENCE_SYMBOL:
2312 if( x[0]=='.' ){
2313 psp->state = WAITING_FOR_DECL_OR_RULE;
2314 }else if( isupper(x[0]) ){
2315 struct symbol *sp;
2316 sp = Symbol_new(x);
2317 if( sp->prec>=0 ){
2318 ErrorMsg(psp->filename,psp->tokenlineno,
2319 "Symbol \"%s\" has already be given a precedence.",x);
2320 psp->errorcnt++;
2321 }else{
2322 sp->prec = psp->preccounter;
2323 sp->assoc = psp->declassoc;
2324 }
2325 }else{
2326 ErrorMsg(psp->filename,psp->tokenlineno,
2327 "Can't assign a precedence to \"%s\".",x);
2328 psp->errorcnt++;
2329 }
2330 break;
2331 case WAITING_FOR_DECL_ARG:
2332 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2333 if( *(psp->declargslot)!=0 ){
2334 ErrorMsg(psp->filename,psp->tokenlineno,
2335 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2336 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2337 psp->errorcnt++;
2338 psp->state = RESYNC_AFTER_DECL_ERROR;
2339 }else{
2340 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2341 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2342 psp->state = WAITING_FOR_DECL_OR_RULE;
2343 }
2344 }else{
2345 ErrorMsg(psp->filename,psp->tokenlineno,
2346 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2347 psp->errorcnt++;
2348 psp->state = RESYNC_AFTER_DECL_ERROR;
2349 }
2350 break;
drh0bd1f4e2002-06-06 18:54:39 +00002351 case WAITING_FOR_FALLBACK_ID:
2352 if( x[0]=='.' ){
2353 psp->state = WAITING_FOR_DECL_OR_RULE;
2354 }else if( !isupper(x[0]) ){
2355 ErrorMsg(psp->filename, psp->tokenlineno,
2356 "%%fallback argument \"%s\" should be a token", x);
2357 psp->errorcnt++;
2358 }else{
2359 struct symbol *sp = Symbol_new(x);
2360 if( psp->fallback==0 ){
2361 psp->fallback = sp;
2362 }else if( sp->fallback ){
2363 ErrorMsg(psp->filename, psp->tokenlineno,
2364 "More than one fallback assigned to token %s", x);
2365 psp->errorcnt++;
2366 }else{
2367 sp->fallback = psp->fallback;
2368 psp->gp->has_fallback = 1;
2369 }
2370 }
2371 break;
drhe09daa92006-06-10 13:29:31 +00002372 case WAITING_FOR_WILDCARD_ID:
2373 if( x[0]=='.' ){
2374 psp->state = WAITING_FOR_DECL_OR_RULE;
2375 }else if( !isupper(x[0]) ){
2376 ErrorMsg(psp->filename, psp->tokenlineno,
2377 "%%wildcard argument \"%s\" should be a token", x);
2378 psp->errorcnt++;
2379 }else{
2380 struct symbol *sp = Symbol_new(x);
2381 if( psp->gp->wildcard==0 ){
2382 psp->gp->wildcard = sp;
2383 }else{
2384 ErrorMsg(psp->filename, psp->tokenlineno,
2385 "Extra wildcard to token: %s", x);
2386 psp->errorcnt++;
2387 }
2388 }
2389 break;
drh75897232000-05-29 14:26:00 +00002390 case RESYNC_AFTER_RULE_ERROR:
2391/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2392** break; */
2393 case RESYNC_AFTER_DECL_ERROR:
2394 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2395 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2396 break;
2397 }
2398}
2399
drh6d08b4d2004-07-20 12:45:22 +00002400/* Run the proprocessor over the input file text. The global variables
2401** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2402** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2403** comments them out. Text in between is also commented out as appropriate.
2404*/
danielk1977940fac92005-01-23 22:41:37 +00002405static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002406 int i, j, k, n;
2407 int exclude = 0;
2408 int start;
2409 int lineno = 1;
2410 int start_lineno;
2411 for(i=0; z[i]; i++){
2412 if( z[i]=='\n' ) lineno++;
2413 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2414 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2415 if( exclude ){
2416 exclude--;
2417 if( exclude==0 ){
2418 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2419 }
2420 }
2421 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2422 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2423 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2424 if( exclude ){
2425 exclude++;
2426 }else{
2427 for(j=i+7; isspace(z[j]); j++){}
2428 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2429 exclude = 1;
2430 for(k=0; k<nDefine; k++){
2431 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2432 exclude = 0;
2433 break;
2434 }
2435 }
2436 if( z[i+3]=='n' ) exclude = !exclude;
2437 if( exclude ){
2438 start = i;
2439 start_lineno = lineno;
2440 }
2441 }
2442 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2443 }
2444 }
2445 if( exclude ){
2446 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2447 exit(1);
2448 }
2449}
2450
drh75897232000-05-29 14:26:00 +00002451/* In spite of its name, this function is really a scanner. It read
2452** in the entire input file (all at once) then tokenizes it. Each
2453** token is passed to the function "parseonetoken" which builds all
2454** the appropriate data structures in the global state vector "gp".
2455*/
2456void Parse(gp)
2457struct lemon *gp;
2458{
2459 struct pstate ps;
2460 FILE *fp;
2461 char *filebuf;
2462 int filesize;
2463 int lineno;
2464 int c;
2465 char *cp, *nextcp;
2466 int startline = 0;
2467
2468 ps.gp = gp;
2469 ps.filename = gp->filename;
2470 ps.errorcnt = 0;
2471 ps.state = INITIALIZE;
2472
2473 /* Begin by reading the input file */
2474 fp = fopen(ps.filename,"rb");
2475 if( fp==0 ){
2476 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2477 gp->errorcnt++;
2478 return;
2479 }
2480 fseek(fp,0,2);
2481 filesize = ftell(fp);
2482 rewind(fp);
2483 filebuf = (char *)malloc( filesize+1 );
2484 if( filebuf==0 ){
2485 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2486 filesize+1);
2487 gp->errorcnt++;
2488 return;
2489 }
2490 if( fread(filebuf,1,filesize,fp)!=filesize ){
2491 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2492 filesize);
2493 free(filebuf);
2494 gp->errorcnt++;
2495 return;
2496 }
2497 fclose(fp);
2498 filebuf[filesize] = 0;
2499
drh6d08b4d2004-07-20 12:45:22 +00002500 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2501 preprocess_input(filebuf);
2502
drh75897232000-05-29 14:26:00 +00002503 /* Now scan the text of the input file */
2504 lineno = 1;
2505 for(cp=filebuf; (c= *cp)!=0; ){
2506 if( c=='\n' ) lineno++; /* Keep track of the line number */
2507 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2508 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2509 cp+=2;
2510 while( (c= *cp)!=0 && c!='\n' ) cp++;
2511 continue;
2512 }
2513 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2514 cp+=2;
2515 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2516 if( c=='\n' ) lineno++;
2517 cp++;
2518 }
2519 if( c ) cp++;
2520 continue;
2521 }
2522 ps.tokenstart = cp; /* Mark the beginning of the token */
2523 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2524 if( c=='\"' ){ /* String literals */
2525 cp++;
2526 while( (c= *cp)!=0 && c!='\"' ){
2527 if( c=='\n' ) lineno++;
2528 cp++;
2529 }
2530 if( c==0 ){
2531 ErrorMsg(ps.filename,startline,
2532"String starting on this line is not terminated before the end of the file.");
2533 ps.errorcnt++;
2534 nextcp = cp;
2535 }else{
2536 nextcp = cp+1;
2537 }
2538 }else if( c=='{' ){ /* A block of C code */
2539 int level;
2540 cp++;
2541 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2542 if( c=='\n' ) lineno++;
2543 else if( c=='{' ) level++;
2544 else if( c=='}' ) level--;
2545 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2546 int prevc;
2547 cp = &cp[2];
2548 prevc = 0;
2549 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2550 if( c=='\n' ) lineno++;
2551 prevc = c;
2552 cp++;
2553 }
2554 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2555 cp = &cp[2];
2556 while( (c= *cp)!=0 && c!='\n' ) cp++;
2557 if( c ) lineno++;
2558 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2559 int startchar, prevc;
2560 startchar = c;
2561 prevc = 0;
2562 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2563 if( c=='\n' ) lineno++;
2564 if( prevc=='\\' ) prevc = 0;
2565 else prevc = c;
2566 }
2567 }
2568 }
2569 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002570 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002571"C code starting on this line is not terminated before the end of the file.");
2572 ps.errorcnt++;
2573 nextcp = cp;
2574 }else{
2575 nextcp = cp+1;
2576 }
2577 }else if( isalnum(c) ){ /* Identifiers */
2578 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2579 nextcp = cp;
2580 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2581 cp += 3;
2582 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002583 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2584 cp += 2;
2585 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2586 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002587 }else{ /* All other (one character) operators */
2588 cp++;
2589 nextcp = cp;
2590 }
2591 c = *cp;
2592 *cp = 0; /* Null terminate the token */
2593 parseonetoken(&ps); /* Parse the token */
2594 *cp = c; /* Restore the buffer */
2595 cp = nextcp;
2596 }
2597 free(filebuf); /* Release the buffer after parsing */
2598 gp->rule = ps.firstrule;
2599 gp->errorcnt = ps.errorcnt;
2600}
2601/*************************** From the file "plink.c" *********************/
2602/*
2603** Routines processing configuration follow-set propagation links
2604** in the LEMON parser generator.
2605*/
2606static struct plink *plink_freelist = 0;
2607
2608/* Allocate a new plink */
2609struct plink *Plink_new(){
2610 struct plink *new;
2611
2612 if( plink_freelist==0 ){
2613 int i;
2614 int amt = 100;
2615 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2616 if( plink_freelist==0 ){
2617 fprintf(stderr,
2618 "Unable to allocate memory for a new follow-set propagation link.\n");
2619 exit(1);
2620 }
2621 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2622 plink_freelist[amt-1].next = 0;
2623 }
2624 new = plink_freelist;
2625 plink_freelist = plink_freelist->next;
2626 return new;
2627}
2628
2629/* Add a plink to a plink list */
2630void Plink_add(plpp,cfp)
2631struct plink **plpp;
2632struct config *cfp;
2633{
2634 struct plink *new;
2635 new = Plink_new();
2636 new->next = *plpp;
2637 *plpp = new;
2638 new->cfp = cfp;
2639}
2640
2641/* Transfer every plink on the list "from" to the list "to" */
2642void Plink_copy(to,from)
2643struct plink **to;
2644struct plink *from;
2645{
2646 struct plink *nextpl;
2647 while( from ){
2648 nextpl = from->next;
2649 from->next = *to;
2650 *to = from;
2651 from = nextpl;
2652 }
2653}
2654
2655/* Delete every plink on the list */
2656void Plink_delete(plp)
2657struct plink *plp;
2658{
2659 struct plink *nextpl;
2660
2661 while( plp ){
2662 nextpl = plp->next;
2663 plp->next = plink_freelist;
2664 plink_freelist = plp;
2665 plp = nextpl;
2666 }
2667}
2668/*********************** From the file "report.c" **************************/
2669/*
2670** Procedures for generating reports and tables in the LEMON parser generator.
2671*/
2672
2673/* Generate a filename with the given suffix. Space to hold the
2674** name comes from malloc() and must be freed by the calling
2675** function.
2676*/
2677PRIVATE char *file_makename(lemp,suffix)
2678struct lemon *lemp;
2679char *suffix;
2680{
2681 char *name;
2682 char *cp;
2683
2684 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2685 if( name==0 ){
2686 fprintf(stderr,"Can't allocate space for a filename.\n");
2687 exit(1);
2688 }
2689 strcpy(name,lemp->filename);
2690 cp = strrchr(name,'.');
2691 if( cp ) *cp = 0;
2692 strcat(name,suffix);
2693 return name;
2694}
2695
2696/* Open a file with a name based on the name of the input file,
2697** but with a different (specified) suffix, and return a pointer
2698** to the stream */
2699PRIVATE FILE *file_open(lemp,suffix,mode)
2700struct lemon *lemp;
2701char *suffix;
2702char *mode;
2703{
2704 FILE *fp;
2705
2706 if( lemp->outname ) free(lemp->outname);
2707 lemp->outname = file_makename(lemp, suffix);
2708 fp = fopen(lemp->outname,mode);
2709 if( fp==0 && *mode=='w' ){
2710 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2711 lemp->errorcnt++;
2712 return 0;
2713 }
2714 return fp;
2715}
2716
2717/* Duplicate the input file without comments and without actions
2718** on rules */
2719void Reprint(lemp)
2720struct lemon *lemp;
2721{
2722 struct rule *rp;
2723 struct symbol *sp;
2724 int i, j, maxlen, len, ncolumns, skip;
2725 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2726 maxlen = 10;
2727 for(i=0; i<lemp->nsymbol; i++){
2728 sp = lemp->symbols[i];
2729 len = strlen(sp->name);
2730 if( len>maxlen ) maxlen = len;
2731 }
2732 ncolumns = 76/(maxlen+5);
2733 if( ncolumns<1 ) ncolumns = 1;
2734 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2735 for(i=0; i<skip; i++){
2736 printf("//");
2737 for(j=i; j<lemp->nsymbol; j+=skip){
2738 sp = lemp->symbols[j];
2739 assert( sp->index==j );
2740 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2741 }
2742 printf("\n");
2743 }
2744 for(rp=lemp->rule; rp; rp=rp->next){
2745 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002746 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002747 printf(" ::=");
2748 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002749 sp = rp->rhs[i];
2750 printf(" %s", sp->name);
2751 if( sp->type==MULTITERMINAL ){
2752 for(j=1; j<sp->nsubsym; j++){
2753 printf("|%s", sp->subsym[j]->name);
2754 }
2755 }
2756 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002757 }
2758 printf(".");
2759 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002760 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002761 printf("\n");
2762 }
2763}
2764
2765void ConfigPrint(fp,cfp)
2766FILE *fp;
2767struct config *cfp;
2768{
2769 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002770 struct symbol *sp;
2771 int i, j;
drh75897232000-05-29 14:26:00 +00002772 rp = cfp->rp;
2773 fprintf(fp,"%s ::=",rp->lhs->name);
2774 for(i=0; i<=rp->nrhs; i++){
2775 if( i==cfp->dot ) fprintf(fp," *");
2776 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002777 sp = rp->rhs[i];
2778 fprintf(fp," %s", sp->name);
2779 if( sp->type==MULTITERMINAL ){
2780 for(j=1; j<sp->nsubsym; j++){
2781 fprintf(fp,"|%s",sp->subsym[j]->name);
2782 }
2783 }
drh75897232000-05-29 14:26:00 +00002784 }
2785}
2786
2787/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002788#if 0
drh75897232000-05-29 14:26:00 +00002789/* Print a set */
2790PRIVATE void SetPrint(out,set,lemp)
2791FILE *out;
2792char *set;
2793struct lemon *lemp;
2794{
2795 int i;
2796 char *spacer;
2797 spacer = "";
2798 fprintf(out,"%12s[","");
2799 for(i=0; i<lemp->nterminal; i++){
2800 if( SetFind(set,i) ){
2801 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2802 spacer = " ";
2803 }
2804 }
2805 fprintf(out,"]\n");
2806}
2807
2808/* Print a plink chain */
2809PRIVATE void PlinkPrint(out,plp,tag)
2810FILE *out;
2811struct plink *plp;
2812char *tag;
2813{
2814 while( plp ){
drhada354d2005-11-05 15:03:59 +00002815 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002816 ConfigPrint(out,plp->cfp);
2817 fprintf(out,"\n");
2818 plp = plp->next;
2819 }
2820}
2821#endif
2822
2823/* Print an action to the given file descriptor. Return FALSE if
2824** nothing was actually printed.
2825*/
2826int PrintAction(struct action *ap, FILE *fp, int indent){
2827 int result = 1;
2828 switch( ap->type ){
2829 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002830 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002831 break;
2832 case REDUCE:
2833 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2834 break;
2835 case ACCEPT:
2836 fprintf(fp,"%*s accept",indent,ap->sp->name);
2837 break;
2838 case ERROR:
2839 fprintf(fp,"%*s error",indent,ap->sp->name);
2840 break;
2841 case CONFLICT:
2842 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2843 indent,ap->sp->name,ap->x.rp->index);
2844 break;
2845 case SH_RESOLVED:
2846 case RD_RESOLVED:
2847 case NOT_USED:
2848 result = 0;
2849 break;
2850 }
2851 return result;
2852}
2853
2854/* Generate the "y.output" log file */
2855void ReportOutput(lemp)
2856struct lemon *lemp;
2857{
2858 int i;
2859 struct state *stp;
2860 struct config *cfp;
2861 struct action *ap;
2862 FILE *fp;
2863
drh2aa6ca42004-09-10 00:14:04 +00002864 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002865 if( fp==0 ) return;
2866 fprintf(fp," \b");
2867 for(i=0; i<lemp->nstate; i++){
2868 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002869 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002870 if( lemp->basisflag ) cfp=stp->bp;
2871 else cfp=stp->cfp;
2872 while( cfp ){
2873 char buf[20];
2874 if( cfp->dot==cfp->rp->nrhs ){
2875 sprintf(buf,"(%d)",cfp->rp->index);
2876 fprintf(fp," %5s ",buf);
2877 }else{
2878 fprintf(fp," ");
2879 }
2880 ConfigPrint(fp,cfp);
2881 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002882#if 0
drh75897232000-05-29 14:26:00 +00002883 SetPrint(fp,cfp->fws,lemp);
2884 PlinkPrint(fp,cfp->fplp,"To ");
2885 PlinkPrint(fp,cfp->bplp,"From");
2886#endif
2887 if( lemp->basisflag ) cfp=cfp->bp;
2888 else cfp=cfp->next;
2889 }
2890 fprintf(fp,"\n");
2891 for(ap=stp->ap; ap; ap=ap->next){
2892 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2893 }
2894 fprintf(fp,"\n");
2895 }
2896 fclose(fp);
2897 return;
2898}
2899
2900/* Search for the file "name" which is in the same directory as
2901** the exacutable */
2902PRIVATE char *pathsearch(argv0,name,modemask)
2903char *argv0;
2904char *name;
2905int modemask;
2906{
2907 char *pathlist;
2908 char *path,*cp;
2909 char c;
2910 extern int access();
2911
2912#ifdef __WIN32__
2913 cp = strrchr(argv0,'\\');
2914#else
2915 cp = strrchr(argv0,'/');
2916#endif
2917 if( cp ){
2918 c = *cp;
2919 *cp = 0;
2920 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2921 if( path ) sprintf(path,"%s/%s",argv0,name);
2922 *cp = c;
2923 }else{
2924 extern char *getenv();
2925 pathlist = getenv("PATH");
2926 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2927 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2928 if( path!=0 ){
2929 while( *pathlist ){
2930 cp = strchr(pathlist,':');
2931 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2932 c = *cp;
2933 *cp = 0;
2934 sprintf(path,"%s/%s",pathlist,name);
2935 *cp = c;
2936 if( c==0 ) pathlist = "";
2937 else pathlist = &cp[1];
2938 if( access(path,modemask)==0 ) break;
2939 }
2940 }
2941 }
2942 return path;
2943}
2944
2945/* Given an action, compute the integer value for that action
2946** which is to be put in the action table of the generated machine.
2947** Return negative if no action should be generated.
2948*/
2949PRIVATE int compute_action(lemp,ap)
2950struct lemon *lemp;
2951struct action *ap;
2952{
2953 int act;
2954 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00002955 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00002956 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2957 case ERROR: act = lemp->nstate + lemp->nrule; break;
2958 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2959 default: act = -1; break;
2960 }
2961 return act;
2962}
2963
2964#define LINESIZE 1000
2965/* The next cluster of routines are for reading the template file
2966** and writing the results to the generated parser */
2967/* The first function transfers data from "in" to "out" until
2968** a line is seen which begins with "%%". The line number is
2969** tracked.
2970**
2971** if name!=0, then any word that begin with "Parse" is changed to
2972** begin with *name instead.
2973*/
2974PRIVATE void tplt_xfer(name,in,out,lineno)
2975char *name;
2976FILE *in;
2977FILE *out;
2978int *lineno;
2979{
2980 int i, iStart;
2981 char line[LINESIZE];
2982 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2983 (*lineno)++;
2984 iStart = 0;
2985 if( name ){
2986 for(i=0; line[i]; i++){
2987 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2988 && (i==0 || !isalpha(line[i-1]))
2989 ){
2990 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2991 fprintf(out,"%s",name);
2992 i += 4;
2993 iStart = i+1;
2994 }
2995 }
2996 }
2997 fprintf(out,"%s",&line[iStart]);
2998 }
2999}
3000
3001/* The next function finds the template file and opens it, returning
3002** a pointer to the opened file. */
3003PRIVATE FILE *tplt_open(lemp)
3004struct lemon *lemp;
3005{
3006 static char templatename[] = "lempar.c";
3007 char buf[1000];
3008 FILE *in;
3009 char *tpltname;
3010 char *cp;
3011
3012 cp = strrchr(lemp->filename,'.');
3013 if( cp ){
drh8b582012003-10-21 13:16:03 +00003014 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003015 }else{
3016 sprintf(buf,"%s.lt",lemp->filename);
3017 }
3018 if( access(buf,004)==0 ){
3019 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003020 }else if( access(templatename,004)==0 ){
3021 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003022 }else{
3023 tpltname = pathsearch(lemp->argv0,templatename,0);
3024 }
3025 if( tpltname==0 ){
3026 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3027 templatename);
3028 lemp->errorcnt++;
3029 return 0;
3030 }
drh2aa6ca42004-09-10 00:14:04 +00003031 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003032 if( in==0 ){
3033 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3034 lemp->errorcnt++;
3035 return 0;
3036 }
3037 return in;
3038}
3039
drhaf805ca2004-09-07 11:28:25 +00003040/* Print a #line directive line to the output file. */
3041PRIVATE void tplt_linedir(out,lineno,filename)
3042FILE *out;
3043int lineno;
3044char *filename;
3045{
3046 fprintf(out,"#line %d \"",lineno);
3047 while( *filename ){
3048 if( *filename == '\\' ) putc('\\',out);
3049 putc(*filename,out);
3050 filename++;
3051 }
3052 fprintf(out,"\"\n");
3053}
3054
drh75897232000-05-29 14:26:00 +00003055/* Print a string to the file and keep the linenumber up to date */
3056PRIVATE void tplt_print(out,lemp,str,strln,lineno)
3057FILE *out;
3058struct lemon *lemp;
3059char *str;
3060int strln;
3061int *lineno;
3062{
3063 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003064 tplt_linedir(out,strln,lemp->filename);
3065 (*lineno)++;
drh75897232000-05-29 14:26:00 +00003066 while( *str ){
3067 if( *str=='\n' ) (*lineno)++;
3068 putc(*str,out);
3069 str++;
3070 }
drh9db55df2004-09-09 14:01:21 +00003071 if( str[-1]!='\n' ){
3072 putc('\n',out);
3073 (*lineno)++;
3074 }
drhaf805ca2004-09-07 11:28:25 +00003075 tplt_linedir(out,*lineno+2,lemp->outname);
3076 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00003077 return;
3078}
3079
3080/*
3081** The following routine emits code for the destructor for the
3082** symbol sp
3083*/
3084void emit_destructor_code(out,sp,lemp,lineno)
3085FILE *out;
3086struct symbol *sp;
3087struct lemon *lemp;
3088int *lineno;
3089{
drhcc83b6e2004-04-23 23:38:42 +00003090 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003091
3092 int linecnt = 0;
3093 if( sp->type==TERMINAL ){
3094 cp = lemp->tokendest;
3095 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003096 tplt_linedir(out,lemp->tokendestln,lemp->filename);
3097 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00003098 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003099 cp = sp->destructor;
drhaf805ca2004-09-07 11:28:25 +00003100 tplt_linedir(out,sp->destructorln,lemp->filename);
3101 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00003102 }else if( lemp->vardest ){
3103 cp = lemp->vardest;
3104 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003105 tplt_linedir(out,lemp->vardestln,lemp->filename);
3106 fprintf(out,"{");
drhcc83b6e2004-04-23 23:38:42 +00003107 }else{
3108 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003109 }
3110 for(; *cp; cp++){
3111 if( *cp=='$' && cp[1]=='$' ){
3112 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3113 cp++;
3114 continue;
3115 }
3116 if( *cp=='\n' ) linecnt++;
3117 fputc(*cp,out);
3118 }
3119 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003120 fprintf(out,"}\n");
3121 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003122 return;
3123}
3124
3125/*
drh960e8c62001-04-03 16:53:21 +00003126** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003127*/
3128int has_destructor(sp, lemp)
3129struct symbol *sp;
3130struct lemon *lemp;
3131{
3132 int ret;
3133 if( sp->type==TERMINAL ){
3134 ret = lemp->tokendest!=0;
3135 }else{
drh960e8c62001-04-03 16:53:21 +00003136 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003137 }
3138 return ret;
3139}
3140
drh0bb132b2004-07-20 14:06:51 +00003141/*
3142** Append text to a dynamically allocated string. If zText is 0 then
3143** reset the string to be empty again. Always return the complete text
3144** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003145**
3146** n bytes of zText are stored. If n==0 then all of zText up to the first
3147** \000 terminator is stored. zText can contain up to two instances of
3148** %d. The values of p1 and p2 are written into the first and second
3149** %d.
3150**
3151** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003152*/
3153PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3154 static char *z = 0;
3155 static int alloced = 0;
3156 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003157 int c;
drh0bb132b2004-07-20 14:06:51 +00003158 char zInt[40];
3159
3160 if( zText==0 ){
3161 used = 0;
3162 return z;
3163 }
drh7ac25c72004-08-19 15:12:26 +00003164 if( n<=0 ){
3165 if( n<0 ){
3166 used += n;
3167 assert( used>=0 );
3168 }
3169 n = strlen(zText);
3170 }
drh0bb132b2004-07-20 14:06:51 +00003171 if( n+sizeof(zInt)*2+used >= alloced ){
3172 alloced = n + sizeof(zInt)*2 + used + 200;
3173 z = realloc(z, alloced);
3174 }
3175 if( z==0 ) return "";
3176 while( n-- > 0 ){
3177 c = *(zText++);
3178 if( c=='%' && zText[0]=='d' ){
3179 sprintf(zInt, "%d", p1);
3180 p1 = p2;
3181 strcpy(&z[used], zInt);
3182 used += strlen(&z[used]);
3183 zText++;
3184 n--;
3185 }else{
3186 z[used++] = c;
3187 }
3188 }
3189 z[used] = 0;
3190 return z;
3191}
3192
3193/*
3194** zCode is a string that is the action associated with a rule. Expand
3195** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003196** stack.
drh0bb132b2004-07-20 14:06:51 +00003197*/
drhaf805ca2004-09-07 11:28:25 +00003198PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003199 char *cp, *xp;
3200 int i;
3201 char lhsused = 0; /* True if the LHS element has been used */
3202 char used[MAXRHS]; /* True for each RHS element which is used */
3203
3204 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3205 lhsused = 0;
3206
3207 append_str(0,0,0,0);
3208 for(cp=rp->code; *cp; cp++){
3209 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3210 char saved;
3211 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3212 saved = *xp;
3213 *xp = 0;
3214 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003215 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003216 cp = xp;
3217 lhsused = 1;
3218 }else{
3219 for(i=0; i<rp->nrhs; i++){
3220 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003221 if( cp!=rp->code && cp[-1]=='@' ){
3222 /* If the argument is of the form @X then substituted
3223 ** the token number of X, not the value of X */
3224 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3225 }else{
drhfd405312005-11-06 04:06:59 +00003226 struct symbol *sp = rp->rhs[i];
3227 int dtnum;
3228 if( sp->type==MULTITERMINAL ){
3229 dtnum = sp->subsym[0]->dtnum;
3230 }else{
3231 dtnum = sp->dtnum;
3232 }
3233 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003234 }
drh0bb132b2004-07-20 14:06:51 +00003235 cp = xp;
3236 used[i] = 1;
3237 break;
3238 }
3239 }
3240 }
3241 *xp = saved;
3242 }
3243 append_str(cp, 1, 0, 0);
3244 } /* End loop */
3245
3246 /* Check to make sure the LHS has been used */
3247 if( rp->lhsalias && !lhsused ){
3248 ErrorMsg(lemp->filename,rp->ruleline,
3249 "Label \"%s\" for \"%s(%s)\" is never used.",
3250 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3251 lemp->errorcnt++;
3252 }
3253
3254 /* Generate destructor code for RHS symbols which are not used in the
3255 ** reduce code */
3256 for(i=0; i<rp->nrhs; i++){
3257 if( rp->rhsalias[i] && !used[i] ){
3258 ErrorMsg(lemp->filename,rp->ruleline,
3259 "Label %s for \"%s(%s)\" is never used.",
3260 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3261 lemp->errorcnt++;
3262 }else if( rp->rhsalias[i]==0 ){
3263 if( has_destructor(rp->rhs[i],lemp) ){
drh7ac25c72004-08-19 15:12:26 +00003264 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003265 rp->rhs[i]->index,i-rp->nrhs+1);
3266 }else{
3267 /* No destructor defined for this term */
3268 }
3269 }
3270 }
3271 cp = append_str(0,0,0,0);
3272 rp->code = Strsafe(cp);
3273}
3274
drh75897232000-05-29 14:26:00 +00003275/*
3276** Generate code which executes when the rule "rp" is reduced. Write
3277** the code to "out". Make sure lineno stays up-to-date.
3278*/
3279PRIVATE void emit_code(out,rp,lemp,lineno)
3280FILE *out;
3281struct rule *rp;
3282struct lemon *lemp;
3283int *lineno;
3284{
drh0bb132b2004-07-20 14:06:51 +00003285 char *cp;
drh75897232000-05-29 14:26:00 +00003286 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003287
3288 /* Generate code to do the reduce action */
3289 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003290 tplt_linedir(out,rp->line,lemp->filename);
3291 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003292 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003293 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003294 } /* End loop */
3295 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003296 fprintf(out,"}\n");
3297 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003298 } /* End if( rp->code ) */
3299
drh75897232000-05-29 14:26:00 +00003300 return;
3301}
3302
3303/*
3304** Print the definition of the union used for the parser's data stack.
3305** This union contains fields for every possible data type for tokens
3306** and nonterminals. In the process of computing and printing this
3307** union, also set the ".dtnum" field of every terminal and nonterminal
3308** symbol.
3309*/
3310void print_stack_union(out,lemp,plineno,mhflag)
3311FILE *out; /* The output stream */
3312struct lemon *lemp; /* The main info structure for this parser */
3313int *plineno; /* Pointer to the line number */
3314int mhflag; /* True if generating makeheaders output */
3315{
3316 int lineno = *plineno; /* The line number of the output */
3317 char **types; /* A hash table of datatypes */
3318 int arraysize; /* Size of the "types" array */
3319 int maxdtlength; /* Maximum length of any ".datatype" field. */
3320 char *stddt; /* Standardized name for a datatype */
3321 int i,j; /* Loop counters */
3322 int hash; /* For hashing the name of a type */
3323 char *name; /* Name of the parser */
3324
3325 /* Allocate and initialize types[] and allocate stddt[] */
3326 arraysize = lemp->nsymbol * 2;
3327 types = (char**)malloc( arraysize * sizeof(char*) );
3328 for(i=0; i<arraysize; i++) types[i] = 0;
3329 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003330 if( lemp->vartype ){
3331 maxdtlength = strlen(lemp->vartype);
3332 }
drh75897232000-05-29 14:26:00 +00003333 for(i=0; i<lemp->nsymbol; i++){
3334 int len;
3335 struct symbol *sp = lemp->symbols[i];
3336 if( sp->datatype==0 ) continue;
3337 len = strlen(sp->datatype);
3338 if( len>maxdtlength ) maxdtlength = len;
3339 }
3340 stddt = (char*)malloc( maxdtlength*2 + 1 );
3341 if( types==0 || stddt==0 ){
3342 fprintf(stderr,"Out of memory.\n");
3343 exit(1);
3344 }
3345
3346 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3347 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003348 ** used for terminal symbols. If there is no %default_type defined then
3349 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3350 ** a datatype using the %type directive.
3351 */
drh75897232000-05-29 14:26:00 +00003352 for(i=0; i<lemp->nsymbol; i++){
3353 struct symbol *sp = lemp->symbols[i];
3354 char *cp;
3355 if( sp==lemp->errsym ){
3356 sp->dtnum = arraysize+1;
3357 continue;
3358 }
drh960e8c62001-04-03 16:53:21 +00003359 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003360 sp->dtnum = 0;
3361 continue;
3362 }
3363 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003364 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003365 j = 0;
3366 while( isspace(*cp) ) cp++;
3367 while( *cp ) stddt[j++] = *cp++;
3368 while( j>0 && isspace(stddt[j-1]) ) j--;
3369 stddt[j] = 0;
3370 hash = 0;
3371 for(j=0; stddt[j]; j++){
3372 hash = hash*53 + stddt[j];
3373 }
drh3b2129c2003-05-13 00:34:21 +00003374 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003375 while( types[hash] ){
3376 if( strcmp(types[hash],stddt)==0 ){
3377 sp->dtnum = hash + 1;
3378 break;
3379 }
3380 hash++;
3381 if( hash>=arraysize ) hash = 0;
3382 }
3383 if( types[hash]==0 ){
3384 sp->dtnum = hash + 1;
3385 types[hash] = (char*)malloc( strlen(stddt)+1 );
3386 if( types[hash]==0 ){
3387 fprintf(stderr,"Out of memory.\n");
3388 exit(1);
3389 }
3390 strcpy(types[hash],stddt);
3391 }
3392 }
3393
3394 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3395 name = lemp->name ? lemp->name : "Parse";
3396 lineno = *plineno;
3397 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3398 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3399 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3400 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3401 fprintf(out,"typedef union {\n"); lineno++;
3402 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3403 for(i=0; i<arraysize; i++){
3404 if( types[i]==0 ) continue;
3405 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3406 free(types[i]);
3407 }
3408 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3409 free(stddt);
3410 free(types);
3411 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3412 *plineno = lineno;
3413}
3414
drhb29b0a52002-02-23 19:39:46 +00003415/*
3416** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003417** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003418*/
drh8b582012003-10-21 13:16:03 +00003419static const char *minimum_size_type(int lwr, int upr){
3420 if( lwr>=0 ){
3421 if( upr<=255 ){
3422 return "unsigned char";
3423 }else if( upr<65535 ){
3424 return "unsigned short int";
3425 }else{
3426 return "unsigned int";
3427 }
3428 }else if( lwr>=-127 && upr<=127 ){
3429 return "signed char";
3430 }else if( lwr>=-32767 && upr<32767 ){
3431 return "short";
drhb29b0a52002-02-23 19:39:46 +00003432 }else{
drh8b582012003-10-21 13:16:03 +00003433 return "int";
drhb29b0a52002-02-23 19:39:46 +00003434 }
3435}
3436
drhfdbf9282003-10-21 16:34:41 +00003437/*
3438** Each state contains a set of token transaction and a set of
3439** nonterminal transactions. Each of these sets makes an instance
3440** of the following structure. An array of these structures is used
3441** to order the creation of entries in the yy_action[] table.
3442*/
3443struct axset {
3444 struct state *stp; /* A pointer to a state */
3445 int isTkn; /* True to use tokens. False for non-terminals */
3446 int nAction; /* Number of actions */
3447};
3448
3449/*
3450** Compare to axset structures for sorting purposes
3451*/
3452static int axset_compare(const void *a, const void *b){
3453 struct axset *p1 = (struct axset*)a;
3454 struct axset *p2 = (struct axset*)b;
3455 return p2->nAction - p1->nAction;
3456}
3457
drh75897232000-05-29 14:26:00 +00003458/* Generate C source code for the parser */
3459void ReportTable(lemp, mhflag)
3460struct lemon *lemp;
3461int mhflag; /* Output in makeheaders format if true */
3462{
3463 FILE *out, *in;
3464 char line[LINESIZE];
3465 int lineno;
3466 struct state *stp;
3467 struct action *ap;
3468 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003469 struct acttab *pActtab;
3470 int i, j, n;
drh75897232000-05-29 14:26:00 +00003471 char *name;
drh8b582012003-10-21 13:16:03 +00003472 int mnTknOfst, mxTknOfst;
3473 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003474 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003475
3476 in = tplt_open(lemp);
3477 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003478 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003479 if( out==0 ){
3480 fclose(in);
3481 return;
3482 }
3483 lineno = 1;
3484 tplt_xfer(lemp->name,in,out,&lineno);
3485
3486 /* Generate the include code, if any */
3487 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3488 if( mhflag ){
3489 char *name = file_makename(lemp, ".h");
3490 fprintf(out,"#include \"%s\"\n", name); lineno++;
3491 free(name);
3492 }
3493 tplt_xfer(lemp->name,in,out,&lineno);
3494
3495 /* Generate #defines for all tokens */
3496 if( mhflag ){
3497 char *prefix;
3498 fprintf(out,"#if INTERFACE\n"); lineno++;
3499 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3500 else prefix = "";
3501 for(i=1; i<lemp->nterminal; i++){
3502 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3503 lineno++;
3504 }
3505 fprintf(out,"#endif\n"); lineno++;
3506 }
3507 tplt_xfer(lemp->name,in,out,&lineno);
3508
3509 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003510 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003511 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003512 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3513 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003514 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003515 if( lemp->wildcard ){
3516 fprintf(out,"#define YYWILDCARD %d\n",
3517 lemp->wildcard->index); lineno++;
3518 }
drh75897232000-05-29 14:26:00 +00003519 print_stack_union(out,lemp,&lineno,mhflag);
3520 if( lemp->stacksize ){
3521 if( atoi(lemp->stacksize)<=0 ){
3522 ErrorMsg(lemp->filename,0,
3523"Illegal stack size: [%s]. The stack size should be an integer constant.",
3524 lemp->stacksize);
3525 lemp->errorcnt++;
3526 lemp->stacksize = "100";
3527 }
3528 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3529 }else{
3530 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3531 }
3532 if( mhflag ){
3533 fprintf(out,"#if INTERFACE\n"); lineno++;
3534 }
3535 name = lemp->name ? lemp->name : "Parse";
3536 if( lemp->arg && lemp->arg[0] ){
3537 int i;
3538 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003539 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3540 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003541 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3542 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3543 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3544 name,lemp->arg,&lemp->arg[i]); lineno++;
3545 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3546 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003547 }else{
drh1f245e42002-03-11 13:55:50 +00003548 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3549 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3550 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3551 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003552 }
3553 if( mhflag ){
3554 fprintf(out,"#endif\n"); lineno++;
3555 }
3556 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3557 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3558 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3559 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drh0bd1f4e2002-06-06 18:54:39 +00003560 if( lemp->has_fallback ){
3561 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3562 }
drh75897232000-05-29 14:26:00 +00003563 tplt_xfer(lemp->name,in,out,&lineno);
3564
drh8b582012003-10-21 13:16:03 +00003565 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003566 **
drh8b582012003-10-21 13:16:03 +00003567 ** yy_action[] A single table containing all actions.
3568 ** yy_lookahead[] A table containing the lookahead for each entry in
3569 ** yy_action. Used to detect hash collisions.
3570 ** yy_shift_ofst[] For each state, the offset into yy_action for
3571 ** shifting terminals.
3572 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3573 ** shifting non-terminals after a reduce.
3574 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003575 */
drh75897232000-05-29 14:26:00 +00003576
drh8b582012003-10-21 13:16:03 +00003577 /* Compute the actions on all states and count them up */
drhfdbf9282003-10-21 16:34:41 +00003578 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3579 if( ax==0 ){
3580 fprintf(stderr,"malloc failed\n");
3581 exit(1);
3582 }
drh75897232000-05-29 14:26:00 +00003583 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003584 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003585 ax[i*2].stp = stp;
3586 ax[i*2].isTkn = 1;
3587 ax[i*2].nAction = stp->nTknAct;
3588 ax[i*2+1].stp = stp;
3589 ax[i*2+1].isTkn = 0;
3590 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003591 }
drh8b582012003-10-21 13:16:03 +00003592 mxTknOfst = mnTknOfst = 0;
3593 mxNtOfst = mnNtOfst = 0;
3594
drhfdbf9282003-10-21 16:34:41 +00003595 /* Compute the action table. In order to try to keep the size of the
3596 ** action table to a minimum, the heuristic of placing the largest action
3597 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003598 */
drhfdbf9282003-10-21 16:34:41 +00003599 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003600 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003601 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3602 stp = ax[i].stp;
3603 if( ax[i].isTkn ){
3604 for(ap=stp->ap; ap; ap=ap->next){
3605 int action;
3606 if( ap->sp->index>=lemp->nterminal ) continue;
3607 action = compute_action(lemp, ap);
3608 if( action<0 ) continue;
3609 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003610 }
drhfdbf9282003-10-21 16:34:41 +00003611 stp->iTknOfst = acttab_insert(pActtab);
3612 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3613 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3614 }else{
3615 for(ap=stp->ap; ap; ap=ap->next){
3616 int action;
3617 if( ap->sp->index<lemp->nterminal ) continue;
3618 if( ap->sp->index==lemp->nsymbol ) continue;
3619 action = compute_action(lemp, ap);
3620 if( action<0 ) continue;
3621 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003622 }
drhfdbf9282003-10-21 16:34:41 +00003623 stp->iNtOfst = acttab_insert(pActtab);
3624 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3625 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003626 }
3627 }
drhfdbf9282003-10-21 16:34:41 +00003628 free(ax);
drh8b582012003-10-21 13:16:03 +00003629
3630 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003631 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003632 n = acttab_size(pActtab);
3633 for(i=j=0; i<n; i++){
3634 int action = acttab_yyaction(pActtab, i);
3635 if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003636 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003637 fprintf(out, " %4d,", action);
3638 if( j==9 || i==n-1 ){
3639 fprintf(out, "\n"); lineno++;
3640 j = 0;
3641 }else{
3642 j++;
3643 }
3644 }
3645 fprintf(out, "};\n"); lineno++;
3646
3647 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003648 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003649 for(i=j=0; i<n; i++){
3650 int la = acttab_yylookahead(pActtab, i);
3651 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003652 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003653 fprintf(out, " %4d,", la);
3654 if( j==9 || i==n-1 ){
3655 fprintf(out, "\n"); lineno++;
3656 j = 0;
3657 }else{
3658 j++;
3659 }
3660 }
3661 fprintf(out, "};\n"); lineno++;
3662
3663 /* Output the yy_shift_ofst[] table */
3664 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003665 n = lemp->nstate;
3666 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3667 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003668 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003669 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003670 for(i=j=0; i<n; i++){
3671 int ofst;
3672 stp = lemp->sorted[i];
3673 ofst = stp->iTknOfst;
3674 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003675 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003676 fprintf(out, " %4d,", ofst);
3677 if( j==9 || i==n-1 ){
3678 fprintf(out, "\n"); lineno++;
3679 j = 0;
3680 }else{
3681 j++;
3682 }
3683 }
3684 fprintf(out, "};\n"); lineno++;
3685
3686 /* Output the yy_reduce_ofst[] table */
3687 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003688 n = lemp->nstate;
3689 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3690 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003691 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003692 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003693 for(i=j=0; i<n; i++){
3694 int ofst;
3695 stp = lemp->sorted[i];
3696 ofst = stp->iNtOfst;
3697 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003698 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003699 fprintf(out, " %4d,", ofst);
3700 if( j==9 || i==n-1 ){
3701 fprintf(out, "\n"); lineno++;
3702 j = 0;
3703 }else{
3704 j++;
3705 }
3706 }
3707 fprintf(out, "};\n"); lineno++;
3708
3709 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003710 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003711 n = lemp->nstate;
3712 for(i=j=0; i<n; i++){
3713 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003714 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003715 fprintf(out, " %4d,", stp->iDflt);
3716 if( j==9 || i==n-1 ){
3717 fprintf(out, "\n"); lineno++;
3718 j = 0;
3719 }else{
3720 j++;
3721 }
3722 }
3723 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003724 tplt_xfer(lemp->name,in,out,&lineno);
3725
drh0bd1f4e2002-06-06 18:54:39 +00003726 /* Generate the table of fallback tokens.
3727 */
3728 if( lemp->has_fallback ){
3729 for(i=0; i<lemp->nterminal; i++){
3730 struct symbol *p = lemp->symbols[i];
3731 if( p->fallback==0 ){
3732 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3733 }else{
3734 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3735 p->name, p->fallback->name);
3736 }
3737 lineno++;
3738 }
3739 }
3740 tplt_xfer(lemp->name, in, out, &lineno);
3741
3742 /* Generate a table containing the symbolic name of every symbol
3743 */
drh75897232000-05-29 14:26:00 +00003744 for(i=0; i<lemp->nsymbol; i++){
3745 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3746 fprintf(out," %-15s",line);
3747 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3748 }
3749 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3750 tplt_xfer(lemp->name,in,out,&lineno);
3751
drh0bd1f4e2002-06-06 18:54:39 +00003752 /* Generate a table containing a text string that describes every
3753 ** rule in the rule set of the grammer. This information is used
3754 ** when tracing REDUCE actions.
3755 */
3756 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3757 assert( rp->index==i );
3758 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00003759 for(j=0; j<rp->nrhs; j++){
3760 struct symbol *sp = rp->rhs[j];
3761 fprintf(out," %s", sp->name);
3762 if( sp->type==MULTITERMINAL ){
3763 int k;
3764 for(k=1; k<sp->nsubsym; k++){
3765 fprintf(out,"|%s",sp->subsym[k]->name);
3766 }
3767 }
3768 }
drh0bd1f4e2002-06-06 18:54:39 +00003769 fprintf(out,"\",\n"); lineno++;
3770 }
3771 tplt_xfer(lemp->name,in,out,&lineno);
3772
drh75897232000-05-29 14:26:00 +00003773 /* Generate code which executes every time a symbol is popped from
3774 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003775 ** (In other words, generate the %destructor actions)
3776 */
drh75897232000-05-29 14:26:00 +00003777 if( lemp->tokendest ){
3778 for(i=0; i<lemp->nsymbol; i++){
3779 struct symbol *sp = lemp->symbols[i];
3780 if( sp==0 || sp->type!=TERMINAL ) continue;
3781 fprintf(out," case %d:\n",sp->index); lineno++;
3782 }
3783 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3784 if( i<lemp->nsymbol ){
3785 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3786 fprintf(out," break;\n"); lineno++;
3787 }
3788 }
drh8d659732005-01-13 23:54:06 +00003789 if( lemp->vardest ){
3790 struct symbol *dflt_sp = 0;
3791 for(i=0; i<lemp->nsymbol; i++){
3792 struct symbol *sp = lemp->symbols[i];
3793 if( sp==0 || sp->type==TERMINAL ||
3794 sp->index<=0 || sp->destructor!=0 ) continue;
3795 fprintf(out," case %d:\n",sp->index); lineno++;
3796 dflt_sp = sp;
3797 }
3798 if( dflt_sp!=0 ){
3799 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3800 fprintf(out," break;\n"); lineno++;
3801 }
3802 }
drh75897232000-05-29 14:26:00 +00003803 for(i=0; i<lemp->nsymbol; i++){
3804 struct symbol *sp = lemp->symbols[i];
3805 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3806 fprintf(out," case %d:\n",sp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003807
3808 /* Combine duplicate destructors into a single case */
3809 for(j=i+1; j<lemp->nsymbol; j++){
3810 struct symbol *sp2 = lemp->symbols[j];
3811 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3812 && sp2->dtnum==sp->dtnum
3813 && strcmp(sp->destructor,sp2->destructor)==0 ){
3814 fprintf(out," case %d:\n",sp2->index); lineno++;
3815 sp2->destructor = 0;
3816 }
3817 }
3818
drh75897232000-05-29 14:26:00 +00003819 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3820 fprintf(out," break;\n"); lineno++;
3821 }
drh75897232000-05-29 14:26:00 +00003822 tplt_xfer(lemp->name,in,out,&lineno);
3823
3824 /* Generate code which executes whenever the parser stack overflows */
3825 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3826 tplt_xfer(lemp->name,in,out,&lineno);
3827
3828 /* Generate the table of rule information
3829 **
3830 ** Note: This code depends on the fact that rules are number
3831 ** sequentually beginning with 0.
3832 */
3833 for(rp=lemp->rule; rp; rp=rp->next){
3834 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3835 }
3836 tplt_xfer(lemp->name,in,out,&lineno);
3837
3838 /* Generate code which execution during each REDUCE action */
3839 for(rp=lemp->rule; rp; rp=rp->next){
drh0bb132b2004-07-20 14:06:51 +00003840 if( rp->code ) translate_code(lemp, rp);
3841 }
3842 for(rp=lemp->rule; rp; rp=rp->next){
3843 struct rule *rp2;
3844 if( rp->code==0 ) continue;
drh75897232000-05-29 14:26:00 +00003845 fprintf(out," case %d:\n",rp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003846 for(rp2=rp->next; rp2; rp2=rp2->next){
3847 if( rp2->code==rp->code ){
3848 fprintf(out," case %d:\n",rp2->index); lineno++;
3849 rp2->code = 0;
3850 }
3851 }
drh75897232000-05-29 14:26:00 +00003852 emit_code(out,rp,lemp,&lineno);
3853 fprintf(out," break;\n"); lineno++;
3854 }
3855 tplt_xfer(lemp->name,in,out,&lineno);
3856
3857 /* Generate code which executes if a parse fails */
3858 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3859 tplt_xfer(lemp->name,in,out,&lineno);
3860
3861 /* Generate code which executes when a syntax error occurs */
3862 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3863 tplt_xfer(lemp->name,in,out,&lineno);
3864
3865 /* Generate code which executes when the parser accepts its input */
3866 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3867 tplt_xfer(lemp->name,in,out,&lineno);
3868
3869 /* Append any addition code the user desires */
3870 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3871
3872 fclose(in);
3873 fclose(out);
3874 return;
3875}
3876
3877/* Generate a header file for the parser */
3878void ReportHeader(lemp)
3879struct lemon *lemp;
3880{
3881 FILE *out, *in;
3882 char *prefix;
3883 char line[LINESIZE];
3884 char pattern[LINESIZE];
3885 int i;
3886
3887 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3888 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003889 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003890 if( in ){
3891 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3892 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3893 if( strcmp(line,pattern) ) break;
3894 }
3895 fclose(in);
3896 if( i==lemp->nterminal ){
3897 /* No change in the file. Don't rewrite it. */
3898 return;
3899 }
3900 }
drh2aa6ca42004-09-10 00:14:04 +00003901 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003902 if( out ){
3903 for(i=1; i<lemp->nterminal; i++){
3904 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3905 }
3906 fclose(out);
3907 }
3908 return;
3909}
3910
3911/* Reduce the size of the action tables, if possible, by making use
3912** of defaults.
3913**
drhb59499c2002-02-23 18:45:13 +00003914** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00003915** it the default. Except, there is no default if the wildcard token
3916** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00003917*/
3918void CompressTables(lemp)
3919struct lemon *lemp;
3920{
3921 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003922 struct action *ap, *ap2;
3923 struct rule *rp, *rp2, *rbest;
3924 int nbest, n;
drh75897232000-05-29 14:26:00 +00003925 int i;
drhe09daa92006-06-10 13:29:31 +00003926 int usesWildcard;
drh75897232000-05-29 14:26:00 +00003927
3928 for(i=0; i<lemp->nstate; i++){
3929 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003930 nbest = 0;
3931 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00003932 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00003933
drhb59499c2002-02-23 18:45:13 +00003934 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00003935 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
3936 usesWildcard = 1;
3937 }
drhb59499c2002-02-23 18:45:13 +00003938 if( ap->type!=REDUCE ) continue;
3939 rp = ap->x.rp;
3940 if( rp==rbest ) continue;
3941 n = 1;
3942 for(ap2=ap->next; ap2; ap2=ap2->next){
3943 if( ap2->type!=REDUCE ) continue;
3944 rp2 = ap2->x.rp;
3945 if( rp2==rbest ) continue;
3946 if( rp2==rp ) n++;
3947 }
3948 if( n>nbest ){
3949 nbest = n;
3950 rbest = rp;
drh75897232000-05-29 14:26:00 +00003951 }
3952 }
drhb59499c2002-02-23 18:45:13 +00003953
3954 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00003955 ** is not at least 1 or if the wildcard token is a possible
3956 ** lookahead.
3957 */
3958 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00003959
drhb59499c2002-02-23 18:45:13 +00003960
3961 /* Combine matching REDUCE actions into a single default */
3962 for(ap=stp->ap; ap; ap=ap->next){
3963 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3964 }
drh75897232000-05-29 14:26:00 +00003965 assert( ap );
3966 ap->sp = Symbol_new("{default}");
3967 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003968 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003969 }
3970 stp->ap = Action_sort(stp->ap);
3971 }
3972}
drhb59499c2002-02-23 18:45:13 +00003973
drhada354d2005-11-05 15:03:59 +00003974
3975/*
3976** Compare two states for sorting purposes. The smaller state is the
3977** one with the most non-terminal actions. If they have the same number
3978** of non-terminal actions, then the smaller is the one with the most
3979** token actions.
3980*/
3981static int stateResortCompare(const void *a, const void *b){
3982 const struct state *pA = *(const struct state**)a;
3983 const struct state *pB = *(const struct state**)b;
3984 int n;
3985
3986 n = pB->nNtAct - pA->nNtAct;
3987 if( n==0 ){
3988 n = pB->nTknAct - pA->nTknAct;
3989 }
3990 return n;
3991}
3992
3993
3994/*
3995** Renumber and resort states so that states with fewer choices
3996** occur at the end. Except, keep state 0 as the first state.
3997*/
3998void ResortStates(lemp)
3999struct lemon *lemp;
4000{
4001 int i;
4002 struct state *stp;
4003 struct action *ap;
4004
4005 for(i=0; i<lemp->nstate; i++){
4006 stp = lemp->sorted[i];
4007 stp->nTknAct = stp->nNtAct = 0;
4008 stp->iDflt = lemp->nstate + lemp->nrule;
4009 stp->iTknOfst = NO_OFFSET;
4010 stp->iNtOfst = NO_OFFSET;
4011 for(ap=stp->ap; ap; ap=ap->next){
4012 if( compute_action(lemp,ap)>=0 ){
4013 if( ap->sp->index<lemp->nterminal ){
4014 stp->nTknAct++;
4015 }else if( ap->sp->index<lemp->nsymbol ){
4016 stp->nNtAct++;
4017 }else{
4018 stp->iDflt = compute_action(lemp, ap);
4019 }
4020 }
4021 }
4022 }
4023 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4024 stateResortCompare);
4025 for(i=0; i<lemp->nstate; i++){
4026 lemp->sorted[i]->statenum = i;
4027 }
4028}
4029
4030
drh75897232000-05-29 14:26:00 +00004031/***************** From the file "set.c" ************************************/
4032/*
4033** Set manipulation routines for the LEMON parser generator.
4034*/
4035
4036static int size = 0;
4037
4038/* Set the set size */
4039void SetSize(n)
4040int n;
4041{
4042 size = n+1;
4043}
4044
4045/* Allocate a new set */
4046char *SetNew(){
4047 char *s;
4048 int i;
4049 s = (char*)malloc( size );
4050 if( s==0 ){
4051 extern void memory_error();
4052 memory_error();
4053 }
4054 for(i=0; i<size; i++) s[i] = 0;
4055 return s;
4056}
4057
4058/* Deallocate a set */
4059void SetFree(s)
4060char *s;
4061{
4062 free(s);
4063}
4064
4065/* Add a new element to the set. Return TRUE if the element was added
4066** and FALSE if it was already there. */
4067int SetAdd(s,e)
4068char *s;
4069int e;
4070{
4071 int rv;
4072 rv = s[e];
4073 s[e] = 1;
4074 return !rv;
4075}
4076
4077/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4078int SetUnion(s1,s2)
4079char *s1;
4080char *s2;
4081{
4082 int i, progress;
4083 progress = 0;
4084 for(i=0; i<size; i++){
4085 if( s2[i]==0 ) continue;
4086 if( s1[i]==0 ){
4087 progress = 1;
4088 s1[i] = 1;
4089 }
4090 }
4091 return progress;
4092}
4093/********************** From the file "table.c" ****************************/
4094/*
4095** All code in this file has been automatically generated
4096** from a specification in the file
4097** "table.q"
4098** by the associative array code building program "aagen".
4099** Do not edit this file! Instead, edit the specification
4100** file, then rerun aagen.
4101*/
4102/*
4103** Code for processing tables in the LEMON parser generator.
4104*/
4105
4106PRIVATE int strhash(x)
4107char *x;
4108{
4109 int h = 0;
4110 while( *x) h = h*13 + *(x++);
4111 return h;
4112}
4113
4114/* Works like strdup, sort of. Save a string in malloced memory, but
4115** keep strings in a table so that the same string is not in more
4116** than one place.
4117*/
4118char *Strsafe(y)
4119char *y;
4120{
4121 char *z;
4122
4123 z = Strsafe_find(y);
4124 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4125 strcpy(z,y);
4126 Strsafe_insert(z);
4127 }
4128 MemoryCheck(z);
4129 return z;
4130}
4131
4132/* There is one instance of the following structure for each
4133** associative array of type "x1".
4134*/
4135struct s_x1 {
4136 int size; /* The number of available slots. */
4137 /* Must be a power of 2 greater than or */
4138 /* equal to 1 */
4139 int count; /* Number of currently slots filled */
4140 struct s_x1node *tbl; /* The data stored here */
4141 struct s_x1node **ht; /* Hash table for lookups */
4142};
4143
4144/* There is one instance of this structure for every data element
4145** in an associative array of type "x1".
4146*/
4147typedef struct s_x1node {
4148 char *data; /* The data */
4149 struct s_x1node *next; /* Next entry with the same hash */
4150 struct s_x1node **from; /* Previous link */
4151} x1node;
4152
4153/* There is only one instance of the array, which is the following */
4154static struct s_x1 *x1a;
4155
4156/* Allocate a new associative array */
4157void Strsafe_init(){
4158 if( x1a ) return;
4159 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4160 if( x1a ){
4161 x1a->size = 1024;
4162 x1a->count = 0;
4163 x1a->tbl = (x1node*)malloc(
4164 (sizeof(x1node) + sizeof(x1node*))*1024 );
4165 if( x1a->tbl==0 ){
4166 free(x1a);
4167 x1a = 0;
4168 }else{
4169 int i;
4170 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4171 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4172 }
4173 }
4174}
4175/* Insert a new record into the array. Return TRUE if successful.
4176** Prior data with the same key is NOT overwritten */
4177int Strsafe_insert(data)
4178char *data;
4179{
4180 x1node *np;
4181 int h;
4182 int ph;
4183
4184 if( x1a==0 ) return 0;
4185 ph = strhash(data);
4186 h = ph & (x1a->size-1);
4187 np = x1a->ht[h];
4188 while( np ){
4189 if( strcmp(np->data,data)==0 ){
4190 /* An existing entry with the same key is found. */
4191 /* Fail because overwrite is not allows. */
4192 return 0;
4193 }
4194 np = np->next;
4195 }
4196 if( x1a->count>=x1a->size ){
4197 /* Need to make the hash table bigger */
4198 int i,size;
4199 struct s_x1 array;
4200 array.size = size = x1a->size*2;
4201 array.count = x1a->count;
4202 array.tbl = (x1node*)malloc(
4203 (sizeof(x1node) + sizeof(x1node*))*size );
4204 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4205 array.ht = (x1node**)&(array.tbl[size]);
4206 for(i=0; i<size; i++) array.ht[i] = 0;
4207 for(i=0; i<x1a->count; i++){
4208 x1node *oldnp, *newnp;
4209 oldnp = &(x1a->tbl[i]);
4210 h = strhash(oldnp->data) & (size-1);
4211 newnp = &(array.tbl[i]);
4212 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4213 newnp->next = array.ht[h];
4214 newnp->data = oldnp->data;
4215 newnp->from = &(array.ht[h]);
4216 array.ht[h] = newnp;
4217 }
4218 free(x1a->tbl);
4219 *x1a = array;
4220 }
4221 /* Insert the new data */
4222 h = ph & (x1a->size-1);
4223 np = &(x1a->tbl[x1a->count++]);
4224 np->data = data;
4225 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4226 np->next = x1a->ht[h];
4227 x1a->ht[h] = np;
4228 np->from = &(x1a->ht[h]);
4229 return 1;
4230}
4231
4232/* Return a pointer to data assigned to the given key. Return NULL
4233** if no such key. */
4234char *Strsafe_find(key)
4235char *key;
4236{
4237 int h;
4238 x1node *np;
4239
4240 if( x1a==0 ) return 0;
4241 h = strhash(key) & (x1a->size-1);
4242 np = x1a->ht[h];
4243 while( np ){
4244 if( strcmp(np->data,key)==0 ) break;
4245 np = np->next;
4246 }
4247 return np ? np->data : 0;
4248}
4249
4250/* Return a pointer to the (terminal or nonterminal) symbol "x".
4251** Create a new symbol if this is the first time "x" has been seen.
4252*/
4253struct symbol *Symbol_new(x)
4254char *x;
4255{
4256 struct symbol *sp;
4257
4258 sp = Symbol_find(x);
4259 if( sp==0 ){
4260 sp = (struct symbol *)malloc( sizeof(struct symbol) );
4261 MemoryCheck(sp);
4262 sp->name = Strsafe(x);
4263 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4264 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004265 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004266 sp->prec = -1;
4267 sp->assoc = UNK;
4268 sp->firstset = 0;
drhb27b83a2002-08-14 23:18:57 +00004269 sp->lambda = B_FALSE;
drh75897232000-05-29 14:26:00 +00004270 sp->destructor = 0;
4271 sp->datatype = 0;
4272 Symbol_insert(sp,sp->name);
4273 }
4274 return sp;
4275}
4276
drh60d31652004-02-22 00:08:04 +00004277/* Compare two symbols for working purposes
4278**
4279** Symbols that begin with upper case letters (terminals or tokens)
4280** must sort before symbols that begin with lower case letters
4281** (non-terminals). Other than that, the order does not matter.
4282**
4283** We find experimentally that leaving the symbols in their original
4284** order (the order they appeared in the grammar file) gives the
4285** smallest parser tables in SQLite.
4286*/
4287int Symbolcmpp(struct symbol **a, struct symbol **b){
4288 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4289 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4290 return i1-i2;
drh75897232000-05-29 14:26:00 +00004291}
4292
4293/* There is one instance of the following structure for each
4294** associative array of type "x2".
4295*/
4296struct s_x2 {
4297 int size; /* The number of available slots. */
4298 /* Must be a power of 2 greater than or */
4299 /* equal to 1 */
4300 int count; /* Number of currently slots filled */
4301 struct s_x2node *tbl; /* The data stored here */
4302 struct s_x2node **ht; /* Hash table for lookups */
4303};
4304
4305/* There is one instance of this structure for every data element
4306** in an associative array of type "x2".
4307*/
4308typedef struct s_x2node {
4309 struct symbol *data; /* The data */
4310 char *key; /* The key */
4311 struct s_x2node *next; /* Next entry with the same hash */
4312 struct s_x2node **from; /* Previous link */
4313} x2node;
4314
4315/* There is only one instance of the array, which is the following */
4316static struct s_x2 *x2a;
4317
4318/* Allocate a new associative array */
4319void Symbol_init(){
4320 if( x2a ) return;
4321 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4322 if( x2a ){
4323 x2a->size = 128;
4324 x2a->count = 0;
4325 x2a->tbl = (x2node*)malloc(
4326 (sizeof(x2node) + sizeof(x2node*))*128 );
4327 if( x2a->tbl==0 ){
4328 free(x2a);
4329 x2a = 0;
4330 }else{
4331 int i;
4332 x2a->ht = (x2node**)&(x2a->tbl[128]);
4333 for(i=0; i<128; i++) x2a->ht[i] = 0;
4334 }
4335 }
4336}
4337/* Insert a new record into the array. Return TRUE if successful.
4338** Prior data with the same key is NOT overwritten */
4339int Symbol_insert(data,key)
4340struct symbol *data;
4341char *key;
4342{
4343 x2node *np;
4344 int h;
4345 int ph;
4346
4347 if( x2a==0 ) return 0;
4348 ph = strhash(key);
4349 h = ph & (x2a->size-1);
4350 np = x2a->ht[h];
4351 while( np ){
4352 if( strcmp(np->key,key)==0 ){
4353 /* An existing entry with the same key is found. */
4354 /* Fail because overwrite is not allows. */
4355 return 0;
4356 }
4357 np = np->next;
4358 }
4359 if( x2a->count>=x2a->size ){
4360 /* Need to make the hash table bigger */
4361 int i,size;
4362 struct s_x2 array;
4363 array.size = size = x2a->size*2;
4364 array.count = x2a->count;
4365 array.tbl = (x2node*)malloc(
4366 (sizeof(x2node) + sizeof(x2node*))*size );
4367 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4368 array.ht = (x2node**)&(array.tbl[size]);
4369 for(i=0; i<size; i++) array.ht[i] = 0;
4370 for(i=0; i<x2a->count; i++){
4371 x2node *oldnp, *newnp;
4372 oldnp = &(x2a->tbl[i]);
4373 h = strhash(oldnp->key) & (size-1);
4374 newnp = &(array.tbl[i]);
4375 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4376 newnp->next = array.ht[h];
4377 newnp->key = oldnp->key;
4378 newnp->data = oldnp->data;
4379 newnp->from = &(array.ht[h]);
4380 array.ht[h] = newnp;
4381 }
4382 free(x2a->tbl);
4383 *x2a = array;
4384 }
4385 /* Insert the new data */
4386 h = ph & (x2a->size-1);
4387 np = &(x2a->tbl[x2a->count++]);
4388 np->key = key;
4389 np->data = data;
4390 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4391 np->next = x2a->ht[h];
4392 x2a->ht[h] = np;
4393 np->from = &(x2a->ht[h]);
4394 return 1;
4395}
4396
4397/* Return a pointer to data assigned to the given key. Return NULL
4398** if no such key. */
4399struct symbol *Symbol_find(key)
4400char *key;
4401{
4402 int h;
4403 x2node *np;
4404
4405 if( x2a==0 ) return 0;
4406 h = strhash(key) & (x2a->size-1);
4407 np = x2a->ht[h];
4408 while( np ){
4409 if( strcmp(np->key,key)==0 ) break;
4410 np = np->next;
4411 }
4412 return np ? np->data : 0;
4413}
4414
4415/* Return the n-th data. Return NULL if n is out of range. */
4416struct symbol *Symbol_Nth(n)
4417int n;
4418{
4419 struct symbol *data;
4420 if( x2a && n>0 && n<=x2a->count ){
4421 data = x2a->tbl[n-1].data;
4422 }else{
4423 data = 0;
4424 }
4425 return data;
4426}
4427
4428/* Return the size of the array */
4429int Symbol_count()
4430{
4431 return x2a ? x2a->count : 0;
4432}
4433
4434/* Return an array of pointers to all data in the table.
4435** The array is obtained from malloc. Return NULL if memory allocation
4436** problems, or if the array is empty. */
4437struct symbol **Symbol_arrayof()
4438{
4439 struct symbol **array;
4440 int i,size;
4441 if( x2a==0 ) return 0;
4442 size = x2a->count;
4443 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4444 if( array ){
4445 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4446 }
4447 return array;
4448}
4449
4450/* Compare two configurations */
4451int Configcmp(a,b)
4452struct config *a;
4453struct config *b;
4454{
4455 int x;
4456 x = a->rp->index - b->rp->index;
4457 if( x==0 ) x = a->dot - b->dot;
4458 return x;
4459}
4460
4461/* Compare two states */
4462PRIVATE int statecmp(a,b)
4463struct config *a;
4464struct config *b;
4465{
4466 int rc;
4467 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4468 rc = a->rp->index - b->rp->index;
4469 if( rc==0 ) rc = a->dot - b->dot;
4470 }
4471 if( rc==0 ){
4472 if( a ) rc = 1;
4473 if( b ) rc = -1;
4474 }
4475 return rc;
4476}
4477
4478/* Hash a state */
4479PRIVATE int statehash(a)
4480struct config *a;
4481{
4482 int h=0;
4483 while( a ){
4484 h = h*571 + a->rp->index*37 + a->dot;
4485 a = a->bp;
4486 }
4487 return h;
4488}
4489
4490/* Allocate a new state structure */
4491struct state *State_new()
4492{
4493 struct state *new;
4494 new = (struct state *)malloc( sizeof(struct state) );
4495 MemoryCheck(new);
4496 return new;
4497}
4498
4499/* There is one instance of the following structure for each
4500** associative array of type "x3".
4501*/
4502struct s_x3 {
4503 int size; /* The number of available slots. */
4504 /* Must be a power of 2 greater than or */
4505 /* equal to 1 */
4506 int count; /* Number of currently slots filled */
4507 struct s_x3node *tbl; /* The data stored here */
4508 struct s_x3node **ht; /* Hash table for lookups */
4509};
4510
4511/* There is one instance of this structure for every data element
4512** in an associative array of type "x3".
4513*/
4514typedef struct s_x3node {
4515 struct state *data; /* The data */
4516 struct config *key; /* The key */
4517 struct s_x3node *next; /* Next entry with the same hash */
4518 struct s_x3node **from; /* Previous link */
4519} x3node;
4520
4521/* There is only one instance of the array, which is the following */
4522static struct s_x3 *x3a;
4523
4524/* Allocate a new associative array */
4525void State_init(){
4526 if( x3a ) return;
4527 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4528 if( x3a ){
4529 x3a->size = 128;
4530 x3a->count = 0;
4531 x3a->tbl = (x3node*)malloc(
4532 (sizeof(x3node) + sizeof(x3node*))*128 );
4533 if( x3a->tbl==0 ){
4534 free(x3a);
4535 x3a = 0;
4536 }else{
4537 int i;
4538 x3a->ht = (x3node**)&(x3a->tbl[128]);
4539 for(i=0; i<128; i++) x3a->ht[i] = 0;
4540 }
4541 }
4542}
4543/* Insert a new record into the array. Return TRUE if successful.
4544** Prior data with the same key is NOT overwritten */
4545int State_insert(data,key)
4546struct state *data;
4547struct config *key;
4548{
4549 x3node *np;
4550 int h;
4551 int ph;
4552
4553 if( x3a==0 ) return 0;
4554 ph = statehash(key);
4555 h = ph & (x3a->size-1);
4556 np = x3a->ht[h];
4557 while( np ){
4558 if( statecmp(np->key,key)==0 ){
4559 /* An existing entry with the same key is found. */
4560 /* Fail because overwrite is not allows. */
4561 return 0;
4562 }
4563 np = np->next;
4564 }
4565 if( x3a->count>=x3a->size ){
4566 /* Need to make the hash table bigger */
4567 int i,size;
4568 struct s_x3 array;
4569 array.size = size = x3a->size*2;
4570 array.count = x3a->count;
4571 array.tbl = (x3node*)malloc(
4572 (sizeof(x3node) + sizeof(x3node*))*size );
4573 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4574 array.ht = (x3node**)&(array.tbl[size]);
4575 for(i=0; i<size; i++) array.ht[i] = 0;
4576 for(i=0; i<x3a->count; i++){
4577 x3node *oldnp, *newnp;
4578 oldnp = &(x3a->tbl[i]);
4579 h = statehash(oldnp->key) & (size-1);
4580 newnp = &(array.tbl[i]);
4581 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4582 newnp->next = array.ht[h];
4583 newnp->key = oldnp->key;
4584 newnp->data = oldnp->data;
4585 newnp->from = &(array.ht[h]);
4586 array.ht[h] = newnp;
4587 }
4588 free(x3a->tbl);
4589 *x3a = array;
4590 }
4591 /* Insert the new data */
4592 h = ph & (x3a->size-1);
4593 np = &(x3a->tbl[x3a->count++]);
4594 np->key = key;
4595 np->data = data;
4596 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4597 np->next = x3a->ht[h];
4598 x3a->ht[h] = np;
4599 np->from = &(x3a->ht[h]);
4600 return 1;
4601}
4602
4603/* Return a pointer to data assigned to the given key. Return NULL
4604** if no such key. */
4605struct state *State_find(key)
4606struct config *key;
4607{
4608 int h;
4609 x3node *np;
4610
4611 if( x3a==0 ) return 0;
4612 h = statehash(key) & (x3a->size-1);
4613 np = x3a->ht[h];
4614 while( np ){
4615 if( statecmp(np->key,key)==0 ) break;
4616 np = np->next;
4617 }
4618 return np ? np->data : 0;
4619}
4620
4621/* Return an array of pointers to all data in the table.
4622** The array is obtained from malloc. Return NULL if memory allocation
4623** problems, or if the array is empty. */
4624struct state **State_arrayof()
4625{
4626 struct state **array;
4627 int i,size;
4628 if( x3a==0 ) return 0;
4629 size = x3a->count;
4630 array = (struct state **)malloc( sizeof(struct state *)*size );
4631 if( array ){
4632 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4633 }
4634 return array;
4635}
4636
4637/* Hash a configuration */
4638PRIVATE int confighash(a)
4639struct config *a;
4640{
4641 int h=0;
4642 h = h*571 + a->rp->index*37 + a->dot;
4643 return h;
4644}
4645
4646/* There is one instance of the following structure for each
4647** associative array of type "x4".
4648*/
4649struct s_x4 {
4650 int size; /* The number of available slots. */
4651 /* Must be a power of 2 greater than or */
4652 /* equal to 1 */
4653 int count; /* Number of currently slots filled */
4654 struct s_x4node *tbl; /* The data stored here */
4655 struct s_x4node **ht; /* Hash table for lookups */
4656};
4657
4658/* There is one instance of this structure for every data element
4659** in an associative array of type "x4".
4660*/
4661typedef struct s_x4node {
4662 struct config *data; /* The data */
4663 struct s_x4node *next; /* Next entry with the same hash */
4664 struct s_x4node **from; /* Previous link */
4665} x4node;
4666
4667/* There is only one instance of the array, which is the following */
4668static struct s_x4 *x4a;
4669
4670/* Allocate a new associative array */
4671void Configtable_init(){
4672 if( x4a ) return;
4673 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4674 if( x4a ){
4675 x4a->size = 64;
4676 x4a->count = 0;
4677 x4a->tbl = (x4node*)malloc(
4678 (sizeof(x4node) + sizeof(x4node*))*64 );
4679 if( x4a->tbl==0 ){
4680 free(x4a);
4681 x4a = 0;
4682 }else{
4683 int i;
4684 x4a->ht = (x4node**)&(x4a->tbl[64]);
4685 for(i=0; i<64; i++) x4a->ht[i] = 0;
4686 }
4687 }
4688}
4689/* Insert a new record into the array. Return TRUE if successful.
4690** Prior data with the same key is NOT overwritten */
4691int Configtable_insert(data)
4692struct config *data;
4693{
4694 x4node *np;
4695 int h;
4696 int ph;
4697
4698 if( x4a==0 ) return 0;
4699 ph = confighash(data);
4700 h = ph & (x4a->size-1);
4701 np = x4a->ht[h];
4702 while( np ){
4703 if( Configcmp(np->data,data)==0 ){
4704 /* An existing entry with the same key is found. */
4705 /* Fail because overwrite is not allows. */
4706 return 0;
4707 }
4708 np = np->next;
4709 }
4710 if( x4a->count>=x4a->size ){
4711 /* Need to make the hash table bigger */
4712 int i,size;
4713 struct s_x4 array;
4714 array.size = size = x4a->size*2;
4715 array.count = x4a->count;
4716 array.tbl = (x4node*)malloc(
4717 (sizeof(x4node) + sizeof(x4node*))*size );
4718 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4719 array.ht = (x4node**)&(array.tbl[size]);
4720 for(i=0; i<size; i++) array.ht[i] = 0;
4721 for(i=0; i<x4a->count; i++){
4722 x4node *oldnp, *newnp;
4723 oldnp = &(x4a->tbl[i]);
4724 h = confighash(oldnp->data) & (size-1);
4725 newnp = &(array.tbl[i]);
4726 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4727 newnp->next = array.ht[h];
4728 newnp->data = oldnp->data;
4729 newnp->from = &(array.ht[h]);
4730 array.ht[h] = newnp;
4731 }
4732 free(x4a->tbl);
4733 *x4a = array;
4734 }
4735 /* Insert the new data */
4736 h = ph & (x4a->size-1);
4737 np = &(x4a->tbl[x4a->count++]);
4738 np->data = data;
4739 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4740 np->next = x4a->ht[h];
4741 x4a->ht[h] = np;
4742 np->from = &(x4a->ht[h]);
4743 return 1;
4744}
4745
4746/* Return a pointer to data assigned to the given key. Return NULL
4747** if no such key. */
4748struct config *Configtable_find(key)
4749struct config *key;
4750{
4751 int h;
4752 x4node *np;
4753
4754 if( x4a==0 ) return 0;
4755 h = confighash(key) & (x4a->size-1);
4756 np = x4a->ht[h];
4757 while( np ){
4758 if( Configcmp(np->data,key)==0 ) break;
4759 np = np->next;
4760 }
4761 return np ? np->data : 0;
4762}
4763
4764/* Remove all data from the table. Pass each data to the function "f"
4765** as it is removed. ("f" may be null to avoid this step.) */
4766void Configtable_clear(f)
4767int(*f)(/* struct config * */);
4768{
4769 int i;
4770 if( x4a==0 || x4a->count==0 ) return;
4771 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4772 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4773 x4a->count = 0;
4774 return;
4775}