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