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