blob: 64b7a28262a9e1be7459f16abb4d001e66706582 [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,
drh9892c5d2007-12-21 00:02:11 +0000194 SSCONFLICT, /* A shift/shift conflict */
195 SRCONFLICT, /* Was a reduce, but part of a conflict */
196 RRCONFLICT, /* Was a reduce, but part of a conflict */
drh75897232000-05-29 14:26:00 +0000197 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
198 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
199 NOT_USED /* Deleted by compression */
200 } type;
201 union {
202 struct state *stp; /* The new state, if a shift */
203 struct rule *rp; /* The rule, if a reduce */
204 } x;
205 struct action *next; /* Next action for this state */
206 struct action *collide; /* Next action with the same hash */
207};
208
209/* Each state of the generated parser's finite state machine
210** is encoded as an instance of the following structure. */
211struct state {
212 struct config *bp; /* The basis configurations for this state */
213 struct config *cfp; /* All configurations in this set */
drhada354d2005-11-05 15:03:59 +0000214 int statenum; /* Sequencial number for this state */
drh75897232000-05-29 14:26:00 +0000215 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000216 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
217 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
218 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000219};
drh8b582012003-10-21 13:16:03 +0000220#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000221
222/* A followset propagation link indicates that the contents of one
223** configuration followset should be propagated to another whenever
224** the first changes. */
225struct plink {
226 struct config *cfp; /* The configuration to which linked */
227 struct plink *next; /* The next propagate link */
228};
229
230/* The state vector for the entire parser generator is recorded as
231** follows. (LEMON uses no global variables and makes little use of
232** static variables. Fields in the following structure can be thought
233** of as begin global variables in the program.) */
234struct lemon {
235 struct state **sorted; /* Table of states sorted by state number */
236 struct rule *rule; /* List of all rules */
237 int nstate; /* Number of states */
238 int nrule; /* Number of rules */
239 int nsymbol; /* Number of terminal and nonterminal symbols */
240 int nterminal; /* Number of terminal symbols */
241 struct symbol **symbols; /* Sorted array of pointers to symbols */
242 int errorcnt; /* Number of errors */
243 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000244 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000245 char *name; /* Name of the generated parser */
246 char *arg; /* Declaration of the 3th argument to parser */
247 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000248 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000249 char *start; /* Name of the start symbol for the grammar */
250 char *stacksize; /* Size of the parser stack */
251 char *include; /* Code to put at the start of the C file */
252 int includeln; /* Line number for start of include code */
253 char *error; /* Code to execute when an error is seen */
254 int errorln; /* Line number for start of error code */
255 char *overflow; /* Code to execute on a stack overflow */
256 int overflowln; /* Line number for start of overflow code */
257 char *failure; /* Code to execute on parser failure */
258 int failureln; /* Line number for start of failure code */
259 char *accept; /* Code to execute when the parser excepts */
260 int acceptln; /* Line number for the start of accept code */
261 char *extracode; /* Code appended to the generated file */
262 int extracodeln; /* Line number for the start of the extra code */
263 char *tokendest; /* Code to execute to destroy token data */
264 int tokendestln; /* Line number for token destroyer code */
drh960e8c62001-04-03 16:53:21 +0000265 char *vardest; /* Code for the default non-terminal destructor */
266 int vardestln; /* Line number for default non-term destructor code*/
drh75897232000-05-29 14:26:00 +0000267 char *filename; /* Name of the input file */
268 char *outname; /* Name of the current output file */
269 char *tokenprefix; /* A prefix added to token names in the .h file */
270 int nconflict; /* Number of parsing conflicts */
271 int tablesize; /* Size of the parse tables */
272 int basisflag; /* Print only basis configurations */
drh0bd1f4e2002-06-06 18:54:39 +0000273 int has_fallback; /* True if any %fallback is seen in the grammer */
drh75897232000-05-29 14:26:00 +0000274 char *argv0; /* Name of the program */
275};
276
277#define MemoryCheck(X) if((X)==0){ \
278 extern void memory_error(); \
279 memory_error(); \
280}
281
282/**************** From the file "table.h" *********************************/
283/*
284** All code in this file has been automatically generated
285** from a specification in the file
286** "table.q"
287** by the associative array code building program "aagen".
288** Do not edit this file! Instead, edit the specification
289** file, then rerun aagen.
290*/
291/*
292** Code for processing tables in the LEMON parser generator.
293*/
294
295/* Routines for handling a strings */
296
297char *Strsafe();
298
299void Strsafe_init(/* void */);
300int Strsafe_insert(/* char * */);
301char *Strsafe_find(/* char * */);
302
303/* Routines for handling symbols of the grammar */
304
305struct symbol *Symbol_new();
306int Symbolcmpp(/* struct symbol **, struct symbol ** */);
307void Symbol_init(/* void */);
308int Symbol_insert(/* struct symbol *, char * */);
309struct symbol *Symbol_find(/* char * */);
310struct symbol *Symbol_Nth(/* int */);
311int Symbol_count(/* */);
312struct symbol **Symbol_arrayof(/* */);
313
314/* Routines to manage the state table */
315
316int Configcmp(/* struct config *, struct config * */);
317struct state *State_new();
318void State_init(/* void */);
319int State_insert(/* struct state *, struct config * */);
320struct state *State_find(/* struct config * */);
321struct state **State_arrayof(/* */);
322
323/* Routines used for efficiency in Configlist_add */
324
325void Configtable_init(/* void */);
326int Configtable_insert(/* struct config * */);
327struct config *Configtable_find(/* struct config * */);
328void Configtable_clear(/* int(*)(struct config *) */);
329/****************** From the file "action.c" *******************************/
330/*
331** Routines processing parser actions in the LEMON parser generator.
332*/
333
334/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000335static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000336 static struct action *freelist = 0;
337 struct action *new;
338
339 if( freelist==0 ){
340 int i;
341 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000342 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000343 if( freelist==0 ){
344 fprintf(stderr,"Unable to allocate memory for a new parser action.");
345 exit(1);
346 }
347 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
348 freelist[amt-1].next = 0;
349 }
350 new = freelist;
351 freelist = freelist->next;
352 return new;
353}
354
drhe9278182007-07-18 18:16:29 +0000355/* Compare two actions for sorting purposes. Return negative, zero, or
356** positive if the first action is less than, equal to, or greater than
357** the first
358*/
359static int actioncmp(
360 struct action *ap1,
361 struct action *ap2
362){
drh75897232000-05-29 14:26:00 +0000363 int rc;
364 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000365 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000366 rc = (int)ap1->type - (int)ap2->type;
367 }
368 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000369 rc = ap1->x.rp->index - ap2->x.rp->index;
370 }
371 return rc;
372}
373
374/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000375static struct action *Action_sort(
376 struct action *ap
377){
378 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
379 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000380 return ap;
381}
382
383void Action_add(app,type,sp,arg)
384struct action **app;
385enum e_action type;
386struct symbol *sp;
387char *arg;
388{
389 struct action *new;
390 new = Action_new();
391 new->next = *app;
392 *app = new;
393 new->type = type;
394 new->sp = sp;
395 if( type==SHIFT ){
396 new->x.stp = (struct state *)arg;
397 }else{
398 new->x.rp = (struct rule *)arg;
399 }
400}
drh8b582012003-10-21 13:16:03 +0000401/********************** New code to implement the "acttab" module ***********/
402/*
403** This module implements routines use to construct the yy_action[] table.
404*/
405
406/*
407** The state of the yy_action table under construction is an instance of
408** the following structure
409*/
410typedef struct acttab acttab;
411struct acttab {
412 int nAction; /* Number of used slots in aAction[] */
413 int nActionAlloc; /* Slots allocated for aAction[] */
414 struct {
415 int lookahead; /* Value of the lookahead token */
416 int action; /* Action to take on the given lookahead */
417 } *aAction, /* The yy_action[] table under construction */
418 *aLookahead; /* A single new transaction set */
419 int mnLookahead; /* Minimum aLookahead[].lookahead */
420 int mnAction; /* Action associated with mnLookahead */
421 int mxLookahead; /* Maximum aLookahead[].lookahead */
422 int nLookahead; /* Used slots in aLookahead[] */
423 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
424};
425
426/* Return the number of entries in the yy_action table */
427#define acttab_size(X) ((X)->nAction)
428
429/* The value for the N-th entry in yy_action */
430#define acttab_yyaction(X,N) ((X)->aAction[N].action)
431
432/* The value for the N-th entry in yy_lookahead */
433#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
434
435/* Free all memory associated with the given acttab */
436void acttab_free(acttab *p){
437 free( p->aAction );
438 free( p->aLookahead );
439 free( p );
440}
441
442/* Allocate a new acttab structure */
443acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000444 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000445 if( p==0 ){
446 fprintf(stderr,"Unable to allocate memory for a new acttab.");
447 exit(1);
448 }
449 memset(p, 0, sizeof(*p));
450 return p;
451}
452
453/* Add a new action to the current transaction set
454*/
455void acttab_action(acttab *p, int lookahead, int action){
456 if( p->nLookahead>=p->nLookaheadAlloc ){
457 p->nLookaheadAlloc += 25;
458 p->aLookahead = realloc( p->aLookahead,
459 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
460 if( p->aLookahead==0 ){
461 fprintf(stderr,"malloc failed\n");
462 exit(1);
463 }
464 }
465 if( p->nLookahead==0 ){
466 p->mxLookahead = lookahead;
467 p->mnLookahead = lookahead;
468 p->mnAction = action;
469 }else{
470 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
471 if( p->mnLookahead>lookahead ){
472 p->mnLookahead = lookahead;
473 p->mnAction = action;
474 }
475 }
476 p->aLookahead[p->nLookahead].lookahead = lookahead;
477 p->aLookahead[p->nLookahead].action = action;
478 p->nLookahead++;
479}
480
481/*
482** Add the transaction set built up with prior calls to acttab_action()
483** into the current action table. Then reset the transaction set back
484** to an empty set in preparation for a new round of acttab_action() calls.
485**
486** Return the offset into the action table of the new transaction.
487*/
488int acttab_insert(acttab *p){
489 int i, j, k, n;
490 assert( p->nLookahead>0 );
491
492 /* Make sure we have enough space to hold the expanded action table
493 ** in the worst case. The worst case occurs if the transaction set
494 ** must be appended to the current action table
495 */
drh784d86f2004-02-19 18:41:53 +0000496 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000497 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000498 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000499 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
500 p->aAction = realloc( p->aAction,
501 sizeof(p->aAction[0])*p->nActionAlloc);
502 if( p->aAction==0 ){
503 fprintf(stderr,"malloc failed\n");
504 exit(1);
505 }
drhfdbf9282003-10-21 16:34:41 +0000506 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000507 p->aAction[i].lookahead = -1;
508 p->aAction[i].action = -1;
509 }
510 }
511
512 /* Scan the existing action table looking for an offset where we can
513 ** insert the current transaction set. Fall out of the loop when that
514 ** offset is found. In the worst case, we fall out of the loop when
515 ** i reaches p->nAction, which means we append the new transaction set.
516 **
517 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
518 */
drh784d86f2004-02-19 18:41:53 +0000519 for(i=0; i<p->nAction+p->mnLookahead; i++){
drh8b582012003-10-21 13:16:03 +0000520 if( p->aAction[i].lookahead<0 ){
521 for(j=0; j<p->nLookahead; j++){
522 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
523 if( k<0 ) break;
524 if( p->aAction[k].lookahead>=0 ) break;
525 }
drhfdbf9282003-10-21 16:34:41 +0000526 if( j<p->nLookahead ) continue;
527 for(j=0; j<p->nAction; j++){
528 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
529 }
530 if( j==p->nAction ){
531 break; /* Fits in empty slots */
532 }
drh8b582012003-10-21 13:16:03 +0000533 }else if( p->aAction[i].lookahead==p->mnLookahead ){
534 if( p->aAction[i].action!=p->mnAction ) continue;
535 for(j=0; j<p->nLookahead; j++){
536 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
537 if( k<0 || k>=p->nAction ) break;
538 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
539 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
540 }
541 if( j<p->nLookahead ) continue;
542 n = 0;
543 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000544 if( p->aAction[j].lookahead<0 ) continue;
545 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000546 }
drhfdbf9282003-10-21 16:34:41 +0000547 if( n==p->nLookahead ){
548 break; /* Same as a prior transaction set */
549 }
drh8b582012003-10-21 13:16:03 +0000550 }
551 }
552 /* Insert transaction set at index i. */
553 for(j=0; j<p->nLookahead; j++){
554 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
555 p->aAction[k] = p->aLookahead[j];
556 if( k>=p->nAction ) p->nAction = k+1;
557 }
558 p->nLookahead = 0;
559
560 /* Return the offset that is added to the lookahead in order to get the
561 ** index into yy_action of the action */
562 return i - p->mnLookahead;
563}
564
drh75897232000-05-29 14:26:00 +0000565/********************** From the file "build.c" *****************************/
566/*
567** Routines to construction the finite state machine for the LEMON
568** parser generator.
569*/
570
571/* Find a precedence symbol of every rule in the grammar.
572**
573** Those rules which have a precedence symbol coded in the input
574** grammar using the "[symbol]" construct will already have the
575** rp->precsym field filled. Other rules take as their precedence
576** symbol the first RHS symbol with a defined precedence. If there
577** are not RHS symbols with a defined precedence, the precedence
578** symbol field is left blank.
579*/
580void FindRulePrecedences(xp)
581struct lemon *xp;
582{
583 struct rule *rp;
584 for(rp=xp->rule; rp; rp=rp->next){
585 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000586 int i, j;
587 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
588 struct symbol *sp = rp->rhs[i];
589 if( sp->type==MULTITERMINAL ){
590 for(j=0; j<sp->nsubsym; j++){
591 if( sp->subsym[j]->prec>=0 ){
592 rp->precsym = sp->subsym[j];
593 break;
594 }
595 }
596 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000597 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000598 }
599 }
600 }
601 }
602 return;
603}
604
605/* Find all nonterminals which will generate the empty string.
606** Then go back and compute the first sets of every nonterminal.
607** The first set is the set of all terminal symbols which can begin
608** a string generated by that nonterminal.
609*/
610void FindFirstSets(lemp)
611struct lemon *lemp;
612{
drhfd405312005-11-06 04:06:59 +0000613 int i, j;
drh75897232000-05-29 14:26:00 +0000614 struct rule *rp;
615 int progress;
616
617 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000618 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000619 }
620 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
621 lemp->symbols[i]->firstset = SetNew();
622 }
623
624 /* First compute all lambdas */
625 do{
626 progress = 0;
627 for(rp=lemp->rule; rp; rp=rp->next){
628 if( rp->lhs->lambda ) continue;
629 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000630 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000631 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000632 }
633 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000634 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000635 progress = 1;
636 }
637 }
638 }while( progress );
639
640 /* Now compute all first sets */
641 do{
642 struct symbol *s1, *s2;
643 progress = 0;
644 for(rp=lemp->rule; rp; rp=rp->next){
645 s1 = rp->lhs;
646 for(i=0; i<rp->nrhs; i++){
647 s2 = rp->rhs[i];
648 if( s2->type==TERMINAL ){
649 progress += SetAdd(s1->firstset,s2->index);
650 break;
drhfd405312005-11-06 04:06:59 +0000651 }else if( s2->type==MULTITERMINAL ){
652 for(j=0; j<s2->nsubsym; j++){
653 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
654 }
655 break;
drh75897232000-05-29 14:26:00 +0000656 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000657 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000658 }else{
659 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000660 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000661 }
662 }
663 }
664 }while( progress );
665 return;
666}
667
668/* Compute all LR(0) states for the grammar. Links
669** are added to between some states so that the LR(1) follow sets
670** can be computed later.
671*/
672PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
673void FindStates(lemp)
674struct lemon *lemp;
675{
676 struct symbol *sp;
677 struct rule *rp;
678
679 Configlist_init();
680
681 /* Find the start symbol */
682 if( lemp->start ){
683 sp = Symbol_find(lemp->start);
684 if( sp==0 ){
685 ErrorMsg(lemp->filename,0,
686"The specified start symbol \"%s\" is not \
687in a nonterminal of the grammar. \"%s\" will be used as the start \
688symbol instead.",lemp->start,lemp->rule->lhs->name);
689 lemp->errorcnt++;
690 sp = lemp->rule->lhs;
691 }
692 }else{
693 sp = lemp->rule->lhs;
694 }
695
696 /* Make sure the start symbol doesn't occur on the right-hand side of
697 ** any rule. Report an error if it does. (YACC would generate a new
698 ** start symbol in this case.) */
699 for(rp=lemp->rule; rp; rp=rp->next){
700 int i;
701 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000702 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000703 ErrorMsg(lemp->filename,0,
704"The start symbol \"%s\" occurs on the \
705right-hand side of a rule. This will result in a parser which \
706does not work properly.",sp->name);
707 lemp->errorcnt++;
708 }
709 }
710 }
711
712 /* The basis configuration set for the first state
713 ** is all rules which have the start symbol as their
714 ** left-hand side */
715 for(rp=sp->rule; rp; rp=rp->nextlhs){
716 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000717 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000718 newcfp = Configlist_addbasis(rp,0);
719 SetAdd(newcfp->fws,0);
720 }
721
722 /* Compute the first state. All other states will be
723 ** computed automatically during the computation of the first one.
724 ** The returned pointer to the first state is not used. */
725 (void)getstate(lemp);
726 return;
727}
728
729/* Return a pointer to a state which is described by the configuration
730** list which has been built from calls to Configlist_add.
731*/
732PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
733PRIVATE struct state *getstate(lemp)
734struct lemon *lemp;
735{
736 struct config *cfp, *bp;
737 struct state *stp;
738
739 /* Extract the sorted basis of the new state. The basis was constructed
740 ** by prior calls to "Configlist_addbasis()". */
741 Configlist_sortbasis();
742 bp = Configlist_basis();
743
744 /* Get a state with the same basis */
745 stp = State_find(bp);
746 if( stp ){
747 /* A state with the same basis already exists! Copy all the follow-set
748 ** propagation links from the state under construction into the
749 ** preexisting state, then return a pointer to the preexisting state */
750 struct config *x, *y;
751 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
752 Plink_copy(&y->bplp,x->bplp);
753 Plink_delete(x->fplp);
754 x->fplp = x->bplp = 0;
755 }
756 cfp = Configlist_return();
757 Configlist_eat(cfp);
758 }else{
759 /* This really is a new state. Construct all the details */
760 Configlist_closure(lemp); /* Compute the configuration closure */
761 Configlist_sort(); /* Sort the configuration closure */
762 cfp = Configlist_return(); /* Get a pointer to the config list */
763 stp = State_new(); /* A new state structure */
764 MemoryCheck(stp);
765 stp->bp = bp; /* Remember the configuration basis */
766 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000767 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000768 stp->ap = 0; /* No actions, yet. */
769 State_insert(stp,stp->bp); /* Add to the state table */
770 buildshifts(lemp,stp); /* Recursively compute successor states */
771 }
772 return stp;
773}
774
drhfd405312005-11-06 04:06:59 +0000775/*
776** Return true if two symbols are the same.
777*/
778int same_symbol(a,b)
779struct symbol *a;
780struct symbol *b;
781{
782 int i;
783 if( a==b ) return 1;
784 if( a->type!=MULTITERMINAL ) return 0;
785 if( b->type!=MULTITERMINAL ) return 0;
786 if( a->nsubsym!=b->nsubsym ) return 0;
787 for(i=0; i<a->nsubsym; i++){
788 if( a->subsym[i]!=b->subsym[i] ) return 0;
789 }
790 return 1;
791}
792
drh75897232000-05-29 14:26:00 +0000793/* Construct all successor states to the given state. A "successor"
794** state is any state which can be reached by a shift action.
795*/
796PRIVATE void buildshifts(lemp,stp)
797struct lemon *lemp;
798struct state *stp; /* The state from which successors are computed */
799{
800 struct config *cfp; /* For looping thru the config closure of "stp" */
801 struct config *bcfp; /* For the inner loop on config closure of "stp" */
802 struct config *new; /* */
803 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
804 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
805 struct state *newstp; /* A pointer to a successor state */
806
807 /* Each configuration becomes complete after it contibutes to a successor
808 ** state. Initially, all configurations are incomplete */
809 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
810
811 /* Loop through all configurations of the state "stp" */
812 for(cfp=stp->cfp; cfp; cfp=cfp->next){
813 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
814 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
815 Configlist_reset(); /* Reset the new config set */
816 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
817
818 /* For every configuration in the state "stp" which has the symbol "sp"
819 ** following its dot, add the same configuration to the basis set under
820 ** construction but with the dot shifted one symbol to the right. */
821 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
822 if( bcfp->status==COMPLETE ) continue; /* Already used */
823 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
824 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000825 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000826 bcfp->status = COMPLETE; /* Mark this config as used */
827 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
828 Plink_add(&new->bplp,bcfp);
829 }
830
831 /* Get a pointer to the state described by the basis configuration set
832 ** constructed in the preceding loop */
833 newstp = getstate(lemp);
834
835 /* The state "newstp" is reached from the state "stp" by a shift action
836 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000837 if( sp->type==MULTITERMINAL ){
838 int i;
839 for(i=0; i<sp->nsubsym; i++){
840 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
841 }
842 }else{
843 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
844 }
drh75897232000-05-29 14:26:00 +0000845 }
846}
847
848/*
849** Construct the propagation links
850*/
851void FindLinks(lemp)
852struct lemon *lemp;
853{
854 int i;
855 struct config *cfp, *other;
856 struct state *stp;
857 struct plink *plp;
858
859 /* Housekeeping detail:
860 ** Add to every propagate link a pointer back to the state to
861 ** which the link is attached. */
862 for(i=0; i<lemp->nstate; i++){
863 stp = lemp->sorted[i];
864 for(cfp=stp->cfp; cfp; cfp=cfp->next){
865 cfp->stp = stp;
866 }
867 }
868
869 /* Convert all backlinks into forward links. Only the forward
870 ** links are used in the follow-set computation. */
871 for(i=0; i<lemp->nstate; i++){
872 stp = lemp->sorted[i];
873 for(cfp=stp->cfp; cfp; cfp=cfp->next){
874 for(plp=cfp->bplp; plp; plp=plp->next){
875 other = plp->cfp;
876 Plink_add(&other->fplp,cfp);
877 }
878 }
879 }
880}
881
882/* Compute all followsets.
883**
884** A followset is the set of all symbols which can come immediately
885** after a configuration.
886*/
887void FindFollowSets(lemp)
888struct lemon *lemp;
889{
890 int i;
891 struct config *cfp;
892 struct plink *plp;
893 int progress;
894 int change;
895
896 for(i=0; i<lemp->nstate; i++){
897 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
898 cfp->status = INCOMPLETE;
899 }
900 }
901
902 do{
903 progress = 0;
904 for(i=0; i<lemp->nstate; i++){
905 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
906 if( cfp->status==COMPLETE ) continue;
907 for(plp=cfp->fplp; plp; plp=plp->next){
908 change = SetUnion(plp->cfp->fws,cfp->fws);
909 if( change ){
910 plp->cfp->status = INCOMPLETE;
911 progress = 1;
912 }
913 }
914 cfp->status = COMPLETE;
915 }
916 }
917 }while( progress );
918}
919
920static int resolve_conflict();
921
922/* Compute the reduce actions, and resolve conflicts.
923*/
924void FindActions(lemp)
925struct lemon *lemp;
926{
927 int i,j;
928 struct config *cfp;
929 struct state *stp;
930 struct symbol *sp;
931 struct rule *rp;
932
933 /* Add all of the reduce actions
934 ** A reduce action is added for each element of the followset of
935 ** a configuration which has its dot at the extreme right.
936 */
937 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
938 stp = lemp->sorted[i];
939 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
940 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
941 for(j=0; j<lemp->nterminal; j++){
942 if( SetFind(cfp->fws,j) ){
943 /* Add a reduce action to the state "stp" which will reduce by the
944 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000945 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000946 }
947 }
948 }
949 }
950 }
951
952 /* Add the accepting token */
953 if( lemp->start ){
954 sp = Symbol_find(lemp->start);
955 if( sp==0 ) sp = lemp->rule->lhs;
956 }else{
957 sp = lemp->rule->lhs;
958 }
959 /* Add to the first state (which is always the starting state of the
960 ** finite state machine) an action to ACCEPT if the lookahead is the
961 ** start nonterminal. */
962 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
963
964 /* Resolve conflicts */
965 for(i=0; i<lemp->nstate; i++){
966 struct action *ap, *nap;
967 struct state *stp;
968 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000969 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000970 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000971 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000972 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
973 /* The two actions "ap" and "nap" have the same lookahead.
974 ** Figure out which one should be used */
975 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
976 }
977 }
978 }
979
980 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000981 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000982 for(i=0; i<lemp->nstate; i++){
983 struct action *ap;
984 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000985 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000986 }
987 }
988 for(rp=lemp->rule; rp; rp=rp->next){
989 if( rp->canReduce ) continue;
990 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
991 lemp->errorcnt++;
992 }
993}
994
995/* Resolve a conflict between the two given actions. If the
996** conflict can't be resolve, return non-zero.
997**
998** NO LONGER TRUE:
999** To resolve a conflict, first look to see if either action
1000** is on an error rule. In that case, take the action which
1001** is not associated with the error rule. If neither or both
1002** actions are associated with an error rule, then try to
1003** use precedence to resolve the conflict.
1004**
1005** If either action is a SHIFT, then it must be apx. This
1006** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1007*/
1008static int resolve_conflict(apx,apy,errsym)
1009struct action *apx;
1010struct action *apy;
1011struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1012{
1013 struct symbol *spx, *spy;
1014 int errcnt = 0;
1015 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001016 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001017 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001018 errcnt++;
1019 }
drh75897232000-05-29 14:26:00 +00001020 if( apx->type==SHIFT && apy->type==REDUCE ){
1021 spx = apx->sp;
1022 spy = apy->x.rp->precsym;
1023 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1024 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001025 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001026 errcnt++;
1027 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1028 apy->type = RD_RESOLVED;
1029 }else if( spx->prec<spy->prec ){
1030 apx->type = SH_RESOLVED;
1031 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1032 apy->type = RD_RESOLVED; /* associativity */
1033 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1034 apx->type = SH_RESOLVED;
1035 }else{
1036 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001037 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001038 errcnt++;
1039 }
1040 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1041 spx = apx->x.rp->precsym;
1042 spy = apy->x.rp->precsym;
1043 if( spx==0 || spy==0 || spx->prec<0 ||
1044 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001045 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001046 errcnt++;
1047 }else if( spx->prec>spy->prec ){
1048 apy->type = RD_RESOLVED;
1049 }else if( spx->prec<spy->prec ){
1050 apx->type = RD_RESOLVED;
1051 }
1052 }else{
drhb59499c2002-02-23 18:45:13 +00001053 assert(
1054 apx->type==SH_RESOLVED ||
1055 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001056 apx->type==SSCONFLICT ||
1057 apx->type==SRCONFLICT ||
1058 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001059 apy->type==SH_RESOLVED ||
1060 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001061 apy->type==SSCONFLICT ||
1062 apy->type==SRCONFLICT ||
1063 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001064 );
1065 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1066 ** REDUCEs on the list. If we reach this point it must be because
1067 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001068 }
1069 return errcnt;
1070}
1071/********************* From the file "configlist.c" *************************/
1072/*
1073** Routines to processing a configuration list and building a state
1074** in the LEMON parser generator.
1075*/
1076
1077static struct config *freelist = 0; /* List of free configurations */
1078static struct config *current = 0; /* Top of list of configurations */
1079static struct config **currentend = 0; /* Last on list of configs */
1080static struct config *basis = 0; /* Top of list of basis configs */
1081static struct config **basisend = 0; /* End of list of basis configs */
1082
1083/* Return a pointer to a new configuration */
1084PRIVATE struct config *newconfig(){
1085 struct config *new;
1086 if( freelist==0 ){
1087 int i;
1088 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001089 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001090 if( freelist==0 ){
1091 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1092 exit(1);
1093 }
1094 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1095 freelist[amt-1].next = 0;
1096 }
1097 new = freelist;
1098 freelist = freelist->next;
1099 return new;
1100}
1101
1102/* The configuration "old" is no longer used */
1103PRIVATE void deleteconfig(old)
1104struct config *old;
1105{
1106 old->next = freelist;
1107 freelist = old;
1108}
1109
1110/* Initialized the configuration list builder */
1111void Configlist_init(){
1112 current = 0;
1113 currentend = &current;
1114 basis = 0;
1115 basisend = &basis;
1116 Configtable_init();
1117 return;
1118}
1119
1120/* Initialized the configuration list builder */
1121void Configlist_reset(){
1122 current = 0;
1123 currentend = &current;
1124 basis = 0;
1125 basisend = &basis;
1126 Configtable_clear(0);
1127 return;
1128}
1129
1130/* Add another configuration to the configuration list */
1131struct config *Configlist_add(rp,dot)
1132struct rule *rp; /* The rule */
1133int dot; /* Index into the RHS of the rule where the dot goes */
1134{
1135 struct config *cfp, model;
1136
1137 assert( currentend!=0 );
1138 model.rp = rp;
1139 model.dot = dot;
1140 cfp = Configtable_find(&model);
1141 if( cfp==0 ){
1142 cfp = newconfig();
1143 cfp->rp = rp;
1144 cfp->dot = dot;
1145 cfp->fws = SetNew();
1146 cfp->stp = 0;
1147 cfp->fplp = cfp->bplp = 0;
1148 cfp->next = 0;
1149 cfp->bp = 0;
1150 *currentend = cfp;
1151 currentend = &cfp->next;
1152 Configtable_insert(cfp);
1153 }
1154 return cfp;
1155}
1156
1157/* Add a basis configuration to the configuration list */
1158struct config *Configlist_addbasis(rp,dot)
1159struct rule *rp;
1160int dot;
1161{
1162 struct config *cfp, model;
1163
1164 assert( basisend!=0 );
1165 assert( currentend!=0 );
1166 model.rp = rp;
1167 model.dot = dot;
1168 cfp = Configtable_find(&model);
1169 if( cfp==0 ){
1170 cfp = newconfig();
1171 cfp->rp = rp;
1172 cfp->dot = dot;
1173 cfp->fws = SetNew();
1174 cfp->stp = 0;
1175 cfp->fplp = cfp->bplp = 0;
1176 cfp->next = 0;
1177 cfp->bp = 0;
1178 *currentend = cfp;
1179 currentend = &cfp->next;
1180 *basisend = cfp;
1181 basisend = &cfp->bp;
1182 Configtable_insert(cfp);
1183 }
1184 return cfp;
1185}
1186
1187/* Compute the closure of the configuration list */
1188void Configlist_closure(lemp)
1189struct lemon *lemp;
1190{
1191 struct config *cfp, *newcfp;
1192 struct rule *rp, *newrp;
1193 struct symbol *sp, *xsp;
1194 int i, dot;
1195
1196 assert( currentend!=0 );
1197 for(cfp=current; cfp; cfp=cfp->next){
1198 rp = cfp->rp;
1199 dot = cfp->dot;
1200 if( dot>=rp->nrhs ) continue;
1201 sp = rp->rhs[dot];
1202 if( sp->type==NONTERMINAL ){
1203 if( sp->rule==0 && sp!=lemp->errsym ){
1204 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1205 sp->name);
1206 lemp->errorcnt++;
1207 }
1208 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1209 newcfp = Configlist_add(newrp,0);
1210 for(i=dot+1; i<rp->nrhs; i++){
1211 xsp = rp->rhs[i];
1212 if( xsp->type==TERMINAL ){
1213 SetAdd(newcfp->fws,xsp->index);
1214 break;
drhfd405312005-11-06 04:06:59 +00001215 }else if( xsp->type==MULTITERMINAL ){
1216 int k;
1217 for(k=0; k<xsp->nsubsym; k++){
1218 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1219 }
1220 break;
drh75897232000-05-29 14:26:00 +00001221 }else{
1222 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001223 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001224 }
1225 }
1226 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1227 }
1228 }
1229 }
1230 return;
1231}
1232
1233/* Sort the configuration list */
1234void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001235 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001236 currentend = 0;
1237 return;
1238}
1239
1240/* Sort the basis configuration list */
1241void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001242 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001243 basisend = 0;
1244 return;
1245}
1246
1247/* Return a pointer to the head of the configuration list and
1248** reset the list */
1249struct config *Configlist_return(){
1250 struct config *old;
1251 old = current;
1252 current = 0;
1253 currentend = 0;
1254 return old;
1255}
1256
1257/* Return a pointer to the head of the configuration list and
1258** reset the list */
1259struct config *Configlist_basis(){
1260 struct config *old;
1261 old = basis;
1262 basis = 0;
1263 basisend = 0;
1264 return old;
1265}
1266
1267/* Free all elements of the given configuration list */
1268void Configlist_eat(cfp)
1269struct config *cfp;
1270{
1271 struct config *nextcfp;
1272 for(; cfp; cfp=nextcfp){
1273 nextcfp = cfp->next;
1274 assert( cfp->fplp==0 );
1275 assert( cfp->bplp==0 );
1276 if( cfp->fws ) SetFree(cfp->fws);
1277 deleteconfig(cfp);
1278 }
1279 return;
1280}
1281/***************** From the file "error.c" *********************************/
1282/*
1283** Code for printing error message.
1284*/
1285
1286/* Find a good place to break "msg" so that its length is at least "min"
1287** but no more than "max". Make the point as close to max as possible.
1288*/
1289static int findbreak(msg,min,max)
1290char *msg;
1291int min;
1292int max;
1293{
1294 int i,spot;
1295 char c;
1296 for(i=spot=min; i<=max; i++){
1297 c = msg[i];
1298 if( c=='\t' ) msg[i] = ' ';
1299 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1300 if( c==0 ){ spot = i; break; }
1301 if( c=='-' && i<max-1 ) spot = i+1;
1302 if( c==' ' ) spot = i;
1303 }
1304 return spot;
1305}
1306
1307/*
1308** The error message is split across multiple lines if necessary. The
1309** splits occur at a space, if there is a space available near the end
1310** of the line.
1311*/
1312#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1313#define LINEWIDTH 79 /* Max width of any output line */
1314#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001315void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001316 char errmsg[ERRMSGSIZE];
1317 char prefix[PREFIXLIMIT+10];
1318 int errmsgsize;
1319 int prefixsize;
1320 int availablewidth;
1321 va_list ap;
1322 int end, restart, base;
1323
drhf9a2e7b2003-04-15 01:49:48 +00001324 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001325 /* Prepare a prefix to be prepended to every output line */
1326 if( lineno>0 ){
1327 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1328 }else{
1329 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1330 }
1331 prefixsize = strlen(prefix);
1332 availablewidth = LINEWIDTH - prefixsize;
1333
1334 /* Generate the error message */
1335 vsprintf(errmsg,format,ap);
1336 va_end(ap);
1337 errmsgsize = strlen(errmsg);
1338 /* Remove trailing '\n's from the error message. */
1339 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1340 errmsg[--errmsgsize] = 0;
1341 }
1342
1343 /* Print the error message */
1344 base = 0;
1345 while( errmsg[base]!=0 ){
1346 end = restart = findbreak(&errmsg[base],0,availablewidth);
1347 restart += base;
1348 while( errmsg[restart]==' ' ) restart++;
1349 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1350 base = restart;
1351 }
1352}
1353/**************** From the file "main.c" ************************************/
1354/*
1355** Main program file for the LEMON parser generator.
1356*/
1357
1358/* Report an out-of-memory condition and abort. This function
1359** is used mostly by the "MemoryCheck" macro in struct.h
1360*/
1361void memory_error(){
1362 fprintf(stderr,"Out of memory. Aborting...\n");
1363 exit(1);
1364}
1365
drh6d08b4d2004-07-20 12:45:22 +00001366static int nDefine = 0; /* Number of -D options on the command line */
1367static char **azDefine = 0; /* Name of the -D macros */
1368
1369/* This routine is called with the argument to each -D command-line option.
1370** Add the macro defined to the azDefine array.
1371*/
1372static void handle_D_option(char *z){
1373 char **paz;
1374 nDefine++;
1375 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1376 if( azDefine==0 ){
1377 fprintf(stderr,"out of memory\n");
1378 exit(1);
1379 }
1380 paz = &azDefine[nDefine-1];
1381 *paz = malloc( strlen(z)+1 );
1382 if( *paz==0 ){
1383 fprintf(stderr,"out of memory\n");
1384 exit(1);
1385 }
1386 strcpy(*paz, z);
1387 for(z=*paz; *z && *z!='='; z++){}
1388 *z = 0;
1389}
1390
drh75897232000-05-29 14:26:00 +00001391
1392/* The main program. Parse the command line and do it... */
1393int main(argc,argv)
1394int argc;
1395char **argv;
1396{
1397 static int version = 0;
1398 static int rpflag = 0;
1399 static int basisflag = 0;
1400 static int compress = 0;
1401 static int quiet = 0;
1402 static int statistics = 0;
1403 static int mhflag = 0;
1404 static struct s_options options[] = {
1405 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1406 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001407 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001408 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1409 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1410 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001411 {OPT_FLAG, "s", (char*)&statistics,
1412 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001413 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1414 {OPT_FLAG,0,0,0}
1415 };
1416 int i;
1417 struct lemon lem;
1418
drhb0c86772000-06-02 23:21:26 +00001419 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001420 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001421 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001422 exit(0);
1423 }
drhb0c86772000-06-02 23:21:26 +00001424 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001425 fprintf(stderr,"Exactly one filename argument is required.\n");
1426 exit(1);
1427 }
drh954f6b42006-06-13 13:27:46 +00001428 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001429 lem.errorcnt = 0;
1430
1431 /* Initialize the machine */
1432 Strsafe_init();
1433 Symbol_init();
1434 State_init();
1435 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001436 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001437 lem.basisflag = basisflag;
drh75897232000-05-29 14:26:00 +00001438 Symbol_new("$");
1439 lem.errsym = Symbol_new("error");
1440
1441 /* Parse the input file */
1442 Parse(&lem);
1443 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001444 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001445 fprintf(stderr,"Empty grammar.\n");
1446 exit(1);
1447 }
1448
1449 /* Count and index the symbols of the grammar */
1450 lem.nsymbol = Symbol_count();
1451 Symbol_new("{default}");
1452 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001453 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001454 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1455 (int(*)())Symbolcmpp);
1456 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1457 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1458 lem.nterminal = i;
1459
1460 /* Generate a reprint of the grammar, if requested on the command line */
1461 if( rpflag ){
1462 Reprint(&lem);
1463 }else{
1464 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001465 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001466
1467 /* Find the precedence for every production rule (that has one) */
1468 FindRulePrecedences(&lem);
1469
1470 /* Compute the lambda-nonterminals and the first-sets for every
1471 ** nonterminal */
1472 FindFirstSets(&lem);
1473
1474 /* Compute all LR(0) states. Also record follow-set propagation
1475 ** links so that the follow-set can be computed later */
1476 lem.nstate = 0;
1477 FindStates(&lem);
1478 lem.sorted = State_arrayof();
1479
1480 /* Tie up loose ends on the propagation links */
1481 FindLinks(&lem);
1482
1483 /* Compute the follow set of every reducible configuration */
1484 FindFollowSets(&lem);
1485
1486 /* Compute the action tables */
1487 FindActions(&lem);
1488
1489 /* Compress the action tables */
1490 if( compress==0 ) CompressTables(&lem);
1491
drhada354d2005-11-05 15:03:59 +00001492 /* Reorder and renumber the states so that states with fewer choices
1493 ** occur at the end. */
1494 ResortStates(&lem);
1495
drh75897232000-05-29 14:26:00 +00001496 /* Generate a report of the parser generated. (the "y.output" file) */
1497 if( !quiet ) ReportOutput(&lem);
1498
1499 /* Generate the source code for the parser */
1500 ReportTable(&lem, mhflag);
1501
1502 /* Produce a header file for use by the scanner. (This step is
1503 ** omitted if the "-m" option is used because makeheaders will
1504 ** generate the file for us.) */
1505 if( !mhflag ) ReportHeader(&lem);
1506 }
1507 if( statistics ){
1508 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1509 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1510 printf(" %d states, %d parser table entries, %d conflicts\n",
1511 lem.nstate, lem.tablesize, lem.nconflict);
1512 }
1513 if( lem.nconflict ){
1514 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1515 }
1516 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001517 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001518}
1519/******************** From the file "msort.c" *******************************/
1520/*
1521** A generic merge-sort program.
1522**
1523** USAGE:
1524** Let "ptr" be a pointer to some structure which is at the head of
1525** a null-terminated list. Then to sort the list call:
1526**
1527** ptr = msort(ptr,&(ptr->next),cmpfnc);
1528**
1529** In the above, "cmpfnc" is a pointer to a function which compares
1530** two instances of the structure and returns an integer, as in
1531** strcmp. The second argument is a pointer to the pointer to the
1532** second element of the linked list. This address is used to compute
1533** the offset to the "next" field within the structure. The offset to
1534** the "next" field must be constant for all structures in the list.
1535**
1536** The function returns a new pointer which is the head of the list
1537** after sorting.
1538**
1539** ALGORITHM:
1540** Merge-sort.
1541*/
1542
1543/*
1544** Return a pointer to the next structure in the linked list.
1545*/
drhba99af52001-10-25 20:37:16 +00001546#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001547
1548/*
1549** Inputs:
1550** a: A sorted, null-terminated linked list. (May be null).
1551** b: A sorted, null-terminated linked list. (May be null).
1552** cmp: A pointer to the comparison function.
1553** offset: Offset in the structure to the "next" field.
1554**
1555** Return Value:
1556** A pointer to the head of a sorted list containing the elements
1557** of both a and b.
1558**
1559** Side effects:
1560** The "next" pointers for elements in the lists a and b are
1561** changed.
1562*/
drhe9278182007-07-18 18:16:29 +00001563static char *merge(
1564 char *a,
1565 char *b,
1566 int (*cmp)(const char*,const char*),
1567 int offset
1568){
drh75897232000-05-29 14:26:00 +00001569 char *ptr, *head;
1570
1571 if( a==0 ){
1572 head = b;
1573 }else if( b==0 ){
1574 head = a;
1575 }else{
1576 if( (*cmp)(a,b)<0 ){
1577 ptr = a;
1578 a = NEXT(a);
1579 }else{
1580 ptr = b;
1581 b = NEXT(b);
1582 }
1583 head = ptr;
1584 while( a && b ){
1585 if( (*cmp)(a,b)<0 ){
1586 NEXT(ptr) = a;
1587 ptr = a;
1588 a = NEXT(a);
1589 }else{
1590 NEXT(ptr) = b;
1591 ptr = b;
1592 b = NEXT(b);
1593 }
1594 }
1595 if( a ) NEXT(ptr) = a;
1596 else NEXT(ptr) = b;
1597 }
1598 return head;
1599}
1600
1601/*
1602** Inputs:
1603** list: Pointer to a singly-linked list of structures.
1604** next: Pointer to pointer to the second element of the list.
1605** cmp: A comparison function.
1606**
1607** Return Value:
1608** A pointer to the head of a sorted list containing the elements
1609** orginally in list.
1610**
1611** Side effects:
1612** The "next" pointers for elements in list are changed.
1613*/
1614#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001615static char *msort(
1616 char *list,
1617 char **next,
1618 int (*cmp)(const char*,const char*)
1619){
drhba99af52001-10-25 20:37:16 +00001620 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001621 char *ep;
1622 char *set[LISTSIZE];
1623 int i;
drhba99af52001-10-25 20:37:16 +00001624 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001625 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1626 while( list ){
1627 ep = list;
1628 list = NEXT(list);
1629 NEXT(ep) = 0;
1630 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1631 ep = merge(ep,set[i],cmp,offset);
1632 set[i] = 0;
1633 }
1634 set[i] = ep;
1635 }
1636 ep = 0;
1637 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1638 return ep;
1639}
1640/************************ From the file "option.c" **************************/
1641static char **argv;
1642static struct s_options *op;
1643static FILE *errstream;
1644
1645#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1646
1647/*
1648** Print the command line with a carrot pointing to the k-th character
1649** of the n-th field.
1650*/
1651static void errline(n,k,err)
1652int n;
1653int k;
1654FILE *err;
1655{
1656 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001657 if( argv[0] ) fprintf(err,"%s",argv[0]);
1658 spcnt = strlen(argv[0]) + 1;
1659 for(i=1; i<n && argv[i]; i++){
1660 fprintf(err," %s",argv[i]);
drhdc30dd32005-02-16 03:35:15 +00001661 spcnt += strlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001662 }
1663 spcnt += k;
1664 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1665 if( spcnt<20 ){
1666 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1667 }else{
1668 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1669 }
1670}
1671
1672/*
1673** Return the index of the N-th non-switch argument. Return -1
1674** if N is out of range.
1675*/
1676static int argindex(n)
1677int n;
1678{
1679 int i;
1680 int dashdash = 0;
1681 if( argv!=0 && *argv!=0 ){
1682 for(i=1; argv[i]; i++){
1683 if( dashdash || !ISOPT(argv[i]) ){
1684 if( n==0 ) return i;
1685 n--;
1686 }
1687 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1688 }
1689 }
1690 return -1;
1691}
1692
1693static char emsg[] = "Command line syntax error: ";
1694
1695/*
1696** Process a flag command line argument.
1697*/
1698static int handleflags(i,err)
1699int i;
1700FILE *err;
1701{
1702 int v;
1703 int errcnt = 0;
1704 int j;
1705 for(j=0; op[j].label; j++){
drh6d08b4d2004-07-20 12:45:22 +00001706 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001707 }
1708 v = argv[i][0]=='-' ? 1 : 0;
1709 if( op[j].label==0 ){
1710 if( err ){
1711 fprintf(err,"%sundefined option.\n",emsg);
1712 errline(i,1,err);
1713 }
1714 errcnt++;
1715 }else if( op[j].type==OPT_FLAG ){
1716 *((int*)op[j].arg) = v;
1717 }else if( op[j].type==OPT_FFLAG ){
1718 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001719 }else if( op[j].type==OPT_FSTR ){
1720 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001721 }else{
1722 if( err ){
1723 fprintf(err,"%smissing argument on switch.\n",emsg);
1724 errline(i,1,err);
1725 }
1726 errcnt++;
1727 }
1728 return errcnt;
1729}
1730
1731/*
1732** Process a command line switch which has an argument.
1733*/
1734static int handleswitch(i,err)
1735int i;
1736FILE *err;
1737{
1738 int lv = 0;
1739 double dv = 0.0;
1740 char *sv = 0, *end;
1741 char *cp;
1742 int j;
1743 int errcnt = 0;
1744 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001745 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001746 *cp = 0;
1747 for(j=0; op[j].label; j++){
1748 if( strcmp(argv[i],op[j].label)==0 ) break;
1749 }
1750 *cp = '=';
1751 if( op[j].label==0 ){
1752 if( err ){
1753 fprintf(err,"%sundefined option.\n",emsg);
1754 errline(i,0,err);
1755 }
1756 errcnt++;
1757 }else{
1758 cp++;
1759 switch( op[j].type ){
1760 case OPT_FLAG:
1761 case OPT_FFLAG:
1762 if( err ){
1763 fprintf(err,"%soption requires an argument.\n",emsg);
1764 errline(i,0,err);
1765 }
1766 errcnt++;
1767 break;
1768 case OPT_DBL:
1769 case OPT_FDBL:
1770 dv = strtod(cp,&end);
1771 if( *end ){
1772 if( err ){
1773 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001774 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001775 }
1776 errcnt++;
1777 }
1778 break;
1779 case OPT_INT:
1780 case OPT_FINT:
1781 lv = strtol(cp,&end,0);
1782 if( *end ){
1783 if( err ){
1784 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001785 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001786 }
1787 errcnt++;
1788 }
1789 break;
1790 case OPT_STR:
1791 case OPT_FSTR:
1792 sv = cp;
1793 break;
1794 }
1795 switch( op[j].type ){
1796 case OPT_FLAG:
1797 case OPT_FFLAG:
1798 break;
1799 case OPT_DBL:
1800 *(double*)(op[j].arg) = dv;
1801 break;
1802 case OPT_FDBL:
1803 (*(void(*)())(op[j].arg))(dv);
1804 break;
1805 case OPT_INT:
1806 *(int*)(op[j].arg) = lv;
1807 break;
1808 case OPT_FINT:
1809 (*(void(*)())(op[j].arg))((int)lv);
1810 break;
1811 case OPT_STR:
1812 *(char**)(op[j].arg) = sv;
1813 break;
1814 case OPT_FSTR:
1815 (*(void(*)())(op[j].arg))(sv);
1816 break;
1817 }
1818 }
1819 return errcnt;
1820}
1821
drhb0c86772000-06-02 23:21:26 +00001822int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001823char **a;
1824struct s_options *o;
1825FILE *err;
1826{
1827 int errcnt = 0;
1828 argv = a;
1829 op = o;
1830 errstream = err;
1831 if( argv && *argv && op ){
1832 int i;
1833 for(i=1; argv[i]; i++){
1834 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1835 errcnt += handleflags(i,err);
1836 }else if( strchr(argv[i],'=') ){
1837 errcnt += handleswitch(i,err);
1838 }
1839 }
1840 }
1841 if( errcnt>0 ){
1842 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001843 OptPrint();
drh75897232000-05-29 14:26:00 +00001844 exit(1);
1845 }
1846 return 0;
1847}
1848
drhb0c86772000-06-02 23:21:26 +00001849int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001850 int cnt = 0;
1851 int dashdash = 0;
1852 int i;
1853 if( argv!=0 && argv[0]!=0 ){
1854 for(i=1; argv[i]; i++){
1855 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1856 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1857 }
1858 }
1859 return cnt;
1860}
1861
drhb0c86772000-06-02 23:21:26 +00001862char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001863int n;
1864{
1865 int i;
1866 i = argindex(n);
1867 return i>=0 ? argv[i] : 0;
1868}
1869
drhb0c86772000-06-02 23:21:26 +00001870void OptErr(n)
drh75897232000-05-29 14:26:00 +00001871int n;
1872{
1873 int i;
1874 i = argindex(n);
1875 if( i>=0 ) errline(i,0,errstream);
1876}
1877
drhb0c86772000-06-02 23:21:26 +00001878void OptPrint(){
drh75897232000-05-29 14:26:00 +00001879 int i;
1880 int max, len;
1881 max = 0;
1882 for(i=0; op[i].label; i++){
1883 len = strlen(op[i].label) + 1;
1884 switch( op[i].type ){
1885 case OPT_FLAG:
1886 case OPT_FFLAG:
1887 break;
1888 case OPT_INT:
1889 case OPT_FINT:
1890 len += 9; /* length of "<integer>" */
1891 break;
1892 case OPT_DBL:
1893 case OPT_FDBL:
1894 len += 6; /* length of "<real>" */
1895 break;
1896 case OPT_STR:
1897 case OPT_FSTR:
1898 len += 8; /* length of "<string>" */
1899 break;
1900 }
1901 if( len>max ) max = len;
1902 }
1903 for(i=0; op[i].label; i++){
1904 switch( op[i].type ){
1905 case OPT_FLAG:
1906 case OPT_FFLAG:
1907 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1908 break;
1909 case OPT_INT:
1910 case OPT_FINT:
1911 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001912 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001913 break;
1914 case OPT_DBL:
1915 case OPT_FDBL:
1916 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001917 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001918 break;
1919 case OPT_STR:
1920 case OPT_FSTR:
1921 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001922 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001923 break;
1924 }
1925 }
1926}
1927/*********************** From the file "parse.c" ****************************/
1928/*
1929** Input file parser for the LEMON parser generator.
1930*/
1931
1932/* The state of the parser */
1933struct pstate {
1934 char *filename; /* Name of the input file */
1935 int tokenlineno; /* Linenumber at which current token starts */
1936 int errorcnt; /* Number of errors so far */
1937 char *tokenstart; /* Text of current token */
1938 struct lemon *gp; /* Global state vector */
1939 enum e_state {
1940 INITIALIZE,
1941 WAITING_FOR_DECL_OR_RULE,
1942 WAITING_FOR_DECL_KEYWORD,
1943 WAITING_FOR_DECL_ARG,
1944 WAITING_FOR_PRECEDENCE_SYMBOL,
1945 WAITING_FOR_ARROW,
1946 IN_RHS,
1947 LHS_ALIAS_1,
1948 LHS_ALIAS_2,
1949 LHS_ALIAS_3,
1950 RHS_ALIAS_1,
1951 RHS_ALIAS_2,
1952 PRECEDENCE_MARK_1,
1953 PRECEDENCE_MARK_2,
1954 RESYNC_AFTER_RULE_ERROR,
1955 RESYNC_AFTER_DECL_ERROR,
1956 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001957 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001958 WAITING_FOR_FALLBACK_ID,
1959 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001960 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001961 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001962 struct symbol *lhs; /* Left-hand side of current rule */
1963 char *lhsalias; /* Alias for the LHS */
1964 int nrhs; /* Number of right-hand side symbols seen */
1965 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1966 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1967 struct rule *prevrule; /* Previous rule parsed */
1968 char *declkeyword; /* Keyword of a declaration */
1969 char **declargslot; /* Where the declaration argument should be put */
1970 int *decllnslot; /* Where the declaration linenumber is put */
1971 enum e_assoc declassoc; /* Assign this association to decl arguments */
1972 int preccounter; /* Assign this precedence to decl arguments */
1973 struct rule *firstrule; /* Pointer to first rule in the grammar */
1974 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1975};
1976
1977/* Parse a single token */
1978static void parseonetoken(psp)
1979struct pstate *psp;
1980{
1981 char *x;
1982 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1983#if 0
1984 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1985 x,psp->state);
1986#endif
1987 switch( psp->state ){
1988 case INITIALIZE:
1989 psp->prevrule = 0;
1990 psp->preccounter = 0;
1991 psp->firstrule = psp->lastrule = 0;
1992 psp->gp->nrule = 0;
1993 /* Fall thru to next case */
1994 case WAITING_FOR_DECL_OR_RULE:
1995 if( x[0]=='%' ){
1996 psp->state = WAITING_FOR_DECL_KEYWORD;
1997 }else if( islower(x[0]) ){
1998 psp->lhs = Symbol_new(x);
1999 psp->nrhs = 0;
2000 psp->lhsalias = 0;
2001 psp->state = WAITING_FOR_ARROW;
2002 }else if( x[0]=='{' ){
2003 if( psp->prevrule==0 ){
2004 ErrorMsg(psp->filename,psp->tokenlineno,
2005"There is not prior rule opon which to attach the code \
2006fragment which begins on this line.");
2007 psp->errorcnt++;
2008 }else if( psp->prevrule->code!=0 ){
2009 ErrorMsg(psp->filename,psp->tokenlineno,
2010"Code fragment beginning on this line is not the first \
2011to follow the previous rule.");
2012 psp->errorcnt++;
2013 }else{
2014 psp->prevrule->line = psp->tokenlineno;
2015 psp->prevrule->code = &x[1];
2016 }
2017 }else if( x[0]=='[' ){
2018 psp->state = PRECEDENCE_MARK_1;
2019 }else{
2020 ErrorMsg(psp->filename,psp->tokenlineno,
2021 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2022 x);
2023 psp->errorcnt++;
2024 }
2025 break;
2026 case PRECEDENCE_MARK_1:
2027 if( !isupper(x[0]) ){
2028 ErrorMsg(psp->filename,psp->tokenlineno,
2029 "The precedence symbol must be a terminal.");
2030 psp->errorcnt++;
2031 }else if( psp->prevrule==0 ){
2032 ErrorMsg(psp->filename,psp->tokenlineno,
2033 "There is no prior rule to assign precedence \"[%s]\".",x);
2034 psp->errorcnt++;
2035 }else if( psp->prevrule->precsym!=0 ){
2036 ErrorMsg(psp->filename,psp->tokenlineno,
2037"Precedence mark on this line is not the first \
2038to follow the previous rule.");
2039 psp->errorcnt++;
2040 }else{
2041 psp->prevrule->precsym = Symbol_new(x);
2042 }
2043 psp->state = PRECEDENCE_MARK_2;
2044 break;
2045 case PRECEDENCE_MARK_2:
2046 if( x[0]!=']' ){
2047 ErrorMsg(psp->filename,psp->tokenlineno,
2048 "Missing \"]\" on precedence mark.");
2049 psp->errorcnt++;
2050 }
2051 psp->state = WAITING_FOR_DECL_OR_RULE;
2052 break;
2053 case WAITING_FOR_ARROW:
2054 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2055 psp->state = IN_RHS;
2056 }else if( x[0]=='(' ){
2057 psp->state = LHS_ALIAS_1;
2058 }else{
2059 ErrorMsg(psp->filename,psp->tokenlineno,
2060 "Expected to see a \":\" following the LHS symbol \"%s\".",
2061 psp->lhs->name);
2062 psp->errorcnt++;
2063 psp->state = RESYNC_AFTER_RULE_ERROR;
2064 }
2065 break;
2066 case LHS_ALIAS_1:
2067 if( isalpha(x[0]) ){
2068 psp->lhsalias = x;
2069 psp->state = LHS_ALIAS_2;
2070 }else{
2071 ErrorMsg(psp->filename,psp->tokenlineno,
2072 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2073 x,psp->lhs->name);
2074 psp->errorcnt++;
2075 psp->state = RESYNC_AFTER_RULE_ERROR;
2076 }
2077 break;
2078 case LHS_ALIAS_2:
2079 if( x[0]==')' ){
2080 psp->state = LHS_ALIAS_3;
2081 }else{
2082 ErrorMsg(psp->filename,psp->tokenlineno,
2083 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2084 psp->errorcnt++;
2085 psp->state = RESYNC_AFTER_RULE_ERROR;
2086 }
2087 break;
2088 case LHS_ALIAS_3:
2089 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2090 psp->state = IN_RHS;
2091 }else{
2092 ErrorMsg(psp->filename,psp->tokenlineno,
2093 "Missing \"->\" following: \"%s(%s)\".",
2094 psp->lhs->name,psp->lhsalias);
2095 psp->errorcnt++;
2096 psp->state = RESYNC_AFTER_RULE_ERROR;
2097 }
2098 break;
2099 case IN_RHS:
2100 if( x[0]=='.' ){
2101 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002102 rp = (struct rule *)calloc( sizeof(struct rule) +
2103 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002104 if( rp==0 ){
2105 ErrorMsg(psp->filename,psp->tokenlineno,
2106 "Can't allocate enough memory for this rule.");
2107 psp->errorcnt++;
2108 psp->prevrule = 0;
2109 }else{
2110 int i;
2111 rp->ruleline = psp->tokenlineno;
2112 rp->rhs = (struct symbol**)&rp[1];
2113 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2114 for(i=0; i<psp->nrhs; i++){
2115 rp->rhs[i] = psp->rhs[i];
2116 rp->rhsalias[i] = psp->alias[i];
2117 }
2118 rp->lhs = psp->lhs;
2119 rp->lhsalias = psp->lhsalias;
2120 rp->nrhs = psp->nrhs;
2121 rp->code = 0;
2122 rp->precsym = 0;
2123 rp->index = psp->gp->nrule++;
2124 rp->nextlhs = rp->lhs->rule;
2125 rp->lhs->rule = rp;
2126 rp->next = 0;
2127 if( psp->firstrule==0 ){
2128 psp->firstrule = psp->lastrule = rp;
2129 }else{
2130 psp->lastrule->next = rp;
2131 psp->lastrule = rp;
2132 }
2133 psp->prevrule = rp;
2134 }
2135 psp->state = WAITING_FOR_DECL_OR_RULE;
2136 }else if( isalpha(x[0]) ){
2137 if( psp->nrhs>=MAXRHS ){
2138 ErrorMsg(psp->filename,psp->tokenlineno,
drhfd405312005-11-06 04:06:59 +00002139 "Too many symbols on RHS or rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002140 x);
2141 psp->errorcnt++;
2142 psp->state = RESYNC_AFTER_RULE_ERROR;
2143 }else{
2144 psp->rhs[psp->nrhs] = Symbol_new(x);
2145 psp->alias[psp->nrhs] = 0;
2146 psp->nrhs++;
2147 }
drhfd405312005-11-06 04:06:59 +00002148 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2149 struct symbol *msp = psp->rhs[psp->nrhs-1];
2150 if( msp->type!=MULTITERMINAL ){
2151 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002152 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002153 memset(msp, 0, sizeof(*msp));
2154 msp->type = MULTITERMINAL;
2155 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002156 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002157 msp->subsym[0] = origsp;
2158 msp->name = origsp->name;
2159 psp->rhs[psp->nrhs-1] = msp;
2160 }
2161 msp->nsubsym++;
2162 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2163 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2164 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2165 ErrorMsg(psp->filename,psp->tokenlineno,
2166 "Cannot form a compound containing a non-terminal");
2167 psp->errorcnt++;
2168 }
drh75897232000-05-29 14:26:00 +00002169 }else if( x[0]=='(' && psp->nrhs>0 ){
2170 psp->state = RHS_ALIAS_1;
2171 }else{
2172 ErrorMsg(psp->filename,psp->tokenlineno,
2173 "Illegal character on RHS of rule: \"%s\".",x);
2174 psp->errorcnt++;
2175 psp->state = RESYNC_AFTER_RULE_ERROR;
2176 }
2177 break;
2178 case RHS_ALIAS_1:
2179 if( isalpha(x[0]) ){
2180 psp->alias[psp->nrhs-1] = x;
2181 psp->state = RHS_ALIAS_2;
2182 }else{
2183 ErrorMsg(psp->filename,psp->tokenlineno,
2184 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2185 x,psp->rhs[psp->nrhs-1]->name);
2186 psp->errorcnt++;
2187 psp->state = RESYNC_AFTER_RULE_ERROR;
2188 }
2189 break;
2190 case RHS_ALIAS_2:
2191 if( x[0]==')' ){
2192 psp->state = IN_RHS;
2193 }else{
2194 ErrorMsg(psp->filename,psp->tokenlineno,
2195 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2196 psp->errorcnt++;
2197 psp->state = RESYNC_AFTER_RULE_ERROR;
2198 }
2199 break;
2200 case WAITING_FOR_DECL_KEYWORD:
2201 if( isalpha(x[0]) ){
2202 psp->declkeyword = x;
2203 psp->declargslot = 0;
2204 psp->decllnslot = 0;
2205 psp->state = WAITING_FOR_DECL_ARG;
2206 if( strcmp(x,"name")==0 ){
2207 psp->declargslot = &(psp->gp->name);
2208 }else if( strcmp(x,"include")==0 ){
2209 psp->declargslot = &(psp->gp->include);
2210 psp->decllnslot = &psp->gp->includeln;
2211 }else if( strcmp(x,"code")==0 ){
2212 psp->declargslot = &(psp->gp->extracode);
2213 psp->decllnslot = &psp->gp->extracodeln;
2214 }else if( strcmp(x,"token_destructor")==0 ){
2215 psp->declargslot = &psp->gp->tokendest;
2216 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00002217 }else if( strcmp(x,"default_destructor")==0 ){
2218 psp->declargslot = &psp->gp->vardest;
2219 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00002220 }else if( strcmp(x,"token_prefix")==0 ){
2221 psp->declargslot = &psp->gp->tokenprefix;
2222 }else if( strcmp(x,"syntax_error")==0 ){
2223 psp->declargslot = &(psp->gp->error);
2224 psp->decllnslot = &psp->gp->errorln;
2225 }else if( strcmp(x,"parse_accept")==0 ){
2226 psp->declargslot = &(psp->gp->accept);
2227 psp->decllnslot = &psp->gp->acceptln;
2228 }else if( strcmp(x,"parse_failure")==0 ){
2229 psp->declargslot = &(psp->gp->failure);
2230 psp->decllnslot = &psp->gp->failureln;
2231 }else if( strcmp(x,"stack_overflow")==0 ){
2232 psp->declargslot = &(psp->gp->overflow);
2233 psp->decllnslot = &psp->gp->overflowln;
2234 }else if( strcmp(x,"extra_argument")==0 ){
2235 psp->declargslot = &(psp->gp->arg);
2236 }else if( strcmp(x,"token_type")==0 ){
2237 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00002238 }else if( strcmp(x,"default_type")==0 ){
2239 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00002240 }else if( strcmp(x,"stack_size")==0 ){
2241 psp->declargslot = &(psp->gp->stacksize);
2242 }else if( strcmp(x,"start_symbol")==0 ){
2243 psp->declargslot = &(psp->gp->start);
2244 }else if( strcmp(x,"left")==0 ){
2245 psp->preccounter++;
2246 psp->declassoc = LEFT;
2247 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2248 }else if( strcmp(x,"right")==0 ){
2249 psp->preccounter++;
2250 psp->declassoc = RIGHT;
2251 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2252 }else if( strcmp(x,"nonassoc")==0 ){
2253 psp->preccounter++;
2254 psp->declassoc = NONE;
2255 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2256 }else if( strcmp(x,"destructor")==0 ){
2257 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2258 }else if( strcmp(x,"type")==0 ){
2259 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002260 }else if( strcmp(x,"fallback")==0 ){
2261 psp->fallback = 0;
2262 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002263 }else if( strcmp(x,"wildcard")==0 ){
2264 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002265 }else{
2266 ErrorMsg(psp->filename,psp->tokenlineno,
2267 "Unknown declaration keyword: \"%%%s\".",x);
2268 psp->errorcnt++;
2269 psp->state = RESYNC_AFTER_DECL_ERROR;
2270 }
2271 }else{
2272 ErrorMsg(psp->filename,psp->tokenlineno,
2273 "Illegal declaration keyword: \"%s\".",x);
2274 psp->errorcnt++;
2275 psp->state = RESYNC_AFTER_DECL_ERROR;
2276 }
2277 break;
2278 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2279 if( !isalpha(x[0]) ){
2280 ErrorMsg(psp->filename,psp->tokenlineno,
2281 "Symbol name missing after %destructor keyword");
2282 psp->errorcnt++;
2283 psp->state = RESYNC_AFTER_DECL_ERROR;
2284 }else{
2285 struct symbol *sp = Symbol_new(x);
2286 psp->declargslot = &sp->destructor;
2287 psp->decllnslot = &sp->destructorln;
2288 psp->state = WAITING_FOR_DECL_ARG;
2289 }
2290 break;
2291 case WAITING_FOR_DATATYPE_SYMBOL:
2292 if( !isalpha(x[0]) ){
2293 ErrorMsg(psp->filename,psp->tokenlineno,
2294 "Symbol name missing after %destructor keyword");
2295 psp->errorcnt++;
2296 psp->state = RESYNC_AFTER_DECL_ERROR;
2297 }else{
2298 struct symbol *sp = Symbol_new(x);
2299 psp->declargslot = &sp->datatype;
2300 psp->decllnslot = 0;
2301 psp->state = WAITING_FOR_DECL_ARG;
2302 }
2303 break;
2304 case WAITING_FOR_PRECEDENCE_SYMBOL:
2305 if( x[0]=='.' ){
2306 psp->state = WAITING_FOR_DECL_OR_RULE;
2307 }else if( isupper(x[0]) ){
2308 struct symbol *sp;
2309 sp = Symbol_new(x);
2310 if( sp->prec>=0 ){
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "Symbol \"%s\" has already be given a precedence.",x);
2313 psp->errorcnt++;
2314 }else{
2315 sp->prec = psp->preccounter;
2316 sp->assoc = psp->declassoc;
2317 }
2318 }else{
2319 ErrorMsg(psp->filename,psp->tokenlineno,
2320 "Can't assign a precedence to \"%s\".",x);
2321 psp->errorcnt++;
2322 }
2323 break;
2324 case WAITING_FOR_DECL_ARG:
2325 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2326 if( *(psp->declargslot)!=0 ){
2327 ErrorMsg(psp->filename,psp->tokenlineno,
2328 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2329 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2330 psp->errorcnt++;
2331 psp->state = RESYNC_AFTER_DECL_ERROR;
2332 }else{
2333 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2334 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2335 psp->state = WAITING_FOR_DECL_OR_RULE;
2336 }
2337 }else{
2338 ErrorMsg(psp->filename,psp->tokenlineno,
2339 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2340 psp->errorcnt++;
2341 psp->state = RESYNC_AFTER_DECL_ERROR;
2342 }
2343 break;
drh0bd1f4e2002-06-06 18:54:39 +00002344 case WAITING_FOR_FALLBACK_ID:
2345 if( x[0]=='.' ){
2346 psp->state = WAITING_FOR_DECL_OR_RULE;
2347 }else if( !isupper(x[0]) ){
2348 ErrorMsg(psp->filename, psp->tokenlineno,
2349 "%%fallback argument \"%s\" should be a token", x);
2350 psp->errorcnt++;
2351 }else{
2352 struct symbol *sp = Symbol_new(x);
2353 if( psp->fallback==0 ){
2354 psp->fallback = sp;
2355 }else if( sp->fallback ){
2356 ErrorMsg(psp->filename, psp->tokenlineno,
2357 "More than one fallback assigned to token %s", x);
2358 psp->errorcnt++;
2359 }else{
2360 sp->fallback = psp->fallback;
2361 psp->gp->has_fallback = 1;
2362 }
2363 }
2364 break;
drhe09daa92006-06-10 13:29:31 +00002365 case WAITING_FOR_WILDCARD_ID:
2366 if( x[0]=='.' ){
2367 psp->state = WAITING_FOR_DECL_OR_RULE;
2368 }else if( !isupper(x[0]) ){
2369 ErrorMsg(psp->filename, psp->tokenlineno,
2370 "%%wildcard argument \"%s\" should be a token", x);
2371 psp->errorcnt++;
2372 }else{
2373 struct symbol *sp = Symbol_new(x);
2374 if( psp->gp->wildcard==0 ){
2375 psp->gp->wildcard = sp;
2376 }else{
2377 ErrorMsg(psp->filename, psp->tokenlineno,
2378 "Extra wildcard to token: %s", x);
2379 psp->errorcnt++;
2380 }
2381 }
2382 break;
drh75897232000-05-29 14:26:00 +00002383 case RESYNC_AFTER_RULE_ERROR:
2384/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2385** break; */
2386 case RESYNC_AFTER_DECL_ERROR:
2387 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2388 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2389 break;
2390 }
2391}
2392
drh6d08b4d2004-07-20 12:45:22 +00002393/* Run the proprocessor over the input file text. The global variables
2394** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2395** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2396** comments them out. Text in between is also commented out as appropriate.
2397*/
danielk1977940fac92005-01-23 22:41:37 +00002398static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002399 int i, j, k, n;
2400 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002401 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002402 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002403 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002404 for(i=0; z[i]; i++){
2405 if( z[i]=='\n' ) lineno++;
2406 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2407 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2408 if( exclude ){
2409 exclude--;
2410 if( exclude==0 ){
2411 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2412 }
2413 }
2414 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2415 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2416 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2417 if( exclude ){
2418 exclude++;
2419 }else{
2420 for(j=i+7; isspace(z[j]); j++){}
2421 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2422 exclude = 1;
2423 for(k=0; k<nDefine; k++){
2424 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2425 exclude = 0;
2426 break;
2427 }
2428 }
2429 if( z[i+3]=='n' ) exclude = !exclude;
2430 if( exclude ){
2431 start = i;
2432 start_lineno = lineno;
2433 }
2434 }
2435 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2436 }
2437 }
2438 if( exclude ){
2439 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2440 exit(1);
2441 }
2442}
2443
drh75897232000-05-29 14:26:00 +00002444/* In spite of its name, this function is really a scanner. It read
2445** in the entire input file (all at once) then tokenizes it. Each
2446** token is passed to the function "parseonetoken" which builds all
2447** the appropriate data structures in the global state vector "gp".
2448*/
2449void Parse(gp)
2450struct lemon *gp;
2451{
2452 struct pstate ps;
2453 FILE *fp;
2454 char *filebuf;
2455 int filesize;
2456 int lineno;
2457 int c;
2458 char *cp, *nextcp;
2459 int startline = 0;
2460
rse38514a92007-09-20 11:34:17 +00002461 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002462 ps.gp = gp;
2463 ps.filename = gp->filename;
2464 ps.errorcnt = 0;
2465 ps.state = INITIALIZE;
2466
2467 /* Begin by reading the input file */
2468 fp = fopen(ps.filename,"rb");
2469 if( fp==0 ){
2470 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2471 gp->errorcnt++;
2472 return;
2473 }
2474 fseek(fp,0,2);
2475 filesize = ftell(fp);
2476 rewind(fp);
2477 filebuf = (char *)malloc( filesize+1 );
2478 if( filebuf==0 ){
2479 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2480 filesize+1);
2481 gp->errorcnt++;
2482 return;
2483 }
2484 if( fread(filebuf,1,filesize,fp)!=filesize ){
2485 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2486 filesize);
2487 free(filebuf);
2488 gp->errorcnt++;
2489 return;
2490 }
2491 fclose(fp);
2492 filebuf[filesize] = 0;
2493
drh6d08b4d2004-07-20 12:45:22 +00002494 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2495 preprocess_input(filebuf);
2496
drh75897232000-05-29 14:26:00 +00002497 /* Now scan the text of the input file */
2498 lineno = 1;
2499 for(cp=filebuf; (c= *cp)!=0; ){
2500 if( c=='\n' ) lineno++; /* Keep track of the line number */
2501 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2502 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2503 cp+=2;
2504 while( (c= *cp)!=0 && c!='\n' ) cp++;
2505 continue;
2506 }
2507 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2508 cp+=2;
2509 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2510 if( c=='\n' ) lineno++;
2511 cp++;
2512 }
2513 if( c ) cp++;
2514 continue;
2515 }
2516 ps.tokenstart = cp; /* Mark the beginning of the token */
2517 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2518 if( c=='\"' ){ /* String literals */
2519 cp++;
2520 while( (c= *cp)!=0 && c!='\"' ){
2521 if( c=='\n' ) lineno++;
2522 cp++;
2523 }
2524 if( c==0 ){
2525 ErrorMsg(ps.filename,startline,
2526"String starting on this line is not terminated before the end of the file.");
2527 ps.errorcnt++;
2528 nextcp = cp;
2529 }else{
2530 nextcp = cp+1;
2531 }
2532 }else if( c=='{' ){ /* A block of C code */
2533 int level;
2534 cp++;
2535 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2536 if( c=='\n' ) lineno++;
2537 else if( c=='{' ) level++;
2538 else if( c=='}' ) level--;
2539 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2540 int prevc;
2541 cp = &cp[2];
2542 prevc = 0;
2543 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2544 if( c=='\n' ) lineno++;
2545 prevc = c;
2546 cp++;
2547 }
2548 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2549 cp = &cp[2];
2550 while( (c= *cp)!=0 && c!='\n' ) cp++;
2551 if( c ) lineno++;
2552 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2553 int startchar, prevc;
2554 startchar = c;
2555 prevc = 0;
2556 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2557 if( c=='\n' ) lineno++;
2558 if( prevc=='\\' ) prevc = 0;
2559 else prevc = c;
2560 }
2561 }
2562 }
2563 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002564 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002565"C code starting on this line is not terminated before the end of the file.");
2566 ps.errorcnt++;
2567 nextcp = cp;
2568 }else{
2569 nextcp = cp+1;
2570 }
2571 }else if( isalnum(c) ){ /* Identifiers */
2572 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2573 nextcp = cp;
2574 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2575 cp += 3;
2576 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002577 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2578 cp += 2;
2579 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2580 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002581 }else{ /* All other (one character) operators */
2582 cp++;
2583 nextcp = cp;
2584 }
2585 c = *cp;
2586 *cp = 0; /* Null terminate the token */
2587 parseonetoken(&ps); /* Parse the token */
2588 *cp = c; /* Restore the buffer */
2589 cp = nextcp;
2590 }
2591 free(filebuf); /* Release the buffer after parsing */
2592 gp->rule = ps.firstrule;
2593 gp->errorcnt = ps.errorcnt;
2594}
2595/*************************** From the file "plink.c" *********************/
2596/*
2597** Routines processing configuration follow-set propagation links
2598** in the LEMON parser generator.
2599*/
2600static struct plink *plink_freelist = 0;
2601
2602/* Allocate a new plink */
2603struct plink *Plink_new(){
2604 struct plink *new;
2605
2606 if( plink_freelist==0 ){
2607 int i;
2608 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002609 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002610 if( plink_freelist==0 ){
2611 fprintf(stderr,
2612 "Unable to allocate memory for a new follow-set propagation link.\n");
2613 exit(1);
2614 }
2615 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2616 plink_freelist[amt-1].next = 0;
2617 }
2618 new = plink_freelist;
2619 plink_freelist = plink_freelist->next;
2620 return new;
2621}
2622
2623/* Add a plink to a plink list */
2624void Plink_add(plpp,cfp)
2625struct plink **plpp;
2626struct config *cfp;
2627{
2628 struct plink *new;
2629 new = Plink_new();
2630 new->next = *plpp;
2631 *plpp = new;
2632 new->cfp = cfp;
2633}
2634
2635/* Transfer every plink on the list "from" to the list "to" */
2636void Plink_copy(to,from)
2637struct plink **to;
2638struct plink *from;
2639{
2640 struct plink *nextpl;
2641 while( from ){
2642 nextpl = from->next;
2643 from->next = *to;
2644 *to = from;
2645 from = nextpl;
2646 }
2647}
2648
2649/* Delete every plink on the list */
2650void Plink_delete(plp)
2651struct plink *plp;
2652{
2653 struct plink *nextpl;
2654
2655 while( plp ){
2656 nextpl = plp->next;
2657 plp->next = plink_freelist;
2658 plink_freelist = plp;
2659 plp = nextpl;
2660 }
2661}
2662/*********************** From the file "report.c" **************************/
2663/*
2664** Procedures for generating reports and tables in the LEMON parser generator.
2665*/
2666
2667/* Generate a filename with the given suffix. Space to hold the
2668** name comes from malloc() and must be freed by the calling
2669** function.
2670*/
2671PRIVATE char *file_makename(lemp,suffix)
2672struct lemon *lemp;
2673char *suffix;
2674{
2675 char *name;
2676 char *cp;
2677
2678 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2679 if( name==0 ){
2680 fprintf(stderr,"Can't allocate space for a filename.\n");
2681 exit(1);
2682 }
2683 strcpy(name,lemp->filename);
2684 cp = strrchr(name,'.');
2685 if( cp ) *cp = 0;
2686 strcat(name,suffix);
2687 return name;
2688}
2689
2690/* Open a file with a name based on the name of the input file,
2691** but with a different (specified) suffix, and return a pointer
2692** to the stream */
2693PRIVATE FILE *file_open(lemp,suffix,mode)
2694struct lemon *lemp;
2695char *suffix;
2696char *mode;
2697{
2698 FILE *fp;
2699
2700 if( lemp->outname ) free(lemp->outname);
2701 lemp->outname = file_makename(lemp, suffix);
2702 fp = fopen(lemp->outname,mode);
2703 if( fp==0 && *mode=='w' ){
2704 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2705 lemp->errorcnt++;
2706 return 0;
2707 }
2708 return fp;
2709}
2710
2711/* Duplicate the input file without comments and without actions
2712** on rules */
2713void Reprint(lemp)
2714struct lemon *lemp;
2715{
2716 struct rule *rp;
2717 struct symbol *sp;
2718 int i, j, maxlen, len, ncolumns, skip;
2719 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2720 maxlen = 10;
2721 for(i=0; i<lemp->nsymbol; i++){
2722 sp = lemp->symbols[i];
2723 len = strlen(sp->name);
2724 if( len>maxlen ) maxlen = len;
2725 }
2726 ncolumns = 76/(maxlen+5);
2727 if( ncolumns<1 ) ncolumns = 1;
2728 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2729 for(i=0; i<skip; i++){
2730 printf("//");
2731 for(j=i; j<lemp->nsymbol; j+=skip){
2732 sp = lemp->symbols[j];
2733 assert( sp->index==j );
2734 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2735 }
2736 printf("\n");
2737 }
2738 for(rp=lemp->rule; rp; rp=rp->next){
2739 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002740 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002741 printf(" ::=");
2742 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002743 sp = rp->rhs[i];
2744 printf(" %s", sp->name);
2745 if( sp->type==MULTITERMINAL ){
2746 for(j=1; j<sp->nsubsym; j++){
2747 printf("|%s", sp->subsym[j]->name);
2748 }
2749 }
2750 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002751 }
2752 printf(".");
2753 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002754 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002755 printf("\n");
2756 }
2757}
2758
2759void ConfigPrint(fp,cfp)
2760FILE *fp;
2761struct config *cfp;
2762{
2763 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002764 struct symbol *sp;
2765 int i, j;
drh75897232000-05-29 14:26:00 +00002766 rp = cfp->rp;
2767 fprintf(fp,"%s ::=",rp->lhs->name);
2768 for(i=0; i<=rp->nrhs; i++){
2769 if( i==cfp->dot ) fprintf(fp," *");
2770 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002771 sp = rp->rhs[i];
2772 fprintf(fp," %s", sp->name);
2773 if( sp->type==MULTITERMINAL ){
2774 for(j=1; j<sp->nsubsym; j++){
2775 fprintf(fp,"|%s",sp->subsym[j]->name);
2776 }
2777 }
drh75897232000-05-29 14:26:00 +00002778 }
2779}
2780
2781/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002782#if 0
drh75897232000-05-29 14:26:00 +00002783/* Print a set */
2784PRIVATE void SetPrint(out,set,lemp)
2785FILE *out;
2786char *set;
2787struct lemon *lemp;
2788{
2789 int i;
2790 char *spacer;
2791 spacer = "";
2792 fprintf(out,"%12s[","");
2793 for(i=0; i<lemp->nterminal; i++){
2794 if( SetFind(set,i) ){
2795 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2796 spacer = " ";
2797 }
2798 }
2799 fprintf(out,"]\n");
2800}
2801
2802/* Print a plink chain */
2803PRIVATE void PlinkPrint(out,plp,tag)
2804FILE *out;
2805struct plink *plp;
2806char *tag;
2807{
2808 while( plp ){
drhada354d2005-11-05 15:03:59 +00002809 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002810 ConfigPrint(out,plp->cfp);
2811 fprintf(out,"\n");
2812 plp = plp->next;
2813 }
2814}
2815#endif
2816
2817/* Print an action to the given file descriptor. Return FALSE if
2818** nothing was actually printed.
2819*/
2820int PrintAction(struct action *ap, FILE *fp, int indent){
2821 int result = 1;
2822 switch( ap->type ){
2823 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002824 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002825 break;
2826 case REDUCE:
2827 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2828 break;
2829 case ACCEPT:
2830 fprintf(fp,"%*s accept",indent,ap->sp->name);
2831 break;
2832 case ERROR:
2833 fprintf(fp,"%*s error",indent,ap->sp->name);
2834 break;
drh9892c5d2007-12-21 00:02:11 +00002835 case SRCONFLICT:
2836 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002837 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2838 indent,ap->sp->name,ap->x.rp->index);
2839 break;
drh9892c5d2007-12-21 00:02:11 +00002840 case SSCONFLICT:
2841 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2842 indent,ap->sp->name,ap->x.stp->statenum);
2843 break;
drh75897232000-05-29 14:26:00 +00002844 case SH_RESOLVED:
2845 case RD_RESOLVED:
2846 case NOT_USED:
2847 result = 0;
2848 break;
2849 }
2850 return result;
2851}
2852
2853/* Generate the "y.output" log file */
2854void ReportOutput(lemp)
2855struct lemon *lemp;
2856{
2857 int i;
2858 struct state *stp;
2859 struct config *cfp;
2860 struct action *ap;
2861 FILE *fp;
2862
drh2aa6ca42004-09-10 00:14:04 +00002863 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002864 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002865 for(i=0; i<lemp->nstate; i++){
2866 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002867 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002868 if( lemp->basisflag ) cfp=stp->bp;
2869 else cfp=stp->cfp;
2870 while( cfp ){
2871 char buf[20];
2872 if( cfp->dot==cfp->rp->nrhs ){
2873 sprintf(buf,"(%d)",cfp->rp->index);
2874 fprintf(fp," %5s ",buf);
2875 }else{
2876 fprintf(fp," ");
2877 }
2878 ConfigPrint(fp,cfp);
2879 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002880#if 0
drh75897232000-05-29 14:26:00 +00002881 SetPrint(fp,cfp->fws,lemp);
2882 PlinkPrint(fp,cfp->fplp,"To ");
2883 PlinkPrint(fp,cfp->bplp,"From");
2884#endif
2885 if( lemp->basisflag ) cfp=cfp->bp;
2886 else cfp=cfp->next;
2887 }
2888 fprintf(fp,"\n");
2889 for(ap=stp->ap; ap; ap=ap->next){
2890 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2891 }
2892 fprintf(fp,"\n");
2893 }
drhe9278182007-07-18 18:16:29 +00002894 fprintf(fp, "----------------------------------------------------\n");
2895 fprintf(fp, "Symbols:\n");
2896 for(i=0; i<lemp->nsymbol; i++){
2897 int j;
2898 struct symbol *sp;
2899
2900 sp = lemp->symbols[i];
2901 fprintf(fp, " %3d: %s", i, sp->name);
2902 if( sp->type==NONTERMINAL ){
2903 fprintf(fp, ":");
2904 if( sp->lambda ){
2905 fprintf(fp, " <lambda>");
2906 }
2907 for(j=0; j<lemp->nterminal; j++){
2908 if( sp->firstset && SetFind(sp->firstset, j) ){
2909 fprintf(fp, " %s", lemp->symbols[j]->name);
2910 }
2911 }
2912 }
2913 fprintf(fp, "\n");
2914 }
drh75897232000-05-29 14:26:00 +00002915 fclose(fp);
2916 return;
2917}
2918
2919/* Search for the file "name" which is in the same directory as
2920** the exacutable */
2921PRIVATE char *pathsearch(argv0,name,modemask)
2922char *argv0;
2923char *name;
2924int modemask;
2925{
2926 char *pathlist;
2927 char *path,*cp;
2928 char c;
drh75897232000-05-29 14:26:00 +00002929
2930#ifdef __WIN32__
2931 cp = strrchr(argv0,'\\');
2932#else
2933 cp = strrchr(argv0,'/');
2934#endif
2935 if( cp ){
2936 c = *cp;
2937 *cp = 0;
2938 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2939 if( path ) sprintf(path,"%s/%s",argv0,name);
2940 *cp = c;
2941 }else{
2942 extern char *getenv();
2943 pathlist = getenv("PATH");
2944 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2945 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2946 if( path!=0 ){
2947 while( *pathlist ){
2948 cp = strchr(pathlist,':');
2949 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2950 c = *cp;
2951 *cp = 0;
2952 sprintf(path,"%s/%s",pathlist,name);
2953 *cp = c;
2954 if( c==0 ) pathlist = "";
2955 else pathlist = &cp[1];
2956 if( access(path,modemask)==0 ) break;
2957 }
2958 }
2959 }
2960 return path;
2961}
2962
2963/* Given an action, compute the integer value for that action
2964** which is to be put in the action table of the generated machine.
2965** Return negative if no action should be generated.
2966*/
2967PRIVATE int compute_action(lemp,ap)
2968struct lemon *lemp;
2969struct action *ap;
2970{
2971 int act;
2972 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00002973 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00002974 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2975 case ERROR: act = lemp->nstate + lemp->nrule; break;
2976 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2977 default: act = -1; break;
2978 }
2979 return act;
2980}
2981
2982#define LINESIZE 1000
2983/* The next cluster of routines are for reading the template file
2984** and writing the results to the generated parser */
2985/* The first function transfers data from "in" to "out" until
2986** a line is seen which begins with "%%". The line number is
2987** tracked.
2988**
2989** if name!=0, then any word that begin with "Parse" is changed to
2990** begin with *name instead.
2991*/
2992PRIVATE void tplt_xfer(name,in,out,lineno)
2993char *name;
2994FILE *in;
2995FILE *out;
2996int *lineno;
2997{
2998 int i, iStart;
2999 char line[LINESIZE];
3000 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3001 (*lineno)++;
3002 iStart = 0;
3003 if( name ){
3004 for(i=0; line[i]; i++){
3005 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3006 && (i==0 || !isalpha(line[i-1]))
3007 ){
3008 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3009 fprintf(out,"%s",name);
3010 i += 4;
3011 iStart = i+1;
3012 }
3013 }
3014 }
3015 fprintf(out,"%s",&line[iStart]);
3016 }
3017}
3018
3019/* The next function finds the template file and opens it, returning
3020** a pointer to the opened file. */
3021PRIVATE FILE *tplt_open(lemp)
3022struct lemon *lemp;
3023{
3024 static char templatename[] = "lempar.c";
3025 char buf[1000];
3026 FILE *in;
3027 char *tpltname;
3028 char *cp;
3029
3030 cp = strrchr(lemp->filename,'.');
3031 if( cp ){
drh8b582012003-10-21 13:16:03 +00003032 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003033 }else{
3034 sprintf(buf,"%s.lt",lemp->filename);
3035 }
3036 if( access(buf,004)==0 ){
3037 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003038 }else if( access(templatename,004)==0 ){
3039 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003040 }else{
3041 tpltname = pathsearch(lemp->argv0,templatename,0);
3042 }
3043 if( tpltname==0 ){
3044 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3045 templatename);
3046 lemp->errorcnt++;
3047 return 0;
3048 }
drh2aa6ca42004-09-10 00:14:04 +00003049 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003050 if( in==0 ){
3051 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3052 lemp->errorcnt++;
3053 return 0;
3054 }
3055 return in;
3056}
3057
drhaf805ca2004-09-07 11:28:25 +00003058/* Print a #line directive line to the output file. */
3059PRIVATE void tplt_linedir(out,lineno,filename)
3060FILE *out;
3061int lineno;
3062char *filename;
3063{
3064 fprintf(out,"#line %d \"",lineno);
3065 while( *filename ){
3066 if( *filename == '\\' ) putc('\\',out);
3067 putc(*filename,out);
3068 filename++;
3069 }
3070 fprintf(out,"\"\n");
3071}
3072
drh75897232000-05-29 14:26:00 +00003073/* Print a string to the file and keep the linenumber up to date */
3074PRIVATE void tplt_print(out,lemp,str,strln,lineno)
3075FILE *out;
3076struct lemon *lemp;
3077char *str;
3078int strln;
3079int *lineno;
3080{
3081 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003082 tplt_linedir(out,strln,lemp->filename);
3083 (*lineno)++;
drh75897232000-05-29 14:26:00 +00003084 while( *str ){
3085 if( *str=='\n' ) (*lineno)++;
3086 putc(*str,out);
3087 str++;
3088 }
drh9db55df2004-09-09 14:01:21 +00003089 if( str[-1]!='\n' ){
3090 putc('\n',out);
3091 (*lineno)++;
3092 }
drhaf805ca2004-09-07 11:28:25 +00003093 tplt_linedir(out,*lineno+2,lemp->outname);
3094 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00003095 return;
3096}
3097
3098/*
3099** The following routine emits code for the destructor for the
3100** symbol sp
3101*/
3102void emit_destructor_code(out,sp,lemp,lineno)
3103FILE *out;
3104struct symbol *sp;
3105struct lemon *lemp;
3106int *lineno;
3107{
drhcc83b6e2004-04-23 23:38:42 +00003108 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003109
3110 int linecnt = 0;
3111 if( sp->type==TERMINAL ){
3112 cp = lemp->tokendest;
3113 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003114 tplt_linedir(out,lemp->tokendestln,lemp->filename);
3115 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00003116 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003117 cp = sp->destructor;
drhaf805ca2004-09-07 11:28:25 +00003118 tplt_linedir(out,sp->destructorln,lemp->filename);
3119 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00003120 }else if( lemp->vardest ){
3121 cp = lemp->vardest;
3122 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003123 tplt_linedir(out,lemp->vardestln,lemp->filename);
3124 fprintf(out,"{");
drhcc83b6e2004-04-23 23:38:42 +00003125 }else{
3126 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003127 }
3128 for(; *cp; cp++){
3129 if( *cp=='$' && cp[1]=='$' ){
3130 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3131 cp++;
3132 continue;
3133 }
3134 if( *cp=='\n' ) linecnt++;
3135 fputc(*cp,out);
3136 }
3137 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003138 fprintf(out,"}\n");
3139 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003140 return;
3141}
3142
3143/*
drh960e8c62001-04-03 16:53:21 +00003144** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003145*/
3146int has_destructor(sp, lemp)
3147struct symbol *sp;
3148struct lemon *lemp;
3149{
3150 int ret;
3151 if( sp->type==TERMINAL ){
3152 ret = lemp->tokendest!=0;
3153 }else{
drh960e8c62001-04-03 16:53:21 +00003154 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003155 }
3156 return ret;
3157}
3158
drh0bb132b2004-07-20 14:06:51 +00003159/*
3160** Append text to a dynamically allocated string. If zText is 0 then
3161** reset the string to be empty again. Always return the complete text
3162** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003163**
3164** n bytes of zText are stored. If n==0 then all of zText up to the first
3165** \000 terminator is stored. zText can contain up to two instances of
3166** %d. The values of p1 and p2 are written into the first and second
3167** %d.
3168**
3169** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003170*/
3171PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3172 static char *z = 0;
3173 static int alloced = 0;
3174 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003175 int c;
drh0bb132b2004-07-20 14:06:51 +00003176 char zInt[40];
3177
3178 if( zText==0 ){
3179 used = 0;
3180 return z;
3181 }
drh7ac25c72004-08-19 15:12:26 +00003182 if( n<=0 ){
3183 if( n<0 ){
3184 used += n;
3185 assert( used>=0 );
3186 }
3187 n = strlen(zText);
3188 }
drh0bb132b2004-07-20 14:06:51 +00003189 if( n+sizeof(zInt)*2+used >= alloced ){
3190 alloced = n + sizeof(zInt)*2 + used + 200;
3191 z = realloc(z, alloced);
3192 }
3193 if( z==0 ) return "";
3194 while( n-- > 0 ){
3195 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003196 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003197 sprintf(zInt, "%d", p1);
3198 p1 = p2;
3199 strcpy(&z[used], zInt);
3200 used += strlen(&z[used]);
3201 zText++;
3202 n--;
3203 }else{
3204 z[used++] = c;
3205 }
3206 }
3207 z[used] = 0;
3208 return z;
3209}
3210
3211/*
3212** zCode is a string that is the action associated with a rule. Expand
3213** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003214** stack.
drh0bb132b2004-07-20 14:06:51 +00003215*/
drhaf805ca2004-09-07 11:28:25 +00003216PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003217 char *cp, *xp;
3218 int i;
3219 char lhsused = 0; /* True if the LHS element has been used */
3220 char used[MAXRHS]; /* True for each RHS element which is used */
3221
3222 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3223 lhsused = 0;
3224
drh19c9e562007-03-29 20:13:53 +00003225 if( rp->code==0 ){
3226 rp->code = "\n";
3227 rp->line = rp->ruleline;
3228 }
3229
drh0bb132b2004-07-20 14:06:51 +00003230 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003231 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003232 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3233 char saved;
3234 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3235 saved = *xp;
3236 *xp = 0;
3237 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003238 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003239 cp = xp;
3240 lhsused = 1;
3241 }else{
3242 for(i=0; i<rp->nrhs; i++){
3243 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003244 if( cp!=rp->code && cp[-1]=='@' ){
3245 /* If the argument is of the form @X then substituted
3246 ** the token number of X, not the value of X */
3247 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3248 }else{
drhfd405312005-11-06 04:06:59 +00003249 struct symbol *sp = rp->rhs[i];
3250 int dtnum;
3251 if( sp->type==MULTITERMINAL ){
3252 dtnum = sp->subsym[0]->dtnum;
3253 }else{
3254 dtnum = sp->dtnum;
3255 }
3256 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003257 }
drh0bb132b2004-07-20 14:06:51 +00003258 cp = xp;
3259 used[i] = 1;
3260 break;
3261 }
3262 }
3263 }
3264 *xp = saved;
3265 }
3266 append_str(cp, 1, 0, 0);
3267 } /* End loop */
3268
3269 /* Check to make sure the LHS has been used */
3270 if( rp->lhsalias && !lhsused ){
3271 ErrorMsg(lemp->filename,rp->ruleline,
3272 "Label \"%s\" for \"%s(%s)\" is never used.",
3273 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3274 lemp->errorcnt++;
3275 }
3276
3277 /* Generate destructor code for RHS symbols which are not used in the
3278 ** reduce code */
3279 for(i=0; i<rp->nrhs; i++){
3280 if( rp->rhsalias[i] && !used[i] ){
3281 ErrorMsg(lemp->filename,rp->ruleline,
3282 "Label %s for \"%s(%s)\" is never used.",
3283 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3284 lemp->errorcnt++;
3285 }else if( rp->rhsalias[i]==0 ){
3286 if( has_destructor(rp->rhs[i],lemp) ){
drh7ac25c72004-08-19 15:12:26 +00003287 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003288 rp->rhs[i]->index,i-rp->nrhs+1);
3289 }else{
3290 /* No destructor defined for this term */
3291 }
3292 }
3293 }
drh61e339a2007-01-16 03:09:02 +00003294 if( rp->code ){
3295 cp = append_str(0,0,0,0);
3296 rp->code = Strsafe(cp?cp:"");
3297 }
drh0bb132b2004-07-20 14:06:51 +00003298}
3299
drh75897232000-05-29 14:26:00 +00003300/*
3301** Generate code which executes when the rule "rp" is reduced. Write
3302** the code to "out". Make sure lineno stays up-to-date.
3303*/
3304PRIVATE void emit_code(out,rp,lemp,lineno)
3305FILE *out;
3306struct rule *rp;
3307struct lemon *lemp;
3308int *lineno;
3309{
drh0bb132b2004-07-20 14:06:51 +00003310 char *cp;
drh75897232000-05-29 14:26:00 +00003311 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003312
3313 /* Generate code to do the reduce action */
3314 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003315 tplt_linedir(out,rp->line,lemp->filename);
3316 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003317 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003318 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003319 } /* End loop */
3320 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003321 fprintf(out,"}\n");
3322 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003323 } /* End if( rp->code ) */
3324
drh75897232000-05-29 14:26:00 +00003325 return;
3326}
3327
3328/*
3329** Print the definition of the union used for the parser's data stack.
3330** This union contains fields for every possible data type for tokens
3331** and nonterminals. In the process of computing and printing this
3332** union, also set the ".dtnum" field of every terminal and nonterminal
3333** symbol.
3334*/
3335void print_stack_union(out,lemp,plineno,mhflag)
3336FILE *out; /* The output stream */
3337struct lemon *lemp; /* The main info structure for this parser */
3338int *plineno; /* Pointer to the line number */
3339int mhflag; /* True if generating makeheaders output */
3340{
3341 int lineno = *plineno; /* The line number of the output */
3342 char **types; /* A hash table of datatypes */
3343 int arraysize; /* Size of the "types" array */
3344 int maxdtlength; /* Maximum length of any ".datatype" field. */
3345 char *stddt; /* Standardized name for a datatype */
3346 int i,j; /* Loop counters */
3347 int hash; /* For hashing the name of a type */
3348 char *name; /* Name of the parser */
3349
3350 /* Allocate and initialize types[] and allocate stddt[] */
3351 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003352 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003353 for(i=0; i<arraysize; i++) types[i] = 0;
3354 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003355 if( lemp->vartype ){
3356 maxdtlength = strlen(lemp->vartype);
3357 }
drh75897232000-05-29 14:26:00 +00003358 for(i=0; i<lemp->nsymbol; i++){
3359 int len;
3360 struct symbol *sp = lemp->symbols[i];
3361 if( sp->datatype==0 ) continue;
3362 len = strlen(sp->datatype);
3363 if( len>maxdtlength ) maxdtlength = len;
3364 }
3365 stddt = (char*)malloc( maxdtlength*2 + 1 );
3366 if( types==0 || stddt==0 ){
3367 fprintf(stderr,"Out of memory.\n");
3368 exit(1);
3369 }
3370
3371 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3372 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003373 ** used for terminal symbols. If there is no %default_type defined then
3374 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3375 ** a datatype using the %type directive.
3376 */
drh75897232000-05-29 14:26:00 +00003377 for(i=0; i<lemp->nsymbol; i++){
3378 struct symbol *sp = lemp->symbols[i];
3379 char *cp;
3380 if( sp==lemp->errsym ){
3381 sp->dtnum = arraysize+1;
3382 continue;
3383 }
drh960e8c62001-04-03 16:53:21 +00003384 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003385 sp->dtnum = 0;
3386 continue;
3387 }
3388 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003389 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003390 j = 0;
3391 while( isspace(*cp) ) cp++;
3392 while( *cp ) stddt[j++] = *cp++;
3393 while( j>0 && isspace(stddt[j-1]) ) j--;
3394 stddt[j] = 0;
3395 hash = 0;
3396 for(j=0; stddt[j]; j++){
3397 hash = hash*53 + stddt[j];
3398 }
drh3b2129c2003-05-13 00:34:21 +00003399 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003400 while( types[hash] ){
3401 if( strcmp(types[hash],stddt)==0 ){
3402 sp->dtnum = hash + 1;
3403 break;
3404 }
3405 hash++;
3406 if( hash>=arraysize ) hash = 0;
3407 }
3408 if( types[hash]==0 ){
3409 sp->dtnum = hash + 1;
3410 types[hash] = (char*)malloc( strlen(stddt)+1 );
3411 if( types[hash]==0 ){
3412 fprintf(stderr,"Out of memory.\n");
3413 exit(1);
3414 }
3415 strcpy(types[hash],stddt);
3416 }
3417 }
3418
3419 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3420 name = lemp->name ? lemp->name : "Parse";
3421 lineno = *plineno;
3422 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3423 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3424 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3425 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3426 fprintf(out,"typedef union {\n"); lineno++;
3427 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3428 for(i=0; i<arraysize; i++){
3429 if( types[i]==0 ) continue;
3430 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3431 free(types[i]);
3432 }
3433 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3434 free(stddt);
3435 free(types);
3436 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3437 *plineno = lineno;
3438}
3439
drhb29b0a52002-02-23 19:39:46 +00003440/*
3441** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003442** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003443*/
drh8b582012003-10-21 13:16:03 +00003444static const char *minimum_size_type(int lwr, int upr){
3445 if( lwr>=0 ){
3446 if( upr<=255 ){
3447 return "unsigned char";
3448 }else if( upr<65535 ){
3449 return "unsigned short int";
3450 }else{
3451 return "unsigned int";
3452 }
3453 }else if( lwr>=-127 && upr<=127 ){
3454 return "signed char";
3455 }else if( lwr>=-32767 && upr<32767 ){
3456 return "short";
drhb29b0a52002-02-23 19:39:46 +00003457 }else{
drh8b582012003-10-21 13:16:03 +00003458 return "int";
drhb29b0a52002-02-23 19:39:46 +00003459 }
3460}
3461
drhfdbf9282003-10-21 16:34:41 +00003462/*
3463** Each state contains a set of token transaction and a set of
3464** nonterminal transactions. Each of these sets makes an instance
3465** of the following structure. An array of these structures is used
3466** to order the creation of entries in the yy_action[] table.
3467*/
3468struct axset {
3469 struct state *stp; /* A pointer to a state */
3470 int isTkn; /* True to use tokens. False for non-terminals */
3471 int nAction; /* Number of actions */
3472};
3473
3474/*
3475** Compare to axset structures for sorting purposes
3476*/
3477static int axset_compare(const void *a, const void *b){
3478 struct axset *p1 = (struct axset*)a;
3479 struct axset *p2 = (struct axset*)b;
3480 return p2->nAction - p1->nAction;
3481}
3482
drh75897232000-05-29 14:26:00 +00003483/* Generate C source code for the parser */
3484void ReportTable(lemp, mhflag)
3485struct lemon *lemp;
3486int mhflag; /* Output in makeheaders format if true */
3487{
3488 FILE *out, *in;
3489 char line[LINESIZE];
3490 int lineno;
3491 struct state *stp;
3492 struct action *ap;
3493 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003494 struct acttab *pActtab;
3495 int i, j, n;
drh75897232000-05-29 14:26:00 +00003496 char *name;
drh8b582012003-10-21 13:16:03 +00003497 int mnTknOfst, mxTknOfst;
3498 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003499 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003500
3501 in = tplt_open(lemp);
3502 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003503 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003504 if( out==0 ){
3505 fclose(in);
3506 return;
3507 }
3508 lineno = 1;
3509 tplt_xfer(lemp->name,in,out,&lineno);
3510
3511 /* Generate the include code, if any */
3512 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3513 if( mhflag ){
3514 char *name = file_makename(lemp, ".h");
3515 fprintf(out,"#include \"%s\"\n", name); lineno++;
3516 free(name);
3517 }
3518 tplt_xfer(lemp->name,in,out,&lineno);
3519
3520 /* Generate #defines for all tokens */
3521 if( mhflag ){
3522 char *prefix;
3523 fprintf(out,"#if INTERFACE\n"); lineno++;
3524 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3525 else prefix = "";
3526 for(i=1; i<lemp->nterminal; i++){
3527 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3528 lineno++;
3529 }
3530 fprintf(out,"#endif\n"); lineno++;
3531 }
3532 tplt_xfer(lemp->name,in,out,&lineno);
3533
3534 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003535 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003536 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003537 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3538 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003539 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003540 if( lemp->wildcard ){
3541 fprintf(out,"#define YYWILDCARD %d\n",
3542 lemp->wildcard->index); lineno++;
3543 }
drh75897232000-05-29 14:26:00 +00003544 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003545 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003546 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003547 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3548 }else{
3549 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3550 }
drhca44b5a2007-02-22 23:06:58 +00003551 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003552 if( mhflag ){
3553 fprintf(out,"#if INTERFACE\n"); lineno++;
3554 }
3555 name = lemp->name ? lemp->name : "Parse";
3556 if( lemp->arg && lemp->arg[0] ){
3557 int i;
3558 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003559 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3560 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003561 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3562 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3563 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3564 name,lemp->arg,&lemp->arg[i]); lineno++;
3565 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3566 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003567 }else{
drh1f245e42002-03-11 13:55:50 +00003568 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3569 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3570 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3571 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003572 }
3573 if( mhflag ){
3574 fprintf(out,"#endif\n"); lineno++;
3575 }
3576 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3577 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3578 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3579 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drh0bd1f4e2002-06-06 18:54:39 +00003580 if( lemp->has_fallback ){
3581 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3582 }
drh75897232000-05-29 14:26:00 +00003583 tplt_xfer(lemp->name,in,out,&lineno);
3584
drh8b582012003-10-21 13:16:03 +00003585 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003586 **
drh8b582012003-10-21 13:16:03 +00003587 ** yy_action[] A single table containing all actions.
3588 ** yy_lookahead[] A table containing the lookahead for each entry in
3589 ** yy_action. Used to detect hash collisions.
3590 ** yy_shift_ofst[] For each state, the offset into yy_action for
3591 ** shifting terminals.
3592 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3593 ** shifting non-terminals after a reduce.
3594 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003595 */
drh75897232000-05-29 14:26:00 +00003596
drh8b582012003-10-21 13:16:03 +00003597 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003598 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003599 if( ax==0 ){
3600 fprintf(stderr,"malloc failed\n");
3601 exit(1);
3602 }
drh75897232000-05-29 14:26:00 +00003603 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003604 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003605 ax[i*2].stp = stp;
3606 ax[i*2].isTkn = 1;
3607 ax[i*2].nAction = stp->nTknAct;
3608 ax[i*2+1].stp = stp;
3609 ax[i*2+1].isTkn = 0;
3610 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003611 }
drh8b582012003-10-21 13:16:03 +00003612 mxTknOfst = mnTknOfst = 0;
3613 mxNtOfst = mnNtOfst = 0;
3614
drhfdbf9282003-10-21 16:34:41 +00003615 /* Compute the action table. In order to try to keep the size of the
3616 ** action table to a minimum, the heuristic of placing the largest action
3617 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003618 */
drhfdbf9282003-10-21 16:34:41 +00003619 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003620 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003621 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3622 stp = ax[i].stp;
3623 if( ax[i].isTkn ){
3624 for(ap=stp->ap; ap; ap=ap->next){
3625 int action;
3626 if( ap->sp->index>=lemp->nterminal ) continue;
3627 action = compute_action(lemp, ap);
3628 if( action<0 ) continue;
3629 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003630 }
drhfdbf9282003-10-21 16:34:41 +00003631 stp->iTknOfst = acttab_insert(pActtab);
3632 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3633 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3634 }else{
3635 for(ap=stp->ap; ap; ap=ap->next){
3636 int action;
3637 if( ap->sp->index<lemp->nterminal ) continue;
3638 if( ap->sp->index==lemp->nsymbol ) continue;
3639 action = compute_action(lemp, ap);
3640 if( action<0 ) continue;
3641 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003642 }
drhfdbf9282003-10-21 16:34:41 +00003643 stp->iNtOfst = acttab_insert(pActtab);
3644 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3645 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003646 }
3647 }
drhfdbf9282003-10-21 16:34:41 +00003648 free(ax);
drh8b582012003-10-21 13:16:03 +00003649
3650 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003651 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003652 n = acttab_size(pActtab);
3653 for(i=j=0; i<n; i++){
3654 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003655 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003656 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003657 fprintf(out, " %4d,", action);
3658 if( j==9 || i==n-1 ){
3659 fprintf(out, "\n"); lineno++;
3660 j = 0;
3661 }else{
3662 j++;
3663 }
3664 }
3665 fprintf(out, "};\n"); lineno++;
3666
3667 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003668 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003669 for(i=j=0; i<n; i++){
3670 int la = acttab_yylookahead(pActtab, i);
3671 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003672 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003673 fprintf(out, " %4d,", la);
3674 if( j==9 || i==n-1 ){
3675 fprintf(out, "\n"); lineno++;
3676 j = 0;
3677 }else{
3678 j++;
3679 }
3680 }
3681 fprintf(out, "};\n"); lineno++;
3682
3683 /* Output the yy_shift_ofst[] table */
3684 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003685 n = lemp->nstate;
3686 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3687 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003688 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003689 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003690 for(i=j=0; i<n; i++){
3691 int ofst;
3692 stp = lemp->sorted[i];
3693 ofst = stp->iTknOfst;
3694 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003695 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003696 fprintf(out, " %4d,", ofst);
3697 if( j==9 || i==n-1 ){
3698 fprintf(out, "\n"); lineno++;
3699 j = 0;
3700 }else{
3701 j++;
3702 }
3703 }
3704 fprintf(out, "};\n"); lineno++;
3705
3706 /* Output the yy_reduce_ofst[] table */
3707 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003708 n = lemp->nstate;
3709 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3710 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003711 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003712 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003713 for(i=j=0; i<n; i++){
3714 int ofst;
3715 stp = lemp->sorted[i];
3716 ofst = stp->iNtOfst;
3717 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003718 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003719 fprintf(out, " %4d,", ofst);
3720 if( j==9 || i==n-1 ){
3721 fprintf(out, "\n"); lineno++;
3722 j = 0;
3723 }else{
3724 j++;
3725 }
3726 }
3727 fprintf(out, "};\n"); lineno++;
3728
3729 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003730 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003731 n = lemp->nstate;
3732 for(i=j=0; i<n; i++){
3733 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003734 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003735 fprintf(out, " %4d,", stp->iDflt);
3736 if( j==9 || i==n-1 ){
3737 fprintf(out, "\n"); lineno++;
3738 j = 0;
3739 }else{
3740 j++;
3741 }
3742 }
3743 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003744 tplt_xfer(lemp->name,in,out,&lineno);
3745
drh0bd1f4e2002-06-06 18:54:39 +00003746 /* Generate the table of fallback tokens.
3747 */
3748 if( lemp->has_fallback ){
3749 for(i=0; i<lemp->nterminal; i++){
3750 struct symbol *p = lemp->symbols[i];
3751 if( p->fallback==0 ){
3752 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3753 }else{
3754 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3755 p->name, p->fallback->name);
3756 }
3757 lineno++;
3758 }
3759 }
3760 tplt_xfer(lemp->name, in, out, &lineno);
3761
3762 /* Generate a table containing the symbolic name of every symbol
3763 */
drh75897232000-05-29 14:26:00 +00003764 for(i=0; i<lemp->nsymbol; i++){
3765 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3766 fprintf(out," %-15s",line);
3767 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3768 }
3769 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3770 tplt_xfer(lemp->name,in,out,&lineno);
3771
drh0bd1f4e2002-06-06 18:54:39 +00003772 /* Generate a table containing a text string that describes every
3773 ** rule in the rule set of the grammer. This information is used
3774 ** when tracing REDUCE actions.
3775 */
3776 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3777 assert( rp->index==i );
3778 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00003779 for(j=0; j<rp->nrhs; j++){
3780 struct symbol *sp = rp->rhs[j];
3781 fprintf(out," %s", sp->name);
3782 if( sp->type==MULTITERMINAL ){
3783 int k;
3784 for(k=1; k<sp->nsubsym; k++){
3785 fprintf(out,"|%s",sp->subsym[k]->name);
3786 }
3787 }
3788 }
drh0bd1f4e2002-06-06 18:54:39 +00003789 fprintf(out,"\",\n"); lineno++;
3790 }
3791 tplt_xfer(lemp->name,in,out,&lineno);
3792
drh75897232000-05-29 14:26:00 +00003793 /* Generate code which executes every time a symbol is popped from
3794 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003795 ** (In other words, generate the %destructor actions)
3796 */
drh75897232000-05-29 14:26:00 +00003797 if( lemp->tokendest ){
3798 for(i=0; i<lemp->nsymbol; i++){
3799 struct symbol *sp = lemp->symbols[i];
3800 if( sp==0 || sp->type!=TERMINAL ) continue;
3801 fprintf(out," case %d:\n",sp->index); lineno++;
3802 }
3803 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3804 if( i<lemp->nsymbol ){
3805 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3806 fprintf(out," break;\n"); lineno++;
3807 }
3808 }
drh8d659732005-01-13 23:54:06 +00003809 if( lemp->vardest ){
3810 struct symbol *dflt_sp = 0;
3811 for(i=0; i<lemp->nsymbol; i++){
3812 struct symbol *sp = lemp->symbols[i];
3813 if( sp==0 || sp->type==TERMINAL ||
3814 sp->index<=0 || sp->destructor!=0 ) continue;
3815 fprintf(out," case %d:\n",sp->index); lineno++;
3816 dflt_sp = sp;
3817 }
3818 if( dflt_sp!=0 ){
3819 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3820 fprintf(out," break;\n"); lineno++;
3821 }
3822 }
drh75897232000-05-29 14:26:00 +00003823 for(i=0; i<lemp->nsymbol; i++){
3824 struct symbol *sp = lemp->symbols[i];
3825 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3826 fprintf(out," case %d:\n",sp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003827
3828 /* Combine duplicate destructors into a single case */
3829 for(j=i+1; j<lemp->nsymbol; j++){
3830 struct symbol *sp2 = lemp->symbols[j];
3831 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3832 && sp2->dtnum==sp->dtnum
3833 && strcmp(sp->destructor,sp2->destructor)==0 ){
3834 fprintf(out," case %d:\n",sp2->index); lineno++;
3835 sp2->destructor = 0;
3836 }
3837 }
3838
drh75897232000-05-29 14:26:00 +00003839 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3840 fprintf(out," break;\n"); lineno++;
3841 }
drh75897232000-05-29 14:26:00 +00003842 tplt_xfer(lemp->name,in,out,&lineno);
3843
3844 /* Generate code which executes whenever the parser stack overflows */
3845 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3846 tplt_xfer(lemp->name,in,out,&lineno);
3847
3848 /* Generate the table of rule information
3849 **
3850 ** Note: This code depends on the fact that rules are number
3851 ** sequentually beginning with 0.
3852 */
3853 for(rp=lemp->rule; rp; rp=rp->next){
3854 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3855 }
3856 tplt_xfer(lemp->name,in,out,&lineno);
3857
3858 /* Generate code which execution during each REDUCE action */
3859 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003860 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003861 }
3862 for(rp=lemp->rule; rp; rp=rp->next){
3863 struct rule *rp2;
3864 if( rp->code==0 ) continue;
drh75897232000-05-29 14:26:00 +00003865 fprintf(out," case %d:\n",rp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003866 for(rp2=rp->next; rp2; rp2=rp2->next){
3867 if( rp2->code==rp->code ){
3868 fprintf(out," case %d:\n",rp2->index); lineno++;
3869 rp2->code = 0;
3870 }
3871 }
drh75897232000-05-29 14:26:00 +00003872 emit_code(out,rp,lemp,&lineno);
3873 fprintf(out," break;\n"); lineno++;
3874 }
3875 tplt_xfer(lemp->name,in,out,&lineno);
3876
3877 /* Generate code which executes if a parse fails */
3878 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3879 tplt_xfer(lemp->name,in,out,&lineno);
3880
3881 /* Generate code which executes when a syntax error occurs */
3882 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3883 tplt_xfer(lemp->name,in,out,&lineno);
3884
3885 /* Generate code which executes when the parser accepts its input */
3886 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3887 tplt_xfer(lemp->name,in,out,&lineno);
3888
3889 /* Append any addition code the user desires */
3890 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3891
3892 fclose(in);
3893 fclose(out);
3894 return;
3895}
3896
3897/* Generate a header file for the parser */
3898void ReportHeader(lemp)
3899struct lemon *lemp;
3900{
3901 FILE *out, *in;
3902 char *prefix;
3903 char line[LINESIZE];
3904 char pattern[LINESIZE];
3905 int i;
3906
3907 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3908 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003909 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003910 if( in ){
3911 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3912 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3913 if( strcmp(line,pattern) ) break;
3914 }
3915 fclose(in);
3916 if( i==lemp->nterminal ){
3917 /* No change in the file. Don't rewrite it. */
3918 return;
3919 }
3920 }
drh2aa6ca42004-09-10 00:14:04 +00003921 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003922 if( out ){
3923 for(i=1; i<lemp->nterminal; i++){
3924 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3925 }
3926 fclose(out);
3927 }
3928 return;
3929}
3930
3931/* Reduce the size of the action tables, if possible, by making use
3932** of defaults.
3933**
drhb59499c2002-02-23 18:45:13 +00003934** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00003935** it the default. Except, there is no default if the wildcard token
3936** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00003937*/
3938void CompressTables(lemp)
3939struct lemon *lemp;
3940{
3941 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003942 struct action *ap, *ap2;
3943 struct rule *rp, *rp2, *rbest;
3944 int nbest, n;
drh75897232000-05-29 14:26:00 +00003945 int i;
drhe09daa92006-06-10 13:29:31 +00003946 int usesWildcard;
drh75897232000-05-29 14:26:00 +00003947
3948 for(i=0; i<lemp->nstate; i++){
3949 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003950 nbest = 0;
3951 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00003952 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00003953
drhb59499c2002-02-23 18:45:13 +00003954 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00003955 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
3956 usesWildcard = 1;
3957 }
drhb59499c2002-02-23 18:45:13 +00003958 if( ap->type!=REDUCE ) continue;
3959 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00003960 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00003961 if( rp==rbest ) continue;
3962 n = 1;
3963 for(ap2=ap->next; ap2; ap2=ap2->next){
3964 if( ap2->type!=REDUCE ) continue;
3965 rp2 = ap2->x.rp;
3966 if( rp2==rbest ) continue;
3967 if( rp2==rp ) n++;
3968 }
3969 if( n>nbest ){
3970 nbest = n;
3971 rbest = rp;
drh75897232000-05-29 14:26:00 +00003972 }
3973 }
drhb59499c2002-02-23 18:45:13 +00003974
3975 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00003976 ** is not at least 1 or if the wildcard token is a possible
3977 ** lookahead.
3978 */
3979 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00003980
drhb59499c2002-02-23 18:45:13 +00003981
3982 /* Combine matching REDUCE actions into a single default */
3983 for(ap=stp->ap; ap; ap=ap->next){
3984 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3985 }
drh75897232000-05-29 14:26:00 +00003986 assert( ap );
3987 ap->sp = Symbol_new("{default}");
3988 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003989 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003990 }
3991 stp->ap = Action_sort(stp->ap);
3992 }
3993}
drhb59499c2002-02-23 18:45:13 +00003994
drhada354d2005-11-05 15:03:59 +00003995
3996/*
3997** Compare two states for sorting purposes. The smaller state is the
3998** one with the most non-terminal actions. If they have the same number
3999** of non-terminal actions, then the smaller is the one with the most
4000** token actions.
4001*/
4002static int stateResortCompare(const void *a, const void *b){
4003 const struct state *pA = *(const struct state**)a;
4004 const struct state *pB = *(const struct state**)b;
4005 int n;
4006
4007 n = pB->nNtAct - pA->nNtAct;
4008 if( n==0 ){
4009 n = pB->nTknAct - pA->nTknAct;
4010 }
4011 return n;
4012}
4013
4014
4015/*
4016** Renumber and resort states so that states with fewer choices
4017** occur at the end. Except, keep state 0 as the first state.
4018*/
4019void ResortStates(lemp)
4020struct lemon *lemp;
4021{
4022 int i;
4023 struct state *stp;
4024 struct action *ap;
4025
4026 for(i=0; i<lemp->nstate; i++){
4027 stp = lemp->sorted[i];
4028 stp->nTknAct = stp->nNtAct = 0;
4029 stp->iDflt = lemp->nstate + lemp->nrule;
4030 stp->iTknOfst = NO_OFFSET;
4031 stp->iNtOfst = NO_OFFSET;
4032 for(ap=stp->ap; ap; ap=ap->next){
4033 if( compute_action(lemp,ap)>=0 ){
4034 if( ap->sp->index<lemp->nterminal ){
4035 stp->nTknAct++;
4036 }else if( ap->sp->index<lemp->nsymbol ){
4037 stp->nNtAct++;
4038 }else{
4039 stp->iDflt = compute_action(lemp, ap);
4040 }
4041 }
4042 }
4043 }
4044 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4045 stateResortCompare);
4046 for(i=0; i<lemp->nstate; i++){
4047 lemp->sorted[i]->statenum = i;
4048 }
4049}
4050
4051
drh75897232000-05-29 14:26:00 +00004052/***************** From the file "set.c" ************************************/
4053/*
4054** Set manipulation routines for the LEMON parser generator.
4055*/
4056
4057static int size = 0;
4058
4059/* Set the set size */
4060void SetSize(n)
4061int n;
4062{
4063 size = n+1;
4064}
4065
4066/* Allocate a new set */
4067char *SetNew(){
4068 char *s;
4069 int i;
drh9892c5d2007-12-21 00:02:11 +00004070 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004071 if( s==0 ){
4072 extern void memory_error();
4073 memory_error();
4074 }
drh75897232000-05-29 14:26:00 +00004075 return s;
4076}
4077
4078/* Deallocate a set */
4079void SetFree(s)
4080char *s;
4081{
4082 free(s);
4083}
4084
4085/* Add a new element to the set. Return TRUE if the element was added
4086** and FALSE if it was already there. */
4087int SetAdd(s,e)
4088char *s;
4089int e;
4090{
4091 int rv;
drh9892c5d2007-12-21 00:02:11 +00004092 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004093 rv = s[e];
4094 s[e] = 1;
4095 return !rv;
4096}
4097
4098/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4099int SetUnion(s1,s2)
4100char *s1;
4101char *s2;
4102{
4103 int i, progress;
4104 progress = 0;
4105 for(i=0; i<size; i++){
4106 if( s2[i]==0 ) continue;
4107 if( s1[i]==0 ){
4108 progress = 1;
4109 s1[i] = 1;
4110 }
4111 }
4112 return progress;
4113}
4114/********************** From the file "table.c" ****************************/
4115/*
4116** All code in this file has been automatically generated
4117** from a specification in the file
4118** "table.q"
4119** by the associative array code building program "aagen".
4120** Do not edit this file! Instead, edit the specification
4121** file, then rerun aagen.
4122*/
4123/*
4124** Code for processing tables in the LEMON parser generator.
4125*/
4126
4127PRIVATE int strhash(x)
4128char *x;
4129{
4130 int h = 0;
4131 while( *x) h = h*13 + *(x++);
4132 return h;
4133}
4134
4135/* Works like strdup, sort of. Save a string in malloced memory, but
4136** keep strings in a table so that the same string is not in more
4137** than one place.
4138*/
4139char *Strsafe(y)
4140char *y;
4141{
4142 char *z;
4143
drh916f75f2006-07-17 00:19:39 +00004144 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004145 z = Strsafe_find(y);
4146 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4147 strcpy(z,y);
4148 Strsafe_insert(z);
4149 }
4150 MemoryCheck(z);
4151 return z;
4152}
4153
4154/* There is one instance of the following structure for each
4155** associative array of type "x1".
4156*/
4157struct s_x1 {
4158 int size; /* The number of available slots. */
4159 /* Must be a power of 2 greater than or */
4160 /* equal to 1 */
4161 int count; /* Number of currently slots filled */
4162 struct s_x1node *tbl; /* The data stored here */
4163 struct s_x1node **ht; /* Hash table for lookups */
4164};
4165
4166/* There is one instance of this structure for every data element
4167** in an associative array of type "x1".
4168*/
4169typedef struct s_x1node {
4170 char *data; /* The data */
4171 struct s_x1node *next; /* Next entry with the same hash */
4172 struct s_x1node **from; /* Previous link */
4173} x1node;
4174
4175/* There is only one instance of the array, which is the following */
4176static struct s_x1 *x1a;
4177
4178/* Allocate a new associative array */
4179void Strsafe_init(){
4180 if( x1a ) return;
4181 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4182 if( x1a ){
4183 x1a->size = 1024;
4184 x1a->count = 0;
4185 x1a->tbl = (x1node*)malloc(
4186 (sizeof(x1node) + sizeof(x1node*))*1024 );
4187 if( x1a->tbl==0 ){
4188 free(x1a);
4189 x1a = 0;
4190 }else{
4191 int i;
4192 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4193 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4194 }
4195 }
4196}
4197/* Insert a new record into the array. Return TRUE if successful.
4198** Prior data with the same key is NOT overwritten */
4199int Strsafe_insert(data)
4200char *data;
4201{
4202 x1node *np;
4203 int h;
4204 int ph;
4205
4206 if( x1a==0 ) return 0;
4207 ph = strhash(data);
4208 h = ph & (x1a->size-1);
4209 np = x1a->ht[h];
4210 while( np ){
4211 if( strcmp(np->data,data)==0 ){
4212 /* An existing entry with the same key is found. */
4213 /* Fail because overwrite is not allows. */
4214 return 0;
4215 }
4216 np = np->next;
4217 }
4218 if( x1a->count>=x1a->size ){
4219 /* Need to make the hash table bigger */
4220 int i,size;
4221 struct s_x1 array;
4222 array.size = size = x1a->size*2;
4223 array.count = x1a->count;
4224 array.tbl = (x1node*)malloc(
4225 (sizeof(x1node) + sizeof(x1node*))*size );
4226 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4227 array.ht = (x1node**)&(array.tbl[size]);
4228 for(i=0; i<size; i++) array.ht[i] = 0;
4229 for(i=0; i<x1a->count; i++){
4230 x1node *oldnp, *newnp;
4231 oldnp = &(x1a->tbl[i]);
4232 h = strhash(oldnp->data) & (size-1);
4233 newnp = &(array.tbl[i]);
4234 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4235 newnp->next = array.ht[h];
4236 newnp->data = oldnp->data;
4237 newnp->from = &(array.ht[h]);
4238 array.ht[h] = newnp;
4239 }
4240 free(x1a->tbl);
4241 *x1a = array;
4242 }
4243 /* Insert the new data */
4244 h = ph & (x1a->size-1);
4245 np = &(x1a->tbl[x1a->count++]);
4246 np->data = data;
4247 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4248 np->next = x1a->ht[h];
4249 x1a->ht[h] = np;
4250 np->from = &(x1a->ht[h]);
4251 return 1;
4252}
4253
4254/* Return a pointer to data assigned to the given key. Return NULL
4255** if no such key. */
4256char *Strsafe_find(key)
4257char *key;
4258{
4259 int h;
4260 x1node *np;
4261
4262 if( x1a==0 ) return 0;
4263 h = strhash(key) & (x1a->size-1);
4264 np = x1a->ht[h];
4265 while( np ){
4266 if( strcmp(np->data,key)==0 ) break;
4267 np = np->next;
4268 }
4269 return np ? np->data : 0;
4270}
4271
4272/* Return a pointer to the (terminal or nonterminal) symbol "x".
4273** Create a new symbol if this is the first time "x" has been seen.
4274*/
4275struct symbol *Symbol_new(x)
4276char *x;
4277{
4278 struct symbol *sp;
4279
4280 sp = Symbol_find(x);
4281 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004282 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004283 MemoryCheck(sp);
4284 sp->name = Strsafe(x);
4285 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4286 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004287 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004288 sp->prec = -1;
4289 sp->assoc = UNK;
4290 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004291 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004292 sp->destructor = 0;
4293 sp->datatype = 0;
4294 Symbol_insert(sp,sp->name);
4295 }
4296 return sp;
4297}
4298
drh60d31652004-02-22 00:08:04 +00004299/* Compare two symbols for working purposes
4300**
4301** Symbols that begin with upper case letters (terminals or tokens)
4302** must sort before symbols that begin with lower case letters
4303** (non-terminals). Other than that, the order does not matter.
4304**
4305** We find experimentally that leaving the symbols in their original
4306** order (the order they appeared in the grammar file) gives the
4307** smallest parser tables in SQLite.
4308*/
4309int Symbolcmpp(struct symbol **a, struct symbol **b){
4310 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4311 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4312 return i1-i2;
drh75897232000-05-29 14:26:00 +00004313}
4314
4315/* There is one instance of the following structure for each
4316** associative array of type "x2".
4317*/
4318struct s_x2 {
4319 int size; /* The number of available slots. */
4320 /* Must be a power of 2 greater than or */
4321 /* equal to 1 */
4322 int count; /* Number of currently slots filled */
4323 struct s_x2node *tbl; /* The data stored here */
4324 struct s_x2node **ht; /* Hash table for lookups */
4325};
4326
4327/* There is one instance of this structure for every data element
4328** in an associative array of type "x2".
4329*/
4330typedef struct s_x2node {
4331 struct symbol *data; /* The data */
4332 char *key; /* The key */
4333 struct s_x2node *next; /* Next entry with the same hash */
4334 struct s_x2node **from; /* Previous link */
4335} x2node;
4336
4337/* There is only one instance of the array, which is the following */
4338static struct s_x2 *x2a;
4339
4340/* Allocate a new associative array */
4341void Symbol_init(){
4342 if( x2a ) return;
4343 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4344 if( x2a ){
4345 x2a->size = 128;
4346 x2a->count = 0;
4347 x2a->tbl = (x2node*)malloc(
4348 (sizeof(x2node) + sizeof(x2node*))*128 );
4349 if( x2a->tbl==0 ){
4350 free(x2a);
4351 x2a = 0;
4352 }else{
4353 int i;
4354 x2a->ht = (x2node**)&(x2a->tbl[128]);
4355 for(i=0; i<128; i++) x2a->ht[i] = 0;
4356 }
4357 }
4358}
4359/* Insert a new record into the array. Return TRUE if successful.
4360** Prior data with the same key is NOT overwritten */
4361int Symbol_insert(data,key)
4362struct symbol *data;
4363char *key;
4364{
4365 x2node *np;
4366 int h;
4367 int ph;
4368
4369 if( x2a==0 ) return 0;
4370 ph = strhash(key);
4371 h = ph & (x2a->size-1);
4372 np = x2a->ht[h];
4373 while( np ){
4374 if( strcmp(np->key,key)==0 ){
4375 /* An existing entry with the same key is found. */
4376 /* Fail because overwrite is not allows. */
4377 return 0;
4378 }
4379 np = np->next;
4380 }
4381 if( x2a->count>=x2a->size ){
4382 /* Need to make the hash table bigger */
4383 int i,size;
4384 struct s_x2 array;
4385 array.size = size = x2a->size*2;
4386 array.count = x2a->count;
4387 array.tbl = (x2node*)malloc(
4388 (sizeof(x2node) + sizeof(x2node*))*size );
4389 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4390 array.ht = (x2node**)&(array.tbl[size]);
4391 for(i=0; i<size; i++) array.ht[i] = 0;
4392 for(i=0; i<x2a->count; i++){
4393 x2node *oldnp, *newnp;
4394 oldnp = &(x2a->tbl[i]);
4395 h = strhash(oldnp->key) & (size-1);
4396 newnp = &(array.tbl[i]);
4397 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4398 newnp->next = array.ht[h];
4399 newnp->key = oldnp->key;
4400 newnp->data = oldnp->data;
4401 newnp->from = &(array.ht[h]);
4402 array.ht[h] = newnp;
4403 }
4404 free(x2a->tbl);
4405 *x2a = array;
4406 }
4407 /* Insert the new data */
4408 h = ph & (x2a->size-1);
4409 np = &(x2a->tbl[x2a->count++]);
4410 np->key = key;
4411 np->data = data;
4412 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4413 np->next = x2a->ht[h];
4414 x2a->ht[h] = np;
4415 np->from = &(x2a->ht[h]);
4416 return 1;
4417}
4418
4419/* Return a pointer to data assigned to the given key. Return NULL
4420** if no such key. */
4421struct symbol *Symbol_find(key)
4422char *key;
4423{
4424 int h;
4425 x2node *np;
4426
4427 if( x2a==0 ) return 0;
4428 h = strhash(key) & (x2a->size-1);
4429 np = x2a->ht[h];
4430 while( np ){
4431 if( strcmp(np->key,key)==0 ) break;
4432 np = np->next;
4433 }
4434 return np ? np->data : 0;
4435}
4436
4437/* Return the n-th data. Return NULL if n is out of range. */
4438struct symbol *Symbol_Nth(n)
4439int n;
4440{
4441 struct symbol *data;
4442 if( x2a && n>0 && n<=x2a->count ){
4443 data = x2a->tbl[n-1].data;
4444 }else{
4445 data = 0;
4446 }
4447 return data;
4448}
4449
4450/* Return the size of the array */
4451int Symbol_count()
4452{
4453 return x2a ? x2a->count : 0;
4454}
4455
4456/* Return an array of pointers to all data in the table.
4457** The array is obtained from malloc. Return NULL if memory allocation
4458** problems, or if the array is empty. */
4459struct symbol **Symbol_arrayof()
4460{
4461 struct symbol **array;
4462 int i,size;
4463 if( x2a==0 ) return 0;
4464 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004465 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004466 if( array ){
4467 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4468 }
4469 return array;
4470}
4471
4472/* Compare two configurations */
4473int Configcmp(a,b)
4474struct config *a;
4475struct config *b;
4476{
4477 int x;
4478 x = a->rp->index - b->rp->index;
4479 if( x==0 ) x = a->dot - b->dot;
4480 return x;
4481}
4482
4483/* Compare two states */
4484PRIVATE int statecmp(a,b)
4485struct config *a;
4486struct config *b;
4487{
4488 int rc;
4489 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4490 rc = a->rp->index - b->rp->index;
4491 if( rc==0 ) rc = a->dot - b->dot;
4492 }
4493 if( rc==0 ){
4494 if( a ) rc = 1;
4495 if( b ) rc = -1;
4496 }
4497 return rc;
4498}
4499
4500/* Hash a state */
4501PRIVATE int statehash(a)
4502struct config *a;
4503{
4504 int h=0;
4505 while( a ){
4506 h = h*571 + a->rp->index*37 + a->dot;
4507 a = a->bp;
4508 }
4509 return h;
4510}
4511
4512/* Allocate a new state structure */
4513struct state *State_new()
4514{
4515 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004516 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004517 MemoryCheck(new);
4518 return new;
4519}
4520
4521/* There is one instance of the following structure for each
4522** associative array of type "x3".
4523*/
4524struct s_x3 {
4525 int size; /* The number of available slots. */
4526 /* Must be a power of 2 greater than or */
4527 /* equal to 1 */
4528 int count; /* Number of currently slots filled */
4529 struct s_x3node *tbl; /* The data stored here */
4530 struct s_x3node **ht; /* Hash table for lookups */
4531};
4532
4533/* There is one instance of this structure for every data element
4534** in an associative array of type "x3".
4535*/
4536typedef struct s_x3node {
4537 struct state *data; /* The data */
4538 struct config *key; /* The key */
4539 struct s_x3node *next; /* Next entry with the same hash */
4540 struct s_x3node **from; /* Previous link */
4541} x3node;
4542
4543/* There is only one instance of the array, which is the following */
4544static struct s_x3 *x3a;
4545
4546/* Allocate a new associative array */
4547void State_init(){
4548 if( x3a ) return;
4549 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4550 if( x3a ){
4551 x3a->size = 128;
4552 x3a->count = 0;
4553 x3a->tbl = (x3node*)malloc(
4554 (sizeof(x3node) + sizeof(x3node*))*128 );
4555 if( x3a->tbl==0 ){
4556 free(x3a);
4557 x3a = 0;
4558 }else{
4559 int i;
4560 x3a->ht = (x3node**)&(x3a->tbl[128]);
4561 for(i=0; i<128; i++) x3a->ht[i] = 0;
4562 }
4563 }
4564}
4565/* Insert a new record into the array. Return TRUE if successful.
4566** Prior data with the same key is NOT overwritten */
4567int State_insert(data,key)
4568struct state *data;
4569struct config *key;
4570{
4571 x3node *np;
4572 int h;
4573 int ph;
4574
4575 if( x3a==0 ) return 0;
4576 ph = statehash(key);
4577 h = ph & (x3a->size-1);
4578 np = x3a->ht[h];
4579 while( np ){
4580 if( statecmp(np->key,key)==0 ){
4581 /* An existing entry with the same key is found. */
4582 /* Fail because overwrite is not allows. */
4583 return 0;
4584 }
4585 np = np->next;
4586 }
4587 if( x3a->count>=x3a->size ){
4588 /* Need to make the hash table bigger */
4589 int i,size;
4590 struct s_x3 array;
4591 array.size = size = x3a->size*2;
4592 array.count = x3a->count;
4593 array.tbl = (x3node*)malloc(
4594 (sizeof(x3node) + sizeof(x3node*))*size );
4595 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4596 array.ht = (x3node**)&(array.tbl[size]);
4597 for(i=0; i<size; i++) array.ht[i] = 0;
4598 for(i=0; i<x3a->count; i++){
4599 x3node *oldnp, *newnp;
4600 oldnp = &(x3a->tbl[i]);
4601 h = statehash(oldnp->key) & (size-1);
4602 newnp = &(array.tbl[i]);
4603 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4604 newnp->next = array.ht[h];
4605 newnp->key = oldnp->key;
4606 newnp->data = oldnp->data;
4607 newnp->from = &(array.ht[h]);
4608 array.ht[h] = newnp;
4609 }
4610 free(x3a->tbl);
4611 *x3a = array;
4612 }
4613 /* Insert the new data */
4614 h = ph & (x3a->size-1);
4615 np = &(x3a->tbl[x3a->count++]);
4616 np->key = key;
4617 np->data = data;
4618 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4619 np->next = x3a->ht[h];
4620 x3a->ht[h] = np;
4621 np->from = &(x3a->ht[h]);
4622 return 1;
4623}
4624
4625/* Return a pointer to data assigned to the given key. Return NULL
4626** if no such key. */
4627struct state *State_find(key)
4628struct config *key;
4629{
4630 int h;
4631 x3node *np;
4632
4633 if( x3a==0 ) return 0;
4634 h = statehash(key) & (x3a->size-1);
4635 np = x3a->ht[h];
4636 while( np ){
4637 if( statecmp(np->key,key)==0 ) break;
4638 np = np->next;
4639 }
4640 return np ? np->data : 0;
4641}
4642
4643/* Return an array of pointers to all data in the table.
4644** The array is obtained from malloc. Return NULL if memory allocation
4645** problems, or if the array is empty. */
4646struct state **State_arrayof()
4647{
4648 struct state **array;
4649 int i,size;
4650 if( x3a==0 ) return 0;
4651 size = x3a->count;
4652 array = (struct state **)malloc( sizeof(struct state *)*size );
4653 if( array ){
4654 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4655 }
4656 return array;
4657}
4658
4659/* Hash a configuration */
4660PRIVATE int confighash(a)
4661struct config *a;
4662{
4663 int h=0;
4664 h = h*571 + a->rp->index*37 + a->dot;
4665 return h;
4666}
4667
4668/* There is one instance of the following structure for each
4669** associative array of type "x4".
4670*/
4671struct s_x4 {
4672 int size; /* The number of available slots. */
4673 /* Must be a power of 2 greater than or */
4674 /* equal to 1 */
4675 int count; /* Number of currently slots filled */
4676 struct s_x4node *tbl; /* The data stored here */
4677 struct s_x4node **ht; /* Hash table for lookups */
4678};
4679
4680/* There is one instance of this structure for every data element
4681** in an associative array of type "x4".
4682*/
4683typedef struct s_x4node {
4684 struct config *data; /* The data */
4685 struct s_x4node *next; /* Next entry with the same hash */
4686 struct s_x4node **from; /* Previous link */
4687} x4node;
4688
4689/* There is only one instance of the array, which is the following */
4690static struct s_x4 *x4a;
4691
4692/* Allocate a new associative array */
4693void Configtable_init(){
4694 if( x4a ) return;
4695 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4696 if( x4a ){
4697 x4a->size = 64;
4698 x4a->count = 0;
4699 x4a->tbl = (x4node*)malloc(
4700 (sizeof(x4node) + sizeof(x4node*))*64 );
4701 if( x4a->tbl==0 ){
4702 free(x4a);
4703 x4a = 0;
4704 }else{
4705 int i;
4706 x4a->ht = (x4node**)&(x4a->tbl[64]);
4707 for(i=0; i<64; i++) x4a->ht[i] = 0;
4708 }
4709 }
4710}
4711/* Insert a new record into the array. Return TRUE if successful.
4712** Prior data with the same key is NOT overwritten */
4713int Configtable_insert(data)
4714struct config *data;
4715{
4716 x4node *np;
4717 int h;
4718 int ph;
4719
4720 if( x4a==0 ) return 0;
4721 ph = confighash(data);
4722 h = ph & (x4a->size-1);
4723 np = x4a->ht[h];
4724 while( np ){
4725 if( Configcmp(np->data,data)==0 ){
4726 /* An existing entry with the same key is found. */
4727 /* Fail because overwrite is not allows. */
4728 return 0;
4729 }
4730 np = np->next;
4731 }
4732 if( x4a->count>=x4a->size ){
4733 /* Need to make the hash table bigger */
4734 int i,size;
4735 struct s_x4 array;
4736 array.size = size = x4a->size*2;
4737 array.count = x4a->count;
4738 array.tbl = (x4node*)malloc(
4739 (sizeof(x4node) + sizeof(x4node*))*size );
4740 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4741 array.ht = (x4node**)&(array.tbl[size]);
4742 for(i=0; i<size; i++) array.ht[i] = 0;
4743 for(i=0; i<x4a->count; i++){
4744 x4node *oldnp, *newnp;
4745 oldnp = &(x4a->tbl[i]);
4746 h = confighash(oldnp->data) & (size-1);
4747 newnp = &(array.tbl[i]);
4748 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4749 newnp->next = array.ht[h];
4750 newnp->data = oldnp->data;
4751 newnp->from = &(array.ht[h]);
4752 array.ht[h] = newnp;
4753 }
4754 free(x4a->tbl);
4755 *x4a = array;
4756 }
4757 /* Insert the new data */
4758 h = ph & (x4a->size-1);
4759 np = &(x4a->tbl[x4a->count++]);
4760 np->data = data;
4761 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4762 np->next = x4a->ht[h];
4763 x4a->ht[h] = np;
4764 np->from = &(x4a->ht[h]);
4765 return 1;
4766}
4767
4768/* Return a pointer to data assigned to the given key. Return NULL
4769** if no such key. */
4770struct config *Configtable_find(key)
4771struct config *key;
4772{
4773 int h;
4774 x4node *np;
4775
4776 if( x4a==0 ) return 0;
4777 h = confighash(key) & (x4a->size-1);
4778 np = x4a->ht[h];
4779 while( np ){
4780 if( Configcmp(np->data,key)==0 ) break;
4781 np = np->next;
4782 }
4783 return np ? np->data : 0;
4784}
4785
4786/* Remove all data from the table. Pass each data to the function "f"
4787** as it is removed. ("f" may be null to avoid this step.) */
4788void Configtable_clear(f)
4789int(*f)(/* struct config * */);
4790{
4791 int i;
4792 if( x4a==0 || x4a->count==0 ) return;
4793 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4794 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4795 x4a->count = 0;
4796 return;
4797}