blob: 3bea77a9f26de4a66b055348200289e9d00d140d [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>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drh75897232000-05-29 14:26:00 +000016#ifndef __WIN32__
17# if defined(_WIN32) || defined(WIN32)
18# define __WIN32__
19# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
23extern int access();
24#else
25#include <unistd.h>
26#endif
27
drh75897232000-05-29 14:26:00 +000028/* #define PRIVATE static */
29#define PRIVATE
30
31#ifdef TEST
32#define MAXRHS 5 /* Set low to exercise exception code */
33#else
34#define MAXRHS 1000
35#endif
36
drhe9278182007-07-18 18:16:29 +000037static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000038
drhe9278182007-07-18 18:16:29 +000039static struct action *Action_new(void);
40static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000041
42/********** From the file "build.h" ************************************/
43void FindRulePrecedences();
44void FindFirstSets();
45void FindStates();
46void FindLinks();
47void FindFollowSets();
48void FindActions();
49
50/********* From the file "configlist.h" *********************************/
51void Configlist_init(/* void */);
52struct config *Configlist_add(/* struct rule *, int */);
53struct config *Configlist_addbasis(/* struct rule *, int */);
54void Configlist_closure(/* void */);
55void Configlist_sort(/* void */);
56void Configlist_sortbasis(/* void */);
57struct config *Configlist_return(/* void */);
58struct config *Configlist_basis(/* void */);
59void Configlist_eat(/* struct config * */);
60void Configlist_reset(/* void */);
61
62/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000063void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000064
65/****** From the file "option.h" ******************************************/
66struct s_options {
67 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
68 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
69 char *label;
70 char *arg;
71 char *message;
72};
drhb0c86772000-06-02 23:21:26 +000073int OptInit(/* char**,struct s_options*,FILE* */);
74int OptNArgs(/* void */);
75char *OptArg(/* int */);
76void OptErr(/* int */);
77void OptPrint(/* void */);
drh75897232000-05-29 14:26:00 +000078
79/******** From the file "parse.h" *****************************************/
80void Parse(/* struct lemon *lemp */);
81
82/********* From the file "plink.h" ***************************************/
83struct plink *Plink_new(/* void */);
84void Plink_add(/* struct plink **, struct config * */);
85void Plink_copy(/* struct plink **, struct plink * */);
86void Plink_delete(/* struct plink * */);
87
88/********** From the file "report.h" *************************************/
89void Reprint(/* struct lemon * */);
90void ReportOutput(/* struct lemon * */);
91void ReportTable(/* struct lemon * */);
92void ReportHeader(/* struct lemon * */);
93void CompressTables(/* struct lemon * */);
drhada354d2005-11-05 15:03:59 +000094void ResortStates(/* struct lemon * */);
drh75897232000-05-29 14:26:00 +000095
96/********** From the file "set.h" ****************************************/
97void SetSize(/* int N */); /* All sets will be of size N */
98char *SetNew(/* void */); /* A new set for element 0..N */
99void SetFree(/* char* */); /* Deallocate a set */
100
101int SetAdd(/* char*,int */); /* Add element to a set */
102int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
103
104#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
105
106/********** From the file "struct.h" *************************************/
107/*
108** Principal data structures for the LEMON parser generator.
109*/
110
drhaa9f1122007-08-23 02:50:56 +0000111typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000112
113/* Symbols (terminals and nonterminals) of the grammar are stored
114** in the following: */
115struct symbol {
116 char *name; /* Name of the symbol */
117 int index; /* Index number for this symbol */
118 enum {
119 TERMINAL,
drhfd405312005-11-06 04:06:59 +0000120 NONTERMINAL,
121 MULTITERMINAL
drh75897232000-05-29 14:26:00 +0000122 } type; /* Symbols are all either TERMINALS or NTs */
123 struct rule *rule; /* Linked list of rules of this (if an NT) */
drh0bd1f4e2002-06-06 18:54:39 +0000124 struct symbol *fallback; /* fallback token in case this token doesn't parse */
drh75897232000-05-29 14:26:00 +0000125 int prec; /* Precedence if defined (-1 otherwise) */
126 enum e_assoc {
127 LEFT,
128 RIGHT,
129 NONE,
130 UNK
131 } assoc; /* Associativity if predecence is defined */
132 char *firstset; /* First-set for all rules of this symbol */
133 Boolean lambda; /* True if NT and can generate an empty string */
134 char *destructor; /* Code which executes whenever this symbol is
135 ** popped from the stack during error processing */
136 int destructorln; /* Line number of destructor code */
137 char *datatype; /* The data type of information held by this
138 ** object. Only used if type==NONTERMINAL */
139 int dtnum; /* The data type number. In the parser, the value
140 ** stack is a union. The .yy%d element of this
141 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000142 /* The following fields are used by MULTITERMINALs only */
143 int nsubsym; /* Number of constituent symbols in the MULTI */
144 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000145};
146
147/* Each production rule in the grammar is stored in the following
148** structure. */
149struct rule {
150 struct symbol *lhs; /* Left-hand side of the rule */
151 char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000152 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000153 int ruleline; /* Line number for the rule */
154 int nrhs; /* Number of RHS symbols */
155 struct symbol **rhs; /* The RHS symbols */
156 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
157 int line; /* Line number at which code begins */
158 char *code; /* The code executed when this rule is reduced */
159 struct symbol *precsym; /* Precedence symbol for this rule */
160 int index; /* An index number for this rule */
161 Boolean canReduce; /* True if this rule is ever reduced */
162 struct rule *nextlhs; /* Next rule with the same LHS */
163 struct rule *next; /* Next rule in the global list */
164};
165
166/* A configuration is a production rule of the grammar together with
167** a mark (dot) showing how much of that rule has been processed so far.
168** Configurations also contain a follow-set which is a list of terminal
169** symbols which are allowed to immediately follow the end of the rule.
170** Every configuration is recorded as an instance of the following: */
171struct config {
172 struct rule *rp; /* The rule upon which the configuration is based */
173 int dot; /* The parse point */
174 char *fws; /* Follow-set for this configuration only */
175 struct plink *fplp; /* Follow-set forward propagation links */
176 struct plink *bplp; /* Follow-set backwards propagation links */
177 struct state *stp; /* Pointer to state which contains this */
178 enum {
179 COMPLETE, /* The status is used during followset and */
180 INCOMPLETE /* shift computations */
181 } status;
182 struct config *next; /* Next configuration in the state */
183 struct config *bp; /* The next basis configuration */
184};
185
186/* Every shift or reduce operation is stored as one of the following */
187struct action {
188 struct symbol *sp; /* The look-ahead symbol */
189 enum e_action {
190 SHIFT,
191 ACCEPT,
192 REDUCE,
193 ERROR,
194 CONFLICT, /* Was a reduce, but part of a conflict */
195 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
196 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
197 NOT_USED /* Deleted by compression */
198 } type;
199 union {
200 struct state *stp; /* The new state, if a shift */
201 struct rule *rp; /* The rule, if a reduce */
202 } x;
203 struct action *next; /* Next action for this state */
204 struct action *collide; /* Next action with the same hash */
205};
206
207/* Each state of the generated parser's finite state machine
208** is encoded as an instance of the following structure. */
209struct state {
210 struct config *bp; /* The basis configurations for this state */
211 struct config *cfp; /* All configurations in this set */
drhada354d2005-11-05 15:03:59 +0000212 int statenum; /* Sequencial number for this state */
drh75897232000-05-29 14:26:00 +0000213 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000214 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
215 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
216 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000217};
drh8b582012003-10-21 13:16:03 +0000218#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000219
220/* A followset propagation link indicates that the contents of one
221** configuration followset should be propagated to another whenever
222** the first changes. */
223struct plink {
224 struct config *cfp; /* The configuration to which linked */
225 struct plink *next; /* The next propagate link */
226};
227
228/* The state vector for the entire parser generator is recorded as
229** follows. (LEMON uses no global variables and makes little use of
230** static variables. Fields in the following structure can be thought
231** of as begin global variables in the program.) */
232struct lemon {
233 struct state **sorted; /* Table of states sorted by state number */
234 struct rule *rule; /* List of all rules */
235 int nstate; /* Number of states */
236 int nrule; /* Number of rules */
237 int nsymbol; /* Number of terminal and nonterminal symbols */
238 int nterminal; /* Number of terminal symbols */
239 struct symbol **symbols; /* Sorted array of pointers to symbols */
240 int errorcnt; /* Number of errors */
241 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000242 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000243 char *name; /* Name of the generated parser */
244 char *arg; /* Declaration of the 3th argument to parser */
245 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000246 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000247 char *start; /* Name of the start symbol for the grammar */
248 char *stacksize; /* Size of the parser stack */
249 char *include; /* Code to put at the start of the C file */
250 int includeln; /* Line number for start of include code */
251 char *error; /* Code to execute when an error is seen */
252 int errorln; /* Line number for start of error code */
253 char *overflow; /* Code to execute on a stack overflow */
254 int overflowln; /* Line number for start of overflow code */
255 char *failure; /* Code to execute on parser failure */
256 int failureln; /* Line number for start of failure code */
257 char *accept; /* Code to execute when the parser excepts */
258 int acceptln; /* Line number for the start of accept code */
259 char *extracode; /* Code appended to the generated file */
260 int extracodeln; /* Line number for the start of the extra code */
261 char *tokendest; /* Code to execute to destroy token data */
262 int tokendestln; /* Line number for token destroyer code */
drh960e8c62001-04-03 16:53:21 +0000263 char *vardest; /* Code for the default non-terminal destructor */
264 int vardestln; /* Line number for default non-term destructor code*/
drh75897232000-05-29 14:26:00 +0000265 char *filename; /* Name of the input file */
266 char *outname; /* Name of the current output file */
267 char *tokenprefix; /* A prefix added to token names in the .h file */
268 int nconflict; /* Number of parsing conflicts */
269 int tablesize; /* Size of the parse tables */
270 int basisflag; /* Print only basis configurations */
drh0bd1f4e2002-06-06 18:54:39 +0000271 int has_fallback; /* True if any %fallback is seen in the grammer */
drh75897232000-05-29 14:26:00 +0000272 char *argv0; /* Name of the program */
273};
274
275#define MemoryCheck(X) if((X)==0){ \
276 extern void memory_error(); \
277 memory_error(); \
278}
279
280/**************** From the file "table.h" *********************************/
281/*
282** All code in this file has been automatically generated
283** from a specification in the file
284** "table.q"
285** by the associative array code building program "aagen".
286** Do not edit this file! Instead, edit the specification
287** file, then rerun aagen.
288*/
289/*
290** Code for processing tables in the LEMON parser generator.
291*/
292
293/* Routines for handling a strings */
294
295char *Strsafe();
296
297void Strsafe_init(/* void */);
298int Strsafe_insert(/* char * */);
299char *Strsafe_find(/* char * */);
300
301/* Routines for handling symbols of the grammar */
302
303struct symbol *Symbol_new();
304int Symbolcmpp(/* struct symbol **, struct symbol ** */);
305void Symbol_init(/* void */);
306int Symbol_insert(/* struct symbol *, char * */);
307struct symbol *Symbol_find(/* char * */);
308struct symbol *Symbol_Nth(/* int */);
309int Symbol_count(/* */);
310struct symbol **Symbol_arrayof(/* */);
311
312/* Routines to manage the state table */
313
314int Configcmp(/* struct config *, struct config * */);
315struct state *State_new();
316void State_init(/* void */);
317int State_insert(/* struct state *, struct config * */);
318struct state *State_find(/* struct config * */);
319struct state **State_arrayof(/* */);
320
321/* Routines used for efficiency in Configlist_add */
322
323void Configtable_init(/* void */);
324int Configtable_insert(/* struct config * */);
325struct config *Configtable_find(/* struct config * */);
326void Configtable_clear(/* int(*)(struct config *) */);
327/****************** From the file "action.c" *******************************/
328/*
329** Routines processing parser actions in the LEMON parser generator.
330*/
331
332/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000333static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000334 static struct action *freelist = 0;
335 struct action *new;
336
337 if( freelist==0 ){
338 int i;
339 int amt = 100;
340 freelist = (struct action *)malloc( sizeof(struct action)*amt );
341 if( freelist==0 ){
342 fprintf(stderr,"Unable to allocate memory for a new parser action.");
343 exit(1);
344 }
345 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
346 freelist[amt-1].next = 0;
347 }
348 new = freelist;
349 freelist = freelist->next;
350 return new;
351}
352
drhe9278182007-07-18 18:16:29 +0000353/* Compare two actions for sorting purposes. Return negative, zero, or
354** positive if the first action is less than, equal to, or greater than
355** the first
356*/
357static int actioncmp(
358 struct action *ap1,
359 struct action *ap2
360){
drh75897232000-05-29 14:26:00 +0000361 int rc;
362 rc = ap1->sp->index - ap2->sp->index;
363 if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
364 if( rc==0 ){
drh75897232000-05-29 14:26:00 +0000365 rc = ap1->x.rp->index - ap2->x.rp->index;
366 }
367 return rc;
368}
369
370/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000371static struct action *Action_sort(
372 struct action *ap
373){
374 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
375 (int(*)(const char*,const char*))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 "build.c" *****************************/
562/*
563** Routines to construction the finite state machine for the LEMON
564** parser generator.
565*/
566
567/* Find a precedence symbol of every rule in the grammar.
568**
569** Those rules which have a precedence symbol coded in the input
570** grammar using the "[symbol]" construct will already have the
571** rp->precsym field filled. Other rules take as their precedence
572** symbol the first RHS symbol with a defined precedence. If there
573** are not RHS symbols with a defined precedence, the precedence
574** symbol field is left blank.
575*/
576void FindRulePrecedences(xp)
577struct lemon *xp;
578{
579 struct rule *rp;
580 for(rp=xp->rule; rp; rp=rp->next){
581 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000582 int i, j;
583 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
584 struct symbol *sp = rp->rhs[i];
585 if( sp->type==MULTITERMINAL ){
586 for(j=0; j<sp->nsubsym; j++){
587 if( sp->subsym[j]->prec>=0 ){
588 rp->precsym = sp->subsym[j];
589 break;
590 }
591 }
592 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000593 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000594 }
595 }
596 }
597 }
598 return;
599}
600
601/* Find all nonterminals which will generate the empty string.
602** Then go back and compute the first sets of every nonterminal.
603** The first set is the set of all terminal symbols which can begin
604** a string generated by that nonterminal.
605*/
606void FindFirstSets(lemp)
607struct lemon *lemp;
608{
drhfd405312005-11-06 04:06:59 +0000609 int i, j;
drh75897232000-05-29 14:26:00 +0000610 struct rule *rp;
611 int progress;
612
613 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000614 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000615 }
616 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
617 lemp->symbols[i]->firstset = SetNew();
618 }
619
620 /* First compute all lambdas */
621 do{
622 progress = 0;
623 for(rp=lemp->rule; rp; rp=rp->next){
624 if( rp->lhs->lambda ) continue;
625 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000626 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000627 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000628 }
629 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000630 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000631 progress = 1;
632 }
633 }
634 }while( progress );
635
636 /* Now compute all first sets */
637 do{
638 struct symbol *s1, *s2;
639 progress = 0;
640 for(rp=lemp->rule; rp; rp=rp->next){
641 s1 = rp->lhs;
642 for(i=0; i<rp->nrhs; i++){
643 s2 = rp->rhs[i];
644 if( s2->type==TERMINAL ){
645 progress += SetAdd(s1->firstset,s2->index);
646 break;
drhfd405312005-11-06 04:06:59 +0000647 }else if( s2->type==MULTITERMINAL ){
648 for(j=0; j<s2->nsubsym; j++){
649 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
650 }
651 break;
drh75897232000-05-29 14:26:00 +0000652 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000653 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000654 }else{
655 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000656 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000657 }
658 }
659 }
660 }while( progress );
661 return;
662}
663
664/* Compute all LR(0) states for the grammar. Links
665** are added to between some states so that the LR(1) follow sets
666** can be computed later.
667*/
668PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
669void FindStates(lemp)
670struct lemon *lemp;
671{
672 struct symbol *sp;
673 struct rule *rp;
674
675 Configlist_init();
676
677 /* Find the start symbol */
678 if( lemp->start ){
679 sp = Symbol_find(lemp->start);
680 if( sp==0 ){
681 ErrorMsg(lemp->filename,0,
682"The specified start symbol \"%s\" is not \
683in a nonterminal of the grammar. \"%s\" will be used as the start \
684symbol instead.",lemp->start,lemp->rule->lhs->name);
685 lemp->errorcnt++;
686 sp = lemp->rule->lhs;
687 }
688 }else{
689 sp = lemp->rule->lhs;
690 }
691
692 /* Make sure the start symbol doesn't occur on the right-hand side of
693 ** any rule. Report an error if it does. (YACC would generate a new
694 ** start symbol in this case.) */
695 for(rp=lemp->rule; rp; rp=rp->next){
696 int i;
697 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000698 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000699 ErrorMsg(lemp->filename,0,
700"The start symbol \"%s\" occurs on the \
701right-hand side of a rule. This will result in a parser which \
702does not work properly.",sp->name);
703 lemp->errorcnt++;
704 }
705 }
706 }
707
708 /* The basis configuration set for the first state
709 ** is all rules which have the start symbol as their
710 ** left-hand side */
711 for(rp=sp->rule; rp; rp=rp->nextlhs){
712 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000713 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000714 newcfp = Configlist_addbasis(rp,0);
715 SetAdd(newcfp->fws,0);
716 }
717
718 /* Compute the first state. All other states will be
719 ** computed automatically during the computation of the first one.
720 ** The returned pointer to the first state is not used. */
721 (void)getstate(lemp);
722 return;
723}
724
725/* Return a pointer to a state which is described by the configuration
726** list which has been built from calls to Configlist_add.
727*/
728PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
729PRIVATE struct state *getstate(lemp)
730struct lemon *lemp;
731{
732 struct config *cfp, *bp;
733 struct state *stp;
734
735 /* Extract the sorted basis of the new state. The basis was constructed
736 ** by prior calls to "Configlist_addbasis()". */
737 Configlist_sortbasis();
738 bp = Configlist_basis();
739
740 /* Get a state with the same basis */
741 stp = State_find(bp);
742 if( stp ){
743 /* A state with the same basis already exists! Copy all the follow-set
744 ** propagation links from the state under construction into the
745 ** preexisting state, then return a pointer to the preexisting state */
746 struct config *x, *y;
747 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
748 Plink_copy(&y->bplp,x->bplp);
749 Plink_delete(x->fplp);
750 x->fplp = x->bplp = 0;
751 }
752 cfp = Configlist_return();
753 Configlist_eat(cfp);
754 }else{
755 /* This really is a new state. Construct all the details */
756 Configlist_closure(lemp); /* Compute the configuration closure */
757 Configlist_sort(); /* Sort the configuration closure */
758 cfp = Configlist_return(); /* Get a pointer to the config list */
759 stp = State_new(); /* A new state structure */
760 MemoryCheck(stp);
761 stp->bp = bp; /* Remember the configuration basis */
762 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000763 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000764 stp->ap = 0; /* No actions, yet. */
765 State_insert(stp,stp->bp); /* Add to the state table */
766 buildshifts(lemp,stp); /* Recursively compute successor states */
767 }
768 return stp;
769}
770
drhfd405312005-11-06 04:06:59 +0000771/*
772** Return true if two symbols are the same.
773*/
774int same_symbol(a,b)
775struct symbol *a;
776struct symbol *b;
777{
778 int i;
779 if( a==b ) return 1;
780 if( a->type!=MULTITERMINAL ) return 0;
781 if( b->type!=MULTITERMINAL ) return 0;
782 if( a->nsubsym!=b->nsubsym ) return 0;
783 for(i=0; i<a->nsubsym; i++){
784 if( a->subsym[i]!=b->subsym[i] ) return 0;
785 }
786 return 1;
787}
788
drh75897232000-05-29 14:26:00 +0000789/* Construct all successor states to the given state. A "successor"
790** state is any state which can be reached by a shift action.
791*/
792PRIVATE void buildshifts(lemp,stp)
793struct lemon *lemp;
794struct state *stp; /* The state from which successors are computed */
795{
796 struct config *cfp; /* For looping thru the config closure of "stp" */
797 struct config *bcfp; /* For the inner loop on config closure of "stp" */
798 struct config *new; /* */
799 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
800 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
801 struct state *newstp; /* A pointer to a successor state */
802
803 /* Each configuration becomes complete after it contibutes to a successor
804 ** state. Initially, all configurations are incomplete */
805 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
806
807 /* Loop through all configurations of the state "stp" */
808 for(cfp=stp->cfp; cfp; cfp=cfp->next){
809 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
810 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
811 Configlist_reset(); /* Reset the new config set */
812 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
813
814 /* For every configuration in the state "stp" which has the symbol "sp"
815 ** following its dot, add the same configuration to the basis set under
816 ** construction but with the dot shifted one symbol to the right. */
817 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
818 if( bcfp->status==COMPLETE ) continue; /* Already used */
819 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
820 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000821 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000822 bcfp->status = COMPLETE; /* Mark this config as used */
823 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
824 Plink_add(&new->bplp,bcfp);
825 }
826
827 /* Get a pointer to the state described by the basis configuration set
828 ** constructed in the preceding loop */
829 newstp = getstate(lemp);
830
831 /* The state "newstp" is reached from the state "stp" by a shift action
832 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000833 if( sp->type==MULTITERMINAL ){
834 int i;
835 for(i=0; i<sp->nsubsym; i++){
836 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
837 }
838 }else{
839 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
840 }
drh75897232000-05-29 14:26:00 +0000841 }
842}
843
844/*
845** Construct the propagation links
846*/
847void FindLinks(lemp)
848struct lemon *lemp;
849{
850 int i;
851 struct config *cfp, *other;
852 struct state *stp;
853 struct plink *plp;
854
855 /* Housekeeping detail:
856 ** Add to every propagate link a pointer back to the state to
857 ** which the link is attached. */
858 for(i=0; i<lemp->nstate; i++){
859 stp = lemp->sorted[i];
860 for(cfp=stp->cfp; cfp; cfp=cfp->next){
861 cfp->stp = stp;
862 }
863 }
864
865 /* Convert all backlinks into forward links. Only the forward
866 ** links are used in the follow-set computation. */
867 for(i=0; i<lemp->nstate; i++){
868 stp = lemp->sorted[i];
869 for(cfp=stp->cfp; cfp; cfp=cfp->next){
870 for(plp=cfp->bplp; plp; plp=plp->next){
871 other = plp->cfp;
872 Plink_add(&other->fplp,cfp);
873 }
874 }
875 }
876}
877
878/* Compute all followsets.
879**
880** A followset is the set of all symbols which can come immediately
881** after a configuration.
882*/
883void FindFollowSets(lemp)
884struct lemon *lemp;
885{
886 int i;
887 struct config *cfp;
888 struct plink *plp;
889 int progress;
890 int change;
891
892 for(i=0; i<lemp->nstate; i++){
893 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
894 cfp->status = INCOMPLETE;
895 }
896 }
897
898 do{
899 progress = 0;
900 for(i=0; i<lemp->nstate; i++){
901 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
902 if( cfp->status==COMPLETE ) continue;
903 for(plp=cfp->fplp; plp; plp=plp->next){
904 change = SetUnion(plp->cfp->fws,cfp->fws);
905 if( change ){
906 plp->cfp->status = INCOMPLETE;
907 progress = 1;
908 }
909 }
910 cfp->status = COMPLETE;
911 }
912 }
913 }while( progress );
914}
915
916static int resolve_conflict();
917
918/* Compute the reduce actions, and resolve conflicts.
919*/
920void FindActions(lemp)
921struct lemon *lemp;
922{
923 int i,j;
924 struct config *cfp;
925 struct state *stp;
926 struct symbol *sp;
927 struct rule *rp;
928
929 /* Add all of the reduce actions
930 ** A reduce action is added for each element of the followset of
931 ** a configuration which has its dot at the extreme right.
932 */
933 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
934 stp = lemp->sorted[i];
935 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
936 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
937 for(j=0; j<lemp->nterminal; j++){
938 if( SetFind(cfp->fws,j) ){
939 /* Add a reduce action to the state "stp" which will reduce by the
940 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000941 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000942 }
943 }
944 }
945 }
946 }
947
948 /* Add the accepting token */
949 if( lemp->start ){
950 sp = Symbol_find(lemp->start);
951 if( sp==0 ) sp = lemp->rule->lhs;
952 }else{
953 sp = lemp->rule->lhs;
954 }
955 /* Add to the first state (which is always the starting state of the
956 ** finite state machine) an action to ACCEPT if the lookahead is the
957 ** start nonterminal. */
958 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
959
960 /* Resolve conflicts */
961 for(i=0; i<lemp->nstate; i++){
962 struct action *ap, *nap;
963 struct state *stp;
964 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000965 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000966 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000967 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000968 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
969 /* The two actions "ap" and "nap" have the same lookahead.
970 ** Figure out which one should be used */
971 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
972 }
973 }
974 }
975
976 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000977 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000978 for(i=0; i<lemp->nstate; i++){
979 struct action *ap;
980 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000981 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000982 }
983 }
984 for(rp=lemp->rule; rp; rp=rp->next){
985 if( rp->canReduce ) continue;
986 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
987 lemp->errorcnt++;
988 }
989}
990
991/* Resolve a conflict between the two given actions. If the
992** conflict can't be resolve, return non-zero.
993**
994** NO LONGER TRUE:
995** To resolve a conflict, first look to see if either action
996** is on an error rule. In that case, take the action which
997** is not associated with the error rule. If neither or both
998** actions are associated with an error rule, then try to
999** use precedence to resolve the conflict.
1000**
1001** If either action is a SHIFT, then it must be apx. This
1002** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1003*/
1004static int resolve_conflict(apx,apy,errsym)
1005struct action *apx;
1006struct action *apy;
1007struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1008{
1009 struct symbol *spx, *spy;
1010 int errcnt = 0;
1011 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001012 if( apx->type==SHIFT && apy->type==SHIFT ){
1013 apy->type = CONFLICT;
1014 errcnt++;
1015 }
drh75897232000-05-29 14:26:00 +00001016 if( apx->type==SHIFT && apy->type==REDUCE ){
1017 spx = apx->sp;
1018 spy = apy->x.rp->precsym;
1019 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1020 /* Not enough precedence information. */
1021 apy->type = CONFLICT;
1022 errcnt++;
1023 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1024 apy->type = RD_RESOLVED;
1025 }else if( spx->prec<spy->prec ){
1026 apx->type = SH_RESOLVED;
1027 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1028 apy->type = RD_RESOLVED; /* associativity */
1029 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1030 apx->type = SH_RESOLVED;
1031 }else{
1032 assert( spx->prec==spy->prec && spx->assoc==NONE );
1033 apy->type = CONFLICT;
1034 errcnt++;
1035 }
1036 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1037 spx = apx->x.rp->precsym;
1038 spy = apy->x.rp->precsym;
1039 if( spx==0 || spy==0 || spx->prec<0 ||
1040 spy->prec<0 || spx->prec==spy->prec ){
1041 apy->type = CONFLICT;
1042 errcnt++;
1043 }else if( spx->prec>spy->prec ){
1044 apy->type = RD_RESOLVED;
1045 }else if( spx->prec<spy->prec ){
1046 apx->type = RD_RESOLVED;
1047 }
1048 }else{
drhb59499c2002-02-23 18:45:13 +00001049 assert(
1050 apx->type==SH_RESOLVED ||
1051 apx->type==RD_RESOLVED ||
1052 apx->type==CONFLICT ||
1053 apy->type==SH_RESOLVED ||
1054 apy->type==RD_RESOLVED ||
1055 apy->type==CONFLICT
1056 );
1057 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1058 ** REDUCEs on the list. If we reach this point it must be because
1059 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001060 }
1061 return errcnt;
1062}
1063/********************* From the file "configlist.c" *************************/
1064/*
1065** Routines to processing a configuration list and building a state
1066** in the LEMON parser generator.
1067*/
1068
1069static struct config *freelist = 0; /* List of free configurations */
1070static struct config *current = 0; /* Top of list of configurations */
1071static struct config **currentend = 0; /* Last on list of configs */
1072static struct config *basis = 0; /* Top of list of basis configs */
1073static struct config **basisend = 0; /* End of list of basis configs */
1074
1075/* Return a pointer to a new configuration */
1076PRIVATE struct config *newconfig(){
1077 struct config *new;
1078 if( freelist==0 ){
1079 int i;
1080 int amt = 3;
1081 freelist = (struct config *)malloc( sizeof(struct config)*amt );
1082 if( freelist==0 ){
1083 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1084 exit(1);
1085 }
1086 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1087 freelist[amt-1].next = 0;
1088 }
1089 new = freelist;
1090 freelist = freelist->next;
1091 return new;
1092}
1093
1094/* The configuration "old" is no longer used */
1095PRIVATE void deleteconfig(old)
1096struct config *old;
1097{
1098 old->next = freelist;
1099 freelist = old;
1100}
1101
1102/* Initialized the configuration list builder */
1103void Configlist_init(){
1104 current = 0;
1105 currentend = &current;
1106 basis = 0;
1107 basisend = &basis;
1108 Configtable_init();
1109 return;
1110}
1111
1112/* Initialized the configuration list builder */
1113void Configlist_reset(){
1114 current = 0;
1115 currentend = &current;
1116 basis = 0;
1117 basisend = &basis;
1118 Configtable_clear(0);
1119 return;
1120}
1121
1122/* Add another configuration to the configuration list */
1123struct config *Configlist_add(rp,dot)
1124struct rule *rp; /* The rule */
1125int dot; /* Index into the RHS of the rule where the dot goes */
1126{
1127 struct config *cfp, model;
1128
1129 assert( currentend!=0 );
1130 model.rp = rp;
1131 model.dot = dot;
1132 cfp = Configtable_find(&model);
1133 if( cfp==0 ){
1134 cfp = newconfig();
1135 cfp->rp = rp;
1136 cfp->dot = dot;
1137 cfp->fws = SetNew();
1138 cfp->stp = 0;
1139 cfp->fplp = cfp->bplp = 0;
1140 cfp->next = 0;
1141 cfp->bp = 0;
1142 *currentend = cfp;
1143 currentend = &cfp->next;
1144 Configtable_insert(cfp);
1145 }
1146 return cfp;
1147}
1148
1149/* Add a basis configuration to the configuration list */
1150struct config *Configlist_addbasis(rp,dot)
1151struct rule *rp;
1152int dot;
1153{
1154 struct config *cfp, model;
1155
1156 assert( basisend!=0 );
1157 assert( currentend!=0 );
1158 model.rp = rp;
1159 model.dot = dot;
1160 cfp = Configtable_find(&model);
1161 if( cfp==0 ){
1162 cfp = newconfig();
1163 cfp->rp = rp;
1164 cfp->dot = dot;
1165 cfp->fws = SetNew();
1166 cfp->stp = 0;
1167 cfp->fplp = cfp->bplp = 0;
1168 cfp->next = 0;
1169 cfp->bp = 0;
1170 *currentend = cfp;
1171 currentend = &cfp->next;
1172 *basisend = cfp;
1173 basisend = &cfp->bp;
1174 Configtable_insert(cfp);
1175 }
1176 return cfp;
1177}
1178
1179/* Compute the closure of the configuration list */
1180void Configlist_closure(lemp)
1181struct lemon *lemp;
1182{
1183 struct config *cfp, *newcfp;
1184 struct rule *rp, *newrp;
1185 struct symbol *sp, *xsp;
1186 int i, dot;
1187
1188 assert( currentend!=0 );
1189 for(cfp=current; cfp; cfp=cfp->next){
1190 rp = cfp->rp;
1191 dot = cfp->dot;
1192 if( dot>=rp->nrhs ) continue;
1193 sp = rp->rhs[dot];
1194 if( sp->type==NONTERMINAL ){
1195 if( sp->rule==0 && sp!=lemp->errsym ){
1196 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1197 sp->name);
1198 lemp->errorcnt++;
1199 }
1200 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1201 newcfp = Configlist_add(newrp,0);
1202 for(i=dot+1; i<rp->nrhs; i++){
1203 xsp = rp->rhs[i];
1204 if( xsp->type==TERMINAL ){
1205 SetAdd(newcfp->fws,xsp->index);
1206 break;
drhfd405312005-11-06 04:06:59 +00001207 }else if( xsp->type==MULTITERMINAL ){
1208 int k;
1209 for(k=0; k<xsp->nsubsym; k++){
1210 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1211 }
1212 break;
drh75897232000-05-29 14:26:00 +00001213 }else{
1214 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001215 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001216 }
1217 }
1218 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1219 }
1220 }
1221 }
1222 return;
1223}
1224
1225/* Sort the configuration list */
1226void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001227 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001228 currentend = 0;
1229 return;
1230}
1231
1232/* Sort the basis configuration list */
1233void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001234 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001235 basisend = 0;
1236 return;
1237}
1238
1239/* Return a pointer to the head of the configuration list and
1240** reset the list */
1241struct config *Configlist_return(){
1242 struct config *old;
1243 old = current;
1244 current = 0;
1245 currentend = 0;
1246 return old;
1247}
1248
1249/* Return a pointer to the head of the configuration list and
1250** reset the list */
1251struct config *Configlist_basis(){
1252 struct config *old;
1253 old = basis;
1254 basis = 0;
1255 basisend = 0;
1256 return old;
1257}
1258
1259/* Free all elements of the given configuration list */
1260void Configlist_eat(cfp)
1261struct config *cfp;
1262{
1263 struct config *nextcfp;
1264 for(; cfp; cfp=nextcfp){
1265 nextcfp = cfp->next;
1266 assert( cfp->fplp==0 );
1267 assert( cfp->bplp==0 );
1268 if( cfp->fws ) SetFree(cfp->fws);
1269 deleteconfig(cfp);
1270 }
1271 return;
1272}
1273/***************** From the file "error.c" *********************************/
1274/*
1275** Code for printing error message.
1276*/
1277
1278/* Find a good place to break "msg" so that its length is at least "min"
1279** but no more than "max". Make the point as close to max as possible.
1280*/
1281static int findbreak(msg,min,max)
1282char *msg;
1283int min;
1284int max;
1285{
1286 int i,spot;
1287 char c;
1288 for(i=spot=min; i<=max; i++){
1289 c = msg[i];
1290 if( c=='\t' ) msg[i] = ' ';
1291 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1292 if( c==0 ){ spot = i; break; }
1293 if( c=='-' && i<max-1 ) spot = i+1;
1294 if( c==' ' ) spot = i;
1295 }
1296 return spot;
1297}
1298
1299/*
1300** The error message is split across multiple lines if necessary. The
1301** splits occur at a space, if there is a space available near the end
1302** of the line.
1303*/
1304#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1305#define LINEWIDTH 79 /* Max width of any output line */
1306#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001307void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001308 char errmsg[ERRMSGSIZE];
1309 char prefix[PREFIXLIMIT+10];
1310 int errmsgsize;
1311 int prefixsize;
1312 int availablewidth;
1313 va_list ap;
1314 int end, restart, base;
1315
drhf9a2e7b2003-04-15 01:49:48 +00001316 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001317 /* Prepare a prefix to be prepended to every output line */
1318 if( lineno>0 ){
1319 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1320 }else{
1321 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1322 }
1323 prefixsize = strlen(prefix);
1324 availablewidth = LINEWIDTH - prefixsize;
1325
1326 /* Generate the error message */
1327 vsprintf(errmsg,format,ap);
1328 va_end(ap);
1329 errmsgsize = strlen(errmsg);
1330 /* Remove trailing '\n's from the error message. */
1331 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1332 errmsg[--errmsgsize] = 0;
1333 }
1334
1335 /* Print the error message */
1336 base = 0;
1337 while( errmsg[base]!=0 ){
1338 end = restart = findbreak(&errmsg[base],0,availablewidth);
1339 restart += base;
1340 while( errmsg[restart]==' ' ) restart++;
1341 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1342 base = restart;
1343 }
1344}
1345/**************** From the file "main.c" ************************************/
1346/*
1347** Main program file for the LEMON parser generator.
1348*/
1349
1350/* Report an out-of-memory condition and abort. This function
1351** is used mostly by the "MemoryCheck" macro in struct.h
1352*/
1353void memory_error(){
1354 fprintf(stderr,"Out of memory. Aborting...\n");
1355 exit(1);
1356}
1357
drh6d08b4d2004-07-20 12:45:22 +00001358static int nDefine = 0; /* Number of -D options on the command line */
1359static char **azDefine = 0; /* Name of the -D macros */
1360
1361/* This routine is called with the argument to each -D command-line option.
1362** Add the macro defined to the azDefine array.
1363*/
1364static void handle_D_option(char *z){
1365 char **paz;
1366 nDefine++;
1367 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1368 if( azDefine==0 ){
1369 fprintf(stderr,"out of memory\n");
1370 exit(1);
1371 }
1372 paz = &azDefine[nDefine-1];
1373 *paz = malloc( strlen(z)+1 );
1374 if( *paz==0 ){
1375 fprintf(stderr,"out of memory\n");
1376 exit(1);
1377 }
1378 strcpy(*paz, z);
1379 for(z=*paz; *z && *z!='='; z++){}
1380 *z = 0;
1381}
1382
drh75897232000-05-29 14:26:00 +00001383
1384/* The main program. Parse the command line and do it... */
1385int main(argc,argv)
1386int argc;
1387char **argv;
1388{
1389 static int version = 0;
1390 static int rpflag = 0;
1391 static int basisflag = 0;
1392 static int compress = 0;
1393 static int quiet = 0;
1394 static int statistics = 0;
1395 static int mhflag = 0;
1396 static struct s_options options[] = {
1397 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1398 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001399 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001400 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1401 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1402 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001403 {OPT_FLAG, "s", (char*)&statistics,
1404 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001405 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1406 {OPT_FLAG,0,0,0}
1407 };
1408 int i;
1409 struct lemon lem;
1410
drhb0c86772000-06-02 23:21:26 +00001411 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001412 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001413 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001414 exit(0);
1415 }
drhb0c86772000-06-02 23:21:26 +00001416 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001417 fprintf(stderr,"Exactly one filename argument is required.\n");
1418 exit(1);
1419 }
drh954f6b42006-06-13 13:27:46 +00001420 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001421 lem.errorcnt = 0;
1422
1423 /* Initialize the machine */
1424 Strsafe_init();
1425 Symbol_init();
1426 State_init();
1427 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001428 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001429 lem.basisflag = basisflag;
drh75897232000-05-29 14:26:00 +00001430 Symbol_new("$");
1431 lem.errsym = Symbol_new("error");
1432
1433 /* Parse the input file */
1434 Parse(&lem);
1435 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001436 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001437 fprintf(stderr,"Empty grammar.\n");
1438 exit(1);
1439 }
1440
1441 /* Count and index the symbols of the grammar */
1442 lem.nsymbol = Symbol_count();
1443 Symbol_new("{default}");
1444 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001445 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001446 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1447 (int(*)())Symbolcmpp);
1448 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1449 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1450 lem.nterminal = i;
1451
1452 /* Generate a reprint of the grammar, if requested on the command line */
1453 if( rpflag ){
1454 Reprint(&lem);
1455 }else{
1456 /* Initialize the size for all follow and first sets */
1457 SetSize(lem.nterminal);
1458
1459 /* Find the precedence for every production rule (that has one) */
1460 FindRulePrecedences(&lem);
1461
1462 /* Compute the lambda-nonterminals and the first-sets for every
1463 ** nonterminal */
1464 FindFirstSets(&lem);
1465
1466 /* Compute all LR(0) states. Also record follow-set propagation
1467 ** links so that the follow-set can be computed later */
1468 lem.nstate = 0;
1469 FindStates(&lem);
1470 lem.sorted = State_arrayof();
1471
1472 /* Tie up loose ends on the propagation links */
1473 FindLinks(&lem);
1474
1475 /* Compute the follow set of every reducible configuration */
1476 FindFollowSets(&lem);
1477
1478 /* Compute the action tables */
1479 FindActions(&lem);
1480
1481 /* Compress the action tables */
1482 if( compress==0 ) CompressTables(&lem);
1483
drhada354d2005-11-05 15:03:59 +00001484 /* Reorder and renumber the states so that states with fewer choices
1485 ** occur at the end. */
1486 ResortStates(&lem);
1487
drh75897232000-05-29 14:26:00 +00001488 /* Generate a report of the parser generated. (the "y.output" file) */
1489 if( !quiet ) ReportOutput(&lem);
1490
1491 /* Generate the source code for the parser */
1492 ReportTable(&lem, mhflag);
1493
1494 /* Produce a header file for use by the scanner. (This step is
1495 ** omitted if the "-m" option is used because makeheaders will
1496 ** generate the file for us.) */
1497 if( !mhflag ) ReportHeader(&lem);
1498 }
1499 if( statistics ){
1500 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1501 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1502 printf(" %d states, %d parser table entries, %d conflicts\n",
1503 lem.nstate, lem.tablesize, lem.nconflict);
1504 }
1505 if( lem.nconflict ){
1506 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1507 }
1508 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001509 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001510}
1511/******************** From the file "msort.c" *******************************/
1512/*
1513** A generic merge-sort program.
1514**
1515** USAGE:
1516** Let "ptr" be a pointer to some structure which is at the head of
1517** a null-terminated list. Then to sort the list call:
1518**
1519** ptr = msort(ptr,&(ptr->next),cmpfnc);
1520**
1521** In the above, "cmpfnc" is a pointer to a function which compares
1522** two instances of the structure and returns an integer, as in
1523** strcmp. The second argument is a pointer to the pointer to the
1524** second element of the linked list. This address is used to compute
1525** the offset to the "next" field within the structure. The offset to
1526** the "next" field must be constant for all structures in the list.
1527**
1528** The function returns a new pointer which is the head of the list
1529** after sorting.
1530**
1531** ALGORITHM:
1532** Merge-sort.
1533*/
1534
1535/*
1536** Return a pointer to the next structure in the linked list.
1537*/
drhba99af52001-10-25 20:37:16 +00001538#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001539
1540/*
1541** Inputs:
1542** a: A sorted, null-terminated linked list. (May be null).
1543** b: A sorted, null-terminated linked list. (May be null).
1544** cmp: A pointer to the comparison function.
1545** offset: Offset in the structure to the "next" field.
1546**
1547** Return Value:
1548** A pointer to the head of a sorted list containing the elements
1549** of both a and b.
1550**
1551** Side effects:
1552** The "next" pointers for elements in the lists a and b are
1553** changed.
1554*/
drhe9278182007-07-18 18:16:29 +00001555static char *merge(
1556 char *a,
1557 char *b,
1558 int (*cmp)(const char*,const char*),
1559 int offset
1560){
drh75897232000-05-29 14:26:00 +00001561 char *ptr, *head;
1562
1563 if( a==0 ){
1564 head = b;
1565 }else if( b==0 ){
1566 head = a;
1567 }else{
1568 if( (*cmp)(a,b)<0 ){
1569 ptr = a;
1570 a = NEXT(a);
1571 }else{
1572 ptr = b;
1573 b = NEXT(b);
1574 }
1575 head = ptr;
1576 while( a && b ){
1577 if( (*cmp)(a,b)<0 ){
1578 NEXT(ptr) = a;
1579 ptr = a;
1580 a = NEXT(a);
1581 }else{
1582 NEXT(ptr) = b;
1583 ptr = b;
1584 b = NEXT(b);
1585 }
1586 }
1587 if( a ) NEXT(ptr) = a;
1588 else NEXT(ptr) = b;
1589 }
1590 return head;
1591}
1592
1593/*
1594** Inputs:
1595** list: Pointer to a singly-linked list of structures.
1596** next: Pointer to pointer to the second element of the list.
1597** cmp: A comparison function.
1598**
1599** Return Value:
1600** A pointer to the head of a sorted list containing the elements
1601** orginally in list.
1602**
1603** Side effects:
1604** The "next" pointers for elements in list are changed.
1605*/
1606#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001607static char *msort(
1608 char *list,
1609 char **next,
1610 int (*cmp)(const char*,const char*)
1611){
drhba99af52001-10-25 20:37:16 +00001612 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001613 char *ep;
1614 char *set[LISTSIZE];
1615 int i;
drhba99af52001-10-25 20:37:16 +00001616 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001617 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1618 while( list ){
1619 ep = list;
1620 list = NEXT(list);
1621 NEXT(ep) = 0;
1622 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1623 ep = merge(ep,set[i],cmp,offset);
1624 set[i] = 0;
1625 }
1626 set[i] = ep;
1627 }
1628 ep = 0;
1629 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1630 return ep;
1631}
1632/************************ From the file "option.c" **************************/
1633static char **argv;
1634static struct s_options *op;
1635static FILE *errstream;
1636
1637#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1638
1639/*
1640** Print the command line with a carrot pointing to the k-th character
1641** of the n-th field.
1642*/
1643static void errline(n,k,err)
1644int n;
1645int k;
1646FILE *err;
1647{
1648 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001649 if( argv[0] ) fprintf(err,"%s",argv[0]);
1650 spcnt = strlen(argv[0]) + 1;
1651 for(i=1; i<n && argv[i]; i++){
1652 fprintf(err," %s",argv[i]);
drhdc30dd32005-02-16 03:35:15 +00001653 spcnt += strlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001654 }
1655 spcnt += k;
1656 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1657 if( spcnt<20 ){
1658 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1659 }else{
1660 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1661 }
1662}
1663
1664/*
1665** Return the index of the N-th non-switch argument. Return -1
1666** if N is out of range.
1667*/
1668static int argindex(n)
1669int n;
1670{
1671 int i;
1672 int dashdash = 0;
1673 if( argv!=0 && *argv!=0 ){
1674 for(i=1; argv[i]; i++){
1675 if( dashdash || !ISOPT(argv[i]) ){
1676 if( n==0 ) return i;
1677 n--;
1678 }
1679 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1680 }
1681 }
1682 return -1;
1683}
1684
1685static char emsg[] = "Command line syntax error: ";
1686
1687/*
1688** Process a flag command line argument.
1689*/
1690static int handleflags(i,err)
1691int i;
1692FILE *err;
1693{
1694 int v;
1695 int errcnt = 0;
1696 int j;
1697 for(j=0; op[j].label; j++){
drh6d08b4d2004-07-20 12:45:22 +00001698 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001699 }
1700 v = argv[i][0]=='-' ? 1 : 0;
1701 if( op[j].label==0 ){
1702 if( err ){
1703 fprintf(err,"%sundefined option.\n",emsg);
1704 errline(i,1,err);
1705 }
1706 errcnt++;
1707 }else if( op[j].type==OPT_FLAG ){
1708 *((int*)op[j].arg) = v;
1709 }else if( op[j].type==OPT_FFLAG ){
1710 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001711 }else if( op[j].type==OPT_FSTR ){
1712 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001713 }else{
1714 if( err ){
1715 fprintf(err,"%smissing argument on switch.\n",emsg);
1716 errline(i,1,err);
1717 }
1718 errcnt++;
1719 }
1720 return errcnt;
1721}
1722
1723/*
1724** Process a command line switch which has an argument.
1725*/
1726static int handleswitch(i,err)
1727int i;
1728FILE *err;
1729{
1730 int lv = 0;
1731 double dv = 0.0;
1732 char *sv = 0, *end;
1733 char *cp;
1734 int j;
1735 int errcnt = 0;
1736 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001737 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001738 *cp = 0;
1739 for(j=0; op[j].label; j++){
1740 if( strcmp(argv[i],op[j].label)==0 ) break;
1741 }
1742 *cp = '=';
1743 if( op[j].label==0 ){
1744 if( err ){
1745 fprintf(err,"%sundefined option.\n",emsg);
1746 errline(i,0,err);
1747 }
1748 errcnt++;
1749 }else{
1750 cp++;
1751 switch( op[j].type ){
1752 case OPT_FLAG:
1753 case OPT_FFLAG:
1754 if( err ){
1755 fprintf(err,"%soption requires an argument.\n",emsg);
1756 errline(i,0,err);
1757 }
1758 errcnt++;
1759 break;
1760 case OPT_DBL:
1761 case OPT_FDBL:
1762 dv = strtod(cp,&end);
1763 if( *end ){
1764 if( err ){
1765 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001766 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001767 }
1768 errcnt++;
1769 }
1770 break;
1771 case OPT_INT:
1772 case OPT_FINT:
1773 lv = strtol(cp,&end,0);
1774 if( *end ){
1775 if( err ){
1776 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001777 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001778 }
1779 errcnt++;
1780 }
1781 break;
1782 case OPT_STR:
1783 case OPT_FSTR:
1784 sv = cp;
1785 break;
1786 }
1787 switch( op[j].type ){
1788 case OPT_FLAG:
1789 case OPT_FFLAG:
1790 break;
1791 case OPT_DBL:
1792 *(double*)(op[j].arg) = dv;
1793 break;
1794 case OPT_FDBL:
1795 (*(void(*)())(op[j].arg))(dv);
1796 break;
1797 case OPT_INT:
1798 *(int*)(op[j].arg) = lv;
1799 break;
1800 case OPT_FINT:
1801 (*(void(*)())(op[j].arg))((int)lv);
1802 break;
1803 case OPT_STR:
1804 *(char**)(op[j].arg) = sv;
1805 break;
1806 case OPT_FSTR:
1807 (*(void(*)())(op[j].arg))(sv);
1808 break;
1809 }
1810 }
1811 return errcnt;
1812}
1813
drhb0c86772000-06-02 23:21:26 +00001814int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001815char **a;
1816struct s_options *o;
1817FILE *err;
1818{
1819 int errcnt = 0;
1820 argv = a;
1821 op = o;
1822 errstream = err;
1823 if( argv && *argv && op ){
1824 int i;
1825 for(i=1; argv[i]; i++){
1826 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1827 errcnt += handleflags(i,err);
1828 }else if( strchr(argv[i],'=') ){
1829 errcnt += handleswitch(i,err);
1830 }
1831 }
1832 }
1833 if( errcnt>0 ){
1834 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001835 OptPrint();
drh75897232000-05-29 14:26:00 +00001836 exit(1);
1837 }
1838 return 0;
1839}
1840
drhb0c86772000-06-02 23:21:26 +00001841int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001842 int cnt = 0;
1843 int dashdash = 0;
1844 int i;
1845 if( argv!=0 && argv[0]!=0 ){
1846 for(i=1; argv[i]; i++){
1847 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1848 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1849 }
1850 }
1851 return cnt;
1852}
1853
drhb0c86772000-06-02 23:21:26 +00001854char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001855int n;
1856{
1857 int i;
1858 i = argindex(n);
1859 return i>=0 ? argv[i] : 0;
1860}
1861
drhb0c86772000-06-02 23:21:26 +00001862void OptErr(n)
drh75897232000-05-29 14:26:00 +00001863int n;
1864{
1865 int i;
1866 i = argindex(n);
1867 if( i>=0 ) errline(i,0,errstream);
1868}
1869
drhb0c86772000-06-02 23:21:26 +00001870void OptPrint(){
drh75897232000-05-29 14:26:00 +00001871 int i;
1872 int max, len;
1873 max = 0;
1874 for(i=0; op[i].label; i++){
1875 len = strlen(op[i].label) + 1;
1876 switch( op[i].type ){
1877 case OPT_FLAG:
1878 case OPT_FFLAG:
1879 break;
1880 case OPT_INT:
1881 case OPT_FINT:
1882 len += 9; /* length of "<integer>" */
1883 break;
1884 case OPT_DBL:
1885 case OPT_FDBL:
1886 len += 6; /* length of "<real>" */
1887 break;
1888 case OPT_STR:
1889 case OPT_FSTR:
1890 len += 8; /* length of "<string>" */
1891 break;
1892 }
1893 if( len>max ) max = len;
1894 }
1895 for(i=0; op[i].label; i++){
1896 switch( op[i].type ){
1897 case OPT_FLAG:
1898 case OPT_FFLAG:
1899 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1900 break;
1901 case OPT_INT:
1902 case OPT_FINT:
1903 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001904 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001905 break;
1906 case OPT_DBL:
1907 case OPT_FDBL:
1908 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001909 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001910 break;
1911 case OPT_STR:
1912 case OPT_FSTR:
1913 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001914 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001915 break;
1916 }
1917 }
1918}
1919/*********************** From the file "parse.c" ****************************/
1920/*
1921** Input file parser for the LEMON parser generator.
1922*/
1923
1924/* The state of the parser */
1925struct pstate {
1926 char *filename; /* Name of the input file */
1927 int tokenlineno; /* Linenumber at which current token starts */
1928 int errorcnt; /* Number of errors so far */
1929 char *tokenstart; /* Text of current token */
1930 struct lemon *gp; /* Global state vector */
1931 enum e_state {
1932 INITIALIZE,
1933 WAITING_FOR_DECL_OR_RULE,
1934 WAITING_FOR_DECL_KEYWORD,
1935 WAITING_FOR_DECL_ARG,
1936 WAITING_FOR_PRECEDENCE_SYMBOL,
1937 WAITING_FOR_ARROW,
1938 IN_RHS,
1939 LHS_ALIAS_1,
1940 LHS_ALIAS_2,
1941 LHS_ALIAS_3,
1942 RHS_ALIAS_1,
1943 RHS_ALIAS_2,
1944 PRECEDENCE_MARK_1,
1945 PRECEDENCE_MARK_2,
1946 RESYNC_AFTER_RULE_ERROR,
1947 RESYNC_AFTER_DECL_ERROR,
1948 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001949 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001950 WAITING_FOR_FALLBACK_ID,
1951 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001952 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001953 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001954 struct symbol *lhs; /* Left-hand side of current rule */
1955 char *lhsalias; /* Alias for the LHS */
1956 int nrhs; /* Number of right-hand side symbols seen */
1957 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1958 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1959 struct rule *prevrule; /* Previous rule parsed */
1960 char *declkeyword; /* Keyword of a declaration */
1961 char **declargslot; /* Where the declaration argument should be put */
1962 int *decllnslot; /* Where the declaration linenumber is put */
1963 enum e_assoc declassoc; /* Assign this association to decl arguments */
1964 int preccounter; /* Assign this precedence to decl arguments */
1965 struct rule *firstrule; /* Pointer to first rule in the grammar */
1966 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1967};
1968
1969/* Parse a single token */
1970static void parseonetoken(psp)
1971struct pstate *psp;
1972{
1973 char *x;
1974 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1975#if 0
1976 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1977 x,psp->state);
1978#endif
1979 switch( psp->state ){
1980 case INITIALIZE:
1981 psp->prevrule = 0;
1982 psp->preccounter = 0;
1983 psp->firstrule = psp->lastrule = 0;
1984 psp->gp->nrule = 0;
1985 /* Fall thru to next case */
1986 case WAITING_FOR_DECL_OR_RULE:
1987 if( x[0]=='%' ){
1988 psp->state = WAITING_FOR_DECL_KEYWORD;
1989 }else if( islower(x[0]) ){
1990 psp->lhs = Symbol_new(x);
1991 psp->nrhs = 0;
1992 psp->lhsalias = 0;
1993 psp->state = WAITING_FOR_ARROW;
1994 }else if( x[0]=='{' ){
1995 if( psp->prevrule==0 ){
1996 ErrorMsg(psp->filename,psp->tokenlineno,
1997"There is not prior rule opon which to attach the code \
1998fragment which begins on this line.");
1999 psp->errorcnt++;
2000 }else if( psp->prevrule->code!=0 ){
2001 ErrorMsg(psp->filename,psp->tokenlineno,
2002"Code fragment beginning on this line is not the first \
2003to follow the previous rule.");
2004 psp->errorcnt++;
2005 }else{
2006 psp->prevrule->line = psp->tokenlineno;
2007 psp->prevrule->code = &x[1];
2008 }
2009 }else if( x[0]=='[' ){
2010 psp->state = PRECEDENCE_MARK_1;
2011 }else{
2012 ErrorMsg(psp->filename,psp->tokenlineno,
2013 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2014 x);
2015 psp->errorcnt++;
2016 }
2017 break;
2018 case PRECEDENCE_MARK_1:
2019 if( !isupper(x[0]) ){
2020 ErrorMsg(psp->filename,psp->tokenlineno,
2021 "The precedence symbol must be a terminal.");
2022 psp->errorcnt++;
2023 }else if( psp->prevrule==0 ){
2024 ErrorMsg(psp->filename,psp->tokenlineno,
2025 "There is no prior rule to assign precedence \"[%s]\".",x);
2026 psp->errorcnt++;
2027 }else if( psp->prevrule->precsym!=0 ){
2028 ErrorMsg(psp->filename,psp->tokenlineno,
2029"Precedence mark on this line is not the first \
2030to follow the previous rule.");
2031 psp->errorcnt++;
2032 }else{
2033 psp->prevrule->precsym = Symbol_new(x);
2034 }
2035 psp->state = PRECEDENCE_MARK_2;
2036 break;
2037 case PRECEDENCE_MARK_2:
2038 if( x[0]!=']' ){
2039 ErrorMsg(psp->filename,psp->tokenlineno,
2040 "Missing \"]\" on precedence mark.");
2041 psp->errorcnt++;
2042 }
2043 psp->state = WAITING_FOR_DECL_OR_RULE;
2044 break;
2045 case WAITING_FOR_ARROW:
2046 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2047 psp->state = IN_RHS;
2048 }else if( x[0]=='(' ){
2049 psp->state = LHS_ALIAS_1;
2050 }else{
2051 ErrorMsg(psp->filename,psp->tokenlineno,
2052 "Expected to see a \":\" following the LHS symbol \"%s\".",
2053 psp->lhs->name);
2054 psp->errorcnt++;
2055 psp->state = RESYNC_AFTER_RULE_ERROR;
2056 }
2057 break;
2058 case LHS_ALIAS_1:
2059 if( isalpha(x[0]) ){
2060 psp->lhsalias = x;
2061 psp->state = LHS_ALIAS_2;
2062 }else{
2063 ErrorMsg(psp->filename,psp->tokenlineno,
2064 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2065 x,psp->lhs->name);
2066 psp->errorcnt++;
2067 psp->state = RESYNC_AFTER_RULE_ERROR;
2068 }
2069 break;
2070 case LHS_ALIAS_2:
2071 if( x[0]==')' ){
2072 psp->state = LHS_ALIAS_3;
2073 }else{
2074 ErrorMsg(psp->filename,psp->tokenlineno,
2075 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2076 psp->errorcnt++;
2077 psp->state = RESYNC_AFTER_RULE_ERROR;
2078 }
2079 break;
2080 case LHS_ALIAS_3:
2081 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2082 psp->state = IN_RHS;
2083 }else{
2084 ErrorMsg(psp->filename,psp->tokenlineno,
2085 "Missing \"->\" following: \"%s(%s)\".",
2086 psp->lhs->name,psp->lhsalias);
2087 psp->errorcnt++;
2088 psp->state = RESYNC_AFTER_RULE_ERROR;
2089 }
2090 break;
2091 case IN_RHS:
2092 if( x[0]=='.' ){
2093 struct rule *rp;
2094 rp = (struct rule *)malloc( sizeof(struct rule) +
2095 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
2096 if( rp==0 ){
2097 ErrorMsg(psp->filename,psp->tokenlineno,
2098 "Can't allocate enough memory for this rule.");
2099 psp->errorcnt++;
2100 psp->prevrule = 0;
2101 }else{
2102 int i;
2103 rp->ruleline = psp->tokenlineno;
2104 rp->rhs = (struct symbol**)&rp[1];
2105 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2106 for(i=0; i<psp->nrhs; i++){
2107 rp->rhs[i] = psp->rhs[i];
2108 rp->rhsalias[i] = psp->alias[i];
2109 }
2110 rp->lhs = psp->lhs;
2111 rp->lhsalias = psp->lhsalias;
2112 rp->nrhs = psp->nrhs;
2113 rp->code = 0;
2114 rp->precsym = 0;
2115 rp->index = psp->gp->nrule++;
2116 rp->nextlhs = rp->lhs->rule;
2117 rp->lhs->rule = rp;
2118 rp->next = 0;
2119 if( psp->firstrule==0 ){
2120 psp->firstrule = psp->lastrule = rp;
2121 }else{
2122 psp->lastrule->next = rp;
2123 psp->lastrule = rp;
2124 }
2125 psp->prevrule = rp;
2126 }
2127 psp->state = WAITING_FOR_DECL_OR_RULE;
2128 }else if( isalpha(x[0]) ){
2129 if( psp->nrhs>=MAXRHS ){
2130 ErrorMsg(psp->filename,psp->tokenlineno,
drhfd405312005-11-06 04:06:59 +00002131 "Too many symbols on RHS or rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002132 x);
2133 psp->errorcnt++;
2134 psp->state = RESYNC_AFTER_RULE_ERROR;
2135 }else{
2136 psp->rhs[psp->nrhs] = Symbol_new(x);
2137 psp->alias[psp->nrhs] = 0;
2138 psp->nrhs++;
2139 }
drhfd405312005-11-06 04:06:59 +00002140 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2141 struct symbol *msp = psp->rhs[psp->nrhs-1];
2142 if( msp->type!=MULTITERMINAL ){
2143 struct symbol *origsp = msp;
2144 msp = malloc(sizeof(*msp));
2145 memset(msp, 0, sizeof(*msp));
2146 msp->type = MULTITERMINAL;
2147 msp->nsubsym = 1;
2148 msp->subsym = malloc(sizeof(struct symbol*));
2149 msp->subsym[0] = origsp;
2150 msp->name = origsp->name;
2151 psp->rhs[psp->nrhs-1] = msp;
2152 }
2153 msp->nsubsym++;
2154 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2155 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2156 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2157 ErrorMsg(psp->filename,psp->tokenlineno,
2158 "Cannot form a compound containing a non-terminal");
2159 psp->errorcnt++;
2160 }
drh75897232000-05-29 14:26:00 +00002161 }else if( x[0]=='(' && psp->nrhs>0 ){
2162 psp->state = RHS_ALIAS_1;
2163 }else{
2164 ErrorMsg(psp->filename,psp->tokenlineno,
2165 "Illegal character on RHS of rule: \"%s\".",x);
2166 psp->errorcnt++;
2167 psp->state = RESYNC_AFTER_RULE_ERROR;
2168 }
2169 break;
2170 case RHS_ALIAS_1:
2171 if( isalpha(x[0]) ){
2172 psp->alias[psp->nrhs-1] = x;
2173 psp->state = RHS_ALIAS_2;
2174 }else{
2175 ErrorMsg(psp->filename,psp->tokenlineno,
2176 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2177 x,psp->rhs[psp->nrhs-1]->name);
2178 psp->errorcnt++;
2179 psp->state = RESYNC_AFTER_RULE_ERROR;
2180 }
2181 break;
2182 case RHS_ALIAS_2:
2183 if( x[0]==')' ){
2184 psp->state = IN_RHS;
2185 }else{
2186 ErrorMsg(psp->filename,psp->tokenlineno,
2187 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2188 psp->errorcnt++;
2189 psp->state = RESYNC_AFTER_RULE_ERROR;
2190 }
2191 break;
2192 case WAITING_FOR_DECL_KEYWORD:
2193 if( isalpha(x[0]) ){
2194 psp->declkeyword = x;
2195 psp->declargslot = 0;
2196 psp->decllnslot = 0;
2197 psp->state = WAITING_FOR_DECL_ARG;
2198 if( strcmp(x,"name")==0 ){
2199 psp->declargslot = &(psp->gp->name);
2200 }else if( strcmp(x,"include")==0 ){
2201 psp->declargslot = &(psp->gp->include);
2202 psp->decllnslot = &psp->gp->includeln;
2203 }else if( strcmp(x,"code")==0 ){
2204 psp->declargslot = &(psp->gp->extracode);
2205 psp->decllnslot = &psp->gp->extracodeln;
2206 }else if( strcmp(x,"token_destructor")==0 ){
2207 psp->declargslot = &psp->gp->tokendest;
2208 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00002209 }else if( strcmp(x,"default_destructor")==0 ){
2210 psp->declargslot = &psp->gp->vardest;
2211 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00002212 }else if( strcmp(x,"token_prefix")==0 ){
2213 psp->declargslot = &psp->gp->tokenprefix;
2214 }else if( strcmp(x,"syntax_error")==0 ){
2215 psp->declargslot = &(psp->gp->error);
2216 psp->decllnslot = &psp->gp->errorln;
2217 }else if( strcmp(x,"parse_accept")==0 ){
2218 psp->declargslot = &(psp->gp->accept);
2219 psp->decllnslot = &psp->gp->acceptln;
2220 }else if( strcmp(x,"parse_failure")==0 ){
2221 psp->declargslot = &(psp->gp->failure);
2222 psp->decllnslot = &psp->gp->failureln;
2223 }else if( strcmp(x,"stack_overflow")==0 ){
2224 psp->declargslot = &(psp->gp->overflow);
2225 psp->decllnslot = &psp->gp->overflowln;
2226 }else if( strcmp(x,"extra_argument")==0 ){
2227 psp->declargslot = &(psp->gp->arg);
2228 }else if( strcmp(x,"token_type")==0 ){
2229 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00002230 }else if( strcmp(x,"default_type")==0 ){
2231 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00002232 }else if( strcmp(x,"stack_size")==0 ){
2233 psp->declargslot = &(psp->gp->stacksize);
2234 }else if( strcmp(x,"start_symbol")==0 ){
2235 psp->declargslot = &(psp->gp->start);
2236 }else if( strcmp(x,"left")==0 ){
2237 psp->preccounter++;
2238 psp->declassoc = LEFT;
2239 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2240 }else if( strcmp(x,"right")==0 ){
2241 psp->preccounter++;
2242 psp->declassoc = RIGHT;
2243 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2244 }else if( strcmp(x,"nonassoc")==0 ){
2245 psp->preccounter++;
2246 psp->declassoc = NONE;
2247 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2248 }else if( strcmp(x,"destructor")==0 ){
2249 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2250 }else if( strcmp(x,"type")==0 ){
2251 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002252 }else if( strcmp(x,"fallback")==0 ){
2253 psp->fallback = 0;
2254 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002255 }else if( strcmp(x,"wildcard")==0 ){
2256 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002257 }else{
2258 ErrorMsg(psp->filename,psp->tokenlineno,
2259 "Unknown declaration keyword: \"%%%s\".",x);
2260 psp->errorcnt++;
2261 psp->state = RESYNC_AFTER_DECL_ERROR;
2262 }
2263 }else{
2264 ErrorMsg(psp->filename,psp->tokenlineno,
2265 "Illegal declaration keyword: \"%s\".",x);
2266 psp->errorcnt++;
2267 psp->state = RESYNC_AFTER_DECL_ERROR;
2268 }
2269 break;
2270 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2271 if( !isalpha(x[0]) ){
2272 ErrorMsg(psp->filename,psp->tokenlineno,
2273 "Symbol name missing after %destructor keyword");
2274 psp->errorcnt++;
2275 psp->state = RESYNC_AFTER_DECL_ERROR;
2276 }else{
2277 struct symbol *sp = Symbol_new(x);
2278 psp->declargslot = &sp->destructor;
2279 psp->decllnslot = &sp->destructorln;
2280 psp->state = WAITING_FOR_DECL_ARG;
2281 }
2282 break;
2283 case WAITING_FOR_DATATYPE_SYMBOL:
2284 if( !isalpha(x[0]) ){
2285 ErrorMsg(psp->filename,psp->tokenlineno,
2286 "Symbol name missing after %destructor keyword");
2287 psp->errorcnt++;
2288 psp->state = RESYNC_AFTER_DECL_ERROR;
2289 }else{
2290 struct symbol *sp = Symbol_new(x);
2291 psp->declargslot = &sp->datatype;
2292 psp->decllnslot = 0;
2293 psp->state = WAITING_FOR_DECL_ARG;
2294 }
2295 break;
2296 case WAITING_FOR_PRECEDENCE_SYMBOL:
2297 if( x[0]=='.' ){
2298 psp->state = WAITING_FOR_DECL_OR_RULE;
2299 }else if( isupper(x[0]) ){
2300 struct symbol *sp;
2301 sp = Symbol_new(x);
2302 if( sp->prec>=0 ){
2303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "Symbol \"%s\" has already be given a precedence.",x);
2305 psp->errorcnt++;
2306 }else{
2307 sp->prec = psp->preccounter;
2308 sp->assoc = psp->declassoc;
2309 }
2310 }else{
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "Can't assign a precedence to \"%s\".",x);
2313 psp->errorcnt++;
2314 }
2315 break;
2316 case WAITING_FOR_DECL_ARG:
2317 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2318 if( *(psp->declargslot)!=0 ){
2319 ErrorMsg(psp->filename,psp->tokenlineno,
2320 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2321 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2322 psp->errorcnt++;
2323 psp->state = RESYNC_AFTER_DECL_ERROR;
2324 }else{
2325 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2326 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2327 psp->state = WAITING_FOR_DECL_OR_RULE;
2328 }
2329 }else{
2330 ErrorMsg(psp->filename,psp->tokenlineno,
2331 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2332 psp->errorcnt++;
2333 psp->state = RESYNC_AFTER_DECL_ERROR;
2334 }
2335 break;
drh0bd1f4e2002-06-06 18:54:39 +00002336 case WAITING_FOR_FALLBACK_ID:
2337 if( x[0]=='.' ){
2338 psp->state = WAITING_FOR_DECL_OR_RULE;
2339 }else if( !isupper(x[0]) ){
2340 ErrorMsg(psp->filename, psp->tokenlineno,
2341 "%%fallback argument \"%s\" should be a token", x);
2342 psp->errorcnt++;
2343 }else{
2344 struct symbol *sp = Symbol_new(x);
2345 if( psp->fallback==0 ){
2346 psp->fallback = sp;
2347 }else if( sp->fallback ){
2348 ErrorMsg(psp->filename, psp->tokenlineno,
2349 "More than one fallback assigned to token %s", x);
2350 psp->errorcnt++;
2351 }else{
2352 sp->fallback = psp->fallback;
2353 psp->gp->has_fallback = 1;
2354 }
2355 }
2356 break;
drhe09daa92006-06-10 13:29:31 +00002357 case WAITING_FOR_WILDCARD_ID:
2358 if( x[0]=='.' ){
2359 psp->state = WAITING_FOR_DECL_OR_RULE;
2360 }else if( !isupper(x[0]) ){
2361 ErrorMsg(psp->filename, psp->tokenlineno,
2362 "%%wildcard argument \"%s\" should be a token", x);
2363 psp->errorcnt++;
2364 }else{
2365 struct symbol *sp = Symbol_new(x);
2366 if( psp->gp->wildcard==0 ){
2367 psp->gp->wildcard = sp;
2368 }else{
2369 ErrorMsg(psp->filename, psp->tokenlineno,
2370 "Extra wildcard to token: %s", x);
2371 psp->errorcnt++;
2372 }
2373 }
2374 break;
drh75897232000-05-29 14:26:00 +00002375 case RESYNC_AFTER_RULE_ERROR:
2376/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2377** break; */
2378 case RESYNC_AFTER_DECL_ERROR:
2379 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2380 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2381 break;
2382 }
2383}
2384
drh6d08b4d2004-07-20 12:45:22 +00002385/* Run the proprocessor over the input file text. The global variables
2386** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2387** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2388** comments them out. Text in between is also commented out as appropriate.
2389*/
danielk1977940fac92005-01-23 22:41:37 +00002390static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002391 int i, j, k, n;
2392 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002393 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002394 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002395 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002396 for(i=0; z[i]; i++){
2397 if( z[i]=='\n' ) lineno++;
2398 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2399 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2400 if( exclude ){
2401 exclude--;
2402 if( exclude==0 ){
2403 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2404 }
2405 }
2406 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2407 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2408 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2409 if( exclude ){
2410 exclude++;
2411 }else{
2412 for(j=i+7; isspace(z[j]); j++){}
2413 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2414 exclude = 1;
2415 for(k=0; k<nDefine; k++){
2416 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2417 exclude = 0;
2418 break;
2419 }
2420 }
2421 if( z[i+3]=='n' ) exclude = !exclude;
2422 if( exclude ){
2423 start = i;
2424 start_lineno = lineno;
2425 }
2426 }
2427 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2428 }
2429 }
2430 if( exclude ){
2431 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2432 exit(1);
2433 }
2434}
2435
drh75897232000-05-29 14:26:00 +00002436/* In spite of its name, this function is really a scanner. It read
2437** in the entire input file (all at once) then tokenizes it. Each
2438** token is passed to the function "parseonetoken" which builds all
2439** the appropriate data structures in the global state vector "gp".
2440*/
2441void Parse(gp)
2442struct lemon *gp;
2443{
2444 struct pstate ps;
2445 FILE *fp;
2446 char *filebuf;
2447 int filesize;
2448 int lineno;
2449 int c;
2450 char *cp, *nextcp;
2451 int startline = 0;
2452
rse38514a92007-09-20 11:34:17 +00002453 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002454 ps.gp = gp;
2455 ps.filename = gp->filename;
2456 ps.errorcnt = 0;
2457 ps.state = INITIALIZE;
2458
2459 /* Begin by reading the input file */
2460 fp = fopen(ps.filename,"rb");
2461 if( fp==0 ){
2462 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2463 gp->errorcnt++;
2464 return;
2465 }
2466 fseek(fp,0,2);
2467 filesize = ftell(fp);
2468 rewind(fp);
2469 filebuf = (char *)malloc( filesize+1 );
2470 if( filebuf==0 ){
2471 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2472 filesize+1);
2473 gp->errorcnt++;
2474 return;
2475 }
2476 if( fread(filebuf,1,filesize,fp)!=filesize ){
2477 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2478 filesize);
2479 free(filebuf);
2480 gp->errorcnt++;
2481 return;
2482 }
2483 fclose(fp);
2484 filebuf[filesize] = 0;
2485
drh6d08b4d2004-07-20 12:45:22 +00002486 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2487 preprocess_input(filebuf);
2488
drh75897232000-05-29 14:26:00 +00002489 /* Now scan the text of the input file */
2490 lineno = 1;
2491 for(cp=filebuf; (c= *cp)!=0; ){
2492 if( c=='\n' ) lineno++; /* Keep track of the line number */
2493 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2494 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2495 cp+=2;
2496 while( (c= *cp)!=0 && c!='\n' ) cp++;
2497 continue;
2498 }
2499 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2500 cp+=2;
2501 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2502 if( c=='\n' ) lineno++;
2503 cp++;
2504 }
2505 if( c ) cp++;
2506 continue;
2507 }
2508 ps.tokenstart = cp; /* Mark the beginning of the token */
2509 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2510 if( c=='\"' ){ /* String literals */
2511 cp++;
2512 while( (c= *cp)!=0 && c!='\"' ){
2513 if( c=='\n' ) lineno++;
2514 cp++;
2515 }
2516 if( c==0 ){
2517 ErrorMsg(ps.filename,startline,
2518"String starting on this line is not terminated before the end of the file.");
2519 ps.errorcnt++;
2520 nextcp = cp;
2521 }else{
2522 nextcp = cp+1;
2523 }
2524 }else if( c=='{' ){ /* A block of C code */
2525 int level;
2526 cp++;
2527 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2528 if( c=='\n' ) lineno++;
2529 else if( c=='{' ) level++;
2530 else if( c=='}' ) level--;
2531 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2532 int prevc;
2533 cp = &cp[2];
2534 prevc = 0;
2535 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2536 if( c=='\n' ) lineno++;
2537 prevc = c;
2538 cp++;
2539 }
2540 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2541 cp = &cp[2];
2542 while( (c= *cp)!=0 && c!='\n' ) cp++;
2543 if( c ) lineno++;
2544 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2545 int startchar, prevc;
2546 startchar = c;
2547 prevc = 0;
2548 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2549 if( c=='\n' ) lineno++;
2550 if( prevc=='\\' ) prevc = 0;
2551 else prevc = c;
2552 }
2553 }
2554 }
2555 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002556 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002557"C code starting on this line is not terminated before the end of the file.");
2558 ps.errorcnt++;
2559 nextcp = cp;
2560 }else{
2561 nextcp = cp+1;
2562 }
2563 }else if( isalnum(c) ){ /* Identifiers */
2564 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2565 nextcp = cp;
2566 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2567 cp += 3;
2568 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002569 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2570 cp += 2;
2571 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2572 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002573 }else{ /* All other (one character) operators */
2574 cp++;
2575 nextcp = cp;
2576 }
2577 c = *cp;
2578 *cp = 0; /* Null terminate the token */
2579 parseonetoken(&ps); /* Parse the token */
2580 *cp = c; /* Restore the buffer */
2581 cp = nextcp;
2582 }
2583 free(filebuf); /* Release the buffer after parsing */
2584 gp->rule = ps.firstrule;
2585 gp->errorcnt = ps.errorcnt;
2586}
2587/*************************** From the file "plink.c" *********************/
2588/*
2589** Routines processing configuration follow-set propagation links
2590** in the LEMON parser generator.
2591*/
2592static struct plink *plink_freelist = 0;
2593
2594/* Allocate a new plink */
2595struct plink *Plink_new(){
2596 struct plink *new;
2597
2598 if( plink_freelist==0 ){
2599 int i;
2600 int amt = 100;
2601 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2602 if( plink_freelist==0 ){
2603 fprintf(stderr,
2604 "Unable to allocate memory for a new follow-set propagation link.\n");
2605 exit(1);
2606 }
2607 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2608 plink_freelist[amt-1].next = 0;
2609 }
2610 new = plink_freelist;
2611 plink_freelist = plink_freelist->next;
2612 return new;
2613}
2614
2615/* Add a plink to a plink list */
2616void Plink_add(plpp,cfp)
2617struct plink **plpp;
2618struct config *cfp;
2619{
2620 struct plink *new;
2621 new = Plink_new();
2622 new->next = *plpp;
2623 *plpp = new;
2624 new->cfp = cfp;
2625}
2626
2627/* Transfer every plink on the list "from" to the list "to" */
2628void Plink_copy(to,from)
2629struct plink **to;
2630struct plink *from;
2631{
2632 struct plink *nextpl;
2633 while( from ){
2634 nextpl = from->next;
2635 from->next = *to;
2636 *to = from;
2637 from = nextpl;
2638 }
2639}
2640
2641/* Delete every plink on the list */
2642void Plink_delete(plp)
2643struct plink *plp;
2644{
2645 struct plink *nextpl;
2646
2647 while( plp ){
2648 nextpl = plp->next;
2649 plp->next = plink_freelist;
2650 plink_freelist = plp;
2651 plp = nextpl;
2652 }
2653}
2654/*********************** From the file "report.c" **************************/
2655/*
2656** Procedures for generating reports and tables in the LEMON parser generator.
2657*/
2658
2659/* Generate a filename with the given suffix. Space to hold the
2660** name comes from malloc() and must be freed by the calling
2661** function.
2662*/
2663PRIVATE char *file_makename(lemp,suffix)
2664struct lemon *lemp;
2665char *suffix;
2666{
2667 char *name;
2668 char *cp;
2669
2670 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2671 if( name==0 ){
2672 fprintf(stderr,"Can't allocate space for a filename.\n");
2673 exit(1);
2674 }
2675 strcpy(name,lemp->filename);
2676 cp = strrchr(name,'.');
2677 if( cp ) *cp = 0;
2678 strcat(name,suffix);
2679 return name;
2680}
2681
2682/* Open a file with a name based on the name of the input file,
2683** but with a different (specified) suffix, and return a pointer
2684** to the stream */
2685PRIVATE FILE *file_open(lemp,suffix,mode)
2686struct lemon *lemp;
2687char *suffix;
2688char *mode;
2689{
2690 FILE *fp;
2691
2692 if( lemp->outname ) free(lemp->outname);
2693 lemp->outname = file_makename(lemp, suffix);
2694 fp = fopen(lemp->outname,mode);
2695 if( fp==0 && *mode=='w' ){
2696 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2697 lemp->errorcnt++;
2698 return 0;
2699 }
2700 return fp;
2701}
2702
2703/* Duplicate the input file without comments and without actions
2704** on rules */
2705void Reprint(lemp)
2706struct lemon *lemp;
2707{
2708 struct rule *rp;
2709 struct symbol *sp;
2710 int i, j, maxlen, len, ncolumns, skip;
2711 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2712 maxlen = 10;
2713 for(i=0; i<lemp->nsymbol; i++){
2714 sp = lemp->symbols[i];
2715 len = strlen(sp->name);
2716 if( len>maxlen ) maxlen = len;
2717 }
2718 ncolumns = 76/(maxlen+5);
2719 if( ncolumns<1 ) ncolumns = 1;
2720 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2721 for(i=0; i<skip; i++){
2722 printf("//");
2723 for(j=i; j<lemp->nsymbol; j+=skip){
2724 sp = lemp->symbols[j];
2725 assert( sp->index==j );
2726 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2727 }
2728 printf("\n");
2729 }
2730 for(rp=lemp->rule; rp; rp=rp->next){
2731 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002732 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002733 printf(" ::=");
2734 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002735 sp = rp->rhs[i];
2736 printf(" %s", sp->name);
2737 if( sp->type==MULTITERMINAL ){
2738 for(j=1; j<sp->nsubsym; j++){
2739 printf("|%s", sp->subsym[j]->name);
2740 }
2741 }
2742 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002743 }
2744 printf(".");
2745 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002746 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002747 printf("\n");
2748 }
2749}
2750
2751void ConfigPrint(fp,cfp)
2752FILE *fp;
2753struct config *cfp;
2754{
2755 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002756 struct symbol *sp;
2757 int i, j;
drh75897232000-05-29 14:26:00 +00002758 rp = cfp->rp;
2759 fprintf(fp,"%s ::=",rp->lhs->name);
2760 for(i=0; i<=rp->nrhs; i++){
2761 if( i==cfp->dot ) fprintf(fp," *");
2762 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002763 sp = rp->rhs[i];
2764 fprintf(fp," %s", sp->name);
2765 if( sp->type==MULTITERMINAL ){
2766 for(j=1; j<sp->nsubsym; j++){
2767 fprintf(fp,"|%s",sp->subsym[j]->name);
2768 }
2769 }
drh75897232000-05-29 14:26:00 +00002770 }
2771}
2772
2773/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002774#if 0
drh75897232000-05-29 14:26:00 +00002775/* Print a set */
2776PRIVATE void SetPrint(out,set,lemp)
2777FILE *out;
2778char *set;
2779struct lemon *lemp;
2780{
2781 int i;
2782 char *spacer;
2783 spacer = "";
2784 fprintf(out,"%12s[","");
2785 for(i=0; i<lemp->nterminal; i++){
2786 if( SetFind(set,i) ){
2787 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2788 spacer = " ";
2789 }
2790 }
2791 fprintf(out,"]\n");
2792}
2793
2794/* Print a plink chain */
2795PRIVATE void PlinkPrint(out,plp,tag)
2796FILE *out;
2797struct plink *plp;
2798char *tag;
2799{
2800 while( plp ){
drhada354d2005-11-05 15:03:59 +00002801 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002802 ConfigPrint(out,plp->cfp);
2803 fprintf(out,"\n");
2804 plp = plp->next;
2805 }
2806}
2807#endif
2808
2809/* Print an action to the given file descriptor. Return FALSE if
2810** nothing was actually printed.
2811*/
2812int PrintAction(struct action *ap, FILE *fp, int indent){
2813 int result = 1;
2814 switch( ap->type ){
2815 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002816 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002817 break;
2818 case REDUCE:
2819 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2820 break;
2821 case ACCEPT:
2822 fprintf(fp,"%*s accept",indent,ap->sp->name);
2823 break;
2824 case ERROR:
2825 fprintf(fp,"%*s error",indent,ap->sp->name);
2826 break;
2827 case CONFLICT:
2828 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2829 indent,ap->sp->name,ap->x.rp->index);
2830 break;
2831 case SH_RESOLVED:
2832 case RD_RESOLVED:
2833 case NOT_USED:
2834 result = 0;
2835 break;
2836 }
2837 return result;
2838}
2839
2840/* Generate the "y.output" log file */
2841void ReportOutput(lemp)
2842struct lemon *lemp;
2843{
2844 int i;
2845 struct state *stp;
2846 struct config *cfp;
2847 struct action *ap;
2848 FILE *fp;
2849
drh2aa6ca42004-09-10 00:14:04 +00002850 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002851 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002852 for(i=0; i<lemp->nstate; i++){
2853 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002854 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002855 if( lemp->basisflag ) cfp=stp->bp;
2856 else cfp=stp->cfp;
2857 while( cfp ){
2858 char buf[20];
2859 if( cfp->dot==cfp->rp->nrhs ){
2860 sprintf(buf,"(%d)",cfp->rp->index);
2861 fprintf(fp," %5s ",buf);
2862 }else{
2863 fprintf(fp," ");
2864 }
2865 ConfigPrint(fp,cfp);
2866 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002867#if 0
drh75897232000-05-29 14:26:00 +00002868 SetPrint(fp,cfp->fws,lemp);
2869 PlinkPrint(fp,cfp->fplp,"To ");
2870 PlinkPrint(fp,cfp->bplp,"From");
2871#endif
2872 if( lemp->basisflag ) cfp=cfp->bp;
2873 else cfp=cfp->next;
2874 }
2875 fprintf(fp,"\n");
2876 for(ap=stp->ap; ap; ap=ap->next){
2877 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2878 }
2879 fprintf(fp,"\n");
2880 }
drhe9278182007-07-18 18:16:29 +00002881 fprintf(fp, "----------------------------------------------------\n");
2882 fprintf(fp, "Symbols:\n");
2883 for(i=0; i<lemp->nsymbol; i++){
2884 int j;
2885 struct symbol *sp;
2886
2887 sp = lemp->symbols[i];
2888 fprintf(fp, " %3d: %s", i, sp->name);
2889 if( sp->type==NONTERMINAL ){
2890 fprintf(fp, ":");
2891 if( sp->lambda ){
2892 fprintf(fp, " <lambda>");
2893 }
2894 for(j=0; j<lemp->nterminal; j++){
2895 if( sp->firstset && SetFind(sp->firstset, j) ){
2896 fprintf(fp, " %s", lemp->symbols[j]->name);
2897 }
2898 }
2899 }
2900 fprintf(fp, "\n");
2901 }
drh75897232000-05-29 14:26:00 +00002902 fclose(fp);
2903 return;
2904}
2905
2906/* Search for the file "name" which is in the same directory as
2907** the exacutable */
2908PRIVATE char *pathsearch(argv0,name,modemask)
2909char *argv0;
2910char *name;
2911int modemask;
2912{
2913 char *pathlist;
2914 char *path,*cp;
2915 char c;
drh75897232000-05-29 14:26:00 +00002916
2917#ifdef __WIN32__
2918 cp = strrchr(argv0,'\\');
2919#else
2920 cp = strrchr(argv0,'/');
2921#endif
2922 if( cp ){
2923 c = *cp;
2924 *cp = 0;
2925 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2926 if( path ) sprintf(path,"%s/%s",argv0,name);
2927 *cp = c;
2928 }else{
2929 extern char *getenv();
2930 pathlist = getenv("PATH");
2931 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2932 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2933 if( path!=0 ){
2934 while( *pathlist ){
2935 cp = strchr(pathlist,':');
2936 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2937 c = *cp;
2938 *cp = 0;
2939 sprintf(path,"%s/%s",pathlist,name);
2940 *cp = c;
2941 if( c==0 ) pathlist = "";
2942 else pathlist = &cp[1];
2943 if( access(path,modemask)==0 ) break;
2944 }
2945 }
2946 }
2947 return path;
2948}
2949
2950/* Given an action, compute the integer value for that action
2951** which is to be put in the action table of the generated machine.
2952** Return negative if no action should be generated.
2953*/
2954PRIVATE int compute_action(lemp,ap)
2955struct lemon *lemp;
2956struct action *ap;
2957{
2958 int act;
2959 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00002960 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00002961 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2962 case ERROR: act = lemp->nstate + lemp->nrule; break;
2963 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2964 default: act = -1; break;
2965 }
2966 return act;
2967}
2968
2969#define LINESIZE 1000
2970/* The next cluster of routines are for reading the template file
2971** and writing the results to the generated parser */
2972/* The first function transfers data from "in" to "out" until
2973** a line is seen which begins with "%%". The line number is
2974** tracked.
2975**
2976** if name!=0, then any word that begin with "Parse" is changed to
2977** begin with *name instead.
2978*/
2979PRIVATE void tplt_xfer(name,in,out,lineno)
2980char *name;
2981FILE *in;
2982FILE *out;
2983int *lineno;
2984{
2985 int i, iStart;
2986 char line[LINESIZE];
2987 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2988 (*lineno)++;
2989 iStart = 0;
2990 if( name ){
2991 for(i=0; line[i]; i++){
2992 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2993 && (i==0 || !isalpha(line[i-1]))
2994 ){
2995 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2996 fprintf(out,"%s",name);
2997 i += 4;
2998 iStart = i+1;
2999 }
3000 }
3001 }
3002 fprintf(out,"%s",&line[iStart]);
3003 }
3004}
3005
3006/* The next function finds the template file and opens it, returning
3007** a pointer to the opened file. */
3008PRIVATE FILE *tplt_open(lemp)
3009struct lemon *lemp;
3010{
3011 static char templatename[] = "lempar.c";
3012 char buf[1000];
3013 FILE *in;
3014 char *tpltname;
3015 char *cp;
3016
3017 cp = strrchr(lemp->filename,'.');
3018 if( cp ){
drh8b582012003-10-21 13:16:03 +00003019 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003020 }else{
3021 sprintf(buf,"%s.lt",lemp->filename);
3022 }
3023 if( access(buf,004)==0 ){
3024 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003025 }else if( access(templatename,004)==0 ){
3026 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003027 }else{
3028 tpltname = pathsearch(lemp->argv0,templatename,0);
3029 }
3030 if( tpltname==0 ){
3031 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3032 templatename);
3033 lemp->errorcnt++;
3034 return 0;
3035 }
drh2aa6ca42004-09-10 00:14:04 +00003036 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003037 if( in==0 ){
3038 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3039 lemp->errorcnt++;
3040 return 0;
3041 }
3042 return in;
3043}
3044
drhaf805ca2004-09-07 11:28:25 +00003045/* Print a #line directive line to the output file. */
3046PRIVATE void tplt_linedir(out,lineno,filename)
3047FILE *out;
3048int lineno;
3049char *filename;
3050{
3051 fprintf(out,"#line %d \"",lineno);
3052 while( *filename ){
3053 if( *filename == '\\' ) putc('\\',out);
3054 putc(*filename,out);
3055 filename++;
3056 }
3057 fprintf(out,"\"\n");
3058}
3059
drh75897232000-05-29 14:26:00 +00003060/* Print a string to the file and keep the linenumber up to date */
3061PRIVATE void tplt_print(out,lemp,str,strln,lineno)
3062FILE *out;
3063struct lemon *lemp;
3064char *str;
3065int strln;
3066int *lineno;
3067{
3068 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003069 tplt_linedir(out,strln,lemp->filename);
3070 (*lineno)++;
drh75897232000-05-29 14:26:00 +00003071 while( *str ){
3072 if( *str=='\n' ) (*lineno)++;
3073 putc(*str,out);
3074 str++;
3075 }
drh9db55df2004-09-09 14:01:21 +00003076 if( str[-1]!='\n' ){
3077 putc('\n',out);
3078 (*lineno)++;
3079 }
drhaf805ca2004-09-07 11:28:25 +00003080 tplt_linedir(out,*lineno+2,lemp->outname);
3081 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00003082 return;
3083}
3084
3085/*
3086** The following routine emits code for the destructor for the
3087** symbol sp
3088*/
3089void emit_destructor_code(out,sp,lemp,lineno)
3090FILE *out;
3091struct symbol *sp;
3092struct lemon *lemp;
3093int *lineno;
3094{
drhcc83b6e2004-04-23 23:38:42 +00003095 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003096
3097 int linecnt = 0;
3098 if( sp->type==TERMINAL ){
3099 cp = lemp->tokendest;
3100 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003101 tplt_linedir(out,lemp->tokendestln,lemp->filename);
3102 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00003103 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003104 cp = sp->destructor;
drhaf805ca2004-09-07 11:28:25 +00003105 tplt_linedir(out,sp->destructorln,lemp->filename);
3106 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00003107 }else if( lemp->vardest ){
3108 cp = lemp->vardest;
3109 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003110 tplt_linedir(out,lemp->vardestln,lemp->filename);
3111 fprintf(out,"{");
drhcc83b6e2004-04-23 23:38:42 +00003112 }else{
3113 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003114 }
3115 for(; *cp; cp++){
3116 if( *cp=='$' && cp[1]=='$' ){
3117 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3118 cp++;
3119 continue;
3120 }
3121 if( *cp=='\n' ) linecnt++;
3122 fputc(*cp,out);
3123 }
3124 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003125 fprintf(out,"}\n");
3126 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003127 return;
3128}
3129
3130/*
drh960e8c62001-04-03 16:53:21 +00003131** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003132*/
3133int has_destructor(sp, lemp)
3134struct symbol *sp;
3135struct lemon *lemp;
3136{
3137 int ret;
3138 if( sp->type==TERMINAL ){
3139 ret = lemp->tokendest!=0;
3140 }else{
drh960e8c62001-04-03 16:53:21 +00003141 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003142 }
3143 return ret;
3144}
3145
drh0bb132b2004-07-20 14:06:51 +00003146/*
3147** Append text to a dynamically allocated string. If zText is 0 then
3148** reset the string to be empty again. Always return the complete text
3149** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003150**
3151** n bytes of zText are stored. If n==0 then all of zText up to the first
3152** \000 terminator is stored. zText can contain up to two instances of
3153** %d. The values of p1 and p2 are written into the first and second
3154** %d.
3155**
3156** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003157*/
3158PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3159 static char *z = 0;
3160 static int alloced = 0;
3161 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003162 int c;
drh0bb132b2004-07-20 14:06:51 +00003163 char zInt[40];
3164
3165 if( zText==0 ){
3166 used = 0;
3167 return z;
3168 }
drh7ac25c72004-08-19 15:12:26 +00003169 if( n<=0 ){
3170 if( n<0 ){
3171 used += n;
3172 assert( used>=0 );
3173 }
3174 n = strlen(zText);
3175 }
drh0bb132b2004-07-20 14:06:51 +00003176 if( n+sizeof(zInt)*2+used >= alloced ){
3177 alloced = n + sizeof(zInt)*2 + used + 200;
3178 z = realloc(z, alloced);
3179 }
3180 if( z==0 ) return "";
3181 while( n-- > 0 ){
3182 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003183 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003184 sprintf(zInt, "%d", p1);
3185 p1 = p2;
3186 strcpy(&z[used], zInt);
3187 used += strlen(&z[used]);
3188 zText++;
3189 n--;
3190 }else{
3191 z[used++] = c;
3192 }
3193 }
3194 z[used] = 0;
3195 return z;
3196}
3197
3198/*
3199** zCode is a string that is the action associated with a rule. Expand
3200** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003201** stack.
drh0bb132b2004-07-20 14:06:51 +00003202*/
drhaf805ca2004-09-07 11:28:25 +00003203PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003204 char *cp, *xp;
3205 int i;
3206 char lhsused = 0; /* True if the LHS element has been used */
3207 char used[MAXRHS]; /* True for each RHS element which is used */
3208
3209 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3210 lhsused = 0;
3211
drh19c9e562007-03-29 20:13:53 +00003212 if( rp->code==0 ){
3213 rp->code = "\n";
3214 rp->line = rp->ruleline;
3215 }
3216
drh0bb132b2004-07-20 14:06:51 +00003217 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003218 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003219 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3220 char saved;
3221 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3222 saved = *xp;
3223 *xp = 0;
3224 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003225 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003226 cp = xp;
3227 lhsused = 1;
3228 }else{
3229 for(i=0; i<rp->nrhs; i++){
3230 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003231 if( cp!=rp->code && cp[-1]=='@' ){
3232 /* If the argument is of the form @X then substituted
3233 ** the token number of X, not the value of X */
3234 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3235 }else{
drhfd405312005-11-06 04:06:59 +00003236 struct symbol *sp = rp->rhs[i];
3237 int dtnum;
3238 if( sp->type==MULTITERMINAL ){
3239 dtnum = sp->subsym[0]->dtnum;
3240 }else{
3241 dtnum = sp->dtnum;
3242 }
3243 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003244 }
drh0bb132b2004-07-20 14:06:51 +00003245 cp = xp;
3246 used[i] = 1;
3247 break;
3248 }
3249 }
3250 }
3251 *xp = saved;
3252 }
3253 append_str(cp, 1, 0, 0);
3254 } /* End loop */
3255
3256 /* Check to make sure the LHS has been used */
3257 if( rp->lhsalias && !lhsused ){
3258 ErrorMsg(lemp->filename,rp->ruleline,
3259 "Label \"%s\" for \"%s(%s)\" is never used.",
3260 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3261 lemp->errorcnt++;
3262 }
3263
3264 /* Generate destructor code for RHS symbols which are not used in the
3265 ** reduce code */
3266 for(i=0; i<rp->nrhs; i++){
3267 if( rp->rhsalias[i] && !used[i] ){
3268 ErrorMsg(lemp->filename,rp->ruleline,
3269 "Label %s for \"%s(%s)\" is never used.",
3270 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3271 lemp->errorcnt++;
3272 }else if( rp->rhsalias[i]==0 ){
3273 if( has_destructor(rp->rhs[i],lemp) ){
drh7ac25c72004-08-19 15:12:26 +00003274 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003275 rp->rhs[i]->index,i-rp->nrhs+1);
3276 }else{
3277 /* No destructor defined for this term */
3278 }
3279 }
3280 }
drh61e339a2007-01-16 03:09:02 +00003281 if( rp->code ){
3282 cp = append_str(0,0,0,0);
3283 rp->code = Strsafe(cp?cp:"");
3284 }
drh0bb132b2004-07-20 14:06:51 +00003285}
3286
drh75897232000-05-29 14:26:00 +00003287/*
3288** Generate code which executes when the rule "rp" is reduced. Write
3289** the code to "out". Make sure lineno stays up-to-date.
3290*/
3291PRIVATE void emit_code(out,rp,lemp,lineno)
3292FILE *out;
3293struct rule *rp;
3294struct lemon *lemp;
3295int *lineno;
3296{
drh0bb132b2004-07-20 14:06:51 +00003297 char *cp;
drh75897232000-05-29 14:26:00 +00003298 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003299
3300 /* Generate code to do the reduce action */
3301 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003302 tplt_linedir(out,rp->line,lemp->filename);
3303 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003304 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003305 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003306 } /* End loop */
3307 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003308 fprintf(out,"}\n");
3309 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003310 } /* End if( rp->code ) */
3311
drh75897232000-05-29 14:26:00 +00003312 return;
3313}
3314
3315/*
3316** Print the definition of the union used for the parser's data stack.
3317** This union contains fields for every possible data type for tokens
3318** and nonterminals. In the process of computing and printing this
3319** union, also set the ".dtnum" field of every terminal and nonterminal
3320** symbol.
3321*/
3322void print_stack_union(out,lemp,plineno,mhflag)
3323FILE *out; /* The output stream */
3324struct lemon *lemp; /* The main info structure for this parser */
3325int *plineno; /* Pointer to the line number */
3326int mhflag; /* True if generating makeheaders output */
3327{
3328 int lineno = *plineno; /* The line number of the output */
3329 char **types; /* A hash table of datatypes */
3330 int arraysize; /* Size of the "types" array */
3331 int maxdtlength; /* Maximum length of any ".datatype" field. */
3332 char *stddt; /* Standardized name for a datatype */
3333 int i,j; /* Loop counters */
3334 int hash; /* For hashing the name of a type */
3335 char *name; /* Name of the parser */
3336
3337 /* Allocate and initialize types[] and allocate stddt[] */
3338 arraysize = lemp->nsymbol * 2;
3339 types = (char**)malloc( arraysize * sizeof(char*) );
3340 for(i=0; i<arraysize; i++) types[i] = 0;
3341 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003342 if( lemp->vartype ){
3343 maxdtlength = strlen(lemp->vartype);
3344 }
drh75897232000-05-29 14:26:00 +00003345 for(i=0; i<lemp->nsymbol; i++){
3346 int len;
3347 struct symbol *sp = lemp->symbols[i];
3348 if( sp->datatype==0 ) continue;
3349 len = strlen(sp->datatype);
3350 if( len>maxdtlength ) maxdtlength = len;
3351 }
3352 stddt = (char*)malloc( maxdtlength*2 + 1 );
3353 if( types==0 || stddt==0 ){
3354 fprintf(stderr,"Out of memory.\n");
3355 exit(1);
3356 }
3357
3358 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3359 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003360 ** used for terminal symbols. If there is no %default_type defined then
3361 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3362 ** a datatype using the %type directive.
3363 */
drh75897232000-05-29 14:26:00 +00003364 for(i=0; i<lemp->nsymbol; i++){
3365 struct symbol *sp = lemp->symbols[i];
3366 char *cp;
3367 if( sp==lemp->errsym ){
3368 sp->dtnum = arraysize+1;
3369 continue;
3370 }
drh960e8c62001-04-03 16:53:21 +00003371 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003372 sp->dtnum = 0;
3373 continue;
3374 }
3375 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003376 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003377 j = 0;
3378 while( isspace(*cp) ) cp++;
3379 while( *cp ) stddt[j++] = *cp++;
3380 while( j>0 && isspace(stddt[j-1]) ) j--;
3381 stddt[j] = 0;
3382 hash = 0;
3383 for(j=0; stddt[j]; j++){
3384 hash = hash*53 + stddt[j];
3385 }
drh3b2129c2003-05-13 00:34:21 +00003386 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003387 while( types[hash] ){
3388 if( strcmp(types[hash],stddt)==0 ){
3389 sp->dtnum = hash + 1;
3390 break;
3391 }
3392 hash++;
3393 if( hash>=arraysize ) hash = 0;
3394 }
3395 if( types[hash]==0 ){
3396 sp->dtnum = hash + 1;
3397 types[hash] = (char*)malloc( strlen(stddt)+1 );
3398 if( types[hash]==0 ){
3399 fprintf(stderr,"Out of memory.\n");
3400 exit(1);
3401 }
3402 strcpy(types[hash],stddt);
3403 }
3404 }
3405
3406 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3407 name = lemp->name ? lemp->name : "Parse";
3408 lineno = *plineno;
3409 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3410 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3411 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3412 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3413 fprintf(out,"typedef union {\n"); lineno++;
3414 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3415 for(i=0; i<arraysize; i++){
3416 if( types[i]==0 ) continue;
3417 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3418 free(types[i]);
3419 }
3420 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3421 free(stddt);
3422 free(types);
3423 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3424 *plineno = lineno;
3425}
3426
drhb29b0a52002-02-23 19:39:46 +00003427/*
3428** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003429** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003430*/
drh8b582012003-10-21 13:16:03 +00003431static const char *minimum_size_type(int lwr, int upr){
3432 if( lwr>=0 ){
3433 if( upr<=255 ){
3434 return "unsigned char";
3435 }else if( upr<65535 ){
3436 return "unsigned short int";
3437 }else{
3438 return "unsigned int";
3439 }
3440 }else if( lwr>=-127 && upr<=127 ){
3441 return "signed char";
3442 }else if( lwr>=-32767 && upr<32767 ){
3443 return "short";
drhb29b0a52002-02-23 19:39:46 +00003444 }else{
drh8b582012003-10-21 13:16:03 +00003445 return "int";
drhb29b0a52002-02-23 19:39:46 +00003446 }
3447}
3448
drhfdbf9282003-10-21 16:34:41 +00003449/*
3450** Each state contains a set of token transaction and a set of
3451** nonterminal transactions. Each of these sets makes an instance
3452** of the following structure. An array of these structures is used
3453** to order the creation of entries in the yy_action[] table.
3454*/
3455struct axset {
3456 struct state *stp; /* A pointer to a state */
3457 int isTkn; /* True to use tokens. False for non-terminals */
3458 int nAction; /* Number of actions */
3459};
3460
3461/*
3462** Compare to axset structures for sorting purposes
3463*/
3464static int axset_compare(const void *a, const void *b){
3465 struct axset *p1 = (struct axset*)a;
3466 struct axset *p2 = (struct axset*)b;
3467 return p2->nAction - p1->nAction;
3468}
3469
drh75897232000-05-29 14:26:00 +00003470/* Generate C source code for the parser */
3471void ReportTable(lemp, mhflag)
3472struct lemon *lemp;
3473int mhflag; /* Output in makeheaders format if true */
3474{
3475 FILE *out, *in;
3476 char line[LINESIZE];
3477 int lineno;
3478 struct state *stp;
3479 struct action *ap;
3480 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003481 struct acttab *pActtab;
3482 int i, j, n;
drh75897232000-05-29 14:26:00 +00003483 char *name;
drh8b582012003-10-21 13:16:03 +00003484 int mnTknOfst, mxTknOfst;
3485 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003486 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003487
3488 in = tplt_open(lemp);
3489 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003490 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003491 if( out==0 ){
3492 fclose(in);
3493 return;
3494 }
3495 lineno = 1;
3496 tplt_xfer(lemp->name,in,out,&lineno);
3497
3498 /* Generate the include code, if any */
3499 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3500 if( mhflag ){
3501 char *name = file_makename(lemp, ".h");
3502 fprintf(out,"#include \"%s\"\n", name); lineno++;
3503 free(name);
3504 }
3505 tplt_xfer(lemp->name,in,out,&lineno);
3506
3507 /* Generate #defines for all tokens */
3508 if( mhflag ){
3509 char *prefix;
3510 fprintf(out,"#if INTERFACE\n"); lineno++;
3511 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3512 else prefix = "";
3513 for(i=1; i<lemp->nterminal; i++){
3514 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3515 lineno++;
3516 }
3517 fprintf(out,"#endif\n"); lineno++;
3518 }
3519 tplt_xfer(lemp->name,in,out,&lineno);
3520
3521 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003522 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003523 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003524 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3525 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003526 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003527 if( lemp->wildcard ){
3528 fprintf(out,"#define YYWILDCARD %d\n",
3529 lemp->wildcard->index); lineno++;
3530 }
drh75897232000-05-29 14:26:00 +00003531 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003532 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003533 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003534 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3535 }else{
3536 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3537 }
drhca44b5a2007-02-22 23:06:58 +00003538 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003539 if( mhflag ){
3540 fprintf(out,"#if INTERFACE\n"); lineno++;
3541 }
3542 name = lemp->name ? lemp->name : "Parse";
3543 if( lemp->arg && lemp->arg[0] ){
3544 int i;
3545 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003546 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3547 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003548 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3549 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3550 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3551 name,lemp->arg,&lemp->arg[i]); lineno++;
3552 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3553 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003554 }else{
drh1f245e42002-03-11 13:55:50 +00003555 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3556 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3557 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3558 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003559 }
3560 if( mhflag ){
3561 fprintf(out,"#endif\n"); lineno++;
3562 }
3563 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3564 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3565 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3566 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drh0bd1f4e2002-06-06 18:54:39 +00003567 if( lemp->has_fallback ){
3568 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3569 }
drh75897232000-05-29 14:26:00 +00003570 tplt_xfer(lemp->name,in,out,&lineno);
3571
drh8b582012003-10-21 13:16:03 +00003572 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003573 **
drh8b582012003-10-21 13:16:03 +00003574 ** yy_action[] A single table containing all actions.
3575 ** yy_lookahead[] A table containing the lookahead for each entry in
3576 ** yy_action. Used to detect hash collisions.
3577 ** yy_shift_ofst[] For each state, the offset into yy_action for
3578 ** shifting terminals.
3579 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3580 ** shifting non-terminals after a reduce.
3581 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003582 */
drh75897232000-05-29 14:26:00 +00003583
drh8b582012003-10-21 13:16:03 +00003584 /* Compute the actions on all states and count them up */
drhfdbf9282003-10-21 16:34:41 +00003585 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3586 if( ax==0 ){
3587 fprintf(stderr,"malloc failed\n");
3588 exit(1);
3589 }
drh75897232000-05-29 14:26:00 +00003590 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003591 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003592 ax[i*2].stp = stp;
3593 ax[i*2].isTkn = 1;
3594 ax[i*2].nAction = stp->nTknAct;
3595 ax[i*2+1].stp = stp;
3596 ax[i*2+1].isTkn = 0;
3597 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003598 }
drh8b582012003-10-21 13:16:03 +00003599 mxTknOfst = mnTknOfst = 0;
3600 mxNtOfst = mnNtOfst = 0;
3601
drhfdbf9282003-10-21 16:34:41 +00003602 /* Compute the action table. In order to try to keep the size of the
3603 ** action table to a minimum, the heuristic of placing the largest action
3604 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003605 */
drhfdbf9282003-10-21 16:34:41 +00003606 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003607 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003608 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3609 stp = ax[i].stp;
3610 if( ax[i].isTkn ){
3611 for(ap=stp->ap; ap; ap=ap->next){
3612 int action;
3613 if( ap->sp->index>=lemp->nterminal ) continue;
3614 action = compute_action(lemp, ap);
3615 if( action<0 ) continue;
3616 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003617 }
drhfdbf9282003-10-21 16:34:41 +00003618 stp->iTknOfst = acttab_insert(pActtab);
3619 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3620 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3621 }else{
3622 for(ap=stp->ap; ap; ap=ap->next){
3623 int action;
3624 if( ap->sp->index<lemp->nterminal ) continue;
3625 if( ap->sp->index==lemp->nsymbol ) continue;
3626 action = compute_action(lemp, ap);
3627 if( action<0 ) continue;
3628 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003629 }
drhfdbf9282003-10-21 16:34:41 +00003630 stp->iNtOfst = acttab_insert(pActtab);
3631 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3632 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003633 }
3634 }
drhfdbf9282003-10-21 16:34:41 +00003635 free(ax);
drh8b582012003-10-21 13:16:03 +00003636
3637 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003638 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003639 n = acttab_size(pActtab);
3640 for(i=j=0; i<n; i++){
3641 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003642 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003643 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003644 fprintf(out, " %4d,", action);
3645 if( j==9 || i==n-1 ){
3646 fprintf(out, "\n"); lineno++;
3647 j = 0;
3648 }else{
3649 j++;
3650 }
3651 }
3652 fprintf(out, "};\n"); lineno++;
3653
3654 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003655 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003656 for(i=j=0; i<n; i++){
3657 int la = acttab_yylookahead(pActtab, i);
3658 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003659 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003660 fprintf(out, " %4d,", la);
3661 if( j==9 || i==n-1 ){
3662 fprintf(out, "\n"); lineno++;
3663 j = 0;
3664 }else{
3665 j++;
3666 }
3667 }
3668 fprintf(out, "};\n"); lineno++;
3669
3670 /* Output the yy_shift_ofst[] table */
3671 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003672 n = lemp->nstate;
3673 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3674 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003675 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003676 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003677 for(i=j=0; i<n; i++){
3678 int ofst;
3679 stp = lemp->sorted[i];
3680 ofst = stp->iTknOfst;
3681 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003682 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003683 fprintf(out, " %4d,", ofst);
3684 if( j==9 || i==n-1 ){
3685 fprintf(out, "\n"); lineno++;
3686 j = 0;
3687 }else{
3688 j++;
3689 }
3690 }
3691 fprintf(out, "};\n"); lineno++;
3692
3693 /* Output the yy_reduce_ofst[] table */
3694 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003695 n = lemp->nstate;
3696 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3697 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003698 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003699 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003700 for(i=j=0; i<n; i++){
3701 int ofst;
3702 stp = lemp->sorted[i];
3703 ofst = stp->iNtOfst;
3704 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003705 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003706 fprintf(out, " %4d,", ofst);
3707 if( j==9 || i==n-1 ){
3708 fprintf(out, "\n"); lineno++;
3709 j = 0;
3710 }else{
3711 j++;
3712 }
3713 }
3714 fprintf(out, "};\n"); lineno++;
3715
3716 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003717 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003718 n = lemp->nstate;
3719 for(i=j=0; i<n; i++){
3720 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003721 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003722 fprintf(out, " %4d,", stp->iDflt);
3723 if( j==9 || i==n-1 ){
3724 fprintf(out, "\n"); lineno++;
3725 j = 0;
3726 }else{
3727 j++;
3728 }
3729 }
3730 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003731 tplt_xfer(lemp->name,in,out,&lineno);
3732
drh0bd1f4e2002-06-06 18:54:39 +00003733 /* Generate the table of fallback tokens.
3734 */
3735 if( lemp->has_fallback ){
3736 for(i=0; i<lemp->nterminal; i++){
3737 struct symbol *p = lemp->symbols[i];
3738 if( p->fallback==0 ){
3739 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3740 }else{
3741 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3742 p->name, p->fallback->name);
3743 }
3744 lineno++;
3745 }
3746 }
3747 tplt_xfer(lemp->name, in, out, &lineno);
3748
3749 /* Generate a table containing the symbolic name of every symbol
3750 */
drh75897232000-05-29 14:26:00 +00003751 for(i=0; i<lemp->nsymbol; i++){
3752 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3753 fprintf(out," %-15s",line);
3754 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3755 }
3756 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3757 tplt_xfer(lemp->name,in,out,&lineno);
3758
drh0bd1f4e2002-06-06 18:54:39 +00003759 /* Generate a table containing a text string that describes every
3760 ** rule in the rule set of the grammer. This information is used
3761 ** when tracing REDUCE actions.
3762 */
3763 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3764 assert( rp->index==i );
3765 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00003766 for(j=0; j<rp->nrhs; j++){
3767 struct symbol *sp = rp->rhs[j];
3768 fprintf(out," %s", sp->name);
3769 if( sp->type==MULTITERMINAL ){
3770 int k;
3771 for(k=1; k<sp->nsubsym; k++){
3772 fprintf(out,"|%s",sp->subsym[k]->name);
3773 }
3774 }
3775 }
drh0bd1f4e2002-06-06 18:54:39 +00003776 fprintf(out,"\",\n"); lineno++;
3777 }
3778 tplt_xfer(lemp->name,in,out,&lineno);
3779
drh75897232000-05-29 14:26:00 +00003780 /* Generate code which executes every time a symbol is popped from
3781 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003782 ** (In other words, generate the %destructor actions)
3783 */
drh75897232000-05-29 14:26:00 +00003784 if( lemp->tokendest ){
3785 for(i=0; i<lemp->nsymbol; i++){
3786 struct symbol *sp = lemp->symbols[i];
3787 if( sp==0 || sp->type!=TERMINAL ) continue;
3788 fprintf(out," case %d:\n",sp->index); lineno++;
3789 }
3790 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3791 if( i<lemp->nsymbol ){
3792 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3793 fprintf(out," break;\n"); lineno++;
3794 }
3795 }
drh8d659732005-01-13 23:54:06 +00003796 if( lemp->vardest ){
3797 struct symbol *dflt_sp = 0;
3798 for(i=0; i<lemp->nsymbol; i++){
3799 struct symbol *sp = lemp->symbols[i];
3800 if( sp==0 || sp->type==TERMINAL ||
3801 sp->index<=0 || sp->destructor!=0 ) continue;
3802 fprintf(out," case %d:\n",sp->index); lineno++;
3803 dflt_sp = sp;
3804 }
3805 if( dflt_sp!=0 ){
3806 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3807 fprintf(out," break;\n"); lineno++;
3808 }
3809 }
drh75897232000-05-29 14:26:00 +00003810 for(i=0; i<lemp->nsymbol; i++){
3811 struct symbol *sp = lemp->symbols[i];
3812 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3813 fprintf(out," case %d:\n",sp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003814
3815 /* Combine duplicate destructors into a single case */
3816 for(j=i+1; j<lemp->nsymbol; j++){
3817 struct symbol *sp2 = lemp->symbols[j];
3818 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3819 && sp2->dtnum==sp->dtnum
3820 && strcmp(sp->destructor,sp2->destructor)==0 ){
3821 fprintf(out," case %d:\n",sp2->index); lineno++;
3822 sp2->destructor = 0;
3823 }
3824 }
3825
drh75897232000-05-29 14:26:00 +00003826 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3827 fprintf(out," break;\n"); lineno++;
3828 }
drh75897232000-05-29 14:26:00 +00003829 tplt_xfer(lemp->name,in,out,&lineno);
3830
3831 /* Generate code which executes whenever the parser stack overflows */
3832 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3833 tplt_xfer(lemp->name,in,out,&lineno);
3834
3835 /* Generate the table of rule information
3836 **
3837 ** Note: This code depends on the fact that rules are number
3838 ** sequentually beginning with 0.
3839 */
3840 for(rp=lemp->rule; rp; rp=rp->next){
3841 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3842 }
3843 tplt_xfer(lemp->name,in,out,&lineno);
3844
3845 /* Generate code which execution during each REDUCE action */
3846 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003847 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003848 }
3849 for(rp=lemp->rule; rp; rp=rp->next){
3850 struct rule *rp2;
3851 if( rp->code==0 ) continue;
drh75897232000-05-29 14:26:00 +00003852 fprintf(out," case %d:\n",rp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003853 for(rp2=rp->next; rp2; rp2=rp2->next){
3854 if( rp2->code==rp->code ){
3855 fprintf(out," case %d:\n",rp2->index); lineno++;
3856 rp2->code = 0;
3857 }
3858 }
drh75897232000-05-29 14:26:00 +00003859 emit_code(out,rp,lemp,&lineno);
3860 fprintf(out," break;\n"); lineno++;
3861 }
3862 tplt_xfer(lemp->name,in,out,&lineno);
3863
3864 /* Generate code which executes if a parse fails */
3865 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3866 tplt_xfer(lemp->name,in,out,&lineno);
3867
3868 /* Generate code which executes when a syntax error occurs */
3869 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3870 tplt_xfer(lemp->name,in,out,&lineno);
3871
3872 /* Generate code which executes when the parser accepts its input */
3873 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3874 tplt_xfer(lemp->name,in,out,&lineno);
3875
3876 /* Append any addition code the user desires */
3877 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3878
3879 fclose(in);
3880 fclose(out);
3881 return;
3882}
3883
3884/* Generate a header file for the parser */
3885void ReportHeader(lemp)
3886struct lemon *lemp;
3887{
3888 FILE *out, *in;
3889 char *prefix;
3890 char line[LINESIZE];
3891 char pattern[LINESIZE];
3892 int i;
3893
3894 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3895 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003896 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003897 if( in ){
3898 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3899 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3900 if( strcmp(line,pattern) ) break;
3901 }
3902 fclose(in);
3903 if( i==lemp->nterminal ){
3904 /* No change in the file. Don't rewrite it. */
3905 return;
3906 }
3907 }
drh2aa6ca42004-09-10 00:14:04 +00003908 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003909 if( out ){
3910 for(i=1; i<lemp->nterminal; i++){
3911 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3912 }
3913 fclose(out);
3914 }
3915 return;
3916}
3917
3918/* Reduce the size of the action tables, if possible, by making use
3919** of defaults.
3920**
drhb59499c2002-02-23 18:45:13 +00003921** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00003922** it the default. Except, there is no default if the wildcard token
3923** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00003924*/
3925void CompressTables(lemp)
3926struct lemon *lemp;
3927{
3928 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003929 struct action *ap, *ap2;
3930 struct rule *rp, *rp2, *rbest;
3931 int nbest, n;
drh75897232000-05-29 14:26:00 +00003932 int i;
drhe09daa92006-06-10 13:29:31 +00003933 int usesWildcard;
drh75897232000-05-29 14:26:00 +00003934
3935 for(i=0; i<lemp->nstate; i++){
3936 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003937 nbest = 0;
3938 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00003939 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00003940
drhb59499c2002-02-23 18:45:13 +00003941 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00003942 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
3943 usesWildcard = 1;
3944 }
drhb59499c2002-02-23 18:45:13 +00003945 if( ap->type!=REDUCE ) continue;
3946 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00003947 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00003948 if( rp==rbest ) continue;
3949 n = 1;
3950 for(ap2=ap->next; ap2; ap2=ap2->next){
3951 if( ap2->type!=REDUCE ) continue;
3952 rp2 = ap2->x.rp;
3953 if( rp2==rbest ) continue;
3954 if( rp2==rp ) n++;
3955 }
3956 if( n>nbest ){
3957 nbest = n;
3958 rbest = rp;
drh75897232000-05-29 14:26:00 +00003959 }
3960 }
drhb59499c2002-02-23 18:45:13 +00003961
3962 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00003963 ** is not at least 1 or if the wildcard token is a possible
3964 ** lookahead.
3965 */
3966 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00003967
drhb59499c2002-02-23 18:45:13 +00003968
3969 /* Combine matching REDUCE actions into a single default */
3970 for(ap=stp->ap; ap; ap=ap->next){
3971 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3972 }
drh75897232000-05-29 14:26:00 +00003973 assert( ap );
3974 ap->sp = Symbol_new("{default}");
3975 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003976 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003977 }
3978 stp->ap = Action_sort(stp->ap);
3979 }
3980}
drhb59499c2002-02-23 18:45:13 +00003981
drhada354d2005-11-05 15:03:59 +00003982
3983/*
3984** Compare two states for sorting purposes. The smaller state is the
3985** one with the most non-terminal actions. If they have the same number
3986** of non-terminal actions, then the smaller is the one with the most
3987** token actions.
3988*/
3989static int stateResortCompare(const void *a, const void *b){
3990 const struct state *pA = *(const struct state**)a;
3991 const struct state *pB = *(const struct state**)b;
3992 int n;
3993
3994 n = pB->nNtAct - pA->nNtAct;
3995 if( n==0 ){
3996 n = pB->nTknAct - pA->nTknAct;
3997 }
3998 return n;
3999}
4000
4001
4002/*
4003** Renumber and resort states so that states with fewer choices
4004** occur at the end. Except, keep state 0 as the first state.
4005*/
4006void ResortStates(lemp)
4007struct lemon *lemp;
4008{
4009 int i;
4010 struct state *stp;
4011 struct action *ap;
4012
4013 for(i=0; i<lemp->nstate; i++){
4014 stp = lemp->sorted[i];
4015 stp->nTknAct = stp->nNtAct = 0;
4016 stp->iDflt = lemp->nstate + lemp->nrule;
4017 stp->iTknOfst = NO_OFFSET;
4018 stp->iNtOfst = NO_OFFSET;
4019 for(ap=stp->ap; ap; ap=ap->next){
4020 if( compute_action(lemp,ap)>=0 ){
4021 if( ap->sp->index<lemp->nterminal ){
4022 stp->nTknAct++;
4023 }else if( ap->sp->index<lemp->nsymbol ){
4024 stp->nNtAct++;
4025 }else{
4026 stp->iDflt = compute_action(lemp, ap);
4027 }
4028 }
4029 }
4030 }
4031 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4032 stateResortCompare);
4033 for(i=0; i<lemp->nstate; i++){
4034 lemp->sorted[i]->statenum = i;
4035 }
4036}
4037
4038
drh75897232000-05-29 14:26:00 +00004039/***************** From the file "set.c" ************************************/
4040/*
4041** Set manipulation routines for the LEMON parser generator.
4042*/
4043
4044static int size = 0;
4045
4046/* Set the set size */
4047void SetSize(n)
4048int n;
4049{
4050 size = n+1;
4051}
4052
4053/* Allocate a new set */
4054char *SetNew(){
4055 char *s;
4056 int i;
4057 s = (char*)malloc( size );
4058 if( s==0 ){
4059 extern void memory_error();
4060 memory_error();
4061 }
4062 for(i=0; i<size; i++) s[i] = 0;
4063 return s;
4064}
4065
4066/* Deallocate a set */
4067void SetFree(s)
4068char *s;
4069{
4070 free(s);
4071}
4072
4073/* Add a new element to the set. Return TRUE if the element was added
4074** and FALSE if it was already there. */
4075int SetAdd(s,e)
4076char *s;
4077int e;
4078{
4079 int rv;
4080 rv = s[e];
4081 s[e] = 1;
4082 return !rv;
4083}
4084
4085/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4086int SetUnion(s1,s2)
4087char *s1;
4088char *s2;
4089{
4090 int i, progress;
4091 progress = 0;
4092 for(i=0; i<size; i++){
4093 if( s2[i]==0 ) continue;
4094 if( s1[i]==0 ){
4095 progress = 1;
4096 s1[i] = 1;
4097 }
4098 }
4099 return progress;
4100}
4101/********************** From the file "table.c" ****************************/
4102/*
4103** All code in this file has been automatically generated
4104** from a specification in the file
4105** "table.q"
4106** by the associative array code building program "aagen".
4107** Do not edit this file! Instead, edit the specification
4108** file, then rerun aagen.
4109*/
4110/*
4111** Code for processing tables in the LEMON parser generator.
4112*/
4113
4114PRIVATE int strhash(x)
4115char *x;
4116{
4117 int h = 0;
4118 while( *x) h = h*13 + *(x++);
4119 return h;
4120}
4121
4122/* Works like strdup, sort of. Save a string in malloced memory, but
4123** keep strings in a table so that the same string is not in more
4124** than one place.
4125*/
4126char *Strsafe(y)
4127char *y;
4128{
4129 char *z;
4130
drh916f75f2006-07-17 00:19:39 +00004131 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004132 z = Strsafe_find(y);
4133 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4134 strcpy(z,y);
4135 Strsafe_insert(z);
4136 }
4137 MemoryCheck(z);
4138 return z;
4139}
4140
4141/* There is one instance of the following structure for each
4142** associative array of type "x1".
4143*/
4144struct s_x1 {
4145 int size; /* The number of available slots. */
4146 /* Must be a power of 2 greater than or */
4147 /* equal to 1 */
4148 int count; /* Number of currently slots filled */
4149 struct s_x1node *tbl; /* The data stored here */
4150 struct s_x1node **ht; /* Hash table for lookups */
4151};
4152
4153/* There is one instance of this structure for every data element
4154** in an associative array of type "x1".
4155*/
4156typedef struct s_x1node {
4157 char *data; /* The data */
4158 struct s_x1node *next; /* Next entry with the same hash */
4159 struct s_x1node **from; /* Previous link */
4160} x1node;
4161
4162/* There is only one instance of the array, which is the following */
4163static struct s_x1 *x1a;
4164
4165/* Allocate a new associative array */
4166void Strsafe_init(){
4167 if( x1a ) return;
4168 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4169 if( x1a ){
4170 x1a->size = 1024;
4171 x1a->count = 0;
4172 x1a->tbl = (x1node*)malloc(
4173 (sizeof(x1node) + sizeof(x1node*))*1024 );
4174 if( x1a->tbl==0 ){
4175 free(x1a);
4176 x1a = 0;
4177 }else{
4178 int i;
4179 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4180 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4181 }
4182 }
4183}
4184/* Insert a new record into the array. Return TRUE if successful.
4185** Prior data with the same key is NOT overwritten */
4186int Strsafe_insert(data)
4187char *data;
4188{
4189 x1node *np;
4190 int h;
4191 int ph;
4192
4193 if( x1a==0 ) return 0;
4194 ph = strhash(data);
4195 h = ph & (x1a->size-1);
4196 np = x1a->ht[h];
4197 while( np ){
4198 if( strcmp(np->data,data)==0 ){
4199 /* An existing entry with the same key is found. */
4200 /* Fail because overwrite is not allows. */
4201 return 0;
4202 }
4203 np = np->next;
4204 }
4205 if( x1a->count>=x1a->size ){
4206 /* Need to make the hash table bigger */
4207 int i,size;
4208 struct s_x1 array;
4209 array.size = size = x1a->size*2;
4210 array.count = x1a->count;
4211 array.tbl = (x1node*)malloc(
4212 (sizeof(x1node) + sizeof(x1node*))*size );
4213 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4214 array.ht = (x1node**)&(array.tbl[size]);
4215 for(i=0; i<size; i++) array.ht[i] = 0;
4216 for(i=0; i<x1a->count; i++){
4217 x1node *oldnp, *newnp;
4218 oldnp = &(x1a->tbl[i]);
4219 h = strhash(oldnp->data) & (size-1);
4220 newnp = &(array.tbl[i]);
4221 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4222 newnp->next = array.ht[h];
4223 newnp->data = oldnp->data;
4224 newnp->from = &(array.ht[h]);
4225 array.ht[h] = newnp;
4226 }
4227 free(x1a->tbl);
4228 *x1a = array;
4229 }
4230 /* Insert the new data */
4231 h = ph & (x1a->size-1);
4232 np = &(x1a->tbl[x1a->count++]);
4233 np->data = data;
4234 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4235 np->next = x1a->ht[h];
4236 x1a->ht[h] = np;
4237 np->from = &(x1a->ht[h]);
4238 return 1;
4239}
4240
4241/* Return a pointer to data assigned to the given key. Return NULL
4242** if no such key. */
4243char *Strsafe_find(key)
4244char *key;
4245{
4246 int h;
4247 x1node *np;
4248
4249 if( x1a==0 ) return 0;
4250 h = strhash(key) & (x1a->size-1);
4251 np = x1a->ht[h];
4252 while( np ){
4253 if( strcmp(np->data,key)==0 ) break;
4254 np = np->next;
4255 }
4256 return np ? np->data : 0;
4257}
4258
4259/* Return a pointer to the (terminal or nonterminal) symbol "x".
4260** Create a new symbol if this is the first time "x" has been seen.
4261*/
4262struct symbol *Symbol_new(x)
4263char *x;
4264{
4265 struct symbol *sp;
4266
4267 sp = Symbol_find(x);
4268 if( sp==0 ){
4269 sp = (struct symbol *)malloc( sizeof(struct symbol) );
4270 MemoryCheck(sp);
4271 sp->name = Strsafe(x);
4272 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4273 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004274 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004275 sp->prec = -1;
4276 sp->assoc = UNK;
4277 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004278 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004279 sp->destructor = 0;
4280 sp->datatype = 0;
4281 Symbol_insert(sp,sp->name);
4282 }
4283 return sp;
4284}
4285
drh60d31652004-02-22 00:08:04 +00004286/* Compare two symbols for working purposes
4287**
4288** Symbols that begin with upper case letters (terminals or tokens)
4289** must sort before symbols that begin with lower case letters
4290** (non-terminals). Other than that, the order does not matter.
4291**
4292** We find experimentally that leaving the symbols in their original
4293** order (the order they appeared in the grammar file) gives the
4294** smallest parser tables in SQLite.
4295*/
4296int Symbolcmpp(struct symbol **a, struct symbol **b){
4297 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4298 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4299 return i1-i2;
drh75897232000-05-29 14:26:00 +00004300}
4301
4302/* There is one instance of the following structure for each
4303** associative array of type "x2".
4304*/
4305struct s_x2 {
4306 int size; /* The number of available slots. */
4307 /* Must be a power of 2 greater than or */
4308 /* equal to 1 */
4309 int count; /* Number of currently slots filled */
4310 struct s_x2node *tbl; /* The data stored here */
4311 struct s_x2node **ht; /* Hash table for lookups */
4312};
4313
4314/* There is one instance of this structure for every data element
4315** in an associative array of type "x2".
4316*/
4317typedef struct s_x2node {
4318 struct symbol *data; /* The data */
4319 char *key; /* The key */
4320 struct s_x2node *next; /* Next entry with the same hash */
4321 struct s_x2node **from; /* Previous link */
4322} x2node;
4323
4324/* There is only one instance of the array, which is the following */
4325static struct s_x2 *x2a;
4326
4327/* Allocate a new associative array */
4328void Symbol_init(){
4329 if( x2a ) return;
4330 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4331 if( x2a ){
4332 x2a->size = 128;
4333 x2a->count = 0;
4334 x2a->tbl = (x2node*)malloc(
4335 (sizeof(x2node) + sizeof(x2node*))*128 );
4336 if( x2a->tbl==0 ){
4337 free(x2a);
4338 x2a = 0;
4339 }else{
4340 int i;
4341 x2a->ht = (x2node**)&(x2a->tbl[128]);
4342 for(i=0; i<128; i++) x2a->ht[i] = 0;
4343 }
4344 }
4345}
4346/* Insert a new record into the array. Return TRUE if successful.
4347** Prior data with the same key is NOT overwritten */
4348int Symbol_insert(data,key)
4349struct symbol *data;
4350char *key;
4351{
4352 x2node *np;
4353 int h;
4354 int ph;
4355
4356 if( x2a==0 ) return 0;
4357 ph = strhash(key);
4358 h = ph & (x2a->size-1);
4359 np = x2a->ht[h];
4360 while( np ){
4361 if( strcmp(np->key,key)==0 ){
4362 /* An existing entry with the same key is found. */
4363 /* Fail because overwrite is not allows. */
4364 return 0;
4365 }
4366 np = np->next;
4367 }
4368 if( x2a->count>=x2a->size ){
4369 /* Need to make the hash table bigger */
4370 int i,size;
4371 struct s_x2 array;
4372 array.size = size = x2a->size*2;
4373 array.count = x2a->count;
4374 array.tbl = (x2node*)malloc(
4375 (sizeof(x2node) + sizeof(x2node*))*size );
4376 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4377 array.ht = (x2node**)&(array.tbl[size]);
4378 for(i=0; i<size; i++) array.ht[i] = 0;
4379 for(i=0; i<x2a->count; i++){
4380 x2node *oldnp, *newnp;
4381 oldnp = &(x2a->tbl[i]);
4382 h = strhash(oldnp->key) & (size-1);
4383 newnp = &(array.tbl[i]);
4384 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4385 newnp->next = array.ht[h];
4386 newnp->key = oldnp->key;
4387 newnp->data = oldnp->data;
4388 newnp->from = &(array.ht[h]);
4389 array.ht[h] = newnp;
4390 }
4391 free(x2a->tbl);
4392 *x2a = array;
4393 }
4394 /* Insert the new data */
4395 h = ph & (x2a->size-1);
4396 np = &(x2a->tbl[x2a->count++]);
4397 np->key = key;
4398 np->data = data;
4399 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4400 np->next = x2a->ht[h];
4401 x2a->ht[h] = np;
4402 np->from = &(x2a->ht[h]);
4403 return 1;
4404}
4405
4406/* Return a pointer to data assigned to the given key. Return NULL
4407** if no such key. */
4408struct symbol *Symbol_find(key)
4409char *key;
4410{
4411 int h;
4412 x2node *np;
4413
4414 if( x2a==0 ) return 0;
4415 h = strhash(key) & (x2a->size-1);
4416 np = x2a->ht[h];
4417 while( np ){
4418 if( strcmp(np->key,key)==0 ) break;
4419 np = np->next;
4420 }
4421 return np ? np->data : 0;
4422}
4423
4424/* Return the n-th data. Return NULL if n is out of range. */
4425struct symbol *Symbol_Nth(n)
4426int n;
4427{
4428 struct symbol *data;
4429 if( x2a && n>0 && n<=x2a->count ){
4430 data = x2a->tbl[n-1].data;
4431 }else{
4432 data = 0;
4433 }
4434 return data;
4435}
4436
4437/* Return the size of the array */
4438int Symbol_count()
4439{
4440 return x2a ? x2a->count : 0;
4441}
4442
4443/* Return an array of pointers to all data in the table.
4444** The array is obtained from malloc. Return NULL if memory allocation
4445** problems, or if the array is empty. */
4446struct symbol **Symbol_arrayof()
4447{
4448 struct symbol **array;
4449 int i,size;
4450 if( x2a==0 ) return 0;
4451 size = x2a->count;
4452 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4453 if( array ){
4454 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4455 }
4456 return array;
4457}
4458
4459/* Compare two configurations */
4460int Configcmp(a,b)
4461struct config *a;
4462struct config *b;
4463{
4464 int x;
4465 x = a->rp->index - b->rp->index;
4466 if( x==0 ) x = a->dot - b->dot;
4467 return x;
4468}
4469
4470/* Compare two states */
4471PRIVATE int statecmp(a,b)
4472struct config *a;
4473struct config *b;
4474{
4475 int rc;
4476 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4477 rc = a->rp->index - b->rp->index;
4478 if( rc==0 ) rc = a->dot - b->dot;
4479 }
4480 if( rc==0 ){
4481 if( a ) rc = 1;
4482 if( b ) rc = -1;
4483 }
4484 return rc;
4485}
4486
4487/* Hash a state */
4488PRIVATE int statehash(a)
4489struct config *a;
4490{
4491 int h=0;
4492 while( a ){
4493 h = h*571 + a->rp->index*37 + a->dot;
4494 a = a->bp;
4495 }
4496 return h;
4497}
4498
4499/* Allocate a new state structure */
4500struct state *State_new()
4501{
4502 struct state *new;
4503 new = (struct state *)malloc( sizeof(struct state) );
4504 MemoryCheck(new);
4505 return new;
4506}
4507
4508/* There is one instance of the following structure for each
4509** associative array of type "x3".
4510*/
4511struct s_x3 {
4512 int size; /* The number of available slots. */
4513 /* Must be a power of 2 greater than or */
4514 /* equal to 1 */
4515 int count; /* Number of currently slots filled */
4516 struct s_x3node *tbl; /* The data stored here */
4517 struct s_x3node **ht; /* Hash table for lookups */
4518};
4519
4520/* There is one instance of this structure for every data element
4521** in an associative array of type "x3".
4522*/
4523typedef struct s_x3node {
4524 struct state *data; /* The data */
4525 struct config *key; /* The key */
4526 struct s_x3node *next; /* Next entry with the same hash */
4527 struct s_x3node **from; /* Previous link */
4528} x3node;
4529
4530/* There is only one instance of the array, which is the following */
4531static struct s_x3 *x3a;
4532
4533/* Allocate a new associative array */
4534void State_init(){
4535 if( x3a ) return;
4536 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4537 if( x3a ){
4538 x3a->size = 128;
4539 x3a->count = 0;
4540 x3a->tbl = (x3node*)malloc(
4541 (sizeof(x3node) + sizeof(x3node*))*128 );
4542 if( x3a->tbl==0 ){
4543 free(x3a);
4544 x3a = 0;
4545 }else{
4546 int i;
4547 x3a->ht = (x3node**)&(x3a->tbl[128]);
4548 for(i=0; i<128; i++) x3a->ht[i] = 0;
4549 }
4550 }
4551}
4552/* Insert a new record into the array. Return TRUE if successful.
4553** Prior data with the same key is NOT overwritten */
4554int State_insert(data,key)
4555struct state *data;
4556struct config *key;
4557{
4558 x3node *np;
4559 int h;
4560 int ph;
4561
4562 if( x3a==0 ) return 0;
4563 ph = statehash(key);
4564 h = ph & (x3a->size-1);
4565 np = x3a->ht[h];
4566 while( np ){
4567 if( statecmp(np->key,key)==0 ){
4568 /* An existing entry with the same key is found. */
4569 /* Fail because overwrite is not allows. */
4570 return 0;
4571 }
4572 np = np->next;
4573 }
4574 if( x3a->count>=x3a->size ){
4575 /* Need to make the hash table bigger */
4576 int i,size;
4577 struct s_x3 array;
4578 array.size = size = x3a->size*2;
4579 array.count = x3a->count;
4580 array.tbl = (x3node*)malloc(
4581 (sizeof(x3node) + sizeof(x3node*))*size );
4582 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4583 array.ht = (x3node**)&(array.tbl[size]);
4584 for(i=0; i<size; i++) array.ht[i] = 0;
4585 for(i=0; i<x3a->count; i++){
4586 x3node *oldnp, *newnp;
4587 oldnp = &(x3a->tbl[i]);
4588 h = statehash(oldnp->key) & (size-1);
4589 newnp = &(array.tbl[i]);
4590 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4591 newnp->next = array.ht[h];
4592 newnp->key = oldnp->key;
4593 newnp->data = oldnp->data;
4594 newnp->from = &(array.ht[h]);
4595 array.ht[h] = newnp;
4596 }
4597 free(x3a->tbl);
4598 *x3a = array;
4599 }
4600 /* Insert the new data */
4601 h = ph & (x3a->size-1);
4602 np = &(x3a->tbl[x3a->count++]);
4603 np->key = key;
4604 np->data = data;
4605 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4606 np->next = x3a->ht[h];
4607 x3a->ht[h] = np;
4608 np->from = &(x3a->ht[h]);
4609 return 1;
4610}
4611
4612/* Return a pointer to data assigned to the given key. Return NULL
4613** if no such key. */
4614struct state *State_find(key)
4615struct config *key;
4616{
4617 int h;
4618 x3node *np;
4619
4620 if( x3a==0 ) return 0;
4621 h = statehash(key) & (x3a->size-1);
4622 np = x3a->ht[h];
4623 while( np ){
4624 if( statecmp(np->key,key)==0 ) break;
4625 np = np->next;
4626 }
4627 return np ? np->data : 0;
4628}
4629
4630/* Return an array of pointers to all data in the table.
4631** The array is obtained from malloc. Return NULL if memory allocation
4632** problems, or if the array is empty. */
4633struct state **State_arrayof()
4634{
4635 struct state **array;
4636 int i,size;
4637 if( x3a==0 ) return 0;
4638 size = x3a->count;
4639 array = (struct state **)malloc( sizeof(struct state *)*size );
4640 if( array ){
4641 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4642 }
4643 return array;
4644}
4645
4646/* Hash a configuration */
4647PRIVATE int confighash(a)
4648struct config *a;
4649{
4650 int h=0;
4651 h = h*571 + a->rp->index*37 + a->dot;
4652 return h;
4653}
4654
4655/* There is one instance of the following structure for each
4656** associative array of type "x4".
4657*/
4658struct s_x4 {
4659 int size; /* The number of available slots. */
4660 /* Must be a power of 2 greater than or */
4661 /* equal to 1 */
4662 int count; /* Number of currently slots filled */
4663 struct s_x4node *tbl; /* The data stored here */
4664 struct s_x4node **ht; /* Hash table for lookups */
4665};
4666
4667/* There is one instance of this structure for every data element
4668** in an associative array of type "x4".
4669*/
4670typedef struct s_x4node {
4671 struct config *data; /* The data */
4672 struct s_x4node *next; /* Next entry with the same hash */
4673 struct s_x4node **from; /* Previous link */
4674} x4node;
4675
4676/* There is only one instance of the array, which is the following */
4677static struct s_x4 *x4a;
4678
4679/* Allocate a new associative array */
4680void Configtable_init(){
4681 if( x4a ) return;
4682 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4683 if( x4a ){
4684 x4a->size = 64;
4685 x4a->count = 0;
4686 x4a->tbl = (x4node*)malloc(
4687 (sizeof(x4node) + sizeof(x4node*))*64 );
4688 if( x4a->tbl==0 ){
4689 free(x4a);
4690 x4a = 0;
4691 }else{
4692 int i;
4693 x4a->ht = (x4node**)&(x4a->tbl[64]);
4694 for(i=0; i<64; i++) x4a->ht[i] = 0;
4695 }
4696 }
4697}
4698/* Insert a new record into the array. Return TRUE if successful.
4699** Prior data with the same key is NOT overwritten */
4700int Configtable_insert(data)
4701struct config *data;
4702{
4703 x4node *np;
4704 int h;
4705 int ph;
4706
4707 if( x4a==0 ) return 0;
4708 ph = confighash(data);
4709 h = ph & (x4a->size-1);
4710 np = x4a->ht[h];
4711 while( np ){
4712 if( Configcmp(np->data,data)==0 ){
4713 /* An existing entry with the same key is found. */
4714 /* Fail because overwrite is not allows. */
4715 return 0;
4716 }
4717 np = np->next;
4718 }
4719 if( x4a->count>=x4a->size ){
4720 /* Need to make the hash table bigger */
4721 int i,size;
4722 struct s_x4 array;
4723 array.size = size = x4a->size*2;
4724 array.count = x4a->count;
4725 array.tbl = (x4node*)malloc(
4726 (sizeof(x4node) + sizeof(x4node*))*size );
4727 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4728 array.ht = (x4node**)&(array.tbl[size]);
4729 for(i=0; i<size; i++) array.ht[i] = 0;
4730 for(i=0; i<x4a->count; i++){
4731 x4node *oldnp, *newnp;
4732 oldnp = &(x4a->tbl[i]);
4733 h = confighash(oldnp->data) & (size-1);
4734 newnp = &(array.tbl[i]);
4735 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4736 newnp->next = array.ht[h];
4737 newnp->data = oldnp->data;
4738 newnp->from = &(array.ht[h]);
4739 array.ht[h] = newnp;
4740 }
4741 free(x4a->tbl);
4742 *x4a = array;
4743 }
4744 /* Insert the new data */
4745 h = ph & (x4a->size-1);
4746 np = &(x4a->tbl[x4a->count++]);
4747 np->data = data;
4748 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4749 np->next = x4a->ht[h];
4750 x4a->ht[h] = np;
4751 np->from = &(x4a->ht[h]);
4752 return 1;
4753}
4754
4755/* Return a pointer to data assigned to the given key. Return NULL
4756** if no such key. */
4757struct config *Configtable_find(key)
4758struct config *key;
4759{
4760 int h;
4761 x4node *np;
4762
4763 if( x4a==0 ) return 0;
4764 h = confighash(key) & (x4a->size-1);
4765 np = x4a->ht[h];
4766 while( np ){
4767 if( Configcmp(np->data,key)==0 ) break;
4768 np = np->next;
4769 }
4770 return np ? np->data : 0;
4771}
4772
4773/* Remove all data from the table. Pass each data to the function "f"
4774** as it is removed. ("f" may be null to avoid this step.) */
4775void Configtable_clear(f)
4776int(*f)(/* struct config * */);
4777{
4778 int i;
4779 if( x4a==0 || x4a->count==0 ) return;
4780 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4781 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4782 x4a->count = 0;
4783 return;
4784}