blob: ce881c16e775960593d6aa0c921bac9cdf8e0eeb [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
drh8dc3e8f2010-01-07 03:53:03 +0000412** the following structure.
413**
414** The yy_action table maps the pair (state_number, lookahead) into an
415** action_number. The table is an array of integers pairs. The state_number
416** determines an initial offset into the yy_action array. The lookahead
417** value is then added to this initial offset to get an index X into the
418** yy_action array. If the aAction[X].lookahead equals the value of the
419** of the lookahead input, then the value of the action_number output is
420** aAction[X].action. If the lookaheads do not match then the
421** default action for the state_number is returned.
422**
423** All actions associated with a single state_number are first entered
424** into aLookahead[] using multiple calls to acttab_action(). Then the
425** actions for that single state_number are placed into the aAction[]
426** array with a single call to acttab_insert(). The acttab_insert() call
427** also resets the aLookahead[] array in preparation for the next
428** state number.
drh8b582012003-10-21 13:16:03 +0000429*/
430typedef struct acttab acttab;
431struct acttab {
432 int nAction; /* Number of used slots in aAction[] */
433 int nActionAlloc; /* Slots allocated for aAction[] */
434 struct {
435 int lookahead; /* Value of the lookahead token */
436 int action; /* Action to take on the given lookahead */
437 } *aAction, /* The yy_action[] table under construction */
438 *aLookahead; /* A single new transaction set */
439 int mnLookahead; /* Minimum aLookahead[].lookahead */
440 int mnAction; /* Action associated with mnLookahead */
441 int mxLookahead; /* Maximum aLookahead[].lookahead */
442 int nLookahead; /* Used slots in aLookahead[] */
443 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
444};
445
446/* Return the number of entries in the yy_action table */
447#define acttab_size(X) ((X)->nAction)
448
449/* The value for the N-th entry in yy_action */
450#define acttab_yyaction(X,N) ((X)->aAction[N].action)
451
452/* The value for the N-th entry in yy_lookahead */
453#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
454
455/* Free all memory associated with the given acttab */
456void acttab_free(acttab *p){
457 free( p->aAction );
458 free( p->aLookahead );
459 free( p );
460}
461
462/* Allocate a new acttab structure */
463acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000464 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000465 if( p==0 ){
466 fprintf(stderr,"Unable to allocate memory for a new acttab.");
467 exit(1);
468 }
469 memset(p, 0, sizeof(*p));
470 return p;
471}
472
drh8dc3e8f2010-01-07 03:53:03 +0000473/* Add a new action to the current transaction set.
474**
475** This routine is called once for each lookahead for a particular
476** state.
drh8b582012003-10-21 13:16:03 +0000477*/
478void acttab_action(acttab *p, int lookahead, int action){
479 if( p->nLookahead>=p->nLookaheadAlloc ){
480 p->nLookaheadAlloc += 25;
481 p->aLookahead = realloc( p->aLookahead,
482 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
483 if( p->aLookahead==0 ){
484 fprintf(stderr,"malloc failed\n");
485 exit(1);
486 }
487 }
488 if( p->nLookahead==0 ){
489 p->mxLookahead = lookahead;
490 p->mnLookahead = lookahead;
491 p->mnAction = action;
492 }else{
493 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
494 if( p->mnLookahead>lookahead ){
495 p->mnLookahead = lookahead;
496 p->mnAction = action;
497 }
498 }
499 p->aLookahead[p->nLookahead].lookahead = lookahead;
500 p->aLookahead[p->nLookahead].action = action;
501 p->nLookahead++;
502}
503
504/*
505** Add the transaction set built up with prior calls to acttab_action()
506** into the current action table. Then reset the transaction set back
507** to an empty set in preparation for a new round of acttab_action() calls.
508**
509** Return the offset into the action table of the new transaction.
510*/
511int acttab_insert(acttab *p){
512 int i, j, k, n;
513 assert( p->nLookahead>0 );
514
515 /* Make sure we have enough space to hold the expanded action table
516 ** in the worst case. The worst case occurs if the transaction set
517 ** must be appended to the current action table
518 */
drh784d86f2004-02-19 18:41:53 +0000519 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000520 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000521 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000522 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
523 p->aAction = realloc( p->aAction,
524 sizeof(p->aAction[0])*p->nActionAlloc);
525 if( p->aAction==0 ){
526 fprintf(stderr,"malloc failed\n");
527 exit(1);
528 }
drhfdbf9282003-10-21 16:34:41 +0000529 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000530 p->aAction[i].lookahead = -1;
531 p->aAction[i].action = -1;
532 }
533 }
534
drh8dc3e8f2010-01-07 03:53:03 +0000535 /* Scan the existing action table looking for an offset that is a
536 ** duplicate of the current transaction set. Fall out of the loop
537 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000538 **
539 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
540 */
drh8dc3e8f2010-01-07 03:53:03 +0000541 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000542 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000543 /* All lookaheads and actions in the aLookahead[] transaction
544 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000545 if( p->aAction[i].action!=p->mnAction ) continue;
546 for(j=0; j<p->nLookahead; j++){
547 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
548 if( k<0 || k>=p->nAction ) break;
549 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
550 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
551 }
552 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000553
554 /* No possible lookahead value that is not in the aLookahead[]
555 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000556 n = 0;
557 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000558 if( p->aAction[j].lookahead<0 ) continue;
559 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000560 }
drhfdbf9282003-10-21 16:34:41 +0000561 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000562 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000563 }
drh8b582012003-10-21 13:16:03 +0000564 }
565 }
drh8dc3e8f2010-01-07 03:53:03 +0000566
567 /* If no existing offsets exactly match the current transaction, find an
568 ** an empty offset in the aAction[] table in which we can add the
569 ** aLookahead[] transaction.
570 */
drhf16371d2009-11-03 19:18:31 +0000571 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000572 /* Look for holes in the aAction[] table that fit the current
573 ** aLookahead[] transaction. Leave i set to the offset of the hole.
574 ** If no holes are found, i is left at p->nAction, which means the
575 ** transaction will be appended. */
576 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000577 if( p->aAction[i].lookahead<0 ){
578 for(j=0; j<p->nLookahead; j++){
579 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
580 if( k<0 ) break;
581 if( p->aAction[k].lookahead>=0 ) break;
582 }
583 if( j<p->nLookahead ) continue;
584 for(j=0; j<p->nAction; j++){
585 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
586 }
587 if( j==p->nAction ){
588 break; /* Fits in empty slots */
589 }
590 }
591 }
592 }
drh8b582012003-10-21 13:16:03 +0000593 /* Insert transaction set at index i. */
594 for(j=0; j<p->nLookahead; j++){
595 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
596 p->aAction[k] = p->aLookahead[j];
597 if( k>=p->nAction ) p->nAction = k+1;
598 }
599 p->nLookahead = 0;
600
601 /* Return the offset that is added to the lookahead in order to get the
602 ** index into yy_action of the action */
603 return i - p->mnLookahead;
604}
605
drh75897232000-05-29 14:26:00 +0000606/********************** From the file "build.c" *****************************/
607/*
608** Routines to construction the finite state machine for the LEMON
609** parser generator.
610*/
611
612/* Find a precedence symbol of every rule in the grammar.
613**
614** Those rules which have a precedence symbol coded in the input
615** grammar using the "[symbol]" construct will already have the
616** rp->precsym field filled. Other rules take as their precedence
617** symbol the first RHS symbol with a defined precedence. If there
618** are not RHS symbols with a defined precedence, the precedence
619** symbol field is left blank.
620*/
621void FindRulePrecedences(xp)
622struct lemon *xp;
623{
624 struct rule *rp;
625 for(rp=xp->rule; rp; rp=rp->next){
626 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000627 int i, j;
628 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
629 struct symbol *sp = rp->rhs[i];
630 if( sp->type==MULTITERMINAL ){
631 for(j=0; j<sp->nsubsym; j++){
632 if( sp->subsym[j]->prec>=0 ){
633 rp->precsym = sp->subsym[j];
634 break;
635 }
636 }
637 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000638 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000639 }
640 }
641 }
642 }
643 return;
644}
645
646/* Find all nonterminals which will generate the empty string.
647** Then go back and compute the first sets of every nonterminal.
648** The first set is the set of all terminal symbols which can begin
649** a string generated by that nonterminal.
650*/
651void FindFirstSets(lemp)
652struct lemon *lemp;
653{
drhfd405312005-11-06 04:06:59 +0000654 int i, j;
drh75897232000-05-29 14:26:00 +0000655 struct rule *rp;
656 int progress;
657
658 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000659 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000660 }
661 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
662 lemp->symbols[i]->firstset = SetNew();
663 }
664
665 /* First compute all lambdas */
666 do{
667 progress = 0;
668 for(rp=lemp->rule; rp; rp=rp->next){
669 if( rp->lhs->lambda ) continue;
670 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000671 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000672 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000673 }
674 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000675 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000676 progress = 1;
677 }
678 }
679 }while( progress );
680
681 /* Now compute all first sets */
682 do{
683 struct symbol *s1, *s2;
684 progress = 0;
685 for(rp=lemp->rule; rp; rp=rp->next){
686 s1 = rp->lhs;
687 for(i=0; i<rp->nrhs; i++){
688 s2 = rp->rhs[i];
689 if( s2->type==TERMINAL ){
690 progress += SetAdd(s1->firstset,s2->index);
691 break;
drhfd405312005-11-06 04:06:59 +0000692 }else if( s2->type==MULTITERMINAL ){
693 for(j=0; j<s2->nsubsym; j++){
694 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
695 }
696 break;
drh75897232000-05-29 14:26:00 +0000697 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000698 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000699 }else{
700 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000701 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000702 }
703 }
704 }
705 }while( progress );
706 return;
707}
708
709/* Compute all LR(0) states for the grammar. Links
710** are added to between some states so that the LR(1) follow sets
711** can be computed later.
712*/
713PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
714void FindStates(lemp)
715struct lemon *lemp;
716{
717 struct symbol *sp;
718 struct rule *rp;
719
720 Configlist_init();
721
722 /* Find the start symbol */
723 if( lemp->start ){
724 sp = Symbol_find(lemp->start);
725 if( sp==0 ){
726 ErrorMsg(lemp->filename,0,
727"The specified start symbol \"%s\" is not \
728in a nonterminal of the grammar. \"%s\" will be used as the start \
729symbol instead.",lemp->start,lemp->rule->lhs->name);
730 lemp->errorcnt++;
731 sp = lemp->rule->lhs;
732 }
733 }else{
734 sp = lemp->rule->lhs;
735 }
736
737 /* Make sure the start symbol doesn't occur on the right-hand side of
738 ** any rule. Report an error if it does. (YACC would generate a new
739 ** start symbol in this case.) */
740 for(rp=lemp->rule; rp; rp=rp->next){
741 int i;
742 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000743 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000744 ErrorMsg(lemp->filename,0,
745"The start symbol \"%s\" occurs on the \
746right-hand side of a rule. This will result in a parser which \
747does not work properly.",sp->name);
748 lemp->errorcnt++;
749 }
750 }
751 }
752
753 /* The basis configuration set for the first state
754 ** is all rules which have the start symbol as their
755 ** left-hand side */
756 for(rp=sp->rule; rp; rp=rp->nextlhs){
757 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000758 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000759 newcfp = Configlist_addbasis(rp,0);
760 SetAdd(newcfp->fws,0);
761 }
762
763 /* Compute the first state. All other states will be
764 ** computed automatically during the computation of the first one.
765 ** The returned pointer to the first state is not used. */
766 (void)getstate(lemp);
767 return;
768}
769
770/* Return a pointer to a state which is described by the configuration
771** list which has been built from calls to Configlist_add.
772*/
773PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
774PRIVATE struct state *getstate(lemp)
775struct lemon *lemp;
776{
777 struct config *cfp, *bp;
778 struct state *stp;
779
780 /* Extract the sorted basis of the new state. The basis was constructed
781 ** by prior calls to "Configlist_addbasis()". */
782 Configlist_sortbasis();
783 bp = Configlist_basis();
784
785 /* Get a state with the same basis */
786 stp = State_find(bp);
787 if( stp ){
788 /* A state with the same basis already exists! Copy all the follow-set
789 ** propagation links from the state under construction into the
790 ** preexisting state, then return a pointer to the preexisting state */
791 struct config *x, *y;
792 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
793 Plink_copy(&y->bplp,x->bplp);
794 Plink_delete(x->fplp);
795 x->fplp = x->bplp = 0;
796 }
797 cfp = Configlist_return();
798 Configlist_eat(cfp);
799 }else{
800 /* This really is a new state. Construct all the details */
801 Configlist_closure(lemp); /* Compute the configuration closure */
802 Configlist_sort(); /* Sort the configuration closure */
803 cfp = Configlist_return(); /* Get a pointer to the config list */
804 stp = State_new(); /* A new state structure */
805 MemoryCheck(stp);
806 stp->bp = bp; /* Remember the configuration basis */
807 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000808 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000809 stp->ap = 0; /* No actions, yet. */
810 State_insert(stp,stp->bp); /* Add to the state table */
811 buildshifts(lemp,stp); /* Recursively compute successor states */
812 }
813 return stp;
814}
815
drhfd405312005-11-06 04:06:59 +0000816/*
817** Return true if two symbols are the same.
818*/
819int same_symbol(a,b)
820struct symbol *a;
821struct symbol *b;
822{
823 int i;
824 if( a==b ) return 1;
825 if( a->type!=MULTITERMINAL ) return 0;
826 if( b->type!=MULTITERMINAL ) return 0;
827 if( a->nsubsym!=b->nsubsym ) return 0;
828 for(i=0; i<a->nsubsym; i++){
829 if( a->subsym[i]!=b->subsym[i] ) return 0;
830 }
831 return 1;
832}
833
drh75897232000-05-29 14:26:00 +0000834/* Construct all successor states to the given state. A "successor"
835** state is any state which can be reached by a shift action.
836*/
837PRIVATE void buildshifts(lemp,stp)
838struct lemon *lemp;
839struct state *stp; /* The state from which successors are computed */
840{
841 struct config *cfp; /* For looping thru the config closure of "stp" */
842 struct config *bcfp; /* For the inner loop on config closure of "stp" */
843 struct config *new; /* */
844 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
845 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
846 struct state *newstp; /* A pointer to a successor state */
847
848 /* Each configuration becomes complete after it contibutes to a successor
849 ** state. Initially, all configurations are incomplete */
850 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
851
852 /* Loop through all configurations of the state "stp" */
853 for(cfp=stp->cfp; cfp; cfp=cfp->next){
854 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
855 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
856 Configlist_reset(); /* Reset the new config set */
857 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
858
859 /* For every configuration in the state "stp" which has the symbol "sp"
860 ** following its dot, add the same configuration to the basis set under
861 ** construction but with the dot shifted one symbol to the right. */
862 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
863 if( bcfp->status==COMPLETE ) continue; /* Already used */
864 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
865 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000866 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000867 bcfp->status = COMPLETE; /* Mark this config as used */
868 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
869 Plink_add(&new->bplp,bcfp);
870 }
871
872 /* Get a pointer to the state described by the basis configuration set
873 ** constructed in the preceding loop */
874 newstp = getstate(lemp);
875
876 /* The state "newstp" is reached from the state "stp" by a shift action
877 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000878 if( sp->type==MULTITERMINAL ){
879 int i;
880 for(i=0; i<sp->nsubsym; i++){
881 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
882 }
883 }else{
884 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
885 }
drh75897232000-05-29 14:26:00 +0000886 }
887}
888
889/*
890** Construct the propagation links
891*/
892void FindLinks(lemp)
893struct lemon *lemp;
894{
895 int i;
896 struct config *cfp, *other;
897 struct state *stp;
898 struct plink *plp;
899
900 /* Housekeeping detail:
901 ** Add to every propagate link a pointer back to the state to
902 ** which the link is attached. */
903 for(i=0; i<lemp->nstate; i++){
904 stp = lemp->sorted[i];
905 for(cfp=stp->cfp; cfp; cfp=cfp->next){
906 cfp->stp = stp;
907 }
908 }
909
910 /* Convert all backlinks into forward links. Only the forward
911 ** links are used in the follow-set computation. */
912 for(i=0; i<lemp->nstate; i++){
913 stp = lemp->sorted[i];
914 for(cfp=stp->cfp; cfp; cfp=cfp->next){
915 for(plp=cfp->bplp; plp; plp=plp->next){
916 other = plp->cfp;
917 Plink_add(&other->fplp,cfp);
918 }
919 }
920 }
921}
922
923/* Compute all followsets.
924**
925** A followset is the set of all symbols which can come immediately
926** after a configuration.
927*/
928void FindFollowSets(lemp)
929struct lemon *lemp;
930{
931 int i;
932 struct config *cfp;
933 struct plink *plp;
934 int progress;
935 int change;
936
937 for(i=0; i<lemp->nstate; i++){
938 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
939 cfp->status = INCOMPLETE;
940 }
941 }
942
943 do{
944 progress = 0;
945 for(i=0; i<lemp->nstate; i++){
946 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
947 if( cfp->status==COMPLETE ) continue;
948 for(plp=cfp->fplp; plp; plp=plp->next){
949 change = SetUnion(plp->cfp->fws,cfp->fws);
950 if( change ){
951 plp->cfp->status = INCOMPLETE;
952 progress = 1;
953 }
954 }
955 cfp->status = COMPLETE;
956 }
957 }
958 }while( progress );
959}
960
961static int resolve_conflict();
962
963/* Compute the reduce actions, and resolve conflicts.
964*/
965void FindActions(lemp)
966struct lemon *lemp;
967{
968 int i,j;
969 struct config *cfp;
970 struct state *stp;
971 struct symbol *sp;
972 struct rule *rp;
973
974 /* Add all of the reduce actions
975 ** A reduce action is added for each element of the followset of
976 ** a configuration which has its dot at the extreme right.
977 */
978 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
979 stp = lemp->sorted[i];
980 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
981 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
982 for(j=0; j<lemp->nterminal; j++){
983 if( SetFind(cfp->fws,j) ){
984 /* Add a reduce action to the state "stp" which will reduce by the
985 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000986 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000987 }
988 }
989 }
990 }
991 }
992
993 /* Add the accepting token */
994 if( lemp->start ){
995 sp = Symbol_find(lemp->start);
996 if( sp==0 ) sp = lemp->rule->lhs;
997 }else{
998 sp = lemp->rule->lhs;
999 }
1000 /* Add to the first state (which is always the starting state of the
1001 ** finite state machine) an action to ACCEPT if the lookahead is the
1002 ** start nonterminal. */
1003 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1004
1005 /* Resolve conflicts */
1006 for(i=0; i<lemp->nstate; i++){
1007 struct action *ap, *nap;
1008 struct state *stp;
1009 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001010 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001011 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001012 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001013 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1014 /* The two actions "ap" and "nap" have the same lookahead.
1015 ** Figure out which one should be used */
1016 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1017 }
1018 }
1019 }
1020
1021 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001022 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001023 for(i=0; i<lemp->nstate; i++){
1024 struct action *ap;
1025 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001026 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001027 }
1028 }
1029 for(rp=lemp->rule; rp; rp=rp->next){
1030 if( rp->canReduce ) continue;
1031 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1032 lemp->errorcnt++;
1033 }
1034}
1035
1036/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001037** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001038**
1039** NO LONGER TRUE:
1040** To resolve a conflict, first look to see if either action
1041** is on an error rule. In that case, take the action which
1042** is not associated with the error rule. If neither or both
1043** actions are associated with an error rule, then try to
1044** use precedence to resolve the conflict.
1045**
1046** If either action is a SHIFT, then it must be apx. This
1047** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1048*/
1049static int resolve_conflict(apx,apy,errsym)
1050struct action *apx;
1051struct action *apy;
1052struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1053{
1054 struct symbol *spx, *spy;
1055 int errcnt = 0;
1056 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001057 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001058 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001059 errcnt++;
1060 }
drh75897232000-05-29 14:26:00 +00001061 if( apx->type==SHIFT && apy->type==REDUCE ){
1062 spx = apx->sp;
1063 spy = apy->x.rp->precsym;
1064 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1065 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001066 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001067 errcnt++;
1068 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1069 apy->type = RD_RESOLVED;
1070 }else if( spx->prec<spy->prec ){
1071 apx->type = SH_RESOLVED;
1072 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1073 apy->type = RD_RESOLVED; /* associativity */
1074 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1075 apx->type = SH_RESOLVED;
1076 }else{
1077 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001078 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001079 errcnt++;
1080 }
1081 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1082 spx = apx->x.rp->precsym;
1083 spy = apy->x.rp->precsym;
1084 if( spx==0 || spy==0 || spx->prec<0 ||
1085 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001086 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001087 errcnt++;
1088 }else if( spx->prec>spy->prec ){
1089 apy->type = RD_RESOLVED;
1090 }else if( spx->prec<spy->prec ){
1091 apx->type = RD_RESOLVED;
1092 }
1093 }else{
drhb59499c2002-02-23 18:45:13 +00001094 assert(
1095 apx->type==SH_RESOLVED ||
1096 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001097 apx->type==SSCONFLICT ||
1098 apx->type==SRCONFLICT ||
1099 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001100 apy->type==SH_RESOLVED ||
1101 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001102 apy->type==SSCONFLICT ||
1103 apy->type==SRCONFLICT ||
1104 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001105 );
1106 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1107 ** REDUCEs on the list. If we reach this point it must be because
1108 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001109 }
1110 return errcnt;
1111}
1112/********************* From the file "configlist.c" *************************/
1113/*
1114** Routines to processing a configuration list and building a state
1115** in the LEMON parser generator.
1116*/
1117
1118static struct config *freelist = 0; /* List of free configurations */
1119static struct config *current = 0; /* Top of list of configurations */
1120static struct config **currentend = 0; /* Last on list of configs */
1121static struct config *basis = 0; /* Top of list of basis configs */
1122static struct config **basisend = 0; /* End of list of basis configs */
1123
1124/* Return a pointer to a new configuration */
1125PRIVATE struct config *newconfig(){
1126 struct config *new;
1127 if( freelist==0 ){
1128 int i;
1129 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001130 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001131 if( freelist==0 ){
1132 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1133 exit(1);
1134 }
1135 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1136 freelist[amt-1].next = 0;
1137 }
1138 new = freelist;
1139 freelist = freelist->next;
1140 return new;
1141}
1142
1143/* The configuration "old" is no longer used */
1144PRIVATE void deleteconfig(old)
1145struct config *old;
1146{
1147 old->next = freelist;
1148 freelist = old;
1149}
1150
1151/* Initialized the configuration list builder */
1152void Configlist_init(){
1153 current = 0;
1154 currentend = &current;
1155 basis = 0;
1156 basisend = &basis;
1157 Configtable_init();
1158 return;
1159}
1160
1161/* Initialized the configuration list builder */
1162void Configlist_reset(){
1163 current = 0;
1164 currentend = &current;
1165 basis = 0;
1166 basisend = &basis;
1167 Configtable_clear(0);
1168 return;
1169}
1170
1171/* Add another configuration to the configuration list */
1172struct config *Configlist_add(rp,dot)
1173struct rule *rp; /* The rule */
1174int dot; /* Index into the RHS of the rule where the dot goes */
1175{
1176 struct config *cfp, model;
1177
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 Configtable_insert(cfp);
1194 }
1195 return cfp;
1196}
1197
1198/* Add a basis configuration to the configuration list */
1199struct config *Configlist_addbasis(rp,dot)
1200struct rule *rp;
1201int dot;
1202{
1203 struct config *cfp, model;
1204
1205 assert( basisend!=0 );
1206 assert( currentend!=0 );
1207 model.rp = rp;
1208 model.dot = dot;
1209 cfp = Configtable_find(&model);
1210 if( cfp==0 ){
1211 cfp = newconfig();
1212 cfp->rp = rp;
1213 cfp->dot = dot;
1214 cfp->fws = SetNew();
1215 cfp->stp = 0;
1216 cfp->fplp = cfp->bplp = 0;
1217 cfp->next = 0;
1218 cfp->bp = 0;
1219 *currentend = cfp;
1220 currentend = &cfp->next;
1221 *basisend = cfp;
1222 basisend = &cfp->bp;
1223 Configtable_insert(cfp);
1224 }
1225 return cfp;
1226}
1227
1228/* Compute the closure of the configuration list */
1229void Configlist_closure(lemp)
1230struct lemon *lemp;
1231{
1232 struct config *cfp, *newcfp;
1233 struct rule *rp, *newrp;
1234 struct symbol *sp, *xsp;
1235 int i, dot;
1236
1237 assert( currentend!=0 );
1238 for(cfp=current; cfp; cfp=cfp->next){
1239 rp = cfp->rp;
1240 dot = cfp->dot;
1241 if( dot>=rp->nrhs ) continue;
1242 sp = rp->rhs[dot];
1243 if( sp->type==NONTERMINAL ){
1244 if( sp->rule==0 && sp!=lemp->errsym ){
1245 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1246 sp->name);
1247 lemp->errorcnt++;
1248 }
1249 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1250 newcfp = Configlist_add(newrp,0);
1251 for(i=dot+1; i<rp->nrhs; i++){
1252 xsp = rp->rhs[i];
1253 if( xsp->type==TERMINAL ){
1254 SetAdd(newcfp->fws,xsp->index);
1255 break;
drhfd405312005-11-06 04:06:59 +00001256 }else if( xsp->type==MULTITERMINAL ){
1257 int k;
1258 for(k=0; k<xsp->nsubsym; k++){
1259 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1260 }
1261 break;
drh75897232000-05-29 14:26:00 +00001262 }else{
1263 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001264 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001265 }
1266 }
1267 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1268 }
1269 }
1270 }
1271 return;
1272}
1273
1274/* Sort the configuration list */
1275void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001276 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001277 currentend = 0;
1278 return;
1279}
1280
1281/* Sort the basis configuration list */
1282void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001283 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001284 basisend = 0;
1285 return;
1286}
1287
1288/* Return a pointer to the head of the configuration list and
1289** reset the list */
1290struct config *Configlist_return(){
1291 struct config *old;
1292 old = current;
1293 current = 0;
1294 currentend = 0;
1295 return old;
1296}
1297
1298/* Return a pointer to the head of the configuration list and
1299** reset the list */
1300struct config *Configlist_basis(){
1301 struct config *old;
1302 old = basis;
1303 basis = 0;
1304 basisend = 0;
1305 return old;
1306}
1307
1308/* Free all elements of the given configuration list */
1309void Configlist_eat(cfp)
1310struct config *cfp;
1311{
1312 struct config *nextcfp;
1313 for(; cfp; cfp=nextcfp){
1314 nextcfp = cfp->next;
1315 assert( cfp->fplp==0 );
1316 assert( cfp->bplp==0 );
1317 if( cfp->fws ) SetFree(cfp->fws);
1318 deleteconfig(cfp);
1319 }
1320 return;
1321}
1322/***************** From the file "error.c" *********************************/
1323/*
1324** Code for printing error message.
1325*/
1326
1327/* Find a good place to break "msg" so that its length is at least "min"
1328** but no more than "max". Make the point as close to max as possible.
1329*/
1330static int findbreak(msg,min,max)
1331char *msg;
1332int min;
1333int max;
1334{
1335 int i,spot;
1336 char c;
1337 for(i=spot=min; i<=max; i++){
1338 c = msg[i];
1339 if( c=='\t' ) msg[i] = ' ';
1340 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1341 if( c==0 ){ spot = i; break; }
1342 if( c=='-' && i<max-1 ) spot = i+1;
1343 if( c==' ' ) spot = i;
1344 }
1345 return spot;
1346}
1347
1348/*
1349** The error message is split across multiple lines if necessary. The
1350** splits occur at a space, if there is a space available near the end
1351** of the line.
1352*/
1353#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1354#define LINEWIDTH 79 /* Max width of any output line */
1355#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001356void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001357 char errmsg[ERRMSGSIZE];
1358 char prefix[PREFIXLIMIT+10];
1359 int errmsgsize;
1360 int prefixsize;
1361 int availablewidth;
1362 va_list ap;
1363 int end, restart, base;
1364
drhf9a2e7b2003-04-15 01:49:48 +00001365 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001366 /* Prepare a prefix to be prepended to every output line */
1367 if( lineno>0 ){
1368 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1369 }else{
1370 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1371 }
drh87cf1372008-08-13 20:09:06 +00001372 prefixsize = lemonStrlen(prefix);
drh75897232000-05-29 14:26:00 +00001373 availablewidth = LINEWIDTH - prefixsize;
1374
1375 /* Generate the error message */
1376 vsprintf(errmsg,format,ap);
1377 va_end(ap);
drh87cf1372008-08-13 20:09:06 +00001378 errmsgsize = lemonStrlen(errmsg);
drh75897232000-05-29 14:26:00 +00001379 /* Remove trailing '\n's from the error message. */
1380 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1381 errmsg[--errmsgsize] = 0;
1382 }
1383
1384 /* Print the error message */
1385 base = 0;
1386 while( errmsg[base]!=0 ){
1387 end = restart = findbreak(&errmsg[base],0,availablewidth);
1388 restart += base;
1389 while( errmsg[restart]==' ' ) restart++;
1390 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1391 base = restart;
1392 }
1393}
1394/**************** From the file "main.c" ************************************/
1395/*
1396** Main program file for the LEMON parser generator.
1397*/
1398
1399/* Report an out-of-memory condition and abort. This function
1400** is used mostly by the "MemoryCheck" macro in struct.h
1401*/
1402void memory_error(){
1403 fprintf(stderr,"Out of memory. Aborting...\n");
1404 exit(1);
1405}
1406
drh6d08b4d2004-07-20 12:45:22 +00001407static int nDefine = 0; /* Number of -D options on the command line */
1408static char **azDefine = 0; /* Name of the -D macros */
1409
1410/* This routine is called with the argument to each -D command-line option.
1411** Add the macro defined to the azDefine array.
1412*/
1413static void handle_D_option(char *z){
1414 char **paz;
1415 nDefine++;
1416 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1417 if( azDefine==0 ){
1418 fprintf(stderr,"out of memory\n");
1419 exit(1);
1420 }
1421 paz = &azDefine[nDefine-1];
drh87cf1372008-08-13 20:09:06 +00001422 *paz = malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001423 if( *paz==0 ){
1424 fprintf(stderr,"out of memory\n");
1425 exit(1);
1426 }
1427 strcpy(*paz, z);
1428 for(z=*paz; *z && *z!='='; z++){}
1429 *z = 0;
1430}
1431
drh75897232000-05-29 14:26:00 +00001432
1433/* The main program. Parse the command line and do it... */
1434int main(argc,argv)
1435int argc;
1436char **argv;
1437{
1438 static int version = 0;
1439 static int rpflag = 0;
1440 static int basisflag = 0;
1441 static int compress = 0;
1442 static int quiet = 0;
1443 static int statistics = 0;
1444 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001445 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001446 static struct s_options options[] = {
1447 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1448 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001449 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001450 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001451 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1452 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001453 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001454 {OPT_FLAG, "s", (char*)&statistics,
1455 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001456 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1457 {OPT_FLAG,0,0,0}
1458 };
1459 int i;
1460 struct lemon lem;
1461
drhb0c86772000-06-02 23:21:26 +00001462 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001463 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001464 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001465 exit(0);
1466 }
drhb0c86772000-06-02 23:21:26 +00001467 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001468 fprintf(stderr,"Exactly one filename argument is required.\n");
1469 exit(1);
1470 }
drh954f6b42006-06-13 13:27:46 +00001471 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001472 lem.errorcnt = 0;
1473
1474 /* Initialize the machine */
1475 Strsafe_init();
1476 Symbol_init();
1477 State_init();
1478 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001479 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001480 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001481 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001482 Symbol_new("$");
1483 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001484 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001485
1486 /* Parse the input file */
1487 Parse(&lem);
1488 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001489 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001490 fprintf(stderr,"Empty grammar.\n");
1491 exit(1);
1492 }
1493
1494 /* Count and index the symbols of the grammar */
1495 lem.nsymbol = Symbol_count();
1496 Symbol_new("{default}");
1497 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001498 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001499 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1500 (int(*)())Symbolcmpp);
1501 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1502 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1503 lem.nterminal = i;
1504
1505 /* Generate a reprint of the grammar, if requested on the command line */
1506 if( rpflag ){
1507 Reprint(&lem);
1508 }else{
1509 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001510 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001511
1512 /* Find the precedence for every production rule (that has one) */
1513 FindRulePrecedences(&lem);
1514
1515 /* Compute the lambda-nonterminals and the first-sets for every
1516 ** nonterminal */
1517 FindFirstSets(&lem);
1518
1519 /* Compute all LR(0) states. Also record follow-set propagation
1520 ** links so that the follow-set can be computed later */
1521 lem.nstate = 0;
1522 FindStates(&lem);
1523 lem.sorted = State_arrayof();
1524
1525 /* Tie up loose ends on the propagation links */
1526 FindLinks(&lem);
1527
1528 /* Compute the follow set of every reducible configuration */
1529 FindFollowSets(&lem);
1530
1531 /* Compute the action tables */
1532 FindActions(&lem);
1533
1534 /* Compress the action tables */
1535 if( compress==0 ) CompressTables(&lem);
1536
drhada354d2005-11-05 15:03:59 +00001537 /* Reorder and renumber the states so that states with fewer choices
1538 ** occur at the end. */
1539 ResortStates(&lem);
1540
drh75897232000-05-29 14:26:00 +00001541 /* Generate a report of the parser generated. (the "y.output" file) */
1542 if( !quiet ) ReportOutput(&lem);
1543
1544 /* Generate the source code for the parser */
1545 ReportTable(&lem, mhflag);
1546
1547 /* Produce a header file for use by the scanner. (This step is
1548 ** omitted if the "-m" option is used because makeheaders will
1549 ** generate the file for us.) */
1550 if( !mhflag ) ReportHeader(&lem);
1551 }
1552 if( statistics ){
1553 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1554 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1555 printf(" %d states, %d parser table entries, %d conflicts\n",
1556 lem.nstate, lem.tablesize, lem.nconflict);
1557 }
1558 if( lem.nconflict ){
1559 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1560 }
1561 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001562 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001563}
1564/******************** From the file "msort.c" *******************************/
1565/*
1566** A generic merge-sort program.
1567**
1568** USAGE:
1569** Let "ptr" be a pointer to some structure which is at the head of
1570** a null-terminated list. Then to sort the list call:
1571**
1572** ptr = msort(ptr,&(ptr->next),cmpfnc);
1573**
1574** In the above, "cmpfnc" is a pointer to a function which compares
1575** two instances of the structure and returns an integer, as in
1576** strcmp. The second argument is a pointer to the pointer to the
1577** second element of the linked list. This address is used to compute
1578** the offset to the "next" field within the structure. The offset to
1579** the "next" field must be constant for all structures in the list.
1580**
1581** The function returns a new pointer which is the head of the list
1582** after sorting.
1583**
1584** ALGORITHM:
1585** Merge-sort.
1586*/
1587
1588/*
1589** Return a pointer to the next structure in the linked list.
1590*/
drhba99af52001-10-25 20:37:16 +00001591#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001592
1593/*
1594** Inputs:
1595** a: A sorted, null-terminated linked list. (May be null).
1596** b: A sorted, null-terminated linked list. (May be null).
1597** cmp: A pointer to the comparison function.
1598** offset: Offset in the structure to the "next" field.
1599**
1600** Return Value:
1601** A pointer to the head of a sorted list containing the elements
1602** of both a and b.
1603**
1604** Side effects:
1605** The "next" pointers for elements in the lists a and b are
1606** changed.
1607*/
drhe9278182007-07-18 18:16:29 +00001608static char *merge(
1609 char *a,
1610 char *b,
1611 int (*cmp)(const char*,const char*),
1612 int offset
1613){
drh75897232000-05-29 14:26:00 +00001614 char *ptr, *head;
1615
1616 if( a==0 ){
1617 head = b;
1618 }else if( b==0 ){
1619 head = a;
1620 }else{
drhe594bc32009-11-03 13:02:25 +00001621 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001622 ptr = a;
1623 a = NEXT(a);
1624 }else{
1625 ptr = b;
1626 b = NEXT(b);
1627 }
1628 head = ptr;
1629 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001630 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001631 NEXT(ptr) = a;
1632 ptr = a;
1633 a = NEXT(a);
1634 }else{
1635 NEXT(ptr) = b;
1636 ptr = b;
1637 b = NEXT(b);
1638 }
1639 }
1640 if( a ) NEXT(ptr) = a;
1641 else NEXT(ptr) = b;
1642 }
1643 return head;
1644}
1645
1646/*
1647** Inputs:
1648** list: Pointer to a singly-linked list of structures.
1649** next: Pointer to pointer to the second element of the list.
1650** cmp: A comparison function.
1651**
1652** Return Value:
1653** A pointer to the head of a sorted list containing the elements
1654** orginally in list.
1655**
1656** Side effects:
1657** The "next" pointers for elements in list are changed.
1658*/
1659#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001660static char *msort(
1661 char *list,
1662 char **next,
1663 int (*cmp)(const char*,const char*)
1664){
drhba99af52001-10-25 20:37:16 +00001665 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001666 char *ep;
1667 char *set[LISTSIZE];
1668 int i;
drhba99af52001-10-25 20:37:16 +00001669 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001670 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1671 while( list ){
1672 ep = list;
1673 list = NEXT(list);
1674 NEXT(ep) = 0;
1675 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1676 ep = merge(ep,set[i],cmp,offset);
1677 set[i] = 0;
1678 }
1679 set[i] = ep;
1680 }
1681 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001682 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001683 return ep;
1684}
1685/************************ From the file "option.c" **************************/
1686static char **argv;
1687static struct s_options *op;
1688static FILE *errstream;
1689
1690#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1691
1692/*
1693** Print the command line with a carrot pointing to the k-th character
1694** of the n-th field.
1695*/
1696static void errline(n,k,err)
1697int n;
1698int k;
1699FILE *err;
1700{
1701 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001702 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001703 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001704 for(i=1; i<n && argv[i]; i++){
1705 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001706 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001707 }
1708 spcnt += k;
1709 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1710 if( spcnt<20 ){
1711 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1712 }else{
1713 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1714 }
1715}
1716
1717/*
1718** Return the index of the N-th non-switch argument. Return -1
1719** if N is out of range.
1720*/
1721static int argindex(n)
1722int n;
1723{
1724 int i;
1725 int dashdash = 0;
1726 if( argv!=0 && *argv!=0 ){
1727 for(i=1; argv[i]; i++){
1728 if( dashdash || !ISOPT(argv[i]) ){
1729 if( n==0 ) return i;
1730 n--;
1731 }
1732 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1733 }
1734 }
1735 return -1;
1736}
1737
1738static char emsg[] = "Command line syntax error: ";
1739
1740/*
1741** Process a flag command line argument.
1742*/
1743static int handleflags(i,err)
1744int i;
1745FILE *err;
1746{
1747 int v;
1748 int errcnt = 0;
1749 int j;
1750 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001751 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001752 }
1753 v = argv[i][0]=='-' ? 1 : 0;
1754 if( op[j].label==0 ){
1755 if( err ){
1756 fprintf(err,"%sundefined option.\n",emsg);
1757 errline(i,1,err);
1758 }
1759 errcnt++;
1760 }else if( op[j].type==OPT_FLAG ){
1761 *((int*)op[j].arg) = v;
1762 }else if( op[j].type==OPT_FFLAG ){
1763 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001764 }else if( op[j].type==OPT_FSTR ){
1765 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001766 }else{
1767 if( err ){
1768 fprintf(err,"%smissing argument on switch.\n",emsg);
1769 errline(i,1,err);
1770 }
1771 errcnt++;
1772 }
1773 return errcnt;
1774}
1775
1776/*
1777** Process a command line switch which has an argument.
1778*/
1779static int handleswitch(i,err)
1780int i;
1781FILE *err;
1782{
1783 int lv = 0;
1784 double dv = 0.0;
1785 char *sv = 0, *end;
1786 char *cp;
1787 int j;
1788 int errcnt = 0;
1789 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001790 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001791 *cp = 0;
1792 for(j=0; op[j].label; j++){
1793 if( strcmp(argv[i],op[j].label)==0 ) break;
1794 }
1795 *cp = '=';
1796 if( op[j].label==0 ){
1797 if( err ){
1798 fprintf(err,"%sundefined option.\n",emsg);
1799 errline(i,0,err);
1800 }
1801 errcnt++;
1802 }else{
1803 cp++;
1804 switch( op[j].type ){
1805 case OPT_FLAG:
1806 case OPT_FFLAG:
1807 if( err ){
1808 fprintf(err,"%soption requires an argument.\n",emsg);
1809 errline(i,0,err);
1810 }
1811 errcnt++;
1812 break;
1813 case OPT_DBL:
1814 case OPT_FDBL:
1815 dv = strtod(cp,&end);
1816 if( *end ){
1817 if( err ){
1818 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001819 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001820 }
1821 errcnt++;
1822 }
1823 break;
1824 case OPT_INT:
1825 case OPT_FINT:
1826 lv = strtol(cp,&end,0);
1827 if( *end ){
1828 if( err ){
1829 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001830 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001831 }
1832 errcnt++;
1833 }
1834 break;
1835 case OPT_STR:
1836 case OPT_FSTR:
1837 sv = cp;
1838 break;
1839 }
1840 switch( op[j].type ){
1841 case OPT_FLAG:
1842 case OPT_FFLAG:
1843 break;
1844 case OPT_DBL:
1845 *(double*)(op[j].arg) = dv;
1846 break;
1847 case OPT_FDBL:
1848 (*(void(*)())(op[j].arg))(dv);
1849 break;
1850 case OPT_INT:
1851 *(int*)(op[j].arg) = lv;
1852 break;
1853 case OPT_FINT:
1854 (*(void(*)())(op[j].arg))((int)lv);
1855 break;
1856 case OPT_STR:
1857 *(char**)(op[j].arg) = sv;
1858 break;
1859 case OPT_FSTR:
1860 (*(void(*)())(op[j].arg))(sv);
1861 break;
1862 }
1863 }
1864 return errcnt;
1865}
1866
drhb0c86772000-06-02 23:21:26 +00001867int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001868char **a;
1869struct s_options *o;
1870FILE *err;
1871{
1872 int errcnt = 0;
1873 argv = a;
1874 op = o;
1875 errstream = err;
1876 if( argv && *argv && op ){
1877 int i;
1878 for(i=1; argv[i]; i++){
1879 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1880 errcnt += handleflags(i,err);
1881 }else if( strchr(argv[i],'=') ){
1882 errcnt += handleswitch(i,err);
1883 }
1884 }
1885 }
1886 if( errcnt>0 ){
1887 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001888 OptPrint();
drh75897232000-05-29 14:26:00 +00001889 exit(1);
1890 }
1891 return 0;
1892}
1893
drhb0c86772000-06-02 23:21:26 +00001894int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001895 int cnt = 0;
1896 int dashdash = 0;
1897 int i;
1898 if( argv!=0 && argv[0]!=0 ){
1899 for(i=1; argv[i]; i++){
1900 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1901 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1902 }
1903 }
1904 return cnt;
1905}
1906
drhb0c86772000-06-02 23:21:26 +00001907char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001908int n;
1909{
1910 int i;
1911 i = argindex(n);
1912 return i>=0 ? argv[i] : 0;
1913}
1914
drhb0c86772000-06-02 23:21:26 +00001915void OptErr(n)
drh75897232000-05-29 14:26:00 +00001916int n;
1917{
1918 int i;
1919 i = argindex(n);
1920 if( i>=0 ) errline(i,0,errstream);
1921}
1922
drhb0c86772000-06-02 23:21:26 +00001923void OptPrint(){
drh75897232000-05-29 14:26:00 +00001924 int i;
1925 int max, len;
1926 max = 0;
1927 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001928 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001929 switch( op[i].type ){
1930 case OPT_FLAG:
1931 case OPT_FFLAG:
1932 break;
1933 case OPT_INT:
1934 case OPT_FINT:
1935 len += 9; /* length of "<integer>" */
1936 break;
1937 case OPT_DBL:
1938 case OPT_FDBL:
1939 len += 6; /* length of "<real>" */
1940 break;
1941 case OPT_STR:
1942 case OPT_FSTR:
1943 len += 8; /* length of "<string>" */
1944 break;
1945 }
1946 if( len>max ) max = len;
1947 }
1948 for(i=0; op[i].label; i++){
1949 switch( op[i].type ){
1950 case OPT_FLAG:
1951 case OPT_FFLAG:
1952 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1953 break;
1954 case OPT_INT:
1955 case OPT_FINT:
1956 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001957 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001958 break;
1959 case OPT_DBL:
1960 case OPT_FDBL:
1961 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001962 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001963 break;
1964 case OPT_STR:
1965 case OPT_FSTR:
1966 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001967 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001968 break;
1969 }
1970 }
1971}
1972/*********************** From the file "parse.c" ****************************/
1973/*
1974** Input file parser for the LEMON parser generator.
1975*/
1976
1977/* The state of the parser */
1978struct pstate {
1979 char *filename; /* Name of the input file */
1980 int tokenlineno; /* Linenumber at which current token starts */
1981 int errorcnt; /* Number of errors so far */
1982 char *tokenstart; /* Text of current token */
1983 struct lemon *gp; /* Global state vector */
1984 enum e_state {
1985 INITIALIZE,
1986 WAITING_FOR_DECL_OR_RULE,
1987 WAITING_FOR_DECL_KEYWORD,
1988 WAITING_FOR_DECL_ARG,
1989 WAITING_FOR_PRECEDENCE_SYMBOL,
1990 WAITING_FOR_ARROW,
1991 IN_RHS,
1992 LHS_ALIAS_1,
1993 LHS_ALIAS_2,
1994 LHS_ALIAS_3,
1995 RHS_ALIAS_1,
1996 RHS_ALIAS_2,
1997 PRECEDENCE_MARK_1,
1998 PRECEDENCE_MARK_2,
1999 RESYNC_AFTER_RULE_ERROR,
2000 RESYNC_AFTER_DECL_ERROR,
2001 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00002002 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00002003 WAITING_FOR_FALLBACK_ID,
2004 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00002005 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002006 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00002007 struct symbol *lhs; /* Left-hand side of current rule */
2008 char *lhsalias; /* Alias for the LHS */
2009 int nrhs; /* Number of right-hand side symbols seen */
2010 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2011 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2012 struct rule *prevrule; /* Previous rule parsed */
2013 char *declkeyword; /* Keyword of a declaration */
2014 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002015 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002016 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002017 enum e_assoc declassoc; /* Assign this association to decl arguments */
2018 int preccounter; /* Assign this precedence to decl arguments */
2019 struct rule *firstrule; /* Pointer to first rule in the grammar */
2020 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2021};
2022
2023/* Parse a single token */
2024static void parseonetoken(psp)
2025struct pstate *psp;
2026{
2027 char *x;
2028 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2029#if 0
2030 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2031 x,psp->state);
2032#endif
2033 switch( psp->state ){
2034 case INITIALIZE:
2035 psp->prevrule = 0;
2036 psp->preccounter = 0;
2037 psp->firstrule = psp->lastrule = 0;
2038 psp->gp->nrule = 0;
2039 /* Fall thru to next case */
2040 case WAITING_FOR_DECL_OR_RULE:
2041 if( x[0]=='%' ){
2042 psp->state = WAITING_FOR_DECL_KEYWORD;
2043 }else if( islower(x[0]) ){
2044 psp->lhs = Symbol_new(x);
2045 psp->nrhs = 0;
2046 psp->lhsalias = 0;
2047 psp->state = WAITING_FOR_ARROW;
2048 }else if( x[0]=='{' ){
2049 if( psp->prevrule==0 ){
2050 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002051"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002052fragment which begins on this line.");
2053 psp->errorcnt++;
2054 }else if( psp->prevrule->code!=0 ){
2055 ErrorMsg(psp->filename,psp->tokenlineno,
2056"Code fragment beginning on this line is not the first \
2057to follow the previous rule.");
2058 psp->errorcnt++;
2059 }else{
2060 psp->prevrule->line = psp->tokenlineno;
2061 psp->prevrule->code = &x[1];
2062 }
2063 }else if( x[0]=='[' ){
2064 psp->state = PRECEDENCE_MARK_1;
2065 }else{
2066 ErrorMsg(psp->filename,psp->tokenlineno,
2067 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2068 x);
2069 psp->errorcnt++;
2070 }
2071 break;
2072 case PRECEDENCE_MARK_1:
2073 if( !isupper(x[0]) ){
2074 ErrorMsg(psp->filename,psp->tokenlineno,
2075 "The precedence symbol must be a terminal.");
2076 psp->errorcnt++;
2077 }else if( psp->prevrule==0 ){
2078 ErrorMsg(psp->filename,psp->tokenlineno,
2079 "There is no prior rule to assign precedence \"[%s]\".",x);
2080 psp->errorcnt++;
2081 }else if( psp->prevrule->precsym!=0 ){
2082 ErrorMsg(psp->filename,psp->tokenlineno,
2083"Precedence mark on this line is not the first \
2084to follow the previous rule.");
2085 psp->errorcnt++;
2086 }else{
2087 psp->prevrule->precsym = Symbol_new(x);
2088 }
2089 psp->state = PRECEDENCE_MARK_2;
2090 break;
2091 case PRECEDENCE_MARK_2:
2092 if( x[0]!=']' ){
2093 ErrorMsg(psp->filename,psp->tokenlineno,
2094 "Missing \"]\" on precedence mark.");
2095 psp->errorcnt++;
2096 }
2097 psp->state = WAITING_FOR_DECL_OR_RULE;
2098 break;
2099 case WAITING_FOR_ARROW:
2100 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2101 psp->state = IN_RHS;
2102 }else if( x[0]=='(' ){
2103 psp->state = LHS_ALIAS_1;
2104 }else{
2105 ErrorMsg(psp->filename,psp->tokenlineno,
2106 "Expected to see a \":\" following the LHS symbol \"%s\".",
2107 psp->lhs->name);
2108 psp->errorcnt++;
2109 psp->state = RESYNC_AFTER_RULE_ERROR;
2110 }
2111 break;
2112 case LHS_ALIAS_1:
2113 if( isalpha(x[0]) ){
2114 psp->lhsalias = x;
2115 psp->state = LHS_ALIAS_2;
2116 }else{
2117 ErrorMsg(psp->filename,psp->tokenlineno,
2118 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2119 x,psp->lhs->name);
2120 psp->errorcnt++;
2121 psp->state = RESYNC_AFTER_RULE_ERROR;
2122 }
2123 break;
2124 case LHS_ALIAS_2:
2125 if( x[0]==')' ){
2126 psp->state = LHS_ALIAS_3;
2127 }else{
2128 ErrorMsg(psp->filename,psp->tokenlineno,
2129 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2130 psp->errorcnt++;
2131 psp->state = RESYNC_AFTER_RULE_ERROR;
2132 }
2133 break;
2134 case LHS_ALIAS_3:
2135 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2136 psp->state = IN_RHS;
2137 }else{
2138 ErrorMsg(psp->filename,psp->tokenlineno,
2139 "Missing \"->\" following: \"%s(%s)\".",
2140 psp->lhs->name,psp->lhsalias);
2141 psp->errorcnt++;
2142 psp->state = RESYNC_AFTER_RULE_ERROR;
2143 }
2144 break;
2145 case IN_RHS:
2146 if( x[0]=='.' ){
2147 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002148 rp = (struct rule *)calloc( sizeof(struct rule) +
2149 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002150 if( rp==0 ){
2151 ErrorMsg(psp->filename,psp->tokenlineno,
2152 "Can't allocate enough memory for this rule.");
2153 psp->errorcnt++;
2154 psp->prevrule = 0;
2155 }else{
2156 int i;
2157 rp->ruleline = psp->tokenlineno;
2158 rp->rhs = (struct symbol**)&rp[1];
2159 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2160 for(i=0; i<psp->nrhs; i++){
2161 rp->rhs[i] = psp->rhs[i];
2162 rp->rhsalias[i] = psp->alias[i];
2163 }
2164 rp->lhs = psp->lhs;
2165 rp->lhsalias = psp->lhsalias;
2166 rp->nrhs = psp->nrhs;
2167 rp->code = 0;
2168 rp->precsym = 0;
2169 rp->index = psp->gp->nrule++;
2170 rp->nextlhs = rp->lhs->rule;
2171 rp->lhs->rule = rp;
2172 rp->next = 0;
2173 if( psp->firstrule==0 ){
2174 psp->firstrule = psp->lastrule = rp;
2175 }else{
2176 psp->lastrule->next = rp;
2177 psp->lastrule = rp;
2178 }
2179 psp->prevrule = rp;
2180 }
2181 psp->state = WAITING_FOR_DECL_OR_RULE;
2182 }else if( isalpha(x[0]) ){
2183 if( psp->nrhs>=MAXRHS ){
2184 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002185 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002186 x);
2187 psp->errorcnt++;
2188 psp->state = RESYNC_AFTER_RULE_ERROR;
2189 }else{
2190 psp->rhs[psp->nrhs] = Symbol_new(x);
2191 psp->alias[psp->nrhs] = 0;
2192 psp->nrhs++;
2193 }
drhfd405312005-11-06 04:06:59 +00002194 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2195 struct symbol *msp = psp->rhs[psp->nrhs-1];
2196 if( msp->type!=MULTITERMINAL ){
2197 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002198 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002199 memset(msp, 0, sizeof(*msp));
2200 msp->type = MULTITERMINAL;
2201 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002202 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002203 msp->subsym[0] = origsp;
2204 msp->name = origsp->name;
2205 psp->rhs[psp->nrhs-1] = msp;
2206 }
2207 msp->nsubsym++;
2208 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2209 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2210 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2211 ErrorMsg(psp->filename,psp->tokenlineno,
2212 "Cannot form a compound containing a non-terminal");
2213 psp->errorcnt++;
2214 }
drh75897232000-05-29 14:26:00 +00002215 }else if( x[0]=='(' && psp->nrhs>0 ){
2216 psp->state = RHS_ALIAS_1;
2217 }else{
2218 ErrorMsg(psp->filename,psp->tokenlineno,
2219 "Illegal character on RHS of rule: \"%s\".",x);
2220 psp->errorcnt++;
2221 psp->state = RESYNC_AFTER_RULE_ERROR;
2222 }
2223 break;
2224 case RHS_ALIAS_1:
2225 if( isalpha(x[0]) ){
2226 psp->alias[psp->nrhs-1] = x;
2227 psp->state = RHS_ALIAS_2;
2228 }else{
2229 ErrorMsg(psp->filename,psp->tokenlineno,
2230 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2231 x,psp->rhs[psp->nrhs-1]->name);
2232 psp->errorcnt++;
2233 psp->state = RESYNC_AFTER_RULE_ERROR;
2234 }
2235 break;
2236 case RHS_ALIAS_2:
2237 if( x[0]==')' ){
2238 psp->state = IN_RHS;
2239 }else{
2240 ErrorMsg(psp->filename,psp->tokenlineno,
2241 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2242 psp->errorcnt++;
2243 psp->state = RESYNC_AFTER_RULE_ERROR;
2244 }
2245 break;
2246 case WAITING_FOR_DECL_KEYWORD:
2247 if( isalpha(x[0]) ){
2248 psp->declkeyword = x;
2249 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002250 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002251 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002252 psp->state = WAITING_FOR_DECL_ARG;
2253 if( strcmp(x,"name")==0 ){
2254 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002255 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002256 }else if( strcmp(x,"include")==0 ){
2257 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002258 }else if( strcmp(x,"code")==0 ){
2259 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002260 }else if( strcmp(x,"token_destructor")==0 ){
2261 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002262 }else if( strcmp(x,"default_destructor")==0 ){
2263 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002264 }else if( strcmp(x,"token_prefix")==0 ){
2265 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002266 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002267 }else if( strcmp(x,"syntax_error")==0 ){
2268 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002269 }else if( strcmp(x,"parse_accept")==0 ){
2270 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002271 }else if( strcmp(x,"parse_failure")==0 ){
2272 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002273 }else if( strcmp(x,"stack_overflow")==0 ){
2274 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002275 }else if( strcmp(x,"extra_argument")==0 ){
2276 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002277 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002278 }else if( strcmp(x,"token_type")==0 ){
2279 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002280 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002281 }else if( strcmp(x,"default_type")==0 ){
2282 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002283 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002284 }else if( strcmp(x,"stack_size")==0 ){
2285 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002286 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002287 }else if( strcmp(x,"start_symbol")==0 ){
2288 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002289 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002290 }else if( strcmp(x,"left")==0 ){
2291 psp->preccounter++;
2292 psp->declassoc = LEFT;
2293 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2294 }else if( strcmp(x,"right")==0 ){
2295 psp->preccounter++;
2296 psp->declassoc = RIGHT;
2297 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2298 }else if( strcmp(x,"nonassoc")==0 ){
2299 psp->preccounter++;
2300 psp->declassoc = NONE;
2301 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2302 }else if( strcmp(x,"destructor")==0 ){
2303 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2304 }else if( strcmp(x,"type")==0 ){
2305 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002306 }else if( strcmp(x,"fallback")==0 ){
2307 psp->fallback = 0;
2308 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002309 }else if( strcmp(x,"wildcard")==0 ){
2310 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002311 }else{
2312 ErrorMsg(psp->filename,psp->tokenlineno,
2313 "Unknown declaration keyword: \"%%%s\".",x);
2314 psp->errorcnt++;
2315 psp->state = RESYNC_AFTER_DECL_ERROR;
2316 }
2317 }else{
2318 ErrorMsg(psp->filename,psp->tokenlineno,
2319 "Illegal declaration keyword: \"%s\".",x);
2320 psp->errorcnt++;
2321 psp->state = RESYNC_AFTER_DECL_ERROR;
2322 }
2323 break;
2324 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2325 if( !isalpha(x[0]) ){
2326 ErrorMsg(psp->filename,psp->tokenlineno,
2327 "Symbol name missing after %destructor keyword");
2328 psp->errorcnt++;
2329 psp->state = RESYNC_AFTER_DECL_ERROR;
2330 }else{
2331 struct symbol *sp = Symbol_new(x);
2332 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002333 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002334 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002335 psp->state = WAITING_FOR_DECL_ARG;
2336 }
2337 break;
2338 case WAITING_FOR_DATATYPE_SYMBOL:
2339 if( !isalpha(x[0]) ){
2340 ErrorMsg(psp->filename,psp->tokenlineno,
2341 "Symbol name missing after %destructor keyword");
2342 psp->errorcnt++;
2343 psp->state = RESYNC_AFTER_DECL_ERROR;
2344 }else{
2345 struct symbol *sp = Symbol_new(x);
2346 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002347 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002348 psp->state = WAITING_FOR_DECL_ARG;
2349 }
2350 break;
2351 case WAITING_FOR_PRECEDENCE_SYMBOL:
2352 if( x[0]=='.' ){
2353 psp->state = WAITING_FOR_DECL_OR_RULE;
2354 }else if( isupper(x[0]) ){
2355 struct symbol *sp;
2356 sp = Symbol_new(x);
2357 if( sp->prec>=0 ){
2358 ErrorMsg(psp->filename,psp->tokenlineno,
2359 "Symbol \"%s\" has already be given a precedence.",x);
2360 psp->errorcnt++;
2361 }else{
2362 sp->prec = psp->preccounter;
2363 sp->assoc = psp->declassoc;
2364 }
2365 }else{
2366 ErrorMsg(psp->filename,psp->tokenlineno,
2367 "Can't assign a precedence to \"%s\".",x);
2368 psp->errorcnt++;
2369 }
2370 break;
2371 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002372 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2373 char *zOld, *zNew, *zBuf, *z;
2374 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002375 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002376 char zLine[50];
2377 zNew = x;
2378 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002379 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002380 if( *psp->declargslot ){
2381 zOld = *psp->declargslot;
2382 }else{
2383 zOld = "";
2384 }
drh87cf1372008-08-13 20:09:06 +00002385 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002386 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002387 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002388 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2389 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002390 for(z=psp->filename, nBack=0; *z; z++){
2391 if( *z=='\\' ) nBack++;
2392 }
2393 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002394 nLine = lemonStrlen(zLine);
2395 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002396 }
2397 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2398 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002399 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002400 if( nOld && zBuf[-1]!='\n' ){
2401 *(zBuf++) = '\n';
2402 }
2403 memcpy(zBuf, zLine, nLine);
2404 zBuf += nLine;
2405 *(zBuf++) = '"';
2406 for(z=psp->filename; *z; z++){
2407 if( *z=='\\' ){
2408 *(zBuf++) = '\\';
2409 }
2410 *(zBuf++) = *z;
2411 }
2412 *(zBuf++) = '"';
2413 *(zBuf++) = '\n';
2414 }
drh4dc8ef52008-07-01 17:13:57 +00002415 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2416 psp->decllinenoslot[0] = psp->tokenlineno;
2417 }
drha5808f32008-04-27 22:19:44 +00002418 memcpy(zBuf, zNew, nNew);
2419 zBuf += nNew;
2420 *zBuf = 0;
2421 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002422 }else{
2423 ErrorMsg(psp->filename,psp->tokenlineno,
2424 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2425 psp->errorcnt++;
2426 psp->state = RESYNC_AFTER_DECL_ERROR;
2427 }
2428 break;
drh0bd1f4e2002-06-06 18:54:39 +00002429 case WAITING_FOR_FALLBACK_ID:
2430 if( x[0]=='.' ){
2431 psp->state = WAITING_FOR_DECL_OR_RULE;
2432 }else if( !isupper(x[0]) ){
2433 ErrorMsg(psp->filename, psp->tokenlineno,
2434 "%%fallback argument \"%s\" should be a token", x);
2435 psp->errorcnt++;
2436 }else{
2437 struct symbol *sp = Symbol_new(x);
2438 if( psp->fallback==0 ){
2439 psp->fallback = sp;
2440 }else if( sp->fallback ){
2441 ErrorMsg(psp->filename, psp->tokenlineno,
2442 "More than one fallback assigned to token %s", x);
2443 psp->errorcnt++;
2444 }else{
2445 sp->fallback = psp->fallback;
2446 psp->gp->has_fallback = 1;
2447 }
2448 }
2449 break;
drhe09daa92006-06-10 13:29:31 +00002450 case WAITING_FOR_WILDCARD_ID:
2451 if( x[0]=='.' ){
2452 psp->state = WAITING_FOR_DECL_OR_RULE;
2453 }else if( !isupper(x[0]) ){
2454 ErrorMsg(psp->filename, psp->tokenlineno,
2455 "%%wildcard argument \"%s\" should be a token", x);
2456 psp->errorcnt++;
2457 }else{
2458 struct symbol *sp = Symbol_new(x);
2459 if( psp->gp->wildcard==0 ){
2460 psp->gp->wildcard = sp;
2461 }else{
2462 ErrorMsg(psp->filename, psp->tokenlineno,
2463 "Extra wildcard to token: %s", x);
2464 psp->errorcnt++;
2465 }
2466 }
2467 break;
drh75897232000-05-29 14:26:00 +00002468 case RESYNC_AFTER_RULE_ERROR:
2469/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2470** break; */
2471 case RESYNC_AFTER_DECL_ERROR:
2472 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2473 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2474 break;
2475 }
2476}
2477
drh34ff57b2008-07-14 12:27:51 +00002478/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002479** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2480** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2481** comments them out. Text in between is also commented out as appropriate.
2482*/
danielk1977940fac92005-01-23 22:41:37 +00002483static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002484 int i, j, k, n;
2485 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002486 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002487 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002488 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002489 for(i=0; z[i]; i++){
2490 if( z[i]=='\n' ) lineno++;
2491 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2492 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2493 if( exclude ){
2494 exclude--;
2495 if( exclude==0 ){
2496 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2497 }
2498 }
2499 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2500 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2501 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2502 if( exclude ){
2503 exclude++;
2504 }else{
2505 for(j=i+7; isspace(z[j]); j++){}
2506 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2507 exclude = 1;
2508 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002509 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002510 exclude = 0;
2511 break;
2512 }
2513 }
2514 if( z[i+3]=='n' ) exclude = !exclude;
2515 if( exclude ){
2516 start = i;
2517 start_lineno = lineno;
2518 }
2519 }
2520 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2521 }
2522 }
2523 if( exclude ){
2524 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2525 exit(1);
2526 }
2527}
2528
drh75897232000-05-29 14:26:00 +00002529/* In spite of its name, this function is really a scanner. It read
2530** in the entire input file (all at once) then tokenizes it. Each
2531** token is passed to the function "parseonetoken" which builds all
2532** the appropriate data structures in the global state vector "gp".
2533*/
2534void Parse(gp)
2535struct lemon *gp;
2536{
2537 struct pstate ps;
2538 FILE *fp;
2539 char *filebuf;
2540 int filesize;
2541 int lineno;
2542 int c;
2543 char *cp, *nextcp;
2544 int startline = 0;
2545
rse38514a92007-09-20 11:34:17 +00002546 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002547 ps.gp = gp;
2548 ps.filename = gp->filename;
2549 ps.errorcnt = 0;
2550 ps.state = INITIALIZE;
2551
2552 /* Begin by reading the input file */
2553 fp = fopen(ps.filename,"rb");
2554 if( fp==0 ){
2555 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2556 gp->errorcnt++;
2557 return;
2558 }
2559 fseek(fp,0,2);
2560 filesize = ftell(fp);
2561 rewind(fp);
2562 filebuf = (char *)malloc( filesize+1 );
2563 if( filebuf==0 ){
2564 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2565 filesize+1);
2566 gp->errorcnt++;
2567 return;
2568 }
2569 if( fread(filebuf,1,filesize,fp)!=filesize ){
2570 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2571 filesize);
2572 free(filebuf);
2573 gp->errorcnt++;
2574 return;
2575 }
2576 fclose(fp);
2577 filebuf[filesize] = 0;
2578
drh6d08b4d2004-07-20 12:45:22 +00002579 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2580 preprocess_input(filebuf);
2581
drh75897232000-05-29 14:26:00 +00002582 /* Now scan the text of the input file */
2583 lineno = 1;
2584 for(cp=filebuf; (c= *cp)!=0; ){
2585 if( c=='\n' ) lineno++; /* Keep track of the line number */
2586 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2587 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2588 cp+=2;
2589 while( (c= *cp)!=0 && c!='\n' ) cp++;
2590 continue;
2591 }
2592 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2593 cp+=2;
2594 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2595 if( c=='\n' ) lineno++;
2596 cp++;
2597 }
2598 if( c ) cp++;
2599 continue;
2600 }
2601 ps.tokenstart = cp; /* Mark the beginning of the token */
2602 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2603 if( c=='\"' ){ /* String literals */
2604 cp++;
2605 while( (c= *cp)!=0 && c!='\"' ){
2606 if( c=='\n' ) lineno++;
2607 cp++;
2608 }
2609 if( c==0 ){
2610 ErrorMsg(ps.filename,startline,
2611"String starting on this line is not terminated before the end of the file.");
2612 ps.errorcnt++;
2613 nextcp = cp;
2614 }else{
2615 nextcp = cp+1;
2616 }
2617 }else if( c=='{' ){ /* A block of C code */
2618 int level;
2619 cp++;
2620 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2621 if( c=='\n' ) lineno++;
2622 else if( c=='{' ) level++;
2623 else if( c=='}' ) level--;
2624 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2625 int prevc;
2626 cp = &cp[2];
2627 prevc = 0;
2628 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2629 if( c=='\n' ) lineno++;
2630 prevc = c;
2631 cp++;
2632 }
2633 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2634 cp = &cp[2];
2635 while( (c= *cp)!=0 && c!='\n' ) cp++;
2636 if( c ) lineno++;
2637 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2638 int startchar, prevc;
2639 startchar = c;
2640 prevc = 0;
2641 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2642 if( c=='\n' ) lineno++;
2643 if( prevc=='\\' ) prevc = 0;
2644 else prevc = c;
2645 }
2646 }
2647 }
2648 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002649 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002650"C code starting on this line is not terminated before the end of the file.");
2651 ps.errorcnt++;
2652 nextcp = cp;
2653 }else{
2654 nextcp = cp+1;
2655 }
2656 }else if( isalnum(c) ){ /* Identifiers */
2657 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2658 nextcp = cp;
2659 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2660 cp += 3;
2661 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002662 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2663 cp += 2;
2664 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2665 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002666 }else{ /* All other (one character) operators */
2667 cp++;
2668 nextcp = cp;
2669 }
2670 c = *cp;
2671 *cp = 0; /* Null terminate the token */
2672 parseonetoken(&ps); /* Parse the token */
2673 *cp = c; /* Restore the buffer */
2674 cp = nextcp;
2675 }
2676 free(filebuf); /* Release the buffer after parsing */
2677 gp->rule = ps.firstrule;
2678 gp->errorcnt = ps.errorcnt;
2679}
2680/*************************** From the file "plink.c" *********************/
2681/*
2682** Routines processing configuration follow-set propagation links
2683** in the LEMON parser generator.
2684*/
2685static struct plink *plink_freelist = 0;
2686
2687/* Allocate a new plink */
2688struct plink *Plink_new(){
2689 struct plink *new;
2690
2691 if( plink_freelist==0 ){
2692 int i;
2693 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002694 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002695 if( plink_freelist==0 ){
2696 fprintf(stderr,
2697 "Unable to allocate memory for a new follow-set propagation link.\n");
2698 exit(1);
2699 }
2700 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2701 plink_freelist[amt-1].next = 0;
2702 }
2703 new = plink_freelist;
2704 plink_freelist = plink_freelist->next;
2705 return new;
2706}
2707
2708/* Add a plink to a plink list */
2709void Plink_add(plpp,cfp)
2710struct plink **plpp;
2711struct config *cfp;
2712{
2713 struct plink *new;
2714 new = Plink_new();
2715 new->next = *plpp;
2716 *plpp = new;
2717 new->cfp = cfp;
2718}
2719
2720/* Transfer every plink on the list "from" to the list "to" */
2721void Plink_copy(to,from)
2722struct plink **to;
2723struct plink *from;
2724{
2725 struct plink *nextpl;
2726 while( from ){
2727 nextpl = from->next;
2728 from->next = *to;
2729 *to = from;
2730 from = nextpl;
2731 }
2732}
2733
2734/* Delete every plink on the list */
2735void Plink_delete(plp)
2736struct plink *plp;
2737{
2738 struct plink *nextpl;
2739
2740 while( plp ){
2741 nextpl = plp->next;
2742 plp->next = plink_freelist;
2743 plink_freelist = plp;
2744 plp = nextpl;
2745 }
2746}
2747/*********************** From the file "report.c" **************************/
2748/*
2749** Procedures for generating reports and tables in the LEMON parser generator.
2750*/
2751
2752/* Generate a filename with the given suffix. Space to hold the
2753** name comes from malloc() and must be freed by the calling
2754** function.
2755*/
2756PRIVATE char *file_makename(lemp,suffix)
2757struct lemon *lemp;
2758char *suffix;
2759{
2760 char *name;
2761 char *cp;
2762
drh87cf1372008-08-13 20:09:06 +00002763 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002764 if( name==0 ){
2765 fprintf(stderr,"Can't allocate space for a filename.\n");
2766 exit(1);
2767 }
2768 strcpy(name,lemp->filename);
2769 cp = strrchr(name,'.');
2770 if( cp ) *cp = 0;
2771 strcat(name,suffix);
2772 return name;
2773}
2774
2775/* Open a file with a name based on the name of the input file,
2776** but with a different (specified) suffix, and return a pointer
2777** to the stream */
2778PRIVATE FILE *file_open(lemp,suffix,mode)
2779struct lemon *lemp;
2780char *suffix;
2781char *mode;
2782{
2783 FILE *fp;
2784
2785 if( lemp->outname ) free(lemp->outname);
2786 lemp->outname = file_makename(lemp, suffix);
2787 fp = fopen(lemp->outname,mode);
2788 if( fp==0 && *mode=='w' ){
2789 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2790 lemp->errorcnt++;
2791 return 0;
2792 }
2793 return fp;
2794}
2795
2796/* Duplicate the input file without comments and without actions
2797** on rules */
2798void Reprint(lemp)
2799struct lemon *lemp;
2800{
2801 struct rule *rp;
2802 struct symbol *sp;
2803 int i, j, maxlen, len, ncolumns, skip;
2804 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2805 maxlen = 10;
2806 for(i=0; i<lemp->nsymbol; i++){
2807 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002808 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002809 if( len>maxlen ) maxlen = len;
2810 }
2811 ncolumns = 76/(maxlen+5);
2812 if( ncolumns<1 ) ncolumns = 1;
2813 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2814 for(i=0; i<skip; i++){
2815 printf("//");
2816 for(j=i; j<lemp->nsymbol; j+=skip){
2817 sp = lemp->symbols[j];
2818 assert( sp->index==j );
2819 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2820 }
2821 printf("\n");
2822 }
2823 for(rp=lemp->rule; rp; rp=rp->next){
2824 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002825 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002826 printf(" ::=");
2827 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002828 sp = rp->rhs[i];
2829 printf(" %s", sp->name);
2830 if( sp->type==MULTITERMINAL ){
2831 for(j=1; j<sp->nsubsym; j++){
2832 printf("|%s", sp->subsym[j]->name);
2833 }
2834 }
2835 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002836 }
2837 printf(".");
2838 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002839 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002840 printf("\n");
2841 }
2842}
2843
2844void ConfigPrint(fp,cfp)
2845FILE *fp;
2846struct config *cfp;
2847{
2848 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002849 struct symbol *sp;
2850 int i, j;
drh75897232000-05-29 14:26:00 +00002851 rp = cfp->rp;
2852 fprintf(fp,"%s ::=",rp->lhs->name);
2853 for(i=0; i<=rp->nrhs; i++){
2854 if( i==cfp->dot ) fprintf(fp," *");
2855 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002856 sp = rp->rhs[i];
2857 fprintf(fp," %s", sp->name);
2858 if( sp->type==MULTITERMINAL ){
2859 for(j=1; j<sp->nsubsym; j++){
2860 fprintf(fp,"|%s",sp->subsym[j]->name);
2861 }
2862 }
drh75897232000-05-29 14:26:00 +00002863 }
2864}
2865
2866/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002867#if 0
drh75897232000-05-29 14:26:00 +00002868/* Print a set */
2869PRIVATE void SetPrint(out,set,lemp)
2870FILE *out;
2871char *set;
2872struct lemon *lemp;
2873{
2874 int i;
2875 char *spacer;
2876 spacer = "";
2877 fprintf(out,"%12s[","");
2878 for(i=0; i<lemp->nterminal; i++){
2879 if( SetFind(set,i) ){
2880 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2881 spacer = " ";
2882 }
2883 }
2884 fprintf(out,"]\n");
2885}
2886
2887/* Print a plink chain */
2888PRIVATE void PlinkPrint(out,plp,tag)
2889FILE *out;
2890struct plink *plp;
2891char *tag;
2892{
2893 while( plp ){
drhada354d2005-11-05 15:03:59 +00002894 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002895 ConfigPrint(out,plp->cfp);
2896 fprintf(out,"\n");
2897 plp = plp->next;
2898 }
2899}
2900#endif
2901
2902/* Print an action to the given file descriptor. Return FALSE if
2903** nothing was actually printed.
2904*/
2905int PrintAction(struct action *ap, FILE *fp, int indent){
2906 int result = 1;
2907 switch( ap->type ){
2908 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002909 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002910 break;
2911 case REDUCE:
2912 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2913 break;
2914 case ACCEPT:
2915 fprintf(fp,"%*s accept",indent,ap->sp->name);
2916 break;
2917 case ERROR:
2918 fprintf(fp,"%*s error",indent,ap->sp->name);
2919 break;
drh9892c5d2007-12-21 00:02:11 +00002920 case SRCONFLICT:
2921 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002922 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2923 indent,ap->sp->name,ap->x.rp->index);
2924 break;
drh9892c5d2007-12-21 00:02:11 +00002925 case SSCONFLICT:
2926 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2927 indent,ap->sp->name,ap->x.stp->statenum);
2928 break;
drh75897232000-05-29 14:26:00 +00002929 case SH_RESOLVED:
2930 case RD_RESOLVED:
2931 case NOT_USED:
2932 result = 0;
2933 break;
2934 }
2935 return result;
2936}
2937
2938/* Generate the "y.output" log file */
2939void ReportOutput(lemp)
2940struct lemon *lemp;
2941{
2942 int i;
2943 struct state *stp;
2944 struct config *cfp;
2945 struct action *ap;
2946 FILE *fp;
2947
drh2aa6ca42004-09-10 00:14:04 +00002948 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002949 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002950 for(i=0; i<lemp->nstate; i++){
2951 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002952 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002953 if( lemp->basisflag ) cfp=stp->bp;
2954 else cfp=stp->cfp;
2955 while( cfp ){
2956 char buf[20];
2957 if( cfp->dot==cfp->rp->nrhs ){
2958 sprintf(buf,"(%d)",cfp->rp->index);
2959 fprintf(fp," %5s ",buf);
2960 }else{
2961 fprintf(fp," ");
2962 }
2963 ConfigPrint(fp,cfp);
2964 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002965#if 0
drh75897232000-05-29 14:26:00 +00002966 SetPrint(fp,cfp->fws,lemp);
2967 PlinkPrint(fp,cfp->fplp,"To ");
2968 PlinkPrint(fp,cfp->bplp,"From");
2969#endif
2970 if( lemp->basisflag ) cfp=cfp->bp;
2971 else cfp=cfp->next;
2972 }
2973 fprintf(fp,"\n");
2974 for(ap=stp->ap; ap; ap=ap->next){
2975 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2976 }
2977 fprintf(fp,"\n");
2978 }
drhe9278182007-07-18 18:16:29 +00002979 fprintf(fp, "----------------------------------------------------\n");
2980 fprintf(fp, "Symbols:\n");
2981 for(i=0; i<lemp->nsymbol; i++){
2982 int j;
2983 struct symbol *sp;
2984
2985 sp = lemp->symbols[i];
2986 fprintf(fp, " %3d: %s", i, sp->name);
2987 if( sp->type==NONTERMINAL ){
2988 fprintf(fp, ":");
2989 if( sp->lambda ){
2990 fprintf(fp, " <lambda>");
2991 }
2992 for(j=0; j<lemp->nterminal; j++){
2993 if( sp->firstset && SetFind(sp->firstset, j) ){
2994 fprintf(fp, " %s", lemp->symbols[j]->name);
2995 }
2996 }
2997 }
2998 fprintf(fp, "\n");
2999 }
drh75897232000-05-29 14:26:00 +00003000 fclose(fp);
3001 return;
3002}
3003
3004/* Search for the file "name" which is in the same directory as
3005** the exacutable */
3006PRIVATE char *pathsearch(argv0,name,modemask)
3007char *argv0;
3008char *name;
3009int modemask;
3010{
3011 char *pathlist;
3012 char *path,*cp;
3013 char c;
drh75897232000-05-29 14:26:00 +00003014
3015#ifdef __WIN32__
3016 cp = strrchr(argv0,'\\');
3017#else
3018 cp = strrchr(argv0,'/');
3019#endif
3020 if( cp ){
3021 c = *cp;
3022 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003023 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003024 if( path ) sprintf(path,"%s/%s",argv0,name);
3025 *cp = c;
3026 }else{
3027 extern char *getenv();
3028 pathlist = getenv("PATH");
3029 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00003030 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00003031 if( path!=0 ){
3032 while( *pathlist ){
3033 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00003034 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00003035 c = *cp;
3036 *cp = 0;
3037 sprintf(path,"%s/%s",pathlist,name);
3038 *cp = c;
3039 if( c==0 ) pathlist = "";
3040 else pathlist = &cp[1];
3041 if( access(path,modemask)==0 ) break;
3042 }
3043 }
3044 }
3045 return path;
3046}
3047
3048/* Given an action, compute the integer value for that action
3049** which is to be put in the action table of the generated machine.
3050** Return negative if no action should be generated.
3051*/
3052PRIVATE int compute_action(lemp,ap)
3053struct lemon *lemp;
3054struct action *ap;
3055{
3056 int act;
3057 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003058 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003059 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3060 case ERROR: act = lemp->nstate + lemp->nrule; break;
3061 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3062 default: act = -1; break;
3063 }
3064 return act;
3065}
3066
3067#define LINESIZE 1000
3068/* The next cluster of routines are for reading the template file
3069** and writing the results to the generated parser */
3070/* The first function transfers data from "in" to "out" until
3071** a line is seen which begins with "%%". The line number is
3072** tracked.
3073**
3074** if name!=0, then any word that begin with "Parse" is changed to
3075** begin with *name instead.
3076*/
3077PRIVATE void tplt_xfer(name,in,out,lineno)
3078char *name;
3079FILE *in;
3080FILE *out;
3081int *lineno;
3082{
3083 int i, iStart;
3084 char line[LINESIZE];
3085 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3086 (*lineno)++;
3087 iStart = 0;
3088 if( name ){
3089 for(i=0; line[i]; i++){
3090 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3091 && (i==0 || !isalpha(line[i-1]))
3092 ){
3093 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3094 fprintf(out,"%s",name);
3095 i += 4;
3096 iStart = i+1;
3097 }
3098 }
3099 }
3100 fprintf(out,"%s",&line[iStart]);
3101 }
3102}
3103
3104/* The next function finds the template file and opens it, returning
3105** a pointer to the opened file. */
3106PRIVATE FILE *tplt_open(lemp)
3107struct lemon *lemp;
3108{
3109 static char templatename[] = "lempar.c";
3110 char buf[1000];
3111 FILE *in;
3112 char *tpltname;
3113 char *cp;
3114
3115 cp = strrchr(lemp->filename,'.');
3116 if( cp ){
drh8b582012003-10-21 13:16:03 +00003117 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003118 }else{
3119 sprintf(buf,"%s.lt",lemp->filename);
3120 }
3121 if( access(buf,004)==0 ){
3122 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003123 }else if( access(templatename,004)==0 ){
3124 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003125 }else{
3126 tpltname = pathsearch(lemp->argv0,templatename,0);
3127 }
3128 if( tpltname==0 ){
3129 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3130 templatename);
3131 lemp->errorcnt++;
3132 return 0;
3133 }
drh2aa6ca42004-09-10 00:14:04 +00003134 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003135 if( in==0 ){
3136 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3137 lemp->errorcnt++;
3138 return 0;
3139 }
3140 return in;
3141}
3142
drhaf805ca2004-09-07 11:28:25 +00003143/* Print a #line directive line to the output file. */
3144PRIVATE void tplt_linedir(out,lineno,filename)
3145FILE *out;
3146int lineno;
3147char *filename;
3148{
3149 fprintf(out,"#line %d \"",lineno);
3150 while( *filename ){
3151 if( *filename == '\\' ) putc('\\',out);
3152 putc(*filename,out);
3153 filename++;
3154 }
3155 fprintf(out,"\"\n");
3156}
3157
drh75897232000-05-29 14:26:00 +00003158/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003159PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003160FILE *out;
3161struct lemon *lemp;
3162char *str;
drh75897232000-05-29 14:26:00 +00003163int *lineno;
3164{
3165 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003166 while( *str ){
drh75897232000-05-29 14:26:00 +00003167 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003168 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003169 str++;
3170 }
drh9db55df2004-09-09 14:01:21 +00003171 if( str[-1]!='\n' ){
3172 putc('\n',out);
3173 (*lineno)++;
3174 }
shane58543932008-12-10 20:10:04 +00003175 if (!lemp->nolinenosflag) {
3176 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3177 }
drh75897232000-05-29 14:26:00 +00003178 return;
3179}
3180
3181/*
3182** The following routine emits code for the destructor for the
3183** symbol sp
3184*/
3185void emit_destructor_code(out,sp,lemp,lineno)
3186FILE *out;
3187struct symbol *sp;
3188struct lemon *lemp;
3189int *lineno;
3190{
drhcc83b6e2004-04-23 23:38:42 +00003191 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003192
drh75897232000-05-29 14:26:00 +00003193 if( sp->type==TERMINAL ){
3194 cp = lemp->tokendest;
3195 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003196 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003197 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003198 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003199 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003200 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003201 }else if( lemp->vardest ){
3202 cp = lemp->vardest;
3203 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003204 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003205 }else{
3206 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003207 }
3208 for(; *cp; cp++){
3209 if( *cp=='$' && cp[1]=='$' ){
3210 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3211 cp++;
3212 continue;
3213 }
shane58543932008-12-10 20:10:04 +00003214 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003215 fputc(*cp,out);
3216 }
shane58543932008-12-10 20:10:04 +00003217 fprintf(out,"\n"); (*lineno)++;
3218 if (!lemp->nolinenosflag) {
3219 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3220 }
3221 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003222 return;
3223}
3224
3225/*
drh960e8c62001-04-03 16:53:21 +00003226** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003227*/
3228int has_destructor(sp, lemp)
3229struct symbol *sp;
3230struct lemon *lemp;
3231{
3232 int ret;
3233 if( sp->type==TERMINAL ){
3234 ret = lemp->tokendest!=0;
3235 }else{
drh960e8c62001-04-03 16:53:21 +00003236 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003237 }
3238 return ret;
3239}
3240
drh0bb132b2004-07-20 14:06:51 +00003241/*
3242** Append text to a dynamically allocated string. If zText is 0 then
3243** reset the string to be empty again. Always return the complete text
3244** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003245**
3246** n bytes of zText are stored. If n==0 then all of zText up to the first
3247** \000 terminator is stored. zText can contain up to two instances of
3248** %d. The values of p1 and p2 are written into the first and second
3249** %d.
3250**
3251** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003252*/
3253PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3254 static char *z = 0;
3255 static int alloced = 0;
3256 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003257 int c;
drh0bb132b2004-07-20 14:06:51 +00003258 char zInt[40];
3259
3260 if( zText==0 ){
3261 used = 0;
3262 return z;
3263 }
drh7ac25c72004-08-19 15:12:26 +00003264 if( n<=0 ){
3265 if( n<0 ){
3266 used += n;
3267 assert( used>=0 );
3268 }
drh87cf1372008-08-13 20:09:06 +00003269 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003270 }
drh0bb132b2004-07-20 14:06:51 +00003271 if( n+sizeof(zInt)*2+used >= alloced ){
3272 alloced = n + sizeof(zInt)*2 + used + 200;
3273 z = realloc(z, alloced);
3274 }
3275 if( z==0 ) return "";
3276 while( n-- > 0 ){
3277 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003278 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003279 sprintf(zInt, "%d", p1);
3280 p1 = p2;
3281 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003282 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003283 zText++;
3284 n--;
3285 }else{
3286 z[used++] = c;
3287 }
3288 }
3289 z[used] = 0;
3290 return z;
3291}
3292
3293/*
3294** zCode is a string that is the action associated with a rule. Expand
3295** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003296** stack.
drh0bb132b2004-07-20 14:06:51 +00003297*/
drhaf805ca2004-09-07 11:28:25 +00003298PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003299 char *cp, *xp;
3300 int i;
3301 char lhsused = 0; /* True if the LHS element has been used */
3302 char used[MAXRHS]; /* True for each RHS element which is used */
3303
3304 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3305 lhsused = 0;
3306
drh19c9e562007-03-29 20:13:53 +00003307 if( rp->code==0 ){
3308 rp->code = "\n";
3309 rp->line = rp->ruleline;
3310 }
3311
drh0bb132b2004-07-20 14:06:51 +00003312 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003313 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003314 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3315 char saved;
3316 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3317 saved = *xp;
3318 *xp = 0;
3319 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003320 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003321 cp = xp;
3322 lhsused = 1;
3323 }else{
3324 for(i=0; i<rp->nrhs; i++){
3325 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003326 if( cp!=rp->code && cp[-1]=='@' ){
3327 /* If the argument is of the form @X then substituted
3328 ** the token number of X, not the value of X */
3329 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3330 }else{
drhfd405312005-11-06 04:06:59 +00003331 struct symbol *sp = rp->rhs[i];
3332 int dtnum;
3333 if( sp->type==MULTITERMINAL ){
3334 dtnum = sp->subsym[0]->dtnum;
3335 }else{
3336 dtnum = sp->dtnum;
3337 }
3338 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003339 }
drh0bb132b2004-07-20 14:06:51 +00003340 cp = xp;
3341 used[i] = 1;
3342 break;
3343 }
3344 }
3345 }
3346 *xp = saved;
3347 }
3348 append_str(cp, 1, 0, 0);
3349 } /* End loop */
3350
3351 /* Check to make sure the LHS has been used */
3352 if( rp->lhsalias && !lhsused ){
3353 ErrorMsg(lemp->filename,rp->ruleline,
3354 "Label \"%s\" for \"%s(%s)\" is never used.",
3355 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3356 lemp->errorcnt++;
3357 }
3358
3359 /* Generate destructor code for RHS symbols which are not used in the
3360 ** reduce code */
3361 for(i=0; i<rp->nrhs; i++){
3362 if( rp->rhsalias[i] && !used[i] ){
3363 ErrorMsg(lemp->filename,rp->ruleline,
3364 "Label %s for \"%s(%s)\" is never used.",
3365 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3366 lemp->errorcnt++;
3367 }else if( rp->rhsalias[i]==0 ){
3368 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003369 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003370 rp->rhs[i]->index,i-rp->nrhs+1);
3371 }else{
3372 /* No destructor defined for this term */
3373 }
3374 }
3375 }
drh61e339a2007-01-16 03:09:02 +00003376 if( rp->code ){
3377 cp = append_str(0,0,0,0);
3378 rp->code = Strsafe(cp?cp:"");
3379 }
drh0bb132b2004-07-20 14:06:51 +00003380}
3381
drh75897232000-05-29 14:26:00 +00003382/*
3383** Generate code which executes when the rule "rp" is reduced. Write
3384** the code to "out". Make sure lineno stays up-to-date.
3385*/
3386PRIVATE void emit_code(out,rp,lemp,lineno)
3387FILE *out;
3388struct rule *rp;
3389struct lemon *lemp;
3390int *lineno;
3391{
drh0bb132b2004-07-20 14:06:51 +00003392 char *cp;
drh75897232000-05-29 14:26:00 +00003393
3394 /* Generate code to do the reduce action */
3395 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003396 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003397 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003398 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003399 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003400 } /* End loop */
shane58543932008-12-10 20:10:04 +00003401 fprintf(out,"}\n"); (*lineno)++;
3402 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003403 } /* End if( rp->code ) */
3404
drh75897232000-05-29 14:26:00 +00003405 return;
3406}
3407
3408/*
3409** Print the definition of the union used for the parser's data stack.
3410** This union contains fields for every possible data type for tokens
3411** and nonterminals. In the process of computing and printing this
3412** union, also set the ".dtnum" field of every terminal and nonterminal
3413** symbol.
3414*/
3415void print_stack_union(out,lemp,plineno,mhflag)
3416FILE *out; /* The output stream */
3417struct lemon *lemp; /* The main info structure for this parser */
3418int *plineno; /* Pointer to the line number */
3419int mhflag; /* True if generating makeheaders output */
3420{
3421 int lineno = *plineno; /* The line number of the output */
3422 char **types; /* A hash table of datatypes */
3423 int arraysize; /* Size of the "types" array */
3424 int maxdtlength; /* Maximum length of any ".datatype" field. */
3425 char *stddt; /* Standardized name for a datatype */
3426 int i,j; /* Loop counters */
3427 int hash; /* For hashing the name of a type */
3428 char *name; /* Name of the parser */
3429
3430 /* Allocate and initialize types[] and allocate stddt[] */
3431 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003432 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003433 for(i=0; i<arraysize; i++) types[i] = 0;
3434 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003435 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003436 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003437 }
drh75897232000-05-29 14:26:00 +00003438 for(i=0; i<lemp->nsymbol; i++){
3439 int len;
3440 struct symbol *sp = lemp->symbols[i];
3441 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003442 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003443 if( len>maxdtlength ) maxdtlength = len;
3444 }
3445 stddt = (char*)malloc( maxdtlength*2 + 1 );
3446 if( types==0 || stddt==0 ){
3447 fprintf(stderr,"Out of memory.\n");
3448 exit(1);
3449 }
3450
3451 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3452 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003453 ** used for terminal symbols. If there is no %default_type defined then
3454 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3455 ** a datatype using the %type directive.
3456 */
drh75897232000-05-29 14:26:00 +00003457 for(i=0; i<lemp->nsymbol; i++){
3458 struct symbol *sp = lemp->symbols[i];
3459 char *cp;
3460 if( sp==lemp->errsym ){
3461 sp->dtnum = arraysize+1;
3462 continue;
3463 }
drh960e8c62001-04-03 16:53:21 +00003464 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003465 sp->dtnum = 0;
3466 continue;
3467 }
3468 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003469 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003470 j = 0;
3471 while( isspace(*cp) ) cp++;
3472 while( *cp ) stddt[j++] = *cp++;
3473 while( j>0 && isspace(stddt[j-1]) ) j--;
3474 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003475 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003476 sp->dtnum = 0;
3477 continue;
3478 }
drh75897232000-05-29 14:26:00 +00003479 hash = 0;
3480 for(j=0; stddt[j]; j++){
3481 hash = hash*53 + stddt[j];
3482 }
drh3b2129c2003-05-13 00:34:21 +00003483 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003484 while( types[hash] ){
3485 if( strcmp(types[hash],stddt)==0 ){
3486 sp->dtnum = hash + 1;
3487 break;
3488 }
3489 hash++;
3490 if( hash>=arraysize ) hash = 0;
3491 }
3492 if( types[hash]==0 ){
3493 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003494 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003495 if( types[hash]==0 ){
3496 fprintf(stderr,"Out of memory.\n");
3497 exit(1);
3498 }
3499 strcpy(types[hash],stddt);
3500 }
3501 }
3502
3503 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3504 name = lemp->name ? lemp->name : "Parse";
3505 lineno = *plineno;
3506 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3507 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3508 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3509 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3510 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003511 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003512 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3513 for(i=0; i<arraysize; i++){
3514 if( types[i]==0 ) continue;
3515 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3516 free(types[i]);
3517 }
drhc4dd3fd2008-01-22 01:48:05 +00003518 if( lemp->errsym->useCnt ){
3519 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3520 }
drh75897232000-05-29 14:26:00 +00003521 free(stddt);
3522 free(types);
3523 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3524 *plineno = lineno;
3525}
3526
drhb29b0a52002-02-23 19:39:46 +00003527/*
3528** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003529** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003530*/
drh8b582012003-10-21 13:16:03 +00003531static const char *minimum_size_type(int lwr, int upr){
3532 if( lwr>=0 ){
3533 if( upr<=255 ){
3534 return "unsigned char";
3535 }else if( upr<65535 ){
3536 return "unsigned short int";
3537 }else{
3538 return "unsigned int";
3539 }
3540 }else if( lwr>=-127 && upr<=127 ){
3541 return "signed char";
3542 }else if( lwr>=-32767 && upr<32767 ){
3543 return "short";
drhb29b0a52002-02-23 19:39:46 +00003544 }else{
drh8b582012003-10-21 13:16:03 +00003545 return "int";
drhb29b0a52002-02-23 19:39:46 +00003546 }
3547}
3548
drhfdbf9282003-10-21 16:34:41 +00003549/*
3550** Each state contains a set of token transaction and a set of
3551** nonterminal transactions. Each of these sets makes an instance
3552** of the following structure. An array of these structures is used
3553** to order the creation of entries in the yy_action[] table.
3554*/
3555struct axset {
3556 struct state *stp; /* A pointer to a state */
3557 int isTkn; /* True to use tokens. False for non-terminals */
3558 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003559 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003560};
3561
3562/*
3563** Compare to axset structures for sorting purposes
3564*/
3565static int axset_compare(const void *a, const void *b){
3566 struct axset *p1 = (struct axset*)a;
3567 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003568 int c;
3569 c = p2->nAction - p1->nAction;
3570 if( c==0 ){
3571 c = p2->iOrder - p1->iOrder;
3572 }
3573 assert( c!=0 || p1==p2 );
3574 return c;
drhfdbf9282003-10-21 16:34:41 +00003575}
3576
drhc4dd3fd2008-01-22 01:48:05 +00003577/*
3578** Write text on "out" that describes the rule "rp".
3579*/
3580static void writeRuleText(FILE *out, struct rule *rp){
3581 int j;
3582 fprintf(out,"%s ::=", rp->lhs->name);
3583 for(j=0; j<rp->nrhs; j++){
3584 struct symbol *sp = rp->rhs[j];
3585 fprintf(out," %s", sp->name);
3586 if( sp->type==MULTITERMINAL ){
3587 int k;
3588 for(k=1; k<sp->nsubsym; k++){
3589 fprintf(out,"|%s",sp->subsym[k]->name);
3590 }
3591 }
3592 }
3593}
3594
3595
drh75897232000-05-29 14:26:00 +00003596/* Generate C source code for the parser */
3597void ReportTable(lemp, mhflag)
3598struct lemon *lemp;
3599int mhflag; /* Output in makeheaders format if true */
3600{
3601 FILE *out, *in;
3602 char line[LINESIZE];
3603 int lineno;
3604 struct state *stp;
3605 struct action *ap;
3606 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003607 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003608 int i, j, k, n;
drh75897232000-05-29 14:26:00 +00003609 char *name;
drh8b582012003-10-21 13:16:03 +00003610 int mnTknOfst, mxTknOfst;
3611 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003612 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003613
3614 in = tplt_open(lemp);
3615 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003616 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003617 if( out==0 ){
3618 fclose(in);
3619 return;
3620 }
3621 lineno = 1;
3622 tplt_xfer(lemp->name,in,out,&lineno);
3623
3624 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003625 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003626 if( mhflag ){
3627 char *name = file_makename(lemp, ".h");
3628 fprintf(out,"#include \"%s\"\n", name); lineno++;
3629 free(name);
3630 }
3631 tplt_xfer(lemp->name,in,out,&lineno);
3632
3633 /* Generate #defines for all tokens */
3634 if( mhflag ){
3635 char *prefix;
3636 fprintf(out,"#if INTERFACE\n"); lineno++;
3637 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3638 else prefix = "";
3639 for(i=1; i<lemp->nterminal; i++){
3640 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3641 lineno++;
3642 }
3643 fprintf(out,"#endif\n"); lineno++;
3644 }
3645 tplt_xfer(lemp->name,in,out,&lineno);
3646
3647 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003648 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003649 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003650 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3651 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003652 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003653 if( lemp->wildcard ){
3654 fprintf(out,"#define YYWILDCARD %d\n",
3655 lemp->wildcard->index); lineno++;
3656 }
drh75897232000-05-29 14:26:00 +00003657 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003658 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003659 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003660 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3661 }else{
3662 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3663 }
drhca44b5a2007-02-22 23:06:58 +00003664 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003665 if( mhflag ){
3666 fprintf(out,"#if INTERFACE\n"); lineno++;
3667 }
3668 name = lemp->name ? lemp->name : "Parse";
3669 if( lemp->arg && lemp->arg[0] ){
3670 int i;
drh87cf1372008-08-13 20:09:06 +00003671 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003672 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3673 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003674 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3675 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3676 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3677 name,lemp->arg,&lemp->arg[i]); lineno++;
3678 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3679 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003680 }else{
drh1f245e42002-03-11 13:55:50 +00003681 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3682 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3683 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3684 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003685 }
3686 if( mhflag ){
3687 fprintf(out,"#endif\n"); lineno++;
3688 }
3689 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3690 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003691 if( lemp->errsym->useCnt ){
3692 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3693 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3694 }
drh0bd1f4e2002-06-06 18:54:39 +00003695 if( lemp->has_fallback ){
3696 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3697 }
drh75897232000-05-29 14:26:00 +00003698 tplt_xfer(lemp->name,in,out,&lineno);
3699
drh8b582012003-10-21 13:16:03 +00003700 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003701 **
drh8b582012003-10-21 13:16:03 +00003702 ** yy_action[] A single table containing all actions.
3703 ** yy_lookahead[] A table containing the lookahead for each entry in
3704 ** yy_action. Used to detect hash collisions.
3705 ** yy_shift_ofst[] For each state, the offset into yy_action for
3706 ** shifting terminals.
3707 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3708 ** shifting non-terminals after a reduce.
3709 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003710 */
drh75897232000-05-29 14:26:00 +00003711
drh8b582012003-10-21 13:16:03 +00003712 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003713 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003714 if( ax==0 ){
3715 fprintf(stderr,"malloc failed\n");
3716 exit(1);
3717 }
drh75897232000-05-29 14:26:00 +00003718 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003719 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003720 ax[i*2].stp = stp;
3721 ax[i*2].isTkn = 1;
3722 ax[i*2].nAction = stp->nTknAct;
3723 ax[i*2+1].stp = stp;
3724 ax[i*2+1].isTkn = 0;
3725 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003726 }
drh8b582012003-10-21 13:16:03 +00003727 mxTknOfst = mnTknOfst = 0;
3728 mxNtOfst = mnNtOfst = 0;
3729
drhfdbf9282003-10-21 16:34:41 +00003730 /* Compute the action table. In order to try to keep the size of the
3731 ** action table to a minimum, the heuristic of placing the largest action
3732 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003733 */
drhe594bc32009-11-03 13:02:25 +00003734 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003735 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003736 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003737 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3738 stp = ax[i].stp;
3739 if( ax[i].isTkn ){
3740 for(ap=stp->ap; ap; ap=ap->next){
3741 int action;
3742 if( ap->sp->index>=lemp->nterminal ) continue;
3743 action = compute_action(lemp, ap);
3744 if( action<0 ) continue;
3745 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003746 }
drhfdbf9282003-10-21 16:34:41 +00003747 stp->iTknOfst = acttab_insert(pActtab);
3748 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3749 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3750 }else{
3751 for(ap=stp->ap; ap; ap=ap->next){
3752 int action;
3753 if( ap->sp->index<lemp->nterminal ) continue;
3754 if( ap->sp->index==lemp->nsymbol ) continue;
3755 action = compute_action(lemp, ap);
3756 if( action<0 ) continue;
3757 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003758 }
drhfdbf9282003-10-21 16:34:41 +00003759 stp->iNtOfst = acttab_insert(pActtab);
3760 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3761 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003762 }
3763 }
drhfdbf9282003-10-21 16:34:41 +00003764 free(ax);
drh8b582012003-10-21 13:16:03 +00003765
3766 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003767 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003768 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3769 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003770 for(i=j=0; i<n; i++){
3771 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003772 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003773 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003774 fprintf(out, " %4d,", action);
3775 if( j==9 || i==n-1 ){
3776 fprintf(out, "\n"); lineno++;
3777 j = 0;
3778 }else{
3779 j++;
3780 }
3781 }
3782 fprintf(out, "};\n"); lineno++;
3783
3784 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003785 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003786 for(i=j=0; i<n; i++){
3787 int la = acttab_yylookahead(pActtab, i);
3788 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003789 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003790 fprintf(out, " %4d,", la);
3791 if( j==9 || i==n-1 ){
3792 fprintf(out, "\n"); lineno++;
3793 j = 0;
3794 }else{
3795 j++;
3796 }
3797 }
3798 fprintf(out, "};\n"); lineno++;
3799
3800 /* Output the yy_shift_ofst[] table */
3801 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003802 n = lemp->nstate;
3803 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003804 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3805 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3806 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003807 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003808 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003809 for(i=j=0; i<n; i++){
3810 int ofst;
3811 stp = lemp->sorted[i];
3812 ofst = stp->iTknOfst;
3813 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003814 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003815 fprintf(out, " %4d,", ofst);
3816 if( j==9 || i==n-1 ){
3817 fprintf(out, "\n"); lineno++;
3818 j = 0;
3819 }else{
3820 j++;
3821 }
3822 }
3823 fprintf(out, "};\n"); lineno++;
3824
3825 /* Output the yy_reduce_ofst[] table */
3826 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003827 n = lemp->nstate;
3828 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003829 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3830 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3831 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003832 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003833 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003834 for(i=j=0; i<n; i++){
3835 int ofst;
3836 stp = lemp->sorted[i];
3837 ofst = stp->iNtOfst;
3838 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003839 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003840 fprintf(out, " %4d,", ofst);
3841 if( j==9 || i==n-1 ){
3842 fprintf(out, "\n"); lineno++;
3843 j = 0;
3844 }else{
3845 j++;
3846 }
3847 }
3848 fprintf(out, "};\n"); lineno++;
3849
3850 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003851 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003852 n = lemp->nstate;
3853 for(i=j=0; i<n; i++){
3854 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003855 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003856 fprintf(out, " %4d,", stp->iDflt);
3857 if( j==9 || i==n-1 ){
3858 fprintf(out, "\n"); lineno++;
3859 j = 0;
3860 }else{
3861 j++;
3862 }
3863 }
3864 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003865 tplt_xfer(lemp->name,in,out,&lineno);
3866
drh0bd1f4e2002-06-06 18:54:39 +00003867 /* Generate the table of fallback tokens.
3868 */
3869 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003870 int mx = lemp->nterminal - 1;
3871 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3872 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003873 struct symbol *p = lemp->symbols[i];
3874 if( p->fallback==0 ){
3875 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3876 }else{
3877 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3878 p->name, p->fallback->name);
3879 }
3880 lineno++;
3881 }
3882 }
3883 tplt_xfer(lemp->name, in, out, &lineno);
3884
3885 /* Generate a table containing the symbolic name of every symbol
3886 */
drh75897232000-05-29 14:26:00 +00003887 for(i=0; i<lemp->nsymbol; i++){
3888 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3889 fprintf(out," %-15s",line);
3890 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3891 }
3892 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3893 tplt_xfer(lemp->name,in,out,&lineno);
3894
drh0bd1f4e2002-06-06 18:54:39 +00003895 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003896 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003897 ** when tracing REDUCE actions.
3898 */
3899 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3900 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003901 fprintf(out," /* %3d */ \"", i);
3902 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003903 fprintf(out,"\",\n"); lineno++;
3904 }
3905 tplt_xfer(lemp->name,in,out,&lineno);
3906
drh75897232000-05-29 14:26:00 +00003907 /* Generate code which executes every time a symbol is popped from
3908 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003909 ** (In other words, generate the %destructor actions)
3910 */
drh75897232000-05-29 14:26:00 +00003911 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003912 int once = 1;
drh75897232000-05-29 14:26:00 +00003913 for(i=0; i<lemp->nsymbol; i++){
3914 struct symbol *sp = lemp->symbols[i];
3915 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003916 if( once ){
3917 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3918 once = 0;
3919 }
drhc53eed12009-06-12 17:46:19 +00003920 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003921 }
3922 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3923 if( i<lemp->nsymbol ){
3924 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3925 fprintf(out," break;\n"); lineno++;
3926 }
3927 }
drh8d659732005-01-13 23:54:06 +00003928 if( lemp->vardest ){
3929 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003930 int once = 1;
drh8d659732005-01-13 23:54:06 +00003931 for(i=0; i<lemp->nsymbol; i++){
3932 struct symbol *sp = lemp->symbols[i];
3933 if( sp==0 || sp->type==TERMINAL ||
3934 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003935 if( once ){
3936 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3937 once = 0;
3938 }
drhc53eed12009-06-12 17:46:19 +00003939 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003940 dflt_sp = sp;
3941 }
3942 if( dflt_sp!=0 ){
3943 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003944 }
drh4dc8ef52008-07-01 17:13:57 +00003945 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003946 }
drh75897232000-05-29 14:26:00 +00003947 for(i=0; i<lemp->nsymbol; i++){
3948 struct symbol *sp = lemp->symbols[i];
3949 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003950 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003951
3952 /* Combine duplicate destructors into a single case */
3953 for(j=i+1; j<lemp->nsymbol; j++){
3954 struct symbol *sp2 = lemp->symbols[j];
3955 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3956 && sp2->dtnum==sp->dtnum
3957 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003958 fprintf(out," case %d: /* %s */\n",
3959 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003960 sp2->destructor = 0;
3961 }
3962 }
3963
drh75897232000-05-29 14:26:00 +00003964 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3965 fprintf(out," break;\n"); lineno++;
3966 }
drh75897232000-05-29 14:26:00 +00003967 tplt_xfer(lemp->name,in,out,&lineno);
3968
3969 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003970 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003971 tplt_xfer(lemp->name,in,out,&lineno);
3972
3973 /* Generate the table of rule information
3974 **
3975 ** Note: This code depends on the fact that rules are number
3976 ** sequentually beginning with 0.
3977 */
3978 for(rp=lemp->rule; rp; rp=rp->next){
3979 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3980 }
3981 tplt_xfer(lemp->name,in,out,&lineno);
3982
3983 /* Generate code which execution during each REDUCE action */
3984 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003985 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003986 }
drhc53eed12009-06-12 17:46:19 +00003987 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003988 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003989 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003990 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003991 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003992 fprintf(out," case %d: /* ", rp->index);
3993 writeRuleText(out, rp);
3994 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003995 for(rp2=rp->next; rp2; rp2=rp2->next){
3996 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003997 fprintf(out," case %d: /* ", rp2->index);
3998 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003999 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004000 rp2->code = 0;
4001 }
4002 }
drh75897232000-05-29 14:26:00 +00004003 emit_code(out,rp,lemp,&lineno);
4004 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004005 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004006 }
drhc53eed12009-06-12 17:46:19 +00004007 /* Finally, output the default: rule. We choose as the default: all
4008 ** empty actions. */
4009 fprintf(out," default:\n"); lineno++;
4010 for(rp=lemp->rule; rp; rp=rp->next){
4011 if( rp->code==0 ) continue;
4012 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4013 fprintf(out," /* (%d) ", rp->index);
4014 writeRuleText(out, rp);
4015 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4016 }
4017 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004018 tplt_xfer(lemp->name,in,out,&lineno);
4019
4020 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004021 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004022 tplt_xfer(lemp->name,in,out,&lineno);
4023
4024 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004025 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004026 tplt_xfer(lemp->name,in,out,&lineno);
4027
4028 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004029 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004030 tplt_xfer(lemp->name,in,out,&lineno);
4031
4032 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004033 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004034
4035 fclose(in);
4036 fclose(out);
4037 return;
4038}
4039
4040/* Generate a header file for the parser */
4041void ReportHeader(lemp)
4042struct lemon *lemp;
4043{
4044 FILE *out, *in;
4045 char *prefix;
4046 char line[LINESIZE];
4047 char pattern[LINESIZE];
4048 int i;
4049
4050 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4051 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004052 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004053 if( in ){
4054 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4055 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4056 if( strcmp(line,pattern) ) break;
4057 }
4058 fclose(in);
4059 if( i==lemp->nterminal ){
4060 /* No change in the file. Don't rewrite it. */
4061 return;
4062 }
4063 }
drh2aa6ca42004-09-10 00:14:04 +00004064 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004065 if( out ){
4066 for(i=1; i<lemp->nterminal; i++){
4067 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4068 }
4069 fclose(out);
4070 }
4071 return;
4072}
4073
4074/* Reduce the size of the action tables, if possible, by making use
4075** of defaults.
4076**
drhb59499c2002-02-23 18:45:13 +00004077** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004078** it the default. Except, there is no default if the wildcard token
4079** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004080*/
4081void CompressTables(lemp)
4082struct lemon *lemp;
4083{
4084 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004085 struct action *ap, *ap2;
4086 struct rule *rp, *rp2, *rbest;
4087 int nbest, n;
drh75897232000-05-29 14:26:00 +00004088 int i;
drhe09daa92006-06-10 13:29:31 +00004089 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004090
4091 for(i=0; i<lemp->nstate; i++){
4092 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004093 nbest = 0;
4094 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004095 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004096
drhb59499c2002-02-23 18:45:13 +00004097 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004098 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4099 usesWildcard = 1;
4100 }
drhb59499c2002-02-23 18:45:13 +00004101 if( ap->type!=REDUCE ) continue;
4102 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004103 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004104 if( rp==rbest ) continue;
4105 n = 1;
4106 for(ap2=ap->next; ap2; ap2=ap2->next){
4107 if( ap2->type!=REDUCE ) continue;
4108 rp2 = ap2->x.rp;
4109 if( rp2==rbest ) continue;
4110 if( rp2==rp ) n++;
4111 }
4112 if( n>nbest ){
4113 nbest = n;
4114 rbest = rp;
drh75897232000-05-29 14:26:00 +00004115 }
4116 }
drhb59499c2002-02-23 18:45:13 +00004117
4118 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004119 ** is not at least 1 or if the wildcard token is a possible
4120 ** lookahead.
4121 */
4122 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004123
drhb59499c2002-02-23 18:45:13 +00004124
4125 /* Combine matching REDUCE actions into a single default */
4126 for(ap=stp->ap; ap; ap=ap->next){
4127 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4128 }
drh75897232000-05-29 14:26:00 +00004129 assert( ap );
4130 ap->sp = Symbol_new("{default}");
4131 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004132 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004133 }
4134 stp->ap = Action_sort(stp->ap);
4135 }
4136}
drhb59499c2002-02-23 18:45:13 +00004137
drhada354d2005-11-05 15:03:59 +00004138
4139/*
4140** Compare two states for sorting purposes. The smaller state is the
4141** one with the most non-terminal actions. If they have the same number
4142** of non-terminal actions, then the smaller is the one with the most
4143** token actions.
4144*/
4145static int stateResortCompare(const void *a, const void *b){
4146 const struct state *pA = *(const struct state**)a;
4147 const struct state *pB = *(const struct state**)b;
4148 int n;
4149
4150 n = pB->nNtAct - pA->nNtAct;
4151 if( n==0 ){
4152 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004153 if( n==0 ){
4154 n = pB->statenum - pA->statenum;
4155 }
drhada354d2005-11-05 15:03:59 +00004156 }
drhe594bc32009-11-03 13:02:25 +00004157 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004158 return n;
4159}
4160
4161
4162/*
4163** Renumber and resort states so that states with fewer choices
4164** occur at the end. Except, keep state 0 as the first state.
4165*/
4166void ResortStates(lemp)
4167struct lemon *lemp;
4168{
4169 int i;
4170 struct state *stp;
4171 struct action *ap;
4172
4173 for(i=0; i<lemp->nstate; i++){
4174 stp = lemp->sorted[i];
4175 stp->nTknAct = stp->nNtAct = 0;
4176 stp->iDflt = lemp->nstate + lemp->nrule;
4177 stp->iTknOfst = NO_OFFSET;
4178 stp->iNtOfst = NO_OFFSET;
4179 for(ap=stp->ap; ap; ap=ap->next){
4180 if( compute_action(lemp,ap)>=0 ){
4181 if( ap->sp->index<lemp->nterminal ){
4182 stp->nTknAct++;
4183 }else if( ap->sp->index<lemp->nsymbol ){
4184 stp->nNtAct++;
4185 }else{
4186 stp->iDflt = compute_action(lemp, ap);
4187 }
4188 }
4189 }
4190 }
4191 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4192 stateResortCompare);
4193 for(i=0; i<lemp->nstate; i++){
4194 lemp->sorted[i]->statenum = i;
4195 }
4196}
4197
4198
drh75897232000-05-29 14:26:00 +00004199/***************** From the file "set.c" ************************************/
4200/*
4201** Set manipulation routines for the LEMON parser generator.
4202*/
4203
4204static int size = 0;
4205
4206/* Set the set size */
4207void SetSize(n)
4208int n;
4209{
4210 size = n+1;
4211}
4212
4213/* Allocate a new set */
4214char *SetNew(){
4215 char *s;
drh9892c5d2007-12-21 00:02:11 +00004216 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004217 if( s==0 ){
4218 extern void memory_error();
4219 memory_error();
4220 }
drh75897232000-05-29 14:26:00 +00004221 return s;
4222}
4223
4224/* Deallocate a set */
4225void SetFree(s)
4226char *s;
4227{
4228 free(s);
4229}
4230
4231/* Add a new element to the set. Return TRUE if the element was added
4232** and FALSE if it was already there. */
4233int SetAdd(s,e)
4234char *s;
4235int e;
4236{
4237 int rv;
drh9892c5d2007-12-21 00:02:11 +00004238 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004239 rv = s[e];
4240 s[e] = 1;
4241 return !rv;
4242}
4243
4244/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4245int SetUnion(s1,s2)
4246char *s1;
4247char *s2;
4248{
4249 int i, progress;
4250 progress = 0;
4251 for(i=0; i<size; i++){
4252 if( s2[i]==0 ) continue;
4253 if( s1[i]==0 ){
4254 progress = 1;
4255 s1[i] = 1;
4256 }
4257 }
4258 return progress;
4259}
4260/********************** From the file "table.c" ****************************/
4261/*
4262** All code in this file has been automatically generated
4263** from a specification in the file
4264** "table.q"
4265** by the associative array code building program "aagen".
4266** Do not edit this file! Instead, edit the specification
4267** file, then rerun aagen.
4268*/
4269/*
4270** Code for processing tables in the LEMON parser generator.
4271*/
4272
4273PRIVATE int strhash(x)
4274char *x;
4275{
4276 int h = 0;
4277 while( *x) h = h*13 + *(x++);
4278 return h;
4279}
4280
4281/* Works like strdup, sort of. Save a string in malloced memory, but
4282** keep strings in a table so that the same string is not in more
4283** than one place.
4284*/
4285char *Strsafe(y)
4286char *y;
4287{
4288 char *z;
4289
drh916f75f2006-07-17 00:19:39 +00004290 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004291 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004292 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004293 strcpy(z,y);
4294 Strsafe_insert(z);
4295 }
4296 MemoryCheck(z);
4297 return z;
4298}
4299
4300/* There is one instance of the following structure for each
4301** associative array of type "x1".
4302*/
4303struct s_x1 {
4304 int size; /* The number of available slots. */
4305 /* Must be a power of 2 greater than or */
4306 /* equal to 1 */
4307 int count; /* Number of currently slots filled */
4308 struct s_x1node *tbl; /* The data stored here */
4309 struct s_x1node **ht; /* Hash table for lookups */
4310};
4311
4312/* There is one instance of this structure for every data element
4313** in an associative array of type "x1".
4314*/
4315typedef struct s_x1node {
4316 char *data; /* The data */
4317 struct s_x1node *next; /* Next entry with the same hash */
4318 struct s_x1node **from; /* Previous link */
4319} x1node;
4320
4321/* There is only one instance of the array, which is the following */
4322static struct s_x1 *x1a;
4323
4324/* Allocate a new associative array */
4325void Strsafe_init(){
4326 if( x1a ) return;
4327 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4328 if( x1a ){
4329 x1a->size = 1024;
4330 x1a->count = 0;
4331 x1a->tbl = (x1node*)malloc(
4332 (sizeof(x1node) + sizeof(x1node*))*1024 );
4333 if( x1a->tbl==0 ){
4334 free(x1a);
4335 x1a = 0;
4336 }else{
4337 int i;
4338 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4339 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4340 }
4341 }
4342}
4343/* Insert a new record into the array. Return TRUE if successful.
4344** Prior data with the same key is NOT overwritten */
4345int Strsafe_insert(data)
4346char *data;
4347{
4348 x1node *np;
4349 int h;
4350 int ph;
4351
4352 if( x1a==0 ) return 0;
4353 ph = strhash(data);
4354 h = ph & (x1a->size-1);
4355 np = x1a->ht[h];
4356 while( np ){
4357 if( strcmp(np->data,data)==0 ){
4358 /* An existing entry with the same key is found. */
4359 /* Fail because overwrite is not allows. */
4360 return 0;
4361 }
4362 np = np->next;
4363 }
4364 if( x1a->count>=x1a->size ){
4365 /* Need to make the hash table bigger */
4366 int i,size;
4367 struct s_x1 array;
4368 array.size = size = x1a->size*2;
4369 array.count = x1a->count;
4370 array.tbl = (x1node*)malloc(
4371 (sizeof(x1node) + sizeof(x1node*))*size );
4372 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4373 array.ht = (x1node**)&(array.tbl[size]);
4374 for(i=0; i<size; i++) array.ht[i] = 0;
4375 for(i=0; i<x1a->count; i++){
4376 x1node *oldnp, *newnp;
4377 oldnp = &(x1a->tbl[i]);
4378 h = strhash(oldnp->data) & (size-1);
4379 newnp = &(array.tbl[i]);
4380 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4381 newnp->next = array.ht[h];
4382 newnp->data = oldnp->data;
4383 newnp->from = &(array.ht[h]);
4384 array.ht[h] = newnp;
4385 }
4386 free(x1a->tbl);
4387 *x1a = array;
4388 }
4389 /* Insert the new data */
4390 h = ph & (x1a->size-1);
4391 np = &(x1a->tbl[x1a->count++]);
4392 np->data = data;
4393 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4394 np->next = x1a->ht[h];
4395 x1a->ht[h] = np;
4396 np->from = &(x1a->ht[h]);
4397 return 1;
4398}
4399
4400/* Return a pointer to data assigned to the given key. Return NULL
4401** if no such key. */
4402char *Strsafe_find(key)
4403char *key;
4404{
4405 int h;
4406 x1node *np;
4407
4408 if( x1a==0 ) return 0;
4409 h = strhash(key) & (x1a->size-1);
4410 np = x1a->ht[h];
4411 while( np ){
4412 if( strcmp(np->data,key)==0 ) break;
4413 np = np->next;
4414 }
4415 return np ? np->data : 0;
4416}
4417
4418/* Return a pointer to the (terminal or nonterminal) symbol "x".
4419** Create a new symbol if this is the first time "x" has been seen.
4420*/
4421struct symbol *Symbol_new(x)
4422char *x;
4423{
4424 struct symbol *sp;
4425
4426 sp = Symbol_find(x);
4427 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004428 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004429 MemoryCheck(sp);
4430 sp->name = Strsafe(x);
4431 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4432 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004433 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004434 sp->prec = -1;
4435 sp->assoc = UNK;
4436 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004437 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004438 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004439 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004440 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004441 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004442 Symbol_insert(sp,sp->name);
4443 }
drhc4dd3fd2008-01-22 01:48:05 +00004444 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004445 return sp;
4446}
4447
drh60d31652004-02-22 00:08:04 +00004448/* Compare two symbols for working purposes
4449**
4450** Symbols that begin with upper case letters (terminals or tokens)
4451** must sort before symbols that begin with lower case letters
4452** (non-terminals). Other than that, the order does not matter.
4453**
4454** We find experimentally that leaving the symbols in their original
4455** order (the order they appeared in the grammar file) gives the
4456** smallest parser tables in SQLite.
4457*/
4458int Symbolcmpp(struct symbol **a, struct symbol **b){
4459 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4460 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004461 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004462 return i1-i2;
drh75897232000-05-29 14:26:00 +00004463}
4464
4465/* There is one instance of the following structure for each
4466** associative array of type "x2".
4467*/
4468struct s_x2 {
4469 int size; /* The number of available slots. */
4470 /* Must be a power of 2 greater than or */
4471 /* equal to 1 */
4472 int count; /* Number of currently slots filled */
4473 struct s_x2node *tbl; /* The data stored here */
4474 struct s_x2node **ht; /* Hash table for lookups */
4475};
4476
4477/* There is one instance of this structure for every data element
4478** in an associative array of type "x2".
4479*/
4480typedef struct s_x2node {
4481 struct symbol *data; /* The data */
4482 char *key; /* The key */
4483 struct s_x2node *next; /* Next entry with the same hash */
4484 struct s_x2node **from; /* Previous link */
4485} x2node;
4486
4487/* There is only one instance of the array, which is the following */
4488static struct s_x2 *x2a;
4489
4490/* Allocate a new associative array */
4491void Symbol_init(){
4492 if( x2a ) return;
4493 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4494 if( x2a ){
4495 x2a->size = 128;
4496 x2a->count = 0;
4497 x2a->tbl = (x2node*)malloc(
4498 (sizeof(x2node) + sizeof(x2node*))*128 );
4499 if( x2a->tbl==0 ){
4500 free(x2a);
4501 x2a = 0;
4502 }else{
4503 int i;
4504 x2a->ht = (x2node**)&(x2a->tbl[128]);
4505 for(i=0; i<128; i++) x2a->ht[i] = 0;
4506 }
4507 }
4508}
4509/* Insert a new record into the array. Return TRUE if successful.
4510** Prior data with the same key is NOT overwritten */
4511int Symbol_insert(data,key)
4512struct symbol *data;
4513char *key;
4514{
4515 x2node *np;
4516 int h;
4517 int ph;
4518
4519 if( x2a==0 ) return 0;
4520 ph = strhash(key);
4521 h = ph & (x2a->size-1);
4522 np = x2a->ht[h];
4523 while( np ){
4524 if( strcmp(np->key,key)==0 ){
4525 /* An existing entry with the same key is found. */
4526 /* Fail because overwrite is not allows. */
4527 return 0;
4528 }
4529 np = np->next;
4530 }
4531 if( x2a->count>=x2a->size ){
4532 /* Need to make the hash table bigger */
4533 int i,size;
4534 struct s_x2 array;
4535 array.size = size = x2a->size*2;
4536 array.count = x2a->count;
4537 array.tbl = (x2node*)malloc(
4538 (sizeof(x2node) + sizeof(x2node*))*size );
4539 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4540 array.ht = (x2node**)&(array.tbl[size]);
4541 for(i=0; i<size; i++) array.ht[i] = 0;
4542 for(i=0; i<x2a->count; i++){
4543 x2node *oldnp, *newnp;
4544 oldnp = &(x2a->tbl[i]);
4545 h = strhash(oldnp->key) & (size-1);
4546 newnp = &(array.tbl[i]);
4547 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4548 newnp->next = array.ht[h];
4549 newnp->key = oldnp->key;
4550 newnp->data = oldnp->data;
4551 newnp->from = &(array.ht[h]);
4552 array.ht[h] = newnp;
4553 }
4554 free(x2a->tbl);
4555 *x2a = array;
4556 }
4557 /* Insert the new data */
4558 h = ph & (x2a->size-1);
4559 np = &(x2a->tbl[x2a->count++]);
4560 np->key = key;
4561 np->data = data;
4562 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4563 np->next = x2a->ht[h];
4564 x2a->ht[h] = np;
4565 np->from = &(x2a->ht[h]);
4566 return 1;
4567}
4568
4569/* Return a pointer to data assigned to the given key. Return NULL
4570** if no such key. */
4571struct symbol *Symbol_find(key)
4572char *key;
4573{
4574 int h;
4575 x2node *np;
4576
4577 if( x2a==0 ) return 0;
4578 h = strhash(key) & (x2a->size-1);
4579 np = x2a->ht[h];
4580 while( np ){
4581 if( strcmp(np->key,key)==0 ) break;
4582 np = np->next;
4583 }
4584 return np ? np->data : 0;
4585}
4586
4587/* Return the n-th data. Return NULL if n is out of range. */
4588struct symbol *Symbol_Nth(n)
4589int n;
4590{
4591 struct symbol *data;
4592 if( x2a && n>0 && n<=x2a->count ){
4593 data = x2a->tbl[n-1].data;
4594 }else{
4595 data = 0;
4596 }
4597 return data;
4598}
4599
4600/* Return the size of the array */
4601int Symbol_count()
4602{
4603 return x2a ? x2a->count : 0;
4604}
4605
4606/* Return an array of pointers to all data in the table.
4607** The array is obtained from malloc. Return NULL if memory allocation
4608** problems, or if the array is empty. */
4609struct symbol **Symbol_arrayof()
4610{
4611 struct symbol **array;
4612 int i,size;
4613 if( x2a==0 ) return 0;
4614 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004615 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004616 if( array ){
4617 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4618 }
4619 return array;
4620}
4621
4622/* Compare two configurations */
4623int Configcmp(a,b)
4624struct config *a;
4625struct config *b;
4626{
4627 int x;
4628 x = a->rp->index - b->rp->index;
4629 if( x==0 ) x = a->dot - b->dot;
4630 return x;
4631}
4632
4633/* Compare two states */
4634PRIVATE int statecmp(a,b)
4635struct config *a;
4636struct config *b;
4637{
4638 int rc;
4639 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4640 rc = a->rp->index - b->rp->index;
4641 if( rc==0 ) rc = a->dot - b->dot;
4642 }
4643 if( rc==0 ){
4644 if( a ) rc = 1;
4645 if( b ) rc = -1;
4646 }
4647 return rc;
4648}
4649
4650/* Hash a state */
4651PRIVATE int statehash(a)
4652struct config *a;
4653{
4654 int h=0;
4655 while( a ){
4656 h = h*571 + a->rp->index*37 + a->dot;
4657 a = a->bp;
4658 }
4659 return h;
4660}
4661
4662/* Allocate a new state structure */
4663struct state *State_new()
4664{
4665 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004666 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004667 MemoryCheck(new);
4668 return new;
4669}
4670
4671/* There is one instance of the following structure for each
4672** associative array of type "x3".
4673*/
4674struct s_x3 {
4675 int size; /* The number of available slots. */
4676 /* Must be a power of 2 greater than or */
4677 /* equal to 1 */
4678 int count; /* Number of currently slots filled */
4679 struct s_x3node *tbl; /* The data stored here */
4680 struct s_x3node **ht; /* Hash table for lookups */
4681};
4682
4683/* There is one instance of this structure for every data element
4684** in an associative array of type "x3".
4685*/
4686typedef struct s_x3node {
4687 struct state *data; /* The data */
4688 struct config *key; /* The key */
4689 struct s_x3node *next; /* Next entry with the same hash */
4690 struct s_x3node **from; /* Previous link */
4691} x3node;
4692
4693/* There is only one instance of the array, which is the following */
4694static struct s_x3 *x3a;
4695
4696/* Allocate a new associative array */
4697void State_init(){
4698 if( x3a ) return;
4699 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4700 if( x3a ){
4701 x3a->size = 128;
4702 x3a->count = 0;
4703 x3a->tbl = (x3node*)malloc(
4704 (sizeof(x3node) + sizeof(x3node*))*128 );
4705 if( x3a->tbl==0 ){
4706 free(x3a);
4707 x3a = 0;
4708 }else{
4709 int i;
4710 x3a->ht = (x3node**)&(x3a->tbl[128]);
4711 for(i=0; i<128; i++) x3a->ht[i] = 0;
4712 }
4713 }
4714}
4715/* Insert a new record into the array. Return TRUE if successful.
4716** Prior data with the same key is NOT overwritten */
4717int State_insert(data,key)
4718struct state *data;
4719struct config *key;
4720{
4721 x3node *np;
4722 int h;
4723 int ph;
4724
4725 if( x3a==0 ) return 0;
4726 ph = statehash(key);
4727 h = ph & (x3a->size-1);
4728 np = x3a->ht[h];
4729 while( np ){
4730 if( statecmp(np->key,key)==0 ){
4731 /* An existing entry with the same key is found. */
4732 /* Fail because overwrite is not allows. */
4733 return 0;
4734 }
4735 np = np->next;
4736 }
4737 if( x3a->count>=x3a->size ){
4738 /* Need to make the hash table bigger */
4739 int i,size;
4740 struct s_x3 array;
4741 array.size = size = x3a->size*2;
4742 array.count = x3a->count;
4743 array.tbl = (x3node*)malloc(
4744 (sizeof(x3node) + sizeof(x3node*))*size );
4745 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4746 array.ht = (x3node**)&(array.tbl[size]);
4747 for(i=0; i<size; i++) array.ht[i] = 0;
4748 for(i=0; i<x3a->count; i++){
4749 x3node *oldnp, *newnp;
4750 oldnp = &(x3a->tbl[i]);
4751 h = statehash(oldnp->key) & (size-1);
4752 newnp = &(array.tbl[i]);
4753 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4754 newnp->next = array.ht[h];
4755 newnp->key = oldnp->key;
4756 newnp->data = oldnp->data;
4757 newnp->from = &(array.ht[h]);
4758 array.ht[h] = newnp;
4759 }
4760 free(x3a->tbl);
4761 *x3a = array;
4762 }
4763 /* Insert the new data */
4764 h = ph & (x3a->size-1);
4765 np = &(x3a->tbl[x3a->count++]);
4766 np->key = key;
4767 np->data = data;
4768 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4769 np->next = x3a->ht[h];
4770 x3a->ht[h] = np;
4771 np->from = &(x3a->ht[h]);
4772 return 1;
4773}
4774
4775/* Return a pointer to data assigned to the given key. Return NULL
4776** if no such key. */
4777struct state *State_find(key)
4778struct config *key;
4779{
4780 int h;
4781 x3node *np;
4782
4783 if( x3a==0 ) return 0;
4784 h = statehash(key) & (x3a->size-1);
4785 np = x3a->ht[h];
4786 while( np ){
4787 if( statecmp(np->key,key)==0 ) break;
4788 np = np->next;
4789 }
4790 return np ? np->data : 0;
4791}
4792
4793/* Return an array of pointers to all data in the table.
4794** The array is obtained from malloc. Return NULL if memory allocation
4795** problems, or if the array is empty. */
4796struct state **State_arrayof()
4797{
4798 struct state **array;
4799 int i,size;
4800 if( x3a==0 ) return 0;
4801 size = x3a->count;
4802 array = (struct state **)malloc( sizeof(struct state *)*size );
4803 if( array ){
4804 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4805 }
4806 return array;
4807}
4808
4809/* Hash a configuration */
4810PRIVATE int confighash(a)
4811struct config *a;
4812{
4813 int h=0;
4814 h = h*571 + a->rp->index*37 + a->dot;
4815 return h;
4816}
4817
4818/* There is one instance of the following structure for each
4819** associative array of type "x4".
4820*/
4821struct s_x4 {
4822 int size; /* The number of available slots. */
4823 /* Must be a power of 2 greater than or */
4824 /* equal to 1 */
4825 int count; /* Number of currently slots filled */
4826 struct s_x4node *tbl; /* The data stored here */
4827 struct s_x4node **ht; /* Hash table for lookups */
4828};
4829
4830/* There is one instance of this structure for every data element
4831** in an associative array of type "x4".
4832*/
4833typedef struct s_x4node {
4834 struct config *data; /* The data */
4835 struct s_x4node *next; /* Next entry with the same hash */
4836 struct s_x4node **from; /* Previous link */
4837} x4node;
4838
4839/* There is only one instance of the array, which is the following */
4840static struct s_x4 *x4a;
4841
4842/* Allocate a new associative array */
4843void Configtable_init(){
4844 if( x4a ) return;
4845 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4846 if( x4a ){
4847 x4a->size = 64;
4848 x4a->count = 0;
4849 x4a->tbl = (x4node*)malloc(
4850 (sizeof(x4node) + sizeof(x4node*))*64 );
4851 if( x4a->tbl==0 ){
4852 free(x4a);
4853 x4a = 0;
4854 }else{
4855 int i;
4856 x4a->ht = (x4node**)&(x4a->tbl[64]);
4857 for(i=0; i<64; i++) x4a->ht[i] = 0;
4858 }
4859 }
4860}
4861/* Insert a new record into the array. Return TRUE if successful.
4862** Prior data with the same key is NOT overwritten */
4863int Configtable_insert(data)
4864struct config *data;
4865{
4866 x4node *np;
4867 int h;
4868 int ph;
4869
4870 if( x4a==0 ) return 0;
4871 ph = confighash(data);
4872 h = ph & (x4a->size-1);
4873 np = x4a->ht[h];
4874 while( np ){
4875 if( Configcmp(np->data,data)==0 ){
4876 /* An existing entry with the same key is found. */
4877 /* Fail because overwrite is not allows. */
4878 return 0;
4879 }
4880 np = np->next;
4881 }
4882 if( x4a->count>=x4a->size ){
4883 /* Need to make the hash table bigger */
4884 int i,size;
4885 struct s_x4 array;
4886 array.size = size = x4a->size*2;
4887 array.count = x4a->count;
4888 array.tbl = (x4node*)malloc(
4889 (sizeof(x4node) + sizeof(x4node*))*size );
4890 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4891 array.ht = (x4node**)&(array.tbl[size]);
4892 for(i=0; i<size; i++) array.ht[i] = 0;
4893 for(i=0; i<x4a->count; i++){
4894 x4node *oldnp, *newnp;
4895 oldnp = &(x4a->tbl[i]);
4896 h = confighash(oldnp->data) & (size-1);
4897 newnp = &(array.tbl[i]);
4898 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4899 newnp->next = array.ht[h];
4900 newnp->data = oldnp->data;
4901 newnp->from = &(array.ht[h]);
4902 array.ht[h] = newnp;
4903 }
4904 free(x4a->tbl);
4905 *x4a = array;
4906 }
4907 /* Insert the new data */
4908 h = ph & (x4a->size-1);
4909 np = &(x4a->tbl[x4a->count++]);
4910 np->data = data;
4911 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4912 np->next = x4a->ht[h];
4913 x4a->ht[h] = np;
4914 np->from = &(x4a->ht[h]);
4915 return 1;
4916}
4917
4918/* Return a pointer to data assigned to the given key. Return NULL
4919** if no such key. */
4920struct config *Configtable_find(key)
4921struct config *key;
4922{
4923 int h;
4924 x4node *np;
4925
4926 if( x4a==0 ) return 0;
4927 h = confighash(key) & (x4a->size-1);
4928 np = x4a->ht[h];
4929 while( np ){
4930 if( Configcmp(np->data,key)==0 ) break;
4931 np = np->next;
4932 }
4933 return np ? np->data : 0;
4934}
4935
4936/* Remove all data from the table. Pass each data to the function "f"
4937** as it is removed. ("f" may be null to avoid this step.) */
4938void Configtable_clear(f)
4939int(*f)(/* struct config * */);
4940{
4941 int i;
4942 if( x4a==0 || x4a->count==0 ) return;
4943 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4944 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4945 x4a->count = 0;
4946 return;
4947}