blob: b5095f3a1708d46479fc7004f687b203d66946dd [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;
drhcf3e5182010-01-06 13:07:30 +0000494 int nActtab; /* Number of slots in the p->aAction[] table */
drh8b582012003-10-21 13:16:03 +0000495 assert( p->nLookahead>0 );
496
497 /* Make sure we have enough space to hold the expanded action table
498 ** in the worst case. The worst case occurs if the transaction set
499 ** must be appended to the current action table
500 */
drh784d86f2004-02-19 18:41:53 +0000501 n = p->mxLookahead + 1;
drhcf3e5182010-01-06 13:07:30 +0000502 nActtab = p->nAction + n;
503 if( nActtab >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000504 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000505 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
506 p->aAction = realloc( p->aAction,
507 sizeof(p->aAction[0])*p->nActionAlloc);
508 if( p->aAction==0 ){
509 fprintf(stderr,"malloc failed\n");
510 exit(1);
511 }
drhfdbf9282003-10-21 16:34:41 +0000512 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000513 p->aAction[i].lookahead = -1;
514 p->aAction[i].action = -1;
515 }
516 }
517
518 /* Scan the existing action table looking for an offset where we can
519 ** insert the current transaction set. Fall out of the loop when that
520 ** offset is found. In the worst case, we fall out of the loop when
drhcf3e5182010-01-06 13:07:30 +0000521 ** i reaches nActtab, which means we append the new transaction set.
drh8b582012003-10-21 13:16:03 +0000522 **
523 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
524 */
drhcf3e5182010-01-06 13:07:30 +0000525 for(i=nActtab-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000526 /* First look for an existing action table entry that can be reused */
527 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8b582012003-10-21 13:16:03 +0000528 if( p->aAction[i].action!=p->mnAction ) continue;
529 for(j=0; j<p->nLookahead; j++){
530 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
531 if( k<0 || k>=p->nAction ) break;
532 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
533 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
534 }
535 if( j<p->nLookahead ) continue;
536 n = 0;
537 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000538 if( p->aAction[j].lookahead<0 ) continue;
539 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000540 }
drhfdbf9282003-10-21 16:34:41 +0000541 if( n==p->nLookahead ){
542 break; /* Same as a prior transaction set */
543 }
drh8b582012003-10-21 13:16:03 +0000544 }
545 }
drhf16371d2009-11-03 19:18:31 +0000546 if( i<0 ){
547 /* If no reusable entry is found, look for an empty slot */
drhcf3e5182010-01-06 13:07:30 +0000548 for(i=0; i<nActtab; i++){
drhf16371d2009-11-03 19:18:31 +0000549 if( p->aAction[i].lookahead<0 ){
550 for(j=0; j<p->nLookahead; j++){
551 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
552 if( k<0 ) break;
553 if( p->aAction[k].lookahead>=0 ) break;
554 }
555 if( j<p->nLookahead ) continue;
556 for(j=0; j<p->nAction; j++){
557 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
558 }
559 if( j==p->nAction ){
560 break; /* Fits in empty slots */
561 }
562 }
563 }
564 }
drh8b582012003-10-21 13:16:03 +0000565 /* Insert transaction set at index i. */
566 for(j=0; j<p->nLookahead; j++){
567 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
568 p->aAction[k] = p->aLookahead[j];
569 if( k>=p->nAction ) p->nAction = k+1;
570 }
571 p->nLookahead = 0;
572
573 /* Return the offset that is added to the lookahead in order to get the
574 ** index into yy_action of the action */
575 return i - p->mnLookahead;
576}
577
drh75897232000-05-29 14:26:00 +0000578/********************** From the file "build.c" *****************************/
579/*
580** Routines to construction the finite state machine for the LEMON
581** parser generator.
582*/
583
584/* Find a precedence symbol of every rule in the grammar.
585**
586** Those rules which have a precedence symbol coded in the input
587** grammar using the "[symbol]" construct will already have the
588** rp->precsym field filled. Other rules take as their precedence
589** symbol the first RHS symbol with a defined precedence. If there
590** are not RHS symbols with a defined precedence, the precedence
591** symbol field is left blank.
592*/
593void FindRulePrecedences(xp)
594struct lemon *xp;
595{
596 struct rule *rp;
597 for(rp=xp->rule; rp; rp=rp->next){
598 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000599 int i, j;
600 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
601 struct symbol *sp = rp->rhs[i];
602 if( sp->type==MULTITERMINAL ){
603 for(j=0; j<sp->nsubsym; j++){
604 if( sp->subsym[j]->prec>=0 ){
605 rp->precsym = sp->subsym[j];
606 break;
607 }
608 }
609 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000610 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000611 }
612 }
613 }
614 }
615 return;
616}
617
618/* Find all nonterminals which will generate the empty string.
619** Then go back and compute the first sets of every nonterminal.
620** The first set is the set of all terminal symbols which can begin
621** a string generated by that nonterminal.
622*/
623void FindFirstSets(lemp)
624struct lemon *lemp;
625{
drhfd405312005-11-06 04:06:59 +0000626 int i, j;
drh75897232000-05-29 14:26:00 +0000627 struct rule *rp;
628 int progress;
629
630 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000631 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000632 }
633 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
634 lemp->symbols[i]->firstset = SetNew();
635 }
636
637 /* First compute all lambdas */
638 do{
639 progress = 0;
640 for(rp=lemp->rule; rp; rp=rp->next){
641 if( rp->lhs->lambda ) continue;
642 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000643 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000644 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000645 }
646 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000647 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000648 progress = 1;
649 }
650 }
651 }while( progress );
652
653 /* Now compute all first sets */
654 do{
655 struct symbol *s1, *s2;
656 progress = 0;
657 for(rp=lemp->rule; rp; rp=rp->next){
658 s1 = rp->lhs;
659 for(i=0; i<rp->nrhs; i++){
660 s2 = rp->rhs[i];
661 if( s2->type==TERMINAL ){
662 progress += SetAdd(s1->firstset,s2->index);
663 break;
drhfd405312005-11-06 04:06:59 +0000664 }else if( s2->type==MULTITERMINAL ){
665 for(j=0; j<s2->nsubsym; j++){
666 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
667 }
668 break;
drh75897232000-05-29 14:26:00 +0000669 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000670 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000671 }else{
672 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000673 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000674 }
675 }
676 }
677 }while( progress );
678 return;
679}
680
681/* Compute all LR(0) states for the grammar. Links
682** are added to between some states so that the LR(1) follow sets
683** can be computed later.
684*/
685PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
686void FindStates(lemp)
687struct lemon *lemp;
688{
689 struct symbol *sp;
690 struct rule *rp;
691
692 Configlist_init();
693
694 /* Find the start symbol */
695 if( lemp->start ){
696 sp = Symbol_find(lemp->start);
697 if( sp==0 ){
698 ErrorMsg(lemp->filename,0,
699"The specified start symbol \"%s\" is not \
700in a nonterminal of the grammar. \"%s\" will be used as the start \
701symbol instead.",lemp->start,lemp->rule->lhs->name);
702 lemp->errorcnt++;
703 sp = lemp->rule->lhs;
704 }
705 }else{
706 sp = lemp->rule->lhs;
707 }
708
709 /* Make sure the start symbol doesn't occur on the right-hand side of
710 ** any rule. Report an error if it does. (YACC would generate a new
711 ** start symbol in this case.) */
712 for(rp=lemp->rule; rp; rp=rp->next){
713 int i;
714 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000715 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000716 ErrorMsg(lemp->filename,0,
717"The start symbol \"%s\" occurs on the \
718right-hand side of a rule. This will result in a parser which \
719does not work properly.",sp->name);
720 lemp->errorcnt++;
721 }
722 }
723 }
724
725 /* The basis configuration set for the first state
726 ** is all rules which have the start symbol as their
727 ** left-hand side */
728 for(rp=sp->rule; rp; rp=rp->nextlhs){
729 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000730 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000731 newcfp = Configlist_addbasis(rp,0);
732 SetAdd(newcfp->fws,0);
733 }
734
735 /* Compute the first state. All other states will be
736 ** computed automatically during the computation of the first one.
737 ** The returned pointer to the first state is not used. */
738 (void)getstate(lemp);
739 return;
740}
741
742/* Return a pointer to a state which is described by the configuration
743** list which has been built from calls to Configlist_add.
744*/
745PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
746PRIVATE struct state *getstate(lemp)
747struct lemon *lemp;
748{
749 struct config *cfp, *bp;
750 struct state *stp;
751
752 /* Extract the sorted basis of the new state. The basis was constructed
753 ** by prior calls to "Configlist_addbasis()". */
754 Configlist_sortbasis();
755 bp = Configlist_basis();
756
757 /* Get a state with the same basis */
758 stp = State_find(bp);
759 if( stp ){
760 /* A state with the same basis already exists! Copy all the follow-set
761 ** propagation links from the state under construction into the
762 ** preexisting state, then return a pointer to the preexisting state */
763 struct config *x, *y;
764 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
765 Plink_copy(&y->bplp,x->bplp);
766 Plink_delete(x->fplp);
767 x->fplp = x->bplp = 0;
768 }
769 cfp = Configlist_return();
770 Configlist_eat(cfp);
771 }else{
772 /* This really is a new state. Construct all the details */
773 Configlist_closure(lemp); /* Compute the configuration closure */
774 Configlist_sort(); /* Sort the configuration closure */
775 cfp = Configlist_return(); /* Get a pointer to the config list */
776 stp = State_new(); /* A new state structure */
777 MemoryCheck(stp);
778 stp->bp = bp; /* Remember the configuration basis */
779 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000780 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000781 stp->ap = 0; /* No actions, yet. */
782 State_insert(stp,stp->bp); /* Add to the state table */
783 buildshifts(lemp,stp); /* Recursively compute successor states */
784 }
785 return stp;
786}
787
drhfd405312005-11-06 04:06:59 +0000788/*
789** Return true if two symbols are the same.
790*/
791int same_symbol(a,b)
792struct symbol *a;
793struct symbol *b;
794{
795 int i;
796 if( a==b ) return 1;
797 if( a->type!=MULTITERMINAL ) return 0;
798 if( b->type!=MULTITERMINAL ) return 0;
799 if( a->nsubsym!=b->nsubsym ) return 0;
800 for(i=0; i<a->nsubsym; i++){
801 if( a->subsym[i]!=b->subsym[i] ) return 0;
802 }
803 return 1;
804}
805
drh75897232000-05-29 14:26:00 +0000806/* Construct all successor states to the given state. A "successor"
807** state is any state which can be reached by a shift action.
808*/
809PRIVATE void buildshifts(lemp,stp)
810struct lemon *lemp;
811struct state *stp; /* The state from which successors are computed */
812{
813 struct config *cfp; /* For looping thru the config closure of "stp" */
814 struct config *bcfp; /* For the inner loop on config closure of "stp" */
815 struct config *new; /* */
816 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
817 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
818 struct state *newstp; /* A pointer to a successor state */
819
820 /* Each configuration becomes complete after it contibutes to a successor
821 ** state. Initially, all configurations are incomplete */
822 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
823
824 /* Loop through all configurations of the state "stp" */
825 for(cfp=stp->cfp; cfp; cfp=cfp->next){
826 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
827 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
828 Configlist_reset(); /* Reset the new config set */
829 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
830
831 /* For every configuration in the state "stp" which has the symbol "sp"
832 ** following its dot, add the same configuration to the basis set under
833 ** construction but with the dot shifted one symbol to the right. */
834 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
835 if( bcfp->status==COMPLETE ) continue; /* Already used */
836 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
837 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000838 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000839 bcfp->status = COMPLETE; /* Mark this config as used */
840 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
841 Plink_add(&new->bplp,bcfp);
842 }
843
844 /* Get a pointer to the state described by the basis configuration set
845 ** constructed in the preceding loop */
846 newstp = getstate(lemp);
847
848 /* The state "newstp" is reached from the state "stp" by a shift action
849 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000850 if( sp->type==MULTITERMINAL ){
851 int i;
852 for(i=0; i<sp->nsubsym; i++){
853 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
854 }
855 }else{
856 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
857 }
drh75897232000-05-29 14:26:00 +0000858 }
859}
860
861/*
862** Construct the propagation links
863*/
864void FindLinks(lemp)
865struct lemon *lemp;
866{
867 int i;
868 struct config *cfp, *other;
869 struct state *stp;
870 struct plink *plp;
871
872 /* Housekeeping detail:
873 ** Add to every propagate link a pointer back to the state to
874 ** which the link is attached. */
875 for(i=0; i<lemp->nstate; i++){
876 stp = lemp->sorted[i];
877 for(cfp=stp->cfp; cfp; cfp=cfp->next){
878 cfp->stp = stp;
879 }
880 }
881
882 /* Convert all backlinks into forward links. Only the forward
883 ** links are used in the follow-set computation. */
884 for(i=0; i<lemp->nstate; i++){
885 stp = lemp->sorted[i];
886 for(cfp=stp->cfp; cfp; cfp=cfp->next){
887 for(plp=cfp->bplp; plp; plp=plp->next){
888 other = plp->cfp;
889 Plink_add(&other->fplp,cfp);
890 }
891 }
892 }
893}
894
895/* Compute all followsets.
896**
897** A followset is the set of all symbols which can come immediately
898** after a configuration.
899*/
900void FindFollowSets(lemp)
901struct lemon *lemp;
902{
903 int i;
904 struct config *cfp;
905 struct plink *plp;
906 int progress;
907 int change;
908
909 for(i=0; i<lemp->nstate; i++){
910 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
911 cfp->status = INCOMPLETE;
912 }
913 }
914
915 do{
916 progress = 0;
917 for(i=0; i<lemp->nstate; i++){
918 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
919 if( cfp->status==COMPLETE ) continue;
920 for(plp=cfp->fplp; plp; plp=plp->next){
921 change = SetUnion(plp->cfp->fws,cfp->fws);
922 if( change ){
923 plp->cfp->status = INCOMPLETE;
924 progress = 1;
925 }
926 }
927 cfp->status = COMPLETE;
928 }
929 }
930 }while( progress );
931}
932
933static int resolve_conflict();
934
935/* Compute the reduce actions, and resolve conflicts.
936*/
937void FindActions(lemp)
938struct lemon *lemp;
939{
940 int i,j;
941 struct config *cfp;
942 struct state *stp;
943 struct symbol *sp;
944 struct rule *rp;
945
946 /* Add all of the reduce actions
947 ** A reduce action is added for each element of the followset of
948 ** a configuration which has its dot at the extreme right.
949 */
950 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
951 stp = lemp->sorted[i];
952 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
953 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
954 for(j=0; j<lemp->nterminal; j++){
955 if( SetFind(cfp->fws,j) ){
956 /* Add a reduce action to the state "stp" which will reduce by the
957 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000958 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000959 }
960 }
961 }
962 }
963 }
964
965 /* Add the accepting token */
966 if( lemp->start ){
967 sp = Symbol_find(lemp->start);
968 if( sp==0 ) sp = lemp->rule->lhs;
969 }else{
970 sp = lemp->rule->lhs;
971 }
972 /* Add to the first state (which is always the starting state of the
973 ** finite state machine) an action to ACCEPT if the lookahead is the
974 ** start nonterminal. */
975 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
976
977 /* Resolve conflicts */
978 for(i=0; i<lemp->nstate; i++){
979 struct action *ap, *nap;
980 struct state *stp;
981 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000982 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000983 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000984 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000985 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
986 /* The two actions "ap" and "nap" have the same lookahead.
987 ** Figure out which one should be used */
988 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
989 }
990 }
991 }
992
993 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000994 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000995 for(i=0; i<lemp->nstate; i++){
996 struct action *ap;
997 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000998 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000999 }
1000 }
1001 for(rp=lemp->rule; rp; rp=rp->next){
1002 if( rp->canReduce ) continue;
1003 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1004 lemp->errorcnt++;
1005 }
1006}
1007
1008/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001009** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001010**
1011** NO LONGER TRUE:
1012** To resolve a conflict, first look to see if either action
1013** is on an error rule. In that case, take the action which
1014** is not associated with the error rule. If neither or both
1015** actions are associated with an error rule, then try to
1016** use precedence to resolve the conflict.
1017**
1018** If either action is a SHIFT, then it must be apx. This
1019** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1020*/
1021static int resolve_conflict(apx,apy,errsym)
1022struct action *apx;
1023struct action *apy;
1024struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1025{
1026 struct symbol *spx, *spy;
1027 int errcnt = 0;
1028 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001029 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001030 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001031 errcnt++;
1032 }
drh75897232000-05-29 14:26:00 +00001033 if( apx->type==SHIFT && apy->type==REDUCE ){
1034 spx = apx->sp;
1035 spy = apy->x.rp->precsym;
1036 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1037 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001038 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001039 errcnt++;
1040 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1041 apy->type = RD_RESOLVED;
1042 }else if( spx->prec<spy->prec ){
1043 apx->type = SH_RESOLVED;
1044 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1045 apy->type = RD_RESOLVED; /* associativity */
1046 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1047 apx->type = SH_RESOLVED;
1048 }else{
1049 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001050 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001051 errcnt++;
1052 }
1053 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1054 spx = apx->x.rp->precsym;
1055 spy = apy->x.rp->precsym;
1056 if( spx==0 || spy==0 || spx->prec<0 ||
1057 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001058 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001059 errcnt++;
1060 }else if( spx->prec>spy->prec ){
1061 apy->type = RD_RESOLVED;
1062 }else if( spx->prec<spy->prec ){
1063 apx->type = RD_RESOLVED;
1064 }
1065 }else{
drhb59499c2002-02-23 18:45:13 +00001066 assert(
1067 apx->type==SH_RESOLVED ||
1068 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001069 apx->type==SSCONFLICT ||
1070 apx->type==SRCONFLICT ||
1071 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001072 apy->type==SH_RESOLVED ||
1073 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001074 apy->type==SSCONFLICT ||
1075 apy->type==SRCONFLICT ||
1076 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001077 );
1078 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1079 ** REDUCEs on the list. If we reach this point it must be because
1080 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001081 }
1082 return errcnt;
1083}
1084/********************* From the file "configlist.c" *************************/
1085/*
1086** Routines to processing a configuration list and building a state
1087** in the LEMON parser generator.
1088*/
1089
1090static struct config *freelist = 0; /* List of free configurations */
1091static struct config *current = 0; /* Top of list of configurations */
1092static struct config **currentend = 0; /* Last on list of configs */
1093static struct config *basis = 0; /* Top of list of basis configs */
1094static struct config **basisend = 0; /* End of list of basis configs */
1095
1096/* Return a pointer to a new configuration */
1097PRIVATE struct config *newconfig(){
1098 struct config *new;
1099 if( freelist==0 ){
1100 int i;
1101 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001102 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001103 if( freelist==0 ){
1104 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1105 exit(1);
1106 }
1107 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1108 freelist[amt-1].next = 0;
1109 }
1110 new = freelist;
1111 freelist = freelist->next;
1112 return new;
1113}
1114
1115/* The configuration "old" is no longer used */
1116PRIVATE void deleteconfig(old)
1117struct config *old;
1118{
1119 old->next = freelist;
1120 freelist = old;
1121}
1122
1123/* Initialized the configuration list builder */
1124void Configlist_init(){
1125 current = 0;
1126 currentend = &current;
1127 basis = 0;
1128 basisend = &basis;
1129 Configtable_init();
1130 return;
1131}
1132
1133/* Initialized the configuration list builder */
1134void Configlist_reset(){
1135 current = 0;
1136 currentend = &current;
1137 basis = 0;
1138 basisend = &basis;
1139 Configtable_clear(0);
1140 return;
1141}
1142
1143/* Add another configuration to the configuration list */
1144struct config *Configlist_add(rp,dot)
1145struct rule *rp; /* The rule */
1146int dot; /* Index into the RHS of the rule where the dot goes */
1147{
1148 struct config *cfp, model;
1149
1150 assert( currentend!=0 );
1151 model.rp = rp;
1152 model.dot = dot;
1153 cfp = Configtable_find(&model);
1154 if( cfp==0 ){
1155 cfp = newconfig();
1156 cfp->rp = rp;
1157 cfp->dot = dot;
1158 cfp->fws = SetNew();
1159 cfp->stp = 0;
1160 cfp->fplp = cfp->bplp = 0;
1161 cfp->next = 0;
1162 cfp->bp = 0;
1163 *currentend = cfp;
1164 currentend = &cfp->next;
1165 Configtable_insert(cfp);
1166 }
1167 return cfp;
1168}
1169
1170/* Add a basis configuration to the configuration list */
1171struct config *Configlist_addbasis(rp,dot)
1172struct rule *rp;
1173int dot;
1174{
1175 struct config *cfp, model;
1176
1177 assert( basisend!=0 );
1178 assert( currentend!=0 );
1179 model.rp = rp;
1180 model.dot = dot;
1181 cfp = Configtable_find(&model);
1182 if( cfp==0 ){
1183 cfp = newconfig();
1184 cfp->rp = rp;
1185 cfp->dot = dot;
1186 cfp->fws = SetNew();
1187 cfp->stp = 0;
1188 cfp->fplp = cfp->bplp = 0;
1189 cfp->next = 0;
1190 cfp->bp = 0;
1191 *currentend = cfp;
1192 currentend = &cfp->next;
1193 *basisend = cfp;
1194 basisend = &cfp->bp;
1195 Configtable_insert(cfp);
1196 }
1197 return cfp;
1198}
1199
1200/* Compute the closure of the configuration list */
1201void Configlist_closure(lemp)
1202struct lemon *lemp;
1203{
1204 struct config *cfp, *newcfp;
1205 struct rule *rp, *newrp;
1206 struct symbol *sp, *xsp;
1207 int i, dot;
1208
1209 assert( currentend!=0 );
1210 for(cfp=current; cfp; cfp=cfp->next){
1211 rp = cfp->rp;
1212 dot = cfp->dot;
1213 if( dot>=rp->nrhs ) continue;
1214 sp = rp->rhs[dot];
1215 if( sp->type==NONTERMINAL ){
1216 if( sp->rule==0 && sp!=lemp->errsym ){
1217 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1218 sp->name);
1219 lemp->errorcnt++;
1220 }
1221 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1222 newcfp = Configlist_add(newrp,0);
1223 for(i=dot+1; i<rp->nrhs; i++){
1224 xsp = rp->rhs[i];
1225 if( xsp->type==TERMINAL ){
1226 SetAdd(newcfp->fws,xsp->index);
1227 break;
drhfd405312005-11-06 04:06:59 +00001228 }else if( xsp->type==MULTITERMINAL ){
1229 int k;
1230 for(k=0; k<xsp->nsubsym; k++){
1231 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1232 }
1233 break;
drh75897232000-05-29 14:26:00 +00001234 }else{
1235 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001236 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001237 }
1238 }
1239 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1240 }
1241 }
1242 }
1243 return;
1244}
1245
1246/* Sort the configuration list */
1247void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001248 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001249 currentend = 0;
1250 return;
1251}
1252
1253/* Sort the basis configuration list */
1254void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001255 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001256 basisend = 0;
1257 return;
1258}
1259
1260/* Return a pointer to the head of the configuration list and
1261** reset the list */
1262struct config *Configlist_return(){
1263 struct config *old;
1264 old = current;
1265 current = 0;
1266 currentend = 0;
1267 return old;
1268}
1269
1270/* Return a pointer to the head of the configuration list and
1271** reset the list */
1272struct config *Configlist_basis(){
1273 struct config *old;
1274 old = basis;
1275 basis = 0;
1276 basisend = 0;
1277 return old;
1278}
1279
1280/* Free all elements of the given configuration list */
1281void Configlist_eat(cfp)
1282struct config *cfp;
1283{
1284 struct config *nextcfp;
1285 for(; cfp; cfp=nextcfp){
1286 nextcfp = cfp->next;
1287 assert( cfp->fplp==0 );
1288 assert( cfp->bplp==0 );
1289 if( cfp->fws ) SetFree(cfp->fws);
1290 deleteconfig(cfp);
1291 }
1292 return;
1293}
1294/***************** From the file "error.c" *********************************/
1295/*
1296** Code for printing error message.
1297*/
1298
1299/* Find a good place to break "msg" so that its length is at least "min"
1300** but no more than "max". Make the point as close to max as possible.
1301*/
1302static int findbreak(msg,min,max)
1303char *msg;
1304int min;
1305int max;
1306{
1307 int i,spot;
1308 char c;
1309 for(i=spot=min; i<=max; i++){
1310 c = msg[i];
1311 if( c=='\t' ) msg[i] = ' ';
1312 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1313 if( c==0 ){ spot = i; break; }
1314 if( c=='-' && i<max-1 ) spot = i+1;
1315 if( c==' ' ) spot = i;
1316 }
1317 return spot;
1318}
1319
1320/*
1321** The error message is split across multiple lines if necessary. The
1322** splits occur at a space, if there is a space available near the end
1323** of the line.
1324*/
1325#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1326#define LINEWIDTH 79 /* Max width of any output line */
1327#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001328void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001329 char errmsg[ERRMSGSIZE];
1330 char prefix[PREFIXLIMIT+10];
1331 int errmsgsize;
1332 int prefixsize;
1333 int availablewidth;
1334 va_list ap;
1335 int end, restart, base;
1336
drhf9a2e7b2003-04-15 01:49:48 +00001337 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001338 /* Prepare a prefix to be prepended to every output line */
1339 if( lineno>0 ){
1340 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1341 }else{
1342 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1343 }
drh87cf1372008-08-13 20:09:06 +00001344 prefixsize = lemonStrlen(prefix);
drh75897232000-05-29 14:26:00 +00001345 availablewidth = LINEWIDTH - prefixsize;
1346
1347 /* Generate the error message */
1348 vsprintf(errmsg,format,ap);
1349 va_end(ap);
drh87cf1372008-08-13 20:09:06 +00001350 errmsgsize = lemonStrlen(errmsg);
drh75897232000-05-29 14:26:00 +00001351 /* Remove trailing '\n's from the error message. */
1352 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1353 errmsg[--errmsgsize] = 0;
1354 }
1355
1356 /* Print the error message */
1357 base = 0;
1358 while( errmsg[base]!=0 ){
1359 end = restart = findbreak(&errmsg[base],0,availablewidth);
1360 restart += base;
1361 while( errmsg[restart]==' ' ) restart++;
1362 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1363 base = restart;
1364 }
1365}
1366/**************** From the file "main.c" ************************************/
1367/*
1368** Main program file for the LEMON parser generator.
1369*/
1370
1371/* Report an out-of-memory condition and abort. This function
1372** is used mostly by the "MemoryCheck" macro in struct.h
1373*/
1374void memory_error(){
1375 fprintf(stderr,"Out of memory. Aborting...\n");
1376 exit(1);
1377}
1378
drh6d08b4d2004-07-20 12:45:22 +00001379static int nDefine = 0; /* Number of -D options on the command line */
1380static char **azDefine = 0; /* Name of the -D macros */
1381
1382/* This routine is called with the argument to each -D command-line option.
1383** Add the macro defined to the azDefine array.
1384*/
1385static void handle_D_option(char *z){
1386 char **paz;
1387 nDefine++;
1388 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1389 if( azDefine==0 ){
1390 fprintf(stderr,"out of memory\n");
1391 exit(1);
1392 }
1393 paz = &azDefine[nDefine-1];
drh87cf1372008-08-13 20:09:06 +00001394 *paz = malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001395 if( *paz==0 ){
1396 fprintf(stderr,"out of memory\n");
1397 exit(1);
1398 }
1399 strcpy(*paz, z);
1400 for(z=*paz; *z && *z!='='; z++){}
1401 *z = 0;
1402}
1403
drh75897232000-05-29 14:26:00 +00001404
1405/* The main program. Parse the command line and do it... */
1406int main(argc,argv)
1407int argc;
1408char **argv;
1409{
1410 static int version = 0;
1411 static int rpflag = 0;
1412 static int basisflag = 0;
1413 static int compress = 0;
1414 static int quiet = 0;
1415 static int statistics = 0;
1416 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001417 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001418 static struct s_options options[] = {
1419 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1420 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001421 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001422 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001423 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1424 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001425 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001426 {OPT_FLAG, "s", (char*)&statistics,
1427 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001428 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1429 {OPT_FLAG,0,0,0}
1430 };
1431 int i;
1432 struct lemon lem;
1433
drhb0c86772000-06-02 23:21:26 +00001434 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001435 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001436 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001437 exit(0);
1438 }
drhb0c86772000-06-02 23:21:26 +00001439 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001440 fprintf(stderr,"Exactly one filename argument is required.\n");
1441 exit(1);
1442 }
drh954f6b42006-06-13 13:27:46 +00001443 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001444 lem.errorcnt = 0;
1445
1446 /* Initialize the machine */
1447 Strsafe_init();
1448 Symbol_init();
1449 State_init();
1450 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001451 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001452 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001453 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001454 Symbol_new("$");
1455 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001456 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001457
1458 /* Parse the input file */
1459 Parse(&lem);
1460 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001461 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001462 fprintf(stderr,"Empty grammar.\n");
1463 exit(1);
1464 }
1465
1466 /* Count and index the symbols of the grammar */
1467 lem.nsymbol = Symbol_count();
1468 Symbol_new("{default}");
1469 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001470 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001471 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1472 (int(*)())Symbolcmpp);
1473 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1474 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1475 lem.nterminal = i;
1476
1477 /* Generate a reprint of the grammar, if requested on the command line */
1478 if( rpflag ){
1479 Reprint(&lem);
1480 }else{
1481 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001482 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001483
1484 /* Find the precedence for every production rule (that has one) */
1485 FindRulePrecedences(&lem);
1486
1487 /* Compute the lambda-nonterminals and the first-sets for every
1488 ** nonterminal */
1489 FindFirstSets(&lem);
1490
1491 /* Compute all LR(0) states. Also record follow-set propagation
1492 ** links so that the follow-set can be computed later */
1493 lem.nstate = 0;
1494 FindStates(&lem);
1495 lem.sorted = State_arrayof();
1496
1497 /* Tie up loose ends on the propagation links */
1498 FindLinks(&lem);
1499
1500 /* Compute the follow set of every reducible configuration */
1501 FindFollowSets(&lem);
1502
1503 /* Compute the action tables */
1504 FindActions(&lem);
1505
1506 /* Compress the action tables */
1507 if( compress==0 ) CompressTables(&lem);
1508
drhada354d2005-11-05 15:03:59 +00001509 /* Reorder and renumber the states so that states with fewer choices
1510 ** occur at the end. */
1511 ResortStates(&lem);
1512
drh75897232000-05-29 14:26:00 +00001513 /* Generate a report of the parser generated. (the "y.output" file) */
1514 if( !quiet ) ReportOutput(&lem);
1515
1516 /* Generate the source code for the parser */
1517 ReportTable(&lem, mhflag);
1518
1519 /* Produce a header file for use by the scanner. (This step is
1520 ** omitted if the "-m" option is used because makeheaders will
1521 ** generate the file for us.) */
1522 if( !mhflag ) ReportHeader(&lem);
1523 }
1524 if( statistics ){
1525 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1526 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1527 printf(" %d states, %d parser table entries, %d conflicts\n",
1528 lem.nstate, lem.tablesize, lem.nconflict);
1529 }
1530 if( lem.nconflict ){
1531 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1532 }
1533 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001534 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001535}
1536/******************** From the file "msort.c" *******************************/
1537/*
1538** A generic merge-sort program.
1539**
1540** USAGE:
1541** Let "ptr" be a pointer to some structure which is at the head of
1542** a null-terminated list. Then to sort the list call:
1543**
1544** ptr = msort(ptr,&(ptr->next),cmpfnc);
1545**
1546** In the above, "cmpfnc" is a pointer to a function which compares
1547** two instances of the structure and returns an integer, as in
1548** strcmp. The second argument is a pointer to the pointer to the
1549** second element of the linked list. This address is used to compute
1550** the offset to the "next" field within the structure. The offset to
1551** the "next" field must be constant for all structures in the list.
1552**
1553** The function returns a new pointer which is the head of the list
1554** after sorting.
1555**
1556** ALGORITHM:
1557** Merge-sort.
1558*/
1559
1560/*
1561** Return a pointer to the next structure in the linked list.
1562*/
drhba99af52001-10-25 20:37:16 +00001563#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001564
1565/*
1566** Inputs:
1567** a: A sorted, null-terminated linked list. (May be null).
1568** b: A sorted, null-terminated linked list. (May be null).
1569** cmp: A pointer to the comparison function.
1570** offset: Offset in the structure to the "next" field.
1571**
1572** Return Value:
1573** A pointer to the head of a sorted list containing the elements
1574** of both a and b.
1575**
1576** Side effects:
1577** The "next" pointers for elements in the lists a and b are
1578** changed.
1579*/
drhe9278182007-07-18 18:16:29 +00001580static char *merge(
1581 char *a,
1582 char *b,
1583 int (*cmp)(const char*,const char*),
1584 int offset
1585){
drh75897232000-05-29 14:26:00 +00001586 char *ptr, *head;
1587
1588 if( a==0 ){
1589 head = b;
1590 }else if( b==0 ){
1591 head = a;
1592 }else{
drhe594bc32009-11-03 13:02:25 +00001593 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001594 ptr = a;
1595 a = NEXT(a);
1596 }else{
1597 ptr = b;
1598 b = NEXT(b);
1599 }
1600 head = ptr;
1601 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001602 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001603 NEXT(ptr) = a;
1604 ptr = a;
1605 a = NEXT(a);
1606 }else{
1607 NEXT(ptr) = b;
1608 ptr = b;
1609 b = NEXT(b);
1610 }
1611 }
1612 if( a ) NEXT(ptr) = a;
1613 else NEXT(ptr) = b;
1614 }
1615 return head;
1616}
1617
1618/*
1619** Inputs:
1620** list: Pointer to a singly-linked list of structures.
1621** next: Pointer to pointer to the second element of the list.
1622** cmp: A comparison function.
1623**
1624** Return Value:
1625** A pointer to the head of a sorted list containing the elements
1626** orginally in list.
1627**
1628** Side effects:
1629** The "next" pointers for elements in list are changed.
1630*/
1631#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001632static char *msort(
1633 char *list,
1634 char **next,
1635 int (*cmp)(const char*,const char*)
1636){
drhba99af52001-10-25 20:37:16 +00001637 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001638 char *ep;
1639 char *set[LISTSIZE];
1640 int i;
drhba99af52001-10-25 20:37:16 +00001641 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001642 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1643 while( list ){
1644 ep = list;
1645 list = NEXT(list);
1646 NEXT(ep) = 0;
1647 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1648 ep = merge(ep,set[i],cmp,offset);
1649 set[i] = 0;
1650 }
1651 set[i] = ep;
1652 }
1653 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001654 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001655 return ep;
1656}
1657/************************ From the file "option.c" **************************/
1658static char **argv;
1659static struct s_options *op;
1660static FILE *errstream;
1661
1662#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1663
1664/*
1665** Print the command line with a carrot pointing to the k-th character
1666** of the n-th field.
1667*/
1668static void errline(n,k,err)
1669int n;
1670int k;
1671FILE *err;
1672{
1673 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001674 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001675 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001676 for(i=1; i<n && argv[i]; i++){
1677 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001678 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001679 }
1680 spcnt += k;
1681 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1682 if( spcnt<20 ){
1683 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1684 }else{
1685 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1686 }
1687}
1688
1689/*
1690** Return the index of the N-th non-switch argument. Return -1
1691** if N is out of range.
1692*/
1693static int argindex(n)
1694int n;
1695{
1696 int i;
1697 int dashdash = 0;
1698 if( argv!=0 && *argv!=0 ){
1699 for(i=1; argv[i]; i++){
1700 if( dashdash || !ISOPT(argv[i]) ){
1701 if( n==0 ) return i;
1702 n--;
1703 }
1704 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1705 }
1706 }
1707 return -1;
1708}
1709
1710static char emsg[] = "Command line syntax error: ";
1711
1712/*
1713** Process a flag command line argument.
1714*/
1715static int handleflags(i,err)
1716int i;
1717FILE *err;
1718{
1719 int v;
1720 int errcnt = 0;
1721 int j;
1722 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001723 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001724 }
1725 v = argv[i][0]=='-' ? 1 : 0;
1726 if( op[j].label==0 ){
1727 if( err ){
1728 fprintf(err,"%sundefined option.\n",emsg);
1729 errline(i,1,err);
1730 }
1731 errcnt++;
1732 }else if( op[j].type==OPT_FLAG ){
1733 *((int*)op[j].arg) = v;
1734 }else if( op[j].type==OPT_FFLAG ){
1735 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001736 }else if( op[j].type==OPT_FSTR ){
1737 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001738 }else{
1739 if( err ){
1740 fprintf(err,"%smissing argument on switch.\n",emsg);
1741 errline(i,1,err);
1742 }
1743 errcnt++;
1744 }
1745 return errcnt;
1746}
1747
1748/*
1749** Process a command line switch which has an argument.
1750*/
1751static int handleswitch(i,err)
1752int i;
1753FILE *err;
1754{
1755 int lv = 0;
1756 double dv = 0.0;
1757 char *sv = 0, *end;
1758 char *cp;
1759 int j;
1760 int errcnt = 0;
1761 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001762 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001763 *cp = 0;
1764 for(j=0; op[j].label; j++){
1765 if( strcmp(argv[i],op[j].label)==0 ) break;
1766 }
1767 *cp = '=';
1768 if( op[j].label==0 ){
1769 if( err ){
1770 fprintf(err,"%sundefined option.\n",emsg);
1771 errline(i,0,err);
1772 }
1773 errcnt++;
1774 }else{
1775 cp++;
1776 switch( op[j].type ){
1777 case OPT_FLAG:
1778 case OPT_FFLAG:
1779 if( err ){
1780 fprintf(err,"%soption requires an argument.\n",emsg);
1781 errline(i,0,err);
1782 }
1783 errcnt++;
1784 break;
1785 case OPT_DBL:
1786 case OPT_FDBL:
1787 dv = strtod(cp,&end);
1788 if( *end ){
1789 if( err ){
1790 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001791 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001792 }
1793 errcnt++;
1794 }
1795 break;
1796 case OPT_INT:
1797 case OPT_FINT:
1798 lv = strtol(cp,&end,0);
1799 if( *end ){
1800 if( err ){
1801 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001802 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001803 }
1804 errcnt++;
1805 }
1806 break;
1807 case OPT_STR:
1808 case OPT_FSTR:
1809 sv = cp;
1810 break;
1811 }
1812 switch( op[j].type ){
1813 case OPT_FLAG:
1814 case OPT_FFLAG:
1815 break;
1816 case OPT_DBL:
1817 *(double*)(op[j].arg) = dv;
1818 break;
1819 case OPT_FDBL:
1820 (*(void(*)())(op[j].arg))(dv);
1821 break;
1822 case OPT_INT:
1823 *(int*)(op[j].arg) = lv;
1824 break;
1825 case OPT_FINT:
1826 (*(void(*)())(op[j].arg))((int)lv);
1827 break;
1828 case OPT_STR:
1829 *(char**)(op[j].arg) = sv;
1830 break;
1831 case OPT_FSTR:
1832 (*(void(*)())(op[j].arg))(sv);
1833 break;
1834 }
1835 }
1836 return errcnt;
1837}
1838
drhb0c86772000-06-02 23:21:26 +00001839int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001840char **a;
1841struct s_options *o;
1842FILE *err;
1843{
1844 int errcnt = 0;
1845 argv = a;
1846 op = o;
1847 errstream = err;
1848 if( argv && *argv && op ){
1849 int i;
1850 for(i=1; argv[i]; i++){
1851 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1852 errcnt += handleflags(i,err);
1853 }else if( strchr(argv[i],'=') ){
1854 errcnt += handleswitch(i,err);
1855 }
1856 }
1857 }
1858 if( errcnt>0 ){
1859 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001860 OptPrint();
drh75897232000-05-29 14:26:00 +00001861 exit(1);
1862 }
1863 return 0;
1864}
1865
drhb0c86772000-06-02 23:21:26 +00001866int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001867 int cnt = 0;
1868 int dashdash = 0;
1869 int i;
1870 if( argv!=0 && argv[0]!=0 ){
1871 for(i=1; argv[i]; i++){
1872 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1873 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1874 }
1875 }
1876 return cnt;
1877}
1878
drhb0c86772000-06-02 23:21:26 +00001879char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001880int n;
1881{
1882 int i;
1883 i = argindex(n);
1884 return i>=0 ? argv[i] : 0;
1885}
1886
drhb0c86772000-06-02 23:21:26 +00001887void OptErr(n)
drh75897232000-05-29 14:26:00 +00001888int n;
1889{
1890 int i;
1891 i = argindex(n);
1892 if( i>=0 ) errline(i,0,errstream);
1893}
1894
drhb0c86772000-06-02 23:21:26 +00001895void OptPrint(){
drh75897232000-05-29 14:26:00 +00001896 int i;
1897 int max, len;
1898 max = 0;
1899 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001900 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001901 switch( op[i].type ){
1902 case OPT_FLAG:
1903 case OPT_FFLAG:
1904 break;
1905 case OPT_INT:
1906 case OPT_FINT:
1907 len += 9; /* length of "<integer>" */
1908 break;
1909 case OPT_DBL:
1910 case OPT_FDBL:
1911 len += 6; /* length of "<real>" */
1912 break;
1913 case OPT_STR:
1914 case OPT_FSTR:
1915 len += 8; /* length of "<string>" */
1916 break;
1917 }
1918 if( len>max ) max = len;
1919 }
1920 for(i=0; op[i].label; i++){
1921 switch( op[i].type ){
1922 case OPT_FLAG:
1923 case OPT_FFLAG:
1924 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1925 break;
1926 case OPT_INT:
1927 case OPT_FINT:
1928 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001929 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001930 break;
1931 case OPT_DBL:
1932 case OPT_FDBL:
1933 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001934 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001935 break;
1936 case OPT_STR:
1937 case OPT_FSTR:
1938 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001939 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001940 break;
1941 }
1942 }
1943}
1944/*********************** From the file "parse.c" ****************************/
1945/*
1946** Input file parser for the LEMON parser generator.
1947*/
1948
1949/* The state of the parser */
1950struct pstate {
1951 char *filename; /* Name of the input file */
1952 int tokenlineno; /* Linenumber at which current token starts */
1953 int errorcnt; /* Number of errors so far */
1954 char *tokenstart; /* Text of current token */
1955 struct lemon *gp; /* Global state vector */
1956 enum e_state {
1957 INITIALIZE,
1958 WAITING_FOR_DECL_OR_RULE,
1959 WAITING_FOR_DECL_KEYWORD,
1960 WAITING_FOR_DECL_ARG,
1961 WAITING_FOR_PRECEDENCE_SYMBOL,
1962 WAITING_FOR_ARROW,
1963 IN_RHS,
1964 LHS_ALIAS_1,
1965 LHS_ALIAS_2,
1966 LHS_ALIAS_3,
1967 RHS_ALIAS_1,
1968 RHS_ALIAS_2,
1969 PRECEDENCE_MARK_1,
1970 PRECEDENCE_MARK_2,
1971 RESYNC_AFTER_RULE_ERROR,
1972 RESYNC_AFTER_DECL_ERROR,
1973 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001974 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001975 WAITING_FOR_FALLBACK_ID,
1976 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001977 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001978 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001979 struct symbol *lhs; /* Left-hand side of current rule */
1980 char *lhsalias; /* Alias for the LHS */
1981 int nrhs; /* Number of right-hand side symbols seen */
1982 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1983 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1984 struct rule *prevrule; /* Previous rule parsed */
1985 char *declkeyword; /* Keyword of a declaration */
1986 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001987 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001988 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001989 enum e_assoc declassoc; /* Assign this association to decl arguments */
1990 int preccounter; /* Assign this precedence to decl arguments */
1991 struct rule *firstrule; /* Pointer to first rule in the grammar */
1992 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1993};
1994
1995/* Parse a single token */
1996static void parseonetoken(psp)
1997struct pstate *psp;
1998{
1999 char *x;
2000 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2001#if 0
2002 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2003 x,psp->state);
2004#endif
2005 switch( psp->state ){
2006 case INITIALIZE:
2007 psp->prevrule = 0;
2008 psp->preccounter = 0;
2009 psp->firstrule = psp->lastrule = 0;
2010 psp->gp->nrule = 0;
2011 /* Fall thru to next case */
2012 case WAITING_FOR_DECL_OR_RULE:
2013 if( x[0]=='%' ){
2014 psp->state = WAITING_FOR_DECL_KEYWORD;
2015 }else if( islower(x[0]) ){
2016 psp->lhs = Symbol_new(x);
2017 psp->nrhs = 0;
2018 psp->lhsalias = 0;
2019 psp->state = WAITING_FOR_ARROW;
2020 }else if( x[0]=='{' ){
2021 if( psp->prevrule==0 ){
2022 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002023"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002024fragment which begins on this line.");
2025 psp->errorcnt++;
2026 }else if( psp->prevrule->code!=0 ){
2027 ErrorMsg(psp->filename,psp->tokenlineno,
2028"Code fragment beginning on this line is not the first \
2029to follow the previous rule.");
2030 psp->errorcnt++;
2031 }else{
2032 psp->prevrule->line = psp->tokenlineno;
2033 psp->prevrule->code = &x[1];
2034 }
2035 }else if( x[0]=='[' ){
2036 psp->state = PRECEDENCE_MARK_1;
2037 }else{
2038 ErrorMsg(psp->filename,psp->tokenlineno,
2039 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2040 x);
2041 psp->errorcnt++;
2042 }
2043 break;
2044 case PRECEDENCE_MARK_1:
2045 if( !isupper(x[0]) ){
2046 ErrorMsg(psp->filename,psp->tokenlineno,
2047 "The precedence symbol must be a terminal.");
2048 psp->errorcnt++;
2049 }else if( psp->prevrule==0 ){
2050 ErrorMsg(psp->filename,psp->tokenlineno,
2051 "There is no prior rule to assign precedence \"[%s]\".",x);
2052 psp->errorcnt++;
2053 }else if( psp->prevrule->precsym!=0 ){
2054 ErrorMsg(psp->filename,psp->tokenlineno,
2055"Precedence mark on this line is not the first \
2056to follow the previous rule.");
2057 psp->errorcnt++;
2058 }else{
2059 psp->prevrule->precsym = Symbol_new(x);
2060 }
2061 psp->state = PRECEDENCE_MARK_2;
2062 break;
2063 case PRECEDENCE_MARK_2:
2064 if( x[0]!=']' ){
2065 ErrorMsg(psp->filename,psp->tokenlineno,
2066 "Missing \"]\" on precedence mark.");
2067 psp->errorcnt++;
2068 }
2069 psp->state = WAITING_FOR_DECL_OR_RULE;
2070 break;
2071 case WAITING_FOR_ARROW:
2072 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2073 psp->state = IN_RHS;
2074 }else if( x[0]=='(' ){
2075 psp->state = LHS_ALIAS_1;
2076 }else{
2077 ErrorMsg(psp->filename,psp->tokenlineno,
2078 "Expected to see a \":\" following the LHS symbol \"%s\".",
2079 psp->lhs->name);
2080 psp->errorcnt++;
2081 psp->state = RESYNC_AFTER_RULE_ERROR;
2082 }
2083 break;
2084 case LHS_ALIAS_1:
2085 if( isalpha(x[0]) ){
2086 psp->lhsalias = x;
2087 psp->state = LHS_ALIAS_2;
2088 }else{
2089 ErrorMsg(psp->filename,psp->tokenlineno,
2090 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2091 x,psp->lhs->name);
2092 psp->errorcnt++;
2093 psp->state = RESYNC_AFTER_RULE_ERROR;
2094 }
2095 break;
2096 case LHS_ALIAS_2:
2097 if( x[0]==')' ){
2098 psp->state = LHS_ALIAS_3;
2099 }else{
2100 ErrorMsg(psp->filename,psp->tokenlineno,
2101 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2102 psp->errorcnt++;
2103 psp->state = RESYNC_AFTER_RULE_ERROR;
2104 }
2105 break;
2106 case LHS_ALIAS_3:
2107 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2108 psp->state = IN_RHS;
2109 }else{
2110 ErrorMsg(psp->filename,psp->tokenlineno,
2111 "Missing \"->\" following: \"%s(%s)\".",
2112 psp->lhs->name,psp->lhsalias);
2113 psp->errorcnt++;
2114 psp->state = RESYNC_AFTER_RULE_ERROR;
2115 }
2116 break;
2117 case IN_RHS:
2118 if( x[0]=='.' ){
2119 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002120 rp = (struct rule *)calloc( sizeof(struct rule) +
2121 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002122 if( rp==0 ){
2123 ErrorMsg(psp->filename,psp->tokenlineno,
2124 "Can't allocate enough memory for this rule.");
2125 psp->errorcnt++;
2126 psp->prevrule = 0;
2127 }else{
2128 int i;
2129 rp->ruleline = psp->tokenlineno;
2130 rp->rhs = (struct symbol**)&rp[1];
2131 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2132 for(i=0; i<psp->nrhs; i++){
2133 rp->rhs[i] = psp->rhs[i];
2134 rp->rhsalias[i] = psp->alias[i];
2135 }
2136 rp->lhs = psp->lhs;
2137 rp->lhsalias = psp->lhsalias;
2138 rp->nrhs = psp->nrhs;
2139 rp->code = 0;
2140 rp->precsym = 0;
2141 rp->index = psp->gp->nrule++;
2142 rp->nextlhs = rp->lhs->rule;
2143 rp->lhs->rule = rp;
2144 rp->next = 0;
2145 if( psp->firstrule==0 ){
2146 psp->firstrule = psp->lastrule = rp;
2147 }else{
2148 psp->lastrule->next = rp;
2149 psp->lastrule = rp;
2150 }
2151 psp->prevrule = rp;
2152 }
2153 psp->state = WAITING_FOR_DECL_OR_RULE;
2154 }else if( isalpha(x[0]) ){
2155 if( psp->nrhs>=MAXRHS ){
2156 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002157 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002158 x);
2159 psp->errorcnt++;
2160 psp->state = RESYNC_AFTER_RULE_ERROR;
2161 }else{
2162 psp->rhs[psp->nrhs] = Symbol_new(x);
2163 psp->alias[psp->nrhs] = 0;
2164 psp->nrhs++;
2165 }
drhfd405312005-11-06 04:06:59 +00002166 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2167 struct symbol *msp = psp->rhs[psp->nrhs-1];
2168 if( msp->type!=MULTITERMINAL ){
2169 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002170 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002171 memset(msp, 0, sizeof(*msp));
2172 msp->type = MULTITERMINAL;
2173 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002174 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002175 msp->subsym[0] = origsp;
2176 msp->name = origsp->name;
2177 psp->rhs[psp->nrhs-1] = msp;
2178 }
2179 msp->nsubsym++;
2180 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2181 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2182 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2183 ErrorMsg(psp->filename,psp->tokenlineno,
2184 "Cannot form a compound containing a non-terminal");
2185 psp->errorcnt++;
2186 }
drh75897232000-05-29 14:26:00 +00002187 }else if( x[0]=='(' && psp->nrhs>0 ){
2188 psp->state = RHS_ALIAS_1;
2189 }else{
2190 ErrorMsg(psp->filename,psp->tokenlineno,
2191 "Illegal character on RHS of rule: \"%s\".",x);
2192 psp->errorcnt++;
2193 psp->state = RESYNC_AFTER_RULE_ERROR;
2194 }
2195 break;
2196 case RHS_ALIAS_1:
2197 if( isalpha(x[0]) ){
2198 psp->alias[psp->nrhs-1] = x;
2199 psp->state = RHS_ALIAS_2;
2200 }else{
2201 ErrorMsg(psp->filename,psp->tokenlineno,
2202 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2203 x,psp->rhs[psp->nrhs-1]->name);
2204 psp->errorcnt++;
2205 psp->state = RESYNC_AFTER_RULE_ERROR;
2206 }
2207 break;
2208 case RHS_ALIAS_2:
2209 if( x[0]==')' ){
2210 psp->state = IN_RHS;
2211 }else{
2212 ErrorMsg(psp->filename,psp->tokenlineno,
2213 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2214 psp->errorcnt++;
2215 psp->state = RESYNC_AFTER_RULE_ERROR;
2216 }
2217 break;
2218 case WAITING_FOR_DECL_KEYWORD:
2219 if( isalpha(x[0]) ){
2220 psp->declkeyword = x;
2221 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002222 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002223 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002224 psp->state = WAITING_FOR_DECL_ARG;
2225 if( strcmp(x,"name")==0 ){
2226 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002227 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002228 }else if( strcmp(x,"include")==0 ){
2229 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002230 }else if( strcmp(x,"code")==0 ){
2231 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002232 }else if( strcmp(x,"token_destructor")==0 ){
2233 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002234 }else if( strcmp(x,"default_destructor")==0 ){
2235 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002236 }else if( strcmp(x,"token_prefix")==0 ){
2237 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002238 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002239 }else if( strcmp(x,"syntax_error")==0 ){
2240 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002241 }else if( strcmp(x,"parse_accept")==0 ){
2242 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002243 }else if( strcmp(x,"parse_failure")==0 ){
2244 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002245 }else if( strcmp(x,"stack_overflow")==0 ){
2246 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002247 }else if( strcmp(x,"extra_argument")==0 ){
2248 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002249 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002250 }else if( strcmp(x,"token_type")==0 ){
2251 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002252 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002253 }else if( strcmp(x,"default_type")==0 ){
2254 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002255 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002256 }else if( strcmp(x,"stack_size")==0 ){
2257 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002258 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002259 }else if( strcmp(x,"start_symbol")==0 ){
2260 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002261 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002262 }else if( strcmp(x,"left")==0 ){
2263 psp->preccounter++;
2264 psp->declassoc = LEFT;
2265 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2266 }else if( strcmp(x,"right")==0 ){
2267 psp->preccounter++;
2268 psp->declassoc = RIGHT;
2269 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2270 }else if( strcmp(x,"nonassoc")==0 ){
2271 psp->preccounter++;
2272 psp->declassoc = NONE;
2273 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2274 }else if( strcmp(x,"destructor")==0 ){
2275 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2276 }else if( strcmp(x,"type")==0 ){
2277 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002278 }else if( strcmp(x,"fallback")==0 ){
2279 psp->fallback = 0;
2280 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002281 }else if( strcmp(x,"wildcard")==0 ){
2282 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002283 }else{
2284 ErrorMsg(psp->filename,psp->tokenlineno,
2285 "Unknown declaration keyword: \"%%%s\".",x);
2286 psp->errorcnt++;
2287 psp->state = RESYNC_AFTER_DECL_ERROR;
2288 }
2289 }else{
2290 ErrorMsg(psp->filename,psp->tokenlineno,
2291 "Illegal declaration keyword: \"%s\".",x);
2292 psp->errorcnt++;
2293 psp->state = RESYNC_AFTER_DECL_ERROR;
2294 }
2295 break;
2296 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2297 if( !isalpha(x[0]) ){
2298 ErrorMsg(psp->filename,psp->tokenlineno,
2299 "Symbol name missing after %destructor keyword");
2300 psp->errorcnt++;
2301 psp->state = RESYNC_AFTER_DECL_ERROR;
2302 }else{
2303 struct symbol *sp = Symbol_new(x);
2304 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002305 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002306 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002307 psp->state = WAITING_FOR_DECL_ARG;
2308 }
2309 break;
2310 case WAITING_FOR_DATATYPE_SYMBOL:
2311 if( !isalpha(x[0]) ){
2312 ErrorMsg(psp->filename,psp->tokenlineno,
2313 "Symbol name missing after %destructor keyword");
2314 psp->errorcnt++;
2315 psp->state = RESYNC_AFTER_DECL_ERROR;
2316 }else{
2317 struct symbol *sp = Symbol_new(x);
2318 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002319 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002320 psp->state = WAITING_FOR_DECL_ARG;
2321 }
2322 break;
2323 case WAITING_FOR_PRECEDENCE_SYMBOL:
2324 if( x[0]=='.' ){
2325 psp->state = WAITING_FOR_DECL_OR_RULE;
2326 }else if( isupper(x[0]) ){
2327 struct symbol *sp;
2328 sp = Symbol_new(x);
2329 if( sp->prec>=0 ){
2330 ErrorMsg(psp->filename,psp->tokenlineno,
2331 "Symbol \"%s\" has already be given a precedence.",x);
2332 psp->errorcnt++;
2333 }else{
2334 sp->prec = psp->preccounter;
2335 sp->assoc = psp->declassoc;
2336 }
2337 }else{
2338 ErrorMsg(psp->filename,psp->tokenlineno,
2339 "Can't assign a precedence to \"%s\".",x);
2340 psp->errorcnt++;
2341 }
2342 break;
2343 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002344 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2345 char *zOld, *zNew, *zBuf, *z;
2346 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002347 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002348 char zLine[50];
2349 zNew = x;
2350 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002351 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002352 if( *psp->declargslot ){
2353 zOld = *psp->declargslot;
2354 }else{
2355 zOld = "";
2356 }
drh87cf1372008-08-13 20:09:06 +00002357 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002358 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002359 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002360 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2361 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002362 for(z=psp->filename, nBack=0; *z; z++){
2363 if( *z=='\\' ) nBack++;
2364 }
2365 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002366 nLine = lemonStrlen(zLine);
2367 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002368 }
2369 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2370 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002371 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002372 if( nOld && zBuf[-1]!='\n' ){
2373 *(zBuf++) = '\n';
2374 }
2375 memcpy(zBuf, zLine, nLine);
2376 zBuf += nLine;
2377 *(zBuf++) = '"';
2378 for(z=psp->filename; *z; z++){
2379 if( *z=='\\' ){
2380 *(zBuf++) = '\\';
2381 }
2382 *(zBuf++) = *z;
2383 }
2384 *(zBuf++) = '"';
2385 *(zBuf++) = '\n';
2386 }
drh4dc8ef52008-07-01 17:13:57 +00002387 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2388 psp->decllinenoslot[0] = psp->tokenlineno;
2389 }
drha5808f32008-04-27 22:19:44 +00002390 memcpy(zBuf, zNew, nNew);
2391 zBuf += nNew;
2392 *zBuf = 0;
2393 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002394 }else{
2395 ErrorMsg(psp->filename,psp->tokenlineno,
2396 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2397 psp->errorcnt++;
2398 psp->state = RESYNC_AFTER_DECL_ERROR;
2399 }
2400 break;
drh0bd1f4e2002-06-06 18:54:39 +00002401 case WAITING_FOR_FALLBACK_ID:
2402 if( x[0]=='.' ){
2403 psp->state = WAITING_FOR_DECL_OR_RULE;
2404 }else if( !isupper(x[0]) ){
2405 ErrorMsg(psp->filename, psp->tokenlineno,
2406 "%%fallback argument \"%s\" should be a token", x);
2407 psp->errorcnt++;
2408 }else{
2409 struct symbol *sp = Symbol_new(x);
2410 if( psp->fallback==0 ){
2411 psp->fallback = sp;
2412 }else if( sp->fallback ){
2413 ErrorMsg(psp->filename, psp->tokenlineno,
2414 "More than one fallback assigned to token %s", x);
2415 psp->errorcnt++;
2416 }else{
2417 sp->fallback = psp->fallback;
2418 psp->gp->has_fallback = 1;
2419 }
2420 }
2421 break;
drhe09daa92006-06-10 13:29:31 +00002422 case WAITING_FOR_WILDCARD_ID:
2423 if( x[0]=='.' ){
2424 psp->state = WAITING_FOR_DECL_OR_RULE;
2425 }else if( !isupper(x[0]) ){
2426 ErrorMsg(psp->filename, psp->tokenlineno,
2427 "%%wildcard argument \"%s\" should be a token", x);
2428 psp->errorcnt++;
2429 }else{
2430 struct symbol *sp = Symbol_new(x);
2431 if( psp->gp->wildcard==0 ){
2432 psp->gp->wildcard = sp;
2433 }else{
2434 ErrorMsg(psp->filename, psp->tokenlineno,
2435 "Extra wildcard to token: %s", x);
2436 psp->errorcnt++;
2437 }
2438 }
2439 break;
drh75897232000-05-29 14:26:00 +00002440 case RESYNC_AFTER_RULE_ERROR:
2441/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2442** break; */
2443 case RESYNC_AFTER_DECL_ERROR:
2444 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2445 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2446 break;
2447 }
2448}
2449
drh34ff57b2008-07-14 12:27:51 +00002450/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002451** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2452** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2453** comments them out. Text in between is also commented out as appropriate.
2454*/
danielk1977940fac92005-01-23 22:41:37 +00002455static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002456 int i, j, k, n;
2457 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002458 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002459 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002460 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002461 for(i=0; z[i]; i++){
2462 if( z[i]=='\n' ) lineno++;
2463 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2464 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2465 if( exclude ){
2466 exclude--;
2467 if( exclude==0 ){
2468 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2469 }
2470 }
2471 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2472 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2473 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2474 if( exclude ){
2475 exclude++;
2476 }else{
2477 for(j=i+7; isspace(z[j]); j++){}
2478 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2479 exclude = 1;
2480 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002481 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002482 exclude = 0;
2483 break;
2484 }
2485 }
2486 if( z[i+3]=='n' ) exclude = !exclude;
2487 if( exclude ){
2488 start = i;
2489 start_lineno = lineno;
2490 }
2491 }
2492 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2493 }
2494 }
2495 if( exclude ){
2496 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2497 exit(1);
2498 }
2499}
2500
drh75897232000-05-29 14:26:00 +00002501/* In spite of its name, this function is really a scanner. It read
2502** in the entire input file (all at once) then tokenizes it. Each
2503** token is passed to the function "parseonetoken" which builds all
2504** the appropriate data structures in the global state vector "gp".
2505*/
2506void Parse(gp)
2507struct lemon *gp;
2508{
2509 struct pstate ps;
2510 FILE *fp;
2511 char *filebuf;
2512 int filesize;
2513 int lineno;
2514 int c;
2515 char *cp, *nextcp;
2516 int startline = 0;
2517
rse38514a92007-09-20 11:34:17 +00002518 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002519 ps.gp = gp;
2520 ps.filename = gp->filename;
2521 ps.errorcnt = 0;
2522 ps.state = INITIALIZE;
2523
2524 /* Begin by reading the input file */
2525 fp = fopen(ps.filename,"rb");
2526 if( fp==0 ){
2527 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2528 gp->errorcnt++;
2529 return;
2530 }
2531 fseek(fp,0,2);
2532 filesize = ftell(fp);
2533 rewind(fp);
2534 filebuf = (char *)malloc( filesize+1 );
2535 if( filebuf==0 ){
2536 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2537 filesize+1);
2538 gp->errorcnt++;
2539 return;
2540 }
2541 if( fread(filebuf,1,filesize,fp)!=filesize ){
2542 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2543 filesize);
2544 free(filebuf);
2545 gp->errorcnt++;
2546 return;
2547 }
2548 fclose(fp);
2549 filebuf[filesize] = 0;
2550
drh6d08b4d2004-07-20 12:45:22 +00002551 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2552 preprocess_input(filebuf);
2553
drh75897232000-05-29 14:26:00 +00002554 /* Now scan the text of the input file */
2555 lineno = 1;
2556 for(cp=filebuf; (c= *cp)!=0; ){
2557 if( c=='\n' ) lineno++; /* Keep track of the line number */
2558 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2559 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2560 cp+=2;
2561 while( (c= *cp)!=0 && c!='\n' ) cp++;
2562 continue;
2563 }
2564 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2565 cp+=2;
2566 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2567 if( c=='\n' ) lineno++;
2568 cp++;
2569 }
2570 if( c ) cp++;
2571 continue;
2572 }
2573 ps.tokenstart = cp; /* Mark the beginning of the token */
2574 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2575 if( c=='\"' ){ /* String literals */
2576 cp++;
2577 while( (c= *cp)!=0 && c!='\"' ){
2578 if( c=='\n' ) lineno++;
2579 cp++;
2580 }
2581 if( c==0 ){
2582 ErrorMsg(ps.filename,startline,
2583"String starting on this line is not terminated before the end of the file.");
2584 ps.errorcnt++;
2585 nextcp = cp;
2586 }else{
2587 nextcp = cp+1;
2588 }
2589 }else if( c=='{' ){ /* A block of C code */
2590 int level;
2591 cp++;
2592 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2593 if( c=='\n' ) lineno++;
2594 else if( c=='{' ) level++;
2595 else if( c=='}' ) level--;
2596 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2597 int prevc;
2598 cp = &cp[2];
2599 prevc = 0;
2600 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2601 if( c=='\n' ) lineno++;
2602 prevc = c;
2603 cp++;
2604 }
2605 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2606 cp = &cp[2];
2607 while( (c= *cp)!=0 && c!='\n' ) cp++;
2608 if( c ) lineno++;
2609 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2610 int startchar, prevc;
2611 startchar = c;
2612 prevc = 0;
2613 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2614 if( c=='\n' ) lineno++;
2615 if( prevc=='\\' ) prevc = 0;
2616 else prevc = c;
2617 }
2618 }
2619 }
2620 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002621 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002622"C code starting on this line is not terminated before the end of the file.");
2623 ps.errorcnt++;
2624 nextcp = cp;
2625 }else{
2626 nextcp = cp+1;
2627 }
2628 }else if( isalnum(c) ){ /* Identifiers */
2629 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2630 nextcp = cp;
2631 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2632 cp += 3;
2633 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002634 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2635 cp += 2;
2636 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2637 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002638 }else{ /* All other (one character) operators */
2639 cp++;
2640 nextcp = cp;
2641 }
2642 c = *cp;
2643 *cp = 0; /* Null terminate the token */
2644 parseonetoken(&ps); /* Parse the token */
2645 *cp = c; /* Restore the buffer */
2646 cp = nextcp;
2647 }
2648 free(filebuf); /* Release the buffer after parsing */
2649 gp->rule = ps.firstrule;
2650 gp->errorcnt = ps.errorcnt;
2651}
2652/*************************** From the file "plink.c" *********************/
2653/*
2654** Routines processing configuration follow-set propagation links
2655** in the LEMON parser generator.
2656*/
2657static struct plink *plink_freelist = 0;
2658
2659/* Allocate a new plink */
2660struct plink *Plink_new(){
2661 struct plink *new;
2662
2663 if( plink_freelist==0 ){
2664 int i;
2665 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002666 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002667 if( plink_freelist==0 ){
2668 fprintf(stderr,
2669 "Unable to allocate memory for a new follow-set propagation link.\n");
2670 exit(1);
2671 }
2672 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2673 plink_freelist[amt-1].next = 0;
2674 }
2675 new = plink_freelist;
2676 plink_freelist = plink_freelist->next;
2677 return new;
2678}
2679
2680/* Add a plink to a plink list */
2681void Plink_add(plpp,cfp)
2682struct plink **plpp;
2683struct config *cfp;
2684{
2685 struct plink *new;
2686 new = Plink_new();
2687 new->next = *plpp;
2688 *plpp = new;
2689 new->cfp = cfp;
2690}
2691
2692/* Transfer every plink on the list "from" to the list "to" */
2693void Plink_copy(to,from)
2694struct plink **to;
2695struct plink *from;
2696{
2697 struct plink *nextpl;
2698 while( from ){
2699 nextpl = from->next;
2700 from->next = *to;
2701 *to = from;
2702 from = nextpl;
2703 }
2704}
2705
2706/* Delete every plink on the list */
2707void Plink_delete(plp)
2708struct plink *plp;
2709{
2710 struct plink *nextpl;
2711
2712 while( plp ){
2713 nextpl = plp->next;
2714 plp->next = plink_freelist;
2715 plink_freelist = plp;
2716 plp = nextpl;
2717 }
2718}
2719/*********************** From the file "report.c" **************************/
2720/*
2721** Procedures for generating reports and tables in the LEMON parser generator.
2722*/
2723
2724/* Generate a filename with the given suffix. Space to hold the
2725** name comes from malloc() and must be freed by the calling
2726** function.
2727*/
2728PRIVATE char *file_makename(lemp,suffix)
2729struct lemon *lemp;
2730char *suffix;
2731{
2732 char *name;
2733 char *cp;
2734
drh87cf1372008-08-13 20:09:06 +00002735 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002736 if( name==0 ){
2737 fprintf(stderr,"Can't allocate space for a filename.\n");
2738 exit(1);
2739 }
2740 strcpy(name,lemp->filename);
2741 cp = strrchr(name,'.');
2742 if( cp ) *cp = 0;
2743 strcat(name,suffix);
2744 return name;
2745}
2746
2747/* Open a file with a name based on the name of the input file,
2748** but with a different (specified) suffix, and return a pointer
2749** to the stream */
2750PRIVATE FILE *file_open(lemp,suffix,mode)
2751struct lemon *lemp;
2752char *suffix;
2753char *mode;
2754{
2755 FILE *fp;
2756
2757 if( lemp->outname ) free(lemp->outname);
2758 lemp->outname = file_makename(lemp, suffix);
2759 fp = fopen(lemp->outname,mode);
2760 if( fp==0 && *mode=='w' ){
2761 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2762 lemp->errorcnt++;
2763 return 0;
2764 }
2765 return fp;
2766}
2767
2768/* Duplicate the input file without comments and without actions
2769** on rules */
2770void Reprint(lemp)
2771struct lemon *lemp;
2772{
2773 struct rule *rp;
2774 struct symbol *sp;
2775 int i, j, maxlen, len, ncolumns, skip;
2776 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2777 maxlen = 10;
2778 for(i=0; i<lemp->nsymbol; i++){
2779 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002780 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002781 if( len>maxlen ) maxlen = len;
2782 }
2783 ncolumns = 76/(maxlen+5);
2784 if( ncolumns<1 ) ncolumns = 1;
2785 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2786 for(i=0; i<skip; i++){
2787 printf("//");
2788 for(j=i; j<lemp->nsymbol; j+=skip){
2789 sp = lemp->symbols[j];
2790 assert( sp->index==j );
2791 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2792 }
2793 printf("\n");
2794 }
2795 for(rp=lemp->rule; rp; rp=rp->next){
2796 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002797 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002798 printf(" ::=");
2799 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002800 sp = rp->rhs[i];
2801 printf(" %s", sp->name);
2802 if( sp->type==MULTITERMINAL ){
2803 for(j=1; j<sp->nsubsym; j++){
2804 printf("|%s", sp->subsym[j]->name);
2805 }
2806 }
2807 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002808 }
2809 printf(".");
2810 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002811 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002812 printf("\n");
2813 }
2814}
2815
2816void ConfigPrint(fp,cfp)
2817FILE *fp;
2818struct config *cfp;
2819{
2820 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002821 struct symbol *sp;
2822 int i, j;
drh75897232000-05-29 14:26:00 +00002823 rp = cfp->rp;
2824 fprintf(fp,"%s ::=",rp->lhs->name);
2825 for(i=0; i<=rp->nrhs; i++){
2826 if( i==cfp->dot ) fprintf(fp," *");
2827 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002828 sp = rp->rhs[i];
2829 fprintf(fp," %s", sp->name);
2830 if( sp->type==MULTITERMINAL ){
2831 for(j=1; j<sp->nsubsym; j++){
2832 fprintf(fp,"|%s",sp->subsym[j]->name);
2833 }
2834 }
drh75897232000-05-29 14:26:00 +00002835 }
2836}
2837
2838/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002839#if 0
drh75897232000-05-29 14:26:00 +00002840/* Print a set */
2841PRIVATE void SetPrint(out,set,lemp)
2842FILE *out;
2843char *set;
2844struct lemon *lemp;
2845{
2846 int i;
2847 char *spacer;
2848 spacer = "";
2849 fprintf(out,"%12s[","");
2850 for(i=0; i<lemp->nterminal; i++){
2851 if( SetFind(set,i) ){
2852 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2853 spacer = " ";
2854 }
2855 }
2856 fprintf(out,"]\n");
2857}
2858
2859/* Print a plink chain */
2860PRIVATE void PlinkPrint(out,plp,tag)
2861FILE *out;
2862struct plink *plp;
2863char *tag;
2864{
2865 while( plp ){
drhada354d2005-11-05 15:03:59 +00002866 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002867 ConfigPrint(out,plp->cfp);
2868 fprintf(out,"\n");
2869 plp = plp->next;
2870 }
2871}
2872#endif
2873
2874/* Print an action to the given file descriptor. Return FALSE if
2875** nothing was actually printed.
2876*/
2877int PrintAction(struct action *ap, FILE *fp, int indent){
2878 int result = 1;
2879 switch( ap->type ){
2880 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002881 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002882 break;
2883 case REDUCE:
2884 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2885 break;
2886 case ACCEPT:
2887 fprintf(fp,"%*s accept",indent,ap->sp->name);
2888 break;
2889 case ERROR:
2890 fprintf(fp,"%*s error",indent,ap->sp->name);
2891 break;
drh9892c5d2007-12-21 00:02:11 +00002892 case SRCONFLICT:
2893 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002894 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2895 indent,ap->sp->name,ap->x.rp->index);
2896 break;
drh9892c5d2007-12-21 00:02:11 +00002897 case SSCONFLICT:
2898 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2899 indent,ap->sp->name,ap->x.stp->statenum);
2900 break;
drh75897232000-05-29 14:26:00 +00002901 case SH_RESOLVED:
2902 case RD_RESOLVED:
2903 case NOT_USED:
2904 result = 0;
2905 break;
2906 }
2907 return result;
2908}
2909
2910/* Generate the "y.output" log file */
2911void ReportOutput(lemp)
2912struct lemon *lemp;
2913{
2914 int i;
2915 struct state *stp;
2916 struct config *cfp;
2917 struct action *ap;
2918 FILE *fp;
2919
drh2aa6ca42004-09-10 00:14:04 +00002920 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002921 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002922 for(i=0; i<lemp->nstate; i++){
2923 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002924 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002925 if( lemp->basisflag ) cfp=stp->bp;
2926 else cfp=stp->cfp;
2927 while( cfp ){
2928 char buf[20];
2929 if( cfp->dot==cfp->rp->nrhs ){
2930 sprintf(buf,"(%d)",cfp->rp->index);
2931 fprintf(fp," %5s ",buf);
2932 }else{
2933 fprintf(fp," ");
2934 }
2935 ConfigPrint(fp,cfp);
2936 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002937#if 0
drh75897232000-05-29 14:26:00 +00002938 SetPrint(fp,cfp->fws,lemp);
2939 PlinkPrint(fp,cfp->fplp,"To ");
2940 PlinkPrint(fp,cfp->bplp,"From");
2941#endif
2942 if( lemp->basisflag ) cfp=cfp->bp;
2943 else cfp=cfp->next;
2944 }
2945 fprintf(fp,"\n");
2946 for(ap=stp->ap; ap; ap=ap->next){
2947 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2948 }
2949 fprintf(fp,"\n");
2950 }
drhe9278182007-07-18 18:16:29 +00002951 fprintf(fp, "----------------------------------------------------\n");
2952 fprintf(fp, "Symbols:\n");
2953 for(i=0; i<lemp->nsymbol; i++){
2954 int j;
2955 struct symbol *sp;
2956
2957 sp = lemp->symbols[i];
2958 fprintf(fp, " %3d: %s", i, sp->name);
2959 if( sp->type==NONTERMINAL ){
2960 fprintf(fp, ":");
2961 if( sp->lambda ){
2962 fprintf(fp, " <lambda>");
2963 }
2964 for(j=0; j<lemp->nterminal; j++){
2965 if( sp->firstset && SetFind(sp->firstset, j) ){
2966 fprintf(fp, " %s", lemp->symbols[j]->name);
2967 }
2968 }
2969 }
2970 fprintf(fp, "\n");
2971 }
drh75897232000-05-29 14:26:00 +00002972 fclose(fp);
2973 return;
2974}
2975
2976/* Search for the file "name" which is in the same directory as
2977** the exacutable */
2978PRIVATE char *pathsearch(argv0,name,modemask)
2979char *argv0;
2980char *name;
2981int modemask;
2982{
2983 char *pathlist;
2984 char *path,*cp;
2985 char c;
drh75897232000-05-29 14:26:00 +00002986
2987#ifdef __WIN32__
2988 cp = strrchr(argv0,'\\');
2989#else
2990 cp = strrchr(argv0,'/');
2991#endif
2992 if( cp ){
2993 c = *cp;
2994 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00002995 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00002996 if( path ) sprintf(path,"%s/%s",argv0,name);
2997 *cp = c;
2998 }else{
2999 extern char *getenv();
3000 pathlist = getenv("PATH");
3001 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00003002 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00003003 if( path!=0 ){
3004 while( *pathlist ){
3005 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00003006 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00003007 c = *cp;
3008 *cp = 0;
3009 sprintf(path,"%s/%s",pathlist,name);
3010 *cp = c;
3011 if( c==0 ) pathlist = "";
3012 else pathlist = &cp[1];
3013 if( access(path,modemask)==0 ) break;
3014 }
3015 }
3016 }
3017 return path;
3018}
3019
3020/* Given an action, compute the integer value for that action
3021** which is to be put in the action table of the generated machine.
3022** Return negative if no action should be generated.
3023*/
3024PRIVATE int compute_action(lemp,ap)
3025struct lemon *lemp;
3026struct action *ap;
3027{
3028 int act;
3029 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003030 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003031 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3032 case ERROR: act = lemp->nstate + lemp->nrule; break;
3033 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3034 default: act = -1; break;
3035 }
3036 return act;
3037}
3038
3039#define LINESIZE 1000
3040/* The next cluster of routines are for reading the template file
3041** and writing the results to the generated parser */
3042/* The first function transfers data from "in" to "out" until
3043** a line is seen which begins with "%%". The line number is
3044** tracked.
3045**
3046** if name!=0, then any word that begin with "Parse" is changed to
3047** begin with *name instead.
3048*/
3049PRIVATE void tplt_xfer(name,in,out,lineno)
3050char *name;
3051FILE *in;
3052FILE *out;
3053int *lineno;
3054{
3055 int i, iStart;
3056 char line[LINESIZE];
3057 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3058 (*lineno)++;
3059 iStart = 0;
3060 if( name ){
3061 for(i=0; line[i]; i++){
3062 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3063 && (i==0 || !isalpha(line[i-1]))
3064 ){
3065 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3066 fprintf(out,"%s",name);
3067 i += 4;
3068 iStart = i+1;
3069 }
3070 }
3071 }
3072 fprintf(out,"%s",&line[iStart]);
3073 }
3074}
3075
3076/* The next function finds the template file and opens it, returning
3077** a pointer to the opened file. */
3078PRIVATE FILE *tplt_open(lemp)
3079struct lemon *lemp;
3080{
3081 static char templatename[] = "lempar.c";
3082 char buf[1000];
3083 FILE *in;
3084 char *tpltname;
3085 char *cp;
3086
3087 cp = strrchr(lemp->filename,'.');
3088 if( cp ){
drh8b582012003-10-21 13:16:03 +00003089 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003090 }else{
3091 sprintf(buf,"%s.lt",lemp->filename);
3092 }
3093 if( access(buf,004)==0 ){
3094 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003095 }else if( access(templatename,004)==0 ){
3096 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003097 }else{
3098 tpltname = pathsearch(lemp->argv0,templatename,0);
3099 }
3100 if( tpltname==0 ){
3101 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3102 templatename);
3103 lemp->errorcnt++;
3104 return 0;
3105 }
drh2aa6ca42004-09-10 00:14:04 +00003106 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003107 if( in==0 ){
3108 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3109 lemp->errorcnt++;
3110 return 0;
3111 }
3112 return in;
3113}
3114
drhaf805ca2004-09-07 11:28:25 +00003115/* Print a #line directive line to the output file. */
3116PRIVATE void tplt_linedir(out,lineno,filename)
3117FILE *out;
3118int lineno;
3119char *filename;
3120{
3121 fprintf(out,"#line %d \"",lineno);
3122 while( *filename ){
3123 if( *filename == '\\' ) putc('\\',out);
3124 putc(*filename,out);
3125 filename++;
3126 }
3127 fprintf(out,"\"\n");
3128}
3129
drh75897232000-05-29 14:26:00 +00003130/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003131PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003132FILE *out;
3133struct lemon *lemp;
3134char *str;
drh75897232000-05-29 14:26:00 +00003135int *lineno;
3136{
3137 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003138 while( *str ){
drh75897232000-05-29 14:26:00 +00003139 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003140 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003141 str++;
3142 }
drh9db55df2004-09-09 14:01:21 +00003143 if( str[-1]!='\n' ){
3144 putc('\n',out);
3145 (*lineno)++;
3146 }
shane58543932008-12-10 20:10:04 +00003147 if (!lemp->nolinenosflag) {
3148 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3149 }
drh75897232000-05-29 14:26:00 +00003150 return;
3151}
3152
3153/*
3154** The following routine emits code for the destructor for the
3155** symbol sp
3156*/
3157void emit_destructor_code(out,sp,lemp,lineno)
3158FILE *out;
3159struct symbol *sp;
3160struct lemon *lemp;
3161int *lineno;
3162{
drhcc83b6e2004-04-23 23:38:42 +00003163 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003164
drh75897232000-05-29 14:26:00 +00003165 if( sp->type==TERMINAL ){
3166 cp = lemp->tokendest;
3167 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003168 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003169 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003170 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003171 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003172 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003173 }else if( lemp->vardest ){
3174 cp = lemp->vardest;
3175 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003176 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003177 }else{
3178 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003179 }
3180 for(; *cp; cp++){
3181 if( *cp=='$' && cp[1]=='$' ){
3182 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3183 cp++;
3184 continue;
3185 }
shane58543932008-12-10 20:10:04 +00003186 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003187 fputc(*cp,out);
3188 }
shane58543932008-12-10 20:10:04 +00003189 fprintf(out,"\n"); (*lineno)++;
3190 if (!lemp->nolinenosflag) {
3191 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3192 }
3193 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003194 return;
3195}
3196
3197/*
drh960e8c62001-04-03 16:53:21 +00003198** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003199*/
3200int has_destructor(sp, lemp)
3201struct symbol *sp;
3202struct lemon *lemp;
3203{
3204 int ret;
3205 if( sp->type==TERMINAL ){
3206 ret = lemp->tokendest!=0;
3207 }else{
drh960e8c62001-04-03 16:53:21 +00003208 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003209 }
3210 return ret;
3211}
3212
drh0bb132b2004-07-20 14:06:51 +00003213/*
3214** Append text to a dynamically allocated string. If zText is 0 then
3215** reset the string to be empty again. Always return the complete text
3216** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003217**
3218** n bytes of zText are stored. If n==0 then all of zText up to the first
3219** \000 terminator is stored. zText can contain up to two instances of
3220** %d. The values of p1 and p2 are written into the first and second
3221** %d.
3222**
3223** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003224*/
3225PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3226 static char *z = 0;
3227 static int alloced = 0;
3228 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003229 int c;
drh0bb132b2004-07-20 14:06:51 +00003230 char zInt[40];
3231
3232 if( zText==0 ){
3233 used = 0;
3234 return z;
3235 }
drh7ac25c72004-08-19 15:12:26 +00003236 if( n<=0 ){
3237 if( n<0 ){
3238 used += n;
3239 assert( used>=0 );
3240 }
drh87cf1372008-08-13 20:09:06 +00003241 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003242 }
drh0bb132b2004-07-20 14:06:51 +00003243 if( n+sizeof(zInt)*2+used >= alloced ){
3244 alloced = n + sizeof(zInt)*2 + used + 200;
3245 z = realloc(z, alloced);
3246 }
3247 if( z==0 ) return "";
3248 while( n-- > 0 ){
3249 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003250 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003251 sprintf(zInt, "%d", p1);
3252 p1 = p2;
3253 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003254 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003255 zText++;
3256 n--;
3257 }else{
3258 z[used++] = c;
3259 }
3260 }
3261 z[used] = 0;
3262 return z;
3263}
3264
3265/*
3266** zCode is a string that is the action associated with a rule. Expand
3267** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003268** stack.
drh0bb132b2004-07-20 14:06:51 +00003269*/
drhaf805ca2004-09-07 11:28:25 +00003270PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003271 char *cp, *xp;
3272 int i;
3273 char lhsused = 0; /* True if the LHS element has been used */
3274 char used[MAXRHS]; /* True for each RHS element which is used */
3275
3276 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3277 lhsused = 0;
3278
drh19c9e562007-03-29 20:13:53 +00003279 if( rp->code==0 ){
3280 rp->code = "\n";
3281 rp->line = rp->ruleline;
3282 }
3283
drh0bb132b2004-07-20 14:06:51 +00003284 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003285 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003286 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3287 char saved;
3288 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3289 saved = *xp;
3290 *xp = 0;
3291 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003292 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003293 cp = xp;
3294 lhsused = 1;
3295 }else{
3296 for(i=0; i<rp->nrhs; i++){
3297 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003298 if( cp!=rp->code && cp[-1]=='@' ){
3299 /* If the argument is of the form @X then substituted
3300 ** the token number of X, not the value of X */
3301 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3302 }else{
drhfd405312005-11-06 04:06:59 +00003303 struct symbol *sp = rp->rhs[i];
3304 int dtnum;
3305 if( sp->type==MULTITERMINAL ){
3306 dtnum = sp->subsym[0]->dtnum;
3307 }else{
3308 dtnum = sp->dtnum;
3309 }
3310 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003311 }
drh0bb132b2004-07-20 14:06:51 +00003312 cp = xp;
3313 used[i] = 1;
3314 break;
3315 }
3316 }
3317 }
3318 *xp = saved;
3319 }
3320 append_str(cp, 1, 0, 0);
3321 } /* End loop */
3322
3323 /* Check to make sure the LHS has been used */
3324 if( rp->lhsalias && !lhsused ){
3325 ErrorMsg(lemp->filename,rp->ruleline,
3326 "Label \"%s\" for \"%s(%s)\" is never used.",
3327 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3328 lemp->errorcnt++;
3329 }
3330
3331 /* Generate destructor code for RHS symbols which are not used in the
3332 ** reduce code */
3333 for(i=0; i<rp->nrhs; i++){
3334 if( rp->rhsalias[i] && !used[i] ){
3335 ErrorMsg(lemp->filename,rp->ruleline,
3336 "Label %s for \"%s(%s)\" is never used.",
3337 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3338 lemp->errorcnt++;
3339 }else if( rp->rhsalias[i]==0 ){
3340 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003341 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003342 rp->rhs[i]->index,i-rp->nrhs+1);
3343 }else{
3344 /* No destructor defined for this term */
3345 }
3346 }
3347 }
drh61e339a2007-01-16 03:09:02 +00003348 if( rp->code ){
3349 cp = append_str(0,0,0,0);
3350 rp->code = Strsafe(cp?cp:"");
3351 }
drh0bb132b2004-07-20 14:06:51 +00003352}
3353
drh75897232000-05-29 14:26:00 +00003354/*
3355** Generate code which executes when the rule "rp" is reduced. Write
3356** the code to "out". Make sure lineno stays up-to-date.
3357*/
3358PRIVATE void emit_code(out,rp,lemp,lineno)
3359FILE *out;
3360struct rule *rp;
3361struct lemon *lemp;
3362int *lineno;
3363{
drh0bb132b2004-07-20 14:06:51 +00003364 char *cp;
drh75897232000-05-29 14:26:00 +00003365
3366 /* Generate code to do the reduce action */
3367 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003368 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003369 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003370 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003371 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003372 } /* End loop */
shane58543932008-12-10 20:10:04 +00003373 fprintf(out,"}\n"); (*lineno)++;
3374 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003375 } /* End if( rp->code ) */
3376
drh75897232000-05-29 14:26:00 +00003377 return;
3378}
3379
3380/*
3381** Print the definition of the union used for the parser's data stack.
3382** This union contains fields for every possible data type for tokens
3383** and nonterminals. In the process of computing and printing this
3384** union, also set the ".dtnum" field of every terminal and nonterminal
3385** symbol.
3386*/
3387void print_stack_union(out,lemp,plineno,mhflag)
3388FILE *out; /* The output stream */
3389struct lemon *lemp; /* The main info structure for this parser */
3390int *plineno; /* Pointer to the line number */
3391int mhflag; /* True if generating makeheaders output */
3392{
3393 int lineno = *plineno; /* The line number of the output */
3394 char **types; /* A hash table of datatypes */
3395 int arraysize; /* Size of the "types" array */
3396 int maxdtlength; /* Maximum length of any ".datatype" field. */
3397 char *stddt; /* Standardized name for a datatype */
3398 int i,j; /* Loop counters */
3399 int hash; /* For hashing the name of a type */
3400 char *name; /* Name of the parser */
3401
3402 /* Allocate and initialize types[] and allocate stddt[] */
3403 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003404 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003405 for(i=0; i<arraysize; i++) types[i] = 0;
3406 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003407 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003408 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003409 }
drh75897232000-05-29 14:26:00 +00003410 for(i=0; i<lemp->nsymbol; i++){
3411 int len;
3412 struct symbol *sp = lemp->symbols[i];
3413 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003414 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003415 if( len>maxdtlength ) maxdtlength = len;
3416 }
3417 stddt = (char*)malloc( maxdtlength*2 + 1 );
3418 if( types==0 || stddt==0 ){
3419 fprintf(stderr,"Out of memory.\n");
3420 exit(1);
3421 }
3422
3423 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3424 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003425 ** used for terminal symbols. If there is no %default_type defined then
3426 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3427 ** a datatype using the %type directive.
3428 */
drh75897232000-05-29 14:26:00 +00003429 for(i=0; i<lemp->nsymbol; i++){
3430 struct symbol *sp = lemp->symbols[i];
3431 char *cp;
3432 if( sp==lemp->errsym ){
3433 sp->dtnum = arraysize+1;
3434 continue;
3435 }
drh960e8c62001-04-03 16:53:21 +00003436 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003437 sp->dtnum = 0;
3438 continue;
3439 }
3440 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003441 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003442 j = 0;
3443 while( isspace(*cp) ) cp++;
3444 while( *cp ) stddt[j++] = *cp++;
3445 while( j>0 && isspace(stddt[j-1]) ) j--;
3446 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003447 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003448 sp->dtnum = 0;
3449 continue;
3450 }
drh75897232000-05-29 14:26:00 +00003451 hash = 0;
3452 for(j=0; stddt[j]; j++){
3453 hash = hash*53 + stddt[j];
3454 }
drh3b2129c2003-05-13 00:34:21 +00003455 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003456 while( types[hash] ){
3457 if( strcmp(types[hash],stddt)==0 ){
3458 sp->dtnum = hash + 1;
3459 break;
3460 }
3461 hash++;
3462 if( hash>=arraysize ) hash = 0;
3463 }
3464 if( types[hash]==0 ){
3465 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003466 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003467 if( types[hash]==0 ){
3468 fprintf(stderr,"Out of memory.\n");
3469 exit(1);
3470 }
3471 strcpy(types[hash],stddt);
3472 }
3473 }
3474
3475 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3476 name = lemp->name ? lemp->name : "Parse";
3477 lineno = *plineno;
3478 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3479 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3480 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3481 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3482 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003483 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003484 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3485 for(i=0; i<arraysize; i++){
3486 if( types[i]==0 ) continue;
3487 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3488 free(types[i]);
3489 }
drhc4dd3fd2008-01-22 01:48:05 +00003490 if( lemp->errsym->useCnt ){
3491 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3492 }
drh75897232000-05-29 14:26:00 +00003493 free(stddt);
3494 free(types);
3495 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3496 *plineno = lineno;
3497}
3498
drhb29b0a52002-02-23 19:39:46 +00003499/*
3500** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003501** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003502*/
drh8b582012003-10-21 13:16:03 +00003503static const char *minimum_size_type(int lwr, int upr){
3504 if( lwr>=0 ){
3505 if( upr<=255 ){
3506 return "unsigned char";
3507 }else if( upr<65535 ){
3508 return "unsigned short int";
3509 }else{
3510 return "unsigned int";
3511 }
3512 }else if( lwr>=-127 && upr<=127 ){
3513 return "signed char";
3514 }else if( lwr>=-32767 && upr<32767 ){
3515 return "short";
drhb29b0a52002-02-23 19:39:46 +00003516 }else{
drh8b582012003-10-21 13:16:03 +00003517 return "int";
drhb29b0a52002-02-23 19:39:46 +00003518 }
3519}
3520
drhfdbf9282003-10-21 16:34:41 +00003521/*
3522** Each state contains a set of token transaction and a set of
3523** nonterminal transactions. Each of these sets makes an instance
3524** of the following structure. An array of these structures is used
3525** to order the creation of entries in the yy_action[] table.
3526*/
3527struct axset {
3528 struct state *stp; /* A pointer to a state */
3529 int isTkn; /* True to use tokens. False for non-terminals */
3530 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003531 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003532};
3533
3534/*
3535** Compare to axset structures for sorting purposes
3536*/
3537static int axset_compare(const void *a, const void *b){
3538 struct axset *p1 = (struct axset*)a;
3539 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003540 int c;
3541 c = p2->nAction - p1->nAction;
3542 if( c==0 ){
3543 c = p2->iOrder - p1->iOrder;
3544 }
3545 assert( c!=0 || p1==p2 );
3546 return c;
drhfdbf9282003-10-21 16:34:41 +00003547}
3548
drhc4dd3fd2008-01-22 01:48:05 +00003549/*
3550** Write text on "out" that describes the rule "rp".
3551*/
3552static void writeRuleText(FILE *out, struct rule *rp){
3553 int j;
3554 fprintf(out,"%s ::=", rp->lhs->name);
3555 for(j=0; j<rp->nrhs; j++){
3556 struct symbol *sp = rp->rhs[j];
3557 fprintf(out," %s", sp->name);
3558 if( sp->type==MULTITERMINAL ){
3559 int k;
3560 for(k=1; k<sp->nsubsym; k++){
3561 fprintf(out,"|%s",sp->subsym[k]->name);
3562 }
3563 }
3564 }
3565}
3566
3567
drh75897232000-05-29 14:26:00 +00003568/* Generate C source code for the parser */
3569void ReportTable(lemp, mhflag)
3570struct lemon *lemp;
3571int mhflag; /* Output in makeheaders format if true */
3572{
3573 FILE *out, *in;
3574 char line[LINESIZE];
3575 int lineno;
3576 struct state *stp;
3577 struct action *ap;
3578 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003579 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003580 int i, j, k, n;
drh75897232000-05-29 14:26:00 +00003581 char *name;
drh8b582012003-10-21 13:16:03 +00003582 int mnTknOfst, mxTknOfst;
3583 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003584 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003585
3586 in = tplt_open(lemp);
3587 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003588 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003589 if( out==0 ){
3590 fclose(in);
3591 return;
3592 }
3593 lineno = 1;
3594 tplt_xfer(lemp->name,in,out,&lineno);
3595
3596 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003597 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003598 if( mhflag ){
3599 char *name = file_makename(lemp, ".h");
3600 fprintf(out,"#include \"%s\"\n", name); lineno++;
3601 free(name);
3602 }
3603 tplt_xfer(lemp->name,in,out,&lineno);
3604
3605 /* Generate #defines for all tokens */
3606 if( mhflag ){
3607 char *prefix;
3608 fprintf(out,"#if INTERFACE\n"); lineno++;
3609 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3610 else prefix = "";
3611 for(i=1; i<lemp->nterminal; i++){
3612 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3613 lineno++;
3614 }
3615 fprintf(out,"#endif\n"); lineno++;
3616 }
3617 tplt_xfer(lemp->name,in,out,&lineno);
3618
3619 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003620 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003621 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003622 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3623 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003624 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003625 if( lemp->wildcard ){
3626 fprintf(out,"#define YYWILDCARD %d\n",
3627 lemp->wildcard->index); lineno++;
3628 }
drh75897232000-05-29 14:26:00 +00003629 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003630 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003631 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003632 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3633 }else{
3634 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3635 }
drhca44b5a2007-02-22 23:06:58 +00003636 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003637 if( mhflag ){
3638 fprintf(out,"#if INTERFACE\n"); lineno++;
3639 }
3640 name = lemp->name ? lemp->name : "Parse";
3641 if( lemp->arg && lemp->arg[0] ){
3642 int i;
drh87cf1372008-08-13 20:09:06 +00003643 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003644 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3645 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003646 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3647 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3648 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3649 name,lemp->arg,&lemp->arg[i]); lineno++;
3650 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3651 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003652 }else{
drh1f245e42002-03-11 13:55:50 +00003653 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3654 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3655 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3656 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003657 }
3658 if( mhflag ){
3659 fprintf(out,"#endif\n"); lineno++;
3660 }
3661 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3662 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003663 if( lemp->errsym->useCnt ){
3664 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3665 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3666 }
drh0bd1f4e2002-06-06 18:54:39 +00003667 if( lemp->has_fallback ){
3668 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3669 }
drh75897232000-05-29 14:26:00 +00003670 tplt_xfer(lemp->name,in,out,&lineno);
3671
drh8b582012003-10-21 13:16:03 +00003672 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003673 **
drh8b582012003-10-21 13:16:03 +00003674 ** yy_action[] A single table containing all actions.
3675 ** yy_lookahead[] A table containing the lookahead for each entry in
3676 ** yy_action. Used to detect hash collisions.
3677 ** yy_shift_ofst[] For each state, the offset into yy_action for
3678 ** shifting terminals.
3679 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3680 ** shifting non-terminals after a reduce.
3681 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003682 */
drh75897232000-05-29 14:26:00 +00003683
drh8b582012003-10-21 13:16:03 +00003684 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003685 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003686 if( ax==0 ){
3687 fprintf(stderr,"malloc failed\n");
3688 exit(1);
3689 }
drh75897232000-05-29 14:26:00 +00003690 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003691 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003692 ax[i*2].stp = stp;
3693 ax[i*2].isTkn = 1;
3694 ax[i*2].nAction = stp->nTknAct;
3695 ax[i*2+1].stp = stp;
3696 ax[i*2+1].isTkn = 0;
3697 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003698 }
drh8b582012003-10-21 13:16:03 +00003699 mxTknOfst = mnTknOfst = 0;
3700 mxNtOfst = mnNtOfst = 0;
3701
drhfdbf9282003-10-21 16:34:41 +00003702 /* Compute the action table. In order to try to keep the size of the
3703 ** action table to a minimum, the heuristic of placing the largest action
3704 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003705 */
drhe594bc32009-11-03 13:02:25 +00003706 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003707 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003708 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003709 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3710 stp = ax[i].stp;
3711 if( ax[i].isTkn ){
3712 for(ap=stp->ap; ap; ap=ap->next){
3713 int action;
3714 if( ap->sp->index>=lemp->nterminal ) continue;
3715 action = compute_action(lemp, ap);
3716 if( action<0 ) continue;
3717 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003718 }
drhfdbf9282003-10-21 16:34:41 +00003719 stp->iTknOfst = acttab_insert(pActtab);
3720 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3721 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3722 }else{
3723 for(ap=stp->ap; ap; ap=ap->next){
3724 int action;
3725 if( ap->sp->index<lemp->nterminal ) continue;
3726 if( ap->sp->index==lemp->nsymbol ) continue;
3727 action = compute_action(lemp, ap);
3728 if( action<0 ) continue;
3729 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003730 }
drhfdbf9282003-10-21 16:34:41 +00003731 stp->iNtOfst = acttab_insert(pActtab);
3732 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3733 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003734 }
3735 }
drhfdbf9282003-10-21 16:34:41 +00003736 free(ax);
drh8b582012003-10-21 13:16:03 +00003737
3738 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003739 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003740 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3741 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003742 for(i=j=0; i<n; i++){
3743 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003744 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003745 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003746 fprintf(out, " %4d,", action);
3747 if( j==9 || i==n-1 ){
3748 fprintf(out, "\n"); lineno++;
3749 j = 0;
3750 }else{
3751 j++;
3752 }
3753 }
3754 fprintf(out, "};\n"); lineno++;
3755
3756 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003757 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003758 for(i=j=0; i<n; i++){
3759 int la = acttab_yylookahead(pActtab, i);
3760 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003761 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003762 fprintf(out, " %4d,", la);
3763 if( j==9 || i==n-1 ){
3764 fprintf(out, "\n"); lineno++;
3765 j = 0;
3766 }else{
3767 j++;
3768 }
3769 }
3770 fprintf(out, "};\n"); lineno++;
3771
3772 /* Output the yy_shift_ofst[] table */
3773 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003774 n = lemp->nstate;
3775 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003776 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3777 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3778 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003779 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003780 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003781 for(i=j=0; i<n; i++){
3782 int ofst;
3783 stp = lemp->sorted[i];
3784 ofst = stp->iTknOfst;
3785 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003786 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003787 fprintf(out, " %4d,", ofst);
3788 if( j==9 || i==n-1 ){
3789 fprintf(out, "\n"); lineno++;
3790 j = 0;
3791 }else{
3792 j++;
3793 }
3794 }
3795 fprintf(out, "};\n"); lineno++;
3796
3797 /* Output the yy_reduce_ofst[] table */
3798 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003799 n = lemp->nstate;
3800 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003801 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3802 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3803 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003804 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003805 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003806 for(i=j=0; i<n; i++){
3807 int ofst;
3808 stp = lemp->sorted[i];
3809 ofst = stp->iNtOfst;
3810 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003811 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003812 fprintf(out, " %4d,", ofst);
3813 if( j==9 || i==n-1 ){
3814 fprintf(out, "\n"); lineno++;
3815 j = 0;
3816 }else{
3817 j++;
3818 }
3819 }
3820 fprintf(out, "};\n"); lineno++;
3821
3822 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003823 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003824 n = lemp->nstate;
3825 for(i=j=0; i<n; i++){
3826 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003827 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003828 fprintf(out, " %4d,", stp->iDflt);
3829 if( j==9 || i==n-1 ){
3830 fprintf(out, "\n"); lineno++;
3831 j = 0;
3832 }else{
3833 j++;
3834 }
3835 }
3836 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003837 tplt_xfer(lemp->name,in,out,&lineno);
3838
drh0bd1f4e2002-06-06 18:54:39 +00003839 /* Generate the table of fallback tokens.
3840 */
3841 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003842 int mx = lemp->nterminal - 1;
3843 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3844 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003845 struct symbol *p = lemp->symbols[i];
3846 if( p->fallback==0 ){
3847 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3848 }else{
3849 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3850 p->name, p->fallback->name);
3851 }
3852 lineno++;
3853 }
3854 }
3855 tplt_xfer(lemp->name, in, out, &lineno);
3856
3857 /* Generate a table containing the symbolic name of every symbol
3858 */
drh75897232000-05-29 14:26:00 +00003859 for(i=0; i<lemp->nsymbol; i++){
3860 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3861 fprintf(out," %-15s",line);
3862 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3863 }
3864 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3865 tplt_xfer(lemp->name,in,out,&lineno);
3866
drh0bd1f4e2002-06-06 18:54:39 +00003867 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003868 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003869 ** when tracing REDUCE actions.
3870 */
3871 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3872 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003873 fprintf(out," /* %3d */ \"", i);
3874 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003875 fprintf(out,"\",\n"); lineno++;
3876 }
3877 tplt_xfer(lemp->name,in,out,&lineno);
3878
drh75897232000-05-29 14:26:00 +00003879 /* Generate code which executes every time a symbol is popped from
3880 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003881 ** (In other words, generate the %destructor actions)
3882 */
drh75897232000-05-29 14:26:00 +00003883 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003884 int once = 1;
drh75897232000-05-29 14:26:00 +00003885 for(i=0; i<lemp->nsymbol; i++){
3886 struct symbol *sp = lemp->symbols[i];
3887 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003888 if( once ){
3889 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3890 once = 0;
3891 }
drhc53eed12009-06-12 17:46:19 +00003892 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003893 }
3894 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3895 if( i<lemp->nsymbol ){
3896 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3897 fprintf(out," break;\n"); lineno++;
3898 }
3899 }
drh8d659732005-01-13 23:54:06 +00003900 if( lemp->vardest ){
3901 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003902 int once = 1;
drh8d659732005-01-13 23:54:06 +00003903 for(i=0; i<lemp->nsymbol; i++){
3904 struct symbol *sp = lemp->symbols[i];
3905 if( sp==0 || sp->type==TERMINAL ||
3906 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003907 if( once ){
3908 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3909 once = 0;
3910 }
drhc53eed12009-06-12 17:46:19 +00003911 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003912 dflt_sp = sp;
3913 }
3914 if( dflt_sp!=0 ){
3915 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003916 }
drh4dc8ef52008-07-01 17:13:57 +00003917 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003918 }
drh75897232000-05-29 14:26:00 +00003919 for(i=0; i<lemp->nsymbol; i++){
3920 struct symbol *sp = lemp->symbols[i];
3921 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003922 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003923
3924 /* Combine duplicate destructors into a single case */
3925 for(j=i+1; j<lemp->nsymbol; j++){
3926 struct symbol *sp2 = lemp->symbols[j];
3927 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3928 && sp2->dtnum==sp->dtnum
3929 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003930 fprintf(out," case %d: /* %s */\n",
3931 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003932 sp2->destructor = 0;
3933 }
3934 }
3935
drh75897232000-05-29 14:26:00 +00003936 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3937 fprintf(out," break;\n"); lineno++;
3938 }
drh75897232000-05-29 14:26:00 +00003939 tplt_xfer(lemp->name,in,out,&lineno);
3940
3941 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003942 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003943 tplt_xfer(lemp->name,in,out,&lineno);
3944
3945 /* Generate the table of rule information
3946 **
3947 ** Note: This code depends on the fact that rules are number
3948 ** sequentually beginning with 0.
3949 */
3950 for(rp=lemp->rule; rp; rp=rp->next){
3951 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3952 }
3953 tplt_xfer(lemp->name,in,out,&lineno);
3954
3955 /* Generate code which execution during each REDUCE action */
3956 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003957 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003958 }
drhc53eed12009-06-12 17:46:19 +00003959 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003960 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003961 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003962 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003963 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003964 fprintf(out," case %d: /* ", rp->index);
3965 writeRuleText(out, rp);
3966 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003967 for(rp2=rp->next; rp2; rp2=rp2->next){
3968 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003969 fprintf(out," case %d: /* ", rp2->index);
3970 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003971 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003972 rp2->code = 0;
3973 }
3974 }
drh75897232000-05-29 14:26:00 +00003975 emit_code(out,rp,lemp,&lineno);
3976 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00003977 rp->code = 0;
drh75897232000-05-29 14:26:00 +00003978 }
drhc53eed12009-06-12 17:46:19 +00003979 /* Finally, output the default: rule. We choose as the default: all
3980 ** empty actions. */
3981 fprintf(out," default:\n"); lineno++;
3982 for(rp=lemp->rule; rp; rp=rp->next){
3983 if( rp->code==0 ) continue;
3984 assert( rp->code[0]=='\n' && rp->code[1]==0 );
3985 fprintf(out," /* (%d) ", rp->index);
3986 writeRuleText(out, rp);
3987 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
3988 }
3989 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003990 tplt_xfer(lemp->name,in,out,&lineno);
3991
3992 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003993 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00003994 tplt_xfer(lemp->name,in,out,&lineno);
3995
3996 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00003997 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00003998 tplt_xfer(lemp->name,in,out,&lineno);
3999
4000 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004001 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004002 tplt_xfer(lemp->name,in,out,&lineno);
4003
4004 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004005 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004006
4007 fclose(in);
4008 fclose(out);
4009 return;
4010}
4011
4012/* Generate a header file for the parser */
4013void ReportHeader(lemp)
4014struct lemon *lemp;
4015{
4016 FILE *out, *in;
4017 char *prefix;
4018 char line[LINESIZE];
4019 char pattern[LINESIZE];
4020 int i;
4021
4022 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4023 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004024 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004025 if( in ){
4026 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4027 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4028 if( strcmp(line,pattern) ) break;
4029 }
4030 fclose(in);
4031 if( i==lemp->nterminal ){
4032 /* No change in the file. Don't rewrite it. */
4033 return;
4034 }
4035 }
drh2aa6ca42004-09-10 00:14:04 +00004036 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004037 if( out ){
4038 for(i=1; i<lemp->nterminal; i++){
4039 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4040 }
4041 fclose(out);
4042 }
4043 return;
4044}
4045
4046/* Reduce the size of the action tables, if possible, by making use
4047** of defaults.
4048**
drhb59499c2002-02-23 18:45:13 +00004049** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004050** it the default. Except, there is no default if the wildcard token
4051** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004052*/
4053void CompressTables(lemp)
4054struct lemon *lemp;
4055{
4056 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004057 struct action *ap, *ap2;
4058 struct rule *rp, *rp2, *rbest;
4059 int nbest, n;
drh75897232000-05-29 14:26:00 +00004060 int i;
drhe09daa92006-06-10 13:29:31 +00004061 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004062
4063 for(i=0; i<lemp->nstate; i++){
4064 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004065 nbest = 0;
4066 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004067 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004068
drhb59499c2002-02-23 18:45:13 +00004069 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004070 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4071 usesWildcard = 1;
4072 }
drhb59499c2002-02-23 18:45:13 +00004073 if( ap->type!=REDUCE ) continue;
4074 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004075 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004076 if( rp==rbest ) continue;
4077 n = 1;
4078 for(ap2=ap->next; ap2; ap2=ap2->next){
4079 if( ap2->type!=REDUCE ) continue;
4080 rp2 = ap2->x.rp;
4081 if( rp2==rbest ) continue;
4082 if( rp2==rp ) n++;
4083 }
4084 if( n>nbest ){
4085 nbest = n;
4086 rbest = rp;
drh75897232000-05-29 14:26:00 +00004087 }
4088 }
drhb59499c2002-02-23 18:45:13 +00004089
4090 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004091 ** is not at least 1 or if the wildcard token is a possible
4092 ** lookahead.
4093 */
4094 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004095
drhb59499c2002-02-23 18:45:13 +00004096
4097 /* Combine matching REDUCE actions into a single default */
4098 for(ap=stp->ap; ap; ap=ap->next){
4099 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4100 }
drh75897232000-05-29 14:26:00 +00004101 assert( ap );
4102 ap->sp = Symbol_new("{default}");
4103 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004104 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004105 }
4106 stp->ap = Action_sort(stp->ap);
4107 }
4108}
drhb59499c2002-02-23 18:45:13 +00004109
drhada354d2005-11-05 15:03:59 +00004110
4111/*
4112** Compare two states for sorting purposes. The smaller state is the
4113** one with the most non-terminal actions. If they have the same number
4114** of non-terminal actions, then the smaller is the one with the most
4115** token actions.
4116*/
4117static int stateResortCompare(const void *a, const void *b){
4118 const struct state *pA = *(const struct state**)a;
4119 const struct state *pB = *(const struct state**)b;
4120 int n;
4121
4122 n = pB->nNtAct - pA->nNtAct;
4123 if( n==0 ){
4124 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004125 if( n==0 ){
4126 n = pB->statenum - pA->statenum;
4127 }
drhada354d2005-11-05 15:03:59 +00004128 }
drhe594bc32009-11-03 13:02:25 +00004129 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004130 return n;
4131}
4132
4133
4134/*
4135** Renumber and resort states so that states with fewer choices
4136** occur at the end. Except, keep state 0 as the first state.
4137*/
4138void ResortStates(lemp)
4139struct lemon *lemp;
4140{
4141 int i;
4142 struct state *stp;
4143 struct action *ap;
4144
4145 for(i=0; i<lemp->nstate; i++){
4146 stp = lemp->sorted[i];
4147 stp->nTknAct = stp->nNtAct = 0;
4148 stp->iDflt = lemp->nstate + lemp->nrule;
4149 stp->iTknOfst = NO_OFFSET;
4150 stp->iNtOfst = NO_OFFSET;
4151 for(ap=stp->ap; ap; ap=ap->next){
4152 if( compute_action(lemp,ap)>=0 ){
4153 if( ap->sp->index<lemp->nterminal ){
4154 stp->nTknAct++;
4155 }else if( ap->sp->index<lemp->nsymbol ){
4156 stp->nNtAct++;
4157 }else{
4158 stp->iDflt = compute_action(lemp, ap);
4159 }
4160 }
4161 }
4162 }
4163 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4164 stateResortCompare);
4165 for(i=0; i<lemp->nstate; i++){
4166 lemp->sorted[i]->statenum = i;
4167 }
4168}
4169
4170
drh75897232000-05-29 14:26:00 +00004171/***************** From the file "set.c" ************************************/
4172/*
4173** Set manipulation routines for the LEMON parser generator.
4174*/
4175
4176static int size = 0;
4177
4178/* Set the set size */
4179void SetSize(n)
4180int n;
4181{
4182 size = n+1;
4183}
4184
4185/* Allocate a new set */
4186char *SetNew(){
4187 char *s;
drh9892c5d2007-12-21 00:02:11 +00004188 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004189 if( s==0 ){
4190 extern void memory_error();
4191 memory_error();
4192 }
drh75897232000-05-29 14:26:00 +00004193 return s;
4194}
4195
4196/* Deallocate a set */
4197void SetFree(s)
4198char *s;
4199{
4200 free(s);
4201}
4202
4203/* Add a new element to the set. Return TRUE if the element was added
4204** and FALSE if it was already there. */
4205int SetAdd(s,e)
4206char *s;
4207int e;
4208{
4209 int rv;
drh9892c5d2007-12-21 00:02:11 +00004210 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004211 rv = s[e];
4212 s[e] = 1;
4213 return !rv;
4214}
4215
4216/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4217int SetUnion(s1,s2)
4218char *s1;
4219char *s2;
4220{
4221 int i, progress;
4222 progress = 0;
4223 for(i=0; i<size; i++){
4224 if( s2[i]==0 ) continue;
4225 if( s1[i]==0 ){
4226 progress = 1;
4227 s1[i] = 1;
4228 }
4229 }
4230 return progress;
4231}
4232/********************** From the file "table.c" ****************************/
4233/*
4234** All code in this file has been automatically generated
4235** from a specification in the file
4236** "table.q"
4237** by the associative array code building program "aagen".
4238** Do not edit this file! Instead, edit the specification
4239** file, then rerun aagen.
4240*/
4241/*
4242** Code for processing tables in the LEMON parser generator.
4243*/
4244
4245PRIVATE int strhash(x)
4246char *x;
4247{
4248 int h = 0;
4249 while( *x) h = h*13 + *(x++);
4250 return h;
4251}
4252
4253/* Works like strdup, sort of. Save a string in malloced memory, but
4254** keep strings in a table so that the same string is not in more
4255** than one place.
4256*/
4257char *Strsafe(y)
4258char *y;
4259{
4260 char *z;
4261
drh916f75f2006-07-17 00:19:39 +00004262 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004263 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004264 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004265 strcpy(z,y);
4266 Strsafe_insert(z);
4267 }
4268 MemoryCheck(z);
4269 return z;
4270}
4271
4272/* There is one instance of the following structure for each
4273** associative array of type "x1".
4274*/
4275struct s_x1 {
4276 int size; /* The number of available slots. */
4277 /* Must be a power of 2 greater than or */
4278 /* equal to 1 */
4279 int count; /* Number of currently slots filled */
4280 struct s_x1node *tbl; /* The data stored here */
4281 struct s_x1node **ht; /* Hash table for lookups */
4282};
4283
4284/* There is one instance of this structure for every data element
4285** in an associative array of type "x1".
4286*/
4287typedef struct s_x1node {
4288 char *data; /* The data */
4289 struct s_x1node *next; /* Next entry with the same hash */
4290 struct s_x1node **from; /* Previous link */
4291} x1node;
4292
4293/* There is only one instance of the array, which is the following */
4294static struct s_x1 *x1a;
4295
4296/* Allocate a new associative array */
4297void Strsafe_init(){
4298 if( x1a ) return;
4299 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4300 if( x1a ){
4301 x1a->size = 1024;
4302 x1a->count = 0;
4303 x1a->tbl = (x1node*)malloc(
4304 (sizeof(x1node) + sizeof(x1node*))*1024 );
4305 if( x1a->tbl==0 ){
4306 free(x1a);
4307 x1a = 0;
4308 }else{
4309 int i;
4310 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4311 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4312 }
4313 }
4314}
4315/* Insert a new record into the array. Return TRUE if successful.
4316** Prior data with the same key is NOT overwritten */
4317int Strsafe_insert(data)
4318char *data;
4319{
4320 x1node *np;
4321 int h;
4322 int ph;
4323
4324 if( x1a==0 ) return 0;
4325 ph = strhash(data);
4326 h = ph & (x1a->size-1);
4327 np = x1a->ht[h];
4328 while( np ){
4329 if( strcmp(np->data,data)==0 ){
4330 /* An existing entry with the same key is found. */
4331 /* Fail because overwrite is not allows. */
4332 return 0;
4333 }
4334 np = np->next;
4335 }
4336 if( x1a->count>=x1a->size ){
4337 /* Need to make the hash table bigger */
4338 int i,size;
4339 struct s_x1 array;
4340 array.size = size = x1a->size*2;
4341 array.count = x1a->count;
4342 array.tbl = (x1node*)malloc(
4343 (sizeof(x1node) + sizeof(x1node*))*size );
4344 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4345 array.ht = (x1node**)&(array.tbl[size]);
4346 for(i=0; i<size; i++) array.ht[i] = 0;
4347 for(i=0; i<x1a->count; i++){
4348 x1node *oldnp, *newnp;
4349 oldnp = &(x1a->tbl[i]);
4350 h = strhash(oldnp->data) & (size-1);
4351 newnp = &(array.tbl[i]);
4352 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4353 newnp->next = array.ht[h];
4354 newnp->data = oldnp->data;
4355 newnp->from = &(array.ht[h]);
4356 array.ht[h] = newnp;
4357 }
4358 free(x1a->tbl);
4359 *x1a = array;
4360 }
4361 /* Insert the new data */
4362 h = ph & (x1a->size-1);
4363 np = &(x1a->tbl[x1a->count++]);
4364 np->data = data;
4365 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4366 np->next = x1a->ht[h];
4367 x1a->ht[h] = np;
4368 np->from = &(x1a->ht[h]);
4369 return 1;
4370}
4371
4372/* Return a pointer to data assigned to the given key. Return NULL
4373** if no such key. */
4374char *Strsafe_find(key)
4375char *key;
4376{
4377 int h;
4378 x1node *np;
4379
4380 if( x1a==0 ) return 0;
4381 h = strhash(key) & (x1a->size-1);
4382 np = x1a->ht[h];
4383 while( np ){
4384 if( strcmp(np->data,key)==0 ) break;
4385 np = np->next;
4386 }
4387 return np ? np->data : 0;
4388}
4389
4390/* Return a pointer to the (terminal or nonterminal) symbol "x".
4391** Create a new symbol if this is the first time "x" has been seen.
4392*/
4393struct symbol *Symbol_new(x)
4394char *x;
4395{
4396 struct symbol *sp;
4397
4398 sp = Symbol_find(x);
4399 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004400 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004401 MemoryCheck(sp);
4402 sp->name = Strsafe(x);
4403 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4404 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004405 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004406 sp->prec = -1;
4407 sp->assoc = UNK;
4408 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004409 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004410 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004411 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004412 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004413 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004414 Symbol_insert(sp,sp->name);
4415 }
drhc4dd3fd2008-01-22 01:48:05 +00004416 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004417 return sp;
4418}
4419
drh60d31652004-02-22 00:08:04 +00004420/* Compare two symbols for working purposes
4421**
4422** Symbols that begin with upper case letters (terminals or tokens)
4423** must sort before symbols that begin with lower case letters
4424** (non-terminals). Other than that, the order does not matter.
4425**
4426** We find experimentally that leaving the symbols in their original
4427** order (the order they appeared in the grammar file) gives the
4428** smallest parser tables in SQLite.
4429*/
4430int Symbolcmpp(struct symbol **a, struct symbol **b){
4431 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4432 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004433 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004434 return i1-i2;
drh75897232000-05-29 14:26:00 +00004435}
4436
4437/* There is one instance of the following structure for each
4438** associative array of type "x2".
4439*/
4440struct s_x2 {
4441 int size; /* The number of available slots. */
4442 /* Must be a power of 2 greater than or */
4443 /* equal to 1 */
4444 int count; /* Number of currently slots filled */
4445 struct s_x2node *tbl; /* The data stored here */
4446 struct s_x2node **ht; /* Hash table for lookups */
4447};
4448
4449/* There is one instance of this structure for every data element
4450** in an associative array of type "x2".
4451*/
4452typedef struct s_x2node {
4453 struct symbol *data; /* The data */
4454 char *key; /* The key */
4455 struct s_x2node *next; /* Next entry with the same hash */
4456 struct s_x2node **from; /* Previous link */
4457} x2node;
4458
4459/* There is only one instance of the array, which is the following */
4460static struct s_x2 *x2a;
4461
4462/* Allocate a new associative array */
4463void Symbol_init(){
4464 if( x2a ) return;
4465 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4466 if( x2a ){
4467 x2a->size = 128;
4468 x2a->count = 0;
4469 x2a->tbl = (x2node*)malloc(
4470 (sizeof(x2node) + sizeof(x2node*))*128 );
4471 if( x2a->tbl==0 ){
4472 free(x2a);
4473 x2a = 0;
4474 }else{
4475 int i;
4476 x2a->ht = (x2node**)&(x2a->tbl[128]);
4477 for(i=0; i<128; i++) x2a->ht[i] = 0;
4478 }
4479 }
4480}
4481/* Insert a new record into the array. Return TRUE if successful.
4482** Prior data with the same key is NOT overwritten */
4483int Symbol_insert(data,key)
4484struct symbol *data;
4485char *key;
4486{
4487 x2node *np;
4488 int h;
4489 int ph;
4490
4491 if( x2a==0 ) return 0;
4492 ph = strhash(key);
4493 h = ph & (x2a->size-1);
4494 np = x2a->ht[h];
4495 while( np ){
4496 if( strcmp(np->key,key)==0 ){
4497 /* An existing entry with the same key is found. */
4498 /* Fail because overwrite is not allows. */
4499 return 0;
4500 }
4501 np = np->next;
4502 }
4503 if( x2a->count>=x2a->size ){
4504 /* Need to make the hash table bigger */
4505 int i,size;
4506 struct s_x2 array;
4507 array.size = size = x2a->size*2;
4508 array.count = x2a->count;
4509 array.tbl = (x2node*)malloc(
4510 (sizeof(x2node) + sizeof(x2node*))*size );
4511 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4512 array.ht = (x2node**)&(array.tbl[size]);
4513 for(i=0; i<size; i++) array.ht[i] = 0;
4514 for(i=0; i<x2a->count; i++){
4515 x2node *oldnp, *newnp;
4516 oldnp = &(x2a->tbl[i]);
4517 h = strhash(oldnp->key) & (size-1);
4518 newnp = &(array.tbl[i]);
4519 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4520 newnp->next = array.ht[h];
4521 newnp->key = oldnp->key;
4522 newnp->data = oldnp->data;
4523 newnp->from = &(array.ht[h]);
4524 array.ht[h] = newnp;
4525 }
4526 free(x2a->tbl);
4527 *x2a = array;
4528 }
4529 /* Insert the new data */
4530 h = ph & (x2a->size-1);
4531 np = &(x2a->tbl[x2a->count++]);
4532 np->key = key;
4533 np->data = data;
4534 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4535 np->next = x2a->ht[h];
4536 x2a->ht[h] = np;
4537 np->from = &(x2a->ht[h]);
4538 return 1;
4539}
4540
4541/* Return a pointer to data assigned to the given key. Return NULL
4542** if no such key. */
4543struct symbol *Symbol_find(key)
4544char *key;
4545{
4546 int h;
4547 x2node *np;
4548
4549 if( x2a==0 ) return 0;
4550 h = strhash(key) & (x2a->size-1);
4551 np = x2a->ht[h];
4552 while( np ){
4553 if( strcmp(np->key,key)==0 ) break;
4554 np = np->next;
4555 }
4556 return np ? np->data : 0;
4557}
4558
4559/* Return the n-th data. Return NULL if n is out of range. */
4560struct symbol *Symbol_Nth(n)
4561int n;
4562{
4563 struct symbol *data;
4564 if( x2a && n>0 && n<=x2a->count ){
4565 data = x2a->tbl[n-1].data;
4566 }else{
4567 data = 0;
4568 }
4569 return data;
4570}
4571
4572/* Return the size of the array */
4573int Symbol_count()
4574{
4575 return x2a ? x2a->count : 0;
4576}
4577
4578/* Return an array of pointers to all data in the table.
4579** The array is obtained from malloc. Return NULL if memory allocation
4580** problems, or if the array is empty. */
4581struct symbol **Symbol_arrayof()
4582{
4583 struct symbol **array;
4584 int i,size;
4585 if( x2a==0 ) return 0;
4586 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004587 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004588 if( array ){
4589 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4590 }
4591 return array;
4592}
4593
4594/* Compare two configurations */
4595int Configcmp(a,b)
4596struct config *a;
4597struct config *b;
4598{
4599 int x;
4600 x = a->rp->index - b->rp->index;
4601 if( x==0 ) x = a->dot - b->dot;
4602 return x;
4603}
4604
4605/* Compare two states */
4606PRIVATE int statecmp(a,b)
4607struct config *a;
4608struct config *b;
4609{
4610 int rc;
4611 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4612 rc = a->rp->index - b->rp->index;
4613 if( rc==0 ) rc = a->dot - b->dot;
4614 }
4615 if( rc==0 ){
4616 if( a ) rc = 1;
4617 if( b ) rc = -1;
4618 }
4619 return rc;
4620}
4621
4622/* Hash a state */
4623PRIVATE int statehash(a)
4624struct config *a;
4625{
4626 int h=0;
4627 while( a ){
4628 h = h*571 + a->rp->index*37 + a->dot;
4629 a = a->bp;
4630 }
4631 return h;
4632}
4633
4634/* Allocate a new state structure */
4635struct state *State_new()
4636{
4637 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004638 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004639 MemoryCheck(new);
4640 return new;
4641}
4642
4643/* There is one instance of the following structure for each
4644** associative array of type "x3".
4645*/
4646struct s_x3 {
4647 int size; /* The number of available slots. */
4648 /* Must be a power of 2 greater than or */
4649 /* equal to 1 */
4650 int count; /* Number of currently slots filled */
4651 struct s_x3node *tbl; /* The data stored here */
4652 struct s_x3node **ht; /* Hash table for lookups */
4653};
4654
4655/* There is one instance of this structure for every data element
4656** in an associative array of type "x3".
4657*/
4658typedef struct s_x3node {
4659 struct state *data; /* The data */
4660 struct config *key; /* The key */
4661 struct s_x3node *next; /* Next entry with the same hash */
4662 struct s_x3node **from; /* Previous link */
4663} x3node;
4664
4665/* There is only one instance of the array, which is the following */
4666static struct s_x3 *x3a;
4667
4668/* Allocate a new associative array */
4669void State_init(){
4670 if( x3a ) return;
4671 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4672 if( x3a ){
4673 x3a->size = 128;
4674 x3a->count = 0;
4675 x3a->tbl = (x3node*)malloc(
4676 (sizeof(x3node) + sizeof(x3node*))*128 );
4677 if( x3a->tbl==0 ){
4678 free(x3a);
4679 x3a = 0;
4680 }else{
4681 int i;
4682 x3a->ht = (x3node**)&(x3a->tbl[128]);
4683 for(i=0; i<128; i++) x3a->ht[i] = 0;
4684 }
4685 }
4686}
4687/* Insert a new record into the array. Return TRUE if successful.
4688** Prior data with the same key is NOT overwritten */
4689int State_insert(data,key)
4690struct state *data;
4691struct config *key;
4692{
4693 x3node *np;
4694 int h;
4695 int ph;
4696
4697 if( x3a==0 ) return 0;
4698 ph = statehash(key);
4699 h = ph & (x3a->size-1);
4700 np = x3a->ht[h];
4701 while( np ){
4702 if( statecmp(np->key,key)==0 ){
4703 /* An existing entry with the same key is found. */
4704 /* Fail because overwrite is not allows. */
4705 return 0;
4706 }
4707 np = np->next;
4708 }
4709 if( x3a->count>=x3a->size ){
4710 /* Need to make the hash table bigger */
4711 int i,size;
4712 struct s_x3 array;
4713 array.size = size = x3a->size*2;
4714 array.count = x3a->count;
4715 array.tbl = (x3node*)malloc(
4716 (sizeof(x3node) + sizeof(x3node*))*size );
4717 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4718 array.ht = (x3node**)&(array.tbl[size]);
4719 for(i=0; i<size; i++) array.ht[i] = 0;
4720 for(i=0; i<x3a->count; i++){
4721 x3node *oldnp, *newnp;
4722 oldnp = &(x3a->tbl[i]);
4723 h = statehash(oldnp->key) & (size-1);
4724 newnp = &(array.tbl[i]);
4725 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4726 newnp->next = array.ht[h];
4727 newnp->key = oldnp->key;
4728 newnp->data = oldnp->data;
4729 newnp->from = &(array.ht[h]);
4730 array.ht[h] = newnp;
4731 }
4732 free(x3a->tbl);
4733 *x3a = array;
4734 }
4735 /* Insert the new data */
4736 h = ph & (x3a->size-1);
4737 np = &(x3a->tbl[x3a->count++]);
4738 np->key = key;
4739 np->data = data;
4740 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4741 np->next = x3a->ht[h];
4742 x3a->ht[h] = np;
4743 np->from = &(x3a->ht[h]);
4744 return 1;
4745}
4746
4747/* Return a pointer to data assigned to the given key. Return NULL
4748** if no such key. */
4749struct state *State_find(key)
4750struct config *key;
4751{
4752 int h;
4753 x3node *np;
4754
4755 if( x3a==0 ) return 0;
4756 h = statehash(key) & (x3a->size-1);
4757 np = x3a->ht[h];
4758 while( np ){
4759 if( statecmp(np->key,key)==0 ) break;
4760 np = np->next;
4761 }
4762 return np ? np->data : 0;
4763}
4764
4765/* Return an array of pointers to all data in the table.
4766** The array is obtained from malloc. Return NULL if memory allocation
4767** problems, or if the array is empty. */
4768struct state **State_arrayof()
4769{
4770 struct state **array;
4771 int i,size;
4772 if( x3a==0 ) return 0;
4773 size = x3a->count;
4774 array = (struct state **)malloc( sizeof(struct state *)*size );
4775 if( array ){
4776 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4777 }
4778 return array;
4779}
4780
4781/* Hash a configuration */
4782PRIVATE int confighash(a)
4783struct config *a;
4784{
4785 int h=0;
4786 h = h*571 + a->rp->index*37 + a->dot;
4787 return h;
4788}
4789
4790/* There is one instance of the following structure for each
4791** associative array of type "x4".
4792*/
4793struct s_x4 {
4794 int size; /* The number of available slots. */
4795 /* Must be a power of 2 greater than or */
4796 /* equal to 1 */
4797 int count; /* Number of currently slots filled */
4798 struct s_x4node *tbl; /* The data stored here */
4799 struct s_x4node **ht; /* Hash table for lookups */
4800};
4801
4802/* There is one instance of this structure for every data element
4803** in an associative array of type "x4".
4804*/
4805typedef struct s_x4node {
4806 struct config *data; /* The data */
4807 struct s_x4node *next; /* Next entry with the same hash */
4808 struct s_x4node **from; /* Previous link */
4809} x4node;
4810
4811/* There is only one instance of the array, which is the following */
4812static struct s_x4 *x4a;
4813
4814/* Allocate a new associative array */
4815void Configtable_init(){
4816 if( x4a ) return;
4817 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4818 if( x4a ){
4819 x4a->size = 64;
4820 x4a->count = 0;
4821 x4a->tbl = (x4node*)malloc(
4822 (sizeof(x4node) + sizeof(x4node*))*64 );
4823 if( x4a->tbl==0 ){
4824 free(x4a);
4825 x4a = 0;
4826 }else{
4827 int i;
4828 x4a->ht = (x4node**)&(x4a->tbl[64]);
4829 for(i=0; i<64; i++) x4a->ht[i] = 0;
4830 }
4831 }
4832}
4833/* Insert a new record into the array. Return TRUE if successful.
4834** Prior data with the same key is NOT overwritten */
4835int Configtable_insert(data)
4836struct config *data;
4837{
4838 x4node *np;
4839 int h;
4840 int ph;
4841
4842 if( x4a==0 ) return 0;
4843 ph = confighash(data);
4844 h = ph & (x4a->size-1);
4845 np = x4a->ht[h];
4846 while( np ){
4847 if( Configcmp(np->data,data)==0 ){
4848 /* An existing entry with the same key is found. */
4849 /* Fail because overwrite is not allows. */
4850 return 0;
4851 }
4852 np = np->next;
4853 }
4854 if( x4a->count>=x4a->size ){
4855 /* Need to make the hash table bigger */
4856 int i,size;
4857 struct s_x4 array;
4858 array.size = size = x4a->size*2;
4859 array.count = x4a->count;
4860 array.tbl = (x4node*)malloc(
4861 (sizeof(x4node) + sizeof(x4node*))*size );
4862 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4863 array.ht = (x4node**)&(array.tbl[size]);
4864 for(i=0; i<size; i++) array.ht[i] = 0;
4865 for(i=0; i<x4a->count; i++){
4866 x4node *oldnp, *newnp;
4867 oldnp = &(x4a->tbl[i]);
4868 h = confighash(oldnp->data) & (size-1);
4869 newnp = &(array.tbl[i]);
4870 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4871 newnp->next = array.ht[h];
4872 newnp->data = oldnp->data;
4873 newnp->from = &(array.ht[h]);
4874 array.ht[h] = newnp;
4875 }
4876 free(x4a->tbl);
4877 *x4a = array;
4878 }
4879 /* Insert the new data */
4880 h = ph & (x4a->size-1);
4881 np = &(x4a->tbl[x4a->count++]);
4882 np->data = data;
4883 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4884 np->next = x4a->ht[h];
4885 x4a->ht[h] = np;
4886 np->from = &(x4a->ht[h]);
4887 return 1;
4888}
4889
4890/* Return a pointer to data assigned to the given key. Return NULL
4891** if no such key. */
4892struct config *Configtable_find(key)
4893struct config *key;
4894{
4895 int h;
4896 x4node *np;
4897
4898 if( x4a==0 ) return 0;
4899 h = confighash(key) & (x4a->size-1);
4900 np = x4a->ht[h];
4901 while( np ){
4902 if( Configcmp(np->data,key)==0 ) break;
4903 np = np->next;
4904 }
4905 return np ? np->data : 0;
4906}
4907
4908/* Remove all data from the table. Pass each data to the function "f"
4909** as it is removed. ("f" may be null to avoid this step.) */
4910void Configtable_clear(f)
4911int(*f)(/* struct config * */);
4912{
4913 int i;
4914 if( x4a==0 || x4a->count==0 ) return;
4915 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4916 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4917 x4a->count = 0;
4918 return;
4919}