blob: 175bc6e810b292e24a9ba764433ded72f3224ef1 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
drhf9a2e7b2003-04-15 01:49:48 +000010#include <stdarg.h>
drh75897232000-05-29 14:26:00 +000011#include <string.h>
12#include <ctype.h>
drh8b582012003-10-21 13:16:03 +000013#include <stdlib.h>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drh75897232000-05-29 14:26:00 +000016#ifndef __WIN32__
17# if defined(_WIN32) || defined(WIN32)
18# define __WIN32__
19# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
23extern int access();
24#else
25#include <unistd.h>
26#endif
27
drh75897232000-05-29 14:26:00 +000028/* #define PRIVATE static */
29#define PRIVATE
30
31#ifdef TEST
32#define MAXRHS 5 /* Set low to exercise exception code */
33#else
34#define MAXRHS 1000
35#endif
36
drhe9278182007-07-18 18:16:29 +000037static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000038
drh87cf1372008-08-13 20:09:06 +000039/*
40** Compilers are getting increasingly pedantic about type conversions
41** as C evolves ever closer to Ada.... To work around the latest problems
42** we have to define the following variant of strlen().
43*/
44#define lemonStrlen(X) ((int)strlen(X))
45
drhe9278182007-07-18 18:16:29 +000046static struct action *Action_new(void);
47static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000048
49/********** From the file "build.h" ************************************/
50void FindRulePrecedences();
51void FindFirstSets();
52void FindStates();
53void FindLinks();
54void FindFollowSets();
55void FindActions();
56
57/********* From the file "configlist.h" *********************************/
58void Configlist_init(/* void */);
59struct config *Configlist_add(/* struct rule *, int */);
60struct config *Configlist_addbasis(/* struct rule *, int */);
61void Configlist_closure(/* void */);
62void Configlist_sort(/* void */);
63void Configlist_sortbasis(/* void */);
64struct config *Configlist_return(/* void */);
65struct config *Configlist_basis(/* void */);
66void Configlist_eat(/* struct config * */);
67void Configlist_reset(/* void */);
68
69/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000070void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000071
72/****** From the file "option.h" ******************************************/
73struct s_options {
74 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
75 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
76 char *label;
77 char *arg;
78 char *message;
79};
drhb0c86772000-06-02 23:21:26 +000080int OptInit(/* char**,struct s_options*,FILE* */);
81int OptNArgs(/* void */);
82char *OptArg(/* int */);
83void OptErr(/* int */);
84void OptPrint(/* void */);
drh75897232000-05-29 14:26:00 +000085
86/******** From the file "parse.h" *****************************************/
87void Parse(/* struct lemon *lemp */);
88
89/********* From the file "plink.h" ***************************************/
90struct plink *Plink_new(/* void */);
91void Plink_add(/* struct plink **, struct config * */);
92void Plink_copy(/* struct plink **, struct plink * */);
93void Plink_delete(/* struct plink * */);
94
95/********** From the file "report.h" *************************************/
96void Reprint(/* struct lemon * */);
97void ReportOutput(/* struct lemon * */);
98void ReportTable(/* struct lemon * */);
99void ReportHeader(/* struct lemon * */);
100void CompressTables(/* struct lemon * */);
drhada354d2005-11-05 15:03:59 +0000101void ResortStates(/* struct lemon * */);
drh75897232000-05-29 14:26:00 +0000102
103/********** From the file "set.h" ****************************************/
104void SetSize(/* int N */); /* All sets will be of size N */
105char *SetNew(/* void */); /* A new set for element 0..N */
106void SetFree(/* char* */); /* Deallocate a set */
107
108int SetAdd(/* char*,int */); /* Add element to a set */
109int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
110
111#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
112
113/********** From the file "struct.h" *************************************/
114/*
115** Principal data structures for the LEMON parser generator.
116*/
117
drhaa9f1122007-08-23 02:50:56 +0000118typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000119
120/* Symbols (terminals and nonterminals) of the grammar are stored
121** in the following: */
122struct symbol {
123 char *name; /* Name of the symbol */
124 int index; /* Index number for this symbol */
125 enum {
126 TERMINAL,
drhfd405312005-11-06 04:06:59 +0000127 NONTERMINAL,
128 MULTITERMINAL
drh75897232000-05-29 14:26:00 +0000129 } type; /* Symbols are all either TERMINALS or NTs */
130 struct rule *rule; /* Linked list of rules of this (if an NT) */
drh0bd1f4e2002-06-06 18:54:39 +0000131 struct symbol *fallback; /* fallback token in case this token doesn't parse */
drh75897232000-05-29 14:26:00 +0000132 int prec; /* Precedence if defined (-1 otherwise) */
133 enum e_assoc {
134 LEFT,
135 RIGHT,
136 NONE,
137 UNK
drh34ff57b2008-07-14 12:27:51 +0000138 } assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000139 char *firstset; /* First-set for all rules of this symbol */
140 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000141 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000142 char *destructor; /* Code which executes whenever this symbol is
143 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000144 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000145 char *datatype; /* The data type of information held by this
146 ** object. Only used if type==NONTERMINAL */
147 int dtnum; /* The data type number. In the parser, the value
148 ** stack is a union. The .yy%d element of this
149 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000150 /* The following fields are used by MULTITERMINALs only */
151 int nsubsym; /* Number of constituent symbols in the MULTI */
152 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000153};
154
155/* Each production rule in the grammar is stored in the following
156** structure. */
157struct rule {
158 struct symbol *lhs; /* Left-hand side of the rule */
159 char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000160 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000161 int ruleline; /* Line number for the rule */
162 int nrhs; /* Number of RHS symbols */
163 struct symbol **rhs; /* The RHS symbols */
164 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
165 int line; /* Line number at which code begins */
166 char *code; /* The code executed when this rule is reduced */
167 struct symbol *precsym; /* Precedence symbol for this rule */
168 int index; /* An index number for this rule */
169 Boolean canReduce; /* True if this rule is ever reduced */
170 struct rule *nextlhs; /* Next rule with the same LHS */
171 struct rule *next; /* Next rule in the global list */
172};
173
174/* A configuration is a production rule of the grammar together with
175** a mark (dot) showing how much of that rule has been processed so far.
176** Configurations also contain a follow-set which is a list of terminal
177** symbols which are allowed to immediately follow the end of the rule.
178** Every configuration is recorded as an instance of the following: */
179struct config {
180 struct rule *rp; /* The rule upon which the configuration is based */
181 int dot; /* The parse point */
182 char *fws; /* Follow-set for this configuration only */
183 struct plink *fplp; /* Follow-set forward propagation links */
184 struct plink *bplp; /* Follow-set backwards propagation links */
185 struct state *stp; /* Pointer to state which contains this */
186 enum {
187 COMPLETE, /* The status is used during followset and */
188 INCOMPLETE /* shift computations */
189 } status;
190 struct config *next; /* Next configuration in the state */
191 struct config *bp; /* The next basis configuration */
192};
193
194/* Every shift or reduce operation is stored as one of the following */
195struct action {
196 struct symbol *sp; /* The look-ahead symbol */
197 enum e_action {
198 SHIFT,
199 ACCEPT,
200 REDUCE,
201 ERROR,
drh9892c5d2007-12-21 00:02:11 +0000202 SSCONFLICT, /* A shift/shift conflict */
203 SRCONFLICT, /* Was a reduce, but part of a conflict */
204 RRCONFLICT, /* Was a reduce, but part of a conflict */
drh75897232000-05-29 14:26:00 +0000205 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
206 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
207 NOT_USED /* Deleted by compression */
208 } type;
209 union {
210 struct state *stp; /* The new state, if a shift */
211 struct rule *rp; /* The rule, if a reduce */
212 } x;
213 struct action *next; /* Next action for this state */
214 struct action *collide; /* Next action with the same hash */
215};
216
217/* Each state of the generated parser's finite state machine
218** is encoded as an instance of the following structure. */
219struct state {
220 struct config *bp; /* The basis configurations for this state */
221 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000222 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000223 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000224 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
225 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
226 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000227};
drh8b582012003-10-21 13:16:03 +0000228#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000229
230/* A followset propagation link indicates that the contents of one
231** configuration followset should be propagated to another whenever
232** the first changes. */
233struct plink {
234 struct config *cfp; /* The configuration to which linked */
235 struct plink *next; /* The next propagate link */
236};
237
238/* The state vector for the entire parser generator is recorded as
239** follows. (LEMON uses no global variables and makes little use of
240** static variables. Fields in the following structure can be thought
241** of as begin global variables in the program.) */
242struct lemon {
243 struct state **sorted; /* Table of states sorted by state number */
244 struct rule *rule; /* List of all rules */
245 int nstate; /* Number of states */
246 int nrule; /* Number of rules */
247 int nsymbol; /* Number of terminal and nonterminal symbols */
248 int nterminal; /* Number of terminal symbols */
249 struct symbol **symbols; /* Sorted array of pointers to symbols */
250 int errorcnt; /* Number of errors */
251 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000252 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000253 char *name; /* Name of the generated parser */
254 char *arg; /* Declaration of the 3th argument to parser */
255 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000256 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000257 char *start; /* Name of the start symbol for the grammar */
258 char *stacksize; /* Size of the parser stack */
259 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000260 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000261 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000262 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000263 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000264 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000265 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000266 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000267 char *filename; /* Name of the input file */
268 char *outname; /* Name of the current output file */
269 char *tokenprefix; /* A prefix added to token names in the .h file */
270 int nconflict; /* Number of parsing conflicts */
271 int tablesize; /* Size of the parse tables */
272 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000273 int has_fallback; /* True if any %fallback is seen in the grammar */
drh75897232000-05-29 14:26:00 +0000274 char *argv0; /* Name of the program */
275};
276
277#define MemoryCheck(X) if((X)==0){ \
278 extern void memory_error(); \
279 memory_error(); \
280}
281
282/**************** From the file "table.h" *********************************/
283/*
284** All code in this file has been automatically generated
285** from a specification in the file
286** "table.q"
287** by the associative array code building program "aagen".
288** Do not edit this file! Instead, edit the specification
289** file, then rerun aagen.
290*/
291/*
292** Code for processing tables in the LEMON parser generator.
293*/
294
295/* Routines for handling a strings */
296
297char *Strsafe();
298
299void Strsafe_init(/* void */);
300int Strsafe_insert(/* char * */);
301char *Strsafe_find(/* char * */);
302
303/* Routines for handling symbols of the grammar */
304
305struct symbol *Symbol_new();
306int Symbolcmpp(/* struct symbol **, struct symbol ** */);
307void Symbol_init(/* void */);
308int Symbol_insert(/* struct symbol *, char * */);
309struct symbol *Symbol_find(/* char * */);
310struct symbol *Symbol_Nth(/* int */);
311int Symbol_count(/* */);
312struct symbol **Symbol_arrayof(/* */);
313
314/* Routines to manage the state table */
315
316int Configcmp(/* struct config *, struct config * */);
317struct state *State_new();
318void State_init(/* void */);
319int State_insert(/* struct state *, struct config * */);
320struct state *State_find(/* struct config * */);
321struct state **State_arrayof(/* */);
322
323/* Routines used for efficiency in Configlist_add */
324
325void Configtable_init(/* void */);
326int Configtable_insert(/* struct config * */);
327struct config *Configtable_find(/* struct config * */);
328void Configtable_clear(/* int(*)(struct config *) */);
329/****************** From the file "action.c" *******************************/
330/*
331** Routines processing parser actions in the LEMON parser generator.
332*/
333
334/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000335static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000336 static struct action *freelist = 0;
337 struct action *new;
338
339 if( freelist==0 ){
340 int i;
341 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000342 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000343 if( freelist==0 ){
344 fprintf(stderr,"Unable to allocate memory for a new parser action.");
345 exit(1);
346 }
347 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
348 freelist[amt-1].next = 0;
349 }
350 new = freelist;
351 freelist = freelist->next;
352 return new;
353}
354
drhe9278182007-07-18 18:16:29 +0000355/* Compare two actions for sorting purposes. Return negative, zero, or
356** positive if the first action is less than, equal to, or greater than
357** the first
358*/
359static int actioncmp(
360 struct action *ap1,
361 struct action *ap2
362){
drh75897232000-05-29 14:26:00 +0000363 int rc;
364 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000365 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000366 rc = (int)ap1->type - (int)ap2->type;
367 }
368 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000369 rc = ap1->x.rp->index - ap2->x.rp->index;
370 }
371 return rc;
372}
373
374/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000375static struct action *Action_sort(
376 struct action *ap
377){
378 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
379 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000380 return ap;
381}
382
383void Action_add(app,type,sp,arg)
384struct action **app;
385enum e_action type;
386struct symbol *sp;
387char *arg;
388{
389 struct action *new;
390 new = Action_new();
391 new->next = *app;
392 *app = new;
393 new->type = type;
394 new->sp = sp;
395 if( type==SHIFT ){
396 new->x.stp = (struct state *)arg;
397 }else{
398 new->x.rp = (struct rule *)arg;
399 }
400}
drh8b582012003-10-21 13:16:03 +0000401/********************** New code to implement the "acttab" module ***********/
402/*
403** This module implements routines use to construct the yy_action[] table.
404*/
405
406/*
407** The state of the yy_action table under construction is an instance of
408** the following structure
409*/
410typedef struct acttab acttab;
411struct acttab {
412 int nAction; /* Number of used slots in aAction[] */
413 int nActionAlloc; /* Slots allocated for aAction[] */
414 struct {
415 int lookahead; /* Value of the lookahead token */
416 int action; /* Action to take on the given lookahead */
417 } *aAction, /* The yy_action[] table under construction */
418 *aLookahead; /* A single new transaction set */
419 int mnLookahead; /* Minimum aLookahead[].lookahead */
420 int mnAction; /* Action associated with mnLookahead */
421 int mxLookahead; /* Maximum aLookahead[].lookahead */
422 int nLookahead; /* Used slots in aLookahead[] */
423 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
424};
425
426/* Return the number of entries in the yy_action table */
427#define acttab_size(X) ((X)->nAction)
428
429/* The value for the N-th entry in yy_action */
430#define acttab_yyaction(X,N) ((X)->aAction[N].action)
431
432/* The value for the N-th entry in yy_lookahead */
433#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
434
435/* Free all memory associated with the given acttab */
436void acttab_free(acttab *p){
437 free( p->aAction );
438 free( p->aLookahead );
439 free( p );
440}
441
442/* Allocate a new acttab structure */
443acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000444 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000445 if( p==0 ){
446 fprintf(stderr,"Unable to allocate memory for a new acttab.");
447 exit(1);
448 }
449 memset(p, 0, sizeof(*p));
450 return p;
451}
452
453/* Add a new action to the current transaction set
454*/
455void acttab_action(acttab *p, int lookahead, int action){
456 if( p->nLookahead>=p->nLookaheadAlloc ){
457 p->nLookaheadAlloc += 25;
458 p->aLookahead = realloc( p->aLookahead,
459 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
460 if( p->aLookahead==0 ){
461 fprintf(stderr,"malloc failed\n");
462 exit(1);
463 }
464 }
465 if( p->nLookahead==0 ){
466 p->mxLookahead = lookahead;
467 p->mnLookahead = lookahead;
468 p->mnAction = action;
469 }else{
470 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
471 if( p->mnLookahead>lookahead ){
472 p->mnLookahead = lookahead;
473 p->mnAction = action;
474 }
475 }
476 p->aLookahead[p->nLookahead].lookahead = lookahead;
477 p->aLookahead[p->nLookahead].action = action;
478 p->nLookahead++;
479}
480
481/*
482** Add the transaction set built up with prior calls to acttab_action()
483** into the current action table. Then reset the transaction set back
484** to an empty set in preparation for a new round of acttab_action() calls.
485**
486** Return the offset into the action table of the new transaction.
487*/
488int acttab_insert(acttab *p){
489 int i, j, k, n;
490 assert( p->nLookahead>0 );
491
492 /* Make sure we have enough space to hold the expanded action table
493 ** in the worst case. The worst case occurs if the transaction set
494 ** must be appended to the current action table
495 */
drh784d86f2004-02-19 18:41:53 +0000496 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000497 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000498 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000499 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
500 p->aAction = realloc( p->aAction,
501 sizeof(p->aAction[0])*p->nActionAlloc);
502 if( p->aAction==0 ){
503 fprintf(stderr,"malloc failed\n");
504 exit(1);
505 }
drhfdbf9282003-10-21 16:34:41 +0000506 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000507 p->aAction[i].lookahead = -1;
508 p->aAction[i].action = -1;
509 }
510 }
511
512 /* Scan the existing action table looking for an offset where we can
513 ** insert the current transaction set. Fall out of the loop when that
514 ** offset is found. In the worst case, we fall out of the loop when
515 ** i reaches p->nAction, which means we append the new transaction set.
516 **
517 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
518 */
drh784d86f2004-02-19 18:41:53 +0000519 for(i=0; i<p->nAction+p->mnLookahead; i++){
drh8b582012003-10-21 13:16:03 +0000520 if( p->aAction[i].lookahead<0 ){
521 for(j=0; j<p->nLookahead; j++){
522 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
523 if( k<0 ) break;
524 if( p->aAction[k].lookahead>=0 ) break;
525 }
drhfdbf9282003-10-21 16:34:41 +0000526 if( j<p->nLookahead ) continue;
527 for(j=0; j<p->nAction; j++){
528 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
529 }
530 if( j==p->nAction ){
531 break; /* Fits in empty slots */
532 }
drh8b582012003-10-21 13:16:03 +0000533 }else if( p->aAction[i].lookahead==p->mnLookahead ){
534 if( p->aAction[i].action!=p->mnAction ) continue;
535 for(j=0; j<p->nLookahead; j++){
536 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
537 if( k<0 || k>=p->nAction ) break;
538 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
539 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
540 }
541 if( j<p->nLookahead ) continue;
542 n = 0;
543 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000544 if( p->aAction[j].lookahead<0 ) continue;
545 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000546 }
drhfdbf9282003-10-21 16:34:41 +0000547 if( n==p->nLookahead ){
548 break; /* Same as a prior transaction set */
549 }
drh8b582012003-10-21 13:16:03 +0000550 }
551 }
552 /* Insert transaction set at index i. */
553 for(j=0; j<p->nLookahead; j++){
554 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
555 p->aAction[k] = p->aLookahead[j];
556 if( k>=p->nAction ) p->nAction = k+1;
557 }
558 p->nLookahead = 0;
559
560 /* Return the offset that is added to the lookahead in order to get the
561 ** index into yy_action of the action */
562 return i - p->mnLookahead;
563}
564
drh75897232000-05-29 14:26:00 +0000565/********************** From the file "build.c" *****************************/
566/*
567** Routines to construction the finite state machine for the LEMON
568** parser generator.
569*/
570
571/* Find a precedence symbol of every rule in the grammar.
572**
573** Those rules which have a precedence symbol coded in the input
574** grammar using the "[symbol]" construct will already have the
575** rp->precsym field filled. Other rules take as their precedence
576** symbol the first RHS symbol with a defined precedence. If there
577** are not RHS symbols with a defined precedence, the precedence
578** symbol field is left blank.
579*/
580void FindRulePrecedences(xp)
581struct lemon *xp;
582{
583 struct rule *rp;
584 for(rp=xp->rule; rp; rp=rp->next){
585 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000586 int i, j;
587 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
588 struct symbol *sp = rp->rhs[i];
589 if( sp->type==MULTITERMINAL ){
590 for(j=0; j<sp->nsubsym; j++){
591 if( sp->subsym[j]->prec>=0 ){
592 rp->precsym = sp->subsym[j];
593 break;
594 }
595 }
596 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000597 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000598 }
599 }
600 }
601 }
602 return;
603}
604
605/* Find all nonterminals which will generate the empty string.
606** Then go back and compute the first sets of every nonterminal.
607** The first set is the set of all terminal symbols which can begin
608** a string generated by that nonterminal.
609*/
610void FindFirstSets(lemp)
611struct lemon *lemp;
612{
drhfd405312005-11-06 04:06:59 +0000613 int i, j;
drh75897232000-05-29 14:26:00 +0000614 struct rule *rp;
615 int progress;
616
617 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000618 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000619 }
620 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
621 lemp->symbols[i]->firstset = SetNew();
622 }
623
624 /* First compute all lambdas */
625 do{
626 progress = 0;
627 for(rp=lemp->rule; rp; rp=rp->next){
628 if( rp->lhs->lambda ) continue;
629 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000630 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000631 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000632 }
633 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000634 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000635 progress = 1;
636 }
637 }
638 }while( progress );
639
640 /* Now compute all first sets */
641 do{
642 struct symbol *s1, *s2;
643 progress = 0;
644 for(rp=lemp->rule; rp; rp=rp->next){
645 s1 = rp->lhs;
646 for(i=0; i<rp->nrhs; i++){
647 s2 = rp->rhs[i];
648 if( s2->type==TERMINAL ){
649 progress += SetAdd(s1->firstset,s2->index);
650 break;
drhfd405312005-11-06 04:06:59 +0000651 }else if( s2->type==MULTITERMINAL ){
652 for(j=0; j<s2->nsubsym; j++){
653 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
654 }
655 break;
drh75897232000-05-29 14:26:00 +0000656 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000657 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000658 }else{
659 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000660 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000661 }
662 }
663 }
664 }while( progress );
665 return;
666}
667
668/* Compute all LR(0) states for the grammar. Links
669** are added to between some states so that the LR(1) follow sets
670** can be computed later.
671*/
672PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
673void FindStates(lemp)
674struct lemon *lemp;
675{
676 struct symbol *sp;
677 struct rule *rp;
678
679 Configlist_init();
680
681 /* Find the start symbol */
682 if( lemp->start ){
683 sp = Symbol_find(lemp->start);
684 if( sp==0 ){
685 ErrorMsg(lemp->filename,0,
686"The specified start symbol \"%s\" is not \
687in a nonterminal of the grammar. \"%s\" will be used as the start \
688symbol instead.",lemp->start,lemp->rule->lhs->name);
689 lemp->errorcnt++;
690 sp = lemp->rule->lhs;
691 }
692 }else{
693 sp = lemp->rule->lhs;
694 }
695
696 /* Make sure the start symbol doesn't occur on the right-hand side of
697 ** any rule. Report an error if it does. (YACC would generate a new
698 ** start symbol in this case.) */
699 for(rp=lemp->rule; rp; rp=rp->next){
700 int i;
701 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000702 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000703 ErrorMsg(lemp->filename,0,
704"The start symbol \"%s\" occurs on the \
705right-hand side of a rule. This will result in a parser which \
706does not work properly.",sp->name);
707 lemp->errorcnt++;
708 }
709 }
710 }
711
712 /* The basis configuration set for the first state
713 ** is all rules which have the start symbol as their
714 ** left-hand side */
715 for(rp=sp->rule; rp; rp=rp->nextlhs){
716 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000717 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000718 newcfp = Configlist_addbasis(rp,0);
719 SetAdd(newcfp->fws,0);
720 }
721
722 /* Compute the first state. All other states will be
723 ** computed automatically during the computation of the first one.
724 ** The returned pointer to the first state is not used. */
725 (void)getstate(lemp);
726 return;
727}
728
729/* Return a pointer to a state which is described by the configuration
730** list which has been built from calls to Configlist_add.
731*/
732PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
733PRIVATE struct state *getstate(lemp)
734struct lemon *lemp;
735{
736 struct config *cfp, *bp;
737 struct state *stp;
738
739 /* Extract the sorted basis of the new state. The basis was constructed
740 ** by prior calls to "Configlist_addbasis()". */
741 Configlist_sortbasis();
742 bp = Configlist_basis();
743
744 /* Get a state with the same basis */
745 stp = State_find(bp);
746 if( stp ){
747 /* A state with the same basis already exists! Copy all the follow-set
748 ** propagation links from the state under construction into the
749 ** preexisting state, then return a pointer to the preexisting state */
750 struct config *x, *y;
751 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
752 Plink_copy(&y->bplp,x->bplp);
753 Plink_delete(x->fplp);
754 x->fplp = x->bplp = 0;
755 }
756 cfp = Configlist_return();
757 Configlist_eat(cfp);
758 }else{
759 /* This really is a new state. Construct all the details */
760 Configlist_closure(lemp); /* Compute the configuration closure */
761 Configlist_sort(); /* Sort the configuration closure */
762 cfp = Configlist_return(); /* Get a pointer to the config list */
763 stp = State_new(); /* A new state structure */
764 MemoryCheck(stp);
765 stp->bp = bp; /* Remember the configuration basis */
766 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000767 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000768 stp->ap = 0; /* No actions, yet. */
769 State_insert(stp,stp->bp); /* Add to the state table */
770 buildshifts(lemp,stp); /* Recursively compute successor states */
771 }
772 return stp;
773}
774
drhfd405312005-11-06 04:06:59 +0000775/*
776** Return true if two symbols are the same.
777*/
778int same_symbol(a,b)
779struct symbol *a;
780struct symbol *b;
781{
782 int i;
783 if( a==b ) return 1;
784 if( a->type!=MULTITERMINAL ) return 0;
785 if( b->type!=MULTITERMINAL ) return 0;
786 if( a->nsubsym!=b->nsubsym ) return 0;
787 for(i=0; i<a->nsubsym; i++){
788 if( a->subsym[i]!=b->subsym[i] ) return 0;
789 }
790 return 1;
791}
792
drh75897232000-05-29 14:26:00 +0000793/* Construct all successor states to the given state. A "successor"
794** state is any state which can be reached by a shift action.
795*/
796PRIVATE void buildshifts(lemp,stp)
797struct lemon *lemp;
798struct state *stp; /* The state from which successors are computed */
799{
800 struct config *cfp; /* For looping thru the config closure of "stp" */
801 struct config *bcfp; /* For the inner loop on config closure of "stp" */
802 struct config *new; /* */
803 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
804 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
805 struct state *newstp; /* A pointer to a successor state */
806
807 /* Each configuration becomes complete after it contibutes to a successor
808 ** state. Initially, all configurations are incomplete */
809 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
810
811 /* Loop through all configurations of the state "stp" */
812 for(cfp=stp->cfp; cfp; cfp=cfp->next){
813 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
814 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
815 Configlist_reset(); /* Reset the new config set */
816 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
817
818 /* For every configuration in the state "stp" which has the symbol "sp"
819 ** following its dot, add the same configuration to the basis set under
820 ** construction but with the dot shifted one symbol to the right. */
821 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
822 if( bcfp->status==COMPLETE ) continue; /* Already used */
823 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
824 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000825 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000826 bcfp->status = COMPLETE; /* Mark this config as used */
827 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
828 Plink_add(&new->bplp,bcfp);
829 }
830
831 /* Get a pointer to the state described by the basis configuration set
832 ** constructed in the preceding loop */
833 newstp = getstate(lemp);
834
835 /* The state "newstp" is reached from the state "stp" by a shift action
836 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000837 if( sp->type==MULTITERMINAL ){
838 int i;
839 for(i=0; i<sp->nsubsym; i++){
840 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
841 }
842 }else{
843 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
844 }
drh75897232000-05-29 14:26:00 +0000845 }
846}
847
848/*
849** Construct the propagation links
850*/
851void FindLinks(lemp)
852struct lemon *lemp;
853{
854 int i;
855 struct config *cfp, *other;
856 struct state *stp;
857 struct plink *plp;
858
859 /* Housekeeping detail:
860 ** Add to every propagate link a pointer back to the state to
861 ** which the link is attached. */
862 for(i=0; i<lemp->nstate; i++){
863 stp = lemp->sorted[i];
864 for(cfp=stp->cfp; cfp; cfp=cfp->next){
865 cfp->stp = stp;
866 }
867 }
868
869 /* Convert all backlinks into forward links. Only the forward
870 ** links are used in the follow-set computation. */
871 for(i=0; i<lemp->nstate; i++){
872 stp = lemp->sorted[i];
873 for(cfp=stp->cfp; cfp; cfp=cfp->next){
874 for(plp=cfp->bplp; plp; plp=plp->next){
875 other = plp->cfp;
876 Plink_add(&other->fplp,cfp);
877 }
878 }
879 }
880}
881
882/* Compute all followsets.
883**
884** A followset is the set of all symbols which can come immediately
885** after a configuration.
886*/
887void FindFollowSets(lemp)
888struct lemon *lemp;
889{
890 int i;
891 struct config *cfp;
892 struct plink *plp;
893 int progress;
894 int change;
895
896 for(i=0; i<lemp->nstate; i++){
897 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
898 cfp->status = INCOMPLETE;
899 }
900 }
901
902 do{
903 progress = 0;
904 for(i=0; i<lemp->nstate; i++){
905 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
906 if( cfp->status==COMPLETE ) continue;
907 for(plp=cfp->fplp; plp; plp=plp->next){
908 change = SetUnion(plp->cfp->fws,cfp->fws);
909 if( change ){
910 plp->cfp->status = INCOMPLETE;
911 progress = 1;
912 }
913 }
914 cfp->status = COMPLETE;
915 }
916 }
917 }while( progress );
918}
919
920static int resolve_conflict();
921
922/* Compute the reduce actions, and resolve conflicts.
923*/
924void FindActions(lemp)
925struct lemon *lemp;
926{
927 int i,j;
928 struct config *cfp;
929 struct state *stp;
930 struct symbol *sp;
931 struct rule *rp;
932
933 /* Add all of the reduce actions
934 ** A reduce action is added for each element of the followset of
935 ** a configuration which has its dot at the extreme right.
936 */
937 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
938 stp = lemp->sorted[i];
939 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
940 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
941 for(j=0; j<lemp->nterminal; j++){
942 if( SetFind(cfp->fws,j) ){
943 /* Add a reduce action to the state "stp" which will reduce by the
944 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000945 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000946 }
947 }
948 }
949 }
950 }
951
952 /* Add the accepting token */
953 if( lemp->start ){
954 sp = Symbol_find(lemp->start);
955 if( sp==0 ) sp = lemp->rule->lhs;
956 }else{
957 sp = lemp->rule->lhs;
958 }
959 /* Add to the first state (which is always the starting state of the
960 ** finite state machine) an action to ACCEPT if the lookahead is the
961 ** start nonterminal. */
962 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
963
964 /* Resolve conflicts */
965 for(i=0; i<lemp->nstate; i++){
966 struct action *ap, *nap;
967 struct state *stp;
968 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000969 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000970 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000971 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000972 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
973 /* The two actions "ap" and "nap" have the same lookahead.
974 ** Figure out which one should be used */
975 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
976 }
977 }
978 }
979
980 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000981 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000982 for(i=0; i<lemp->nstate; i++){
983 struct action *ap;
984 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000985 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000986 }
987 }
988 for(rp=lemp->rule; rp; rp=rp->next){
989 if( rp->canReduce ) continue;
990 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
991 lemp->errorcnt++;
992 }
993}
994
995/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +0000996** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +0000997**
998** NO LONGER TRUE:
999** To resolve a conflict, first look to see if either action
1000** is on an error rule. In that case, take the action which
1001** is not associated with the error rule. If neither or both
1002** actions are associated with an error rule, then try to
1003** use precedence to resolve the conflict.
1004**
1005** If either action is a SHIFT, then it must be apx. This
1006** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1007*/
1008static int resolve_conflict(apx,apy,errsym)
1009struct action *apx;
1010struct action *apy;
1011struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1012{
1013 struct symbol *spx, *spy;
1014 int errcnt = 0;
1015 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001016 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001017 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001018 errcnt++;
1019 }
drh75897232000-05-29 14:26:00 +00001020 if( apx->type==SHIFT && apy->type==REDUCE ){
1021 spx = apx->sp;
1022 spy = apy->x.rp->precsym;
1023 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1024 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001025 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001026 errcnt++;
1027 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1028 apy->type = RD_RESOLVED;
1029 }else if( spx->prec<spy->prec ){
1030 apx->type = SH_RESOLVED;
1031 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1032 apy->type = RD_RESOLVED; /* associativity */
1033 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1034 apx->type = SH_RESOLVED;
1035 }else{
1036 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001037 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001038 errcnt++;
1039 }
1040 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1041 spx = apx->x.rp->precsym;
1042 spy = apy->x.rp->precsym;
1043 if( spx==0 || spy==0 || spx->prec<0 ||
1044 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001045 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001046 errcnt++;
1047 }else if( spx->prec>spy->prec ){
1048 apy->type = RD_RESOLVED;
1049 }else if( spx->prec<spy->prec ){
1050 apx->type = RD_RESOLVED;
1051 }
1052 }else{
drhb59499c2002-02-23 18:45:13 +00001053 assert(
1054 apx->type==SH_RESOLVED ||
1055 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001056 apx->type==SSCONFLICT ||
1057 apx->type==SRCONFLICT ||
1058 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001059 apy->type==SH_RESOLVED ||
1060 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001061 apy->type==SSCONFLICT ||
1062 apy->type==SRCONFLICT ||
1063 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001064 );
1065 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1066 ** REDUCEs on the list. If we reach this point it must be because
1067 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001068 }
1069 return errcnt;
1070}
1071/********************* From the file "configlist.c" *************************/
1072/*
1073** Routines to processing a configuration list and building a state
1074** in the LEMON parser generator.
1075*/
1076
1077static struct config *freelist = 0; /* List of free configurations */
1078static struct config *current = 0; /* Top of list of configurations */
1079static struct config **currentend = 0; /* Last on list of configs */
1080static struct config *basis = 0; /* Top of list of basis configs */
1081static struct config **basisend = 0; /* End of list of basis configs */
1082
1083/* Return a pointer to a new configuration */
1084PRIVATE struct config *newconfig(){
1085 struct config *new;
1086 if( freelist==0 ){
1087 int i;
1088 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001089 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001090 if( freelist==0 ){
1091 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1092 exit(1);
1093 }
1094 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1095 freelist[amt-1].next = 0;
1096 }
1097 new = freelist;
1098 freelist = freelist->next;
1099 return new;
1100}
1101
1102/* The configuration "old" is no longer used */
1103PRIVATE void deleteconfig(old)
1104struct config *old;
1105{
1106 old->next = freelist;
1107 freelist = old;
1108}
1109
1110/* Initialized the configuration list builder */
1111void Configlist_init(){
1112 current = 0;
1113 currentend = &current;
1114 basis = 0;
1115 basisend = &basis;
1116 Configtable_init();
1117 return;
1118}
1119
1120/* Initialized the configuration list builder */
1121void Configlist_reset(){
1122 current = 0;
1123 currentend = &current;
1124 basis = 0;
1125 basisend = &basis;
1126 Configtable_clear(0);
1127 return;
1128}
1129
1130/* Add another configuration to the configuration list */
1131struct config *Configlist_add(rp,dot)
1132struct rule *rp; /* The rule */
1133int dot; /* Index into the RHS of the rule where the dot goes */
1134{
1135 struct config *cfp, model;
1136
1137 assert( currentend!=0 );
1138 model.rp = rp;
1139 model.dot = dot;
1140 cfp = Configtable_find(&model);
1141 if( cfp==0 ){
1142 cfp = newconfig();
1143 cfp->rp = rp;
1144 cfp->dot = dot;
1145 cfp->fws = SetNew();
1146 cfp->stp = 0;
1147 cfp->fplp = cfp->bplp = 0;
1148 cfp->next = 0;
1149 cfp->bp = 0;
1150 *currentend = cfp;
1151 currentend = &cfp->next;
1152 Configtable_insert(cfp);
1153 }
1154 return cfp;
1155}
1156
1157/* Add a basis configuration to the configuration list */
1158struct config *Configlist_addbasis(rp,dot)
1159struct rule *rp;
1160int dot;
1161{
1162 struct config *cfp, model;
1163
1164 assert( basisend!=0 );
1165 assert( currentend!=0 );
1166 model.rp = rp;
1167 model.dot = dot;
1168 cfp = Configtable_find(&model);
1169 if( cfp==0 ){
1170 cfp = newconfig();
1171 cfp->rp = rp;
1172 cfp->dot = dot;
1173 cfp->fws = SetNew();
1174 cfp->stp = 0;
1175 cfp->fplp = cfp->bplp = 0;
1176 cfp->next = 0;
1177 cfp->bp = 0;
1178 *currentend = cfp;
1179 currentend = &cfp->next;
1180 *basisend = cfp;
1181 basisend = &cfp->bp;
1182 Configtable_insert(cfp);
1183 }
1184 return cfp;
1185}
1186
1187/* Compute the closure of the configuration list */
1188void Configlist_closure(lemp)
1189struct lemon *lemp;
1190{
1191 struct config *cfp, *newcfp;
1192 struct rule *rp, *newrp;
1193 struct symbol *sp, *xsp;
1194 int i, dot;
1195
1196 assert( currentend!=0 );
1197 for(cfp=current; cfp; cfp=cfp->next){
1198 rp = cfp->rp;
1199 dot = cfp->dot;
1200 if( dot>=rp->nrhs ) continue;
1201 sp = rp->rhs[dot];
1202 if( sp->type==NONTERMINAL ){
1203 if( sp->rule==0 && sp!=lemp->errsym ){
1204 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1205 sp->name);
1206 lemp->errorcnt++;
1207 }
1208 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1209 newcfp = Configlist_add(newrp,0);
1210 for(i=dot+1; i<rp->nrhs; i++){
1211 xsp = rp->rhs[i];
1212 if( xsp->type==TERMINAL ){
1213 SetAdd(newcfp->fws,xsp->index);
1214 break;
drhfd405312005-11-06 04:06:59 +00001215 }else if( xsp->type==MULTITERMINAL ){
1216 int k;
1217 for(k=0; k<xsp->nsubsym; k++){
1218 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1219 }
1220 break;
drh75897232000-05-29 14:26:00 +00001221 }else{
1222 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001223 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001224 }
1225 }
1226 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1227 }
1228 }
1229 }
1230 return;
1231}
1232
1233/* Sort the configuration list */
1234void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001235 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001236 currentend = 0;
1237 return;
1238}
1239
1240/* Sort the basis configuration list */
1241void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001242 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001243 basisend = 0;
1244 return;
1245}
1246
1247/* Return a pointer to the head of the configuration list and
1248** reset the list */
1249struct config *Configlist_return(){
1250 struct config *old;
1251 old = current;
1252 current = 0;
1253 currentend = 0;
1254 return old;
1255}
1256
1257/* Return a pointer to the head of the configuration list and
1258** reset the list */
1259struct config *Configlist_basis(){
1260 struct config *old;
1261 old = basis;
1262 basis = 0;
1263 basisend = 0;
1264 return old;
1265}
1266
1267/* Free all elements of the given configuration list */
1268void Configlist_eat(cfp)
1269struct config *cfp;
1270{
1271 struct config *nextcfp;
1272 for(; cfp; cfp=nextcfp){
1273 nextcfp = cfp->next;
1274 assert( cfp->fplp==0 );
1275 assert( cfp->bplp==0 );
1276 if( cfp->fws ) SetFree(cfp->fws);
1277 deleteconfig(cfp);
1278 }
1279 return;
1280}
1281/***************** From the file "error.c" *********************************/
1282/*
1283** Code for printing error message.
1284*/
1285
1286/* Find a good place to break "msg" so that its length is at least "min"
1287** but no more than "max". Make the point as close to max as possible.
1288*/
1289static int findbreak(msg,min,max)
1290char *msg;
1291int min;
1292int max;
1293{
1294 int i,spot;
1295 char c;
1296 for(i=spot=min; i<=max; i++){
1297 c = msg[i];
1298 if( c=='\t' ) msg[i] = ' ';
1299 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1300 if( c==0 ){ spot = i; break; }
1301 if( c=='-' && i<max-1 ) spot = i+1;
1302 if( c==' ' ) spot = i;
1303 }
1304 return spot;
1305}
1306
1307/*
1308** The error message is split across multiple lines if necessary. The
1309** splits occur at a space, if there is a space available near the end
1310** of the line.
1311*/
1312#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1313#define LINEWIDTH 79 /* Max width of any output line */
1314#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001315void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001316 char errmsg[ERRMSGSIZE];
1317 char prefix[PREFIXLIMIT+10];
1318 int errmsgsize;
1319 int prefixsize;
1320 int availablewidth;
1321 va_list ap;
1322 int end, restart, base;
1323
drhf9a2e7b2003-04-15 01:49:48 +00001324 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001325 /* Prepare a prefix to be prepended to every output line */
1326 if( lineno>0 ){
1327 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1328 }else{
1329 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1330 }
drh87cf1372008-08-13 20:09:06 +00001331 prefixsize = lemonStrlen(prefix);
drh75897232000-05-29 14:26:00 +00001332 availablewidth = LINEWIDTH - prefixsize;
1333
1334 /* Generate the error message */
1335 vsprintf(errmsg,format,ap);
1336 va_end(ap);
drh87cf1372008-08-13 20:09:06 +00001337 errmsgsize = lemonStrlen(errmsg);
drh75897232000-05-29 14:26:00 +00001338 /* Remove trailing '\n's from the error message. */
1339 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1340 errmsg[--errmsgsize] = 0;
1341 }
1342
1343 /* Print the error message */
1344 base = 0;
1345 while( errmsg[base]!=0 ){
1346 end = restart = findbreak(&errmsg[base],0,availablewidth);
1347 restart += base;
1348 while( errmsg[restart]==' ' ) restart++;
1349 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1350 base = restart;
1351 }
1352}
1353/**************** From the file "main.c" ************************************/
1354/*
1355** Main program file for the LEMON parser generator.
1356*/
1357
1358/* Report an out-of-memory condition and abort. This function
1359** is used mostly by the "MemoryCheck" macro in struct.h
1360*/
1361void memory_error(){
1362 fprintf(stderr,"Out of memory. Aborting...\n");
1363 exit(1);
1364}
1365
drh6d08b4d2004-07-20 12:45:22 +00001366static int nDefine = 0; /* Number of -D options on the command line */
1367static char **azDefine = 0; /* Name of the -D macros */
1368
1369/* This routine is called with the argument to each -D command-line option.
1370** Add the macro defined to the azDefine array.
1371*/
1372static void handle_D_option(char *z){
1373 char **paz;
1374 nDefine++;
1375 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1376 if( azDefine==0 ){
1377 fprintf(stderr,"out of memory\n");
1378 exit(1);
1379 }
1380 paz = &azDefine[nDefine-1];
drh87cf1372008-08-13 20:09:06 +00001381 *paz = malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001382 if( *paz==0 ){
1383 fprintf(stderr,"out of memory\n");
1384 exit(1);
1385 }
1386 strcpy(*paz, z);
1387 for(z=*paz; *z && *z!='='; z++){}
1388 *z = 0;
1389}
1390
drh75897232000-05-29 14:26:00 +00001391
1392/* The main program. Parse the command line and do it... */
1393int main(argc,argv)
1394int argc;
1395char **argv;
1396{
1397 static int version = 0;
1398 static int rpflag = 0;
1399 static int basisflag = 0;
1400 static int compress = 0;
1401 static int quiet = 0;
1402 static int statistics = 0;
1403 static int mhflag = 0;
1404 static struct s_options options[] = {
1405 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1406 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001407 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001408 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1409 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1410 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001411 {OPT_FLAG, "s", (char*)&statistics,
1412 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001413 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1414 {OPT_FLAG,0,0,0}
1415 };
1416 int i;
1417 struct lemon lem;
1418
drhb0c86772000-06-02 23:21:26 +00001419 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001420 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001421 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001422 exit(0);
1423 }
drhb0c86772000-06-02 23:21:26 +00001424 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001425 fprintf(stderr,"Exactly one filename argument is required.\n");
1426 exit(1);
1427 }
drh954f6b42006-06-13 13:27:46 +00001428 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001429 lem.errorcnt = 0;
1430
1431 /* Initialize the machine */
1432 Strsafe_init();
1433 Symbol_init();
1434 State_init();
1435 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001436 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001437 lem.basisflag = basisflag;
drh75897232000-05-29 14:26:00 +00001438 Symbol_new("$");
1439 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001440 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001441
1442 /* Parse the input file */
1443 Parse(&lem);
1444 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001445 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001446 fprintf(stderr,"Empty grammar.\n");
1447 exit(1);
1448 }
1449
1450 /* Count and index the symbols of the grammar */
1451 lem.nsymbol = Symbol_count();
1452 Symbol_new("{default}");
1453 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001454 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001455 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1456 (int(*)())Symbolcmpp);
1457 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1458 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1459 lem.nterminal = i;
1460
1461 /* Generate a reprint of the grammar, if requested on the command line */
1462 if( rpflag ){
1463 Reprint(&lem);
1464 }else{
1465 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001466 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001467
1468 /* Find the precedence for every production rule (that has one) */
1469 FindRulePrecedences(&lem);
1470
1471 /* Compute the lambda-nonterminals and the first-sets for every
1472 ** nonterminal */
1473 FindFirstSets(&lem);
1474
1475 /* Compute all LR(0) states. Also record follow-set propagation
1476 ** links so that the follow-set can be computed later */
1477 lem.nstate = 0;
1478 FindStates(&lem);
1479 lem.sorted = State_arrayof();
1480
1481 /* Tie up loose ends on the propagation links */
1482 FindLinks(&lem);
1483
1484 /* Compute the follow set of every reducible configuration */
1485 FindFollowSets(&lem);
1486
1487 /* Compute the action tables */
1488 FindActions(&lem);
1489
1490 /* Compress the action tables */
1491 if( compress==0 ) CompressTables(&lem);
1492
drhada354d2005-11-05 15:03:59 +00001493 /* Reorder and renumber the states so that states with fewer choices
1494 ** occur at the end. */
1495 ResortStates(&lem);
1496
drh75897232000-05-29 14:26:00 +00001497 /* Generate a report of the parser generated. (the "y.output" file) */
1498 if( !quiet ) ReportOutput(&lem);
1499
1500 /* Generate the source code for the parser */
1501 ReportTable(&lem, mhflag);
1502
1503 /* Produce a header file for use by the scanner. (This step is
1504 ** omitted if the "-m" option is used because makeheaders will
1505 ** generate the file for us.) */
1506 if( !mhflag ) ReportHeader(&lem);
1507 }
1508 if( statistics ){
1509 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1510 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1511 printf(" %d states, %d parser table entries, %d conflicts\n",
1512 lem.nstate, lem.tablesize, lem.nconflict);
1513 }
1514 if( lem.nconflict ){
1515 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1516 }
1517 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001518 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001519}
1520/******************** From the file "msort.c" *******************************/
1521/*
1522** A generic merge-sort program.
1523**
1524** USAGE:
1525** Let "ptr" be a pointer to some structure which is at the head of
1526** a null-terminated list. Then to sort the list call:
1527**
1528** ptr = msort(ptr,&(ptr->next),cmpfnc);
1529**
1530** In the above, "cmpfnc" is a pointer to a function which compares
1531** two instances of the structure and returns an integer, as in
1532** strcmp. The second argument is a pointer to the pointer to the
1533** second element of the linked list. This address is used to compute
1534** the offset to the "next" field within the structure. The offset to
1535** the "next" field must be constant for all structures in the list.
1536**
1537** The function returns a new pointer which is the head of the list
1538** after sorting.
1539**
1540** ALGORITHM:
1541** Merge-sort.
1542*/
1543
1544/*
1545** Return a pointer to the next structure in the linked list.
1546*/
drhba99af52001-10-25 20:37:16 +00001547#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001548
1549/*
1550** Inputs:
1551** a: A sorted, null-terminated linked list. (May be null).
1552** b: A sorted, null-terminated linked list. (May be null).
1553** cmp: A pointer to the comparison function.
1554** offset: Offset in the structure to the "next" field.
1555**
1556** Return Value:
1557** A pointer to the head of a sorted list containing the elements
1558** of both a and b.
1559**
1560** Side effects:
1561** The "next" pointers for elements in the lists a and b are
1562** changed.
1563*/
drhe9278182007-07-18 18:16:29 +00001564static char *merge(
1565 char *a,
1566 char *b,
1567 int (*cmp)(const char*,const char*),
1568 int offset
1569){
drh75897232000-05-29 14:26:00 +00001570 char *ptr, *head;
1571
1572 if( a==0 ){
1573 head = b;
1574 }else if( b==0 ){
1575 head = a;
1576 }else{
1577 if( (*cmp)(a,b)<0 ){
1578 ptr = a;
1579 a = NEXT(a);
1580 }else{
1581 ptr = b;
1582 b = NEXT(b);
1583 }
1584 head = ptr;
1585 while( a && b ){
1586 if( (*cmp)(a,b)<0 ){
1587 NEXT(ptr) = a;
1588 ptr = a;
1589 a = NEXT(a);
1590 }else{
1591 NEXT(ptr) = b;
1592 ptr = b;
1593 b = NEXT(b);
1594 }
1595 }
1596 if( a ) NEXT(ptr) = a;
1597 else NEXT(ptr) = b;
1598 }
1599 return head;
1600}
1601
1602/*
1603** Inputs:
1604** list: Pointer to a singly-linked list of structures.
1605** next: Pointer to pointer to the second element of the list.
1606** cmp: A comparison function.
1607**
1608** Return Value:
1609** A pointer to the head of a sorted list containing the elements
1610** orginally in list.
1611**
1612** Side effects:
1613** The "next" pointers for elements in list are changed.
1614*/
1615#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001616static char *msort(
1617 char *list,
1618 char **next,
1619 int (*cmp)(const char*,const char*)
1620){
drhba99af52001-10-25 20:37:16 +00001621 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001622 char *ep;
1623 char *set[LISTSIZE];
1624 int i;
drhba99af52001-10-25 20:37:16 +00001625 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001626 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1627 while( list ){
1628 ep = list;
1629 list = NEXT(list);
1630 NEXT(ep) = 0;
1631 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1632 ep = merge(ep,set[i],cmp,offset);
1633 set[i] = 0;
1634 }
1635 set[i] = ep;
1636 }
1637 ep = 0;
1638 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1639 return ep;
1640}
1641/************************ From the file "option.c" **************************/
1642static char **argv;
1643static struct s_options *op;
1644static FILE *errstream;
1645
1646#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1647
1648/*
1649** Print the command line with a carrot pointing to the k-th character
1650** of the n-th field.
1651*/
1652static void errline(n,k,err)
1653int n;
1654int k;
1655FILE *err;
1656{
1657 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001658 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001659 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001660 for(i=1; i<n && argv[i]; i++){
1661 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001662 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001663 }
1664 spcnt += k;
1665 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1666 if( spcnt<20 ){
1667 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1668 }else{
1669 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1670 }
1671}
1672
1673/*
1674** Return the index of the N-th non-switch argument. Return -1
1675** if N is out of range.
1676*/
1677static int argindex(n)
1678int n;
1679{
1680 int i;
1681 int dashdash = 0;
1682 if( argv!=0 && *argv!=0 ){
1683 for(i=1; argv[i]; i++){
1684 if( dashdash || !ISOPT(argv[i]) ){
1685 if( n==0 ) return i;
1686 n--;
1687 }
1688 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1689 }
1690 }
1691 return -1;
1692}
1693
1694static char emsg[] = "Command line syntax error: ";
1695
1696/*
1697** Process a flag command line argument.
1698*/
1699static int handleflags(i,err)
1700int i;
1701FILE *err;
1702{
1703 int v;
1704 int errcnt = 0;
1705 int j;
1706 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001707 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001708 }
1709 v = argv[i][0]=='-' ? 1 : 0;
1710 if( op[j].label==0 ){
1711 if( err ){
1712 fprintf(err,"%sundefined option.\n",emsg);
1713 errline(i,1,err);
1714 }
1715 errcnt++;
1716 }else if( op[j].type==OPT_FLAG ){
1717 *((int*)op[j].arg) = v;
1718 }else if( op[j].type==OPT_FFLAG ){
1719 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001720 }else if( op[j].type==OPT_FSTR ){
1721 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001722 }else{
1723 if( err ){
1724 fprintf(err,"%smissing argument on switch.\n",emsg);
1725 errline(i,1,err);
1726 }
1727 errcnt++;
1728 }
1729 return errcnt;
1730}
1731
1732/*
1733** Process a command line switch which has an argument.
1734*/
1735static int handleswitch(i,err)
1736int i;
1737FILE *err;
1738{
1739 int lv = 0;
1740 double dv = 0.0;
1741 char *sv = 0, *end;
1742 char *cp;
1743 int j;
1744 int errcnt = 0;
1745 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001746 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001747 *cp = 0;
1748 for(j=0; op[j].label; j++){
1749 if( strcmp(argv[i],op[j].label)==0 ) break;
1750 }
1751 *cp = '=';
1752 if( op[j].label==0 ){
1753 if( err ){
1754 fprintf(err,"%sundefined option.\n",emsg);
1755 errline(i,0,err);
1756 }
1757 errcnt++;
1758 }else{
1759 cp++;
1760 switch( op[j].type ){
1761 case OPT_FLAG:
1762 case OPT_FFLAG:
1763 if( err ){
1764 fprintf(err,"%soption requires an argument.\n",emsg);
1765 errline(i,0,err);
1766 }
1767 errcnt++;
1768 break;
1769 case OPT_DBL:
1770 case OPT_FDBL:
1771 dv = strtod(cp,&end);
1772 if( *end ){
1773 if( err ){
1774 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001775 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001776 }
1777 errcnt++;
1778 }
1779 break;
1780 case OPT_INT:
1781 case OPT_FINT:
1782 lv = strtol(cp,&end,0);
1783 if( *end ){
1784 if( err ){
1785 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001786 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001787 }
1788 errcnt++;
1789 }
1790 break;
1791 case OPT_STR:
1792 case OPT_FSTR:
1793 sv = cp;
1794 break;
1795 }
1796 switch( op[j].type ){
1797 case OPT_FLAG:
1798 case OPT_FFLAG:
1799 break;
1800 case OPT_DBL:
1801 *(double*)(op[j].arg) = dv;
1802 break;
1803 case OPT_FDBL:
1804 (*(void(*)())(op[j].arg))(dv);
1805 break;
1806 case OPT_INT:
1807 *(int*)(op[j].arg) = lv;
1808 break;
1809 case OPT_FINT:
1810 (*(void(*)())(op[j].arg))((int)lv);
1811 break;
1812 case OPT_STR:
1813 *(char**)(op[j].arg) = sv;
1814 break;
1815 case OPT_FSTR:
1816 (*(void(*)())(op[j].arg))(sv);
1817 break;
1818 }
1819 }
1820 return errcnt;
1821}
1822
drhb0c86772000-06-02 23:21:26 +00001823int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001824char **a;
1825struct s_options *o;
1826FILE *err;
1827{
1828 int errcnt = 0;
1829 argv = a;
1830 op = o;
1831 errstream = err;
1832 if( argv && *argv && op ){
1833 int i;
1834 for(i=1; argv[i]; i++){
1835 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1836 errcnt += handleflags(i,err);
1837 }else if( strchr(argv[i],'=') ){
1838 errcnt += handleswitch(i,err);
1839 }
1840 }
1841 }
1842 if( errcnt>0 ){
1843 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001844 OptPrint();
drh75897232000-05-29 14:26:00 +00001845 exit(1);
1846 }
1847 return 0;
1848}
1849
drhb0c86772000-06-02 23:21:26 +00001850int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001851 int cnt = 0;
1852 int dashdash = 0;
1853 int i;
1854 if( argv!=0 && argv[0]!=0 ){
1855 for(i=1; argv[i]; i++){
1856 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1857 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1858 }
1859 }
1860 return cnt;
1861}
1862
drhb0c86772000-06-02 23:21:26 +00001863char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001864int n;
1865{
1866 int i;
1867 i = argindex(n);
1868 return i>=0 ? argv[i] : 0;
1869}
1870
drhb0c86772000-06-02 23:21:26 +00001871void OptErr(n)
drh75897232000-05-29 14:26:00 +00001872int n;
1873{
1874 int i;
1875 i = argindex(n);
1876 if( i>=0 ) errline(i,0,errstream);
1877}
1878
drhb0c86772000-06-02 23:21:26 +00001879void OptPrint(){
drh75897232000-05-29 14:26:00 +00001880 int i;
1881 int max, len;
1882 max = 0;
1883 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001884 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001885 switch( op[i].type ){
1886 case OPT_FLAG:
1887 case OPT_FFLAG:
1888 break;
1889 case OPT_INT:
1890 case OPT_FINT:
1891 len += 9; /* length of "<integer>" */
1892 break;
1893 case OPT_DBL:
1894 case OPT_FDBL:
1895 len += 6; /* length of "<real>" */
1896 break;
1897 case OPT_STR:
1898 case OPT_FSTR:
1899 len += 8; /* length of "<string>" */
1900 break;
1901 }
1902 if( len>max ) max = len;
1903 }
1904 for(i=0; op[i].label; i++){
1905 switch( op[i].type ){
1906 case OPT_FLAG:
1907 case OPT_FFLAG:
1908 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1909 break;
1910 case OPT_INT:
1911 case OPT_FINT:
1912 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001913 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001914 break;
1915 case OPT_DBL:
1916 case OPT_FDBL:
1917 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001918 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001919 break;
1920 case OPT_STR:
1921 case OPT_FSTR:
1922 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001923 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001924 break;
1925 }
1926 }
1927}
1928/*********************** From the file "parse.c" ****************************/
1929/*
1930** Input file parser for the LEMON parser generator.
1931*/
1932
1933/* The state of the parser */
1934struct pstate {
1935 char *filename; /* Name of the input file */
1936 int tokenlineno; /* Linenumber at which current token starts */
1937 int errorcnt; /* Number of errors so far */
1938 char *tokenstart; /* Text of current token */
1939 struct lemon *gp; /* Global state vector */
1940 enum e_state {
1941 INITIALIZE,
1942 WAITING_FOR_DECL_OR_RULE,
1943 WAITING_FOR_DECL_KEYWORD,
1944 WAITING_FOR_DECL_ARG,
1945 WAITING_FOR_PRECEDENCE_SYMBOL,
1946 WAITING_FOR_ARROW,
1947 IN_RHS,
1948 LHS_ALIAS_1,
1949 LHS_ALIAS_2,
1950 LHS_ALIAS_3,
1951 RHS_ALIAS_1,
1952 RHS_ALIAS_2,
1953 PRECEDENCE_MARK_1,
1954 PRECEDENCE_MARK_2,
1955 RESYNC_AFTER_RULE_ERROR,
1956 RESYNC_AFTER_DECL_ERROR,
1957 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001958 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001959 WAITING_FOR_FALLBACK_ID,
1960 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001961 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001962 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001963 struct symbol *lhs; /* Left-hand side of current rule */
1964 char *lhsalias; /* Alias for the LHS */
1965 int nrhs; /* Number of right-hand side symbols seen */
1966 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1967 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1968 struct rule *prevrule; /* Previous rule parsed */
1969 char *declkeyword; /* Keyword of a declaration */
1970 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001971 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001972 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001973 enum e_assoc declassoc; /* Assign this association to decl arguments */
1974 int preccounter; /* Assign this precedence to decl arguments */
1975 struct rule *firstrule; /* Pointer to first rule in the grammar */
1976 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1977};
1978
1979/* Parse a single token */
1980static void parseonetoken(psp)
1981struct pstate *psp;
1982{
1983 char *x;
1984 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1985#if 0
1986 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1987 x,psp->state);
1988#endif
1989 switch( psp->state ){
1990 case INITIALIZE:
1991 psp->prevrule = 0;
1992 psp->preccounter = 0;
1993 psp->firstrule = psp->lastrule = 0;
1994 psp->gp->nrule = 0;
1995 /* Fall thru to next case */
1996 case WAITING_FOR_DECL_OR_RULE:
1997 if( x[0]=='%' ){
1998 psp->state = WAITING_FOR_DECL_KEYWORD;
1999 }else if( islower(x[0]) ){
2000 psp->lhs = Symbol_new(x);
2001 psp->nrhs = 0;
2002 psp->lhsalias = 0;
2003 psp->state = WAITING_FOR_ARROW;
2004 }else if( x[0]=='{' ){
2005 if( psp->prevrule==0 ){
2006 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002007"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002008fragment which begins on this line.");
2009 psp->errorcnt++;
2010 }else if( psp->prevrule->code!=0 ){
2011 ErrorMsg(psp->filename,psp->tokenlineno,
2012"Code fragment beginning on this line is not the first \
2013to follow the previous rule.");
2014 psp->errorcnt++;
2015 }else{
2016 psp->prevrule->line = psp->tokenlineno;
2017 psp->prevrule->code = &x[1];
2018 }
2019 }else if( x[0]=='[' ){
2020 psp->state = PRECEDENCE_MARK_1;
2021 }else{
2022 ErrorMsg(psp->filename,psp->tokenlineno,
2023 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2024 x);
2025 psp->errorcnt++;
2026 }
2027 break;
2028 case PRECEDENCE_MARK_1:
2029 if( !isupper(x[0]) ){
2030 ErrorMsg(psp->filename,psp->tokenlineno,
2031 "The precedence symbol must be a terminal.");
2032 psp->errorcnt++;
2033 }else if( psp->prevrule==0 ){
2034 ErrorMsg(psp->filename,psp->tokenlineno,
2035 "There is no prior rule to assign precedence \"[%s]\".",x);
2036 psp->errorcnt++;
2037 }else if( psp->prevrule->precsym!=0 ){
2038 ErrorMsg(psp->filename,psp->tokenlineno,
2039"Precedence mark on this line is not the first \
2040to follow the previous rule.");
2041 psp->errorcnt++;
2042 }else{
2043 psp->prevrule->precsym = Symbol_new(x);
2044 }
2045 psp->state = PRECEDENCE_MARK_2;
2046 break;
2047 case PRECEDENCE_MARK_2:
2048 if( x[0]!=']' ){
2049 ErrorMsg(psp->filename,psp->tokenlineno,
2050 "Missing \"]\" on precedence mark.");
2051 psp->errorcnt++;
2052 }
2053 psp->state = WAITING_FOR_DECL_OR_RULE;
2054 break;
2055 case WAITING_FOR_ARROW:
2056 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2057 psp->state = IN_RHS;
2058 }else if( x[0]=='(' ){
2059 psp->state = LHS_ALIAS_1;
2060 }else{
2061 ErrorMsg(psp->filename,psp->tokenlineno,
2062 "Expected to see a \":\" following the LHS symbol \"%s\".",
2063 psp->lhs->name);
2064 psp->errorcnt++;
2065 psp->state = RESYNC_AFTER_RULE_ERROR;
2066 }
2067 break;
2068 case LHS_ALIAS_1:
2069 if( isalpha(x[0]) ){
2070 psp->lhsalias = x;
2071 psp->state = LHS_ALIAS_2;
2072 }else{
2073 ErrorMsg(psp->filename,psp->tokenlineno,
2074 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2075 x,psp->lhs->name);
2076 psp->errorcnt++;
2077 psp->state = RESYNC_AFTER_RULE_ERROR;
2078 }
2079 break;
2080 case LHS_ALIAS_2:
2081 if( x[0]==')' ){
2082 psp->state = LHS_ALIAS_3;
2083 }else{
2084 ErrorMsg(psp->filename,psp->tokenlineno,
2085 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2086 psp->errorcnt++;
2087 psp->state = RESYNC_AFTER_RULE_ERROR;
2088 }
2089 break;
2090 case LHS_ALIAS_3:
2091 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2092 psp->state = IN_RHS;
2093 }else{
2094 ErrorMsg(psp->filename,psp->tokenlineno,
2095 "Missing \"->\" following: \"%s(%s)\".",
2096 psp->lhs->name,psp->lhsalias);
2097 psp->errorcnt++;
2098 psp->state = RESYNC_AFTER_RULE_ERROR;
2099 }
2100 break;
2101 case IN_RHS:
2102 if( x[0]=='.' ){
2103 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002104 rp = (struct rule *)calloc( sizeof(struct rule) +
2105 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002106 if( rp==0 ){
2107 ErrorMsg(psp->filename,psp->tokenlineno,
2108 "Can't allocate enough memory for this rule.");
2109 psp->errorcnt++;
2110 psp->prevrule = 0;
2111 }else{
2112 int i;
2113 rp->ruleline = psp->tokenlineno;
2114 rp->rhs = (struct symbol**)&rp[1];
2115 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2116 for(i=0; i<psp->nrhs; i++){
2117 rp->rhs[i] = psp->rhs[i];
2118 rp->rhsalias[i] = psp->alias[i];
2119 }
2120 rp->lhs = psp->lhs;
2121 rp->lhsalias = psp->lhsalias;
2122 rp->nrhs = psp->nrhs;
2123 rp->code = 0;
2124 rp->precsym = 0;
2125 rp->index = psp->gp->nrule++;
2126 rp->nextlhs = rp->lhs->rule;
2127 rp->lhs->rule = rp;
2128 rp->next = 0;
2129 if( psp->firstrule==0 ){
2130 psp->firstrule = psp->lastrule = rp;
2131 }else{
2132 psp->lastrule->next = rp;
2133 psp->lastrule = rp;
2134 }
2135 psp->prevrule = rp;
2136 }
2137 psp->state = WAITING_FOR_DECL_OR_RULE;
2138 }else if( isalpha(x[0]) ){
2139 if( psp->nrhs>=MAXRHS ){
2140 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002141 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002142 x);
2143 psp->errorcnt++;
2144 psp->state = RESYNC_AFTER_RULE_ERROR;
2145 }else{
2146 psp->rhs[psp->nrhs] = Symbol_new(x);
2147 psp->alias[psp->nrhs] = 0;
2148 psp->nrhs++;
2149 }
drhfd405312005-11-06 04:06:59 +00002150 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2151 struct symbol *msp = psp->rhs[psp->nrhs-1];
2152 if( msp->type!=MULTITERMINAL ){
2153 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002154 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002155 memset(msp, 0, sizeof(*msp));
2156 msp->type = MULTITERMINAL;
2157 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002158 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002159 msp->subsym[0] = origsp;
2160 msp->name = origsp->name;
2161 psp->rhs[psp->nrhs-1] = msp;
2162 }
2163 msp->nsubsym++;
2164 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2165 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2166 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2167 ErrorMsg(psp->filename,psp->tokenlineno,
2168 "Cannot form a compound containing a non-terminal");
2169 psp->errorcnt++;
2170 }
drh75897232000-05-29 14:26:00 +00002171 }else if( x[0]=='(' && psp->nrhs>0 ){
2172 psp->state = RHS_ALIAS_1;
2173 }else{
2174 ErrorMsg(psp->filename,psp->tokenlineno,
2175 "Illegal character on RHS of rule: \"%s\".",x);
2176 psp->errorcnt++;
2177 psp->state = RESYNC_AFTER_RULE_ERROR;
2178 }
2179 break;
2180 case RHS_ALIAS_1:
2181 if( isalpha(x[0]) ){
2182 psp->alias[psp->nrhs-1] = x;
2183 psp->state = RHS_ALIAS_2;
2184 }else{
2185 ErrorMsg(psp->filename,psp->tokenlineno,
2186 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2187 x,psp->rhs[psp->nrhs-1]->name);
2188 psp->errorcnt++;
2189 psp->state = RESYNC_AFTER_RULE_ERROR;
2190 }
2191 break;
2192 case RHS_ALIAS_2:
2193 if( x[0]==')' ){
2194 psp->state = IN_RHS;
2195 }else{
2196 ErrorMsg(psp->filename,psp->tokenlineno,
2197 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2198 psp->errorcnt++;
2199 psp->state = RESYNC_AFTER_RULE_ERROR;
2200 }
2201 break;
2202 case WAITING_FOR_DECL_KEYWORD:
2203 if( isalpha(x[0]) ){
2204 psp->declkeyword = x;
2205 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002206 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002207 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002208 psp->state = WAITING_FOR_DECL_ARG;
2209 if( strcmp(x,"name")==0 ){
2210 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002211 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002212 }else if( strcmp(x,"include")==0 ){
2213 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002214 }else if( strcmp(x,"code")==0 ){
2215 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002216 }else if( strcmp(x,"token_destructor")==0 ){
2217 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002218 }else if( strcmp(x,"default_destructor")==0 ){
2219 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002220 }else if( strcmp(x,"token_prefix")==0 ){
2221 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002222 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002223 }else if( strcmp(x,"syntax_error")==0 ){
2224 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002225 }else if( strcmp(x,"parse_accept")==0 ){
2226 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002227 }else if( strcmp(x,"parse_failure")==0 ){
2228 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002229 }else if( strcmp(x,"stack_overflow")==0 ){
2230 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002231 }else if( strcmp(x,"extra_argument")==0 ){
2232 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002233 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002234 }else if( strcmp(x,"token_type")==0 ){
2235 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002236 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002237 }else if( strcmp(x,"default_type")==0 ){
2238 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002239 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002240 }else if( strcmp(x,"stack_size")==0 ){
2241 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002242 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002243 }else if( strcmp(x,"start_symbol")==0 ){
2244 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002245 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002246 }else if( strcmp(x,"left")==0 ){
2247 psp->preccounter++;
2248 psp->declassoc = LEFT;
2249 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2250 }else if( strcmp(x,"right")==0 ){
2251 psp->preccounter++;
2252 psp->declassoc = RIGHT;
2253 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2254 }else if( strcmp(x,"nonassoc")==0 ){
2255 psp->preccounter++;
2256 psp->declassoc = NONE;
2257 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2258 }else if( strcmp(x,"destructor")==0 ){
2259 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2260 }else if( strcmp(x,"type")==0 ){
2261 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002262 }else if( strcmp(x,"fallback")==0 ){
2263 psp->fallback = 0;
2264 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002265 }else if( strcmp(x,"wildcard")==0 ){
2266 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002267 }else{
2268 ErrorMsg(psp->filename,psp->tokenlineno,
2269 "Unknown declaration keyword: \"%%%s\".",x);
2270 psp->errorcnt++;
2271 psp->state = RESYNC_AFTER_DECL_ERROR;
2272 }
2273 }else{
2274 ErrorMsg(psp->filename,psp->tokenlineno,
2275 "Illegal declaration keyword: \"%s\".",x);
2276 psp->errorcnt++;
2277 psp->state = RESYNC_AFTER_DECL_ERROR;
2278 }
2279 break;
2280 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2281 if( !isalpha(x[0]) ){
2282 ErrorMsg(psp->filename,psp->tokenlineno,
2283 "Symbol name missing after %destructor keyword");
2284 psp->errorcnt++;
2285 psp->state = RESYNC_AFTER_DECL_ERROR;
2286 }else{
2287 struct symbol *sp = Symbol_new(x);
2288 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002289 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002290 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002291 psp->state = WAITING_FOR_DECL_ARG;
2292 }
2293 break;
2294 case WAITING_FOR_DATATYPE_SYMBOL:
2295 if( !isalpha(x[0]) ){
2296 ErrorMsg(psp->filename,psp->tokenlineno,
2297 "Symbol name missing after %destructor keyword");
2298 psp->errorcnt++;
2299 psp->state = RESYNC_AFTER_DECL_ERROR;
2300 }else{
2301 struct symbol *sp = Symbol_new(x);
2302 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002303 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002304 psp->state = WAITING_FOR_DECL_ARG;
2305 }
2306 break;
2307 case WAITING_FOR_PRECEDENCE_SYMBOL:
2308 if( x[0]=='.' ){
2309 psp->state = WAITING_FOR_DECL_OR_RULE;
2310 }else if( isupper(x[0]) ){
2311 struct symbol *sp;
2312 sp = Symbol_new(x);
2313 if( sp->prec>=0 ){
2314 ErrorMsg(psp->filename,psp->tokenlineno,
2315 "Symbol \"%s\" has already be given a precedence.",x);
2316 psp->errorcnt++;
2317 }else{
2318 sp->prec = psp->preccounter;
2319 sp->assoc = psp->declassoc;
2320 }
2321 }else{
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "Can't assign a precedence to \"%s\".",x);
2324 psp->errorcnt++;
2325 }
2326 break;
2327 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002328 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2329 char *zOld, *zNew, *zBuf, *z;
2330 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002331 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002332 char zLine[50];
2333 zNew = x;
2334 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002335 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002336 if( *psp->declargslot ){
2337 zOld = *psp->declargslot;
2338 }else{
2339 zOld = "";
2340 }
drh87cf1372008-08-13 20:09:06 +00002341 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002342 n = nOld + nNew + 20;
drhb5bd49e2008-07-14 12:21:08 +00002343 addLineMacro = psp->insertLineMacro &&
2344 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2345 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002346 for(z=psp->filename, nBack=0; *z; z++){
2347 if( *z=='\\' ) nBack++;
2348 }
2349 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002350 nLine = lemonStrlen(zLine);
2351 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002352 }
2353 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2354 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002355 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002356 if( nOld && zBuf[-1]!='\n' ){
2357 *(zBuf++) = '\n';
2358 }
2359 memcpy(zBuf, zLine, nLine);
2360 zBuf += nLine;
2361 *(zBuf++) = '"';
2362 for(z=psp->filename; *z; z++){
2363 if( *z=='\\' ){
2364 *(zBuf++) = '\\';
2365 }
2366 *(zBuf++) = *z;
2367 }
2368 *(zBuf++) = '"';
2369 *(zBuf++) = '\n';
2370 }
drh4dc8ef52008-07-01 17:13:57 +00002371 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2372 psp->decllinenoslot[0] = psp->tokenlineno;
2373 }
drha5808f32008-04-27 22:19:44 +00002374 memcpy(zBuf, zNew, nNew);
2375 zBuf += nNew;
2376 *zBuf = 0;
2377 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002378 }else{
2379 ErrorMsg(psp->filename,psp->tokenlineno,
2380 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2381 psp->errorcnt++;
2382 psp->state = RESYNC_AFTER_DECL_ERROR;
2383 }
2384 break;
drh0bd1f4e2002-06-06 18:54:39 +00002385 case WAITING_FOR_FALLBACK_ID:
2386 if( x[0]=='.' ){
2387 psp->state = WAITING_FOR_DECL_OR_RULE;
2388 }else if( !isupper(x[0]) ){
2389 ErrorMsg(psp->filename, psp->tokenlineno,
2390 "%%fallback argument \"%s\" should be a token", x);
2391 psp->errorcnt++;
2392 }else{
2393 struct symbol *sp = Symbol_new(x);
2394 if( psp->fallback==0 ){
2395 psp->fallback = sp;
2396 }else if( sp->fallback ){
2397 ErrorMsg(psp->filename, psp->tokenlineno,
2398 "More than one fallback assigned to token %s", x);
2399 psp->errorcnt++;
2400 }else{
2401 sp->fallback = psp->fallback;
2402 psp->gp->has_fallback = 1;
2403 }
2404 }
2405 break;
drhe09daa92006-06-10 13:29:31 +00002406 case WAITING_FOR_WILDCARD_ID:
2407 if( x[0]=='.' ){
2408 psp->state = WAITING_FOR_DECL_OR_RULE;
2409 }else if( !isupper(x[0]) ){
2410 ErrorMsg(psp->filename, psp->tokenlineno,
2411 "%%wildcard argument \"%s\" should be a token", x);
2412 psp->errorcnt++;
2413 }else{
2414 struct symbol *sp = Symbol_new(x);
2415 if( psp->gp->wildcard==0 ){
2416 psp->gp->wildcard = sp;
2417 }else{
2418 ErrorMsg(psp->filename, psp->tokenlineno,
2419 "Extra wildcard to token: %s", x);
2420 psp->errorcnt++;
2421 }
2422 }
2423 break;
drh75897232000-05-29 14:26:00 +00002424 case RESYNC_AFTER_RULE_ERROR:
2425/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2426** break; */
2427 case RESYNC_AFTER_DECL_ERROR:
2428 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2429 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2430 break;
2431 }
2432}
2433
drh34ff57b2008-07-14 12:27:51 +00002434/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002435** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2436** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2437** comments them out. Text in between is also commented out as appropriate.
2438*/
danielk1977940fac92005-01-23 22:41:37 +00002439static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002440 int i, j, k, n;
2441 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002442 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002443 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002444 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002445 for(i=0; z[i]; i++){
2446 if( z[i]=='\n' ) lineno++;
2447 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2448 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2449 if( exclude ){
2450 exclude--;
2451 if( exclude==0 ){
2452 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2453 }
2454 }
2455 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2456 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2457 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2458 if( exclude ){
2459 exclude++;
2460 }else{
2461 for(j=i+7; isspace(z[j]); j++){}
2462 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2463 exclude = 1;
2464 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002465 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002466 exclude = 0;
2467 break;
2468 }
2469 }
2470 if( z[i+3]=='n' ) exclude = !exclude;
2471 if( exclude ){
2472 start = i;
2473 start_lineno = lineno;
2474 }
2475 }
2476 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2477 }
2478 }
2479 if( exclude ){
2480 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2481 exit(1);
2482 }
2483}
2484
drh75897232000-05-29 14:26:00 +00002485/* In spite of its name, this function is really a scanner. It read
2486** in the entire input file (all at once) then tokenizes it. Each
2487** token is passed to the function "parseonetoken" which builds all
2488** the appropriate data structures in the global state vector "gp".
2489*/
2490void Parse(gp)
2491struct lemon *gp;
2492{
2493 struct pstate ps;
2494 FILE *fp;
2495 char *filebuf;
2496 int filesize;
2497 int lineno;
2498 int c;
2499 char *cp, *nextcp;
2500 int startline = 0;
2501
rse38514a92007-09-20 11:34:17 +00002502 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002503 ps.gp = gp;
2504 ps.filename = gp->filename;
2505 ps.errorcnt = 0;
2506 ps.state = INITIALIZE;
2507
2508 /* Begin by reading the input file */
2509 fp = fopen(ps.filename,"rb");
2510 if( fp==0 ){
2511 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2512 gp->errorcnt++;
2513 return;
2514 }
2515 fseek(fp,0,2);
2516 filesize = ftell(fp);
2517 rewind(fp);
2518 filebuf = (char *)malloc( filesize+1 );
2519 if( filebuf==0 ){
2520 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2521 filesize+1);
2522 gp->errorcnt++;
2523 return;
2524 }
2525 if( fread(filebuf,1,filesize,fp)!=filesize ){
2526 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2527 filesize);
2528 free(filebuf);
2529 gp->errorcnt++;
2530 return;
2531 }
2532 fclose(fp);
2533 filebuf[filesize] = 0;
2534
drh6d08b4d2004-07-20 12:45:22 +00002535 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2536 preprocess_input(filebuf);
2537
drh75897232000-05-29 14:26:00 +00002538 /* Now scan the text of the input file */
2539 lineno = 1;
2540 for(cp=filebuf; (c= *cp)!=0; ){
2541 if( c=='\n' ) lineno++; /* Keep track of the line number */
2542 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2543 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2544 cp+=2;
2545 while( (c= *cp)!=0 && c!='\n' ) cp++;
2546 continue;
2547 }
2548 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2549 cp+=2;
2550 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2551 if( c=='\n' ) lineno++;
2552 cp++;
2553 }
2554 if( c ) cp++;
2555 continue;
2556 }
2557 ps.tokenstart = cp; /* Mark the beginning of the token */
2558 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2559 if( c=='\"' ){ /* String literals */
2560 cp++;
2561 while( (c= *cp)!=0 && c!='\"' ){
2562 if( c=='\n' ) lineno++;
2563 cp++;
2564 }
2565 if( c==0 ){
2566 ErrorMsg(ps.filename,startline,
2567"String starting on this line is not terminated before the end of the file.");
2568 ps.errorcnt++;
2569 nextcp = cp;
2570 }else{
2571 nextcp = cp+1;
2572 }
2573 }else if( c=='{' ){ /* A block of C code */
2574 int level;
2575 cp++;
2576 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2577 if( c=='\n' ) lineno++;
2578 else if( c=='{' ) level++;
2579 else if( c=='}' ) level--;
2580 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2581 int prevc;
2582 cp = &cp[2];
2583 prevc = 0;
2584 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2585 if( c=='\n' ) lineno++;
2586 prevc = c;
2587 cp++;
2588 }
2589 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2590 cp = &cp[2];
2591 while( (c= *cp)!=0 && c!='\n' ) cp++;
2592 if( c ) lineno++;
2593 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2594 int startchar, prevc;
2595 startchar = c;
2596 prevc = 0;
2597 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2598 if( c=='\n' ) lineno++;
2599 if( prevc=='\\' ) prevc = 0;
2600 else prevc = c;
2601 }
2602 }
2603 }
2604 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002605 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002606"C code starting on this line is not terminated before the end of the file.");
2607 ps.errorcnt++;
2608 nextcp = cp;
2609 }else{
2610 nextcp = cp+1;
2611 }
2612 }else if( isalnum(c) ){ /* Identifiers */
2613 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2614 nextcp = cp;
2615 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2616 cp += 3;
2617 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002618 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2619 cp += 2;
2620 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2621 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002622 }else{ /* All other (one character) operators */
2623 cp++;
2624 nextcp = cp;
2625 }
2626 c = *cp;
2627 *cp = 0; /* Null terminate the token */
2628 parseonetoken(&ps); /* Parse the token */
2629 *cp = c; /* Restore the buffer */
2630 cp = nextcp;
2631 }
2632 free(filebuf); /* Release the buffer after parsing */
2633 gp->rule = ps.firstrule;
2634 gp->errorcnt = ps.errorcnt;
2635}
2636/*************************** From the file "plink.c" *********************/
2637/*
2638** Routines processing configuration follow-set propagation links
2639** in the LEMON parser generator.
2640*/
2641static struct plink *plink_freelist = 0;
2642
2643/* Allocate a new plink */
2644struct plink *Plink_new(){
2645 struct plink *new;
2646
2647 if( plink_freelist==0 ){
2648 int i;
2649 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002650 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002651 if( plink_freelist==0 ){
2652 fprintf(stderr,
2653 "Unable to allocate memory for a new follow-set propagation link.\n");
2654 exit(1);
2655 }
2656 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2657 plink_freelist[amt-1].next = 0;
2658 }
2659 new = plink_freelist;
2660 plink_freelist = plink_freelist->next;
2661 return new;
2662}
2663
2664/* Add a plink to a plink list */
2665void Plink_add(plpp,cfp)
2666struct plink **plpp;
2667struct config *cfp;
2668{
2669 struct plink *new;
2670 new = Plink_new();
2671 new->next = *plpp;
2672 *plpp = new;
2673 new->cfp = cfp;
2674}
2675
2676/* Transfer every plink on the list "from" to the list "to" */
2677void Plink_copy(to,from)
2678struct plink **to;
2679struct plink *from;
2680{
2681 struct plink *nextpl;
2682 while( from ){
2683 nextpl = from->next;
2684 from->next = *to;
2685 *to = from;
2686 from = nextpl;
2687 }
2688}
2689
2690/* Delete every plink on the list */
2691void Plink_delete(plp)
2692struct plink *plp;
2693{
2694 struct plink *nextpl;
2695
2696 while( plp ){
2697 nextpl = plp->next;
2698 plp->next = plink_freelist;
2699 plink_freelist = plp;
2700 plp = nextpl;
2701 }
2702}
2703/*********************** From the file "report.c" **************************/
2704/*
2705** Procedures for generating reports and tables in the LEMON parser generator.
2706*/
2707
2708/* Generate a filename with the given suffix. Space to hold the
2709** name comes from malloc() and must be freed by the calling
2710** function.
2711*/
2712PRIVATE char *file_makename(lemp,suffix)
2713struct lemon *lemp;
2714char *suffix;
2715{
2716 char *name;
2717 char *cp;
2718
drh87cf1372008-08-13 20:09:06 +00002719 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002720 if( name==0 ){
2721 fprintf(stderr,"Can't allocate space for a filename.\n");
2722 exit(1);
2723 }
2724 strcpy(name,lemp->filename);
2725 cp = strrchr(name,'.');
2726 if( cp ) *cp = 0;
2727 strcat(name,suffix);
2728 return name;
2729}
2730
2731/* Open a file with a name based on the name of the input file,
2732** but with a different (specified) suffix, and return a pointer
2733** to the stream */
2734PRIVATE FILE *file_open(lemp,suffix,mode)
2735struct lemon *lemp;
2736char *suffix;
2737char *mode;
2738{
2739 FILE *fp;
2740
2741 if( lemp->outname ) free(lemp->outname);
2742 lemp->outname = file_makename(lemp, suffix);
2743 fp = fopen(lemp->outname,mode);
2744 if( fp==0 && *mode=='w' ){
2745 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2746 lemp->errorcnt++;
2747 return 0;
2748 }
2749 return fp;
2750}
2751
2752/* Duplicate the input file without comments and without actions
2753** on rules */
2754void Reprint(lemp)
2755struct lemon *lemp;
2756{
2757 struct rule *rp;
2758 struct symbol *sp;
2759 int i, j, maxlen, len, ncolumns, skip;
2760 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2761 maxlen = 10;
2762 for(i=0; i<lemp->nsymbol; i++){
2763 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002764 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002765 if( len>maxlen ) maxlen = len;
2766 }
2767 ncolumns = 76/(maxlen+5);
2768 if( ncolumns<1 ) ncolumns = 1;
2769 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2770 for(i=0; i<skip; i++){
2771 printf("//");
2772 for(j=i; j<lemp->nsymbol; j+=skip){
2773 sp = lemp->symbols[j];
2774 assert( sp->index==j );
2775 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2776 }
2777 printf("\n");
2778 }
2779 for(rp=lemp->rule; rp; rp=rp->next){
2780 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002781 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002782 printf(" ::=");
2783 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002784 sp = rp->rhs[i];
2785 printf(" %s", sp->name);
2786 if( sp->type==MULTITERMINAL ){
2787 for(j=1; j<sp->nsubsym; j++){
2788 printf("|%s", sp->subsym[j]->name);
2789 }
2790 }
2791 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002792 }
2793 printf(".");
2794 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002795 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002796 printf("\n");
2797 }
2798}
2799
2800void ConfigPrint(fp,cfp)
2801FILE *fp;
2802struct config *cfp;
2803{
2804 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002805 struct symbol *sp;
2806 int i, j;
drh75897232000-05-29 14:26:00 +00002807 rp = cfp->rp;
2808 fprintf(fp,"%s ::=",rp->lhs->name);
2809 for(i=0; i<=rp->nrhs; i++){
2810 if( i==cfp->dot ) fprintf(fp," *");
2811 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002812 sp = rp->rhs[i];
2813 fprintf(fp," %s", sp->name);
2814 if( sp->type==MULTITERMINAL ){
2815 for(j=1; j<sp->nsubsym; j++){
2816 fprintf(fp,"|%s",sp->subsym[j]->name);
2817 }
2818 }
drh75897232000-05-29 14:26:00 +00002819 }
2820}
2821
2822/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002823#if 0
drh75897232000-05-29 14:26:00 +00002824/* Print a set */
2825PRIVATE void SetPrint(out,set,lemp)
2826FILE *out;
2827char *set;
2828struct lemon *lemp;
2829{
2830 int i;
2831 char *spacer;
2832 spacer = "";
2833 fprintf(out,"%12s[","");
2834 for(i=0; i<lemp->nterminal; i++){
2835 if( SetFind(set,i) ){
2836 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2837 spacer = " ";
2838 }
2839 }
2840 fprintf(out,"]\n");
2841}
2842
2843/* Print a plink chain */
2844PRIVATE void PlinkPrint(out,plp,tag)
2845FILE *out;
2846struct plink *plp;
2847char *tag;
2848{
2849 while( plp ){
drhada354d2005-11-05 15:03:59 +00002850 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002851 ConfigPrint(out,plp->cfp);
2852 fprintf(out,"\n");
2853 plp = plp->next;
2854 }
2855}
2856#endif
2857
2858/* Print an action to the given file descriptor. Return FALSE if
2859** nothing was actually printed.
2860*/
2861int PrintAction(struct action *ap, FILE *fp, int indent){
2862 int result = 1;
2863 switch( ap->type ){
2864 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002865 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002866 break;
2867 case REDUCE:
2868 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2869 break;
2870 case ACCEPT:
2871 fprintf(fp,"%*s accept",indent,ap->sp->name);
2872 break;
2873 case ERROR:
2874 fprintf(fp,"%*s error",indent,ap->sp->name);
2875 break;
drh9892c5d2007-12-21 00:02:11 +00002876 case SRCONFLICT:
2877 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002878 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2879 indent,ap->sp->name,ap->x.rp->index);
2880 break;
drh9892c5d2007-12-21 00:02:11 +00002881 case SSCONFLICT:
2882 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2883 indent,ap->sp->name,ap->x.stp->statenum);
2884 break;
drh75897232000-05-29 14:26:00 +00002885 case SH_RESOLVED:
2886 case RD_RESOLVED:
2887 case NOT_USED:
2888 result = 0;
2889 break;
2890 }
2891 return result;
2892}
2893
2894/* Generate the "y.output" log file */
2895void ReportOutput(lemp)
2896struct lemon *lemp;
2897{
2898 int i;
2899 struct state *stp;
2900 struct config *cfp;
2901 struct action *ap;
2902 FILE *fp;
2903
drh2aa6ca42004-09-10 00:14:04 +00002904 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002905 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002906 for(i=0; i<lemp->nstate; i++){
2907 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002908 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002909 if( lemp->basisflag ) cfp=stp->bp;
2910 else cfp=stp->cfp;
2911 while( cfp ){
2912 char buf[20];
2913 if( cfp->dot==cfp->rp->nrhs ){
2914 sprintf(buf,"(%d)",cfp->rp->index);
2915 fprintf(fp," %5s ",buf);
2916 }else{
2917 fprintf(fp," ");
2918 }
2919 ConfigPrint(fp,cfp);
2920 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002921#if 0
drh75897232000-05-29 14:26:00 +00002922 SetPrint(fp,cfp->fws,lemp);
2923 PlinkPrint(fp,cfp->fplp,"To ");
2924 PlinkPrint(fp,cfp->bplp,"From");
2925#endif
2926 if( lemp->basisflag ) cfp=cfp->bp;
2927 else cfp=cfp->next;
2928 }
2929 fprintf(fp,"\n");
2930 for(ap=stp->ap; ap; ap=ap->next){
2931 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2932 }
2933 fprintf(fp,"\n");
2934 }
drhe9278182007-07-18 18:16:29 +00002935 fprintf(fp, "----------------------------------------------------\n");
2936 fprintf(fp, "Symbols:\n");
2937 for(i=0; i<lemp->nsymbol; i++){
2938 int j;
2939 struct symbol *sp;
2940
2941 sp = lemp->symbols[i];
2942 fprintf(fp, " %3d: %s", i, sp->name);
2943 if( sp->type==NONTERMINAL ){
2944 fprintf(fp, ":");
2945 if( sp->lambda ){
2946 fprintf(fp, " <lambda>");
2947 }
2948 for(j=0; j<lemp->nterminal; j++){
2949 if( sp->firstset && SetFind(sp->firstset, j) ){
2950 fprintf(fp, " %s", lemp->symbols[j]->name);
2951 }
2952 }
2953 }
2954 fprintf(fp, "\n");
2955 }
drh75897232000-05-29 14:26:00 +00002956 fclose(fp);
2957 return;
2958}
2959
2960/* Search for the file "name" which is in the same directory as
2961** the exacutable */
2962PRIVATE char *pathsearch(argv0,name,modemask)
2963char *argv0;
2964char *name;
2965int modemask;
2966{
2967 char *pathlist;
2968 char *path,*cp;
2969 char c;
drh75897232000-05-29 14:26:00 +00002970
2971#ifdef __WIN32__
2972 cp = strrchr(argv0,'\\');
2973#else
2974 cp = strrchr(argv0,'/');
2975#endif
2976 if( cp ){
2977 c = *cp;
2978 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00002979 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00002980 if( path ) sprintf(path,"%s/%s",argv0,name);
2981 *cp = c;
2982 }else{
2983 extern char *getenv();
2984 pathlist = getenv("PATH");
2985 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00002986 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00002987 if( path!=0 ){
2988 while( *pathlist ){
2989 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00002990 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00002991 c = *cp;
2992 *cp = 0;
2993 sprintf(path,"%s/%s",pathlist,name);
2994 *cp = c;
2995 if( c==0 ) pathlist = "";
2996 else pathlist = &cp[1];
2997 if( access(path,modemask)==0 ) break;
2998 }
2999 }
3000 }
3001 return path;
3002}
3003
3004/* Given an action, compute the integer value for that action
3005** which is to be put in the action table of the generated machine.
3006** Return negative if no action should be generated.
3007*/
3008PRIVATE int compute_action(lemp,ap)
3009struct lemon *lemp;
3010struct action *ap;
3011{
3012 int act;
3013 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003014 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003015 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3016 case ERROR: act = lemp->nstate + lemp->nrule; break;
3017 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3018 default: act = -1; break;
3019 }
3020 return act;
3021}
3022
3023#define LINESIZE 1000
3024/* The next cluster of routines are for reading the template file
3025** and writing the results to the generated parser */
3026/* The first function transfers data from "in" to "out" until
3027** a line is seen which begins with "%%". The line number is
3028** tracked.
3029**
3030** if name!=0, then any word that begin with "Parse" is changed to
3031** begin with *name instead.
3032*/
3033PRIVATE void tplt_xfer(name,in,out,lineno)
3034char *name;
3035FILE *in;
3036FILE *out;
3037int *lineno;
3038{
3039 int i, iStart;
3040 char line[LINESIZE];
3041 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3042 (*lineno)++;
3043 iStart = 0;
3044 if( name ){
3045 for(i=0; line[i]; i++){
3046 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3047 && (i==0 || !isalpha(line[i-1]))
3048 ){
3049 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3050 fprintf(out,"%s",name);
3051 i += 4;
3052 iStart = i+1;
3053 }
3054 }
3055 }
3056 fprintf(out,"%s",&line[iStart]);
3057 }
3058}
3059
3060/* The next function finds the template file and opens it, returning
3061** a pointer to the opened file. */
3062PRIVATE FILE *tplt_open(lemp)
3063struct lemon *lemp;
3064{
3065 static char templatename[] = "lempar.c";
3066 char buf[1000];
3067 FILE *in;
3068 char *tpltname;
3069 char *cp;
3070
3071 cp = strrchr(lemp->filename,'.');
3072 if( cp ){
drh8b582012003-10-21 13:16:03 +00003073 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003074 }else{
3075 sprintf(buf,"%s.lt",lemp->filename);
3076 }
3077 if( access(buf,004)==0 ){
3078 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003079 }else if( access(templatename,004)==0 ){
3080 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003081 }else{
3082 tpltname = pathsearch(lemp->argv0,templatename,0);
3083 }
3084 if( tpltname==0 ){
3085 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3086 templatename);
3087 lemp->errorcnt++;
3088 return 0;
3089 }
drh2aa6ca42004-09-10 00:14:04 +00003090 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003091 if( in==0 ){
3092 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3093 lemp->errorcnt++;
3094 return 0;
3095 }
3096 return in;
3097}
3098
drhaf805ca2004-09-07 11:28:25 +00003099/* Print a #line directive line to the output file. */
3100PRIVATE void tplt_linedir(out,lineno,filename)
3101FILE *out;
3102int lineno;
3103char *filename;
3104{
3105 fprintf(out,"#line %d \"",lineno);
3106 while( *filename ){
3107 if( *filename == '\\' ) putc('\\',out);
3108 putc(*filename,out);
3109 filename++;
3110 }
3111 fprintf(out,"\"\n");
3112}
3113
drh75897232000-05-29 14:26:00 +00003114/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003115PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003116FILE *out;
3117struct lemon *lemp;
3118char *str;
drh75897232000-05-29 14:26:00 +00003119int *lineno;
3120{
3121 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003122 (*lineno)++;
drh75897232000-05-29 14:26:00 +00003123 while( *str ){
3124 if( *str=='\n' ) (*lineno)++;
3125 putc(*str,out);
3126 str++;
3127 }
drh9db55df2004-09-09 14:01:21 +00003128 if( str[-1]!='\n' ){
3129 putc('\n',out);
3130 (*lineno)++;
3131 }
drhaf805ca2004-09-07 11:28:25 +00003132 tplt_linedir(out,*lineno+2,lemp->outname);
3133 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00003134 return;
3135}
3136
3137/*
3138** The following routine emits code for the destructor for the
3139** symbol sp
3140*/
3141void emit_destructor_code(out,sp,lemp,lineno)
3142FILE *out;
3143struct symbol *sp;
3144struct lemon *lemp;
3145int *lineno;
3146{
drhcc83b6e2004-04-23 23:38:42 +00003147 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003148
3149 int linecnt = 0;
3150 if( sp->type==TERMINAL ){
3151 cp = lemp->tokendest;
3152 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003153 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003154 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003155 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003156 fprintf(out,"{\n"); (*lineno)++;
drh633e6d52008-07-28 19:34:53 +00003157 tplt_linedir(out,sp->destLineno,lemp->filename); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003158 }else if( lemp->vardest ){
3159 cp = lemp->vardest;
3160 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003161 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003162 }else{
3163 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003164 }
3165 for(; *cp; cp++){
3166 if( *cp=='$' && cp[1]=='$' ){
3167 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3168 cp++;
3169 continue;
3170 }
3171 if( *cp=='\n' ) linecnt++;
3172 fputc(*cp,out);
3173 }
3174 (*lineno) += 3 + linecnt;
drha5808f32008-04-27 22:19:44 +00003175 fprintf(out,"\n");
drhaf805ca2004-09-07 11:28:25 +00003176 tplt_linedir(out,*lineno,lemp->outname);
drha5808f32008-04-27 22:19:44 +00003177 fprintf(out,"}\n");
drh75897232000-05-29 14:26:00 +00003178 return;
3179}
3180
3181/*
drh960e8c62001-04-03 16:53:21 +00003182** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003183*/
3184int has_destructor(sp, lemp)
3185struct symbol *sp;
3186struct lemon *lemp;
3187{
3188 int ret;
3189 if( sp->type==TERMINAL ){
3190 ret = lemp->tokendest!=0;
3191 }else{
drh960e8c62001-04-03 16:53:21 +00003192 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003193 }
3194 return ret;
3195}
3196
drh0bb132b2004-07-20 14:06:51 +00003197/*
3198** Append text to a dynamically allocated string. If zText is 0 then
3199** reset the string to be empty again. Always return the complete text
3200** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003201**
3202** n bytes of zText are stored. If n==0 then all of zText up to the first
3203** \000 terminator is stored. zText can contain up to two instances of
3204** %d. The values of p1 and p2 are written into the first and second
3205** %d.
3206**
3207** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003208*/
3209PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3210 static char *z = 0;
3211 static int alloced = 0;
3212 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003213 int c;
drh0bb132b2004-07-20 14:06:51 +00003214 char zInt[40];
3215
3216 if( zText==0 ){
3217 used = 0;
3218 return z;
3219 }
drh7ac25c72004-08-19 15:12:26 +00003220 if( n<=0 ){
3221 if( n<0 ){
3222 used += n;
3223 assert( used>=0 );
3224 }
drh87cf1372008-08-13 20:09:06 +00003225 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003226 }
drh0bb132b2004-07-20 14:06:51 +00003227 if( n+sizeof(zInt)*2+used >= alloced ){
3228 alloced = n + sizeof(zInt)*2 + used + 200;
3229 z = realloc(z, alloced);
3230 }
3231 if( z==0 ) return "";
3232 while( n-- > 0 ){
3233 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003234 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003235 sprintf(zInt, "%d", p1);
3236 p1 = p2;
3237 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003238 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003239 zText++;
3240 n--;
3241 }else{
3242 z[used++] = c;
3243 }
3244 }
3245 z[used] = 0;
3246 return z;
3247}
3248
3249/*
3250** zCode is a string that is the action associated with a rule. Expand
3251** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003252** stack.
drh0bb132b2004-07-20 14:06:51 +00003253*/
drhaf805ca2004-09-07 11:28:25 +00003254PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003255 char *cp, *xp;
3256 int i;
3257 char lhsused = 0; /* True if the LHS element has been used */
3258 char used[MAXRHS]; /* True for each RHS element which is used */
3259
3260 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3261 lhsused = 0;
3262
drh19c9e562007-03-29 20:13:53 +00003263 if( rp->code==0 ){
3264 rp->code = "\n";
3265 rp->line = rp->ruleline;
3266 }
3267
drh0bb132b2004-07-20 14:06:51 +00003268 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003269 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003270 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3271 char saved;
3272 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3273 saved = *xp;
3274 *xp = 0;
3275 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003276 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003277 cp = xp;
3278 lhsused = 1;
3279 }else{
3280 for(i=0; i<rp->nrhs; i++){
3281 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003282 if( cp!=rp->code && cp[-1]=='@' ){
3283 /* If the argument is of the form @X then substituted
3284 ** the token number of X, not the value of X */
3285 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3286 }else{
drhfd405312005-11-06 04:06:59 +00003287 struct symbol *sp = rp->rhs[i];
3288 int dtnum;
3289 if( sp->type==MULTITERMINAL ){
3290 dtnum = sp->subsym[0]->dtnum;
3291 }else{
3292 dtnum = sp->dtnum;
3293 }
3294 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003295 }
drh0bb132b2004-07-20 14:06:51 +00003296 cp = xp;
3297 used[i] = 1;
3298 break;
3299 }
3300 }
3301 }
3302 *xp = saved;
3303 }
3304 append_str(cp, 1, 0, 0);
3305 } /* End loop */
3306
3307 /* Check to make sure the LHS has been used */
3308 if( rp->lhsalias && !lhsused ){
3309 ErrorMsg(lemp->filename,rp->ruleline,
3310 "Label \"%s\" for \"%s(%s)\" is never used.",
3311 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3312 lemp->errorcnt++;
3313 }
3314
3315 /* Generate destructor code for RHS symbols which are not used in the
3316 ** reduce code */
3317 for(i=0; i<rp->nrhs; i++){
3318 if( rp->rhsalias[i] && !used[i] ){
3319 ErrorMsg(lemp->filename,rp->ruleline,
3320 "Label %s for \"%s(%s)\" is never used.",
3321 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3322 lemp->errorcnt++;
3323 }else if( rp->rhsalias[i]==0 ){
3324 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003325 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003326 rp->rhs[i]->index,i-rp->nrhs+1);
3327 }else{
3328 /* No destructor defined for this term */
3329 }
3330 }
3331 }
drh61e339a2007-01-16 03:09:02 +00003332 if( rp->code ){
3333 cp = append_str(0,0,0,0);
3334 rp->code = Strsafe(cp?cp:"");
3335 }
drh0bb132b2004-07-20 14:06:51 +00003336}
3337
drh75897232000-05-29 14:26:00 +00003338/*
3339** Generate code which executes when the rule "rp" is reduced. Write
3340** the code to "out". Make sure lineno stays up-to-date.
3341*/
3342PRIVATE void emit_code(out,rp,lemp,lineno)
3343FILE *out;
3344struct rule *rp;
3345struct lemon *lemp;
3346int *lineno;
3347{
drh0bb132b2004-07-20 14:06:51 +00003348 char *cp;
drh75897232000-05-29 14:26:00 +00003349 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003350
3351 /* Generate code to do the reduce action */
3352 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003353 tplt_linedir(out,rp->line,lemp->filename);
3354 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003355 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003356 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003357 } /* End loop */
3358 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003359 fprintf(out,"}\n");
3360 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003361 } /* End if( rp->code ) */
3362
drh75897232000-05-29 14:26:00 +00003363 return;
3364}
3365
3366/*
3367** Print the definition of the union used for the parser's data stack.
3368** This union contains fields for every possible data type for tokens
3369** and nonterminals. In the process of computing and printing this
3370** union, also set the ".dtnum" field of every terminal and nonterminal
3371** symbol.
3372*/
3373void print_stack_union(out,lemp,plineno,mhflag)
3374FILE *out; /* The output stream */
3375struct lemon *lemp; /* The main info structure for this parser */
3376int *plineno; /* Pointer to the line number */
3377int mhflag; /* True if generating makeheaders output */
3378{
3379 int lineno = *plineno; /* The line number of the output */
3380 char **types; /* A hash table of datatypes */
3381 int arraysize; /* Size of the "types" array */
3382 int maxdtlength; /* Maximum length of any ".datatype" field. */
3383 char *stddt; /* Standardized name for a datatype */
3384 int i,j; /* Loop counters */
3385 int hash; /* For hashing the name of a type */
3386 char *name; /* Name of the parser */
3387
3388 /* Allocate and initialize types[] and allocate stddt[] */
3389 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003390 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003391 for(i=0; i<arraysize; i++) types[i] = 0;
3392 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003393 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003394 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003395 }
drh75897232000-05-29 14:26:00 +00003396 for(i=0; i<lemp->nsymbol; i++){
3397 int len;
3398 struct symbol *sp = lemp->symbols[i];
3399 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003400 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003401 if( len>maxdtlength ) maxdtlength = len;
3402 }
3403 stddt = (char*)malloc( maxdtlength*2 + 1 );
3404 if( types==0 || stddt==0 ){
3405 fprintf(stderr,"Out of memory.\n");
3406 exit(1);
3407 }
3408
3409 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3410 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003411 ** used for terminal symbols. If there is no %default_type defined then
3412 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3413 ** a datatype using the %type directive.
3414 */
drh75897232000-05-29 14:26:00 +00003415 for(i=0; i<lemp->nsymbol; i++){
3416 struct symbol *sp = lemp->symbols[i];
3417 char *cp;
3418 if( sp==lemp->errsym ){
3419 sp->dtnum = arraysize+1;
3420 continue;
3421 }
drh960e8c62001-04-03 16:53:21 +00003422 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003423 sp->dtnum = 0;
3424 continue;
3425 }
3426 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003427 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003428 j = 0;
3429 while( isspace(*cp) ) cp++;
3430 while( *cp ) stddt[j++] = *cp++;
3431 while( j>0 && isspace(stddt[j-1]) ) j--;
3432 stddt[j] = 0;
drh32c4d742008-07-01 16:34:49 +00003433 if( strcmp(stddt, lemp->tokentype)==0 ){
3434 sp->dtnum = 0;
3435 continue;
3436 }
drh75897232000-05-29 14:26:00 +00003437 hash = 0;
3438 for(j=0; stddt[j]; j++){
3439 hash = hash*53 + stddt[j];
3440 }
drh3b2129c2003-05-13 00:34:21 +00003441 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003442 while( types[hash] ){
3443 if( strcmp(types[hash],stddt)==0 ){
3444 sp->dtnum = hash + 1;
3445 break;
3446 }
3447 hash++;
3448 if( hash>=arraysize ) hash = 0;
3449 }
3450 if( types[hash]==0 ){
3451 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003452 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003453 if( types[hash]==0 ){
3454 fprintf(stderr,"Out of memory.\n");
3455 exit(1);
3456 }
3457 strcpy(types[hash],stddt);
3458 }
3459 }
3460
3461 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3462 name = lemp->name ? lemp->name : "Parse";
3463 lineno = *plineno;
3464 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3465 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3466 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3467 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3468 fprintf(out,"typedef union {\n"); lineno++;
3469 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3470 for(i=0; i<arraysize; i++){
3471 if( types[i]==0 ) continue;
3472 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3473 free(types[i]);
3474 }
drhc4dd3fd2008-01-22 01:48:05 +00003475 if( lemp->errsym->useCnt ){
3476 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3477 }
drh75897232000-05-29 14:26:00 +00003478 free(stddt);
3479 free(types);
3480 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3481 *plineno = lineno;
3482}
3483
drhb29b0a52002-02-23 19:39:46 +00003484/*
3485** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003486** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003487*/
drh8b582012003-10-21 13:16:03 +00003488static const char *minimum_size_type(int lwr, int upr){
3489 if( lwr>=0 ){
3490 if( upr<=255 ){
3491 return "unsigned char";
3492 }else if( upr<65535 ){
3493 return "unsigned short int";
3494 }else{
3495 return "unsigned int";
3496 }
3497 }else if( lwr>=-127 && upr<=127 ){
3498 return "signed char";
3499 }else if( lwr>=-32767 && upr<32767 ){
3500 return "short";
drhb29b0a52002-02-23 19:39:46 +00003501 }else{
drh8b582012003-10-21 13:16:03 +00003502 return "int";
drhb29b0a52002-02-23 19:39:46 +00003503 }
3504}
3505
drhfdbf9282003-10-21 16:34:41 +00003506/*
3507** Each state contains a set of token transaction and a set of
3508** nonterminal transactions. Each of these sets makes an instance
3509** of the following structure. An array of these structures is used
3510** to order the creation of entries in the yy_action[] table.
3511*/
3512struct axset {
3513 struct state *stp; /* A pointer to a state */
3514 int isTkn; /* True to use tokens. False for non-terminals */
3515 int nAction; /* Number of actions */
3516};
3517
3518/*
3519** Compare to axset structures for sorting purposes
3520*/
3521static int axset_compare(const void *a, const void *b){
3522 struct axset *p1 = (struct axset*)a;
3523 struct axset *p2 = (struct axset*)b;
3524 return p2->nAction - p1->nAction;
3525}
3526
drhc4dd3fd2008-01-22 01:48:05 +00003527/*
3528** Write text on "out" that describes the rule "rp".
3529*/
3530static void writeRuleText(FILE *out, struct rule *rp){
3531 int j;
3532 fprintf(out,"%s ::=", rp->lhs->name);
3533 for(j=0; j<rp->nrhs; j++){
3534 struct symbol *sp = rp->rhs[j];
3535 fprintf(out," %s", sp->name);
3536 if( sp->type==MULTITERMINAL ){
3537 int k;
3538 for(k=1; k<sp->nsubsym; k++){
3539 fprintf(out,"|%s",sp->subsym[k]->name);
3540 }
3541 }
3542 }
3543}
3544
3545
drh75897232000-05-29 14:26:00 +00003546/* Generate C source code for the parser */
3547void ReportTable(lemp, mhflag)
3548struct lemon *lemp;
3549int mhflag; /* Output in makeheaders format if true */
3550{
3551 FILE *out, *in;
3552 char line[LINESIZE];
3553 int lineno;
3554 struct state *stp;
3555 struct action *ap;
3556 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003557 struct acttab *pActtab;
3558 int i, j, n;
drh75897232000-05-29 14:26:00 +00003559 char *name;
drh8b582012003-10-21 13:16:03 +00003560 int mnTknOfst, mxTknOfst;
3561 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003562 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003563
3564 in = tplt_open(lemp);
3565 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003566 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003567 if( out==0 ){
3568 fclose(in);
3569 return;
3570 }
3571 lineno = 1;
3572 tplt_xfer(lemp->name,in,out,&lineno);
3573
3574 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003575 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003576 if( mhflag ){
3577 char *name = file_makename(lemp, ".h");
3578 fprintf(out,"#include \"%s\"\n", name); lineno++;
3579 free(name);
3580 }
3581 tplt_xfer(lemp->name,in,out,&lineno);
3582
3583 /* Generate #defines for all tokens */
3584 if( mhflag ){
3585 char *prefix;
3586 fprintf(out,"#if INTERFACE\n"); lineno++;
3587 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3588 else prefix = "";
3589 for(i=1; i<lemp->nterminal; i++){
3590 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3591 lineno++;
3592 }
3593 fprintf(out,"#endif\n"); lineno++;
3594 }
3595 tplt_xfer(lemp->name,in,out,&lineno);
3596
3597 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003598 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003599 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003600 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3601 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003602 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003603 if( lemp->wildcard ){
3604 fprintf(out,"#define YYWILDCARD %d\n",
3605 lemp->wildcard->index); lineno++;
3606 }
drh75897232000-05-29 14:26:00 +00003607 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003608 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003609 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003610 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3611 }else{
3612 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3613 }
drhca44b5a2007-02-22 23:06:58 +00003614 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003615 if( mhflag ){
3616 fprintf(out,"#if INTERFACE\n"); lineno++;
3617 }
3618 name = lemp->name ? lemp->name : "Parse";
3619 if( lemp->arg && lemp->arg[0] ){
3620 int i;
drh87cf1372008-08-13 20:09:06 +00003621 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003622 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3623 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003624 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3625 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3626 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3627 name,lemp->arg,&lemp->arg[i]); lineno++;
3628 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3629 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003630 }else{
drh1f245e42002-03-11 13:55:50 +00003631 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3632 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3633 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3634 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003635 }
3636 if( mhflag ){
3637 fprintf(out,"#endif\n"); lineno++;
3638 }
3639 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3640 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003641 if( lemp->errsym->useCnt ){
3642 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3643 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3644 }
drh0bd1f4e2002-06-06 18:54:39 +00003645 if( lemp->has_fallback ){
3646 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3647 }
drh75897232000-05-29 14:26:00 +00003648 tplt_xfer(lemp->name,in,out,&lineno);
3649
drh8b582012003-10-21 13:16:03 +00003650 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003651 **
drh8b582012003-10-21 13:16:03 +00003652 ** yy_action[] A single table containing all actions.
3653 ** yy_lookahead[] A table containing the lookahead for each entry in
3654 ** yy_action. Used to detect hash collisions.
3655 ** yy_shift_ofst[] For each state, the offset into yy_action for
3656 ** shifting terminals.
3657 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3658 ** shifting non-terminals after a reduce.
3659 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003660 */
drh75897232000-05-29 14:26:00 +00003661
drh8b582012003-10-21 13:16:03 +00003662 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003663 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003664 if( ax==0 ){
3665 fprintf(stderr,"malloc failed\n");
3666 exit(1);
3667 }
drh75897232000-05-29 14:26:00 +00003668 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003669 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003670 ax[i*2].stp = stp;
3671 ax[i*2].isTkn = 1;
3672 ax[i*2].nAction = stp->nTknAct;
3673 ax[i*2+1].stp = stp;
3674 ax[i*2+1].isTkn = 0;
3675 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003676 }
drh8b582012003-10-21 13:16:03 +00003677 mxTknOfst = mnTknOfst = 0;
3678 mxNtOfst = mnNtOfst = 0;
3679
drhfdbf9282003-10-21 16:34:41 +00003680 /* Compute the action table. In order to try to keep the size of the
3681 ** action table to a minimum, the heuristic of placing the largest action
3682 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003683 */
drhfdbf9282003-10-21 16:34:41 +00003684 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003685 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003686 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3687 stp = ax[i].stp;
3688 if( ax[i].isTkn ){
3689 for(ap=stp->ap; ap; ap=ap->next){
3690 int action;
3691 if( ap->sp->index>=lemp->nterminal ) continue;
3692 action = compute_action(lemp, ap);
3693 if( action<0 ) continue;
3694 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003695 }
drhfdbf9282003-10-21 16:34:41 +00003696 stp->iTknOfst = acttab_insert(pActtab);
3697 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3698 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3699 }else{
3700 for(ap=stp->ap; ap; ap=ap->next){
3701 int action;
3702 if( ap->sp->index<lemp->nterminal ) continue;
3703 if( ap->sp->index==lemp->nsymbol ) continue;
3704 action = compute_action(lemp, ap);
3705 if( action<0 ) continue;
3706 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003707 }
drhfdbf9282003-10-21 16:34:41 +00003708 stp->iNtOfst = acttab_insert(pActtab);
3709 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3710 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003711 }
3712 }
drhfdbf9282003-10-21 16:34:41 +00003713 free(ax);
drh8b582012003-10-21 13:16:03 +00003714
3715 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003716 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003717 n = acttab_size(pActtab);
3718 for(i=j=0; i<n; i++){
3719 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003720 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003721 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003722 fprintf(out, " %4d,", action);
3723 if( j==9 || i==n-1 ){
3724 fprintf(out, "\n"); lineno++;
3725 j = 0;
3726 }else{
3727 j++;
3728 }
3729 }
3730 fprintf(out, "};\n"); lineno++;
3731
3732 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003733 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003734 for(i=j=0; i<n; i++){
3735 int la = acttab_yylookahead(pActtab, i);
3736 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003737 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003738 fprintf(out, " %4d,", la);
3739 if( j==9 || i==n-1 ){
3740 fprintf(out, "\n"); lineno++;
3741 j = 0;
3742 }else{
3743 j++;
3744 }
3745 }
3746 fprintf(out, "};\n"); lineno++;
3747
3748 /* Output the yy_shift_ofst[] table */
3749 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003750 n = lemp->nstate;
3751 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3752 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003753 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003754 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003755 for(i=j=0; i<n; i++){
3756 int ofst;
3757 stp = lemp->sorted[i];
3758 ofst = stp->iTknOfst;
3759 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003760 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003761 fprintf(out, " %4d,", ofst);
3762 if( j==9 || i==n-1 ){
3763 fprintf(out, "\n"); lineno++;
3764 j = 0;
3765 }else{
3766 j++;
3767 }
3768 }
3769 fprintf(out, "};\n"); lineno++;
3770
3771 /* Output the yy_reduce_ofst[] table */
3772 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003773 n = lemp->nstate;
3774 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3775 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003776 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003777 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003778 for(i=j=0; i<n; i++){
3779 int ofst;
3780 stp = lemp->sorted[i];
3781 ofst = stp->iNtOfst;
3782 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003783 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003784 fprintf(out, " %4d,", ofst);
3785 if( j==9 || i==n-1 ){
3786 fprintf(out, "\n"); lineno++;
3787 j = 0;
3788 }else{
3789 j++;
3790 }
3791 }
3792 fprintf(out, "};\n"); lineno++;
3793
3794 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003795 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003796 n = lemp->nstate;
3797 for(i=j=0; i<n; i++){
3798 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003799 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003800 fprintf(out, " %4d,", stp->iDflt);
3801 if( j==9 || i==n-1 ){
3802 fprintf(out, "\n"); lineno++;
3803 j = 0;
3804 }else{
3805 j++;
3806 }
3807 }
3808 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003809 tplt_xfer(lemp->name,in,out,&lineno);
3810
drh0bd1f4e2002-06-06 18:54:39 +00003811 /* Generate the table of fallback tokens.
3812 */
3813 if( lemp->has_fallback ){
3814 for(i=0; i<lemp->nterminal; i++){
3815 struct symbol *p = lemp->symbols[i];
3816 if( p->fallback==0 ){
3817 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3818 }else{
3819 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3820 p->name, p->fallback->name);
3821 }
3822 lineno++;
3823 }
3824 }
3825 tplt_xfer(lemp->name, in, out, &lineno);
3826
3827 /* Generate a table containing the symbolic name of every symbol
3828 */
drh75897232000-05-29 14:26:00 +00003829 for(i=0; i<lemp->nsymbol; i++){
3830 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3831 fprintf(out," %-15s",line);
3832 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3833 }
3834 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3835 tplt_xfer(lemp->name,in,out,&lineno);
3836
drh0bd1f4e2002-06-06 18:54:39 +00003837 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003838 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003839 ** when tracing REDUCE actions.
3840 */
3841 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3842 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003843 fprintf(out," /* %3d */ \"", i);
3844 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003845 fprintf(out,"\",\n"); lineno++;
3846 }
3847 tplt_xfer(lemp->name,in,out,&lineno);
3848
drh75897232000-05-29 14:26:00 +00003849 /* Generate code which executes every time a symbol is popped from
3850 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003851 ** (In other words, generate the %destructor actions)
3852 */
drh75897232000-05-29 14:26:00 +00003853 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003854 int once = 1;
drh75897232000-05-29 14:26:00 +00003855 for(i=0; i<lemp->nsymbol; i++){
3856 struct symbol *sp = lemp->symbols[i];
3857 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003858 if( once ){
3859 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3860 once = 0;
3861 }
drhc4dd3fd2008-01-22 01:48:05 +00003862 fprintf(out," case %d: /* %s */\n",
3863 sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003864 }
3865 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3866 if( i<lemp->nsymbol ){
3867 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3868 fprintf(out," break;\n"); lineno++;
3869 }
3870 }
drh8d659732005-01-13 23:54:06 +00003871 if( lemp->vardest ){
3872 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003873 int once = 1;
drh8d659732005-01-13 23:54:06 +00003874 for(i=0; i<lemp->nsymbol; i++){
3875 struct symbol *sp = lemp->symbols[i];
3876 if( sp==0 || sp->type==TERMINAL ||
3877 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003878 if( once ){
3879 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3880 once = 0;
3881 }
drhc4dd3fd2008-01-22 01:48:05 +00003882 fprintf(out," case %d: /* %s */\n",
3883 sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003884 dflt_sp = sp;
3885 }
3886 if( dflt_sp!=0 ){
3887 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003888 }
drh4dc8ef52008-07-01 17:13:57 +00003889 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003890 }
drh75897232000-05-29 14:26:00 +00003891 for(i=0; i<lemp->nsymbol; i++){
3892 struct symbol *sp = lemp->symbols[i];
3893 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003894 fprintf(out," case %d: /* %s */\n",
3895 sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003896
3897 /* Combine duplicate destructors into a single case */
3898 for(j=i+1; j<lemp->nsymbol; j++){
3899 struct symbol *sp2 = lemp->symbols[j];
3900 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3901 && sp2->dtnum==sp->dtnum
3902 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc4dd3fd2008-01-22 01:48:05 +00003903 fprintf(out," case %d: /* %s */\n",
3904 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003905 sp2->destructor = 0;
3906 }
3907 }
3908
drh75897232000-05-29 14:26:00 +00003909 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3910 fprintf(out," break;\n"); lineno++;
3911 }
drh75897232000-05-29 14:26:00 +00003912 tplt_xfer(lemp->name,in,out,&lineno);
3913
3914 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003915 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003916 tplt_xfer(lemp->name,in,out,&lineno);
3917
3918 /* Generate the table of rule information
3919 **
3920 ** Note: This code depends on the fact that rules are number
3921 ** sequentually beginning with 0.
3922 */
3923 for(rp=lemp->rule; rp; rp=rp->next){
3924 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3925 }
3926 tplt_xfer(lemp->name,in,out,&lineno);
3927
3928 /* Generate code which execution during each REDUCE action */
3929 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003930 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003931 }
3932 for(rp=lemp->rule; rp; rp=rp->next){
3933 struct rule *rp2;
3934 if( rp->code==0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003935 fprintf(out," case %d: /* ", rp->index);
3936 writeRuleText(out, rp);
3937 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003938 for(rp2=rp->next; rp2; rp2=rp2->next){
3939 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003940 fprintf(out," case %d: /* ", rp2->index);
3941 writeRuleText(out, rp2);
3942 fprintf(out," */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003943 rp2->code = 0;
3944 }
3945 }
drh75897232000-05-29 14:26:00 +00003946 emit_code(out,rp,lemp,&lineno);
3947 fprintf(out," break;\n"); lineno++;
3948 }
3949 tplt_xfer(lemp->name,in,out,&lineno);
3950
3951 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003952 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00003953 tplt_xfer(lemp->name,in,out,&lineno);
3954
3955 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00003956 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00003957 tplt_xfer(lemp->name,in,out,&lineno);
3958
3959 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00003960 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00003961 tplt_xfer(lemp->name,in,out,&lineno);
3962
3963 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00003964 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00003965
3966 fclose(in);
3967 fclose(out);
3968 return;
3969}
3970
3971/* Generate a header file for the parser */
3972void ReportHeader(lemp)
3973struct lemon *lemp;
3974{
3975 FILE *out, *in;
3976 char *prefix;
3977 char line[LINESIZE];
3978 char pattern[LINESIZE];
3979 int i;
3980
3981 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3982 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003983 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003984 if( in ){
3985 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3986 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3987 if( strcmp(line,pattern) ) break;
3988 }
3989 fclose(in);
3990 if( i==lemp->nterminal ){
3991 /* No change in the file. Don't rewrite it. */
3992 return;
3993 }
3994 }
drh2aa6ca42004-09-10 00:14:04 +00003995 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003996 if( out ){
3997 for(i=1; i<lemp->nterminal; i++){
3998 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3999 }
4000 fclose(out);
4001 }
4002 return;
4003}
4004
4005/* Reduce the size of the action tables, if possible, by making use
4006** of defaults.
4007**
drhb59499c2002-02-23 18:45:13 +00004008** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004009** it the default. Except, there is no default if the wildcard token
4010** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004011*/
4012void CompressTables(lemp)
4013struct lemon *lemp;
4014{
4015 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004016 struct action *ap, *ap2;
4017 struct rule *rp, *rp2, *rbest;
4018 int nbest, n;
drh75897232000-05-29 14:26:00 +00004019 int i;
drhe09daa92006-06-10 13:29:31 +00004020 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004021
4022 for(i=0; i<lemp->nstate; i++){
4023 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004024 nbest = 0;
4025 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004026 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004027
drhb59499c2002-02-23 18:45:13 +00004028 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004029 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4030 usesWildcard = 1;
4031 }
drhb59499c2002-02-23 18:45:13 +00004032 if( ap->type!=REDUCE ) continue;
4033 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004034 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004035 if( rp==rbest ) continue;
4036 n = 1;
4037 for(ap2=ap->next; ap2; ap2=ap2->next){
4038 if( ap2->type!=REDUCE ) continue;
4039 rp2 = ap2->x.rp;
4040 if( rp2==rbest ) continue;
4041 if( rp2==rp ) n++;
4042 }
4043 if( n>nbest ){
4044 nbest = n;
4045 rbest = rp;
drh75897232000-05-29 14:26:00 +00004046 }
4047 }
drhb59499c2002-02-23 18:45:13 +00004048
4049 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004050 ** is not at least 1 or if the wildcard token is a possible
4051 ** lookahead.
4052 */
4053 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004054
drhb59499c2002-02-23 18:45:13 +00004055
4056 /* Combine matching REDUCE actions into a single default */
4057 for(ap=stp->ap; ap; ap=ap->next){
4058 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4059 }
drh75897232000-05-29 14:26:00 +00004060 assert( ap );
4061 ap->sp = Symbol_new("{default}");
4062 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004063 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004064 }
4065 stp->ap = Action_sort(stp->ap);
4066 }
4067}
drhb59499c2002-02-23 18:45:13 +00004068
drhada354d2005-11-05 15:03:59 +00004069
4070/*
4071** Compare two states for sorting purposes. The smaller state is the
4072** one with the most non-terminal actions. If they have the same number
4073** of non-terminal actions, then the smaller is the one with the most
4074** token actions.
4075*/
4076static int stateResortCompare(const void *a, const void *b){
4077 const struct state *pA = *(const struct state**)a;
4078 const struct state *pB = *(const struct state**)b;
4079 int n;
4080
4081 n = pB->nNtAct - pA->nNtAct;
4082 if( n==0 ){
4083 n = pB->nTknAct - pA->nTknAct;
4084 }
4085 return n;
4086}
4087
4088
4089/*
4090** Renumber and resort states so that states with fewer choices
4091** occur at the end. Except, keep state 0 as the first state.
4092*/
4093void ResortStates(lemp)
4094struct lemon *lemp;
4095{
4096 int i;
4097 struct state *stp;
4098 struct action *ap;
4099
4100 for(i=0; i<lemp->nstate; i++){
4101 stp = lemp->sorted[i];
4102 stp->nTknAct = stp->nNtAct = 0;
4103 stp->iDflt = lemp->nstate + lemp->nrule;
4104 stp->iTknOfst = NO_OFFSET;
4105 stp->iNtOfst = NO_OFFSET;
4106 for(ap=stp->ap; ap; ap=ap->next){
4107 if( compute_action(lemp,ap)>=0 ){
4108 if( ap->sp->index<lemp->nterminal ){
4109 stp->nTknAct++;
4110 }else if( ap->sp->index<lemp->nsymbol ){
4111 stp->nNtAct++;
4112 }else{
4113 stp->iDflt = compute_action(lemp, ap);
4114 }
4115 }
4116 }
4117 }
4118 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4119 stateResortCompare);
4120 for(i=0; i<lemp->nstate; i++){
4121 lemp->sorted[i]->statenum = i;
4122 }
4123}
4124
4125
drh75897232000-05-29 14:26:00 +00004126/***************** From the file "set.c" ************************************/
4127/*
4128** Set manipulation routines for the LEMON parser generator.
4129*/
4130
4131static int size = 0;
4132
4133/* Set the set size */
4134void SetSize(n)
4135int n;
4136{
4137 size = n+1;
4138}
4139
4140/* Allocate a new set */
4141char *SetNew(){
4142 char *s;
drh9892c5d2007-12-21 00:02:11 +00004143 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004144 if( s==0 ){
4145 extern void memory_error();
4146 memory_error();
4147 }
drh75897232000-05-29 14:26:00 +00004148 return s;
4149}
4150
4151/* Deallocate a set */
4152void SetFree(s)
4153char *s;
4154{
4155 free(s);
4156}
4157
4158/* Add a new element to the set. Return TRUE if the element was added
4159** and FALSE if it was already there. */
4160int SetAdd(s,e)
4161char *s;
4162int e;
4163{
4164 int rv;
drh9892c5d2007-12-21 00:02:11 +00004165 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004166 rv = s[e];
4167 s[e] = 1;
4168 return !rv;
4169}
4170
4171/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4172int SetUnion(s1,s2)
4173char *s1;
4174char *s2;
4175{
4176 int i, progress;
4177 progress = 0;
4178 for(i=0; i<size; i++){
4179 if( s2[i]==0 ) continue;
4180 if( s1[i]==0 ){
4181 progress = 1;
4182 s1[i] = 1;
4183 }
4184 }
4185 return progress;
4186}
4187/********************** From the file "table.c" ****************************/
4188/*
4189** All code in this file has been automatically generated
4190** from a specification in the file
4191** "table.q"
4192** by the associative array code building program "aagen".
4193** Do not edit this file! Instead, edit the specification
4194** file, then rerun aagen.
4195*/
4196/*
4197** Code for processing tables in the LEMON parser generator.
4198*/
4199
4200PRIVATE int strhash(x)
4201char *x;
4202{
4203 int h = 0;
4204 while( *x) h = h*13 + *(x++);
4205 return h;
4206}
4207
4208/* Works like strdup, sort of. Save a string in malloced memory, but
4209** keep strings in a table so that the same string is not in more
4210** than one place.
4211*/
4212char *Strsafe(y)
4213char *y;
4214{
4215 char *z;
4216
drh916f75f2006-07-17 00:19:39 +00004217 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004218 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004219 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004220 strcpy(z,y);
4221 Strsafe_insert(z);
4222 }
4223 MemoryCheck(z);
4224 return z;
4225}
4226
4227/* There is one instance of the following structure for each
4228** associative array of type "x1".
4229*/
4230struct s_x1 {
4231 int size; /* The number of available slots. */
4232 /* Must be a power of 2 greater than or */
4233 /* equal to 1 */
4234 int count; /* Number of currently slots filled */
4235 struct s_x1node *tbl; /* The data stored here */
4236 struct s_x1node **ht; /* Hash table for lookups */
4237};
4238
4239/* There is one instance of this structure for every data element
4240** in an associative array of type "x1".
4241*/
4242typedef struct s_x1node {
4243 char *data; /* The data */
4244 struct s_x1node *next; /* Next entry with the same hash */
4245 struct s_x1node **from; /* Previous link */
4246} x1node;
4247
4248/* There is only one instance of the array, which is the following */
4249static struct s_x1 *x1a;
4250
4251/* Allocate a new associative array */
4252void Strsafe_init(){
4253 if( x1a ) return;
4254 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4255 if( x1a ){
4256 x1a->size = 1024;
4257 x1a->count = 0;
4258 x1a->tbl = (x1node*)malloc(
4259 (sizeof(x1node) + sizeof(x1node*))*1024 );
4260 if( x1a->tbl==0 ){
4261 free(x1a);
4262 x1a = 0;
4263 }else{
4264 int i;
4265 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4266 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4267 }
4268 }
4269}
4270/* Insert a new record into the array. Return TRUE if successful.
4271** Prior data with the same key is NOT overwritten */
4272int Strsafe_insert(data)
4273char *data;
4274{
4275 x1node *np;
4276 int h;
4277 int ph;
4278
4279 if( x1a==0 ) return 0;
4280 ph = strhash(data);
4281 h = ph & (x1a->size-1);
4282 np = x1a->ht[h];
4283 while( np ){
4284 if( strcmp(np->data,data)==0 ){
4285 /* An existing entry with the same key is found. */
4286 /* Fail because overwrite is not allows. */
4287 return 0;
4288 }
4289 np = np->next;
4290 }
4291 if( x1a->count>=x1a->size ){
4292 /* Need to make the hash table bigger */
4293 int i,size;
4294 struct s_x1 array;
4295 array.size = size = x1a->size*2;
4296 array.count = x1a->count;
4297 array.tbl = (x1node*)malloc(
4298 (sizeof(x1node) + sizeof(x1node*))*size );
4299 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4300 array.ht = (x1node**)&(array.tbl[size]);
4301 for(i=0; i<size; i++) array.ht[i] = 0;
4302 for(i=0; i<x1a->count; i++){
4303 x1node *oldnp, *newnp;
4304 oldnp = &(x1a->tbl[i]);
4305 h = strhash(oldnp->data) & (size-1);
4306 newnp = &(array.tbl[i]);
4307 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4308 newnp->next = array.ht[h];
4309 newnp->data = oldnp->data;
4310 newnp->from = &(array.ht[h]);
4311 array.ht[h] = newnp;
4312 }
4313 free(x1a->tbl);
4314 *x1a = array;
4315 }
4316 /* Insert the new data */
4317 h = ph & (x1a->size-1);
4318 np = &(x1a->tbl[x1a->count++]);
4319 np->data = data;
4320 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4321 np->next = x1a->ht[h];
4322 x1a->ht[h] = np;
4323 np->from = &(x1a->ht[h]);
4324 return 1;
4325}
4326
4327/* Return a pointer to data assigned to the given key. Return NULL
4328** if no such key. */
4329char *Strsafe_find(key)
4330char *key;
4331{
4332 int h;
4333 x1node *np;
4334
4335 if( x1a==0 ) return 0;
4336 h = strhash(key) & (x1a->size-1);
4337 np = x1a->ht[h];
4338 while( np ){
4339 if( strcmp(np->data,key)==0 ) break;
4340 np = np->next;
4341 }
4342 return np ? np->data : 0;
4343}
4344
4345/* Return a pointer to the (terminal or nonterminal) symbol "x".
4346** Create a new symbol if this is the first time "x" has been seen.
4347*/
4348struct symbol *Symbol_new(x)
4349char *x;
4350{
4351 struct symbol *sp;
4352
4353 sp = Symbol_find(x);
4354 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004355 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004356 MemoryCheck(sp);
4357 sp->name = Strsafe(x);
4358 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4359 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004360 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004361 sp->prec = -1;
4362 sp->assoc = UNK;
4363 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004364 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004365 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004366 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004367 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004368 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004369 Symbol_insert(sp,sp->name);
4370 }
drhc4dd3fd2008-01-22 01:48:05 +00004371 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004372 return sp;
4373}
4374
drh60d31652004-02-22 00:08:04 +00004375/* Compare two symbols for working purposes
4376**
4377** Symbols that begin with upper case letters (terminals or tokens)
4378** must sort before symbols that begin with lower case letters
4379** (non-terminals). Other than that, the order does not matter.
4380**
4381** We find experimentally that leaving the symbols in their original
4382** order (the order they appeared in the grammar file) gives the
4383** smallest parser tables in SQLite.
4384*/
4385int Symbolcmpp(struct symbol **a, struct symbol **b){
4386 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4387 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4388 return i1-i2;
drh75897232000-05-29 14:26:00 +00004389}
4390
4391/* There is one instance of the following structure for each
4392** associative array of type "x2".
4393*/
4394struct s_x2 {
4395 int size; /* The number of available slots. */
4396 /* Must be a power of 2 greater than or */
4397 /* equal to 1 */
4398 int count; /* Number of currently slots filled */
4399 struct s_x2node *tbl; /* The data stored here */
4400 struct s_x2node **ht; /* Hash table for lookups */
4401};
4402
4403/* There is one instance of this structure for every data element
4404** in an associative array of type "x2".
4405*/
4406typedef struct s_x2node {
4407 struct symbol *data; /* The data */
4408 char *key; /* The key */
4409 struct s_x2node *next; /* Next entry with the same hash */
4410 struct s_x2node **from; /* Previous link */
4411} x2node;
4412
4413/* There is only one instance of the array, which is the following */
4414static struct s_x2 *x2a;
4415
4416/* Allocate a new associative array */
4417void Symbol_init(){
4418 if( x2a ) return;
4419 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4420 if( x2a ){
4421 x2a->size = 128;
4422 x2a->count = 0;
4423 x2a->tbl = (x2node*)malloc(
4424 (sizeof(x2node) + sizeof(x2node*))*128 );
4425 if( x2a->tbl==0 ){
4426 free(x2a);
4427 x2a = 0;
4428 }else{
4429 int i;
4430 x2a->ht = (x2node**)&(x2a->tbl[128]);
4431 for(i=0; i<128; i++) x2a->ht[i] = 0;
4432 }
4433 }
4434}
4435/* Insert a new record into the array. Return TRUE if successful.
4436** Prior data with the same key is NOT overwritten */
4437int Symbol_insert(data,key)
4438struct symbol *data;
4439char *key;
4440{
4441 x2node *np;
4442 int h;
4443 int ph;
4444
4445 if( x2a==0 ) return 0;
4446 ph = strhash(key);
4447 h = ph & (x2a->size-1);
4448 np = x2a->ht[h];
4449 while( np ){
4450 if( strcmp(np->key,key)==0 ){
4451 /* An existing entry with the same key is found. */
4452 /* Fail because overwrite is not allows. */
4453 return 0;
4454 }
4455 np = np->next;
4456 }
4457 if( x2a->count>=x2a->size ){
4458 /* Need to make the hash table bigger */
4459 int i,size;
4460 struct s_x2 array;
4461 array.size = size = x2a->size*2;
4462 array.count = x2a->count;
4463 array.tbl = (x2node*)malloc(
4464 (sizeof(x2node) + sizeof(x2node*))*size );
4465 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4466 array.ht = (x2node**)&(array.tbl[size]);
4467 for(i=0; i<size; i++) array.ht[i] = 0;
4468 for(i=0; i<x2a->count; i++){
4469 x2node *oldnp, *newnp;
4470 oldnp = &(x2a->tbl[i]);
4471 h = strhash(oldnp->key) & (size-1);
4472 newnp = &(array.tbl[i]);
4473 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4474 newnp->next = array.ht[h];
4475 newnp->key = oldnp->key;
4476 newnp->data = oldnp->data;
4477 newnp->from = &(array.ht[h]);
4478 array.ht[h] = newnp;
4479 }
4480 free(x2a->tbl);
4481 *x2a = array;
4482 }
4483 /* Insert the new data */
4484 h = ph & (x2a->size-1);
4485 np = &(x2a->tbl[x2a->count++]);
4486 np->key = key;
4487 np->data = data;
4488 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4489 np->next = x2a->ht[h];
4490 x2a->ht[h] = np;
4491 np->from = &(x2a->ht[h]);
4492 return 1;
4493}
4494
4495/* Return a pointer to data assigned to the given key. Return NULL
4496** if no such key. */
4497struct symbol *Symbol_find(key)
4498char *key;
4499{
4500 int h;
4501 x2node *np;
4502
4503 if( x2a==0 ) return 0;
4504 h = strhash(key) & (x2a->size-1);
4505 np = x2a->ht[h];
4506 while( np ){
4507 if( strcmp(np->key,key)==0 ) break;
4508 np = np->next;
4509 }
4510 return np ? np->data : 0;
4511}
4512
4513/* Return the n-th data. Return NULL if n is out of range. */
4514struct symbol *Symbol_Nth(n)
4515int n;
4516{
4517 struct symbol *data;
4518 if( x2a && n>0 && n<=x2a->count ){
4519 data = x2a->tbl[n-1].data;
4520 }else{
4521 data = 0;
4522 }
4523 return data;
4524}
4525
4526/* Return the size of the array */
4527int Symbol_count()
4528{
4529 return x2a ? x2a->count : 0;
4530}
4531
4532/* Return an array of pointers to all data in the table.
4533** The array is obtained from malloc. Return NULL if memory allocation
4534** problems, or if the array is empty. */
4535struct symbol **Symbol_arrayof()
4536{
4537 struct symbol **array;
4538 int i,size;
4539 if( x2a==0 ) return 0;
4540 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004541 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004542 if( array ){
4543 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4544 }
4545 return array;
4546}
4547
4548/* Compare two configurations */
4549int Configcmp(a,b)
4550struct config *a;
4551struct config *b;
4552{
4553 int x;
4554 x = a->rp->index - b->rp->index;
4555 if( x==0 ) x = a->dot - b->dot;
4556 return x;
4557}
4558
4559/* Compare two states */
4560PRIVATE int statecmp(a,b)
4561struct config *a;
4562struct config *b;
4563{
4564 int rc;
4565 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4566 rc = a->rp->index - b->rp->index;
4567 if( rc==0 ) rc = a->dot - b->dot;
4568 }
4569 if( rc==0 ){
4570 if( a ) rc = 1;
4571 if( b ) rc = -1;
4572 }
4573 return rc;
4574}
4575
4576/* Hash a state */
4577PRIVATE int statehash(a)
4578struct config *a;
4579{
4580 int h=0;
4581 while( a ){
4582 h = h*571 + a->rp->index*37 + a->dot;
4583 a = a->bp;
4584 }
4585 return h;
4586}
4587
4588/* Allocate a new state structure */
4589struct state *State_new()
4590{
4591 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004592 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004593 MemoryCheck(new);
4594 return new;
4595}
4596
4597/* There is one instance of the following structure for each
4598** associative array of type "x3".
4599*/
4600struct s_x3 {
4601 int size; /* The number of available slots. */
4602 /* Must be a power of 2 greater than or */
4603 /* equal to 1 */
4604 int count; /* Number of currently slots filled */
4605 struct s_x3node *tbl; /* The data stored here */
4606 struct s_x3node **ht; /* Hash table for lookups */
4607};
4608
4609/* There is one instance of this structure for every data element
4610** in an associative array of type "x3".
4611*/
4612typedef struct s_x3node {
4613 struct state *data; /* The data */
4614 struct config *key; /* The key */
4615 struct s_x3node *next; /* Next entry with the same hash */
4616 struct s_x3node **from; /* Previous link */
4617} x3node;
4618
4619/* There is only one instance of the array, which is the following */
4620static struct s_x3 *x3a;
4621
4622/* Allocate a new associative array */
4623void State_init(){
4624 if( x3a ) return;
4625 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4626 if( x3a ){
4627 x3a->size = 128;
4628 x3a->count = 0;
4629 x3a->tbl = (x3node*)malloc(
4630 (sizeof(x3node) + sizeof(x3node*))*128 );
4631 if( x3a->tbl==0 ){
4632 free(x3a);
4633 x3a = 0;
4634 }else{
4635 int i;
4636 x3a->ht = (x3node**)&(x3a->tbl[128]);
4637 for(i=0; i<128; i++) x3a->ht[i] = 0;
4638 }
4639 }
4640}
4641/* Insert a new record into the array. Return TRUE if successful.
4642** Prior data with the same key is NOT overwritten */
4643int State_insert(data,key)
4644struct state *data;
4645struct config *key;
4646{
4647 x3node *np;
4648 int h;
4649 int ph;
4650
4651 if( x3a==0 ) return 0;
4652 ph = statehash(key);
4653 h = ph & (x3a->size-1);
4654 np = x3a->ht[h];
4655 while( np ){
4656 if( statecmp(np->key,key)==0 ){
4657 /* An existing entry with the same key is found. */
4658 /* Fail because overwrite is not allows. */
4659 return 0;
4660 }
4661 np = np->next;
4662 }
4663 if( x3a->count>=x3a->size ){
4664 /* Need to make the hash table bigger */
4665 int i,size;
4666 struct s_x3 array;
4667 array.size = size = x3a->size*2;
4668 array.count = x3a->count;
4669 array.tbl = (x3node*)malloc(
4670 (sizeof(x3node) + sizeof(x3node*))*size );
4671 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4672 array.ht = (x3node**)&(array.tbl[size]);
4673 for(i=0; i<size; i++) array.ht[i] = 0;
4674 for(i=0; i<x3a->count; i++){
4675 x3node *oldnp, *newnp;
4676 oldnp = &(x3a->tbl[i]);
4677 h = statehash(oldnp->key) & (size-1);
4678 newnp = &(array.tbl[i]);
4679 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4680 newnp->next = array.ht[h];
4681 newnp->key = oldnp->key;
4682 newnp->data = oldnp->data;
4683 newnp->from = &(array.ht[h]);
4684 array.ht[h] = newnp;
4685 }
4686 free(x3a->tbl);
4687 *x3a = array;
4688 }
4689 /* Insert the new data */
4690 h = ph & (x3a->size-1);
4691 np = &(x3a->tbl[x3a->count++]);
4692 np->key = key;
4693 np->data = data;
4694 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4695 np->next = x3a->ht[h];
4696 x3a->ht[h] = np;
4697 np->from = &(x3a->ht[h]);
4698 return 1;
4699}
4700
4701/* Return a pointer to data assigned to the given key. Return NULL
4702** if no such key. */
4703struct state *State_find(key)
4704struct config *key;
4705{
4706 int h;
4707 x3node *np;
4708
4709 if( x3a==0 ) return 0;
4710 h = statehash(key) & (x3a->size-1);
4711 np = x3a->ht[h];
4712 while( np ){
4713 if( statecmp(np->key,key)==0 ) break;
4714 np = np->next;
4715 }
4716 return np ? np->data : 0;
4717}
4718
4719/* Return an array of pointers to all data in the table.
4720** The array is obtained from malloc. Return NULL if memory allocation
4721** problems, or if the array is empty. */
4722struct state **State_arrayof()
4723{
4724 struct state **array;
4725 int i,size;
4726 if( x3a==0 ) return 0;
4727 size = x3a->count;
4728 array = (struct state **)malloc( sizeof(struct state *)*size );
4729 if( array ){
4730 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4731 }
4732 return array;
4733}
4734
4735/* Hash a configuration */
4736PRIVATE int confighash(a)
4737struct config *a;
4738{
4739 int h=0;
4740 h = h*571 + a->rp->index*37 + a->dot;
4741 return h;
4742}
4743
4744/* There is one instance of the following structure for each
4745** associative array of type "x4".
4746*/
4747struct s_x4 {
4748 int size; /* The number of available slots. */
4749 /* Must be a power of 2 greater than or */
4750 /* equal to 1 */
4751 int count; /* Number of currently slots filled */
4752 struct s_x4node *tbl; /* The data stored here */
4753 struct s_x4node **ht; /* Hash table for lookups */
4754};
4755
4756/* There is one instance of this structure for every data element
4757** in an associative array of type "x4".
4758*/
4759typedef struct s_x4node {
4760 struct config *data; /* The data */
4761 struct s_x4node *next; /* Next entry with the same hash */
4762 struct s_x4node **from; /* Previous link */
4763} x4node;
4764
4765/* There is only one instance of the array, which is the following */
4766static struct s_x4 *x4a;
4767
4768/* Allocate a new associative array */
4769void Configtable_init(){
4770 if( x4a ) return;
4771 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4772 if( x4a ){
4773 x4a->size = 64;
4774 x4a->count = 0;
4775 x4a->tbl = (x4node*)malloc(
4776 (sizeof(x4node) + sizeof(x4node*))*64 );
4777 if( x4a->tbl==0 ){
4778 free(x4a);
4779 x4a = 0;
4780 }else{
4781 int i;
4782 x4a->ht = (x4node**)&(x4a->tbl[64]);
4783 for(i=0; i<64; i++) x4a->ht[i] = 0;
4784 }
4785 }
4786}
4787/* Insert a new record into the array. Return TRUE if successful.
4788** Prior data with the same key is NOT overwritten */
4789int Configtable_insert(data)
4790struct config *data;
4791{
4792 x4node *np;
4793 int h;
4794 int ph;
4795
4796 if( x4a==0 ) return 0;
4797 ph = confighash(data);
4798 h = ph & (x4a->size-1);
4799 np = x4a->ht[h];
4800 while( np ){
4801 if( Configcmp(np->data,data)==0 ){
4802 /* An existing entry with the same key is found. */
4803 /* Fail because overwrite is not allows. */
4804 return 0;
4805 }
4806 np = np->next;
4807 }
4808 if( x4a->count>=x4a->size ){
4809 /* Need to make the hash table bigger */
4810 int i,size;
4811 struct s_x4 array;
4812 array.size = size = x4a->size*2;
4813 array.count = x4a->count;
4814 array.tbl = (x4node*)malloc(
4815 (sizeof(x4node) + sizeof(x4node*))*size );
4816 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4817 array.ht = (x4node**)&(array.tbl[size]);
4818 for(i=0; i<size; i++) array.ht[i] = 0;
4819 for(i=0; i<x4a->count; i++){
4820 x4node *oldnp, *newnp;
4821 oldnp = &(x4a->tbl[i]);
4822 h = confighash(oldnp->data) & (size-1);
4823 newnp = &(array.tbl[i]);
4824 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4825 newnp->next = array.ht[h];
4826 newnp->data = oldnp->data;
4827 newnp->from = &(array.ht[h]);
4828 array.ht[h] = newnp;
4829 }
4830 free(x4a->tbl);
4831 *x4a = array;
4832 }
4833 /* Insert the new data */
4834 h = ph & (x4a->size-1);
4835 np = &(x4a->tbl[x4a->count++]);
4836 np->data = data;
4837 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4838 np->next = x4a->ht[h];
4839 x4a->ht[h] = np;
4840 np->from = &(x4a->ht[h]);
4841 return 1;
4842}
4843
4844/* Return a pointer to data assigned to the given key. Return NULL
4845** if no such key. */
4846struct config *Configtable_find(key)
4847struct config *key;
4848{
4849 int h;
4850 x4node *np;
4851
4852 if( x4a==0 ) return 0;
4853 h = confighash(key) & (x4a->size-1);
4854 np = x4a->ht[h];
4855 while( np ){
4856 if( Configcmp(np->data,key)==0 ) break;
4857 np = np->next;
4858 }
4859 return np ? np->data : 0;
4860}
4861
4862/* Remove all data from the table. Pass each data to the function "f"
4863** as it is removed. ("f" may be null to avoid this step.) */
4864void Configtable_clear(f)
4865int(*f)(/* struct config * */);
4866{
4867 int i;
4868 if( x4a==0 || x4a->count==0 ) return;
4869 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4870 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4871 x4a->count = 0;
4872 return;
4873}