blob: 6cfd2c0bff1e56e3b80db3021d12dee15f2858fd [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,
123 NONTERMINAL
124 } type; /* Symbols are all either TERMINALS or NTs */
125 struct rule *rule; /* Linked list of rules of this (if an NT) */
drh0bd1f4e2002-06-06 18:54:39 +0000126 struct symbol *fallback; /* fallback token in case this token doesn't parse */
drh75897232000-05-29 14:26:00 +0000127 int prec; /* Precedence if defined (-1 otherwise) */
128 enum e_assoc {
129 LEFT,
130 RIGHT,
131 NONE,
132 UNK
133 } assoc; /* Associativity if predecence is defined */
134 char *firstset; /* First-set for all rules of this symbol */
135 Boolean lambda; /* True if NT and can generate an empty string */
136 char *destructor; /* Code which executes whenever this symbol is
137 ** popped from the stack during error processing */
138 int destructorln; /* Line number of destructor code */
139 char *datatype; /* The data type of information held by this
140 ** object. Only used if type==NONTERMINAL */
141 int dtnum; /* The data type number. In the parser, the value
142 ** stack is a union. The .yy%d element of this
143 ** union is the correct data type for this object */
144};
145
146/* Each production rule in the grammar is stored in the following
147** structure. */
148struct rule {
149 struct symbol *lhs; /* Left-hand side of the rule */
150 char *lhsalias; /* Alias for the LHS (NULL if none) */
151 int ruleline; /* Line number for the rule */
152 int nrhs; /* Number of RHS symbols */
153 struct symbol **rhs; /* The RHS symbols */
154 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
155 int line; /* Line number at which code begins */
156 char *code; /* The code executed when this rule is reduced */
157 struct symbol *precsym; /* Precedence symbol for this rule */
158 int index; /* An index number for this rule */
159 Boolean canReduce; /* True if this rule is ever reduced */
160 struct rule *nextlhs; /* Next rule with the same LHS */
161 struct rule *next; /* Next rule in the global list */
162};
163
164/* A configuration is a production rule of the grammar together with
165** a mark (dot) showing how much of that rule has been processed so far.
166** Configurations also contain a follow-set which is a list of terminal
167** symbols which are allowed to immediately follow the end of the rule.
168** Every configuration is recorded as an instance of the following: */
169struct config {
170 struct rule *rp; /* The rule upon which the configuration is based */
171 int dot; /* The parse point */
172 char *fws; /* Follow-set for this configuration only */
173 struct plink *fplp; /* Follow-set forward propagation links */
174 struct plink *bplp; /* Follow-set backwards propagation links */
175 struct state *stp; /* Pointer to state which contains this */
176 enum {
177 COMPLETE, /* The status is used during followset and */
178 INCOMPLETE /* shift computations */
179 } status;
180 struct config *next; /* Next configuration in the state */
181 struct config *bp; /* The next basis configuration */
182};
183
184/* Every shift or reduce operation is stored as one of the following */
185struct action {
186 struct symbol *sp; /* The look-ahead symbol */
187 enum e_action {
188 SHIFT,
189 ACCEPT,
190 REDUCE,
191 ERROR,
192 CONFLICT, /* Was a reduce, but part of a conflict */
193 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
194 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
195 NOT_USED /* Deleted by compression */
196 } type;
197 union {
198 struct state *stp; /* The new state, if a shift */
199 struct rule *rp; /* The rule, if a reduce */
200 } x;
201 struct action *next; /* Next action for this state */
202 struct action *collide; /* Next action with the same hash */
203};
204
205/* Each state of the generated parser's finite state machine
206** is encoded as an instance of the following structure. */
207struct state {
208 struct config *bp; /* The basis configurations for this state */
209 struct config *cfp; /* All configurations in this set */
drhada354d2005-11-05 15:03:59 +0000210 int statenum; /* Sequencial number for this state */
drh75897232000-05-29 14:26:00 +0000211 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000212 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
213 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
214 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000215};
drh8b582012003-10-21 13:16:03 +0000216#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000217
218/* A followset propagation link indicates that the contents of one
219** configuration followset should be propagated to another whenever
220** the first changes. */
221struct plink {
222 struct config *cfp; /* The configuration to which linked */
223 struct plink *next; /* The next propagate link */
224};
225
226/* The state vector for the entire parser generator is recorded as
227** follows. (LEMON uses no global variables and makes little use of
228** static variables. Fields in the following structure can be thought
229** of as begin global variables in the program.) */
230struct lemon {
231 struct state **sorted; /* Table of states sorted by state number */
232 struct rule *rule; /* List of all rules */
233 int nstate; /* Number of states */
234 int nrule; /* Number of rules */
235 int nsymbol; /* Number of terminal and nonterminal symbols */
236 int nterminal; /* Number of terminal symbols */
237 struct symbol **symbols; /* Sorted array of pointers to symbols */
238 int errorcnt; /* Number of errors */
239 struct symbol *errsym; /* The error symbol */
240 char *name; /* Name of the generated parser */
241 char *arg; /* Declaration of the 3th argument to parser */
242 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000243 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000244 char *start; /* Name of the start symbol for the grammar */
245 char *stacksize; /* Size of the parser stack */
246 char *include; /* Code to put at the start of the C file */
247 int includeln; /* Line number for start of include code */
248 char *error; /* Code to execute when an error is seen */
249 int errorln; /* Line number for start of error code */
250 char *overflow; /* Code to execute on a stack overflow */
251 int overflowln; /* Line number for start of overflow code */
252 char *failure; /* Code to execute on parser failure */
253 int failureln; /* Line number for start of failure code */
254 char *accept; /* Code to execute when the parser excepts */
255 int acceptln; /* Line number for the start of accept code */
256 char *extracode; /* Code appended to the generated file */
257 int extracodeln; /* Line number for the start of the extra code */
258 char *tokendest; /* Code to execute to destroy token data */
259 int tokendestln; /* Line number for token destroyer code */
drh960e8c62001-04-03 16:53:21 +0000260 char *vardest; /* Code for the default non-terminal destructor */
261 int vardestln; /* Line number for default non-term destructor code*/
drh75897232000-05-29 14:26:00 +0000262 char *filename; /* Name of the input file */
263 char *outname; /* Name of the current output file */
264 char *tokenprefix; /* A prefix added to token names in the .h file */
265 int nconflict; /* Number of parsing conflicts */
266 int tablesize; /* Size of the parse tables */
267 int basisflag; /* Print only basis configurations */
drh0bd1f4e2002-06-06 18:54:39 +0000268 int has_fallback; /* True if any %fallback is seen in the grammer */
drh75897232000-05-29 14:26:00 +0000269 char *argv0; /* Name of the program */
270};
271
272#define MemoryCheck(X) if((X)==0){ \
273 extern void memory_error(); \
274 memory_error(); \
275}
276
277/**************** From the file "table.h" *********************************/
278/*
279** All code in this file has been automatically generated
280** from a specification in the file
281** "table.q"
282** by the associative array code building program "aagen".
283** Do not edit this file! Instead, edit the specification
284** file, then rerun aagen.
285*/
286/*
287** Code for processing tables in the LEMON parser generator.
288*/
289
290/* Routines for handling a strings */
291
292char *Strsafe();
293
294void Strsafe_init(/* void */);
295int Strsafe_insert(/* char * */);
296char *Strsafe_find(/* char * */);
297
298/* Routines for handling symbols of the grammar */
299
300struct symbol *Symbol_new();
301int Symbolcmpp(/* struct symbol **, struct symbol ** */);
302void Symbol_init(/* void */);
303int Symbol_insert(/* struct symbol *, char * */);
304struct symbol *Symbol_find(/* char * */);
305struct symbol *Symbol_Nth(/* int */);
306int Symbol_count(/* */);
307struct symbol **Symbol_arrayof(/* */);
308
309/* Routines to manage the state table */
310
311int Configcmp(/* struct config *, struct config * */);
312struct state *State_new();
313void State_init(/* void */);
314int State_insert(/* struct state *, struct config * */);
315struct state *State_find(/* struct config * */);
316struct state **State_arrayof(/* */);
317
318/* Routines used for efficiency in Configlist_add */
319
320void Configtable_init(/* void */);
321int Configtable_insert(/* struct config * */);
322struct config *Configtable_find(/* struct config * */);
323void Configtable_clear(/* int(*)(struct config *) */);
324/****************** From the file "action.c" *******************************/
325/*
326** Routines processing parser actions in the LEMON parser generator.
327*/
328
329/* Allocate a new parser action */
330struct action *Action_new(){
331 static struct action *freelist = 0;
332 struct action *new;
333
334 if( freelist==0 ){
335 int i;
336 int amt = 100;
337 freelist = (struct action *)malloc( sizeof(struct action)*amt );
338 if( freelist==0 ){
339 fprintf(stderr,"Unable to allocate memory for a new parser action.");
340 exit(1);
341 }
342 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
343 freelist[amt-1].next = 0;
344 }
345 new = freelist;
346 freelist = freelist->next;
347 return new;
348}
349
350/* Compare two actions */
351static int actioncmp(ap1,ap2)
352struct action *ap1;
353struct action *ap2;
354{
355 int rc;
356 rc = ap1->sp->index - ap2->sp->index;
357 if( rc==0 ) rc = (int)ap1->type - (int)ap2->type;
358 if( rc==0 ){
drh61bc2722000-08-20 11:42:46 +0000359 assert( ap1->type==REDUCE || ap1->type==RD_RESOLVED || ap1->type==CONFLICT);
360 assert( ap2->type==REDUCE || ap2->type==RD_RESOLVED || ap2->type==CONFLICT);
drh75897232000-05-29 14:26:00 +0000361 rc = ap1->x.rp->index - ap2->x.rp->index;
362 }
363 return rc;
364}
365
366/* Sort parser actions */
367struct action *Action_sort(ap)
368struct action *ap;
369{
drh218dc692004-05-31 23:13:45 +0000370 ap = (struct action *)msort((char *)ap,(char **)&ap->next,actioncmp);
drh75897232000-05-29 14:26:00 +0000371 return ap;
372}
373
374void Action_add(app,type,sp,arg)
375struct action **app;
376enum e_action type;
377struct symbol *sp;
378char *arg;
379{
380 struct action *new;
381 new = Action_new();
382 new->next = *app;
383 *app = new;
384 new->type = type;
385 new->sp = sp;
386 if( type==SHIFT ){
387 new->x.stp = (struct state *)arg;
388 }else{
389 new->x.rp = (struct rule *)arg;
390 }
391}
drh8b582012003-10-21 13:16:03 +0000392/********************** New code to implement the "acttab" module ***********/
393/*
394** This module implements routines use to construct the yy_action[] table.
395*/
396
397/*
398** The state of the yy_action table under construction is an instance of
399** the following structure
400*/
401typedef struct acttab acttab;
402struct acttab {
403 int nAction; /* Number of used slots in aAction[] */
404 int nActionAlloc; /* Slots allocated for aAction[] */
405 struct {
406 int lookahead; /* Value of the lookahead token */
407 int action; /* Action to take on the given lookahead */
408 } *aAction, /* The yy_action[] table under construction */
409 *aLookahead; /* A single new transaction set */
410 int mnLookahead; /* Minimum aLookahead[].lookahead */
411 int mnAction; /* Action associated with mnLookahead */
412 int mxLookahead; /* Maximum aLookahead[].lookahead */
413 int nLookahead; /* Used slots in aLookahead[] */
414 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
415};
416
417/* Return the number of entries in the yy_action table */
418#define acttab_size(X) ((X)->nAction)
419
420/* The value for the N-th entry in yy_action */
421#define acttab_yyaction(X,N) ((X)->aAction[N].action)
422
423/* The value for the N-th entry in yy_lookahead */
424#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
425
426/* Free all memory associated with the given acttab */
427void acttab_free(acttab *p){
428 free( p->aAction );
429 free( p->aLookahead );
430 free( p );
431}
432
433/* Allocate a new acttab structure */
434acttab *acttab_alloc(void){
435 acttab *p = malloc( sizeof(*p) );
436 if( p==0 ){
437 fprintf(stderr,"Unable to allocate memory for a new acttab.");
438 exit(1);
439 }
440 memset(p, 0, sizeof(*p));
441 return p;
442}
443
444/* Add a new action to the current transaction set
445*/
446void acttab_action(acttab *p, int lookahead, int action){
447 if( p->nLookahead>=p->nLookaheadAlloc ){
448 p->nLookaheadAlloc += 25;
449 p->aLookahead = realloc( p->aLookahead,
450 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
451 if( p->aLookahead==0 ){
452 fprintf(stderr,"malloc failed\n");
453 exit(1);
454 }
455 }
456 if( p->nLookahead==0 ){
457 p->mxLookahead = lookahead;
458 p->mnLookahead = lookahead;
459 p->mnAction = action;
460 }else{
461 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
462 if( p->mnLookahead>lookahead ){
463 p->mnLookahead = lookahead;
464 p->mnAction = action;
465 }
466 }
467 p->aLookahead[p->nLookahead].lookahead = lookahead;
468 p->aLookahead[p->nLookahead].action = action;
469 p->nLookahead++;
470}
471
472/*
473** Add the transaction set built up with prior calls to acttab_action()
474** into the current action table. Then reset the transaction set back
475** to an empty set in preparation for a new round of acttab_action() calls.
476**
477** Return the offset into the action table of the new transaction.
478*/
479int acttab_insert(acttab *p){
480 int i, j, k, n;
481 assert( p->nLookahead>0 );
482
483 /* Make sure we have enough space to hold the expanded action table
484 ** in the worst case. The worst case occurs if the transaction set
485 ** must be appended to the current action table
486 */
drh784d86f2004-02-19 18:41:53 +0000487 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000488 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000489 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000490 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
491 p->aAction = realloc( p->aAction,
492 sizeof(p->aAction[0])*p->nActionAlloc);
493 if( p->aAction==0 ){
494 fprintf(stderr,"malloc failed\n");
495 exit(1);
496 }
drhfdbf9282003-10-21 16:34:41 +0000497 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000498 p->aAction[i].lookahead = -1;
499 p->aAction[i].action = -1;
500 }
501 }
502
503 /* Scan the existing action table looking for an offset where we can
504 ** insert the current transaction set. Fall out of the loop when that
505 ** offset is found. In the worst case, we fall out of the loop when
506 ** i reaches p->nAction, which means we append the new transaction set.
507 **
508 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
509 */
drh784d86f2004-02-19 18:41:53 +0000510 for(i=0; i<p->nAction+p->mnLookahead; i++){
drh8b582012003-10-21 13:16:03 +0000511 if( p->aAction[i].lookahead<0 ){
512 for(j=0; j<p->nLookahead; j++){
513 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
514 if( k<0 ) break;
515 if( p->aAction[k].lookahead>=0 ) break;
516 }
drhfdbf9282003-10-21 16:34:41 +0000517 if( j<p->nLookahead ) continue;
518 for(j=0; j<p->nAction; j++){
519 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
520 }
521 if( j==p->nAction ){
522 break; /* Fits in empty slots */
523 }
drh8b582012003-10-21 13:16:03 +0000524 }else if( p->aAction[i].lookahead==p->mnLookahead ){
525 if( p->aAction[i].action!=p->mnAction ) continue;
526 for(j=0; j<p->nLookahead; j++){
527 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
528 if( k<0 || k>=p->nAction ) break;
529 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
530 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
531 }
532 if( j<p->nLookahead ) continue;
533 n = 0;
534 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000535 if( p->aAction[j].lookahead<0 ) continue;
536 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000537 }
drhfdbf9282003-10-21 16:34:41 +0000538 if( n==p->nLookahead ){
539 break; /* Same as a prior transaction set */
540 }
drh8b582012003-10-21 13:16:03 +0000541 }
542 }
543 /* Insert transaction set at index i. */
544 for(j=0; j<p->nLookahead; j++){
545 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
546 p->aAction[k] = p->aLookahead[j];
547 if( k>=p->nAction ) p->nAction = k+1;
548 }
549 p->nLookahead = 0;
550
551 /* Return the offset that is added to the lookahead in order to get the
552 ** index into yy_action of the action */
553 return i - p->mnLookahead;
554}
555
drh75897232000-05-29 14:26:00 +0000556/********************** From the file "assert.c" ****************************/
557/*
558** A more efficient way of handling assertions.
559*/
560void myassert(file,line)
561char *file;
562int line;
563{
564 fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file);
565 exit(1);
566}
567/********************** From the file "build.c" *****************************/
568/*
569** Routines to construction the finite state machine for the LEMON
570** parser generator.
571*/
572
573/* Find a precedence symbol of every rule in the grammar.
574**
575** Those rules which have a precedence symbol coded in the input
576** grammar using the "[symbol]" construct will already have the
577** rp->precsym field filled. Other rules take as their precedence
578** symbol the first RHS symbol with a defined precedence. If there
579** are not RHS symbols with a defined precedence, the precedence
580** symbol field is left blank.
581*/
582void FindRulePrecedences(xp)
583struct lemon *xp;
584{
585 struct rule *rp;
586 for(rp=xp->rule; rp; rp=rp->next){
587 if( rp->precsym==0 ){
588 int i;
589 for(i=0; i<rp->nrhs; i++){
590 if( rp->rhs[i]->prec>=0 ){
591 rp->precsym = rp->rhs[i];
592 break;
593 }
594 }
595 }
596 }
597 return;
598}
599
600/* Find all nonterminals which will generate the empty string.
601** Then go back and compute the first sets of every nonterminal.
602** The first set is the set of all terminal symbols which can begin
603** a string generated by that nonterminal.
604*/
605void FindFirstSets(lemp)
606struct lemon *lemp;
607{
608 int i;
609 struct rule *rp;
610 int progress;
611
612 for(i=0; i<lemp->nsymbol; i++){
drhb27b83a2002-08-14 23:18:57 +0000613 lemp->symbols[i]->lambda = B_FALSE;
drh75897232000-05-29 14:26:00 +0000614 }
615 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
616 lemp->symbols[i]->firstset = SetNew();
617 }
618
619 /* First compute all lambdas */
620 do{
621 progress = 0;
622 for(rp=lemp->rule; rp; rp=rp->next){
623 if( rp->lhs->lambda ) continue;
624 for(i=0; i<rp->nrhs; i++){
drhb27b83a2002-08-14 23:18:57 +0000625 if( rp->rhs[i]->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000626 }
627 if( i==rp->nrhs ){
drhb27b83a2002-08-14 23:18:57 +0000628 rp->lhs->lambda = B_TRUE;
drh75897232000-05-29 14:26:00 +0000629 progress = 1;
630 }
631 }
632 }while( progress );
633
634 /* Now compute all first sets */
635 do{
636 struct symbol *s1, *s2;
637 progress = 0;
638 for(rp=lemp->rule; rp; rp=rp->next){
639 s1 = rp->lhs;
640 for(i=0; i<rp->nrhs; i++){
641 s2 = rp->rhs[i];
642 if( s2->type==TERMINAL ){
643 progress += SetAdd(s1->firstset,s2->index);
644 break;
645 }else if( s1==s2 ){
drhb27b83a2002-08-14 23:18:57 +0000646 if( s1->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000647 }else{
648 progress += SetUnion(s1->firstset,s2->firstset);
drhb27b83a2002-08-14 23:18:57 +0000649 if( s2->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000650 }
651 }
652 }
653 }while( progress );
654 return;
655}
656
657/* Compute all LR(0) states for the grammar. Links
658** are added to between some states so that the LR(1) follow sets
659** can be computed later.
660*/
661PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
662void FindStates(lemp)
663struct lemon *lemp;
664{
665 struct symbol *sp;
666 struct rule *rp;
667
668 Configlist_init();
669
670 /* Find the start symbol */
671 if( lemp->start ){
672 sp = Symbol_find(lemp->start);
673 if( sp==0 ){
674 ErrorMsg(lemp->filename,0,
675"The specified start symbol \"%s\" is not \
676in a nonterminal of the grammar. \"%s\" will be used as the start \
677symbol instead.",lemp->start,lemp->rule->lhs->name);
678 lemp->errorcnt++;
679 sp = lemp->rule->lhs;
680 }
681 }else{
682 sp = lemp->rule->lhs;
683 }
684
685 /* Make sure the start symbol doesn't occur on the right-hand side of
686 ** any rule. Report an error if it does. (YACC would generate a new
687 ** start symbol in this case.) */
688 for(rp=lemp->rule; rp; rp=rp->next){
689 int i;
690 for(i=0; i<rp->nrhs; i++){
691 if( rp->rhs[i]==sp ){
692 ErrorMsg(lemp->filename,0,
693"The start symbol \"%s\" occurs on the \
694right-hand side of a rule. This will result in a parser which \
695does not work properly.",sp->name);
696 lemp->errorcnt++;
697 }
698 }
699 }
700
701 /* The basis configuration set for the first state
702 ** is all rules which have the start symbol as their
703 ** left-hand side */
704 for(rp=sp->rule; rp; rp=rp->nextlhs){
705 struct config *newcfp;
706 newcfp = Configlist_addbasis(rp,0);
707 SetAdd(newcfp->fws,0);
708 }
709
710 /* Compute the first state. All other states will be
711 ** computed automatically during the computation of the first one.
712 ** The returned pointer to the first state is not used. */
713 (void)getstate(lemp);
714 return;
715}
716
717/* Return a pointer to a state which is described by the configuration
718** list which has been built from calls to Configlist_add.
719*/
720PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
721PRIVATE struct state *getstate(lemp)
722struct lemon *lemp;
723{
724 struct config *cfp, *bp;
725 struct state *stp;
726
727 /* Extract the sorted basis of the new state. The basis was constructed
728 ** by prior calls to "Configlist_addbasis()". */
729 Configlist_sortbasis();
730 bp = Configlist_basis();
731
732 /* Get a state with the same basis */
733 stp = State_find(bp);
734 if( stp ){
735 /* A state with the same basis already exists! Copy all the follow-set
736 ** propagation links from the state under construction into the
737 ** preexisting state, then return a pointer to the preexisting state */
738 struct config *x, *y;
739 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
740 Plink_copy(&y->bplp,x->bplp);
741 Plink_delete(x->fplp);
742 x->fplp = x->bplp = 0;
743 }
744 cfp = Configlist_return();
745 Configlist_eat(cfp);
746 }else{
747 /* This really is a new state. Construct all the details */
748 Configlist_closure(lemp); /* Compute the configuration closure */
749 Configlist_sort(); /* Sort the configuration closure */
750 cfp = Configlist_return(); /* Get a pointer to the config list */
751 stp = State_new(); /* A new state structure */
752 MemoryCheck(stp);
753 stp->bp = bp; /* Remember the configuration basis */
754 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000755 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000756 stp->ap = 0; /* No actions, yet. */
757 State_insert(stp,stp->bp); /* Add to the state table */
758 buildshifts(lemp,stp); /* Recursively compute successor states */
759 }
760 return stp;
761}
762
763/* Construct all successor states to the given state. A "successor"
764** state is any state which can be reached by a shift action.
765*/
766PRIVATE void buildshifts(lemp,stp)
767struct lemon *lemp;
768struct state *stp; /* The state from which successors are computed */
769{
770 struct config *cfp; /* For looping thru the config closure of "stp" */
771 struct config *bcfp; /* For the inner loop on config closure of "stp" */
772 struct config *new; /* */
773 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
774 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
775 struct state *newstp; /* A pointer to a successor state */
776
777 /* Each configuration becomes complete after it contibutes to a successor
778 ** state. Initially, all configurations are incomplete */
779 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
780
781 /* Loop through all configurations of the state "stp" */
782 for(cfp=stp->cfp; cfp; cfp=cfp->next){
783 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
784 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
785 Configlist_reset(); /* Reset the new config set */
786 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
787
788 /* For every configuration in the state "stp" which has the symbol "sp"
789 ** following its dot, add the same configuration to the basis set under
790 ** construction but with the dot shifted one symbol to the right. */
791 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
792 if( bcfp->status==COMPLETE ) continue; /* Already used */
793 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
794 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
795 if( bsp!=sp ) continue; /* Must be same as for "cfp" */
796 bcfp->status = COMPLETE; /* Mark this config as used */
797 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
798 Plink_add(&new->bplp,bcfp);
799 }
800
801 /* Get a pointer to the state described by the basis configuration set
802 ** constructed in the preceding loop */
803 newstp = getstate(lemp);
804
805 /* The state "newstp" is reached from the state "stp" by a shift action
806 ** on the symbol "sp" */
drh218dc692004-05-31 23:13:45 +0000807 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
drh75897232000-05-29 14:26:00 +0000808 }
809}
810
811/*
812** Construct the propagation links
813*/
814void FindLinks(lemp)
815struct lemon *lemp;
816{
817 int i;
818 struct config *cfp, *other;
819 struct state *stp;
820 struct plink *plp;
821
822 /* Housekeeping detail:
823 ** Add to every propagate link a pointer back to the state to
824 ** which the link is attached. */
825 for(i=0; i<lemp->nstate; i++){
826 stp = lemp->sorted[i];
827 for(cfp=stp->cfp; cfp; cfp=cfp->next){
828 cfp->stp = stp;
829 }
830 }
831
832 /* Convert all backlinks into forward links. Only the forward
833 ** links are used in the follow-set computation. */
834 for(i=0; i<lemp->nstate; i++){
835 stp = lemp->sorted[i];
836 for(cfp=stp->cfp; cfp; cfp=cfp->next){
837 for(plp=cfp->bplp; plp; plp=plp->next){
838 other = plp->cfp;
839 Plink_add(&other->fplp,cfp);
840 }
841 }
842 }
843}
844
845/* Compute all followsets.
846**
847** A followset is the set of all symbols which can come immediately
848** after a configuration.
849*/
850void FindFollowSets(lemp)
851struct lemon *lemp;
852{
853 int i;
854 struct config *cfp;
855 struct plink *plp;
856 int progress;
857 int change;
858
859 for(i=0; i<lemp->nstate; i++){
860 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
861 cfp->status = INCOMPLETE;
862 }
863 }
864
865 do{
866 progress = 0;
867 for(i=0; i<lemp->nstate; i++){
868 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
869 if( cfp->status==COMPLETE ) continue;
870 for(plp=cfp->fplp; plp; plp=plp->next){
871 change = SetUnion(plp->cfp->fws,cfp->fws);
872 if( change ){
873 plp->cfp->status = INCOMPLETE;
874 progress = 1;
875 }
876 }
877 cfp->status = COMPLETE;
878 }
879 }
880 }while( progress );
881}
882
883static int resolve_conflict();
884
885/* Compute the reduce actions, and resolve conflicts.
886*/
887void FindActions(lemp)
888struct lemon *lemp;
889{
890 int i,j;
891 struct config *cfp;
892 struct state *stp;
893 struct symbol *sp;
894 struct rule *rp;
895
896 /* Add all of the reduce actions
897 ** A reduce action is added for each element of the followset of
898 ** a configuration which has its dot at the extreme right.
899 */
900 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
901 stp = lemp->sorted[i];
902 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
903 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
904 for(j=0; j<lemp->nterminal; j++){
905 if( SetFind(cfp->fws,j) ){
906 /* Add a reduce action to the state "stp" which will reduce by the
907 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000908 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000909 }
910 }
911 }
912 }
913 }
914
915 /* Add the accepting token */
916 if( lemp->start ){
917 sp = Symbol_find(lemp->start);
918 if( sp==0 ) sp = lemp->rule->lhs;
919 }else{
920 sp = lemp->rule->lhs;
921 }
922 /* Add to the first state (which is always the starting state of the
923 ** finite state machine) an action to ACCEPT if the lookahead is the
924 ** start nonterminal. */
925 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
926
927 /* Resolve conflicts */
928 for(i=0; i<lemp->nstate; i++){
929 struct action *ap, *nap;
930 struct state *stp;
931 stp = lemp->sorted[i];
932 assert( stp->ap );
933 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000934 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000935 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
936 /* The two actions "ap" and "nap" have the same lookahead.
937 ** Figure out which one should be used */
938 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
939 }
940 }
941 }
942
943 /* Report an error for each rule that can never be reduced. */
drhb27b83a2002-08-14 23:18:57 +0000944 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = B_FALSE;
drh75897232000-05-29 14:26:00 +0000945 for(i=0; i<lemp->nstate; i++){
946 struct action *ap;
947 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhb27b83a2002-08-14 23:18:57 +0000948 if( ap->type==REDUCE ) ap->x.rp->canReduce = B_TRUE;
drh75897232000-05-29 14:26:00 +0000949 }
950 }
951 for(rp=lemp->rule; rp; rp=rp->next){
952 if( rp->canReduce ) continue;
953 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
954 lemp->errorcnt++;
955 }
956}
957
958/* Resolve a conflict between the two given actions. If the
959** conflict can't be resolve, return non-zero.
960**
961** NO LONGER TRUE:
962** To resolve a conflict, first look to see if either action
963** is on an error rule. In that case, take the action which
964** is not associated with the error rule. If neither or both
965** actions are associated with an error rule, then try to
966** use precedence to resolve the conflict.
967**
968** If either action is a SHIFT, then it must be apx. This
969** function won't work if apx->type==REDUCE and apy->type==SHIFT.
970*/
971static int resolve_conflict(apx,apy,errsym)
972struct action *apx;
973struct action *apy;
974struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
975{
976 struct symbol *spx, *spy;
977 int errcnt = 0;
978 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
979 if( apx->type==SHIFT && apy->type==REDUCE ){
980 spx = apx->sp;
981 spy = apy->x.rp->precsym;
982 if( spy==0 || spx->prec<0 || spy->prec<0 ){
983 /* Not enough precedence information. */
984 apy->type = CONFLICT;
985 errcnt++;
986 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
987 apy->type = RD_RESOLVED;
988 }else if( spx->prec<spy->prec ){
989 apx->type = SH_RESOLVED;
990 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
991 apy->type = RD_RESOLVED; /* associativity */
992 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
993 apx->type = SH_RESOLVED;
994 }else{
995 assert( spx->prec==spy->prec && spx->assoc==NONE );
996 apy->type = CONFLICT;
997 errcnt++;
998 }
999 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1000 spx = apx->x.rp->precsym;
1001 spy = apy->x.rp->precsym;
1002 if( spx==0 || spy==0 || spx->prec<0 ||
1003 spy->prec<0 || spx->prec==spy->prec ){
1004 apy->type = CONFLICT;
1005 errcnt++;
1006 }else if( spx->prec>spy->prec ){
1007 apy->type = RD_RESOLVED;
1008 }else if( spx->prec<spy->prec ){
1009 apx->type = RD_RESOLVED;
1010 }
1011 }else{
drhb59499c2002-02-23 18:45:13 +00001012 assert(
1013 apx->type==SH_RESOLVED ||
1014 apx->type==RD_RESOLVED ||
1015 apx->type==CONFLICT ||
1016 apy->type==SH_RESOLVED ||
1017 apy->type==RD_RESOLVED ||
1018 apy->type==CONFLICT
1019 );
1020 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1021 ** REDUCEs on the list. If we reach this point it must be because
1022 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001023 }
1024 return errcnt;
1025}
1026/********************* From the file "configlist.c" *************************/
1027/*
1028** Routines to processing a configuration list and building a state
1029** in the LEMON parser generator.
1030*/
1031
1032static struct config *freelist = 0; /* List of free configurations */
1033static struct config *current = 0; /* Top of list of configurations */
1034static struct config **currentend = 0; /* Last on list of configs */
1035static struct config *basis = 0; /* Top of list of basis configs */
1036static struct config **basisend = 0; /* End of list of basis configs */
1037
1038/* Return a pointer to a new configuration */
1039PRIVATE struct config *newconfig(){
1040 struct config *new;
1041 if( freelist==0 ){
1042 int i;
1043 int amt = 3;
1044 freelist = (struct config *)malloc( sizeof(struct config)*amt );
1045 if( freelist==0 ){
1046 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1047 exit(1);
1048 }
1049 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1050 freelist[amt-1].next = 0;
1051 }
1052 new = freelist;
1053 freelist = freelist->next;
1054 return new;
1055}
1056
1057/* The configuration "old" is no longer used */
1058PRIVATE void deleteconfig(old)
1059struct config *old;
1060{
1061 old->next = freelist;
1062 freelist = old;
1063}
1064
1065/* Initialized the configuration list builder */
1066void Configlist_init(){
1067 current = 0;
1068 currentend = &current;
1069 basis = 0;
1070 basisend = &basis;
1071 Configtable_init();
1072 return;
1073}
1074
1075/* Initialized the configuration list builder */
1076void Configlist_reset(){
1077 current = 0;
1078 currentend = &current;
1079 basis = 0;
1080 basisend = &basis;
1081 Configtable_clear(0);
1082 return;
1083}
1084
1085/* Add another configuration to the configuration list */
1086struct config *Configlist_add(rp,dot)
1087struct rule *rp; /* The rule */
1088int dot; /* Index into the RHS of the rule where the dot goes */
1089{
1090 struct config *cfp, model;
1091
1092 assert( currentend!=0 );
1093 model.rp = rp;
1094 model.dot = dot;
1095 cfp = Configtable_find(&model);
1096 if( cfp==0 ){
1097 cfp = newconfig();
1098 cfp->rp = rp;
1099 cfp->dot = dot;
1100 cfp->fws = SetNew();
1101 cfp->stp = 0;
1102 cfp->fplp = cfp->bplp = 0;
1103 cfp->next = 0;
1104 cfp->bp = 0;
1105 *currentend = cfp;
1106 currentend = &cfp->next;
1107 Configtable_insert(cfp);
1108 }
1109 return cfp;
1110}
1111
1112/* Add a basis configuration to the configuration list */
1113struct config *Configlist_addbasis(rp,dot)
1114struct rule *rp;
1115int dot;
1116{
1117 struct config *cfp, model;
1118
1119 assert( basisend!=0 );
1120 assert( currentend!=0 );
1121 model.rp = rp;
1122 model.dot = dot;
1123 cfp = Configtable_find(&model);
1124 if( cfp==0 ){
1125 cfp = newconfig();
1126 cfp->rp = rp;
1127 cfp->dot = dot;
1128 cfp->fws = SetNew();
1129 cfp->stp = 0;
1130 cfp->fplp = cfp->bplp = 0;
1131 cfp->next = 0;
1132 cfp->bp = 0;
1133 *currentend = cfp;
1134 currentend = &cfp->next;
1135 *basisend = cfp;
1136 basisend = &cfp->bp;
1137 Configtable_insert(cfp);
1138 }
1139 return cfp;
1140}
1141
1142/* Compute the closure of the configuration list */
1143void Configlist_closure(lemp)
1144struct lemon *lemp;
1145{
1146 struct config *cfp, *newcfp;
1147 struct rule *rp, *newrp;
1148 struct symbol *sp, *xsp;
1149 int i, dot;
1150
1151 assert( currentend!=0 );
1152 for(cfp=current; cfp; cfp=cfp->next){
1153 rp = cfp->rp;
1154 dot = cfp->dot;
1155 if( dot>=rp->nrhs ) continue;
1156 sp = rp->rhs[dot];
1157 if( sp->type==NONTERMINAL ){
1158 if( sp->rule==0 && sp!=lemp->errsym ){
1159 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1160 sp->name);
1161 lemp->errorcnt++;
1162 }
1163 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1164 newcfp = Configlist_add(newrp,0);
1165 for(i=dot+1; i<rp->nrhs; i++){
1166 xsp = rp->rhs[i];
1167 if( xsp->type==TERMINAL ){
1168 SetAdd(newcfp->fws,xsp->index);
1169 break;
1170 }else{
1171 SetUnion(newcfp->fws,xsp->firstset);
drhb27b83a2002-08-14 23:18:57 +00001172 if( xsp->lambda==B_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001173 }
1174 }
1175 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1176 }
1177 }
1178 }
1179 return;
1180}
1181
1182/* Sort the configuration list */
1183void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001184 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001185 currentend = 0;
1186 return;
1187}
1188
1189/* Sort the basis configuration list */
1190void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001191 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001192 basisend = 0;
1193 return;
1194}
1195
1196/* Return a pointer to the head of the configuration list and
1197** reset the list */
1198struct config *Configlist_return(){
1199 struct config *old;
1200 old = current;
1201 current = 0;
1202 currentend = 0;
1203 return old;
1204}
1205
1206/* Return a pointer to the head of the configuration list and
1207** reset the list */
1208struct config *Configlist_basis(){
1209 struct config *old;
1210 old = basis;
1211 basis = 0;
1212 basisend = 0;
1213 return old;
1214}
1215
1216/* Free all elements of the given configuration list */
1217void Configlist_eat(cfp)
1218struct config *cfp;
1219{
1220 struct config *nextcfp;
1221 for(; cfp; cfp=nextcfp){
1222 nextcfp = cfp->next;
1223 assert( cfp->fplp==0 );
1224 assert( cfp->bplp==0 );
1225 if( cfp->fws ) SetFree(cfp->fws);
1226 deleteconfig(cfp);
1227 }
1228 return;
1229}
1230/***************** From the file "error.c" *********************************/
1231/*
1232** Code for printing error message.
1233*/
1234
1235/* Find a good place to break "msg" so that its length is at least "min"
1236** but no more than "max". Make the point as close to max as possible.
1237*/
1238static int findbreak(msg,min,max)
1239char *msg;
1240int min;
1241int max;
1242{
1243 int i,spot;
1244 char c;
1245 for(i=spot=min; i<=max; i++){
1246 c = msg[i];
1247 if( c=='\t' ) msg[i] = ' ';
1248 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1249 if( c==0 ){ spot = i; break; }
1250 if( c=='-' && i<max-1 ) spot = i+1;
1251 if( c==' ' ) spot = i;
1252 }
1253 return spot;
1254}
1255
1256/*
1257** The error message is split across multiple lines if necessary. The
1258** splits occur at a space, if there is a space available near the end
1259** of the line.
1260*/
1261#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1262#define LINEWIDTH 79 /* Max width of any output line */
1263#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001264void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001265 char errmsg[ERRMSGSIZE];
1266 char prefix[PREFIXLIMIT+10];
1267 int errmsgsize;
1268 int prefixsize;
1269 int availablewidth;
1270 va_list ap;
1271 int end, restart, base;
1272
drhf9a2e7b2003-04-15 01:49:48 +00001273 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001274 /* Prepare a prefix to be prepended to every output line */
1275 if( lineno>0 ){
1276 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1277 }else{
1278 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1279 }
1280 prefixsize = strlen(prefix);
1281 availablewidth = LINEWIDTH - prefixsize;
1282
1283 /* Generate the error message */
1284 vsprintf(errmsg,format,ap);
1285 va_end(ap);
1286 errmsgsize = strlen(errmsg);
1287 /* Remove trailing '\n's from the error message. */
1288 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1289 errmsg[--errmsgsize] = 0;
1290 }
1291
1292 /* Print the error message */
1293 base = 0;
1294 while( errmsg[base]!=0 ){
1295 end = restart = findbreak(&errmsg[base],0,availablewidth);
1296 restart += base;
1297 while( errmsg[restart]==' ' ) restart++;
1298 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1299 base = restart;
1300 }
1301}
1302/**************** From the file "main.c" ************************************/
1303/*
1304** Main program file for the LEMON parser generator.
1305*/
1306
1307/* Report an out-of-memory condition and abort. This function
1308** is used mostly by the "MemoryCheck" macro in struct.h
1309*/
1310void memory_error(){
1311 fprintf(stderr,"Out of memory. Aborting...\n");
1312 exit(1);
1313}
1314
drh6d08b4d2004-07-20 12:45:22 +00001315static int nDefine = 0; /* Number of -D options on the command line */
1316static char **azDefine = 0; /* Name of the -D macros */
1317
1318/* This routine is called with the argument to each -D command-line option.
1319** Add the macro defined to the azDefine array.
1320*/
1321static void handle_D_option(char *z){
1322 char **paz;
1323 nDefine++;
1324 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1325 if( azDefine==0 ){
1326 fprintf(stderr,"out of memory\n");
1327 exit(1);
1328 }
1329 paz = &azDefine[nDefine-1];
1330 *paz = malloc( strlen(z)+1 );
1331 if( *paz==0 ){
1332 fprintf(stderr,"out of memory\n");
1333 exit(1);
1334 }
1335 strcpy(*paz, z);
1336 for(z=*paz; *z && *z!='='; z++){}
1337 *z = 0;
1338}
1339
drh75897232000-05-29 14:26:00 +00001340
1341/* The main program. Parse the command line and do it... */
1342int main(argc,argv)
1343int argc;
1344char **argv;
1345{
1346 static int version = 0;
1347 static int rpflag = 0;
1348 static int basisflag = 0;
1349 static int compress = 0;
1350 static int quiet = 0;
1351 static int statistics = 0;
1352 static int mhflag = 0;
1353 static struct s_options options[] = {
1354 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1355 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001356 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001357 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1358 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1359 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001360 {OPT_FLAG, "s", (char*)&statistics,
1361 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001362 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1363 {OPT_FLAG,0,0,0}
1364 };
1365 int i;
1366 struct lemon lem;
1367
drhb0c86772000-06-02 23:21:26 +00001368 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001369 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001370 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001371 exit(0);
1372 }
drhb0c86772000-06-02 23:21:26 +00001373 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001374 fprintf(stderr,"Exactly one filename argument is required.\n");
1375 exit(1);
1376 }
1377 lem.errorcnt = 0;
1378
1379 /* Initialize the machine */
1380 Strsafe_init();
1381 Symbol_init();
1382 State_init();
1383 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001384 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001385 lem.basisflag = basisflag;
drh0bd1f4e2002-06-06 18:54:39 +00001386 lem.has_fallback = 0;
drh75897232000-05-29 14:26:00 +00001387 lem.nconflict = 0;
1388 lem.name = lem.include = lem.arg = lem.tokentype = lem.start = 0;
drh960e8c62001-04-03 16:53:21 +00001389 lem.vartype = 0;
drh75897232000-05-29 14:26:00 +00001390 lem.stacksize = 0;
1391 lem.error = lem.overflow = lem.failure = lem.accept = lem.tokendest =
1392 lem.tokenprefix = lem.outname = lem.extracode = 0;
drh960e8c62001-04-03 16:53:21 +00001393 lem.vardest = 0;
drh75897232000-05-29 14:26:00 +00001394 lem.tablesize = 0;
1395 Symbol_new("$");
1396 lem.errsym = Symbol_new("error");
1397
1398 /* Parse the input file */
1399 Parse(&lem);
1400 if( lem.errorcnt ) exit(lem.errorcnt);
1401 if( lem.rule==0 ){
1402 fprintf(stderr,"Empty grammar.\n");
1403 exit(1);
1404 }
1405
1406 /* Count and index the symbols of the grammar */
1407 lem.nsymbol = Symbol_count();
1408 Symbol_new("{default}");
1409 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001410 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001411 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1412 (int(*)())Symbolcmpp);
1413 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1414 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1415 lem.nterminal = i;
1416
1417 /* Generate a reprint of the grammar, if requested on the command line */
1418 if( rpflag ){
1419 Reprint(&lem);
1420 }else{
1421 /* Initialize the size for all follow and first sets */
1422 SetSize(lem.nterminal);
1423
1424 /* Find the precedence for every production rule (that has one) */
1425 FindRulePrecedences(&lem);
1426
1427 /* Compute the lambda-nonterminals and the first-sets for every
1428 ** nonterminal */
1429 FindFirstSets(&lem);
1430
1431 /* Compute all LR(0) states. Also record follow-set propagation
1432 ** links so that the follow-set can be computed later */
1433 lem.nstate = 0;
1434 FindStates(&lem);
1435 lem.sorted = State_arrayof();
1436
1437 /* Tie up loose ends on the propagation links */
1438 FindLinks(&lem);
1439
1440 /* Compute the follow set of every reducible configuration */
1441 FindFollowSets(&lem);
1442
1443 /* Compute the action tables */
1444 FindActions(&lem);
1445
1446 /* Compress the action tables */
1447 if( compress==0 ) CompressTables(&lem);
1448
drhada354d2005-11-05 15:03:59 +00001449 /* Reorder and renumber the states so that states with fewer choices
1450 ** occur at the end. */
1451 ResortStates(&lem);
1452
drh75897232000-05-29 14:26:00 +00001453 /* Generate a report of the parser generated. (the "y.output" file) */
1454 if( !quiet ) ReportOutput(&lem);
1455
1456 /* Generate the source code for the parser */
1457 ReportTable(&lem, mhflag);
1458
1459 /* Produce a header file for use by the scanner. (This step is
1460 ** omitted if the "-m" option is used because makeheaders will
1461 ** generate the file for us.) */
1462 if( !mhflag ) ReportHeader(&lem);
1463 }
1464 if( statistics ){
1465 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1466 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1467 printf(" %d states, %d parser table entries, %d conflicts\n",
1468 lem.nstate, lem.tablesize, lem.nconflict);
1469 }
1470 if( lem.nconflict ){
1471 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1472 }
1473 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001474 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001475}
1476/******************** From the file "msort.c" *******************************/
1477/*
1478** A generic merge-sort program.
1479**
1480** USAGE:
1481** Let "ptr" be a pointer to some structure which is at the head of
1482** a null-terminated list. Then to sort the list call:
1483**
1484** ptr = msort(ptr,&(ptr->next),cmpfnc);
1485**
1486** In the above, "cmpfnc" is a pointer to a function which compares
1487** two instances of the structure and returns an integer, as in
1488** strcmp. The second argument is a pointer to the pointer to the
1489** second element of the linked list. This address is used to compute
1490** the offset to the "next" field within the structure. The offset to
1491** the "next" field must be constant for all structures in the list.
1492**
1493** The function returns a new pointer which is the head of the list
1494** after sorting.
1495**
1496** ALGORITHM:
1497** Merge-sort.
1498*/
1499
1500/*
1501** Return a pointer to the next structure in the linked list.
1502*/
drhba99af52001-10-25 20:37:16 +00001503#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001504
1505/*
1506** Inputs:
1507** a: A sorted, null-terminated linked list. (May be null).
1508** b: A sorted, null-terminated linked list. (May be null).
1509** cmp: A pointer to the comparison function.
1510** offset: Offset in the structure to the "next" field.
1511**
1512** Return Value:
1513** A pointer to the head of a sorted list containing the elements
1514** of both a and b.
1515**
1516** Side effects:
1517** The "next" pointers for elements in the lists a and b are
1518** changed.
1519*/
1520static char *merge(a,b,cmp,offset)
1521char *a;
1522char *b;
1523int (*cmp)();
1524int offset;
1525{
1526 char *ptr, *head;
1527
1528 if( a==0 ){
1529 head = b;
1530 }else if( b==0 ){
1531 head = a;
1532 }else{
1533 if( (*cmp)(a,b)<0 ){
1534 ptr = a;
1535 a = NEXT(a);
1536 }else{
1537 ptr = b;
1538 b = NEXT(b);
1539 }
1540 head = ptr;
1541 while( a && b ){
1542 if( (*cmp)(a,b)<0 ){
1543 NEXT(ptr) = a;
1544 ptr = a;
1545 a = NEXT(a);
1546 }else{
1547 NEXT(ptr) = b;
1548 ptr = b;
1549 b = NEXT(b);
1550 }
1551 }
1552 if( a ) NEXT(ptr) = a;
1553 else NEXT(ptr) = b;
1554 }
1555 return head;
1556}
1557
1558/*
1559** Inputs:
1560** list: Pointer to a singly-linked list of structures.
1561** next: Pointer to pointer to the second element of the list.
1562** cmp: A comparison function.
1563**
1564** Return Value:
1565** A pointer to the head of a sorted list containing the elements
1566** orginally in list.
1567**
1568** Side effects:
1569** The "next" pointers for elements in list are changed.
1570*/
1571#define LISTSIZE 30
1572char *msort(list,next,cmp)
1573char *list;
1574char **next;
1575int (*cmp)();
1576{
drhba99af52001-10-25 20:37:16 +00001577 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001578 char *ep;
1579 char *set[LISTSIZE];
1580 int i;
drhba99af52001-10-25 20:37:16 +00001581 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001582 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1583 while( list ){
1584 ep = list;
1585 list = NEXT(list);
1586 NEXT(ep) = 0;
1587 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1588 ep = merge(ep,set[i],cmp,offset);
1589 set[i] = 0;
1590 }
1591 set[i] = ep;
1592 }
1593 ep = 0;
1594 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1595 return ep;
1596}
1597/************************ From the file "option.c" **************************/
1598static char **argv;
1599static struct s_options *op;
1600static FILE *errstream;
1601
1602#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1603
1604/*
1605** Print the command line with a carrot pointing to the k-th character
1606** of the n-th field.
1607*/
1608static void errline(n,k,err)
1609int n;
1610int k;
1611FILE *err;
1612{
1613 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001614 if( argv[0] ) fprintf(err,"%s",argv[0]);
1615 spcnt = strlen(argv[0]) + 1;
1616 for(i=1; i<n && argv[i]; i++){
1617 fprintf(err," %s",argv[i]);
drhdc30dd32005-02-16 03:35:15 +00001618 spcnt += strlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001619 }
1620 spcnt += k;
1621 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1622 if( spcnt<20 ){
1623 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1624 }else{
1625 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1626 }
1627}
1628
1629/*
1630** Return the index of the N-th non-switch argument. Return -1
1631** if N is out of range.
1632*/
1633static int argindex(n)
1634int n;
1635{
1636 int i;
1637 int dashdash = 0;
1638 if( argv!=0 && *argv!=0 ){
1639 for(i=1; argv[i]; i++){
1640 if( dashdash || !ISOPT(argv[i]) ){
1641 if( n==0 ) return i;
1642 n--;
1643 }
1644 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1645 }
1646 }
1647 return -1;
1648}
1649
1650static char emsg[] = "Command line syntax error: ";
1651
1652/*
1653** Process a flag command line argument.
1654*/
1655static int handleflags(i,err)
1656int i;
1657FILE *err;
1658{
1659 int v;
1660 int errcnt = 0;
1661 int j;
1662 for(j=0; op[j].label; j++){
drh6d08b4d2004-07-20 12:45:22 +00001663 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001664 }
1665 v = argv[i][0]=='-' ? 1 : 0;
1666 if( op[j].label==0 ){
1667 if( err ){
1668 fprintf(err,"%sundefined option.\n",emsg);
1669 errline(i,1,err);
1670 }
1671 errcnt++;
1672 }else if( op[j].type==OPT_FLAG ){
1673 *((int*)op[j].arg) = v;
1674 }else if( op[j].type==OPT_FFLAG ){
1675 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001676 }else if( op[j].type==OPT_FSTR ){
1677 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001678 }else{
1679 if( err ){
1680 fprintf(err,"%smissing argument on switch.\n",emsg);
1681 errline(i,1,err);
1682 }
1683 errcnt++;
1684 }
1685 return errcnt;
1686}
1687
1688/*
1689** Process a command line switch which has an argument.
1690*/
1691static int handleswitch(i,err)
1692int i;
1693FILE *err;
1694{
1695 int lv = 0;
1696 double dv = 0.0;
1697 char *sv = 0, *end;
1698 char *cp;
1699 int j;
1700 int errcnt = 0;
1701 cp = strchr(argv[i],'=');
1702 *cp = 0;
1703 for(j=0; op[j].label; j++){
1704 if( strcmp(argv[i],op[j].label)==0 ) break;
1705 }
1706 *cp = '=';
1707 if( op[j].label==0 ){
1708 if( err ){
1709 fprintf(err,"%sundefined option.\n",emsg);
1710 errline(i,0,err);
1711 }
1712 errcnt++;
1713 }else{
1714 cp++;
1715 switch( op[j].type ){
1716 case OPT_FLAG:
1717 case OPT_FFLAG:
1718 if( err ){
1719 fprintf(err,"%soption requires an argument.\n",emsg);
1720 errline(i,0,err);
1721 }
1722 errcnt++;
1723 break;
1724 case OPT_DBL:
1725 case OPT_FDBL:
1726 dv = strtod(cp,&end);
1727 if( *end ){
1728 if( err ){
1729 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001730 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001731 }
1732 errcnt++;
1733 }
1734 break;
1735 case OPT_INT:
1736 case OPT_FINT:
1737 lv = strtol(cp,&end,0);
1738 if( *end ){
1739 if( err ){
1740 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001741 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001742 }
1743 errcnt++;
1744 }
1745 break;
1746 case OPT_STR:
1747 case OPT_FSTR:
1748 sv = cp;
1749 break;
1750 }
1751 switch( op[j].type ){
1752 case OPT_FLAG:
1753 case OPT_FFLAG:
1754 break;
1755 case OPT_DBL:
1756 *(double*)(op[j].arg) = dv;
1757 break;
1758 case OPT_FDBL:
1759 (*(void(*)())(op[j].arg))(dv);
1760 break;
1761 case OPT_INT:
1762 *(int*)(op[j].arg) = lv;
1763 break;
1764 case OPT_FINT:
1765 (*(void(*)())(op[j].arg))((int)lv);
1766 break;
1767 case OPT_STR:
1768 *(char**)(op[j].arg) = sv;
1769 break;
1770 case OPT_FSTR:
1771 (*(void(*)())(op[j].arg))(sv);
1772 break;
1773 }
1774 }
1775 return errcnt;
1776}
1777
drhb0c86772000-06-02 23:21:26 +00001778int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001779char **a;
1780struct s_options *o;
1781FILE *err;
1782{
1783 int errcnt = 0;
1784 argv = a;
1785 op = o;
1786 errstream = err;
1787 if( argv && *argv && op ){
1788 int i;
1789 for(i=1; argv[i]; i++){
1790 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1791 errcnt += handleflags(i,err);
1792 }else if( strchr(argv[i],'=') ){
1793 errcnt += handleswitch(i,err);
1794 }
1795 }
1796 }
1797 if( errcnt>0 ){
1798 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001799 OptPrint();
drh75897232000-05-29 14:26:00 +00001800 exit(1);
1801 }
1802 return 0;
1803}
1804
drhb0c86772000-06-02 23:21:26 +00001805int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001806 int cnt = 0;
1807 int dashdash = 0;
1808 int i;
1809 if( argv!=0 && argv[0]!=0 ){
1810 for(i=1; argv[i]; i++){
1811 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1812 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1813 }
1814 }
1815 return cnt;
1816}
1817
drhb0c86772000-06-02 23:21:26 +00001818char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001819int n;
1820{
1821 int i;
1822 i = argindex(n);
1823 return i>=0 ? argv[i] : 0;
1824}
1825
drhb0c86772000-06-02 23:21:26 +00001826void OptErr(n)
drh75897232000-05-29 14:26:00 +00001827int n;
1828{
1829 int i;
1830 i = argindex(n);
1831 if( i>=0 ) errline(i,0,errstream);
1832}
1833
drhb0c86772000-06-02 23:21:26 +00001834void OptPrint(){
drh75897232000-05-29 14:26:00 +00001835 int i;
1836 int max, len;
1837 max = 0;
1838 for(i=0; op[i].label; i++){
1839 len = strlen(op[i].label) + 1;
1840 switch( op[i].type ){
1841 case OPT_FLAG:
1842 case OPT_FFLAG:
1843 break;
1844 case OPT_INT:
1845 case OPT_FINT:
1846 len += 9; /* length of "<integer>" */
1847 break;
1848 case OPT_DBL:
1849 case OPT_FDBL:
1850 len += 6; /* length of "<real>" */
1851 break;
1852 case OPT_STR:
1853 case OPT_FSTR:
1854 len += 8; /* length of "<string>" */
1855 break;
1856 }
1857 if( len>max ) max = len;
1858 }
1859 for(i=0; op[i].label; i++){
1860 switch( op[i].type ){
1861 case OPT_FLAG:
1862 case OPT_FFLAG:
1863 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1864 break;
1865 case OPT_INT:
1866 case OPT_FINT:
1867 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001868 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001869 break;
1870 case OPT_DBL:
1871 case OPT_FDBL:
1872 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001873 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001874 break;
1875 case OPT_STR:
1876 case OPT_FSTR:
1877 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001878 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001879 break;
1880 }
1881 }
1882}
1883/*********************** From the file "parse.c" ****************************/
1884/*
1885** Input file parser for the LEMON parser generator.
1886*/
1887
1888/* The state of the parser */
1889struct pstate {
1890 char *filename; /* Name of the input file */
1891 int tokenlineno; /* Linenumber at which current token starts */
1892 int errorcnt; /* Number of errors so far */
1893 char *tokenstart; /* Text of current token */
1894 struct lemon *gp; /* Global state vector */
1895 enum e_state {
1896 INITIALIZE,
1897 WAITING_FOR_DECL_OR_RULE,
1898 WAITING_FOR_DECL_KEYWORD,
1899 WAITING_FOR_DECL_ARG,
1900 WAITING_FOR_PRECEDENCE_SYMBOL,
1901 WAITING_FOR_ARROW,
1902 IN_RHS,
1903 LHS_ALIAS_1,
1904 LHS_ALIAS_2,
1905 LHS_ALIAS_3,
1906 RHS_ALIAS_1,
1907 RHS_ALIAS_2,
1908 PRECEDENCE_MARK_1,
1909 PRECEDENCE_MARK_2,
1910 RESYNC_AFTER_RULE_ERROR,
1911 RESYNC_AFTER_DECL_ERROR,
1912 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001913 WAITING_FOR_DATATYPE_SYMBOL,
1914 WAITING_FOR_FALLBACK_ID
drh75897232000-05-29 14:26:00 +00001915 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001916 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001917 struct symbol *lhs; /* Left-hand side of current rule */
1918 char *lhsalias; /* Alias for the LHS */
1919 int nrhs; /* Number of right-hand side symbols seen */
1920 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1921 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1922 struct rule *prevrule; /* Previous rule parsed */
1923 char *declkeyword; /* Keyword of a declaration */
1924 char **declargslot; /* Where the declaration argument should be put */
1925 int *decllnslot; /* Where the declaration linenumber is put */
1926 enum e_assoc declassoc; /* Assign this association to decl arguments */
1927 int preccounter; /* Assign this precedence to decl arguments */
1928 struct rule *firstrule; /* Pointer to first rule in the grammar */
1929 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1930};
1931
1932/* Parse a single token */
1933static void parseonetoken(psp)
1934struct pstate *psp;
1935{
1936 char *x;
1937 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1938#if 0
1939 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1940 x,psp->state);
1941#endif
1942 switch( psp->state ){
1943 case INITIALIZE:
1944 psp->prevrule = 0;
1945 psp->preccounter = 0;
1946 psp->firstrule = psp->lastrule = 0;
1947 psp->gp->nrule = 0;
1948 /* Fall thru to next case */
1949 case WAITING_FOR_DECL_OR_RULE:
1950 if( x[0]=='%' ){
1951 psp->state = WAITING_FOR_DECL_KEYWORD;
1952 }else if( islower(x[0]) ){
1953 psp->lhs = Symbol_new(x);
1954 psp->nrhs = 0;
1955 psp->lhsalias = 0;
1956 psp->state = WAITING_FOR_ARROW;
1957 }else if( x[0]=='{' ){
1958 if( psp->prevrule==0 ){
1959 ErrorMsg(psp->filename,psp->tokenlineno,
1960"There is not prior rule opon which to attach the code \
1961fragment which begins on this line.");
1962 psp->errorcnt++;
1963 }else if( psp->prevrule->code!=0 ){
1964 ErrorMsg(psp->filename,psp->tokenlineno,
1965"Code fragment beginning on this line is not the first \
1966to follow the previous rule.");
1967 psp->errorcnt++;
1968 }else{
1969 psp->prevrule->line = psp->tokenlineno;
1970 psp->prevrule->code = &x[1];
1971 }
1972 }else if( x[0]=='[' ){
1973 psp->state = PRECEDENCE_MARK_1;
1974 }else{
1975 ErrorMsg(psp->filename,psp->tokenlineno,
1976 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
1977 x);
1978 psp->errorcnt++;
1979 }
1980 break;
1981 case PRECEDENCE_MARK_1:
1982 if( !isupper(x[0]) ){
1983 ErrorMsg(psp->filename,psp->tokenlineno,
1984 "The precedence symbol must be a terminal.");
1985 psp->errorcnt++;
1986 }else if( psp->prevrule==0 ){
1987 ErrorMsg(psp->filename,psp->tokenlineno,
1988 "There is no prior rule to assign precedence \"[%s]\".",x);
1989 psp->errorcnt++;
1990 }else if( psp->prevrule->precsym!=0 ){
1991 ErrorMsg(psp->filename,psp->tokenlineno,
1992"Precedence mark on this line is not the first \
1993to follow the previous rule.");
1994 psp->errorcnt++;
1995 }else{
1996 psp->prevrule->precsym = Symbol_new(x);
1997 }
1998 psp->state = PRECEDENCE_MARK_2;
1999 break;
2000 case PRECEDENCE_MARK_2:
2001 if( x[0]!=']' ){
2002 ErrorMsg(psp->filename,psp->tokenlineno,
2003 "Missing \"]\" on precedence mark.");
2004 psp->errorcnt++;
2005 }
2006 psp->state = WAITING_FOR_DECL_OR_RULE;
2007 break;
2008 case WAITING_FOR_ARROW:
2009 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2010 psp->state = IN_RHS;
2011 }else if( x[0]=='(' ){
2012 psp->state = LHS_ALIAS_1;
2013 }else{
2014 ErrorMsg(psp->filename,psp->tokenlineno,
2015 "Expected to see a \":\" following the LHS symbol \"%s\".",
2016 psp->lhs->name);
2017 psp->errorcnt++;
2018 psp->state = RESYNC_AFTER_RULE_ERROR;
2019 }
2020 break;
2021 case LHS_ALIAS_1:
2022 if( isalpha(x[0]) ){
2023 psp->lhsalias = x;
2024 psp->state = LHS_ALIAS_2;
2025 }else{
2026 ErrorMsg(psp->filename,psp->tokenlineno,
2027 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2028 x,psp->lhs->name);
2029 psp->errorcnt++;
2030 psp->state = RESYNC_AFTER_RULE_ERROR;
2031 }
2032 break;
2033 case LHS_ALIAS_2:
2034 if( x[0]==')' ){
2035 psp->state = LHS_ALIAS_3;
2036 }else{
2037 ErrorMsg(psp->filename,psp->tokenlineno,
2038 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2039 psp->errorcnt++;
2040 psp->state = RESYNC_AFTER_RULE_ERROR;
2041 }
2042 break;
2043 case LHS_ALIAS_3:
2044 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2045 psp->state = IN_RHS;
2046 }else{
2047 ErrorMsg(psp->filename,psp->tokenlineno,
2048 "Missing \"->\" following: \"%s(%s)\".",
2049 psp->lhs->name,psp->lhsalias);
2050 psp->errorcnt++;
2051 psp->state = RESYNC_AFTER_RULE_ERROR;
2052 }
2053 break;
2054 case IN_RHS:
2055 if( x[0]=='.' ){
2056 struct rule *rp;
2057 rp = (struct rule *)malloc( sizeof(struct rule) +
2058 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs );
2059 if( rp==0 ){
2060 ErrorMsg(psp->filename,psp->tokenlineno,
2061 "Can't allocate enough memory for this rule.");
2062 psp->errorcnt++;
2063 psp->prevrule = 0;
2064 }else{
2065 int i;
2066 rp->ruleline = psp->tokenlineno;
2067 rp->rhs = (struct symbol**)&rp[1];
2068 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2069 for(i=0; i<psp->nrhs; i++){
2070 rp->rhs[i] = psp->rhs[i];
2071 rp->rhsalias[i] = psp->alias[i];
2072 }
2073 rp->lhs = psp->lhs;
2074 rp->lhsalias = psp->lhsalias;
2075 rp->nrhs = psp->nrhs;
2076 rp->code = 0;
2077 rp->precsym = 0;
2078 rp->index = psp->gp->nrule++;
2079 rp->nextlhs = rp->lhs->rule;
2080 rp->lhs->rule = rp;
2081 rp->next = 0;
2082 if( psp->firstrule==0 ){
2083 psp->firstrule = psp->lastrule = rp;
2084 }else{
2085 psp->lastrule->next = rp;
2086 psp->lastrule = rp;
2087 }
2088 psp->prevrule = rp;
2089 }
2090 psp->state = WAITING_FOR_DECL_OR_RULE;
2091 }else if( isalpha(x[0]) ){
2092 if( psp->nrhs>=MAXRHS ){
2093 ErrorMsg(psp->filename,psp->tokenlineno,
2094 "Too many symbol on RHS or rule beginning at \"%s\".",
2095 x);
2096 psp->errorcnt++;
2097 psp->state = RESYNC_AFTER_RULE_ERROR;
2098 }else{
2099 psp->rhs[psp->nrhs] = Symbol_new(x);
2100 psp->alias[psp->nrhs] = 0;
2101 psp->nrhs++;
2102 }
2103 }else if( x[0]=='(' && psp->nrhs>0 ){
2104 psp->state = RHS_ALIAS_1;
2105 }else{
2106 ErrorMsg(psp->filename,psp->tokenlineno,
2107 "Illegal character on RHS of rule: \"%s\".",x);
2108 psp->errorcnt++;
2109 psp->state = RESYNC_AFTER_RULE_ERROR;
2110 }
2111 break;
2112 case RHS_ALIAS_1:
2113 if( isalpha(x[0]) ){
2114 psp->alias[psp->nrhs-1] = x;
2115 psp->state = RHS_ALIAS_2;
2116 }else{
2117 ErrorMsg(psp->filename,psp->tokenlineno,
2118 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2119 x,psp->rhs[psp->nrhs-1]->name);
2120 psp->errorcnt++;
2121 psp->state = RESYNC_AFTER_RULE_ERROR;
2122 }
2123 break;
2124 case RHS_ALIAS_2:
2125 if( x[0]==')' ){
2126 psp->state = IN_RHS;
2127 }else{
2128 ErrorMsg(psp->filename,psp->tokenlineno,
2129 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2130 psp->errorcnt++;
2131 psp->state = RESYNC_AFTER_RULE_ERROR;
2132 }
2133 break;
2134 case WAITING_FOR_DECL_KEYWORD:
2135 if( isalpha(x[0]) ){
2136 psp->declkeyword = x;
2137 psp->declargslot = 0;
2138 psp->decllnslot = 0;
2139 psp->state = WAITING_FOR_DECL_ARG;
2140 if( strcmp(x,"name")==0 ){
2141 psp->declargslot = &(psp->gp->name);
2142 }else if( strcmp(x,"include")==0 ){
2143 psp->declargslot = &(psp->gp->include);
2144 psp->decllnslot = &psp->gp->includeln;
2145 }else if( strcmp(x,"code")==0 ){
2146 psp->declargslot = &(psp->gp->extracode);
2147 psp->decllnslot = &psp->gp->extracodeln;
2148 }else if( strcmp(x,"token_destructor")==0 ){
2149 psp->declargslot = &psp->gp->tokendest;
2150 psp->decllnslot = &psp->gp->tokendestln;
drh960e8c62001-04-03 16:53:21 +00002151 }else if( strcmp(x,"default_destructor")==0 ){
2152 psp->declargslot = &psp->gp->vardest;
2153 psp->decllnslot = &psp->gp->vardestln;
drh75897232000-05-29 14:26:00 +00002154 }else if( strcmp(x,"token_prefix")==0 ){
2155 psp->declargslot = &psp->gp->tokenprefix;
2156 }else if( strcmp(x,"syntax_error")==0 ){
2157 psp->declargslot = &(psp->gp->error);
2158 psp->decllnslot = &psp->gp->errorln;
2159 }else if( strcmp(x,"parse_accept")==0 ){
2160 psp->declargslot = &(psp->gp->accept);
2161 psp->decllnslot = &psp->gp->acceptln;
2162 }else if( strcmp(x,"parse_failure")==0 ){
2163 psp->declargslot = &(psp->gp->failure);
2164 psp->decllnslot = &psp->gp->failureln;
2165 }else if( strcmp(x,"stack_overflow")==0 ){
2166 psp->declargslot = &(psp->gp->overflow);
2167 psp->decllnslot = &psp->gp->overflowln;
2168 }else if( strcmp(x,"extra_argument")==0 ){
2169 psp->declargslot = &(psp->gp->arg);
2170 }else if( strcmp(x,"token_type")==0 ){
2171 psp->declargslot = &(psp->gp->tokentype);
drh960e8c62001-04-03 16:53:21 +00002172 }else if( strcmp(x,"default_type")==0 ){
2173 psp->declargslot = &(psp->gp->vartype);
drh75897232000-05-29 14:26:00 +00002174 }else if( strcmp(x,"stack_size")==0 ){
2175 psp->declargslot = &(psp->gp->stacksize);
2176 }else if( strcmp(x,"start_symbol")==0 ){
2177 psp->declargslot = &(psp->gp->start);
2178 }else if( strcmp(x,"left")==0 ){
2179 psp->preccounter++;
2180 psp->declassoc = LEFT;
2181 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2182 }else if( strcmp(x,"right")==0 ){
2183 psp->preccounter++;
2184 psp->declassoc = RIGHT;
2185 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2186 }else if( strcmp(x,"nonassoc")==0 ){
2187 psp->preccounter++;
2188 psp->declassoc = NONE;
2189 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2190 }else if( strcmp(x,"destructor")==0 ){
2191 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2192 }else if( strcmp(x,"type")==0 ){
2193 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002194 }else if( strcmp(x,"fallback")==0 ){
2195 psp->fallback = 0;
2196 psp->state = WAITING_FOR_FALLBACK_ID;
drh75897232000-05-29 14:26:00 +00002197 }else{
2198 ErrorMsg(psp->filename,psp->tokenlineno,
2199 "Unknown declaration keyword: \"%%%s\".",x);
2200 psp->errorcnt++;
2201 psp->state = RESYNC_AFTER_DECL_ERROR;
2202 }
2203 }else{
2204 ErrorMsg(psp->filename,psp->tokenlineno,
2205 "Illegal declaration keyword: \"%s\".",x);
2206 psp->errorcnt++;
2207 psp->state = RESYNC_AFTER_DECL_ERROR;
2208 }
2209 break;
2210 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2211 if( !isalpha(x[0]) ){
2212 ErrorMsg(psp->filename,psp->tokenlineno,
2213 "Symbol name missing after %destructor keyword");
2214 psp->errorcnt++;
2215 psp->state = RESYNC_AFTER_DECL_ERROR;
2216 }else{
2217 struct symbol *sp = Symbol_new(x);
2218 psp->declargslot = &sp->destructor;
2219 psp->decllnslot = &sp->destructorln;
2220 psp->state = WAITING_FOR_DECL_ARG;
2221 }
2222 break;
2223 case WAITING_FOR_DATATYPE_SYMBOL:
2224 if( !isalpha(x[0]) ){
2225 ErrorMsg(psp->filename,psp->tokenlineno,
2226 "Symbol name missing after %destructor keyword");
2227 psp->errorcnt++;
2228 psp->state = RESYNC_AFTER_DECL_ERROR;
2229 }else{
2230 struct symbol *sp = Symbol_new(x);
2231 psp->declargslot = &sp->datatype;
2232 psp->decllnslot = 0;
2233 psp->state = WAITING_FOR_DECL_ARG;
2234 }
2235 break;
2236 case WAITING_FOR_PRECEDENCE_SYMBOL:
2237 if( x[0]=='.' ){
2238 psp->state = WAITING_FOR_DECL_OR_RULE;
2239 }else if( isupper(x[0]) ){
2240 struct symbol *sp;
2241 sp = Symbol_new(x);
2242 if( sp->prec>=0 ){
2243 ErrorMsg(psp->filename,psp->tokenlineno,
2244 "Symbol \"%s\" has already be given a precedence.",x);
2245 psp->errorcnt++;
2246 }else{
2247 sp->prec = psp->preccounter;
2248 sp->assoc = psp->declassoc;
2249 }
2250 }else{
2251 ErrorMsg(psp->filename,psp->tokenlineno,
2252 "Can't assign a precedence to \"%s\".",x);
2253 psp->errorcnt++;
2254 }
2255 break;
2256 case WAITING_FOR_DECL_ARG:
2257 if( (x[0]=='{' || x[0]=='\"' || isalnum(x[0])) ){
2258 if( *(psp->declargslot)!=0 ){
2259 ErrorMsg(psp->filename,psp->tokenlineno,
2260 "The argument \"%s\" to declaration \"%%%s\" is not the first.",
2261 x[0]=='\"' ? &x[1] : x,psp->declkeyword);
2262 psp->errorcnt++;
2263 psp->state = RESYNC_AFTER_DECL_ERROR;
2264 }else{
2265 *(psp->declargslot) = (x[0]=='\"' || x[0]=='{') ? &x[1] : x;
2266 if( psp->decllnslot ) *psp->decllnslot = psp->tokenlineno;
2267 psp->state = WAITING_FOR_DECL_OR_RULE;
2268 }
2269 }else{
2270 ErrorMsg(psp->filename,psp->tokenlineno,
2271 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2272 psp->errorcnt++;
2273 psp->state = RESYNC_AFTER_DECL_ERROR;
2274 }
2275 break;
drh0bd1f4e2002-06-06 18:54:39 +00002276 case WAITING_FOR_FALLBACK_ID:
2277 if( x[0]=='.' ){
2278 psp->state = WAITING_FOR_DECL_OR_RULE;
2279 }else if( !isupper(x[0]) ){
2280 ErrorMsg(psp->filename, psp->tokenlineno,
2281 "%%fallback argument \"%s\" should be a token", x);
2282 psp->errorcnt++;
2283 }else{
2284 struct symbol *sp = Symbol_new(x);
2285 if( psp->fallback==0 ){
2286 psp->fallback = sp;
2287 }else if( sp->fallback ){
2288 ErrorMsg(psp->filename, psp->tokenlineno,
2289 "More than one fallback assigned to token %s", x);
2290 psp->errorcnt++;
2291 }else{
2292 sp->fallback = psp->fallback;
2293 psp->gp->has_fallback = 1;
2294 }
2295 }
2296 break;
drh75897232000-05-29 14:26:00 +00002297 case RESYNC_AFTER_RULE_ERROR:
2298/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2299** break; */
2300 case RESYNC_AFTER_DECL_ERROR:
2301 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2302 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2303 break;
2304 }
2305}
2306
drh6d08b4d2004-07-20 12:45:22 +00002307/* Run the proprocessor over the input file text. The global variables
2308** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2309** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2310** comments them out. Text in between is also commented out as appropriate.
2311*/
danielk1977940fac92005-01-23 22:41:37 +00002312static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002313 int i, j, k, n;
2314 int exclude = 0;
2315 int start;
2316 int lineno = 1;
2317 int start_lineno;
2318 for(i=0; z[i]; i++){
2319 if( z[i]=='\n' ) lineno++;
2320 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2321 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2322 if( exclude ){
2323 exclude--;
2324 if( exclude==0 ){
2325 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2326 }
2327 }
2328 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2329 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2330 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2331 if( exclude ){
2332 exclude++;
2333 }else{
2334 for(j=i+7; isspace(z[j]); j++){}
2335 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2336 exclude = 1;
2337 for(k=0; k<nDefine; k++){
2338 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2339 exclude = 0;
2340 break;
2341 }
2342 }
2343 if( z[i+3]=='n' ) exclude = !exclude;
2344 if( exclude ){
2345 start = i;
2346 start_lineno = lineno;
2347 }
2348 }
2349 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2350 }
2351 }
2352 if( exclude ){
2353 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2354 exit(1);
2355 }
2356}
2357
drh75897232000-05-29 14:26:00 +00002358/* In spite of its name, this function is really a scanner. It read
2359** in the entire input file (all at once) then tokenizes it. Each
2360** token is passed to the function "parseonetoken" which builds all
2361** the appropriate data structures in the global state vector "gp".
2362*/
2363void Parse(gp)
2364struct lemon *gp;
2365{
2366 struct pstate ps;
2367 FILE *fp;
2368 char *filebuf;
2369 int filesize;
2370 int lineno;
2371 int c;
2372 char *cp, *nextcp;
2373 int startline = 0;
2374
2375 ps.gp = gp;
2376 ps.filename = gp->filename;
2377 ps.errorcnt = 0;
2378 ps.state = INITIALIZE;
2379
2380 /* Begin by reading the input file */
2381 fp = fopen(ps.filename,"rb");
2382 if( fp==0 ){
2383 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2384 gp->errorcnt++;
2385 return;
2386 }
2387 fseek(fp,0,2);
2388 filesize = ftell(fp);
2389 rewind(fp);
2390 filebuf = (char *)malloc( filesize+1 );
2391 if( filebuf==0 ){
2392 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2393 filesize+1);
2394 gp->errorcnt++;
2395 return;
2396 }
2397 if( fread(filebuf,1,filesize,fp)!=filesize ){
2398 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2399 filesize);
2400 free(filebuf);
2401 gp->errorcnt++;
2402 return;
2403 }
2404 fclose(fp);
2405 filebuf[filesize] = 0;
2406
drh6d08b4d2004-07-20 12:45:22 +00002407 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2408 preprocess_input(filebuf);
2409
drh75897232000-05-29 14:26:00 +00002410 /* Now scan the text of the input file */
2411 lineno = 1;
2412 for(cp=filebuf; (c= *cp)!=0; ){
2413 if( c=='\n' ) lineno++; /* Keep track of the line number */
2414 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2415 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2416 cp+=2;
2417 while( (c= *cp)!=0 && c!='\n' ) cp++;
2418 continue;
2419 }
2420 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2421 cp+=2;
2422 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2423 if( c=='\n' ) lineno++;
2424 cp++;
2425 }
2426 if( c ) cp++;
2427 continue;
2428 }
2429 ps.tokenstart = cp; /* Mark the beginning of the token */
2430 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2431 if( c=='\"' ){ /* String literals */
2432 cp++;
2433 while( (c= *cp)!=0 && c!='\"' ){
2434 if( c=='\n' ) lineno++;
2435 cp++;
2436 }
2437 if( c==0 ){
2438 ErrorMsg(ps.filename,startline,
2439"String starting on this line is not terminated before the end of the file.");
2440 ps.errorcnt++;
2441 nextcp = cp;
2442 }else{
2443 nextcp = cp+1;
2444 }
2445 }else if( c=='{' ){ /* A block of C code */
2446 int level;
2447 cp++;
2448 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2449 if( c=='\n' ) lineno++;
2450 else if( c=='{' ) level++;
2451 else if( c=='}' ) level--;
2452 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2453 int prevc;
2454 cp = &cp[2];
2455 prevc = 0;
2456 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2457 if( c=='\n' ) lineno++;
2458 prevc = c;
2459 cp++;
2460 }
2461 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2462 cp = &cp[2];
2463 while( (c= *cp)!=0 && c!='\n' ) cp++;
2464 if( c ) lineno++;
2465 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2466 int startchar, prevc;
2467 startchar = c;
2468 prevc = 0;
2469 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2470 if( c=='\n' ) lineno++;
2471 if( prevc=='\\' ) prevc = 0;
2472 else prevc = c;
2473 }
2474 }
2475 }
2476 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002477 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002478"C code starting on this line is not terminated before the end of the file.");
2479 ps.errorcnt++;
2480 nextcp = cp;
2481 }else{
2482 nextcp = cp+1;
2483 }
2484 }else if( isalnum(c) ){ /* Identifiers */
2485 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2486 nextcp = cp;
2487 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2488 cp += 3;
2489 nextcp = cp;
2490 }else{ /* All other (one character) operators */
2491 cp++;
2492 nextcp = cp;
2493 }
2494 c = *cp;
2495 *cp = 0; /* Null terminate the token */
2496 parseonetoken(&ps); /* Parse the token */
2497 *cp = c; /* Restore the buffer */
2498 cp = nextcp;
2499 }
2500 free(filebuf); /* Release the buffer after parsing */
2501 gp->rule = ps.firstrule;
2502 gp->errorcnt = ps.errorcnt;
2503}
2504/*************************** From the file "plink.c" *********************/
2505/*
2506** Routines processing configuration follow-set propagation links
2507** in the LEMON parser generator.
2508*/
2509static struct plink *plink_freelist = 0;
2510
2511/* Allocate a new plink */
2512struct plink *Plink_new(){
2513 struct plink *new;
2514
2515 if( plink_freelist==0 ){
2516 int i;
2517 int amt = 100;
2518 plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt );
2519 if( plink_freelist==0 ){
2520 fprintf(stderr,
2521 "Unable to allocate memory for a new follow-set propagation link.\n");
2522 exit(1);
2523 }
2524 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2525 plink_freelist[amt-1].next = 0;
2526 }
2527 new = plink_freelist;
2528 plink_freelist = plink_freelist->next;
2529 return new;
2530}
2531
2532/* Add a plink to a plink list */
2533void Plink_add(plpp,cfp)
2534struct plink **plpp;
2535struct config *cfp;
2536{
2537 struct plink *new;
2538 new = Plink_new();
2539 new->next = *plpp;
2540 *plpp = new;
2541 new->cfp = cfp;
2542}
2543
2544/* Transfer every plink on the list "from" to the list "to" */
2545void Plink_copy(to,from)
2546struct plink **to;
2547struct plink *from;
2548{
2549 struct plink *nextpl;
2550 while( from ){
2551 nextpl = from->next;
2552 from->next = *to;
2553 *to = from;
2554 from = nextpl;
2555 }
2556}
2557
2558/* Delete every plink on the list */
2559void Plink_delete(plp)
2560struct plink *plp;
2561{
2562 struct plink *nextpl;
2563
2564 while( plp ){
2565 nextpl = plp->next;
2566 plp->next = plink_freelist;
2567 plink_freelist = plp;
2568 plp = nextpl;
2569 }
2570}
2571/*********************** From the file "report.c" **************************/
2572/*
2573** Procedures for generating reports and tables in the LEMON parser generator.
2574*/
2575
2576/* Generate a filename with the given suffix. Space to hold the
2577** name comes from malloc() and must be freed by the calling
2578** function.
2579*/
2580PRIVATE char *file_makename(lemp,suffix)
2581struct lemon *lemp;
2582char *suffix;
2583{
2584 char *name;
2585 char *cp;
2586
2587 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2588 if( name==0 ){
2589 fprintf(stderr,"Can't allocate space for a filename.\n");
2590 exit(1);
2591 }
2592 strcpy(name,lemp->filename);
2593 cp = strrchr(name,'.');
2594 if( cp ) *cp = 0;
2595 strcat(name,suffix);
2596 return name;
2597}
2598
2599/* Open a file with a name based on the name of the input file,
2600** but with a different (specified) suffix, and return a pointer
2601** to the stream */
2602PRIVATE FILE *file_open(lemp,suffix,mode)
2603struct lemon *lemp;
2604char *suffix;
2605char *mode;
2606{
2607 FILE *fp;
2608
2609 if( lemp->outname ) free(lemp->outname);
2610 lemp->outname = file_makename(lemp, suffix);
2611 fp = fopen(lemp->outname,mode);
2612 if( fp==0 && *mode=='w' ){
2613 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2614 lemp->errorcnt++;
2615 return 0;
2616 }
2617 return fp;
2618}
2619
2620/* Duplicate the input file without comments and without actions
2621** on rules */
2622void Reprint(lemp)
2623struct lemon *lemp;
2624{
2625 struct rule *rp;
2626 struct symbol *sp;
2627 int i, j, maxlen, len, ncolumns, skip;
2628 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2629 maxlen = 10;
2630 for(i=0; i<lemp->nsymbol; i++){
2631 sp = lemp->symbols[i];
2632 len = strlen(sp->name);
2633 if( len>maxlen ) maxlen = len;
2634 }
2635 ncolumns = 76/(maxlen+5);
2636 if( ncolumns<1 ) ncolumns = 1;
2637 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2638 for(i=0; i<skip; i++){
2639 printf("//");
2640 for(j=i; j<lemp->nsymbol; j+=skip){
2641 sp = lemp->symbols[j];
2642 assert( sp->index==j );
2643 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2644 }
2645 printf("\n");
2646 }
2647 for(rp=lemp->rule; rp; rp=rp->next){
2648 printf("%s",rp->lhs->name);
2649/* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
2650 printf(" ::=");
2651 for(i=0; i<rp->nrhs; i++){
2652 printf(" %s",rp->rhs[i]->name);
2653/* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
2654 }
2655 printf(".");
2656 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
2657/* if( rp->code ) printf("\n %s",rp->code); */
2658 printf("\n");
2659 }
2660}
2661
2662void ConfigPrint(fp,cfp)
2663FILE *fp;
2664struct config *cfp;
2665{
2666 struct rule *rp;
2667 int i;
2668 rp = cfp->rp;
2669 fprintf(fp,"%s ::=",rp->lhs->name);
2670 for(i=0; i<=rp->nrhs; i++){
2671 if( i==cfp->dot ) fprintf(fp," *");
2672 if( i==rp->nrhs ) break;
2673 fprintf(fp," %s",rp->rhs[i]->name);
2674 }
2675}
2676
2677/* #define TEST */
2678#ifdef TEST
2679/* Print a set */
2680PRIVATE void SetPrint(out,set,lemp)
2681FILE *out;
2682char *set;
2683struct lemon *lemp;
2684{
2685 int i;
2686 char *spacer;
2687 spacer = "";
2688 fprintf(out,"%12s[","");
2689 for(i=0; i<lemp->nterminal; i++){
2690 if( SetFind(set,i) ){
2691 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2692 spacer = " ";
2693 }
2694 }
2695 fprintf(out,"]\n");
2696}
2697
2698/* Print a plink chain */
2699PRIVATE void PlinkPrint(out,plp,tag)
2700FILE *out;
2701struct plink *plp;
2702char *tag;
2703{
2704 while( plp ){
drhada354d2005-11-05 15:03:59 +00002705 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002706 ConfigPrint(out,plp->cfp);
2707 fprintf(out,"\n");
2708 plp = plp->next;
2709 }
2710}
2711#endif
2712
2713/* Print an action to the given file descriptor. Return FALSE if
2714** nothing was actually printed.
2715*/
2716int PrintAction(struct action *ap, FILE *fp, int indent){
2717 int result = 1;
2718 switch( ap->type ){
2719 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002720 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002721 break;
2722 case REDUCE:
2723 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2724 break;
2725 case ACCEPT:
2726 fprintf(fp,"%*s accept",indent,ap->sp->name);
2727 break;
2728 case ERROR:
2729 fprintf(fp,"%*s error",indent,ap->sp->name);
2730 break;
2731 case CONFLICT:
2732 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2733 indent,ap->sp->name,ap->x.rp->index);
2734 break;
2735 case SH_RESOLVED:
2736 case RD_RESOLVED:
2737 case NOT_USED:
2738 result = 0;
2739 break;
2740 }
2741 return result;
2742}
2743
2744/* Generate the "y.output" log file */
2745void ReportOutput(lemp)
2746struct lemon *lemp;
2747{
2748 int i;
2749 struct state *stp;
2750 struct config *cfp;
2751 struct action *ap;
2752 FILE *fp;
2753
drh2aa6ca42004-09-10 00:14:04 +00002754 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002755 if( fp==0 ) return;
2756 fprintf(fp," \b");
2757 for(i=0; i<lemp->nstate; i++){
2758 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002759 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002760 if( lemp->basisflag ) cfp=stp->bp;
2761 else cfp=stp->cfp;
2762 while( cfp ){
2763 char buf[20];
2764 if( cfp->dot==cfp->rp->nrhs ){
2765 sprintf(buf,"(%d)",cfp->rp->index);
2766 fprintf(fp," %5s ",buf);
2767 }else{
2768 fprintf(fp," ");
2769 }
2770 ConfigPrint(fp,cfp);
2771 fprintf(fp,"\n");
2772#ifdef TEST
2773 SetPrint(fp,cfp->fws,lemp);
2774 PlinkPrint(fp,cfp->fplp,"To ");
2775 PlinkPrint(fp,cfp->bplp,"From");
2776#endif
2777 if( lemp->basisflag ) cfp=cfp->bp;
2778 else cfp=cfp->next;
2779 }
2780 fprintf(fp,"\n");
2781 for(ap=stp->ap; ap; ap=ap->next){
2782 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2783 }
2784 fprintf(fp,"\n");
2785 }
2786 fclose(fp);
2787 return;
2788}
2789
2790/* Search for the file "name" which is in the same directory as
2791** the exacutable */
2792PRIVATE char *pathsearch(argv0,name,modemask)
2793char *argv0;
2794char *name;
2795int modemask;
2796{
2797 char *pathlist;
2798 char *path,*cp;
2799 char c;
2800 extern int access();
2801
2802#ifdef __WIN32__
2803 cp = strrchr(argv0,'\\');
2804#else
2805 cp = strrchr(argv0,'/');
2806#endif
2807 if( cp ){
2808 c = *cp;
2809 *cp = 0;
2810 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2811 if( path ) sprintf(path,"%s/%s",argv0,name);
2812 *cp = c;
2813 }else{
2814 extern char *getenv();
2815 pathlist = getenv("PATH");
2816 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2817 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2818 if( path!=0 ){
2819 while( *pathlist ){
2820 cp = strchr(pathlist,':');
2821 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2822 c = *cp;
2823 *cp = 0;
2824 sprintf(path,"%s/%s",pathlist,name);
2825 *cp = c;
2826 if( c==0 ) pathlist = "";
2827 else pathlist = &cp[1];
2828 if( access(path,modemask)==0 ) break;
2829 }
2830 }
2831 }
2832 return path;
2833}
2834
2835/* Given an action, compute the integer value for that action
2836** which is to be put in the action table of the generated machine.
2837** Return negative if no action should be generated.
2838*/
2839PRIVATE int compute_action(lemp,ap)
2840struct lemon *lemp;
2841struct action *ap;
2842{
2843 int act;
2844 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00002845 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00002846 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2847 case ERROR: act = lemp->nstate + lemp->nrule; break;
2848 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
2849 default: act = -1; break;
2850 }
2851 return act;
2852}
2853
2854#define LINESIZE 1000
2855/* The next cluster of routines are for reading the template file
2856** and writing the results to the generated parser */
2857/* The first function transfers data from "in" to "out" until
2858** a line is seen which begins with "%%". The line number is
2859** tracked.
2860**
2861** if name!=0, then any word that begin with "Parse" is changed to
2862** begin with *name instead.
2863*/
2864PRIVATE void tplt_xfer(name,in,out,lineno)
2865char *name;
2866FILE *in;
2867FILE *out;
2868int *lineno;
2869{
2870 int i, iStart;
2871 char line[LINESIZE];
2872 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
2873 (*lineno)++;
2874 iStart = 0;
2875 if( name ){
2876 for(i=0; line[i]; i++){
2877 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
2878 && (i==0 || !isalpha(line[i-1]))
2879 ){
2880 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
2881 fprintf(out,"%s",name);
2882 i += 4;
2883 iStart = i+1;
2884 }
2885 }
2886 }
2887 fprintf(out,"%s",&line[iStart]);
2888 }
2889}
2890
2891/* The next function finds the template file and opens it, returning
2892** a pointer to the opened file. */
2893PRIVATE FILE *tplt_open(lemp)
2894struct lemon *lemp;
2895{
2896 static char templatename[] = "lempar.c";
2897 char buf[1000];
2898 FILE *in;
2899 char *tpltname;
2900 char *cp;
2901
2902 cp = strrchr(lemp->filename,'.');
2903 if( cp ){
drh8b582012003-10-21 13:16:03 +00002904 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00002905 }else{
2906 sprintf(buf,"%s.lt",lemp->filename);
2907 }
2908 if( access(buf,004)==0 ){
2909 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00002910 }else if( access(templatename,004)==0 ){
2911 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00002912 }else{
2913 tpltname = pathsearch(lemp->argv0,templatename,0);
2914 }
2915 if( tpltname==0 ){
2916 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
2917 templatename);
2918 lemp->errorcnt++;
2919 return 0;
2920 }
drh2aa6ca42004-09-10 00:14:04 +00002921 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00002922 if( in==0 ){
2923 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
2924 lemp->errorcnt++;
2925 return 0;
2926 }
2927 return in;
2928}
2929
drhaf805ca2004-09-07 11:28:25 +00002930/* Print a #line directive line to the output file. */
2931PRIVATE void tplt_linedir(out,lineno,filename)
2932FILE *out;
2933int lineno;
2934char *filename;
2935{
2936 fprintf(out,"#line %d \"",lineno);
2937 while( *filename ){
2938 if( *filename == '\\' ) putc('\\',out);
2939 putc(*filename,out);
2940 filename++;
2941 }
2942 fprintf(out,"\"\n");
2943}
2944
drh75897232000-05-29 14:26:00 +00002945/* Print a string to the file and keep the linenumber up to date */
2946PRIVATE void tplt_print(out,lemp,str,strln,lineno)
2947FILE *out;
2948struct lemon *lemp;
2949char *str;
2950int strln;
2951int *lineno;
2952{
2953 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00002954 tplt_linedir(out,strln,lemp->filename);
2955 (*lineno)++;
drh75897232000-05-29 14:26:00 +00002956 while( *str ){
2957 if( *str=='\n' ) (*lineno)++;
2958 putc(*str,out);
2959 str++;
2960 }
drh9db55df2004-09-09 14:01:21 +00002961 if( str[-1]!='\n' ){
2962 putc('\n',out);
2963 (*lineno)++;
2964 }
drhaf805ca2004-09-07 11:28:25 +00002965 tplt_linedir(out,*lineno+2,lemp->outname);
2966 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00002967 return;
2968}
2969
2970/*
2971** The following routine emits code for the destructor for the
2972** symbol sp
2973*/
2974void emit_destructor_code(out,sp,lemp,lineno)
2975FILE *out;
2976struct symbol *sp;
2977struct lemon *lemp;
2978int *lineno;
2979{
drhcc83b6e2004-04-23 23:38:42 +00002980 char *cp = 0;
drh75897232000-05-29 14:26:00 +00002981
2982 int linecnt = 0;
2983 if( sp->type==TERMINAL ){
2984 cp = lemp->tokendest;
2985 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00002986 tplt_linedir(out,lemp->tokendestln,lemp->filename);
2987 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00002988 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00002989 cp = sp->destructor;
drhaf805ca2004-09-07 11:28:25 +00002990 tplt_linedir(out,sp->destructorln,lemp->filename);
2991 fprintf(out,"{");
drh960e8c62001-04-03 16:53:21 +00002992 }else if( lemp->vardest ){
2993 cp = lemp->vardest;
2994 if( cp==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00002995 tplt_linedir(out,lemp->vardestln,lemp->filename);
2996 fprintf(out,"{");
drhcc83b6e2004-04-23 23:38:42 +00002997 }else{
2998 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00002999 }
3000 for(; *cp; cp++){
3001 if( *cp=='$' && cp[1]=='$' ){
3002 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3003 cp++;
3004 continue;
3005 }
3006 if( *cp=='\n' ) linecnt++;
3007 fputc(*cp,out);
3008 }
3009 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003010 fprintf(out,"}\n");
3011 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003012 return;
3013}
3014
3015/*
drh960e8c62001-04-03 16:53:21 +00003016** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003017*/
3018int has_destructor(sp, lemp)
3019struct symbol *sp;
3020struct lemon *lemp;
3021{
3022 int ret;
3023 if( sp->type==TERMINAL ){
3024 ret = lemp->tokendest!=0;
3025 }else{
drh960e8c62001-04-03 16:53:21 +00003026 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003027 }
3028 return ret;
3029}
3030
drh0bb132b2004-07-20 14:06:51 +00003031/*
3032** Append text to a dynamically allocated string. If zText is 0 then
3033** reset the string to be empty again. Always return the complete text
3034** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003035**
3036** n bytes of zText are stored. If n==0 then all of zText up to the first
3037** \000 terminator is stored. zText can contain up to two instances of
3038** %d. The values of p1 and p2 are written into the first and second
3039** %d.
3040**
3041** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003042*/
3043PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3044 static char *z = 0;
3045 static int alloced = 0;
3046 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003047 int c;
drh0bb132b2004-07-20 14:06:51 +00003048 char zInt[40];
3049
3050 if( zText==0 ){
3051 used = 0;
3052 return z;
3053 }
drh7ac25c72004-08-19 15:12:26 +00003054 if( n<=0 ){
3055 if( n<0 ){
3056 used += n;
3057 assert( used>=0 );
3058 }
3059 n = strlen(zText);
3060 }
drh0bb132b2004-07-20 14:06:51 +00003061 if( n+sizeof(zInt)*2+used >= alloced ){
3062 alloced = n + sizeof(zInt)*2 + used + 200;
3063 z = realloc(z, alloced);
3064 }
3065 if( z==0 ) return "";
3066 while( n-- > 0 ){
3067 c = *(zText++);
3068 if( c=='%' && zText[0]=='d' ){
3069 sprintf(zInt, "%d", p1);
3070 p1 = p2;
3071 strcpy(&z[used], zInt);
3072 used += strlen(&z[used]);
3073 zText++;
3074 n--;
3075 }else{
3076 z[used++] = c;
3077 }
3078 }
3079 z[used] = 0;
3080 return z;
3081}
3082
3083/*
3084** zCode is a string that is the action associated with a rule. Expand
3085** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003086** stack.
drh0bb132b2004-07-20 14:06:51 +00003087*/
drhaf805ca2004-09-07 11:28:25 +00003088PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003089 char *cp, *xp;
3090 int i;
3091 char lhsused = 0; /* True if the LHS element has been used */
3092 char used[MAXRHS]; /* True for each RHS element which is used */
3093
3094 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3095 lhsused = 0;
3096
3097 append_str(0,0,0,0);
3098 for(cp=rp->code; *cp; cp++){
3099 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3100 char saved;
3101 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3102 saved = *xp;
3103 *xp = 0;
3104 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003105 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003106 cp = xp;
3107 lhsused = 1;
3108 }else{
3109 for(i=0; i<rp->nrhs; i++){
3110 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003111 if( cp!=rp->code && cp[-1]=='@' ){
3112 /* If the argument is of the form @X then substituted
3113 ** the token number of X, not the value of X */
3114 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3115 }else{
3116 append_str("yymsp[%d].minor.yy%d",0,
3117 i-rp->nrhs+1,rp->rhs[i]->dtnum);
3118 }
drh0bb132b2004-07-20 14:06:51 +00003119 cp = xp;
3120 used[i] = 1;
3121 break;
3122 }
3123 }
3124 }
3125 *xp = saved;
3126 }
3127 append_str(cp, 1, 0, 0);
3128 } /* End loop */
3129
3130 /* Check to make sure the LHS has been used */
3131 if( rp->lhsalias && !lhsused ){
3132 ErrorMsg(lemp->filename,rp->ruleline,
3133 "Label \"%s\" for \"%s(%s)\" is never used.",
3134 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3135 lemp->errorcnt++;
3136 }
3137
3138 /* Generate destructor code for RHS symbols which are not used in the
3139 ** reduce code */
3140 for(i=0; i<rp->nrhs; i++){
3141 if( rp->rhsalias[i] && !used[i] ){
3142 ErrorMsg(lemp->filename,rp->ruleline,
3143 "Label %s for \"%s(%s)\" is never used.",
3144 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3145 lemp->errorcnt++;
3146 }else if( rp->rhsalias[i]==0 ){
3147 if( has_destructor(rp->rhs[i],lemp) ){
drh7ac25c72004-08-19 15:12:26 +00003148 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003149 rp->rhs[i]->index,i-rp->nrhs+1);
3150 }else{
3151 /* No destructor defined for this term */
3152 }
3153 }
3154 }
3155 cp = append_str(0,0,0,0);
3156 rp->code = Strsafe(cp);
3157}
3158
drh75897232000-05-29 14:26:00 +00003159/*
3160** Generate code which executes when the rule "rp" is reduced. Write
3161** the code to "out". Make sure lineno stays up-to-date.
3162*/
3163PRIVATE void emit_code(out,rp,lemp,lineno)
3164FILE *out;
3165struct rule *rp;
3166struct lemon *lemp;
3167int *lineno;
3168{
drh0bb132b2004-07-20 14:06:51 +00003169 char *cp;
drh75897232000-05-29 14:26:00 +00003170 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003171
3172 /* Generate code to do the reduce action */
3173 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003174 tplt_linedir(out,rp->line,lemp->filename);
3175 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003176 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003177 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003178 } /* End loop */
3179 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003180 fprintf(out,"}\n");
3181 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003182 } /* End if( rp->code ) */
3183
drh75897232000-05-29 14:26:00 +00003184 return;
3185}
3186
3187/*
3188** Print the definition of the union used for the parser's data stack.
3189** This union contains fields for every possible data type for tokens
3190** and nonterminals. In the process of computing and printing this
3191** union, also set the ".dtnum" field of every terminal and nonterminal
3192** symbol.
3193*/
3194void print_stack_union(out,lemp,plineno,mhflag)
3195FILE *out; /* The output stream */
3196struct lemon *lemp; /* The main info structure for this parser */
3197int *plineno; /* Pointer to the line number */
3198int mhflag; /* True if generating makeheaders output */
3199{
3200 int lineno = *plineno; /* The line number of the output */
3201 char **types; /* A hash table of datatypes */
3202 int arraysize; /* Size of the "types" array */
3203 int maxdtlength; /* Maximum length of any ".datatype" field. */
3204 char *stddt; /* Standardized name for a datatype */
3205 int i,j; /* Loop counters */
3206 int hash; /* For hashing the name of a type */
3207 char *name; /* Name of the parser */
3208
3209 /* Allocate and initialize types[] and allocate stddt[] */
3210 arraysize = lemp->nsymbol * 2;
3211 types = (char**)malloc( arraysize * sizeof(char*) );
3212 for(i=0; i<arraysize; i++) types[i] = 0;
3213 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003214 if( lemp->vartype ){
3215 maxdtlength = strlen(lemp->vartype);
3216 }
drh75897232000-05-29 14:26:00 +00003217 for(i=0; i<lemp->nsymbol; i++){
3218 int len;
3219 struct symbol *sp = lemp->symbols[i];
3220 if( sp->datatype==0 ) continue;
3221 len = strlen(sp->datatype);
3222 if( len>maxdtlength ) maxdtlength = len;
3223 }
3224 stddt = (char*)malloc( maxdtlength*2 + 1 );
3225 if( types==0 || stddt==0 ){
3226 fprintf(stderr,"Out of memory.\n");
3227 exit(1);
3228 }
3229
3230 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3231 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003232 ** used for terminal symbols. If there is no %default_type defined then
3233 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3234 ** a datatype using the %type directive.
3235 */
drh75897232000-05-29 14:26:00 +00003236 for(i=0; i<lemp->nsymbol; i++){
3237 struct symbol *sp = lemp->symbols[i];
3238 char *cp;
3239 if( sp==lemp->errsym ){
3240 sp->dtnum = arraysize+1;
3241 continue;
3242 }
drh960e8c62001-04-03 16:53:21 +00003243 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003244 sp->dtnum = 0;
3245 continue;
3246 }
3247 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003248 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003249 j = 0;
3250 while( isspace(*cp) ) cp++;
3251 while( *cp ) stddt[j++] = *cp++;
3252 while( j>0 && isspace(stddt[j-1]) ) j--;
3253 stddt[j] = 0;
3254 hash = 0;
3255 for(j=0; stddt[j]; j++){
3256 hash = hash*53 + stddt[j];
3257 }
drh3b2129c2003-05-13 00:34:21 +00003258 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003259 while( types[hash] ){
3260 if( strcmp(types[hash],stddt)==0 ){
3261 sp->dtnum = hash + 1;
3262 break;
3263 }
3264 hash++;
3265 if( hash>=arraysize ) hash = 0;
3266 }
3267 if( types[hash]==0 ){
3268 sp->dtnum = hash + 1;
3269 types[hash] = (char*)malloc( strlen(stddt)+1 );
3270 if( types[hash]==0 ){
3271 fprintf(stderr,"Out of memory.\n");
3272 exit(1);
3273 }
3274 strcpy(types[hash],stddt);
3275 }
3276 }
3277
3278 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3279 name = lemp->name ? lemp->name : "Parse";
3280 lineno = *plineno;
3281 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3282 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3283 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3284 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3285 fprintf(out,"typedef union {\n"); lineno++;
3286 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3287 for(i=0; i<arraysize; i++){
3288 if( types[i]==0 ) continue;
3289 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3290 free(types[i]);
3291 }
3292 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3293 free(stddt);
3294 free(types);
3295 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3296 *plineno = lineno;
3297}
3298
drhb29b0a52002-02-23 19:39:46 +00003299/*
3300** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003301** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003302*/
drh8b582012003-10-21 13:16:03 +00003303static const char *minimum_size_type(int lwr, int upr){
3304 if( lwr>=0 ){
3305 if( upr<=255 ){
3306 return "unsigned char";
3307 }else if( upr<65535 ){
3308 return "unsigned short int";
3309 }else{
3310 return "unsigned int";
3311 }
3312 }else if( lwr>=-127 && upr<=127 ){
3313 return "signed char";
3314 }else if( lwr>=-32767 && upr<32767 ){
3315 return "short";
drhb29b0a52002-02-23 19:39:46 +00003316 }else{
drh8b582012003-10-21 13:16:03 +00003317 return "int";
drhb29b0a52002-02-23 19:39:46 +00003318 }
3319}
3320
drhfdbf9282003-10-21 16:34:41 +00003321/*
3322** Each state contains a set of token transaction and a set of
3323** nonterminal transactions. Each of these sets makes an instance
3324** of the following structure. An array of these structures is used
3325** to order the creation of entries in the yy_action[] table.
3326*/
3327struct axset {
3328 struct state *stp; /* A pointer to a state */
3329 int isTkn; /* True to use tokens. False for non-terminals */
3330 int nAction; /* Number of actions */
3331};
3332
3333/*
3334** Compare to axset structures for sorting purposes
3335*/
3336static int axset_compare(const void *a, const void *b){
3337 struct axset *p1 = (struct axset*)a;
3338 struct axset *p2 = (struct axset*)b;
3339 return p2->nAction - p1->nAction;
3340}
3341
drh75897232000-05-29 14:26:00 +00003342/* Generate C source code for the parser */
3343void ReportTable(lemp, mhflag)
3344struct lemon *lemp;
3345int mhflag; /* Output in makeheaders format if true */
3346{
3347 FILE *out, *in;
3348 char line[LINESIZE];
3349 int lineno;
3350 struct state *stp;
3351 struct action *ap;
3352 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003353 struct acttab *pActtab;
3354 int i, j, n;
drh75897232000-05-29 14:26:00 +00003355 char *name;
drh8b582012003-10-21 13:16:03 +00003356 int mnTknOfst, mxTknOfst;
3357 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003358 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003359
3360 in = tplt_open(lemp);
3361 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003362 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003363 if( out==0 ){
3364 fclose(in);
3365 return;
3366 }
3367 lineno = 1;
3368 tplt_xfer(lemp->name,in,out,&lineno);
3369
3370 /* Generate the include code, if any */
3371 tplt_print(out,lemp,lemp->include,lemp->includeln,&lineno);
3372 if( mhflag ){
3373 char *name = file_makename(lemp, ".h");
3374 fprintf(out,"#include \"%s\"\n", name); lineno++;
3375 free(name);
3376 }
3377 tplt_xfer(lemp->name,in,out,&lineno);
3378
3379 /* Generate #defines for all tokens */
3380 if( mhflag ){
3381 char *prefix;
3382 fprintf(out,"#if INTERFACE\n"); lineno++;
3383 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3384 else prefix = "";
3385 for(i=1; i<lemp->nterminal; i++){
3386 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3387 lineno++;
3388 }
3389 fprintf(out,"#endif\n"); lineno++;
3390 }
3391 tplt_xfer(lemp->name,in,out,&lineno);
3392
3393 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003394 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003395 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003396 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3397 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003398 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003399 print_stack_union(out,lemp,&lineno,mhflag);
3400 if( lemp->stacksize ){
3401 if( atoi(lemp->stacksize)<=0 ){
3402 ErrorMsg(lemp->filename,0,
3403"Illegal stack size: [%s]. The stack size should be an integer constant.",
3404 lemp->stacksize);
3405 lemp->errorcnt++;
3406 lemp->stacksize = "100";
3407 }
3408 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3409 }else{
3410 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3411 }
3412 if( mhflag ){
3413 fprintf(out,"#if INTERFACE\n"); lineno++;
3414 }
3415 name = lemp->name ? lemp->name : "Parse";
3416 if( lemp->arg && lemp->arg[0] ){
3417 int i;
3418 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003419 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3420 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003421 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3422 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3423 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3424 name,lemp->arg,&lemp->arg[i]); lineno++;
3425 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3426 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003427 }else{
drh1f245e42002-03-11 13:55:50 +00003428 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3429 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3430 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3431 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003432 }
3433 if( mhflag ){
3434 fprintf(out,"#endif\n"); lineno++;
3435 }
3436 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3437 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
3438 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3439 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drh0bd1f4e2002-06-06 18:54:39 +00003440 if( lemp->has_fallback ){
3441 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3442 }
drh75897232000-05-29 14:26:00 +00003443 tplt_xfer(lemp->name,in,out,&lineno);
3444
drh8b582012003-10-21 13:16:03 +00003445 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003446 **
drh8b582012003-10-21 13:16:03 +00003447 ** yy_action[] A single table containing all actions.
3448 ** yy_lookahead[] A table containing the lookahead for each entry in
3449 ** yy_action. Used to detect hash collisions.
3450 ** yy_shift_ofst[] For each state, the offset into yy_action for
3451 ** shifting terminals.
3452 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3453 ** shifting non-terminals after a reduce.
3454 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003455 */
drh75897232000-05-29 14:26:00 +00003456
drh8b582012003-10-21 13:16:03 +00003457 /* Compute the actions on all states and count them up */
drhfdbf9282003-10-21 16:34:41 +00003458 ax = malloc( sizeof(ax[0])*lemp->nstate*2 );
3459 if( ax==0 ){
3460 fprintf(stderr,"malloc failed\n");
3461 exit(1);
3462 }
drh75897232000-05-29 14:26:00 +00003463 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003464 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003465 ax[i*2].stp = stp;
3466 ax[i*2].isTkn = 1;
3467 ax[i*2].nAction = stp->nTknAct;
3468 ax[i*2+1].stp = stp;
3469 ax[i*2+1].isTkn = 0;
3470 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003471 }
drh8b582012003-10-21 13:16:03 +00003472 mxTknOfst = mnTknOfst = 0;
3473 mxNtOfst = mnNtOfst = 0;
3474
drhfdbf9282003-10-21 16:34:41 +00003475 /* Compute the action table. In order to try to keep the size of the
3476 ** action table to a minimum, the heuristic of placing the largest action
3477 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003478 */
drhfdbf9282003-10-21 16:34:41 +00003479 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003480 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003481 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3482 stp = ax[i].stp;
3483 if( ax[i].isTkn ){
3484 for(ap=stp->ap; ap; ap=ap->next){
3485 int action;
3486 if( ap->sp->index>=lemp->nterminal ) continue;
3487 action = compute_action(lemp, ap);
3488 if( action<0 ) continue;
3489 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003490 }
drhfdbf9282003-10-21 16:34:41 +00003491 stp->iTknOfst = acttab_insert(pActtab);
3492 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3493 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3494 }else{
3495 for(ap=stp->ap; ap; ap=ap->next){
3496 int action;
3497 if( ap->sp->index<lemp->nterminal ) continue;
3498 if( ap->sp->index==lemp->nsymbol ) continue;
3499 action = compute_action(lemp, ap);
3500 if( action<0 ) continue;
3501 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003502 }
drhfdbf9282003-10-21 16:34:41 +00003503 stp->iNtOfst = acttab_insert(pActtab);
3504 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3505 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003506 }
3507 }
drhfdbf9282003-10-21 16:34:41 +00003508 free(ax);
drh8b582012003-10-21 13:16:03 +00003509
3510 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003511 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003512 n = acttab_size(pActtab);
3513 for(i=j=0; i<n; i++){
3514 int action = acttab_yyaction(pActtab, i);
3515 if( action<0 ) action = lemp->nsymbol + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003516 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003517 fprintf(out, " %4d,", action);
3518 if( j==9 || i==n-1 ){
3519 fprintf(out, "\n"); lineno++;
3520 j = 0;
3521 }else{
3522 j++;
3523 }
3524 }
3525 fprintf(out, "};\n"); lineno++;
3526
3527 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003528 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003529 for(i=j=0; i<n; i++){
3530 int la = acttab_yylookahead(pActtab, i);
3531 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003532 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003533 fprintf(out, " %4d,", la);
3534 if( j==9 || i==n-1 ){
3535 fprintf(out, "\n"); lineno++;
3536 j = 0;
3537 }else{
3538 j++;
3539 }
3540 }
3541 fprintf(out, "};\n"); lineno++;
3542
3543 /* Output the yy_shift_ofst[] table */
3544 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003545 n = lemp->nstate;
3546 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3547 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003548 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003549 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003550 for(i=j=0; i<n; i++){
3551 int ofst;
3552 stp = lemp->sorted[i];
3553 ofst = stp->iTknOfst;
3554 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003555 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003556 fprintf(out, " %4d,", ofst);
3557 if( j==9 || i==n-1 ){
3558 fprintf(out, "\n"); lineno++;
3559 j = 0;
3560 }else{
3561 j++;
3562 }
3563 }
3564 fprintf(out, "};\n"); lineno++;
3565
3566 /* Output the yy_reduce_ofst[] table */
3567 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003568 n = lemp->nstate;
3569 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3570 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003571 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003572 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003573 for(i=j=0; i<n; i++){
3574 int ofst;
3575 stp = lemp->sorted[i];
3576 ofst = stp->iNtOfst;
3577 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003578 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003579 fprintf(out, " %4d,", ofst);
3580 if( j==9 || i==n-1 ){
3581 fprintf(out, "\n"); lineno++;
3582 j = 0;
3583 }else{
3584 j++;
3585 }
3586 }
3587 fprintf(out, "};\n"); lineno++;
3588
3589 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003590 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003591 n = lemp->nstate;
3592 for(i=j=0; i<n; i++){
3593 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003594 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003595 fprintf(out, " %4d,", stp->iDflt);
3596 if( j==9 || i==n-1 ){
3597 fprintf(out, "\n"); lineno++;
3598 j = 0;
3599 }else{
3600 j++;
3601 }
3602 }
3603 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003604 tplt_xfer(lemp->name,in,out,&lineno);
3605
drh0bd1f4e2002-06-06 18:54:39 +00003606 /* Generate the table of fallback tokens.
3607 */
3608 if( lemp->has_fallback ){
3609 for(i=0; i<lemp->nterminal; i++){
3610 struct symbol *p = lemp->symbols[i];
3611 if( p->fallback==0 ){
3612 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3613 }else{
3614 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3615 p->name, p->fallback->name);
3616 }
3617 lineno++;
3618 }
3619 }
3620 tplt_xfer(lemp->name, in, out, &lineno);
3621
3622 /* Generate a table containing the symbolic name of every symbol
3623 */
drh75897232000-05-29 14:26:00 +00003624 for(i=0; i<lemp->nsymbol; i++){
3625 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3626 fprintf(out," %-15s",line);
3627 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3628 }
3629 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3630 tplt_xfer(lemp->name,in,out,&lineno);
3631
drh0bd1f4e2002-06-06 18:54:39 +00003632 /* Generate a table containing a text string that describes every
3633 ** rule in the rule set of the grammer. This information is used
3634 ** when tracing REDUCE actions.
3635 */
3636 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3637 assert( rp->index==i );
3638 fprintf(out," /* %3d */ \"%s ::=", i, rp->lhs->name);
3639 for(j=0; j<rp->nrhs; j++) fprintf(out," %s",rp->rhs[j]->name);
3640 fprintf(out,"\",\n"); lineno++;
3641 }
3642 tplt_xfer(lemp->name,in,out,&lineno);
3643
drh75897232000-05-29 14:26:00 +00003644 /* Generate code which executes every time a symbol is popped from
3645 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003646 ** (In other words, generate the %destructor actions)
3647 */
drh75897232000-05-29 14:26:00 +00003648 if( lemp->tokendest ){
3649 for(i=0; i<lemp->nsymbol; i++){
3650 struct symbol *sp = lemp->symbols[i];
3651 if( sp==0 || sp->type!=TERMINAL ) continue;
3652 fprintf(out," case %d:\n",sp->index); lineno++;
3653 }
3654 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3655 if( i<lemp->nsymbol ){
3656 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3657 fprintf(out," break;\n"); lineno++;
3658 }
3659 }
drh8d659732005-01-13 23:54:06 +00003660 if( lemp->vardest ){
3661 struct symbol *dflt_sp = 0;
3662 for(i=0; i<lemp->nsymbol; i++){
3663 struct symbol *sp = lemp->symbols[i];
3664 if( sp==0 || sp->type==TERMINAL ||
3665 sp->index<=0 || sp->destructor!=0 ) continue;
3666 fprintf(out," case %d:\n",sp->index); lineno++;
3667 dflt_sp = sp;
3668 }
3669 if( dflt_sp!=0 ){
3670 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3671 fprintf(out," break;\n"); lineno++;
3672 }
3673 }
drh75897232000-05-29 14:26:00 +00003674 for(i=0; i<lemp->nsymbol; i++){
3675 struct symbol *sp = lemp->symbols[i];
3676 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
3677 fprintf(out," case %d:\n",sp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003678
3679 /* Combine duplicate destructors into a single case */
3680 for(j=i+1; j<lemp->nsymbol; j++){
3681 struct symbol *sp2 = lemp->symbols[j];
3682 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3683 && sp2->dtnum==sp->dtnum
3684 && strcmp(sp->destructor,sp2->destructor)==0 ){
3685 fprintf(out," case %d:\n",sp2->index); lineno++;
3686 sp2->destructor = 0;
3687 }
3688 }
3689
drh75897232000-05-29 14:26:00 +00003690 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3691 fprintf(out," break;\n"); lineno++;
3692 }
drh75897232000-05-29 14:26:00 +00003693 tplt_xfer(lemp->name,in,out,&lineno);
3694
3695 /* Generate code which executes whenever the parser stack overflows */
3696 tplt_print(out,lemp,lemp->overflow,lemp->overflowln,&lineno);
3697 tplt_xfer(lemp->name,in,out,&lineno);
3698
3699 /* Generate the table of rule information
3700 **
3701 ** Note: This code depends on the fact that rules are number
3702 ** sequentually beginning with 0.
3703 */
3704 for(rp=lemp->rule; rp; rp=rp->next){
3705 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3706 }
3707 tplt_xfer(lemp->name,in,out,&lineno);
3708
3709 /* Generate code which execution during each REDUCE action */
3710 for(rp=lemp->rule; rp; rp=rp->next){
drh0bb132b2004-07-20 14:06:51 +00003711 if( rp->code ) translate_code(lemp, rp);
3712 }
3713 for(rp=lemp->rule; rp; rp=rp->next){
3714 struct rule *rp2;
3715 if( rp->code==0 ) continue;
drh75897232000-05-29 14:26:00 +00003716 fprintf(out," case %d:\n",rp->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003717 for(rp2=rp->next; rp2; rp2=rp2->next){
3718 if( rp2->code==rp->code ){
3719 fprintf(out," case %d:\n",rp2->index); lineno++;
3720 rp2->code = 0;
3721 }
3722 }
drh75897232000-05-29 14:26:00 +00003723 emit_code(out,rp,lemp,&lineno);
3724 fprintf(out," break;\n"); lineno++;
3725 }
3726 tplt_xfer(lemp->name,in,out,&lineno);
3727
3728 /* Generate code which executes if a parse fails */
3729 tplt_print(out,lemp,lemp->failure,lemp->failureln,&lineno);
3730 tplt_xfer(lemp->name,in,out,&lineno);
3731
3732 /* Generate code which executes when a syntax error occurs */
3733 tplt_print(out,lemp,lemp->error,lemp->errorln,&lineno);
3734 tplt_xfer(lemp->name,in,out,&lineno);
3735
3736 /* Generate code which executes when the parser accepts its input */
3737 tplt_print(out,lemp,lemp->accept,lemp->acceptln,&lineno);
3738 tplt_xfer(lemp->name,in,out,&lineno);
3739
3740 /* Append any addition code the user desires */
3741 tplt_print(out,lemp,lemp->extracode,lemp->extracodeln,&lineno);
3742
3743 fclose(in);
3744 fclose(out);
3745 return;
3746}
3747
3748/* Generate a header file for the parser */
3749void ReportHeader(lemp)
3750struct lemon *lemp;
3751{
3752 FILE *out, *in;
3753 char *prefix;
3754 char line[LINESIZE];
3755 char pattern[LINESIZE];
3756 int i;
3757
3758 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3759 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003760 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003761 if( in ){
3762 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3763 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3764 if( strcmp(line,pattern) ) break;
3765 }
3766 fclose(in);
3767 if( i==lemp->nterminal ){
3768 /* No change in the file. Don't rewrite it. */
3769 return;
3770 }
3771 }
drh2aa6ca42004-09-10 00:14:04 +00003772 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003773 if( out ){
3774 for(i=1; i<lemp->nterminal; i++){
3775 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3776 }
3777 fclose(out);
3778 }
3779 return;
3780}
3781
3782/* Reduce the size of the action tables, if possible, by making use
3783** of defaults.
3784**
drhb59499c2002-02-23 18:45:13 +00003785** In this version, we take the most frequent REDUCE action and make
drhada354d2005-11-05 15:03:59 +00003786** it the default.
drh75897232000-05-29 14:26:00 +00003787*/
3788void CompressTables(lemp)
3789struct lemon *lemp;
3790{
3791 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003792 struct action *ap, *ap2;
3793 struct rule *rp, *rp2, *rbest;
3794 int nbest, n;
drh75897232000-05-29 14:26:00 +00003795 int i;
drh75897232000-05-29 14:26:00 +00003796
3797 for(i=0; i<lemp->nstate; i++){
3798 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003799 nbest = 0;
3800 rbest = 0;
drh75897232000-05-29 14:26:00 +00003801
drhb59499c2002-02-23 18:45:13 +00003802 for(ap=stp->ap; ap; ap=ap->next){
3803 if( ap->type!=REDUCE ) continue;
3804 rp = ap->x.rp;
3805 if( rp==rbest ) continue;
3806 n = 1;
3807 for(ap2=ap->next; ap2; ap2=ap2->next){
3808 if( ap2->type!=REDUCE ) continue;
3809 rp2 = ap2->x.rp;
3810 if( rp2==rbest ) continue;
3811 if( rp2==rp ) n++;
3812 }
3813 if( n>nbest ){
3814 nbest = n;
3815 rbest = rp;
drh75897232000-05-29 14:26:00 +00003816 }
3817 }
drhb59499c2002-02-23 18:45:13 +00003818
3819 /* Do not make a default if the number of rules to default
drhada354d2005-11-05 15:03:59 +00003820 ** is not at least 1 */
3821 if( nbest<1 ) continue;
drh75897232000-05-29 14:26:00 +00003822
drhb59499c2002-02-23 18:45:13 +00003823
3824 /* Combine matching REDUCE actions into a single default */
3825 for(ap=stp->ap; ap; ap=ap->next){
3826 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
3827 }
drh75897232000-05-29 14:26:00 +00003828 assert( ap );
3829 ap->sp = Symbol_new("{default}");
3830 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00003831 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00003832 }
3833 stp->ap = Action_sort(stp->ap);
3834 }
3835}
drhb59499c2002-02-23 18:45:13 +00003836
drhada354d2005-11-05 15:03:59 +00003837
3838/*
3839** Compare two states for sorting purposes. The smaller state is the
3840** one with the most non-terminal actions. If they have the same number
3841** of non-terminal actions, then the smaller is the one with the most
3842** token actions.
3843*/
3844static int stateResortCompare(const void *a, const void *b){
3845 const struct state *pA = *(const struct state**)a;
3846 const struct state *pB = *(const struct state**)b;
3847 int n;
3848
3849 n = pB->nNtAct - pA->nNtAct;
3850 if( n==0 ){
3851 n = pB->nTknAct - pA->nTknAct;
3852 }
3853 return n;
3854}
3855
3856
3857/*
3858** Renumber and resort states so that states with fewer choices
3859** occur at the end. Except, keep state 0 as the first state.
3860*/
3861void ResortStates(lemp)
3862struct lemon *lemp;
3863{
3864 int i;
3865 struct state *stp;
3866 struct action *ap;
3867
3868 for(i=0; i<lemp->nstate; i++){
3869 stp = lemp->sorted[i];
3870 stp->nTknAct = stp->nNtAct = 0;
3871 stp->iDflt = lemp->nstate + lemp->nrule;
3872 stp->iTknOfst = NO_OFFSET;
3873 stp->iNtOfst = NO_OFFSET;
3874 for(ap=stp->ap; ap; ap=ap->next){
3875 if( compute_action(lemp,ap)>=0 ){
3876 if( ap->sp->index<lemp->nterminal ){
3877 stp->nTknAct++;
3878 }else if( ap->sp->index<lemp->nsymbol ){
3879 stp->nNtAct++;
3880 }else{
3881 stp->iDflt = compute_action(lemp, ap);
3882 }
3883 }
3884 }
3885 }
3886 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
3887 stateResortCompare);
3888 for(i=0; i<lemp->nstate; i++){
3889 lemp->sorted[i]->statenum = i;
3890 }
3891}
3892
3893
drh75897232000-05-29 14:26:00 +00003894/***************** From the file "set.c" ************************************/
3895/*
3896** Set manipulation routines for the LEMON parser generator.
3897*/
3898
3899static int size = 0;
3900
3901/* Set the set size */
3902void SetSize(n)
3903int n;
3904{
3905 size = n+1;
3906}
3907
3908/* Allocate a new set */
3909char *SetNew(){
3910 char *s;
3911 int i;
3912 s = (char*)malloc( size );
3913 if( s==0 ){
3914 extern void memory_error();
3915 memory_error();
3916 }
3917 for(i=0; i<size; i++) s[i] = 0;
3918 return s;
3919}
3920
3921/* Deallocate a set */
3922void SetFree(s)
3923char *s;
3924{
3925 free(s);
3926}
3927
3928/* Add a new element to the set. Return TRUE if the element was added
3929** and FALSE if it was already there. */
3930int SetAdd(s,e)
3931char *s;
3932int e;
3933{
3934 int rv;
3935 rv = s[e];
3936 s[e] = 1;
3937 return !rv;
3938}
3939
3940/* Add every element of s2 to s1. Return TRUE if s1 changes. */
3941int SetUnion(s1,s2)
3942char *s1;
3943char *s2;
3944{
3945 int i, progress;
3946 progress = 0;
3947 for(i=0; i<size; i++){
3948 if( s2[i]==0 ) continue;
3949 if( s1[i]==0 ){
3950 progress = 1;
3951 s1[i] = 1;
3952 }
3953 }
3954 return progress;
3955}
3956/********************** From the file "table.c" ****************************/
3957/*
3958** All code in this file has been automatically generated
3959** from a specification in the file
3960** "table.q"
3961** by the associative array code building program "aagen".
3962** Do not edit this file! Instead, edit the specification
3963** file, then rerun aagen.
3964*/
3965/*
3966** Code for processing tables in the LEMON parser generator.
3967*/
3968
3969PRIVATE int strhash(x)
3970char *x;
3971{
3972 int h = 0;
3973 while( *x) h = h*13 + *(x++);
3974 return h;
3975}
3976
3977/* Works like strdup, sort of. Save a string in malloced memory, but
3978** keep strings in a table so that the same string is not in more
3979** than one place.
3980*/
3981char *Strsafe(y)
3982char *y;
3983{
3984 char *z;
3985
3986 z = Strsafe_find(y);
3987 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
3988 strcpy(z,y);
3989 Strsafe_insert(z);
3990 }
3991 MemoryCheck(z);
3992 return z;
3993}
3994
3995/* There is one instance of the following structure for each
3996** associative array of type "x1".
3997*/
3998struct s_x1 {
3999 int size; /* The number of available slots. */
4000 /* Must be a power of 2 greater than or */
4001 /* equal to 1 */
4002 int count; /* Number of currently slots filled */
4003 struct s_x1node *tbl; /* The data stored here */
4004 struct s_x1node **ht; /* Hash table for lookups */
4005};
4006
4007/* There is one instance of this structure for every data element
4008** in an associative array of type "x1".
4009*/
4010typedef struct s_x1node {
4011 char *data; /* The data */
4012 struct s_x1node *next; /* Next entry with the same hash */
4013 struct s_x1node **from; /* Previous link */
4014} x1node;
4015
4016/* There is only one instance of the array, which is the following */
4017static struct s_x1 *x1a;
4018
4019/* Allocate a new associative array */
4020void Strsafe_init(){
4021 if( x1a ) return;
4022 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4023 if( x1a ){
4024 x1a->size = 1024;
4025 x1a->count = 0;
4026 x1a->tbl = (x1node*)malloc(
4027 (sizeof(x1node) + sizeof(x1node*))*1024 );
4028 if( x1a->tbl==0 ){
4029 free(x1a);
4030 x1a = 0;
4031 }else{
4032 int i;
4033 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4034 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4035 }
4036 }
4037}
4038/* Insert a new record into the array. Return TRUE if successful.
4039** Prior data with the same key is NOT overwritten */
4040int Strsafe_insert(data)
4041char *data;
4042{
4043 x1node *np;
4044 int h;
4045 int ph;
4046
4047 if( x1a==0 ) return 0;
4048 ph = strhash(data);
4049 h = ph & (x1a->size-1);
4050 np = x1a->ht[h];
4051 while( np ){
4052 if( strcmp(np->data,data)==0 ){
4053 /* An existing entry with the same key is found. */
4054 /* Fail because overwrite is not allows. */
4055 return 0;
4056 }
4057 np = np->next;
4058 }
4059 if( x1a->count>=x1a->size ){
4060 /* Need to make the hash table bigger */
4061 int i,size;
4062 struct s_x1 array;
4063 array.size = size = x1a->size*2;
4064 array.count = x1a->count;
4065 array.tbl = (x1node*)malloc(
4066 (sizeof(x1node) + sizeof(x1node*))*size );
4067 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4068 array.ht = (x1node**)&(array.tbl[size]);
4069 for(i=0; i<size; i++) array.ht[i] = 0;
4070 for(i=0; i<x1a->count; i++){
4071 x1node *oldnp, *newnp;
4072 oldnp = &(x1a->tbl[i]);
4073 h = strhash(oldnp->data) & (size-1);
4074 newnp = &(array.tbl[i]);
4075 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4076 newnp->next = array.ht[h];
4077 newnp->data = oldnp->data;
4078 newnp->from = &(array.ht[h]);
4079 array.ht[h] = newnp;
4080 }
4081 free(x1a->tbl);
4082 *x1a = array;
4083 }
4084 /* Insert the new data */
4085 h = ph & (x1a->size-1);
4086 np = &(x1a->tbl[x1a->count++]);
4087 np->data = data;
4088 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4089 np->next = x1a->ht[h];
4090 x1a->ht[h] = np;
4091 np->from = &(x1a->ht[h]);
4092 return 1;
4093}
4094
4095/* Return a pointer to data assigned to the given key. Return NULL
4096** if no such key. */
4097char *Strsafe_find(key)
4098char *key;
4099{
4100 int h;
4101 x1node *np;
4102
4103 if( x1a==0 ) return 0;
4104 h = strhash(key) & (x1a->size-1);
4105 np = x1a->ht[h];
4106 while( np ){
4107 if( strcmp(np->data,key)==0 ) break;
4108 np = np->next;
4109 }
4110 return np ? np->data : 0;
4111}
4112
4113/* Return a pointer to the (terminal or nonterminal) symbol "x".
4114** Create a new symbol if this is the first time "x" has been seen.
4115*/
4116struct symbol *Symbol_new(x)
4117char *x;
4118{
4119 struct symbol *sp;
4120
4121 sp = Symbol_find(x);
4122 if( sp==0 ){
4123 sp = (struct symbol *)malloc( sizeof(struct symbol) );
4124 MemoryCheck(sp);
4125 sp->name = Strsafe(x);
4126 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4127 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004128 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004129 sp->prec = -1;
4130 sp->assoc = UNK;
4131 sp->firstset = 0;
drhb27b83a2002-08-14 23:18:57 +00004132 sp->lambda = B_FALSE;
drh75897232000-05-29 14:26:00 +00004133 sp->destructor = 0;
4134 sp->datatype = 0;
4135 Symbol_insert(sp,sp->name);
4136 }
4137 return sp;
4138}
4139
drh60d31652004-02-22 00:08:04 +00004140/* Compare two symbols for working purposes
4141**
4142** Symbols that begin with upper case letters (terminals or tokens)
4143** must sort before symbols that begin with lower case letters
4144** (non-terminals). Other than that, the order does not matter.
4145**
4146** We find experimentally that leaving the symbols in their original
4147** order (the order they appeared in the grammar file) gives the
4148** smallest parser tables in SQLite.
4149*/
4150int Symbolcmpp(struct symbol **a, struct symbol **b){
4151 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4152 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4153 return i1-i2;
drh75897232000-05-29 14:26:00 +00004154}
4155
4156/* There is one instance of the following structure for each
4157** associative array of type "x2".
4158*/
4159struct s_x2 {
4160 int size; /* The number of available slots. */
4161 /* Must be a power of 2 greater than or */
4162 /* equal to 1 */
4163 int count; /* Number of currently slots filled */
4164 struct s_x2node *tbl; /* The data stored here */
4165 struct s_x2node **ht; /* Hash table for lookups */
4166};
4167
4168/* There is one instance of this structure for every data element
4169** in an associative array of type "x2".
4170*/
4171typedef struct s_x2node {
4172 struct symbol *data; /* The data */
4173 char *key; /* The key */
4174 struct s_x2node *next; /* Next entry with the same hash */
4175 struct s_x2node **from; /* Previous link */
4176} x2node;
4177
4178/* There is only one instance of the array, which is the following */
4179static struct s_x2 *x2a;
4180
4181/* Allocate a new associative array */
4182void Symbol_init(){
4183 if( x2a ) return;
4184 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4185 if( x2a ){
4186 x2a->size = 128;
4187 x2a->count = 0;
4188 x2a->tbl = (x2node*)malloc(
4189 (sizeof(x2node) + sizeof(x2node*))*128 );
4190 if( x2a->tbl==0 ){
4191 free(x2a);
4192 x2a = 0;
4193 }else{
4194 int i;
4195 x2a->ht = (x2node**)&(x2a->tbl[128]);
4196 for(i=0; i<128; i++) x2a->ht[i] = 0;
4197 }
4198 }
4199}
4200/* Insert a new record into the array. Return TRUE if successful.
4201** Prior data with the same key is NOT overwritten */
4202int Symbol_insert(data,key)
4203struct symbol *data;
4204char *key;
4205{
4206 x2node *np;
4207 int h;
4208 int ph;
4209
4210 if( x2a==0 ) return 0;
4211 ph = strhash(key);
4212 h = ph & (x2a->size-1);
4213 np = x2a->ht[h];
4214 while( np ){
4215 if( strcmp(np->key,key)==0 ){
4216 /* An existing entry with the same key is found. */
4217 /* Fail because overwrite is not allows. */
4218 return 0;
4219 }
4220 np = np->next;
4221 }
4222 if( x2a->count>=x2a->size ){
4223 /* Need to make the hash table bigger */
4224 int i,size;
4225 struct s_x2 array;
4226 array.size = size = x2a->size*2;
4227 array.count = x2a->count;
4228 array.tbl = (x2node*)malloc(
4229 (sizeof(x2node) + sizeof(x2node*))*size );
4230 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4231 array.ht = (x2node**)&(array.tbl[size]);
4232 for(i=0; i<size; i++) array.ht[i] = 0;
4233 for(i=0; i<x2a->count; i++){
4234 x2node *oldnp, *newnp;
4235 oldnp = &(x2a->tbl[i]);
4236 h = strhash(oldnp->key) & (size-1);
4237 newnp = &(array.tbl[i]);
4238 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4239 newnp->next = array.ht[h];
4240 newnp->key = oldnp->key;
4241 newnp->data = oldnp->data;
4242 newnp->from = &(array.ht[h]);
4243 array.ht[h] = newnp;
4244 }
4245 free(x2a->tbl);
4246 *x2a = array;
4247 }
4248 /* Insert the new data */
4249 h = ph & (x2a->size-1);
4250 np = &(x2a->tbl[x2a->count++]);
4251 np->key = key;
4252 np->data = data;
4253 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4254 np->next = x2a->ht[h];
4255 x2a->ht[h] = np;
4256 np->from = &(x2a->ht[h]);
4257 return 1;
4258}
4259
4260/* Return a pointer to data assigned to the given key. Return NULL
4261** if no such key. */
4262struct symbol *Symbol_find(key)
4263char *key;
4264{
4265 int h;
4266 x2node *np;
4267
4268 if( x2a==0 ) return 0;
4269 h = strhash(key) & (x2a->size-1);
4270 np = x2a->ht[h];
4271 while( np ){
4272 if( strcmp(np->key,key)==0 ) break;
4273 np = np->next;
4274 }
4275 return np ? np->data : 0;
4276}
4277
4278/* Return the n-th data. Return NULL if n is out of range. */
4279struct symbol *Symbol_Nth(n)
4280int n;
4281{
4282 struct symbol *data;
4283 if( x2a && n>0 && n<=x2a->count ){
4284 data = x2a->tbl[n-1].data;
4285 }else{
4286 data = 0;
4287 }
4288 return data;
4289}
4290
4291/* Return the size of the array */
4292int Symbol_count()
4293{
4294 return x2a ? x2a->count : 0;
4295}
4296
4297/* Return an array of pointers to all data in the table.
4298** The array is obtained from malloc. Return NULL if memory allocation
4299** problems, or if the array is empty. */
4300struct symbol **Symbol_arrayof()
4301{
4302 struct symbol **array;
4303 int i,size;
4304 if( x2a==0 ) return 0;
4305 size = x2a->count;
4306 array = (struct symbol **)malloc( sizeof(struct symbol *)*size );
4307 if( array ){
4308 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4309 }
4310 return array;
4311}
4312
4313/* Compare two configurations */
4314int Configcmp(a,b)
4315struct config *a;
4316struct config *b;
4317{
4318 int x;
4319 x = a->rp->index - b->rp->index;
4320 if( x==0 ) x = a->dot - b->dot;
4321 return x;
4322}
4323
4324/* Compare two states */
4325PRIVATE int statecmp(a,b)
4326struct config *a;
4327struct config *b;
4328{
4329 int rc;
4330 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4331 rc = a->rp->index - b->rp->index;
4332 if( rc==0 ) rc = a->dot - b->dot;
4333 }
4334 if( rc==0 ){
4335 if( a ) rc = 1;
4336 if( b ) rc = -1;
4337 }
4338 return rc;
4339}
4340
4341/* Hash a state */
4342PRIVATE int statehash(a)
4343struct config *a;
4344{
4345 int h=0;
4346 while( a ){
4347 h = h*571 + a->rp->index*37 + a->dot;
4348 a = a->bp;
4349 }
4350 return h;
4351}
4352
4353/* Allocate a new state structure */
4354struct state *State_new()
4355{
4356 struct state *new;
4357 new = (struct state *)malloc( sizeof(struct state) );
4358 MemoryCheck(new);
4359 return new;
4360}
4361
4362/* There is one instance of the following structure for each
4363** associative array of type "x3".
4364*/
4365struct s_x3 {
4366 int size; /* The number of available slots. */
4367 /* Must be a power of 2 greater than or */
4368 /* equal to 1 */
4369 int count; /* Number of currently slots filled */
4370 struct s_x3node *tbl; /* The data stored here */
4371 struct s_x3node **ht; /* Hash table for lookups */
4372};
4373
4374/* There is one instance of this structure for every data element
4375** in an associative array of type "x3".
4376*/
4377typedef struct s_x3node {
4378 struct state *data; /* The data */
4379 struct config *key; /* The key */
4380 struct s_x3node *next; /* Next entry with the same hash */
4381 struct s_x3node **from; /* Previous link */
4382} x3node;
4383
4384/* There is only one instance of the array, which is the following */
4385static struct s_x3 *x3a;
4386
4387/* Allocate a new associative array */
4388void State_init(){
4389 if( x3a ) return;
4390 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4391 if( x3a ){
4392 x3a->size = 128;
4393 x3a->count = 0;
4394 x3a->tbl = (x3node*)malloc(
4395 (sizeof(x3node) + sizeof(x3node*))*128 );
4396 if( x3a->tbl==0 ){
4397 free(x3a);
4398 x3a = 0;
4399 }else{
4400 int i;
4401 x3a->ht = (x3node**)&(x3a->tbl[128]);
4402 for(i=0; i<128; i++) x3a->ht[i] = 0;
4403 }
4404 }
4405}
4406/* Insert a new record into the array. Return TRUE if successful.
4407** Prior data with the same key is NOT overwritten */
4408int State_insert(data,key)
4409struct state *data;
4410struct config *key;
4411{
4412 x3node *np;
4413 int h;
4414 int ph;
4415
4416 if( x3a==0 ) return 0;
4417 ph = statehash(key);
4418 h = ph & (x3a->size-1);
4419 np = x3a->ht[h];
4420 while( np ){
4421 if( statecmp(np->key,key)==0 ){
4422 /* An existing entry with the same key is found. */
4423 /* Fail because overwrite is not allows. */
4424 return 0;
4425 }
4426 np = np->next;
4427 }
4428 if( x3a->count>=x3a->size ){
4429 /* Need to make the hash table bigger */
4430 int i,size;
4431 struct s_x3 array;
4432 array.size = size = x3a->size*2;
4433 array.count = x3a->count;
4434 array.tbl = (x3node*)malloc(
4435 (sizeof(x3node) + sizeof(x3node*))*size );
4436 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4437 array.ht = (x3node**)&(array.tbl[size]);
4438 for(i=0; i<size; i++) array.ht[i] = 0;
4439 for(i=0; i<x3a->count; i++){
4440 x3node *oldnp, *newnp;
4441 oldnp = &(x3a->tbl[i]);
4442 h = statehash(oldnp->key) & (size-1);
4443 newnp = &(array.tbl[i]);
4444 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4445 newnp->next = array.ht[h];
4446 newnp->key = oldnp->key;
4447 newnp->data = oldnp->data;
4448 newnp->from = &(array.ht[h]);
4449 array.ht[h] = newnp;
4450 }
4451 free(x3a->tbl);
4452 *x3a = array;
4453 }
4454 /* Insert the new data */
4455 h = ph & (x3a->size-1);
4456 np = &(x3a->tbl[x3a->count++]);
4457 np->key = key;
4458 np->data = data;
4459 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4460 np->next = x3a->ht[h];
4461 x3a->ht[h] = np;
4462 np->from = &(x3a->ht[h]);
4463 return 1;
4464}
4465
4466/* Return a pointer to data assigned to the given key. Return NULL
4467** if no such key. */
4468struct state *State_find(key)
4469struct config *key;
4470{
4471 int h;
4472 x3node *np;
4473
4474 if( x3a==0 ) return 0;
4475 h = statehash(key) & (x3a->size-1);
4476 np = x3a->ht[h];
4477 while( np ){
4478 if( statecmp(np->key,key)==0 ) break;
4479 np = np->next;
4480 }
4481 return np ? np->data : 0;
4482}
4483
4484/* Return an array of pointers to all data in the table.
4485** The array is obtained from malloc. Return NULL if memory allocation
4486** problems, or if the array is empty. */
4487struct state **State_arrayof()
4488{
4489 struct state **array;
4490 int i,size;
4491 if( x3a==0 ) return 0;
4492 size = x3a->count;
4493 array = (struct state **)malloc( sizeof(struct state *)*size );
4494 if( array ){
4495 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4496 }
4497 return array;
4498}
4499
4500/* Hash a configuration */
4501PRIVATE int confighash(a)
4502struct config *a;
4503{
4504 int h=0;
4505 h = h*571 + a->rp->index*37 + a->dot;
4506 return h;
4507}
4508
4509/* There is one instance of the following structure for each
4510** associative array of type "x4".
4511*/
4512struct s_x4 {
4513 int size; /* The number of available slots. */
4514 /* Must be a power of 2 greater than or */
4515 /* equal to 1 */
4516 int count; /* Number of currently slots filled */
4517 struct s_x4node *tbl; /* The data stored here */
4518 struct s_x4node **ht; /* Hash table for lookups */
4519};
4520
4521/* There is one instance of this structure for every data element
4522** in an associative array of type "x4".
4523*/
4524typedef struct s_x4node {
4525 struct config *data; /* The data */
4526 struct s_x4node *next; /* Next entry with the same hash */
4527 struct s_x4node **from; /* Previous link */
4528} x4node;
4529
4530/* There is only one instance of the array, which is the following */
4531static struct s_x4 *x4a;
4532
4533/* Allocate a new associative array */
4534void Configtable_init(){
4535 if( x4a ) return;
4536 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4537 if( x4a ){
4538 x4a->size = 64;
4539 x4a->count = 0;
4540 x4a->tbl = (x4node*)malloc(
4541 (sizeof(x4node) + sizeof(x4node*))*64 );
4542 if( x4a->tbl==0 ){
4543 free(x4a);
4544 x4a = 0;
4545 }else{
4546 int i;
4547 x4a->ht = (x4node**)&(x4a->tbl[64]);
4548 for(i=0; i<64; i++) x4a->ht[i] = 0;
4549 }
4550 }
4551}
4552/* Insert a new record into the array. Return TRUE if successful.
4553** Prior data with the same key is NOT overwritten */
4554int Configtable_insert(data)
4555struct config *data;
4556{
4557 x4node *np;
4558 int h;
4559 int ph;
4560
4561 if( x4a==0 ) return 0;
4562 ph = confighash(data);
4563 h = ph & (x4a->size-1);
4564 np = x4a->ht[h];
4565 while( np ){
4566 if( Configcmp(np->data,data)==0 ){
4567 /* An existing entry with the same key is found. */
4568 /* Fail because overwrite is not allows. */
4569 return 0;
4570 }
4571 np = np->next;
4572 }
4573 if( x4a->count>=x4a->size ){
4574 /* Need to make the hash table bigger */
4575 int i,size;
4576 struct s_x4 array;
4577 array.size = size = x4a->size*2;
4578 array.count = x4a->count;
4579 array.tbl = (x4node*)malloc(
4580 (sizeof(x4node) + sizeof(x4node*))*size );
4581 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4582 array.ht = (x4node**)&(array.tbl[size]);
4583 for(i=0; i<size; i++) array.ht[i] = 0;
4584 for(i=0; i<x4a->count; i++){
4585 x4node *oldnp, *newnp;
4586 oldnp = &(x4a->tbl[i]);
4587 h = confighash(oldnp->data) & (size-1);
4588 newnp = &(array.tbl[i]);
4589 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4590 newnp->next = array.ht[h];
4591 newnp->data = oldnp->data;
4592 newnp->from = &(array.ht[h]);
4593 array.ht[h] = newnp;
4594 }
4595 free(x4a->tbl);
4596 *x4a = array;
4597 }
4598 /* Insert the new data */
4599 h = ph & (x4a->size-1);
4600 np = &(x4a->tbl[x4a->count++]);
4601 np->data = data;
4602 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4603 np->next = x4a->ht[h];
4604 x4a->ht[h] = np;
4605 np->from = &(x4a->ht[h]);
4606 return 1;
4607}
4608
4609/* Return a pointer to data assigned to the given key. Return NULL
4610** if no such key. */
4611struct config *Configtable_find(key)
4612struct config *key;
4613{
4614 int h;
4615 x4node *np;
4616
4617 if( x4a==0 ) return 0;
4618 h = confighash(key) & (x4a->size-1);
4619 np = x4a->ht[h];
4620 while( np ){
4621 if( Configcmp(np->data,key)==0 ) break;
4622 np = np->next;
4623 }
4624 return np ? np->data : 0;
4625}
4626
4627/* Remove all data from the table. Pass each data to the function "f"
4628** as it is removed. ("f" may be null to avoid this step.) */
4629void Configtable_clear(f)
4630int(*f)(/* struct config * */);
4631{
4632 int i;
4633 if( x4a==0 || x4a->count==0 ) return;
4634 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4635 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4636 x4a->count = 0;
4637 return;
4638}