blob: 75c29fc3e596cd865288e06a15f0317882e0b6fb [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 */
shane58543932008-12-10 20:10:04 +0000274 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000275 char *argv0; /* Name of the program */
276};
277
278#define MemoryCheck(X) if((X)==0){ \
279 extern void memory_error(); \
280 memory_error(); \
281}
282
283/**************** From the file "table.h" *********************************/
284/*
285** All code in this file has been automatically generated
286** from a specification in the file
287** "table.q"
288** by the associative array code building program "aagen".
289** Do not edit this file! Instead, edit the specification
290** file, then rerun aagen.
291*/
292/*
293** Code for processing tables in the LEMON parser generator.
294*/
295
296/* Routines for handling a strings */
297
298char *Strsafe();
299
300void Strsafe_init(/* void */);
301int Strsafe_insert(/* char * */);
302char *Strsafe_find(/* char * */);
303
304/* Routines for handling symbols of the grammar */
305
306struct symbol *Symbol_new();
307int Symbolcmpp(/* struct symbol **, struct symbol ** */);
308void Symbol_init(/* void */);
309int Symbol_insert(/* struct symbol *, char * */);
310struct symbol *Symbol_find(/* char * */);
311struct symbol *Symbol_Nth(/* int */);
312int Symbol_count(/* */);
313struct symbol **Symbol_arrayof(/* */);
314
315/* Routines to manage the state table */
316
317int Configcmp(/* struct config *, struct config * */);
318struct state *State_new();
319void State_init(/* void */);
320int State_insert(/* struct state *, struct config * */);
321struct state *State_find(/* struct config * */);
322struct state **State_arrayof(/* */);
323
324/* Routines used for efficiency in Configlist_add */
325
326void Configtable_init(/* void */);
327int Configtable_insert(/* struct config * */);
328struct config *Configtable_find(/* struct config * */);
329void Configtable_clear(/* int(*)(struct config *) */);
330/****************** From the file "action.c" *******************************/
331/*
332** Routines processing parser actions in the LEMON parser generator.
333*/
334
335/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000336static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000337 static struct action *freelist = 0;
338 struct action *new;
339
340 if( freelist==0 ){
341 int i;
342 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000343 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000344 if( freelist==0 ){
345 fprintf(stderr,"Unable to allocate memory for a new parser action.");
346 exit(1);
347 }
348 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
349 freelist[amt-1].next = 0;
350 }
351 new = freelist;
352 freelist = freelist->next;
353 return new;
354}
355
drhe9278182007-07-18 18:16:29 +0000356/* Compare two actions for sorting purposes. Return negative, zero, or
357** positive if the first action is less than, equal to, or greater than
358** the first
359*/
360static int actioncmp(
361 struct action *ap1,
362 struct action *ap2
363){
drh75897232000-05-29 14:26:00 +0000364 int rc;
365 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000366 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000367 rc = (int)ap1->type - (int)ap2->type;
368 }
369 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000370 rc = ap1->x.rp->index - ap2->x.rp->index;
371 }
drhe594bc32009-11-03 13:02:25 +0000372 if( rc==0 ){
373 rc = ap2 - ap1;
374 }
drh75897232000-05-29 14:26:00 +0000375 return rc;
376}
377
378/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000379static struct action *Action_sort(
380 struct action *ap
381){
382 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
383 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000384 return ap;
385}
386
387void Action_add(app,type,sp,arg)
388struct action **app;
389enum e_action type;
390struct symbol *sp;
391char *arg;
392{
393 struct action *new;
394 new = Action_new();
395 new->next = *app;
396 *app = new;
397 new->type = type;
398 new->sp = sp;
399 if( type==SHIFT ){
400 new->x.stp = (struct state *)arg;
401 }else{
402 new->x.rp = (struct rule *)arg;
403 }
404}
drh8b582012003-10-21 13:16:03 +0000405/********************** New code to implement the "acttab" module ***********/
406/*
407** This module implements routines use to construct the yy_action[] table.
408*/
409
410/*
411** The state of the yy_action table under construction is an instance of
412** the following structure
413*/
414typedef struct acttab acttab;
415struct acttab {
416 int nAction; /* Number of used slots in aAction[] */
417 int nActionAlloc; /* Slots allocated for aAction[] */
418 struct {
419 int lookahead; /* Value of the lookahead token */
420 int action; /* Action to take on the given lookahead */
421 } *aAction, /* The yy_action[] table under construction */
422 *aLookahead; /* A single new transaction set */
423 int mnLookahead; /* Minimum aLookahead[].lookahead */
424 int mnAction; /* Action associated with mnLookahead */
425 int mxLookahead; /* Maximum aLookahead[].lookahead */
426 int nLookahead; /* Used slots in aLookahead[] */
427 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
428};
429
430/* Return the number of entries in the yy_action table */
431#define acttab_size(X) ((X)->nAction)
432
433/* The value for the N-th entry in yy_action */
434#define acttab_yyaction(X,N) ((X)->aAction[N].action)
435
436/* The value for the N-th entry in yy_lookahead */
437#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
438
439/* Free all memory associated with the given acttab */
440void acttab_free(acttab *p){
441 free( p->aAction );
442 free( p->aLookahead );
443 free( p );
444}
445
446/* Allocate a new acttab structure */
447acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000448 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000449 if( p==0 ){
450 fprintf(stderr,"Unable to allocate memory for a new acttab.");
451 exit(1);
452 }
453 memset(p, 0, sizeof(*p));
454 return p;
455}
456
457/* Add a new action to the current transaction set
458*/
459void acttab_action(acttab *p, int lookahead, int action){
460 if( p->nLookahead>=p->nLookaheadAlloc ){
461 p->nLookaheadAlloc += 25;
462 p->aLookahead = realloc( p->aLookahead,
463 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
464 if( p->aLookahead==0 ){
465 fprintf(stderr,"malloc failed\n");
466 exit(1);
467 }
468 }
469 if( p->nLookahead==0 ){
470 p->mxLookahead = lookahead;
471 p->mnLookahead = lookahead;
472 p->mnAction = action;
473 }else{
474 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
475 if( p->mnLookahead>lookahead ){
476 p->mnLookahead = lookahead;
477 p->mnAction = action;
478 }
479 }
480 p->aLookahead[p->nLookahead].lookahead = lookahead;
481 p->aLookahead[p->nLookahead].action = action;
482 p->nLookahead++;
483}
484
485/*
486** Add the transaction set built up with prior calls to acttab_action()
487** into the current action table. Then reset the transaction set back
488** to an empty set in preparation for a new round of acttab_action() calls.
489**
490** Return the offset into the action table of the new transaction.
491*/
492int acttab_insert(acttab *p){
493 int i, j, k, n;
494 assert( p->nLookahead>0 );
495
496 /* Make sure we have enough space to hold the expanded action table
497 ** in the worst case. The worst case occurs if the transaction set
498 ** must be appended to the current action table
499 */
drh784d86f2004-02-19 18:41:53 +0000500 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000501 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000502 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000503 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
504 p->aAction = realloc( p->aAction,
505 sizeof(p->aAction[0])*p->nActionAlloc);
506 if( p->aAction==0 ){
507 fprintf(stderr,"malloc failed\n");
508 exit(1);
509 }
drhfdbf9282003-10-21 16:34:41 +0000510 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000511 p->aAction[i].lookahead = -1;
512 p->aAction[i].action = -1;
513 }
514 }
515
516 /* Scan the existing action table looking for an offset where we can
517 ** insert the current transaction set. Fall out of the loop when that
518 ** offset is found. In the worst case, we fall out of the loop when
519 ** i reaches p->nAction, which means we append the new transaction set.
520 **
521 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
522 */
drhf16371d2009-11-03 19:18:31 +0000523 for(i=p->nAction-1; i>=0; i--){
524 /* First look for an existing action table entry that can be reused */
525 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8b582012003-10-21 13:16:03 +0000526 if( p->aAction[i].action!=p->mnAction ) continue;
527 for(j=0; j<p->nLookahead; j++){
528 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
529 if( k<0 || k>=p->nAction ) break;
530 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
531 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
532 }
533 if( j<p->nLookahead ) continue;
534 n = 0;
535 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000536 if( p->aAction[j].lookahead<0 ) continue;
537 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000538 }
drhfdbf9282003-10-21 16:34:41 +0000539 if( n==p->nLookahead ){
540 break; /* Same as a prior transaction set */
541 }
drh8b582012003-10-21 13:16:03 +0000542 }
543 }
drhf16371d2009-11-03 19:18:31 +0000544 if( i<0 ){
545 /* If no reusable entry is found, look for an empty slot */
546 for(i=0; i<p->nAction; i++){
547 if( p->aAction[i].lookahead<0 ){
548 for(j=0; j<p->nLookahead; j++){
549 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
550 if( k<0 ) break;
551 if( p->aAction[k].lookahead>=0 ) break;
552 }
553 if( j<p->nLookahead ) continue;
554 for(j=0; j<p->nAction; j++){
555 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
556 }
557 if( j==p->nAction ){
558 break; /* Fits in empty slots */
559 }
560 }
561 }
562 }
drh8b582012003-10-21 13:16:03 +0000563 /* Insert transaction set at index i. */
564 for(j=0; j<p->nLookahead; j++){
565 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
566 p->aAction[k] = p->aLookahead[j];
567 if( k>=p->nAction ) p->nAction = k+1;
568 }
569 p->nLookahead = 0;
570
571 /* Return the offset that is added to the lookahead in order to get the
572 ** index into yy_action of the action */
573 return i - p->mnLookahead;
574}
575
drh75897232000-05-29 14:26:00 +0000576/********************** From the file "build.c" *****************************/
577/*
578** Routines to construction the finite state machine for the LEMON
579** parser generator.
580*/
581
582/* Find a precedence symbol of every rule in the grammar.
583**
584** Those rules which have a precedence symbol coded in the input
585** grammar using the "[symbol]" construct will already have the
586** rp->precsym field filled. Other rules take as their precedence
587** symbol the first RHS symbol with a defined precedence. If there
588** are not RHS symbols with a defined precedence, the precedence
589** symbol field is left blank.
590*/
591void FindRulePrecedences(xp)
592struct lemon *xp;
593{
594 struct rule *rp;
595 for(rp=xp->rule; rp; rp=rp->next){
596 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000597 int i, j;
598 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
599 struct symbol *sp = rp->rhs[i];
600 if( sp->type==MULTITERMINAL ){
601 for(j=0; j<sp->nsubsym; j++){
602 if( sp->subsym[j]->prec>=0 ){
603 rp->precsym = sp->subsym[j];
604 break;
605 }
606 }
607 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000608 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000609 }
610 }
611 }
612 }
613 return;
614}
615
616/* Find all nonterminals which will generate the empty string.
617** Then go back and compute the first sets of every nonterminal.
618** The first set is the set of all terminal symbols which can begin
619** a string generated by that nonterminal.
620*/
621void FindFirstSets(lemp)
622struct lemon *lemp;
623{
drhfd405312005-11-06 04:06:59 +0000624 int i, j;
drh75897232000-05-29 14:26:00 +0000625 struct rule *rp;
626 int progress;
627
628 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000629 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000630 }
631 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
632 lemp->symbols[i]->firstset = SetNew();
633 }
634
635 /* First compute all lambdas */
636 do{
637 progress = 0;
638 for(rp=lemp->rule; rp; rp=rp->next){
639 if( rp->lhs->lambda ) continue;
640 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000641 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000642 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000643 }
644 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000645 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000646 progress = 1;
647 }
648 }
649 }while( progress );
650
651 /* Now compute all first sets */
652 do{
653 struct symbol *s1, *s2;
654 progress = 0;
655 for(rp=lemp->rule; rp; rp=rp->next){
656 s1 = rp->lhs;
657 for(i=0; i<rp->nrhs; i++){
658 s2 = rp->rhs[i];
659 if( s2->type==TERMINAL ){
660 progress += SetAdd(s1->firstset,s2->index);
661 break;
drhfd405312005-11-06 04:06:59 +0000662 }else if( s2->type==MULTITERMINAL ){
663 for(j=0; j<s2->nsubsym; j++){
664 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
665 }
666 break;
drh75897232000-05-29 14:26:00 +0000667 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000668 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000669 }else{
670 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000671 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000672 }
673 }
674 }
675 }while( progress );
676 return;
677}
678
679/* Compute all LR(0) states for the grammar. Links
680** are added to between some states so that the LR(1) follow sets
681** can be computed later.
682*/
683PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
684void FindStates(lemp)
685struct lemon *lemp;
686{
687 struct symbol *sp;
688 struct rule *rp;
689
690 Configlist_init();
691
692 /* Find the start symbol */
693 if( lemp->start ){
694 sp = Symbol_find(lemp->start);
695 if( sp==0 ){
696 ErrorMsg(lemp->filename,0,
697"The specified start symbol \"%s\" is not \
698in a nonterminal of the grammar. \"%s\" will be used as the start \
699symbol instead.",lemp->start,lemp->rule->lhs->name);
700 lemp->errorcnt++;
701 sp = lemp->rule->lhs;
702 }
703 }else{
704 sp = lemp->rule->lhs;
705 }
706
707 /* Make sure the start symbol doesn't occur on the right-hand side of
708 ** any rule. Report an error if it does. (YACC would generate a new
709 ** start symbol in this case.) */
710 for(rp=lemp->rule; rp; rp=rp->next){
711 int i;
712 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000713 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000714 ErrorMsg(lemp->filename,0,
715"The start symbol \"%s\" occurs on the \
716right-hand side of a rule. This will result in a parser which \
717does not work properly.",sp->name);
718 lemp->errorcnt++;
719 }
720 }
721 }
722
723 /* The basis configuration set for the first state
724 ** is all rules which have the start symbol as their
725 ** left-hand side */
726 for(rp=sp->rule; rp; rp=rp->nextlhs){
727 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000728 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000729 newcfp = Configlist_addbasis(rp,0);
730 SetAdd(newcfp->fws,0);
731 }
732
733 /* Compute the first state. All other states will be
734 ** computed automatically during the computation of the first one.
735 ** The returned pointer to the first state is not used. */
736 (void)getstate(lemp);
737 return;
738}
739
740/* Return a pointer to a state which is described by the configuration
741** list which has been built from calls to Configlist_add.
742*/
743PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
744PRIVATE struct state *getstate(lemp)
745struct lemon *lemp;
746{
747 struct config *cfp, *bp;
748 struct state *stp;
749
750 /* Extract the sorted basis of the new state. The basis was constructed
751 ** by prior calls to "Configlist_addbasis()". */
752 Configlist_sortbasis();
753 bp = Configlist_basis();
754
755 /* Get a state with the same basis */
756 stp = State_find(bp);
757 if( stp ){
758 /* A state with the same basis already exists! Copy all the follow-set
759 ** propagation links from the state under construction into the
760 ** preexisting state, then return a pointer to the preexisting state */
761 struct config *x, *y;
762 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
763 Plink_copy(&y->bplp,x->bplp);
764 Plink_delete(x->fplp);
765 x->fplp = x->bplp = 0;
766 }
767 cfp = Configlist_return();
768 Configlist_eat(cfp);
769 }else{
770 /* This really is a new state. Construct all the details */
771 Configlist_closure(lemp); /* Compute the configuration closure */
772 Configlist_sort(); /* Sort the configuration closure */
773 cfp = Configlist_return(); /* Get a pointer to the config list */
774 stp = State_new(); /* A new state structure */
775 MemoryCheck(stp);
776 stp->bp = bp; /* Remember the configuration basis */
777 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000778 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000779 stp->ap = 0; /* No actions, yet. */
780 State_insert(stp,stp->bp); /* Add to the state table */
781 buildshifts(lemp,stp); /* Recursively compute successor states */
782 }
783 return stp;
784}
785
drhfd405312005-11-06 04:06:59 +0000786/*
787** Return true if two symbols are the same.
788*/
789int same_symbol(a,b)
790struct symbol *a;
791struct symbol *b;
792{
793 int i;
794 if( a==b ) return 1;
795 if( a->type!=MULTITERMINAL ) return 0;
796 if( b->type!=MULTITERMINAL ) return 0;
797 if( a->nsubsym!=b->nsubsym ) return 0;
798 for(i=0; i<a->nsubsym; i++){
799 if( a->subsym[i]!=b->subsym[i] ) return 0;
800 }
801 return 1;
802}
803
drh75897232000-05-29 14:26:00 +0000804/* Construct all successor states to the given state. A "successor"
805** state is any state which can be reached by a shift action.
806*/
807PRIVATE void buildshifts(lemp,stp)
808struct lemon *lemp;
809struct state *stp; /* The state from which successors are computed */
810{
811 struct config *cfp; /* For looping thru the config closure of "stp" */
812 struct config *bcfp; /* For the inner loop on config closure of "stp" */
813 struct config *new; /* */
814 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
815 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
816 struct state *newstp; /* A pointer to a successor state */
817
818 /* Each configuration becomes complete after it contibutes to a successor
819 ** state. Initially, all configurations are incomplete */
820 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
821
822 /* Loop through all configurations of the state "stp" */
823 for(cfp=stp->cfp; cfp; cfp=cfp->next){
824 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
825 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
826 Configlist_reset(); /* Reset the new config set */
827 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
828
829 /* For every configuration in the state "stp" which has the symbol "sp"
830 ** following its dot, add the same configuration to the basis set under
831 ** construction but with the dot shifted one symbol to the right. */
832 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
833 if( bcfp->status==COMPLETE ) continue; /* Already used */
834 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
835 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000836 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000837 bcfp->status = COMPLETE; /* Mark this config as used */
838 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
839 Plink_add(&new->bplp,bcfp);
840 }
841
842 /* Get a pointer to the state described by the basis configuration set
843 ** constructed in the preceding loop */
844 newstp = getstate(lemp);
845
846 /* The state "newstp" is reached from the state "stp" by a shift action
847 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000848 if( sp->type==MULTITERMINAL ){
849 int i;
850 for(i=0; i<sp->nsubsym; i++){
851 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
852 }
853 }else{
854 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
855 }
drh75897232000-05-29 14:26:00 +0000856 }
857}
858
859/*
860** Construct the propagation links
861*/
862void FindLinks(lemp)
863struct lemon *lemp;
864{
865 int i;
866 struct config *cfp, *other;
867 struct state *stp;
868 struct plink *plp;
869
870 /* Housekeeping detail:
871 ** Add to every propagate link a pointer back to the state to
872 ** which the link is attached. */
873 for(i=0; i<lemp->nstate; i++){
874 stp = lemp->sorted[i];
875 for(cfp=stp->cfp; cfp; cfp=cfp->next){
876 cfp->stp = stp;
877 }
878 }
879
880 /* Convert all backlinks into forward links. Only the forward
881 ** links are used in the follow-set computation. */
882 for(i=0; i<lemp->nstate; i++){
883 stp = lemp->sorted[i];
884 for(cfp=stp->cfp; cfp; cfp=cfp->next){
885 for(plp=cfp->bplp; plp; plp=plp->next){
886 other = plp->cfp;
887 Plink_add(&other->fplp,cfp);
888 }
889 }
890 }
891}
892
893/* Compute all followsets.
894**
895** A followset is the set of all symbols which can come immediately
896** after a configuration.
897*/
898void FindFollowSets(lemp)
899struct lemon *lemp;
900{
901 int i;
902 struct config *cfp;
903 struct plink *plp;
904 int progress;
905 int change;
906
907 for(i=0; i<lemp->nstate; i++){
908 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
909 cfp->status = INCOMPLETE;
910 }
911 }
912
913 do{
914 progress = 0;
915 for(i=0; i<lemp->nstate; i++){
916 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
917 if( cfp->status==COMPLETE ) continue;
918 for(plp=cfp->fplp; plp; plp=plp->next){
919 change = SetUnion(plp->cfp->fws,cfp->fws);
920 if( change ){
921 plp->cfp->status = INCOMPLETE;
922 progress = 1;
923 }
924 }
925 cfp->status = COMPLETE;
926 }
927 }
928 }while( progress );
929}
930
931static int resolve_conflict();
932
933/* Compute the reduce actions, and resolve conflicts.
934*/
935void FindActions(lemp)
936struct lemon *lemp;
937{
938 int i,j;
939 struct config *cfp;
940 struct state *stp;
941 struct symbol *sp;
942 struct rule *rp;
943
944 /* Add all of the reduce actions
945 ** A reduce action is added for each element of the followset of
946 ** a configuration which has its dot at the extreme right.
947 */
948 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
949 stp = lemp->sorted[i];
950 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
951 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
952 for(j=0; j<lemp->nterminal; j++){
953 if( SetFind(cfp->fws,j) ){
954 /* Add a reduce action to the state "stp" which will reduce by the
955 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000956 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000957 }
958 }
959 }
960 }
961 }
962
963 /* Add the accepting token */
964 if( lemp->start ){
965 sp = Symbol_find(lemp->start);
966 if( sp==0 ) sp = lemp->rule->lhs;
967 }else{
968 sp = lemp->rule->lhs;
969 }
970 /* Add to the first state (which is always the starting state of the
971 ** finite state machine) an action to ACCEPT if the lookahead is the
972 ** start nonterminal. */
973 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
974
975 /* Resolve conflicts */
976 for(i=0; i<lemp->nstate; i++){
977 struct action *ap, *nap;
978 struct state *stp;
979 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000980 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000981 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000982 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000983 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
984 /* The two actions "ap" and "nap" have the same lookahead.
985 ** Figure out which one should be used */
986 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
987 }
988 }
989 }
990
991 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000992 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000993 for(i=0; i<lemp->nstate; i++){
994 struct action *ap;
995 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000996 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000997 }
998 }
999 for(rp=lemp->rule; rp; rp=rp->next){
1000 if( rp->canReduce ) continue;
1001 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1002 lemp->errorcnt++;
1003 }
1004}
1005
1006/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001007** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001008**
1009** NO LONGER TRUE:
1010** To resolve a conflict, first look to see if either action
1011** is on an error rule. In that case, take the action which
1012** is not associated with the error rule. If neither or both
1013** actions are associated with an error rule, then try to
1014** use precedence to resolve the conflict.
1015**
1016** If either action is a SHIFT, then it must be apx. This
1017** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1018*/
1019static int resolve_conflict(apx,apy,errsym)
1020struct action *apx;
1021struct action *apy;
1022struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1023{
1024 struct symbol *spx, *spy;
1025 int errcnt = 0;
1026 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001027 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001028 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001029 errcnt++;
1030 }
drh75897232000-05-29 14:26:00 +00001031 if( apx->type==SHIFT && apy->type==REDUCE ){
1032 spx = apx->sp;
1033 spy = apy->x.rp->precsym;
1034 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1035 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001036 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001037 errcnt++;
1038 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1039 apy->type = RD_RESOLVED;
1040 }else if( spx->prec<spy->prec ){
1041 apx->type = SH_RESOLVED;
1042 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1043 apy->type = RD_RESOLVED; /* associativity */
1044 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1045 apx->type = SH_RESOLVED;
1046 }else{
1047 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001048 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001049 errcnt++;
1050 }
1051 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1052 spx = apx->x.rp->precsym;
1053 spy = apy->x.rp->precsym;
1054 if( spx==0 || spy==0 || spx->prec<0 ||
1055 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001056 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001057 errcnt++;
1058 }else if( spx->prec>spy->prec ){
1059 apy->type = RD_RESOLVED;
1060 }else if( spx->prec<spy->prec ){
1061 apx->type = RD_RESOLVED;
1062 }
1063 }else{
drhb59499c2002-02-23 18:45:13 +00001064 assert(
1065 apx->type==SH_RESOLVED ||
1066 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001067 apx->type==SSCONFLICT ||
1068 apx->type==SRCONFLICT ||
1069 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001070 apy->type==SH_RESOLVED ||
1071 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001072 apy->type==SSCONFLICT ||
1073 apy->type==SRCONFLICT ||
1074 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001075 );
1076 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1077 ** REDUCEs on the list. If we reach this point it must be because
1078 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001079 }
1080 return errcnt;
1081}
1082/********************* From the file "configlist.c" *************************/
1083/*
1084** Routines to processing a configuration list and building a state
1085** in the LEMON parser generator.
1086*/
1087
1088static struct config *freelist = 0; /* List of free configurations */
1089static struct config *current = 0; /* Top of list of configurations */
1090static struct config **currentend = 0; /* Last on list of configs */
1091static struct config *basis = 0; /* Top of list of basis configs */
1092static struct config **basisend = 0; /* End of list of basis configs */
1093
1094/* Return a pointer to a new configuration */
1095PRIVATE struct config *newconfig(){
1096 struct config *new;
1097 if( freelist==0 ){
1098 int i;
1099 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001100 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001101 if( freelist==0 ){
1102 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1103 exit(1);
1104 }
1105 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1106 freelist[amt-1].next = 0;
1107 }
1108 new = freelist;
1109 freelist = freelist->next;
1110 return new;
1111}
1112
1113/* The configuration "old" is no longer used */
1114PRIVATE void deleteconfig(old)
1115struct config *old;
1116{
1117 old->next = freelist;
1118 freelist = old;
1119}
1120
1121/* Initialized the configuration list builder */
1122void Configlist_init(){
1123 current = 0;
1124 currentend = &current;
1125 basis = 0;
1126 basisend = &basis;
1127 Configtable_init();
1128 return;
1129}
1130
1131/* Initialized the configuration list builder */
1132void Configlist_reset(){
1133 current = 0;
1134 currentend = &current;
1135 basis = 0;
1136 basisend = &basis;
1137 Configtable_clear(0);
1138 return;
1139}
1140
1141/* Add another configuration to the configuration list */
1142struct config *Configlist_add(rp,dot)
1143struct rule *rp; /* The rule */
1144int dot; /* Index into the RHS of the rule where the dot goes */
1145{
1146 struct config *cfp, model;
1147
1148 assert( currentend!=0 );
1149 model.rp = rp;
1150 model.dot = dot;
1151 cfp = Configtable_find(&model);
1152 if( cfp==0 ){
1153 cfp = newconfig();
1154 cfp->rp = rp;
1155 cfp->dot = dot;
1156 cfp->fws = SetNew();
1157 cfp->stp = 0;
1158 cfp->fplp = cfp->bplp = 0;
1159 cfp->next = 0;
1160 cfp->bp = 0;
1161 *currentend = cfp;
1162 currentend = &cfp->next;
1163 Configtable_insert(cfp);
1164 }
1165 return cfp;
1166}
1167
1168/* Add a basis configuration to the configuration list */
1169struct config *Configlist_addbasis(rp,dot)
1170struct rule *rp;
1171int dot;
1172{
1173 struct config *cfp, model;
1174
1175 assert( basisend!=0 );
1176 assert( currentend!=0 );
1177 model.rp = rp;
1178 model.dot = dot;
1179 cfp = Configtable_find(&model);
1180 if( cfp==0 ){
1181 cfp = newconfig();
1182 cfp->rp = rp;
1183 cfp->dot = dot;
1184 cfp->fws = SetNew();
1185 cfp->stp = 0;
1186 cfp->fplp = cfp->bplp = 0;
1187 cfp->next = 0;
1188 cfp->bp = 0;
1189 *currentend = cfp;
1190 currentend = &cfp->next;
1191 *basisend = cfp;
1192 basisend = &cfp->bp;
1193 Configtable_insert(cfp);
1194 }
1195 return cfp;
1196}
1197
1198/* Compute the closure of the configuration list */
1199void Configlist_closure(lemp)
1200struct lemon *lemp;
1201{
1202 struct config *cfp, *newcfp;
1203 struct rule *rp, *newrp;
1204 struct symbol *sp, *xsp;
1205 int i, dot;
1206
1207 assert( currentend!=0 );
1208 for(cfp=current; cfp; cfp=cfp->next){
1209 rp = cfp->rp;
1210 dot = cfp->dot;
1211 if( dot>=rp->nrhs ) continue;
1212 sp = rp->rhs[dot];
1213 if( sp->type==NONTERMINAL ){
1214 if( sp->rule==0 && sp!=lemp->errsym ){
1215 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1216 sp->name);
1217 lemp->errorcnt++;
1218 }
1219 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1220 newcfp = Configlist_add(newrp,0);
1221 for(i=dot+1; i<rp->nrhs; i++){
1222 xsp = rp->rhs[i];
1223 if( xsp->type==TERMINAL ){
1224 SetAdd(newcfp->fws,xsp->index);
1225 break;
drhfd405312005-11-06 04:06:59 +00001226 }else if( xsp->type==MULTITERMINAL ){
1227 int k;
1228 for(k=0; k<xsp->nsubsym; k++){
1229 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1230 }
1231 break;
drh75897232000-05-29 14:26:00 +00001232 }else{
1233 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001234 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001235 }
1236 }
1237 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1238 }
1239 }
1240 }
1241 return;
1242}
1243
1244/* Sort the configuration list */
1245void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001246 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001247 currentend = 0;
1248 return;
1249}
1250
1251/* Sort the basis configuration list */
1252void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001253 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001254 basisend = 0;
1255 return;
1256}
1257
1258/* Return a pointer to the head of the configuration list and
1259** reset the list */
1260struct config *Configlist_return(){
1261 struct config *old;
1262 old = current;
1263 current = 0;
1264 currentend = 0;
1265 return old;
1266}
1267
1268/* Return a pointer to the head of the configuration list and
1269** reset the list */
1270struct config *Configlist_basis(){
1271 struct config *old;
1272 old = basis;
1273 basis = 0;
1274 basisend = 0;
1275 return old;
1276}
1277
1278/* Free all elements of the given configuration list */
1279void Configlist_eat(cfp)
1280struct config *cfp;
1281{
1282 struct config *nextcfp;
1283 for(; cfp; cfp=nextcfp){
1284 nextcfp = cfp->next;
1285 assert( cfp->fplp==0 );
1286 assert( cfp->bplp==0 );
1287 if( cfp->fws ) SetFree(cfp->fws);
1288 deleteconfig(cfp);
1289 }
1290 return;
1291}
1292/***************** From the file "error.c" *********************************/
1293/*
1294** Code for printing error message.
1295*/
1296
1297/* Find a good place to break "msg" so that its length is at least "min"
1298** but no more than "max". Make the point as close to max as possible.
1299*/
1300static int findbreak(msg,min,max)
1301char *msg;
1302int min;
1303int max;
1304{
1305 int i,spot;
1306 char c;
1307 for(i=spot=min; i<=max; i++){
1308 c = msg[i];
1309 if( c=='\t' ) msg[i] = ' ';
1310 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1311 if( c==0 ){ spot = i; break; }
1312 if( c=='-' && i<max-1 ) spot = i+1;
1313 if( c==' ' ) spot = i;
1314 }
1315 return spot;
1316}
1317
1318/*
1319** The error message is split across multiple lines if necessary. The
1320** splits occur at a space, if there is a space available near the end
1321** of the line.
1322*/
1323#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1324#define LINEWIDTH 79 /* Max width of any output line */
1325#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001326void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001327 char errmsg[ERRMSGSIZE];
1328 char prefix[PREFIXLIMIT+10];
1329 int errmsgsize;
1330 int prefixsize;
1331 int availablewidth;
1332 va_list ap;
1333 int end, restart, base;
1334
drhf9a2e7b2003-04-15 01:49:48 +00001335 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001336 /* Prepare a prefix to be prepended to every output line */
1337 if( lineno>0 ){
1338 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1339 }else{
1340 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1341 }
drh87cf1372008-08-13 20:09:06 +00001342 prefixsize = lemonStrlen(prefix);
drh75897232000-05-29 14:26:00 +00001343 availablewidth = LINEWIDTH - prefixsize;
1344
1345 /* Generate the error message */
1346 vsprintf(errmsg,format,ap);
1347 va_end(ap);
drh87cf1372008-08-13 20:09:06 +00001348 errmsgsize = lemonStrlen(errmsg);
drh75897232000-05-29 14:26:00 +00001349 /* Remove trailing '\n's from the error message. */
1350 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1351 errmsg[--errmsgsize] = 0;
1352 }
1353
1354 /* Print the error message */
1355 base = 0;
1356 while( errmsg[base]!=0 ){
1357 end = restart = findbreak(&errmsg[base],0,availablewidth);
1358 restart += base;
1359 while( errmsg[restart]==' ' ) restart++;
1360 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1361 base = restart;
1362 }
1363}
1364/**************** From the file "main.c" ************************************/
1365/*
1366** Main program file for the LEMON parser generator.
1367*/
1368
1369/* Report an out-of-memory condition and abort. This function
1370** is used mostly by the "MemoryCheck" macro in struct.h
1371*/
1372void memory_error(){
1373 fprintf(stderr,"Out of memory. Aborting...\n");
1374 exit(1);
1375}
1376
drh6d08b4d2004-07-20 12:45:22 +00001377static int nDefine = 0; /* Number of -D options on the command line */
1378static char **azDefine = 0; /* Name of the -D macros */
1379
1380/* This routine is called with the argument to each -D command-line option.
1381** Add the macro defined to the azDefine array.
1382*/
1383static void handle_D_option(char *z){
1384 char **paz;
1385 nDefine++;
1386 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1387 if( azDefine==0 ){
1388 fprintf(stderr,"out of memory\n");
1389 exit(1);
1390 }
1391 paz = &azDefine[nDefine-1];
drh87cf1372008-08-13 20:09:06 +00001392 *paz = malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001393 if( *paz==0 ){
1394 fprintf(stderr,"out of memory\n");
1395 exit(1);
1396 }
1397 strcpy(*paz, z);
1398 for(z=*paz; *z && *z!='='; z++){}
1399 *z = 0;
1400}
1401
drh75897232000-05-29 14:26:00 +00001402
1403/* The main program. Parse the command line and do it... */
1404int main(argc,argv)
1405int argc;
1406char **argv;
1407{
1408 static int version = 0;
1409 static int rpflag = 0;
1410 static int basisflag = 0;
1411 static int compress = 0;
1412 static int quiet = 0;
1413 static int statistics = 0;
1414 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001415 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001416 static struct s_options options[] = {
1417 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1418 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001419 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001420 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001421 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1422 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001423 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001424 {OPT_FLAG, "s", (char*)&statistics,
1425 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001426 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1427 {OPT_FLAG,0,0,0}
1428 };
1429 int i;
1430 struct lemon lem;
1431
drhb0c86772000-06-02 23:21:26 +00001432 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001433 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001434 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001435 exit(0);
1436 }
drhb0c86772000-06-02 23:21:26 +00001437 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001438 fprintf(stderr,"Exactly one filename argument is required.\n");
1439 exit(1);
1440 }
drh954f6b42006-06-13 13:27:46 +00001441 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001442 lem.errorcnt = 0;
1443
1444 /* Initialize the machine */
1445 Strsafe_init();
1446 Symbol_init();
1447 State_init();
1448 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001449 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001450 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001451 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001452 Symbol_new("$");
1453 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001454 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001455
1456 /* Parse the input file */
1457 Parse(&lem);
1458 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001459 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001460 fprintf(stderr,"Empty grammar.\n");
1461 exit(1);
1462 }
1463
1464 /* Count and index the symbols of the grammar */
1465 lem.nsymbol = Symbol_count();
1466 Symbol_new("{default}");
1467 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001468 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001469 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1470 (int(*)())Symbolcmpp);
1471 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1472 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1473 lem.nterminal = i;
1474
1475 /* Generate a reprint of the grammar, if requested on the command line */
1476 if( rpflag ){
1477 Reprint(&lem);
1478 }else{
1479 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001480 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001481
1482 /* Find the precedence for every production rule (that has one) */
1483 FindRulePrecedences(&lem);
1484
1485 /* Compute the lambda-nonterminals and the first-sets for every
1486 ** nonterminal */
1487 FindFirstSets(&lem);
1488
1489 /* Compute all LR(0) states. Also record follow-set propagation
1490 ** links so that the follow-set can be computed later */
1491 lem.nstate = 0;
1492 FindStates(&lem);
1493 lem.sorted = State_arrayof();
1494
1495 /* Tie up loose ends on the propagation links */
1496 FindLinks(&lem);
1497
1498 /* Compute the follow set of every reducible configuration */
1499 FindFollowSets(&lem);
1500
1501 /* Compute the action tables */
1502 FindActions(&lem);
1503
1504 /* Compress the action tables */
1505 if( compress==0 ) CompressTables(&lem);
1506
drhada354d2005-11-05 15:03:59 +00001507 /* Reorder and renumber the states so that states with fewer choices
1508 ** occur at the end. */
1509 ResortStates(&lem);
1510
drh75897232000-05-29 14:26:00 +00001511 /* Generate a report of the parser generated. (the "y.output" file) */
1512 if( !quiet ) ReportOutput(&lem);
1513
1514 /* Generate the source code for the parser */
1515 ReportTable(&lem, mhflag);
1516
1517 /* Produce a header file for use by the scanner. (This step is
1518 ** omitted if the "-m" option is used because makeheaders will
1519 ** generate the file for us.) */
1520 if( !mhflag ) ReportHeader(&lem);
1521 }
1522 if( statistics ){
1523 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1524 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1525 printf(" %d states, %d parser table entries, %d conflicts\n",
1526 lem.nstate, lem.tablesize, lem.nconflict);
1527 }
1528 if( lem.nconflict ){
1529 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1530 }
1531 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001532 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001533}
1534/******************** From the file "msort.c" *******************************/
1535/*
1536** A generic merge-sort program.
1537**
1538** USAGE:
1539** Let "ptr" be a pointer to some structure which is at the head of
1540** a null-terminated list. Then to sort the list call:
1541**
1542** ptr = msort(ptr,&(ptr->next),cmpfnc);
1543**
1544** In the above, "cmpfnc" is a pointer to a function which compares
1545** two instances of the structure and returns an integer, as in
1546** strcmp. The second argument is a pointer to the pointer to the
1547** second element of the linked list. This address is used to compute
1548** the offset to the "next" field within the structure. The offset to
1549** the "next" field must be constant for all structures in the list.
1550**
1551** The function returns a new pointer which is the head of the list
1552** after sorting.
1553**
1554** ALGORITHM:
1555** Merge-sort.
1556*/
1557
1558/*
1559** Return a pointer to the next structure in the linked list.
1560*/
drhba99af52001-10-25 20:37:16 +00001561#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001562
1563/*
1564** Inputs:
1565** a: A sorted, null-terminated linked list. (May be null).
1566** b: A sorted, null-terminated linked list. (May be null).
1567** cmp: A pointer to the comparison function.
1568** offset: Offset in the structure to the "next" field.
1569**
1570** Return Value:
1571** A pointer to the head of a sorted list containing the elements
1572** of both a and b.
1573**
1574** Side effects:
1575** The "next" pointers for elements in the lists a and b are
1576** changed.
1577*/
drhe9278182007-07-18 18:16:29 +00001578static char *merge(
1579 char *a,
1580 char *b,
1581 int (*cmp)(const char*,const char*),
1582 int offset
1583){
drh75897232000-05-29 14:26:00 +00001584 char *ptr, *head;
1585
1586 if( a==0 ){
1587 head = b;
1588 }else if( b==0 ){
1589 head = a;
1590 }else{
drhe594bc32009-11-03 13:02:25 +00001591 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001592 ptr = a;
1593 a = NEXT(a);
1594 }else{
1595 ptr = b;
1596 b = NEXT(b);
1597 }
1598 head = ptr;
1599 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001600 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001601 NEXT(ptr) = a;
1602 ptr = a;
1603 a = NEXT(a);
1604 }else{
1605 NEXT(ptr) = b;
1606 ptr = b;
1607 b = NEXT(b);
1608 }
1609 }
1610 if( a ) NEXT(ptr) = a;
1611 else NEXT(ptr) = b;
1612 }
1613 return head;
1614}
1615
1616/*
1617** Inputs:
1618** list: Pointer to a singly-linked list of structures.
1619** next: Pointer to pointer to the second element of the list.
1620** cmp: A comparison function.
1621**
1622** Return Value:
1623** A pointer to the head of a sorted list containing the elements
1624** orginally in list.
1625**
1626** Side effects:
1627** The "next" pointers for elements in list are changed.
1628*/
1629#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001630static char *msort(
1631 char *list,
1632 char **next,
1633 int (*cmp)(const char*,const char*)
1634){
drhba99af52001-10-25 20:37:16 +00001635 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001636 char *ep;
1637 char *set[LISTSIZE];
1638 int i;
drhba99af52001-10-25 20:37:16 +00001639 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001640 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1641 while( list ){
1642 ep = list;
1643 list = NEXT(list);
1644 NEXT(ep) = 0;
1645 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1646 ep = merge(ep,set[i],cmp,offset);
1647 set[i] = 0;
1648 }
1649 set[i] = ep;
1650 }
1651 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001652 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001653 return ep;
1654}
1655/************************ From the file "option.c" **************************/
1656static char **argv;
1657static struct s_options *op;
1658static FILE *errstream;
1659
1660#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1661
1662/*
1663** Print the command line with a carrot pointing to the k-th character
1664** of the n-th field.
1665*/
1666static void errline(n,k,err)
1667int n;
1668int k;
1669FILE *err;
1670{
1671 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001672 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001673 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001674 for(i=1; i<n && argv[i]; i++){
1675 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001676 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001677 }
1678 spcnt += k;
1679 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1680 if( spcnt<20 ){
1681 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1682 }else{
1683 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1684 }
1685}
1686
1687/*
1688** Return the index of the N-th non-switch argument. Return -1
1689** if N is out of range.
1690*/
1691static int argindex(n)
1692int n;
1693{
1694 int i;
1695 int dashdash = 0;
1696 if( argv!=0 && *argv!=0 ){
1697 for(i=1; argv[i]; i++){
1698 if( dashdash || !ISOPT(argv[i]) ){
1699 if( n==0 ) return i;
1700 n--;
1701 }
1702 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1703 }
1704 }
1705 return -1;
1706}
1707
1708static char emsg[] = "Command line syntax error: ";
1709
1710/*
1711** Process a flag command line argument.
1712*/
1713static int handleflags(i,err)
1714int i;
1715FILE *err;
1716{
1717 int v;
1718 int errcnt = 0;
1719 int j;
1720 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001721 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001722 }
1723 v = argv[i][0]=='-' ? 1 : 0;
1724 if( op[j].label==0 ){
1725 if( err ){
1726 fprintf(err,"%sundefined option.\n",emsg);
1727 errline(i,1,err);
1728 }
1729 errcnt++;
1730 }else if( op[j].type==OPT_FLAG ){
1731 *((int*)op[j].arg) = v;
1732 }else if( op[j].type==OPT_FFLAG ){
1733 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001734 }else if( op[j].type==OPT_FSTR ){
1735 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001736 }else{
1737 if( err ){
1738 fprintf(err,"%smissing argument on switch.\n",emsg);
1739 errline(i,1,err);
1740 }
1741 errcnt++;
1742 }
1743 return errcnt;
1744}
1745
1746/*
1747** Process a command line switch which has an argument.
1748*/
1749static int handleswitch(i,err)
1750int i;
1751FILE *err;
1752{
1753 int lv = 0;
1754 double dv = 0.0;
1755 char *sv = 0, *end;
1756 char *cp;
1757 int j;
1758 int errcnt = 0;
1759 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001760 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001761 *cp = 0;
1762 for(j=0; op[j].label; j++){
1763 if( strcmp(argv[i],op[j].label)==0 ) break;
1764 }
1765 *cp = '=';
1766 if( op[j].label==0 ){
1767 if( err ){
1768 fprintf(err,"%sundefined option.\n",emsg);
1769 errline(i,0,err);
1770 }
1771 errcnt++;
1772 }else{
1773 cp++;
1774 switch( op[j].type ){
1775 case OPT_FLAG:
1776 case OPT_FFLAG:
1777 if( err ){
1778 fprintf(err,"%soption requires an argument.\n",emsg);
1779 errline(i,0,err);
1780 }
1781 errcnt++;
1782 break;
1783 case OPT_DBL:
1784 case OPT_FDBL:
1785 dv = strtod(cp,&end);
1786 if( *end ){
1787 if( err ){
1788 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001789 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001790 }
1791 errcnt++;
1792 }
1793 break;
1794 case OPT_INT:
1795 case OPT_FINT:
1796 lv = strtol(cp,&end,0);
1797 if( *end ){
1798 if( err ){
1799 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001800 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001801 }
1802 errcnt++;
1803 }
1804 break;
1805 case OPT_STR:
1806 case OPT_FSTR:
1807 sv = cp;
1808 break;
1809 }
1810 switch( op[j].type ){
1811 case OPT_FLAG:
1812 case OPT_FFLAG:
1813 break;
1814 case OPT_DBL:
1815 *(double*)(op[j].arg) = dv;
1816 break;
1817 case OPT_FDBL:
1818 (*(void(*)())(op[j].arg))(dv);
1819 break;
1820 case OPT_INT:
1821 *(int*)(op[j].arg) = lv;
1822 break;
1823 case OPT_FINT:
1824 (*(void(*)())(op[j].arg))((int)lv);
1825 break;
1826 case OPT_STR:
1827 *(char**)(op[j].arg) = sv;
1828 break;
1829 case OPT_FSTR:
1830 (*(void(*)())(op[j].arg))(sv);
1831 break;
1832 }
1833 }
1834 return errcnt;
1835}
1836
drhb0c86772000-06-02 23:21:26 +00001837int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001838char **a;
1839struct s_options *o;
1840FILE *err;
1841{
1842 int errcnt = 0;
1843 argv = a;
1844 op = o;
1845 errstream = err;
1846 if( argv && *argv && op ){
1847 int i;
1848 for(i=1; argv[i]; i++){
1849 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1850 errcnt += handleflags(i,err);
1851 }else if( strchr(argv[i],'=') ){
1852 errcnt += handleswitch(i,err);
1853 }
1854 }
1855 }
1856 if( errcnt>0 ){
1857 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001858 OptPrint();
drh75897232000-05-29 14:26:00 +00001859 exit(1);
1860 }
1861 return 0;
1862}
1863
drhb0c86772000-06-02 23:21:26 +00001864int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001865 int cnt = 0;
1866 int dashdash = 0;
1867 int i;
1868 if( argv!=0 && argv[0]!=0 ){
1869 for(i=1; argv[i]; i++){
1870 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1871 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1872 }
1873 }
1874 return cnt;
1875}
1876
drhb0c86772000-06-02 23:21:26 +00001877char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001878int n;
1879{
1880 int i;
1881 i = argindex(n);
1882 return i>=0 ? argv[i] : 0;
1883}
1884
drhb0c86772000-06-02 23:21:26 +00001885void OptErr(n)
drh75897232000-05-29 14:26:00 +00001886int n;
1887{
1888 int i;
1889 i = argindex(n);
1890 if( i>=0 ) errline(i,0,errstream);
1891}
1892
drhb0c86772000-06-02 23:21:26 +00001893void OptPrint(){
drh75897232000-05-29 14:26:00 +00001894 int i;
1895 int max, len;
1896 max = 0;
1897 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001898 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001899 switch( op[i].type ){
1900 case OPT_FLAG:
1901 case OPT_FFLAG:
1902 break;
1903 case OPT_INT:
1904 case OPT_FINT:
1905 len += 9; /* length of "<integer>" */
1906 break;
1907 case OPT_DBL:
1908 case OPT_FDBL:
1909 len += 6; /* length of "<real>" */
1910 break;
1911 case OPT_STR:
1912 case OPT_FSTR:
1913 len += 8; /* length of "<string>" */
1914 break;
1915 }
1916 if( len>max ) max = len;
1917 }
1918 for(i=0; op[i].label; i++){
1919 switch( op[i].type ){
1920 case OPT_FLAG:
1921 case OPT_FFLAG:
1922 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1923 break;
1924 case OPT_INT:
1925 case OPT_FINT:
1926 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001927 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001928 break;
1929 case OPT_DBL:
1930 case OPT_FDBL:
1931 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001932 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001933 break;
1934 case OPT_STR:
1935 case OPT_FSTR:
1936 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001937 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001938 break;
1939 }
1940 }
1941}
1942/*********************** From the file "parse.c" ****************************/
1943/*
1944** Input file parser for the LEMON parser generator.
1945*/
1946
1947/* The state of the parser */
1948struct pstate {
1949 char *filename; /* Name of the input file */
1950 int tokenlineno; /* Linenumber at which current token starts */
1951 int errorcnt; /* Number of errors so far */
1952 char *tokenstart; /* Text of current token */
1953 struct lemon *gp; /* Global state vector */
1954 enum e_state {
1955 INITIALIZE,
1956 WAITING_FOR_DECL_OR_RULE,
1957 WAITING_FOR_DECL_KEYWORD,
1958 WAITING_FOR_DECL_ARG,
1959 WAITING_FOR_PRECEDENCE_SYMBOL,
1960 WAITING_FOR_ARROW,
1961 IN_RHS,
1962 LHS_ALIAS_1,
1963 LHS_ALIAS_2,
1964 LHS_ALIAS_3,
1965 RHS_ALIAS_1,
1966 RHS_ALIAS_2,
1967 PRECEDENCE_MARK_1,
1968 PRECEDENCE_MARK_2,
1969 RESYNC_AFTER_RULE_ERROR,
1970 RESYNC_AFTER_DECL_ERROR,
1971 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001972 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001973 WAITING_FOR_FALLBACK_ID,
1974 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001975 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001976 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001977 struct symbol *lhs; /* Left-hand side of current rule */
1978 char *lhsalias; /* Alias for the LHS */
1979 int nrhs; /* Number of right-hand side symbols seen */
1980 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1981 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1982 struct rule *prevrule; /* Previous rule parsed */
1983 char *declkeyword; /* Keyword of a declaration */
1984 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001985 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001986 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001987 enum e_assoc declassoc; /* Assign this association to decl arguments */
1988 int preccounter; /* Assign this precedence to decl arguments */
1989 struct rule *firstrule; /* Pointer to first rule in the grammar */
1990 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1991};
1992
1993/* Parse a single token */
1994static void parseonetoken(psp)
1995struct pstate *psp;
1996{
1997 char *x;
1998 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1999#if 0
2000 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2001 x,psp->state);
2002#endif
2003 switch( psp->state ){
2004 case INITIALIZE:
2005 psp->prevrule = 0;
2006 psp->preccounter = 0;
2007 psp->firstrule = psp->lastrule = 0;
2008 psp->gp->nrule = 0;
2009 /* Fall thru to next case */
2010 case WAITING_FOR_DECL_OR_RULE:
2011 if( x[0]=='%' ){
2012 psp->state = WAITING_FOR_DECL_KEYWORD;
2013 }else if( islower(x[0]) ){
2014 psp->lhs = Symbol_new(x);
2015 psp->nrhs = 0;
2016 psp->lhsalias = 0;
2017 psp->state = WAITING_FOR_ARROW;
2018 }else if( x[0]=='{' ){
2019 if( psp->prevrule==0 ){
2020 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002021"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002022fragment which begins on this line.");
2023 psp->errorcnt++;
2024 }else if( psp->prevrule->code!=0 ){
2025 ErrorMsg(psp->filename,psp->tokenlineno,
2026"Code fragment beginning on this line is not the first \
2027to follow the previous rule.");
2028 psp->errorcnt++;
2029 }else{
2030 psp->prevrule->line = psp->tokenlineno;
2031 psp->prevrule->code = &x[1];
2032 }
2033 }else if( x[0]=='[' ){
2034 psp->state = PRECEDENCE_MARK_1;
2035 }else{
2036 ErrorMsg(psp->filename,psp->tokenlineno,
2037 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2038 x);
2039 psp->errorcnt++;
2040 }
2041 break;
2042 case PRECEDENCE_MARK_1:
2043 if( !isupper(x[0]) ){
2044 ErrorMsg(psp->filename,psp->tokenlineno,
2045 "The precedence symbol must be a terminal.");
2046 psp->errorcnt++;
2047 }else if( psp->prevrule==0 ){
2048 ErrorMsg(psp->filename,psp->tokenlineno,
2049 "There is no prior rule to assign precedence \"[%s]\".",x);
2050 psp->errorcnt++;
2051 }else if( psp->prevrule->precsym!=0 ){
2052 ErrorMsg(psp->filename,psp->tokenlineno,
2053"Precedence mark on this line is not the first \
2054to follow the previous rule.");
2055 psp->errorcnt++;
2056 }else{
2057 psp->prevrule->precsym = Symbol_new(x);
2058 }
2059 psp->state = PRECEDENCE_MARK_2;
2060 break;
2061 case PRECEDENCE_MARK_2:
2062 if( x[0]!=']' ){
2063 ErrorMsg(psp->filename,psp->tokenlineno,
2064 "Missing \"]\" on precedence mark.");
2065 psp->errorcnt++;
2066 }
2067 psp->state = WAITING_FOR_DECL_OR_RULE;
2068 break;
2069 case WAITING_FOR_ARROW:
2070 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2071 psp->state = IN_RHS;
2072 }else if( x[0]=='(' ){
2073 psp->state = LHS_ALIAS_1;
2074 }else{
2075 ErrorMsg(psp->filename,psp->tokenlineno,
2076 "Expected to see a \":\" following the LHS symbol \"%s\".",
2077 psp->lhs->name);
2078 psp->errorcnt++;
2079 psp->state = RESYNC_AFTER_RULE_ERROR;
2080 }
2081 break;
2082 case LHS_ALIAS_1:
2083 if( isalpha(x[0]) ){
2084 psp->lhsalias = x;
2085 psp->state = LHS_ALIAS_2;
2086 }else{
2087 ErrorMsg(psp->filename,psp->tokenlineno,
2088 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2089 x,psp->lhs->name);
2090 psp->errorcnt++;
2091 psp->state = RESYNC_AFTER_RULE_ERROR;
2092 }
2093 break;
2094 case LHS_ALIAS_2:
2095 if( x[0]==')' ){
2096 psp->state = LHS_ALIAS_3;
2097 }else{
2098 ErrorMsg(psp->filename,psp->tokenlineno,
2099 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2100 psp->errorcnt++;
2101 psp->state = RESYNC_AFTER_RULE_ERROR;
2102 }
2103 break;
2104 case LHS_ALIAS_3:
2105 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2106 psp->state = IN_RHS;
2107 }else{
2108 ErrorMsg(psp->filename,psp->tokenlineno,
2109 "Missing \"->\" following: \"%s(%s)\".",
2110 psp->lhs->name,psp->lhsalias);
2111 psp->errorcnt++;
2112 psp->state = RESYNC_AFTER_RULE_ERROR;
2113 }
2114 break;
2115 case IN_RHS:
2116 if( x[0]=='.' ){
2117 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002118 rp = (struct rule *)calloc( sizeof(struct rule) +
2119 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002120 if( rp==0 ){
2121 ErrorMsg(psp->filename,psp->tokenlineno,
2122 "Can't allocate enough memory for this rule.");
2123 psp->errorcnt++;
2124 psp->prevrule = 0;
2125 }else{
2126 int i;
2127 rp->ruleline = psp->tokenlineno;
2128 rp->rhs = (struct symbol**)&rp[1];
2129 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2130 for(i=0; i<psp->nrhs; i++){
2131 rp->rhs[i] = psp->rhs[i];
2132 rp->rhsalias[i] = psp->alias[i];
2133 }
2134 rp->lhs = psp->lhs;
2135 rp->lhsalias = psp->lhsalias;
2136 rp->nrhs = psp->nrhs;
2137 rp->code = 0;
2138 rp->precsym = 0;
2139 rp->index = psp->gp->nrule++;
2140 rp->nextlhs = rp->lhs->rule;
2141 rp->lhs->rule = rp;
2142 rp->next = 0;
2143 if( psp->firstrule==0 ){
2144 psp->firstrule = psp->lastrule = rp;
2145 }else{
2146 psp->lastrule->next = rp;
2147 psp->lastrule = rp;
2148 }
2149 psp->prevrule = rp;
2150 }
2151 psp->state = WAITING_FOR_DECL_OR_RULE;
2152 }else if( isalpha(x[0]) ){
2153 if( psp->nrhs>=MAXRHS ){
2154 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002155 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002156 x);
2157 psp->errorcnt++;
2158 psp->state = RESYNC_AFTER_RULE_ERROR;
2159 }else{
2160 psp->rhs[psp->nrhs] = Symbol_new(x);
2161 psp->alias[psp->nrhs] = 0;
2162 psp->nrhs++;
2163 }
drhfd405312005-11-06 04:06:59 +00002164 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2165 struct symbol *msp = psp->rhs[psp->nrhs-1];
2166 if( msp->type!=MULTITERMINAL ){
2167 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002168 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002169 memset(msp, 0, sizeof(*msp));
2170 msp->type = MULTITERMINAL;
2171 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002172 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002173 msp->subsym[0] = origsp;
2174 msp->name = origsp->name;
2175 psp->rhs[psp->nrhs-1] = msp;
2176 }
2177 msp->nsubsym++;
2178 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2179 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2180 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2181 ErrorMsg(psp->filename,psp->tokenlineno,
2182 "Cannot form a compound containing a non-terminal");
2183 psp->errorcnt++;
2184 }
drh75897232000-05-29 14:26:00 +00002185 }else if( x[0]=='(' && psp->nrhs>0 ){
2186 psp->state = RHS_ALIAS_1;
2187 }else{
2188 ErrorMsg(psp->filename,psp->tokenlineno,
2189 "Illegal character on RHS of rule: \"%s\".",x);
2190 psp->errorcnt++;
2191 psp->state = RESYNC_AFTER_RULE_ERROR;
2192 }
2193 break;
2194 case RHS_ALIAS_1:
2195 if( isalpha(x[0]) ){
2196 psp->alias[psp->nrhs-1] = x;
2197 psp->state = RHS_ALIAS_2;
2198 }else{
2199 ErrorMsg(psp->filename,psp->tokenlineno,
2200 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2201 x,psp->rhs[psp->nrhs-1]->name);
2202 psp->errorcnt++;
2203 psp->state = RESYNC_AFTER_RULE_ERROR;
2204 }
2205 break;
2206 case RHS_ALIAS_2:
2207 if( x[0]==')' ){
2208 psp->state = IN_RHS;
2209 }else{
2210 ErrorMsg(psp->filename,psp->tokenlineno,
2211 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2212 psp->errorcnt++;
2213 psp->state = RESYNC_AFTER_RULE_ERROR;
2214 }
2215 break;
2216 case WAITING_FOR_DECL_KEYWORD:
2217 if( isalpha(x[0]) ){
2218 psp->declkeyword = x;
2219 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002220 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002221 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002222 psp->state = WAITING_FOR_DECL_ARG;
2223 if( strcmp(x,"name")==0 ){
2224 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002225 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002226 }else if( strcmp(x,"include")==0 ){
2227 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002228 }else if( strcmp(x,"code")==0 ){
2229 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002230 }else if( strcmp(x,"token_destructor")==0 ){
2231 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002232 }else if( strcmp(x,"default_destructor")==0 ){
2233 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002234 }else if( strcmp(x,"token_prefix")==0 ){
2235 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002236 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002237 }else if( strcmp(x,"syntax_error")==0 ){
2238 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002239 }else if( strcmp(x,"parse_accept")==0 ){
2240 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002241 }else if( strcmp(x,"parse_failure")==0 ){
2242 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002243 }else if( strcmp(x,"stack_overflow")==0 ){
2244 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002245 }else if( strcmp(x,"extra_argument")==0 ){
2246 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002247 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002248 }else if( strcmp(x,"token_type")==0 ){
2249 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002250 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002251 }else if( strcmp(x,"default_type")==0 ){
2252 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002253 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002254 }else if( strcmp(x,"stack_size")==0 ){
2255 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002256 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002257 }else if( strcmp(x,"start_symbol")==0 ){
2258 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002259 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002260 }else if( strcmp(x,"left")==0 ){
2261 psp->preccounter++;
2262 psp->declassoc = LEFT;
2263 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2264 }else if( strcmp(x,"right")==0 ){
2265 psp->preccounter++;
2266 psp->declassoc = RIGHT;
2267 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2268 }else if( strcmp(x,"nonassoc")==0 ){
2269 psp->preccounter++;
2270 psp->declassoc = NONE;
2271 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2272 }else if( strcmp(x,"destructor")==0 ){
2273 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2274 }else if( strcmp(x,"type")==0 ){
2275 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002276 }else if( strcmp(x,"fallback")==0 ){
2277 psp->fallback = 0;
2278 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002279 }else if( strcmp(x,"wildcard")==0 ){
2280 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002281 }else{
2282 ErrorMsg(psp->filename,psp->tokenlineno,
2283 "Unknown declaration keyword: \"%%%s\".",x);
2284 psp->errorcnt++;
2285 psp->state = RESYNC_AFTER_DECL_ERROR;
2286 }
2287 }else{
2288 ErrorMsg(psp->filename,psp->tokenlineno,
2289 "Illegal declaration keyword: \"%s\".",x);
2290 psp->errorcnt++;
2291 psp->state = RESYNC_AFTER_DECL_ERROR;
2292 }
2293 break;
2294 case WAITING_FOR_DESTRUCTOR_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->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002303 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002304 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002305 psp->state = WAITING_FOR_DECL_ARG;
2306 }
2307 break;
2308 case WAITING_FOR_DATATYPE_SYMBOL:
2309 if( !isalpha(x[0]) ){
2310 ErrorMsg(psp->filename,psp->tokenlineno,
2311 "Symbol name missing after %destructor keyword");
2312 psp->errorcnt++;
2313 psp->state = RESYNC_AFTER_DECL_ERROR;
2314 }else{
2315 struct symbol *sp = Symbol_new(x);
2316 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002317 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002318 psp->state = WAITING_FOR_DECL_ARG;
2319 }
2320 break;
2321 case WAITING_FOR_PRECEDENCE_SYMBOL:
2322 if( x[0]=='.' ){
2323 psp->state = WAITING_FOR_DECL_OR_RULE;
2324 }else if( isupper(x[0]) ){
2325 struct symbol *sp;
2326 sp = Symbol_new(x);
2327 if( sp->prec>=0 ){
2328 ErrorMsg(psp->filename,psp->tokenlineno,
2329 "Symbol \"%s\" has already be given a precedence.",x);
2330 psp->errorcnt++;
2331 }else{
2332 sp->prec = psp->preccounter;
2333 sp->assoc = psp->declassoc;
2334 }
2335 }else{
2336 ErrorMsg(psp->filename,psp->tokenlineno,
2337 "Can't assign a precedence to \"%s\".",x);
2338 psp->errorcnt++;
2339 }
2340 break;
2341 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002342 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2343 char *zOld, *zNew, *zBuf, *z;
2344 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002345 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002346 char zLine[50];
2347 zNew = x;
2348 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002349 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002350 if( *psp->declargslot ){
2351 zOld = *psp->declargslot;
2352 }else{
2353 zOld = "";
2354 }
drh87cf1372008-08-13 20:09:06 +00002355 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002356 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002357 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002358 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2359 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002360 for(z=psp->filename, nBack=0; *z; z++){
2361 if( *z=='\\' ) nBack++;
2362 }
2363 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002364 nLine = lemonStrlen(zLine);
2365 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002366 }
2367 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2368 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002369 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002370 if( nOld && zBuf[-1]!='\n' ){
2371 *(zBuf++) = '\n';
2372 }
2373 memcpy(zBuf, zLine, nLine);
2374 zBuf += nLine;
2375 *(zBuf++) = '"';
2376 for(z=psp->filename; *z; z++){
2377 if( *z=='\\' ){
2378 *(zBuf++) = '\\';
2379 }
2380 *(zBuf++) = *z;
2381 }
2382 *(zBuf++) = '"';
2383 *(zBuf++) = '\n';
2384 }
drh4dc8ef52008-07-01 17:13:57 +00002385 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2386 psp->decllinenoslot[0] = psp->tokenlineno;
2387 }
drha5808f32008-04-27 22:19:44 +00002388 memcpy(zBuf, zNew, nNew);
2389 zBuf += nNew;
2390 *zBuf = 0;
2391 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002392 }else{
2393 ErrorMsg(psp->filename,psp->tokenlineno,
2394 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2395 psp->errorcnt++;
2396 psp->state = RESYNC_AFTER_DECL_ERROR;
2397 }
2398 break;
drh0bd1f4e2002-06-06 18:54:39 +00002399 case WAITING_FOR_FALLBACK_ID:
2400 if( x[0]=='.' ){
2401 psp->state = WAITING_FOR_DECL_OR_RULE;
2402 }else if( !isupper(x[0]) ){
2403 ErrorMsg(psp->filename, psp->tokenlineno,
2404 "%%fallback argument \"%s\" should be a token", x);
2405 psp->errorcnt++;
2406 }else{
2407 struct symbol *sp = Symbol_new(x);
2408 if( psp->fallback==0 ){
2409 psp->fallback = sp;
2410 }else if( sp->fallback ){
2411 ErrorMsg(psp->filename, psp->tokenlineno,
2412 "More than one fallback assigned to token %s", x);
2413 psp->errorcnt++;
2414 }else{
2415 sp->fallback = psp->fallback;
2416 psp->gp->has_fallback = 1;
2417 }
2418 }
2419 break;
drhe09daa92006-06-10 13:29:31 +00002420 case WAITING_FOR_WILDCARD_ID:
2421 if( x[0]=='.' ){
2422 psp->state = WAITING_FOR_DECL_OR_RULE;
2423 }else if( !isupper(x[0]) ){
2424 ErrorMsg(psp->filename, psp->tokenlineno,
2425 "%%wildcard argument \"%s\" should be a token", x);
2426 psp->errorcnt++;
2427 }else{
2428 struct symbol *sp = Symbol_new(x);
2429 if( psp->gp->wildcard==0 ){
2430 psp->gp->wildcard = sp;
2431 }else{
2432 ErrorMsg(psp->filename, psp->tokenlineno,
2433 "Extra wildcard to token: %s", x);
2434 psp->errorcnt++;
2435 }
2436 }
2437 break;
drh75897232000-05-29 14:26:00 +00002438 case RESYNC_AFTER_RULE_ERROR:
2439/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2440** break; */
2441 case RESYNC_AFTER_DECL_ERROR:
2442 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2443 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2444 break;
2445 }
2446}
2447
drh34ff57b2008-07-14 12:27:51 +00002448/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002449** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2450** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2451** comments them out. Text in between is also commented out as appropriate.
2452*/
danielk1977940fac92005-01-23 22:41:37 +00002453static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002454 int i, j, k, n;
2455 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002456 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002457 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002458 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002459 for(i=0; z[i]; i++){
2460 if( z[i]=='\n' ) lineno++;
2461 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2462 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2463 if( exclude ){
2464 exclude--;
2465 if( exclude==0 ){
2466 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2467 }
2468 }
2469 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2470 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2471 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2472 if( exclude ){
2473 exclude++;
2474 }else{
2475 for(j=i+7; isspace(z[j]); j++){}
2476 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2477 exclude = 1;
2478 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002479 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002480 exclude = 0;
2481 break;
2482 }
2483 }
2484 if( z[i+3]=='n' ) exclude = !exclude;
2485 if( exclude ){
2486 start = i;
2487 start_lineno = lineno;
2488 }
2489 }
2490 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2491 }
2492 }
2493 if( exclude ){
2494 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2495 exit(1);
2496 }
2497}
2498
drh75897232000-05-29 14:26:00 +00002499/* In spite of its name, this function is really a scanner. It read
2500** in the entire input file (all at once) then tokenizes it. Each
2501** token is passed to the function "parseonetoken" which builds all
2502** the appropriate data structures in the global state vector "gp".
2503*/
2504void Parse(gp)
2505struct lemon *gp;
2506{
2507 struct pstate ps;
2508 FILE *fp;
2509 char *filebuf;
2510 int filesize;
2511 int lineno;
2512 int c;
2513 char *cp, *nextcp;
2514 int startline = 0;
2515
rse38514a92007-09-20 11:34:17 +00002516 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002517 ps.gp = gp;
2518 ps.filename = gp->filename;
2519 ps.errorcnt = 0;
2520 ps.state = INITIALIZE;
2521
2522 /* Begin by reading the input file */
2523 fp = fopen(ps.filename,"rb");
2524 if( fp==0 ){
2525 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2526 gp->errorcnt++;
2527 return;
2528 }
2529 fseek(fp,0,2);
2530 filesize = ftell(fp);
2531 rewind(fp);
2532 filebuf = (char *)malloc( filesize+1 );
2533 if( filebuf==0 ){
2534 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2535 filesize+1);
2536 gp->errorcnt++;
2537 return;
2538 }
2539 if( fread(filebuf,1,filesize,fp)!=filesize ){
2540 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2541 filesize);
2542 free(filebuf);
2543 gp->errorcnt++;
2544 return;
2545 }
2546 fclose(fp);
2547 filebuf[filesize] = 0;
2548
drh6d08b4d2004-07-20 12:45:22 +00002549 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2550 preprocess_input(filebuf);
2551
drh75897232000-05-29 14:26:00 +00002552 /* Now scan the text of the input file */
2553 lineno = 1;
2554 for(cp=filebuf; (c= *cp)!=0; ){
2555 if( c=='\n' ) lineno++; /* Keep track of the line number */
2556 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2557 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2558 cp+=2;
2559 while( (c= *cp)!=0 && c!='\n' ) cp++;
2560 continue;
2561 }
2562 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2563 cp+=2;
2564 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2565 if( c=='\n' ) lineno++;
2566 cp++;
2567 }
2568 if( c ) cp++;
2569 continue;
2570 }
2571 ps.tokenstart = cp; /* Mark the beginning of the token */
2572 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2573 if( c=='\"' ){ /* String literals */
2574 cp++;
2575 while( (c= *cp)!=0 && c!='\"' ){
2576 if( c=='\n' ) lineno++;
2577 cp++;
2578 }
2579 if( c==0 ){
2580 ErrorMsg(ps.filename,startline,
2581"String starting on this line is not terminated before the end of the file.");
2582 ps.errorcnt++;
2583 nextcp = cp;
2584 }else{
2585 nextcp = cp+1;
2586 }
2587 }else if( c=='{' ){ /* A block of C code */
2588 int level;
2589 cp++;
2590 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2591 if( c=='\n' ) lineno++;
2592 else if( c=='{' ) level++;
2593 else if( c=='}' ) level--;
2594 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2595 int prevc;
2596 cp = &cp[2];
2597 prevc = 0;
2598 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2599 if( c=='\n' ) lineno++;
2600 prevc = c;
2601 cp++;
2602 }
2603 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2604 cp = &cp[2];
2605 while( (c= *cp)!=0 && c!='\n' ) cp++;
2606 if( c ) lineno++;
2607 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2608 int startchar, prevc;
2609 startchar = c;
2610 prevc = 0;
2611 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2612 if( c=='\n' ) lineno++;
2613 if( prevc=='\\' ) prevc = 0;
2614 else prevc = c;
2615 }
2616 }
2617 }
2618 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002619 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002620"C code starting on this line is not terminated before the end of the file.");
2621 ps.errorcnt++;
2622 nextcp = cp;
2623 }else{
2624 nextcp = cp+1;
2625 }
2626 }else if( isalnum(c) ){ /* Identifiers */
2627 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2628 nextcp = cp;
2629 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2630 cp += 3;
2631 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002632 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2633 cp += 2;
2634 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2635 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002636 }else{ /* All other (one character) operators */
2637 cp++;
2638 nextcp = cp;
2639 }
2640 c = *cp;
2641 *cp = 0; /* Null terminate the token */
2642 parseonetoken(&ps); /* Parse the token */
2643 *cp = c; /* Restore the buffer */
2644 cp = nextcp;
2645 }
2646 free(filebuf); /* Release the buffer after parsing */
2647 gp->rule = ps.firstrule;
2648 gp->errorcnt = ps.errorcnt;
2649}
2650/*************************** From the file "plink.c" *********************/
2651/*
2652** Routines processing configuration follow-set propagation links
2653** in the LEMON parser generator.
2654*/
2655static struct plink *plink_freelist = 0;
2656
2657/* Allocate a new plink */
2658struct plink *Plink_new(){
2659 struct plink *new;
2660
2661 if( plink_freelist==0 ){
2662 int i;
2663 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002664 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002665 if( plink_freelist==0 ){
2666 fprintf(stderr,
2667 "Unable to allocate memory for a new follow-set propagation link.\n");
2668 exit(1);
2669 }
2670 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2671 plink_freelist[amt-1].next = 0;
2672 }
2673 new = plink_freelist;
2674 plink_freelist = plink_freelist->next;
2675 return new;
2676}
2677
2678/* Add a plink to a plink list */
2679void Plink_add(plpp,cfp)
2680struct plink **plpp;
2681struct config *cfp;
2682{
2683 struct plink *new;
2684 new = Plink_new();
2685 new->next = *plpp;
2686 *plpp = new;
2687 new->cfp = cfp;
2688}
2689
2690/* Transfer every plink on the list "from" to the list "to" */
2691void Plink_copy(to,from)
2692struct plink **to;
2693struct plink *from;
2694{
2695 struct plink *nextpl;
2696 while( from ){
2697 nextpl = from->next;
2698 from->next = *to;
2699 *to = from;
2700 from = nextpl;
2701 }
2702}
2703
2704/* Delete every plink on the list */
2705void Plink_delete(plp)
2706struct plink *plp;
2707{
2708 struct plink *nextpl;
2709
2710 while( plp ){
2711 nextpl = plp->next;
2712 plp->next = plink_freelist;
2713 plink_freelist = plp;
2714 plp = nextpl;
2715 }
2716}
2717/*********************** From the file "report.c" **************************/
2718/*
2719** Procedures for generating reports and tables in the LEMON parser generator.
2720*/
2721
2722/* Generate a filename with the given suffix. Space to hold the
2723** name comes from malloc() and must be freed by the calling
2724** function.
2725*/
2726PRIVATE char *file_makename(lemp,suffix)
2727struct lemon *lemp;
2728char *suffix;
2729{
2730 char *name;
2731 char *cp;
2732
drh87cf1372008-08-13 20:09:06 +00002733 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002734 if( name==0 ){
2735 fprintf(stderr,"Can't allocate space for a filename.\n");
2736 exit(1);
2737 }
2738 strcpy(name,lemp->filename);
2739 cp = strrchr(name,'.');
2740 if( cp ) *cp = 0;
2741 strcat(name,suffix);
2742 return name;
2743}
2744
2745/* Open a file with a name based on the name of the input file,
2746** but with a different (specified) suffix, and return a pointer
2747** to the stream */
2748PRIVATE FILE *file_open(lemp,suffix,mode)
2749struct lemon *lemp;
2750char *suffix;
2751char *mode;
2752{
2753 FILE *fp;
2754
2755 if( lemp->outname ) free(lemp->outname);
2756 lemp->outname = file_makename(lemp, suffix);
2757 fp = fopen(lemp->outname,mode);
2758 if( fp==0 && *mode=='w' ){
2759 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2760 lemp->errorcnt++;
2761 return 0;
2762 }
2763 return fp;
2764}
2765
2766/* Duplicate the input file without comments and without actions
2767** on rules */
2768void Reprint(lemp)
2769struct lemon *lemp;
2770{
2771 struct rule *rp;
2772 struct symbol *sp;
2773 int i, j, maxlen, len, ncolumns, skip;
2774 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2775 maxlen = 10;
2776 for(i=0; i<lemp->nsymbol; i++){
2777 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002778 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002779 if( len>maxlen ) maxlen = len;
2780 }
2781 ncolumns = 76/(maxlen+5);
2782 if( ncolumns<1 ) ncolumns = 1;
2783 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2784 for(i=0; i<skip; i++){
2785 printf("//");
2786 for(j=i; j<lemp->nsymbol; j+=skip){
2787 sp = lemp->symbols[j];
2788 assert( sp->index==j );
2789 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2790 }
2791 printf("\n");
2792 }
2793 for(rp=lemp->rule; rp; rp=rp->next){
2794 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002795 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002796 printf(" ::=");
2797 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002798 sp = rp->rhs[i];
2799 printf(" %s", sp->name);
2800 if( sp->type==MULTITERMINAL ){
2801 for(j=1; j<sp->nsubsym; j++){
2802 printf("|%s", sp->subsym[j]->name);
2803 }
2804 }
2805 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002806 }
2807 printf(".");
2808 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002809 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002810 printf("\n");
2811 }
2812}
2813
2814void ConfigPrint(fp,cfp)
2815FILE *fp;
2816struct config *cfp;
2817{
2818 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002819 struct symbol *sp;
2820 int i, j;
drh75897232000-05-29 14:26:00 +00002821 rp = cfp->rp;
2822 fprintf(fp,"%s ::=",rp->lhs->name);
2823 for(i=0; i<=rp->nrhs; i++){
2824 if( i==cfp->dot ) fprintf(fp," *");
2825 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002826 sp = rp->rhs[i];
2827 fprintf(fp," %s", sp->name);
2828 if( sp->type==MULTITERMINAL ){
2829 for(j=1; j<sp->nsubsym; j++){
2830 fprintf(fp,"|%s",sp->subsym[j]->name);
2831 }
2832 }
drh75897232000-05-29 14:26:00 +00002833 }
2834}
2835
2836/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002837#if 0
drh75897232000-05-29 14:26:00 +00002838/* Print a set */
2839PRIVATE void SetPrint(out,set,lemp)
2840FILE *out;
2841char *set;
2842struct lemon *lemp;
2843{
2844 int i;
2845 char *spacer;
2846 spacer = "";
2847 fprintf(out,"%12s[","");
2848 for(i=0; i<lemp->nterminal; i++){
2849 if( SetFind(set,i) ){
2850 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2851 spacer = " ";
2852 }
2853 }
2854 fprintf(out,"]\n");
2855}
2856
2857/* Print a plink chain */
2858PRIVATE void PlinkPrint(out,plp,tag)
2859FILE *out;
2860struct plink *plp;
2861char *tag;
2862{
2863 while( plp ){
drhada354d2005-11-05 15:03:59 +00002864 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002865 ConfigPrint(out,plp->cfp);
2866 fprintf(out,"\n");
2867 plp = plp->next;
2868 }
2869}
2870#endif
2871
2872/* Print an action to the given file descriptor. Return FALSE if
2873** nothing was actually printed.
2874*/
2875int PrintAction(struct action *ap, FILE *fp, int indent){
2876 int result = 1;
2877 switch( ap->type ){
2878 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002879 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002880 break;
2881 case REDUCE:
2882 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2883 break;
2884 case ACCEPT:
2885 fprintf(fp,"%*s accept",indent,ap->sp->name);
2886 break;
2887 case ERROR:
2888 fprintf(fp,"%*s error",indent,ap->sp->name);
2889 break;
drh9892c5d2007-12-21 00:02:11 +00002890 case SRCONFLICT:
2891 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002892 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2893 indent,ap->sp->name,ap->x.rp->index);
2894 break;
drh9892c5d2007-12-21 00:02:11 +00002895 case SSCONFLICT:
2896 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2897 indent,ap->sp->name,ap->x.stp->statenum);
2898 break;
drh75897232000-05-29 14:26:00 +00002899 case SH_RESOLVED:
2900 case RD_RESOLVED:
2901 case NOT_USED:
2902 result = 0;
2903 break;
2904 }
2905 return result;
2906}
2907
2908/* Generate the "y.output" log file */
2909void ReportOutput(lemp)
2910struct lemon *lemp;
2911{
2912 int i;
2913 struct state *stp;
2914 struct config *cfp;
2915 struct action *ap;
2916 FILE *fp;
2917
drh2aa6ca42004-09-10 00:14:04 +00002918 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002919 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002920 for(i=0; i<lemp->nstate; i++){
2921 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002922 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002923 if( lemp->basisflag ) cfp=stp->bp;
2924 else cfp=stp->cfp;
2925 while( cfp ){
2926 char buf[20];
2927 if( cfp->dot==cfp->rp->nrhs ){
2928 sprintf(buf,"(%d)",cfp->rp->index);
2929 fprintf(fp," %5s ",buf);
2930 }else{
2931 fprintf(fp," ");
2932 }
2933 ConfigPrint(fp,cfp);
2934 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002935#if 0
drh75897232000-05-29 14:26:00 +00002936 SetPrint(fp,cfp->fws,lemp);
2937 PlinkPrint(fp,cfp->fplp,"To ");
2938 PlinkPrint(fp,cfp->bplp,"From");
2939#endif
2940 if( lemp->basisflag ) cfp=cfp->bp;
2941 else cfp=cfp->next;
2942 }
2943 fprintf(fp,"\n");
2944 for(ap=stp->ap; ap; ap=ap->next){
2945 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2946 }
2947 fprintf(fp,"\n");
2948 }
drhe9278182007-07-18 18:16:29 +00002949 fprintf(fp, "----------------------------------------------------\n");
2950 fprintf(fp, "Symbols:\n");
2951 for(i=0; i<lemp->nsymbol; i++){
2952 int j;
2953 struct symbol *sp;
2954
2955 sp = lemp->symbols[i];
2956 fprintf(fp, " %3d: %s", i, sp->name);
2957 if( sp->type==NONTERMINAL ){
2958 fprintf(fp, ":");
2959 if( sp->lambda ){
2960 fprintf(fp, " <lambda>");
2961 }
2962 for(j=0; j<lemp->nterminal; j++){
2963 if( sp->firstset && SetFind(sp->firstset, j) ){
2964 fprintf(fp, " %s", lemp->symbols[j]->name);
2965 }
2966 }
2967 }
2968 fprintf(fp, "\n");
2969 }
drh75897232000-05-29 14:26:00 +00002970 fclose(fp);
2971 return;
2972}
2973
2974/* Search for the file "name" which is in the same directory as
2975** the exacutable */
2976PRIVATE char *pathsearch(argv0,name,modemask)
2977char *argv0;
2978char *name;
2979int modemask;
2980{
2981 char *pathlist;
2982 char *path,*cp;
2983 char c;
drh75897232000-05-29 14:26:00 +00002984
2985#ifdef __WIN32__
2986 cp = strrchr(argv0,'\\');
2987#else
2988 cp = strrchr(argv0,'/');
2989#endif
2990 if( cp ){
2991 c = *cp;
2992 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00002993 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00002994 if( path ) sprintf(path,"%s/%s",argv0,name);
2995 *cp = c;
2996 }else{
2997 extern char *getenv();
2998 pathlist = getenv("PATH");
2999 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00003000 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00003001 if( path!=0 ){
3002 while( *pathlist ){
3003 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00003004 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00003005 c = *cp;
3006 *cp = 0;
3007 sprintf(path,"%s/%s",pathlist,name);
3008 *cp = c;
3009 if( c==0 ) pathlist = "";
3010 else pathlist = &cp[1];
3011 if( access(path,modemask)==0 ) break;
3012 }
3013 }
3014 }
3015 return path;
3016}
3017
3018/* Given an action, compute the integer value for that action
3019** which is to be put in the action table of the generated machine.
3020** Return negative if no action should be generated.
3021*/
3022PRIVATE int compute_action(lemp,ap)
3023struct lemon *lemp;
3024struct action *ap;
3025{
3026 int act;
3027 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003028 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003029 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3030 case ERROR: act = lemp->nstate + lemp->nrule; break;
3031 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3032 default: act = -1; break;
3033 }
3034 return act;
3035}
3036
3037#define LINESIZE 1000
3038/* The next cluster of routines are for reading the template file
3039** and writing the results to the generated parser */
3040/* The first function transfers data from "in" to "out" until
3041** a line is seen which begins with "%%". The line number is
3042** tracked.
3043**
3044** if name!=0, then any word that begin with "Parse" is changed to
3045** begin with *name instead.
3046*/
3047PRIVATE void tplt_xfer(name,in,out,lineno)
3048char *name;
3049FILE *in;
3050FILE *out;
3051int *lineno;
3052{
3053 int i, iStart;
3054 char line[LINESIZE];
3055 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3056 (*lineno)++;
3057 iStart = 0;
3058 if( name ){
3059 for(i=0; line[i]; i++){
3060 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3061 && (i==0 || !isalpha(line[i-1]))
3062 ){
3063 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3064 fprintf(out,"%s",name);
3065 i += 4;
3066 iStart = i+1;
3067 }
3068 }
3069 }
3070 fprintf(out,"%s",&line[iStart]);
3071 }
3072}
3073
3074/* The next function finds the template file and opens it, returning
3075** a pointer to the opened file. */
3076PRIVATE FILE *tplt_open(lemp)
3077struct lemon *lemp;
3078{
3079 static char templatename[] = "lempar.c";
3080 char buf[1000];
3081 FILE *in;
3082 char *tpltname;
3083 char *cp;
3084
3085 cp = strrchr(lemp->filename,'.');
3086 if( cp ){
drh8b582012003-10-21 13:16:03 +00003087 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003088 }else{
3089 sprintf(buf,"%s.lt",lemp->filename);
3090 }
3091 if( access(buf,004)==0 ){
3092 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003093 }else if( access(templatename,004)==0 ){
3094 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003095 }else{
3096 tpltname = pathsearch(lemp->argv0,templatename,0);
3097 }
3098 if( tpltname==0 ){
3099 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3100 templatename);
3101 lemp->errorcnt++;
3102 return 0;
3103 }
drh2aa6ca42004-09-10 00:14:04 +00003104 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003105 if( in==0 ){
3106 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3107 lemp->errorcnt++;
3108 return 0;
3109 }
3110 return in;
3111}
3112
drhaf805ca2004-09-07 11:28:25 +00003113/* Print a #line directive line to the output file. */
3114PRIVATE void tplt_linedir(out,lineno,filename)
3115FILE *out;
3116int lineno;
3117char *filename;
3118{
3119 fprintf(out,"#line %d \"",lineno);
3120 while( *filename ){
3121 if( *filename == '\\' ) putc('\\',out);
3122 putc(*filename,out);
3123 filename++;
3124 }
3125 fprintf(out,"\"\n");
3126}
3127
drh75897232000-05-29 14:26:00 +00003128/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003129PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003130FILE *out;
3131struct lemon *lemp;
3132char *str;
drh75897232000-05-29 14:26:00 +00003133int *lineno;
3134{
3135 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003136 while( *str ){
drh75897232000-05-29 14:26:00 +00003137 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003138 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003139 str++;
3140 }
drh9db55df2004-09-09 14:01:21 +00003141 if( str[-1]!='\n' ){
3142 putc('\n',out);
3143 (*lineno)++;
3144 }
shane58543932008-12-10 20:10:04 +00003145 if (!lemp->nolinenosflag) {
3146 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3147 }
drh75897232000-05-29 14:26:00 +00003148 return;
3149}
3150
3151/*
3152** The following routine emits code for the destructor for the
3153** symbol sp
3154*/
3155void emit_destructor_code(out,sp,lemp,lineno)
3156FILE *out;
3157struct symbol *sp;
3158struct lemon *lemp;
3159int *lineno;
3160{
drhcc83b6e2004-04-23 23:38:42 +00003161 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003162
drh75897232000-05-29 14:26:00 +00003163 if( sp->type==TERMINAL ){
3164 cp = lemp->tokendest;
3165 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003166 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003167 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003168 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003169 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003170 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003171 }else if( lemp->vardest ){
3172 cp = lemp->vardest;
3173 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003174 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003175 }else{
3176 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003177 }
3178 for(; *cp; cp++){
3179 if( *cp=='$' && cp[1]=='$' ){
3180 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3181 cp++;
3182 continue;
3183 }
shane58543932008-12-10 20:10:04 +00003184 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003185 fputc(*cp,out);
3186 }
shane58543932008-12-10 20:10:04 +00003187 fprintf(out,"\n"); (*lineno)++;
3188 if (!lemp->nolinenosflag) {
3189 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3190 }
3191 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003192 return;
3193}
3194
3195/*
drh960e8c62001-04-03 16:53:21 +00003196** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003197*/
3198int has_destructor(sp, lemp)
3199struct symbol *sp;
3200struct lemon *lemp;
3201{
3202 int ret;
3203 if( sp->type==TERMINAL ){
3204 ret = lemp->tokendest!=0;
3205 }else{
drh960e8c62001-04-03 16:53:21 +00003206 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003207 }
3208 return ret;
3209}
3210
drh0bb132b2004-07-20 14:06:51 +00003211/*
3212** Append text to a dynamically allocated string. If zText is 0 then
3213** reset the string to be empty again. Always return the complete text
3214** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003215**
3216** n bytes of zText are stored. If n==0 then all of zText up to the first
3217** \000 terminator is stored. zText can contain up to two instances of
3218** %d. The values of p1 and p2 are written into the first and second
3219** %d.
3220**
3221** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003222*/
3223PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3224 static char *z = 0;
3225 static int alloced = 0;
3226 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003227 int c;
drh0bb132b2004-07-20 14:06:51 +00003228 char zInt[40];
3229
3230 if( zText==0 ){
3231 used = 0;
3232 return z;
3233 }
drh7ac25c72004-08-19 15:12:26 +00003234 if( n<=0 ){
3235 if( n<0 ){
3236 used += n;
3237 assert( used>=0 );
3238 }
drh87cf1372008-08-13 20:09:06 +00003239 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003240 }
drh0bb132b2004-07-20 14:06:51 +00003241 if( n+sizeof(zInt)*2+used >= alloced ){
3242 alloced = n + sizeof(zInt)*2 + used + 200;
3243 z = realloc(z, alloced);
3244 }
3245 if( z==0 ) return "";
3246 while( n-- > 0 ){
3247 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003248 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003249 sprintf(zInt, "%d", p1);
3250 p1 = p2;
3251 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003252 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003253 zText++;
3254 n--;
3255 }else{
3256 z[used++] = c;
3257 }
3258 }
3259 z[used] = 0;
3260 return z;
3261}
3262
3263/*
3264** zCode is a string that is the action associated with a rule. Expand
3265** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003266** stack.
drh0bb132b2004-07-20 14:06:51 +00003267*/
drhaf805ca2004-09-07 11:28:25 +00003268PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003269 char *cp, *xp;
3270 int i;
3271 char lhsused = 0; /* True if the LHS element has been used */
3272 char used[MAXRHS]; /* True for each RHS element which is used */
3273
3274 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3275 lhsused = 0;
3276
drh19c9e562007-03-29 20:13:53 +00003277 if( rp->code==0 ){
3278 rp->code = "\n";
3279 rp->line = rp->ruleline;
3280 }
3281
drh0bb132b2004-07-20 14:06:51 +00003282 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003283 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003284 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3285 char saved;
3286 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3287 saved = *xp;
3288 *xp = 0;
3289 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003290 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003291 cp = xp;
3292 lhsused = 1;
3293 }else{
3294 for(i=0; i<rp->nrhs; i++){
3295 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003296 if( cp!=rp->code && cp[-1]=='@' ){
3297 /* If the argument is of the form @X then substituted
3298 ** the token number of X, not the value of X */
3299 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3300 }else{
drhfd405312005-11-06 04:06:59 +00003301 struct symbol *sp = rp->rhs[i];
3302 int dtnum;
3303 if( sp->type==MULTITERMINAL ){
3304 dtnum = sp->subsym[0]->dtnum;
3305 }else{
3306 dtnum = sp->dtnum;
3307 }
3308 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003309 }
drh0bb132b2004-07-20 14:06:51 +00003310 cp = xp;
3311 used[i] = 1;
3312 break;
3313 }
3314 }
3315 }
3316 *xp = saved;
3317 }
3318 append_str(cp, 1, 0, 0);
3319 } /* End loop */
3320
3321 /* Check to make sure the LHS has been used */
3322 if( rp->lhsalias && !lhsused ){
3323 ErrorMsg(lemp->filename,rp->ruleline,
3324 "Label \"%s\" for \"%s(%s)\" is never used.",
3325 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3326 lemp->errorcnt++;
3327 }
3328
3329 /* Generate destructor code for RHS symbols which are not used in the
3330 ** reduce code */
3331 for(i=0; i<rp->nrhs; i++){
3332 if( rp->rhsalias[i] && !used[i] ){
3333 ErrorMsg(lemp->filename,rp->ruleline,
3334 "Label %s for \"%s(%s)\" is never used.",
3335 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3336 lemp->errorcnt++;
3337 }else if( rp->rhsalias[i]==0 ){
3338 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003339 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003340 rp->rhs[i]->index,i-rp->nrhs+1);
3341 }else{
3342 /* No destructor defined for this term */
3343 }
3344 }
3345 }
drh61e339a2007-01-16 03:09:02 +00003346 if( rp->code ){
3347 cp = append_str(0,0,0,0);
3348 rp->code = Strsafe(cp?cp:"");
3349 }
drh0bb132b2004-07-20 14:06:51 +00003350}
3351
drh75897232000-05-29 14:26:00 +00003352/*
3353** Generate code which executes when the rule "rp" is reduced. Write
3354** the code to "out". Make sure lineno stays up-to-date.
3355*/
3356PRIVATE void emit_code(out,rp,lemp,lineno)
3357FILE *out;
3358struct rule *rp;
3359struct lemon *lemp;
3360int *lineno;
3361{
drh0bb132b2004-07-20 14:06:51 +00003362 char *cp;
drh75897232000-05-29 14:26:00 +00003363
3364 /* Generate code to do the reduce action */
3365 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003366 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003367 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003368 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003369 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003370 } /* End loop */
shane58543932008-12-10 20:10:04 +00003371 fprintf(out,"}\n"); (*lineno)++;
3372 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003373 } /* End if( rp->code ) */
3374
drh75897232000-05-29 14:26:00 +00003375 return;
3376}
3377
3378/*
3379** Print the definition of the union used for the parser's data stack.
3380** This union contains fields for every possible data type for tokens
3381** and nonterminals. In the process of computing and printing this
3382** union, also set the ".dtnum" field of every terminal and nonterminal
3383** symbol.
3384*/
3385void print_stack_union(out,lemp,plineno,mhflag)
3386FILE *out; /* The output stream */
3387struct lemon *lemp; /* The main info structure for this parser */
3388int *plineno; /* Pointer to the line number */
3389int mhflag; /* True if generating makeheaders output */
3390{
3391 int lineno = *plineno; /* The line number of the output */
3392 char **types; /* A hash table of datatypes */
3393 int arraysize; /* Size of the "types" array */
3394 int maxdtlength; /* Maximum length of any ".datatype" field. */
3395 char *stddt; /* Standardized name for a datatype */
3396 int i,j; /* Loop counters */
3397 int hash; /* For hashing the name of a type */
3398 char *name; /* Name of the parser */
3399
3400 /* Allocate and initialize types[] and allocate stddt[] */
3401 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003402 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003403 for(i=0; i<arraysize; i++) types[i] = 0;
3404 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003405 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003406 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003407 }
drh75897232000-05-29 14:26:00 +00003408 for(i=0; i<lemp->nsymbol; i++){
3409 int len;
3410 struct symbol *sp = lemp->symbols[i];
3411 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003412 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003413 if( len>maxdtlength ) maxdtlength = len;
3414 }
3415 stddt = (char*)malloc( maxdtlength*2 + 1 );
3416 if( types==0 || stddt==0 ){
3417 fprintf(stderr,"Out of memory.\n");
3418 exit(1);
3419 }
3420
3421 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3422 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003423 ** used for terminal symbols. If there is no %default_type defined then
3424 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3425 ** a datatype using the %type directive.
3426 */
drh75897232000-05-29 14:26:00 +00003427 for(i=0; i<lemp->nsymbol; i++){
3428 struct symbol *sp = lemp->symbols[i];
3429 char *cp;
3430 if( sp==lemp->errsym ){
3431 sp->dtnum = arraysize+1;
3432 continue;
3433 }
drh960e8c62001-04-03 16:53:21 +00003434 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003435 sp->dtnum = 0;
3436 continue;
3437 }
3438 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003439 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003440 j = 0;
3441 while( isspace(*cp) ) cp++;
3442 while( *cp ) stddt[j++] = *cp++;
3443 while( j>0 && isspace(stddt[j-1]) ) j--;
3444 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003445 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003446 sp->dtnum = 0;
3447 continue;
3448 }
drh75897232000-05-29 14:26:00 +00003449 hash = 0;
3450 for(j=0; stddt[j]; j++){
3451 hash = hash*53 + stddt[j];
3452 }
drh3b2129c2003-05-13 00:34:21 +00003453 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003454 while( types[hash] ){
3455 if( strcmp(types[hash],stddt)==0 ){
3456 sp->dtnum = hash + 1;
3457 break;
3458 }
3459 hash++;
3460 if( hash>=arraysize ) hash = 0;
3461 }
3462 if( types[hash]==0 ){
3463 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003464 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003465 if( types[hash]==0 ){
3466 fprintf(stderr,"Out of memory.\n");
3467 exit(1);
3468 }
3469 strcpy(types[hash],stddt);
3470 }
3471 }
3472
3473 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3474 name = lemp->name ? lemp->name : "Parse";
3475 lineno = *plineno;
3476 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3477 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3478 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3479 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3480 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003481 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003482 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3483 for(i=0; i<arraysize; i++){
3484 if( types[i]==0 ) continue;
3485 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3486 free(types[i]);
3487 }
drhc4dd3fd2008-01-22 01:48:05 +00003488 if( lemp->errsym->useCnt ){
3489 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3490 }
drh75897232000-05-29 14:26:00 +00003491 free(stddt);
3492 free(types);
3493 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3494 *plineno = lineno;
3495}
3496
drhb29b0a52002-02-23 19:39:46 +00003497/*
3498** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003499** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003500*/
drh8b582012003-10-21 13:16:03 +00003501static const char *minimum_size_type(int lwr, int upr){
3502 if( lwr>=0 ){
3503 if( upr<=255 ){
3504 return "unsigned char";
3505 }else if( upr<65535 ){
3506 return "unsigned short int";
3507 }else{
3508 return "unsigned int";
3509 }
3510 }else if( lwr>=-127 && upr<=127 ){
3511 return "signed char";
3512 }else if( lwr>=-32767 && upr<32767 ){
3513 return "short";
drhb29b0a52002-02-23 19:39:46 +00003514 }else{
drh8b582012003-10-21 13:16:03 +00003515 return "int";
drhb29b0a52002-02-23 19:39:46 +00003516 }
3517}
3518
drhfdbf9282003-10-21 16:34:41 +00003519/*
3520** Each state contains a set of token transaction and a set of
3521** nonterminal transactions. Each of these sets makes an instance
3522** of the following structure. An array of these structures is used
3523** to order the creation of entries in the yy_action[] table.
3524*/
3525struct axset {
3526 struct state *stp; /* A pointer to a state */
3527 int isTkn; /* True to use tokens. False for non-terminals */
3528 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003529 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003530};
3531
3532/*
3533** Compare to axset structures for sorting purposes
3534*/
3535static int axset_compare(const void *a, const void *b){
3536 struct axset *p1 = (struct axset*)a;
3537 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003538 int c;
3539 c = p2->nAction - p1->nAction;
3540 if( c==0 ){
3541 c = p2->iOrder - p1->iOrder;
3542 }
3543 assert( c!=0 || p1==p2 );
3544 return c;
drhfdbf9282003-10-21 16:34:41 +00003545}
3546
drhc4dd3fd2008-01-22 01:48:05 +00003547/*
3548** Write text on "out" that describes the rule "rp".
3549*/
3550static void writeRuleText(FILE *out, struct rule *rp){
3551 int j;
3552 fprintf(out,"%s ::=", rp->lhs->name);
3553 for(j=0; j<rp->nrhs; j++){
3554 struct symbol *sp = rp->rhs[j];
3555 fprintf(out," %s", sp->name);
3556 if( sp->type==MULTITERMINAL ){
3557 int k;
3558 for(k=1; k<sp->nsubsym; k++){
3559 fprintf(out,"|%s",sp->subsym[k]->name);
3560 }
3561 }
3562 }
3563}
3564
3565
drh75897232000-05-29 14:26:00 +00003566/* Generate C source code for the parser */
3567void ReportTable(lemp, mhflag)
3568struct lemon *lemp;
3569int mhflag; /* Output in makeheaders format if true */
3570{
3571 FILE *out, *in;
3572 char line[LINESIZE];
3573 int lineno;
3574 struct state *stp;
3575 struct action *ap;
3576 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003577 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003578 int i, j, k, n;
drh75897232000-05-29 14:26:00 +00003579 char *name;
drh8b582012003-10-21 13:16:03 +00003580 int mnTknOfst, mxTknOfst;
3581 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003582 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003583
3584 in = tplt_open(lemp);
3585 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003586 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003587 if( out==0 ){
3588 fclose(in);
3589 return;
3590 }
3591 lineno = 1;
3592 tplt_xfer(lemp->name,in,out,&lineno);
3593
3594 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003595 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003596 if( mhflag ){
3597 char *name = file_makename(lemp, ".h");
3598 fprintf(out,"#include \"%s\"\n", name); lineno++;
3599 free(name);
3600 }
3601 tplt_xfer(lemp->name,in,out,&lineno);
3602
3603 /* Generate #defines for all tokens */
3604 if( mhflag ){
3605 char *prefix;
3606 fprintf(out,"#if INTERFACE\n"); lineno++;
3607 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3608 else prefix = "";
3609 for(i=1; i<lemp->nterminal; i++){
3610 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3611 lineno++;
3612 }
3613 fprintf(out,"#endif\n"); lineno++;
3614 }
3615 tplt_xfer(lemp->name,in,out,&lineno);
3616
3617 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003618 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003619 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003620 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3621 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003622 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003623 if( lemp->wildcard ){
3624 fprintf(out,"#define YYWILDCARD %d\n",
3625 lemp->wildcard->index); lineno++;
3626 }
drh75897232000-05-29 14:26:00 +00003627 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003628 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003629 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003630 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3631 }else{
3632 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3633 }
drhca44b5a2007-02-22 23:06:58 +00003634 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003635 if( mhflag ){
3636 fprintf(out,"#if INTERFACE\n"); lineno++;
3637 }
3638 name = lemp->name ? lemp->name : "Parse";
3639 if( lemp->arg && lemp->arg[0] ){
3640 int i;
drh87cf1372008-08-13 20:09:06 +00003641 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003642 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3643 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003644 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3645 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3646 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3647 name,lemp->arg,&lemp->arg[i]); lineno++;
3648 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3649 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003650 }else{
drh1f245e42002-03-11 13:55:50 +00003651 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3652 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3653 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3654 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003655 }
3656 if( mhflag ){
3657 fprintf(out,"#endif\n"); lineno++;
3658 }
3659 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3660 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003661 if( lemp->errsym->useCnt ){
3662 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3663 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3664 }
drh0bd1f4e2002-06-06 18:54:39 +00003665 if( lemp->has_fallback ){
3666 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3667 }
drh75897232000-05-29 14:26:00 +00003668 tplt_xfer(lemp->name,in,out,&lineno);
3669
drh8b582012003-10-21 13:16:03 +00003670 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003671 **
drh8b582012003-10-21 13:16:03 +00003672 ** yy_action[] A single table containing all actions.
3673 ** yy_lookahead[] A table containing the lookahead for each entry in
3674 ** yy_action. Used to detect hash collisions.
3675 ** yy_shift_ofst[] For each state, the offset into yy_action for
3676 ** shifting terminals.
3677 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3678 ** shifting non-terminals after a reduce.
3679 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003680 */
drh75897232000-05-29 14:26:00 +00003681
drh8b582012003-10-21 13:16:03 +00003682 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003683 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003684 if( ax==0 ){
3685 fprintf(stderr,"malloc failed\n");
3686 exit(1);
3687 }
drh75897232000-05-29 14:26:00 +00003688 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003689 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003690 ax[i*2].stp = stp;
3691 ax[i*2].isTkn = 1;
3692 ax[i*2].nAction = stp->nTknAct;
3693 ax[i*2+1].stp = stp;
3694 ax[i*2+1].isTkn = 0;
3695 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003696 }
drh8b582012003-10-21 13:16:03 +00003697 mxTknOfst = mnTknOfst = 0;
3698 mxNtOfst = mnNtOfst = 0;
3699
drhfdbf9282003-10-21 16:34:41 +00003700 /* Compute the action table. In order to try to keep the size of the
3701 ** action table to a minimum, the heuristic of placing the largest action
3702 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003703 */
drhe594bc32009-11-03 13:02:25 +00003704 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003705 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003706 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003707 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3708 stp = ax[i].stp;
3709 if( ax[i].isTkn ){
3710 for(ap=stp->ap; ap; ap=ap->next){
3711 int action;
3712 if( ap->sp->index>=lemp->nterminal ) continue;
3713 action = compute_action(lemp, ap);
3714 if( action<0 ) continue;
3715 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003716 }
drhfdbf9282003-10-21 16:34:41 +00003717 stp->iTknOfst = acttab_insert(pActtab);
3718 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3719 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3720 }else{
3721 for(ap=stp->ap; ap; ap=ap->next){
3722 int action;
3723 if( ap->sp->index<lemp->nterminal ) continue;
3724 if( ap->sp->index==lemp->nsymbol ) continue;
3725 action = compute_action(lemp, ap);
3726 if( action<0 ) continue;
3727 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003728 }
drhfdbf9282003-10-21 16:34:41 +00003729 stp->iNtOfst = acttab_insert(pActtab);
3730 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3731 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003732 }
3733 }
drhfdbf9282003-10-21 16:34:41 +00003734 free(ax);
drh8b582012003-10-21 13:16:03 +00003735
3736 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003737 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003738 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3739 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003740 for(i=j=0; i<n; i++){
3741 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003742 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003743 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003744 fprintf(out, " %4d,", action);
3745 if( j==9 || i==n-1 ){
3746 fprintf(out, "\n"); lineno++;
3747 j = 0;
3748 }else{
3749 j++;
3750 }
3751 }
3752 fprintf(out, "};\n"); lineno++;
3753
3754 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003755 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003756 for(i=j=0; i<n; i++){
3757 int la = acttab_yylookahead(pActtab, i);
3758 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003759 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003760 fprintf(out, " %4d,", la);
3761 if( j==9 || i==n-1 ){
3762 fprintf(out, "\n"); lineno++;
3763 j = 0;
3764 }else{
3765 j++;
3766 }
3767 }
3768 fprintf(out, "};\n"); lineno++;
3769
3770 /* Output the yy_shift_ofst[] table */
3771 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003772 n = lemp->nstate;
3773 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003774 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3775 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3776 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003777 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003778 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003779 for(i=j=0; i<n; i++){
3780 int ofst;
3781 stp = lemp->sorted[i];
3782 ofst = stp->iTknOfst;
3783 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003784 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003785 fprintf(out, " %4d,", ofst);
3786 if( j==9 || i==n-1 ){
3787 fprintf(out, "\n"); lineno++;
3788 j = 0;
3789 }else{
3790 j++;
3791 }
3792 }
3793 fprintf(out, "};\n"); lineno++;
3794
3795 /* Output the yy_reduce_ofst[] table */
3796 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003797 n = lemp->nstate;
3798 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003799 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3800 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3801 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003802 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003803 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003804 for(i=j=0; i<n; i++){
3805 int ofst;
3806 stp = lemp->sorted[i];
3807 ofst = stp->iNtOfst;
3808 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003809 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003810 fprintf(out, " %4d,", ofst);
3811 if( j==9 || i==n-1 ){
3812 fprintf(out, "\n"); lineno++;
3813 j = 0;
3814 }else{
3815 j++;
3816 }
3817 }
3818 fprintf(out, "};\n"); lineno++;
3819
3820 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003821 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003822 n = lemp->nstate;
3823 for(i=j=0; i<n; i++){
3824 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003825 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003826 fprintf(out, " %4d,", stp->iDflt);
3827 if( j==9 || i==n-1 ){
3828 fprintf(out, "\n"); lineno++;
3829 j = 0;
3830 }else{
3831 j++;
3832 }
3833 }
3834 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003835 tplt_xfer(lemp->name,in,out,&lineno);
3836
drh0bd1f4e2002-06-06 18:54:39 +00003837 /* Generate the table of fallback tokens.
3838 */
3839 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003840 int mx = lemp->nterminal - 1;
3841 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3842 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003843 struct symbol *p = lemp->symbols[i];
3844 if( p->fallback==0 ){
3845 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3846 }else{
3847 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3848 p->name, p->fallback->name);
3849 }
3850 lineno++;
3851 }
3852 }
3853 tplt_xfer(lemp->name, in, out, &lineno);
3854
3855 /* Generate a table containing the symbolic name of every symbol
3856 */
drh75897232000-05-29 14:26:00 +00003857 for(i=0; i<lemp->nsymbol; i++){
3858 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3859 fprintf(out," %-15s",line);
3860 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3861 }
3862 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3863 tplt_xfer(lemp->name,in,out,&lineno);
3864
drh0bd1f4e2002-06-06 18:54:39 +00003865 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003866 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003867 ** when tracing REDUCE actions.
3868 */
3869 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3870 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003871 fprintf(out," /* %3d */ \"", i);
3872 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003873 fprintf(out,"\",\n"); lineno++;
3874 }
3875 tplt_xfer(lemp->name,in,out,&lineno);
3876
drh75897232000-05-29 14:26:00 +00003877 /* Generate code which executes every time a symbol is popped from
3878 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003879 ** (In other words, generate the %destructor actions)
3880 */
drh75897232000-05-29 14:26:00 +00003881 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003882 int once = 1;
drh75897232000-05-29 14:26:00 +00003883 for(i=0; i<lemp->nsymbol; i++){
3884 struct symbol *sp = lemp->symbols[i];
3885 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003886 if( once ){
3887 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3888 once = 0;
3889 }
drhc53eed12009-06-12 17:46:19 +00003890 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003891 }
3892 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3893 if( i<lemp->nsymbol ){
3894 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3895 fprintf(out," break;\n"); lineno++;
3896 }
3897 }
drh8d659732005-01-13 23:54:06 +00003898 if( lemp->vardest ){
3899 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003900 int once = 1;
drh8d659732005-01-13 23:54:06 +00003901 for(i=0; i<lemp->nsymbol; i++){
3902 struct symbol *sp = lemp->symbols[i];
3903 if( sp==0 || sp->type==TERMINAL ||
3904 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003905 if( once ){
3906 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3907 once = 0;
3908 }
drhc53eed12009-06-12 17:46:19 +00003909 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003910 dflt_sp = sp;
3911 }
3912 if( dflt_sp!=0 ){
3913 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003914 }
drh4dc8ef52008-07-01 17:13:57 +00003915 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003916 }
drh75897232000-05-29 14:26:00 +00003917 for(i=0; i<lemp->nsymbol; i++){
3918 struct symbol *sp = lemp->symbols[i];
3919 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003920 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003921
3922 /* Combine duplicate destructors into a single case */
3923 for(j=i+1; j<lemp->nsymbol; j++){
3924 struct symbol *sp2 = lemp->symbols[j];
3925 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3926 && sp2->dtnum==sp->dtnum
3927 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003928 fprintf(out," case %d: /* %s */\n",
3929 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003930 sp2->destructor = 0;
3931 }
3932 }
3933
drh75897232000-05-29 14:26:00 +00003934 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3935 fprintf(out," break;\n"); lineno++;
3936 }
drh75897232000-05-29 14:26:00 +00003937 tplt_xfer(lemp->name,in,out,&lineno);
3938
3939 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003940 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003941 tplt_xfer(lemp->name,in,out,&lineno);
3942
3943 /* Generate the table of rule information
3944 **
3945 ** Note: This code depends on the fact that rules are number
3946 ** sequentually beginning with 0.
3947 */
3948 for(rp=lemp->rule; rp; rp=rp->next){
3949 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3950 }
3951 tplt_xfer(lemp->name,in,out,&lineno);
3952
3953 /* Generate code which execution during each REDUCE action */
3954 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003955 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003956 }
drhc53eed12009-06-12 17:46:19 +00003957 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003958 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003959 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003960 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003961 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003962 fprintf(out," case %d: /* ", rp->index);
3963 writeRuleText(out, rp);
3964 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003965 for(rp2=rp->next; rp2; rp2=rp2->next){
3966 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003967 fprintf(out," case %d: /* ", rp2->index);
3968 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003969 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003970 rp2->code = 0;
3971 }
3972 }
drh75897232000-05-29 14:26:00 +00003973 emit_code(out,rp,lemp,&lineno);
3974 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00003975 rp->code = 0;
drh75897232000-05-29 14:26:00 +00003976 }
drhc53eed12009-06-12 17:46:19 +00003977 /* Finally, output the default: rule. We choose as the default: all
3978 ** empty actions. */
3979 fprintf(out," default:\n"); lineno++;
3980 for(rp=lemp->rule; rp; rp=rp->next){
3981 if( rp->code==0 ) continue;
3982 assert( rp->code[0]=='\n' && rp->code[1]==0 );
3983 fprintf(out," /* (%d) ", rp->index);
3984 writeRuleText(out, rp);
3985 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
3986 }
3987 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003988 tplt_xfer(lemp->name,in,out,&lineno);
3989
3990 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003991 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00003992 tplt_xfer(lemp->name,in,out,&lineno);
3993
3994 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00003995 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00003996 tplt_xfer(lemp->name,in,out,&lineno);
3997
3998 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00003999 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004000 tplt_xfer(lemp->name,in,out,&lineno);
4001
4002 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004003 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004004
4005 fclose(in);
4006 fclose(out);
4007 return;
4008}
4009
4010/* Generate a header file for the parser */
4011void ReportHeader(lemp)
4012struct lemon *lemp;
4013{
4014 FILE *out, *in;
4015 char *prefix;
4016 char line[LINESIZE];
4017 char pattern[LINESIZE];
4018 int i;
4019
4020 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4021 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004022 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004023 if( in ){
4024 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4025 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4026 if( strcmp(line,pattern) ) break;
4027 }
4028 fclose(in);
4029 if( i==lemp->nterminal ){
4030 /* No change in the file. Don't rewrite it. */
4031 return;
4032 }
4033 }
drh2aa6ca42004-09-10 00:14:04 +00004034 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004035 if( out ){
4036 for(i=1; i<lemp->nterminal; i++){
4037 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4038 }
4039 fclose(out);
4040 }
4041 return;
4042}
4043
4044/* Reduce the size of the action tables, if possible, by making use
4045** of defaults.
4046**
drhb59499c2002-02-23 18:45:13 +00004047** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004048** it the default. Except, there is no default if the wildcard token
4049** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004050*/
4051void CompressTables(lemp)
4052struct lemon *lemp;
4053{
4054 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004055 struct action *ap, *ap2;
4056 struct rule *rp, *rp2, *rbest;
4057 int nbest, n;
drh75897232000-05-29 14:26:00 +00004058 int i;
drhe09daa92006-06-10 13:29:31 +00004059 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004060
4061 for(i=0; i<lemp->nstate; i++){
4062 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004063 nbest = 0;
4064 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004065 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004066
drhb59499c2002-02-23 18:45:13 +00004067 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004068 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4069 usesWildcard = 1;
4070 }
drhb59499c2002-02-23 18:45:13 +00004071 if( ap->type!=REDUCE ) continue;
4072 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004073 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004074 if( rp==rbest ) continue;
4075 n = 1;
4076 for(ap2=ap->next; ap2; ap2=ap2->next){
4077 if( ap2->type!=REDUCE ) continue;
4078 rp2 = ap2->x.rp;
4079 if( rp2==rbest ) continue;
4080 if( rp2==rp ) n++;
4081 }
4082 if( n>nbest ){
4083 nbest = n;
4084 rbest = rp;
drh75897232000-05-29 14:26:00 +00004085 }
4086 }
drhb59499c2002-02-23 18:45:13 +00004087
4088 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004089 ** is not at least 1 or if the wildcard token is a possible
4090 ** lookahead.
4091 */
4092 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004093
drhb59499c2002-02-23 18:45:13 +00004094
4095 /* Combine matching REDUCE actions into a single default */
4096 for(ap=stp->ap; ap; ap=ap->next){
4097 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4098 }
drh75897232000-05-29 14:26:00 +00004099 assert( ap );
4100 ap->sp = Symbol_new("{default}");
4101 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004102 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004103 }
4104 stp->ap = Action_sort(stp->ap);
4105 }
4106}
drhb59499c2002-02-23 18:45:13 +00004107
drhada354d2005-11-05 15:03:59 +00004108
4109/*
4110** Compare two states for sorting purposes. The smaller state is the
4111** one with the most non-terminal actions. If they have the same number
4112** of non-terminal actions, then the smaller is the one with the most
4113** token actions.
4114*/
4115static int stateResortCompare(const void *a, const void *b){
4116 const struct state *pA = *(const struct state**)a;
4117 const struct state *pB = *(const struct state**)b;
4118 int n;
4119
4120 n = pB->nNtAct - pA->nNtAct;
4121 if( n==0 ){
4122 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004123 if( n==0 ){
4124 n = pB->statenum - pA->statenum;
4125 }
drhada354d2005-11-05 15:03:59 +00004126 }
drhe594bc32009-11-03 13:02:25 +00004127 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004128 return n;
4129}
4130
4131
4132/*
4133** Renumber and resort states so that states with fewer choices
4134** occur at the end. Except, keep state 0 as the first state.
4135*/
4136void ResortStates(lemp)
4137struct lemon *lemp;
4138{
4139 int i;
4140 struct state *stp;
4141 struct action *ap;
4142
4143 for(i=0; i<lemp->nstate; i++){
4144 stp = lemp->sorted[i];
4145 stp->nTknAct = stp->nNtAct = 0;
4146 stp->iDflt = lemp->nstate + lemp->nrule;
4147 stp->iTknOfst = NO_OFFSET;
4148 stp->iNtOfst = NO_OFFSET;
4149 for(ap=stp->ap; ap; ap=ap->next){
4150 if( compute_action(lemp,ap)>=0 ){
4151 if( ap->sp->index<lemp->nterminal ){
4152 stp->nTknAct++;
4153 }else if( ap->sp->index<lemp->nsymbol ){
4154 stp->nNtAct++;
4155 }else{
4156 stp->iDflt = compute_action(lemp, ap);
4157 }
4158 }
4159 }
4160 }
4161 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4162 stateResortCompare);
4163 for(i=0; i<lemp->nstate; i++){
4164 lemp->sorted[i]->statenum = i;
4165 }
4166}
4167
4168
drh75897232000-05-29 14:26:00 +00004169/***************** From the file "set.c" ************************************/
4170/*
4171** Set manipulation routines for the LEMON parser generator.
4172*/
4173
4174static int size = 0;
4175
4176/* Set the set size */
4177void SetSize(n)
4178int n;
4179{
4180 size = n+1;
4181}
4182
4183/* Allocate a new set */
4184char *SetNew(){
4185 char *s;
drh9892c5d2007-12-21 00:02:11 +00004186 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004187 if( s==0 ){
4188 extern void memory_error();
4189 memory_error();
4190 }
drh75897232000-05-29 14:26:00 +00004191 return s;
4192}
4193
4194/* Deallocate a set */
4195void SetFree(s)
4196char *s;
4197{
4198 free(s);
4199}
4200
4201/* Add a new element to the set. Return TRUE if the element was added
4202** and FALSE if it was already there. */
4203int SetAdd(s,e)
4204char *s;
4205int e;
4206{
4207 int rv;
drh9892c5d2007-12-21 00:02:11 +00004208 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004209 rv = s[e];
4210 s[e] = 1;
4211 return !rv;
4212}
4213
4214/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4215int SetUnion(s1,s2)
4216char *s1;
4217char *s2;
4218{
4219 int i, progress;
4220 progress = 0;
4221 for(i=0; i<size; i++){
4222 if( s2[i]==0 ) continue;
4223 if( s1[i]==0 ){
4224 progress = 1;
4225 s1[i] = 1;
4226 }
4227 }
4228 return progress;
4229}
4230/********************** From the file "table.c" ****************************/
4231/*
4232** All code in this file has been automatically generated
4233** from a specification in the file
4234** "table.q"
4235** by the associative array code building program "aagen".
4236** Do not edit this file! Instead, edit the specification
4237** file, then rerun aagen.
4238*/
4239/*
4240** Code for processing tables in the LEMON parser generator.
4241*/
4242
4243PRIVATE int strhash(x)
4244char *x;
4245{
4246 int h = 0;
4247 while( *x) h = h*13 + *(x++);
4248 return h;
4249}
4250
4251/* Works like strdup, sort of. Save a string in malloced memory, but
4252** keep strings in a table so that the same string is not in more
4253** than one place.
4254*/
4255char *Strsafe(y)
4256char *y;
4257{
4258 char *z;
4259
drh916f75f2006-07-17 00:19:39 +00004260 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004261 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004262 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004263 strcpy(z,y);
4264 Strsafe_insert(z);
4265 }
4266 MemoryCheck(z);
4267 return z;
4268}
4269
4270/* There is one instance of the following structure for each
4271** associative array of type "x1".
4272*/
4273struct s_x1 {
4274 int size; /* The number of available slots. */
4275 /* Must be a power of 2 greater than or */
4276 /* equal to 1 */
4277 int count; /* Number of currently slots filled */
4278 struct s_x1node *tbl; /* The data stored here */
4279 struct s_x1node **ht; /* Hash table for lookups */
4280};
4281
4282/* There is one instance of this structure for every data element
4283** in an associative array of type "x1".
4284*/
4285typedef struct s_x1node {
4286 char *data; /* The data */
4287 struct s_x1node *next; /* Next entry with the same hash */
4288 struct s_x1node **from; /* Previous link */
4289} x1node;
4290
4291/* There is only one instance of the array, which is the following */
4292static struct s_x1 *x1a;
4293
4294/* Allocate a new associative array */
4295void Strsafe_init(){
4296 if( x1a ) return;
4297 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4298 if( x1a ){
4299 x1a->size = 1024;
4300 x1a->count = 0;
4301 x1a->tbl = (x1node*)malloc(
4302 (sizeof(x1node) + sizeof(x1node*))*1024 );
4303 if( x1a->tbl==0 ){
4304 free(x1a);
4305 x1a = 0;
4306 }else{
4307 int i;
4308 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4309 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4310 }
4311 }
4312}
4313/* Insert a new record into the array. Return TRUE if successful.
4314** Prior data with the same key is NOT overwritten */
4315int Strsafe_insert(data)
4316char *data;
4317{
4318 x1node *np;
4319 int h;
4320 int ph;
4321
4322 if( x1a==0 ) return 0;
4323 ph = strhash(data);
4324 h = ph & (x1a->size-1);
4325 np = x1a->ht[h];
4326 while( np ){
4327 if( strcmp(np->data,data)==0 ){
4328 /* An existing entry with the same key is found. */
4329 /* Fail because overwrite is not allows. */
4330 return 0;
4331 }
4332 np = np->next;
4333 }
4334 if( x1a->count>=x1a->size ){
4335 /* Need to make the hash table bigger */
4336 int i,size;
4337 struct s_x1 array;
4338 array.size = size = x1a->size*2;
4339 array.count = x1a->count;
4340 array.tbl = (x1node*)malloc(
4341 (sizeof(x1node) + sizeof(x1node*))*size );
4342 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4343 array.ht = (x1node**)&(array.tbl[size]);
4344 for(i=0; i<size; i++) array.ht[i] = 0;
4345 for(i=0; i<x1a->count; i++){
4346 x1node *oldnp, *newnp;
4347 oldnp = &(x1a->tbl[i]);
4348 h = strhash(oldnp->data) & (size-1);
4349 newnp = &(array.tbl[i]);
4350 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4351 newnp->next = array.ht[h];
4352 newnp->data = oldnp->data;
4353 newnp->from = &(array.ht[h]);
4354 array.ht[h] = newnp;
4355 }
4356 free(x1a->tbl);
4357 *x1a = array;
4358 }
4359 /* Insert the new data */
4360 h = ph & (x1a->size-1);
4361 np = &(x1a->tbl[x1a->count++]);
4362 np->data = data;
4363 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4364 np->next = x1a->ht[h];
4365 x1a->ht[h] = np;
4366 np->from = &(x1a->ht[h]);
4367 return 1;
4368}
4369
4370/* Return a pointer to data assigned to the given key. Return NULL
4371** if no such key. */
4372char *Strsafe_find(key)
4373char *key;
4374{
4375 int h;
4376 x1node *np;
4377
4378 if( x1a==0 ) return 0;
4379 h = strhash(key) & (x1a->size-1);
4380 np = x1a->ht[h];
4381 while( np ){
4382 if( strcmp(np->data,key)==0 ) break;
4383 np = np->next;
4384 }
4385 return np ? np->data : 0;
4386}
4387
4388/* Return a pointer to the (terminal or nonterminal) symbol "x".
4389** Create a new symbol if this is the first time "x" has been seen.
4390*/
4391struct symbol *Symbol_new(x)
4392char *x;
4393{
4394 struct symbol *sp;
4395
4396 sp = Symbol_find(x);
4397 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004398 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004399 MemoryCheck(sp);
4400 sp->name = Strsafe(x);
4401 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4402 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004403 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004404 sp->prec = -1;
4405 sp->assoc = UNK;
4406 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004407 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004408 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004409 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004410 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004411 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004412 Symbol_insert(sp,sp->name);
4413 }
drhc4dd3fd2008-01-22 01:48:05 +00004414 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004415 return sp;
4416}
4417
drh60d31652004-02-22 00:08:04 +00004418/* Compare two symbols for working purposes
4419**
4420** Symbols that begin with upper case letters (terminals or tokens)
4421** must sort before symbols that begin with lower case letters
4422** (non-terminals). Other than that, the order does not matter.
4423**
4424** We find experimentally that leaving the symbols in their original
4425** order (the order they appeared in the grammar file) gives the
4426** smallest parser tables in SQLite.
4427*/
4428int Symbolcmpp(struct symbol **a, struct symbol **b){
4429 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4430 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004431 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004432 return i1-i2;
drh75897232000-05-29 14:26:00 +00004433}
4434
4435/* There is one instance of the following structure for each
4436** associative array of type "x2".
4437*/
4438struct s_x2 {
4439 int size; /* The number of available slots. */
4440 /* Must be a power of 2 greater than or */
4441 /* equal to 1 */
4442 int count; /* Number of currently slots filled */
4443 struct s_x2node *tbl; /* The data stored here */
4444 struct s_x2node **ht; /* Hash table for lookups */
4445};
4446
4447/* There is one instance of this structure for every data element
4448** in an associative array of type "x2".
4449*/
4450typedef struct s_x2node {
4451 struct symbol *data; /* The data */
4452 char *key; /* The key */
4453 struct s_x2node *next; /* Next entry with the same hash */
4454 struct s_x2node **from; /* Previous link */
4455} x2node;
4456
4457/* There is only one instance of the array, which is the following */
4458static struct s_x2 *x2a;
4459
4460/* Allocate a new associative array */
4461void Symbol_init(){
4462 if( x2a ) return;
4463 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4464 if( x2a ){
4465 x2a->size = 128;
4466 x2a->count = 0;
4467 x2a->tbl = (x2node*)malloc(
4468 (sizeof(x2node) + sizeof(x2node*))*128 );
4469 if( x2a->tbl==0 ){
4470 free(x2a);
4471 x2a = 0;
4472 }else{
4473 int i;
4474 x2a->ht = (x2node**)&(x2a->tbl[128]);
4475 for(i=0; i<128; i++) x2a->ht[i] = 0;
4476 }
4477 }
4478}
4479/* Insert a new record into the array. Return TRUE if successful.
4480** Prior data with the same key is NOT overwritten */
4481int Symbol_insert(data,key)
4482struct symbol *data;
4483char *key;
4484{
4485 x2node *np;
4486 int h;
4487 int ph;
4488
4489 if( x2a==0 ) return 0;
4490 ph = strhash(key);
4491 h = ph & (x2a->size-1);
4492 np = x2a->ht[h];
4493 while( np ){
4494 if( strcmp(np->key,key)==0 ){
4495 /* An existing entry with the same key is found. */
4496 /* Fail because overwrite is not allows. */
4497 return 0;
4498 }
4499 np = np->next;
4500 }
4501 if( x2a->count>=x2a->size ){
4502 /* Need to make the hash table bigger */
4503 int i,size;
4504 struct s_x2 array;
4505 array.size = size = x2a->size*2;
4506 array.count = x2a->count;
4507 array.tbl = (x2node*)malloc(
4508 (sizeof(x2node) + sizeof(x2node*))*size );
4509 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4510 array.ht = (x2node**)&(array.tbl[size]);
4511 for(i=0; i<size; i++) array.ht[i] = 0;
4512 for(i=0; i<x2a->count; i++){
4513 x2node *oldnp, *newnp;
4514 oldnp = &(x2a->tbl[i]);
4515 h = strhash(oldnp->key) & (size-1);
4516 newnp = &(array.tbl[i]);
4517 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4518 newnp->next = array.ht[h];
4519 newnp->key = oldnp->key;
4520 newnp->data = oldnp->data;
4521 newnp->from = &(array.ht[h]);
4522 array.ht[h] = newnp;
4523 }
4524 free(x2a->tbl);
4525 *x2a = array;
4526 }
4527 /* Insert the new data */
4528 h = ph & (x2a->size-1);
4529 np = &(x2a->tbl[x2a->count++]);
4530 np->key = key;
4531 np->data = data;
4532 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4533 np->next = x2a->ht[h];
4534 x2a->ht[h] = np;
4535 np->from = &(x2a->ht[h]);
4536 return 1;
4537}
4538
4539/* Return a pointer to data assigned to the given key. Return NULL
4540** if no such key. */
4541struct symbol *Symbol_find(key)
4542char *key;
4543{
4544 int h;
4545 x2node *np;
4546
4547 if( x2a==0 ) return 0;
4548 h = strhash(key) & (x2a->size-1);
4549 np = x2a->ht[h];
4550 while( np ){
4551 if( strcmp(np->key,key)==0 ) break;
4552 np = np->next;
4553 }
4554 return np ? np->data : 0;
4555}
4556
4557/* Return the n-th data. Return NULL if n is out of range. */
4558struct symbol *Symbol_Nth(n)
4559int n;
4560{
4561 struct symbol *data;
4562 if( x2a && n>0 && n<=x2a->count ){
4563 data = x2a->tbl[n-1].data;
4564 }else{
4565 data = 0;
4566 }
4567 return data;
4568}
4569
4570/* Return the size of the array */
4571int Symbol_count()
4572{
4573 return x2a ? x2a->count : 0;
4574}
4575
4576/* Return an array of pointers to all data in the table.
4577** The array is obtained from malloc. Return NULL if memory allocation
4578** problems, or if the array is empty. */
4579struct symbol **Symbol_arrayof()
4580{
4581 struct symbol **array;
4582 int i,size;
4583 if( x2a==0 ) return 0;
4584 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004585 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004586 if( array ){
4587 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4588 }
4589 return array;
4590}
4591
4592/* Compare two configurations */
4593int Configcmp(a,b)
4594struct config *a;
4595struct config *b;
4596{
4597 int x;
4598 x = a->rp->index - b->rp->index;
4599 if( x==0 ) x = a->dot - b->dot;
4600 return x;
4601}
4602
4603/* Compare two states */
4604PRIVATE int statecmp(a,b)
4605struct config *a;
4606struct config *b;
4607{
4608 int rc;
4609 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4610 rc = a->rp->index - b->rp->index;
4611 if( rc==0 ) rc = a->dot - b->dot;
4612 }
4613 if( rc==0 ){
4614 if( a ) rc = 1;
4615 if( b ) rc = -1;
4616 }
4617 return rc;
4618}
4619
4620/* Hash a state */
4621PRIVATE int statehash(a)
4622struct config *a;
4623{
4624 int h=0;
4625 while( a ){
4626 h = h*571 + a->rp->index*37 + a->dot;
4627 a = a->bp;
4628 }
4629 return h;
4630}
4631
4632/* Allocate a new state structure */
4633struct state *State_new()
4634{
4635 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004636 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004637 MemoryCheck(new);
4638 return new;
4639}
4640
4641/* There is one instance of the following structure for each
4642** associative array of type "x3".
4643*/
4644struct s_x3 {
4645 int size; /* The number of available slots. */
4646 /* Must be a power of 2 greater than or */
4647 /* equal to 1 */
4648 int count; /* Number of currently slots filled */
4649 struct s_x3node *tbl; /* The data stored here */
4650 struct s_x3node **ht; /* Hash table for lookups */
4651};
4652
4653/* There is one instance of this structure for every data element
4654** in an associative array of type "x3".
4655*/
4656typedef struct s_x3node {
4657 struct state *data; /* The data */
4658 struct config *key; /* The key */
4659 struct s_x3node *next; /* Next entry with the same hash */
4660 struct s_x3node **from; /* Previous link */
4661} x3node;
4662
4663/* There is only one instance of the array, which is the following */
4664static struct s_x3 *x3a;
4665
4666/* Allocate a new associative array */
4667void State_init(){
4668 if( x3a ) return;
4669 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4670 if( x3a ){
4671 x3a->size = 128;
4672 x3a->count = 0;
4673 x3a->tbl = (x3node*)malloc(
4674 (sizeof(x3node) + sizeof(x3node*))*128 );
4675 if( x3a->tbl==0 ){
4676 free(x3a);
4677 x3a = 0;
4678 }else{
4679 int i;
4680 x3a->ht = (x3node**)&(x3a->tbl[128]);
4681 for(i=0; i<128; i++) x3a->ht[i] = 0;
4682 }
4683 }
4684}
4685/* Insert a new record into the array. Return TRUE if successful.
4686** Prior data with the same key is NOT overwritten */
4687int State_insert(data,key)
4688struct state *data;
4689struct config *key;
4690{
4691 x3node *np;
4692 int h;
4693 int ph;
4694
4695 if( x3a==0 ) return 0;
4696 ph = statehash(key);
4697 h = ph & (x3a->size-1);
4698 np = x3a->ht[h];
4699 while( np ){
4700 if( statecmp(np->key,key)==0 ){
4701 /* An existing entry with the same key is found. */
4702 /* Fail because overwrite is not allows. */
4703 return 0;
4704 }
4705 np = np->next;
4706 }
4707 if( x3a->count>=x3a->size ){
4708 /* Need to make the hash table bigger */
4709 int i,size;
4710 struct s_x3 array;
4711 array.size = size = x3a->size*2;
4712 array.count = x3a->count;
4713 array.tbl = (x3node*)malloc(
4714 (sizeof(x3node) + sizeof(x3node*))*size );
4715 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4716 array.ht = (x3node**)&(array.tbl[size]);
4717 for(i=0; i<size; i++) array.ht[i] = 0;
4718 for(i=0; i<x3a->count; i++){
4719 x3node *oldnp, *newnp;
4720 oldnp = &(x3a->tbl[i]);
4721 h = statehash(oldnp->key) & (size-1);
4722 newnp = &(array.tbl[i]);
4723 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4724 newnp->next = array.ht[h];
4725 newnp->key = oldnp->key;
4726 newnp->data = oldnp->data;
4727 newnp->from = &(array.ht[h]);
4728 array.ht[h] = newnp;
4729 }
4730 free(x3a->tbl);
4731 *x3a = array;
4732 }
4733 /* Insert the new data */
4734 h = ph & (x3a->size-1);
4735 np = &(x3a->tbl[x3a->count++]);
4736 np->key = key;
4737 np->data = data;
4738 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4739 np->next = x3a->ht[h];
4740 x3a->ht[h] = np;
4741 np->from = &(x3a->ht[h]);
4742 return 1;
4743}
4744
4745/* Return a pointer to data assigned to the given key. Return NULL
4746** if no such key. */
4747struct state *State_find(key)
4748struct config *key;
4749{
4750 int h;
4751 x3node *np;
4752
4753 if( x3a==0 ) return 0;
4754 h = statehash(key) & (x3a->size-1);
4755 np = x3a->ht[h];
4756 while( np ){
4757 if( statecmp(np->key,key)==0 ) break;
4758 np = np->next;
4759 }
4760 return np ? np->data : 0;
4761}
4762
4763/* Return an array of pointers to all data in the table.
4764** The array is obtained from malloc. Return NULL if memory allocation
4765** problems, or if the array is empty. */
4766struct state **State_arrayof()
4767{
4768 struct state **array;
4769 int i,size;
4770 if( x3a==0 ) return 0;
4771 size = x3a->count;
4772 array = (struct state **)malloc( sizeof(struct state *)*size );
4773 if( array ){
4774 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4775 }
4776 return array;
4777}
4778
4779/* Hash a configuration */
4780PRIVATE int confighash(a)
4781struct config *a;
4782{
4783 int h=0;
4784 h = h*571 + a->rp->index*37 + a->dot;
4785 return h;
4786}
4787
4788/* There is one instance of the following structure for each
4789** associative array of type "x4".
4790*/
4791struct s_x4 {
4792 int size; /* The number of available slots. */
4793 /* Must be a power of 2 greater than or */
4794 /* equal to 1 */
4795 int count; /* Number of currently slots filled */
4796 struct s_x4node *tbl; /* The data stored here */
4797 struct s_x4node **ht; /* Hash table for lookups */
4798};
4799
4800/* There is one instance of this structure for every data element
4801** in an associative array of type "x4".
4802*/
4803typedef struct s_x4node {
4804 struct config *data; /* The data */
4805 struct s_x4node *next; /* Next entry with the same hash */
4806 struct s_x4node **from; /* Previous link */
4807} x4node;
4808
4809/* There is only one instance of the array, which is the following */
4810static struct s_x4 *x4a;
4811
4812/* Allocate a new associative array */
4813void Configtable_init(){
4814 if( x4a ) return;
4815 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4816 if( x4a ){
4817 x4a->size = 64;
4818 x4a->count = 0;
4819 x4a->tbl = (x4node*)malloc(
4820 (sizeof(x4node) + sizeof(x4node*))*64 );
4821 if( x4a->tbl==0 ){
4822 free(x4a);
4823 x4a = 0;
4824 }else{
4825 int i;
4826 x4a->ht = (x4node**)&(x4a->tbl[64]);
4827 for(i=0; i<64; i++) x4a->ht[i] = 0;
4828 }
4829 }
4830}
4831/* Insert a new record into the array. Return TRUE if successful.
4832** Prior data with the same key is NOT overwritten */
4833int Configtable_insert(data)
4834struct config *data;
4835{
4836 x4node *np;
4837 int h;
4838 int ph;
4839
4840 if( x4a==0 ) return 0;
4841 ph = confighash(data);
4842 h = ph & (x4a->size-1);
4843 np = x4a->ht[h];
4844 while( np ){
4845 if( Configcmp(np->data,data)==0 ){
4846 /* An existing entry with the same key is found. */
4847 /* Fail because overwrite is not allows. */
4848 return 0;
4849 }
4850 np = np->next;
4851 }
4852 if( x4a->count>=x4a->size ){
4853 /* Need to make the hash table bigger */
4854 int i,size;
4855 struct s_x4 array;
4856 array.size = size = x4a->size*2;
4857 array.count = x4a->count;
4858 array.tbl = (x4node*)malloc(
4859 (sizeof(x4node) + sizeof(x4node*))*size );
4860 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4861 array.ht = (x4node**)&(array.tbl[size]);
4862 for(i=0; i<size; i++) array.ht[i] = 0;
4863 for(i=0; i<x4a->count; i++){
4864 x4node *oldnp, *newnp;
4865 oldnp = &(x4a->tbl[i]);
4866 h = confighash(oldnp->data) & (size-1);
4867 newnp = &(array.tbl[i]);
4868 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4869 newnp->next = array.ht[h];
4870 newnp->data = oldnp->data;
4871 newnp->from = &(array.ht[h]);
4872 array.ht[h] = newnp;
4873 }
4874 free(x4a->tbl);
4875 *x4a = array;
4876 }
4877 /* Insert the new data */
4878 h = ph & (x4a->size-1);
4879 np = &(x4a->tbl[x4a->count++]);
4880 np->data = data;
4881 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4882 np->next = x4a->ht[h];
4883 x4a->ht[h] = np;
4884 np->from = &(x4a->ht[h]);
4885 return 1;
4886}
4887
4888/* Return a pointer to data assigned to the given key. Return NULL
4889** if no such key. */
4890struct config *Configtable_find(key)
4891struct config *key;
4892{
4893 int h;
4894 x4node *np;
4895
4896 if( x4a==0 ) return 0;
4897 h = confighash(key) & (x4a->size-1);
4898 np = x4a->ht[h];
4899 while( np ){
4900 if( Configcmp(np->data,key)==0 ) break;
4901 np = np->next;
4902 }
4903 return np ? np->data : 0;
4904}
4905
4906/* Remove all data from the table. Pass each data to the function "f"
4907** as it is removed. ("f" may be null to avoid this step.) */
4908void Configtable_clear(f)
4909int(*f)(/* struct config * */);
4910{
4911 int i;
4912 if( x4a==0 || x4a->count==0 ) return;
4913 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4914 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4915 x4a->count = 0;
4916 return;
4917}