blob: 11b474e6b1c9d93a48a4ee2a235fc314da405a01 [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
icculus3e143bd2010-02-14 00:48:49 +00001432static char *user_templatename = NULL;
1433static void handle_T_option(char *z){
1434 user_templatename = malloc( lemonStrlen(z)+1 );
1435 if( user_templatename==0 ){
1436 memory_error();
1437 }
1438 strcpy(user_templatename, z);
1439}
drh75897232000-05-29 14:26:00 +00001440
1441/* The main program. Parse the command line and do it... */
1442int main(argc,argv)
1443int argc;
1444char **argv;
1445{
1446 static int version = 0;
1447 static int rpflag = 0;
1448 static int basisflag = 0;
1449 static int compress = 0;
1450 static int quiet = 0;
1451 static int statistics = 0;
1452 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001453 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001454 static struct s_options options[] = {
1455 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1456 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001457 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001458 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001459 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001460 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1461 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001462 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001463 {OPT_FLAG, "s", (char*)&statistics,
1464 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001465 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1466 {OPT_FLAG,0,0,0}
1467 };
1468 int i;
1469 struct lemon lem;
1470
drhb0c86772000-06-02 23:21:26 +00001471 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001472 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001473 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001474 exit(0);
1475 }
drhb0c86772000-06-02 23:21:26 +00001476 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001477 fprintf(stderr,"Exactly one filename argument is required.\n");
1478 exit(1);
1479 }
drh954f6b42006-06-13 13:27:46 +00001480 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001481 lem.errorcnt = 0;
1482
1483 /* Initialize the machine */
1484 Strsafe_init();
1485 Symbol_init();
1486 State_init();
1487 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001488 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001489 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001490 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001491 Symbol_new("$");
1492 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001493 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001494
1495 /* Parse the input file */
1496 Parse(&lem);
1497 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001498 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001499 fprintf(stderr,"Empty grammar.\n");
1500 exit(1);
1501 }
1502
1503 /* Count and index the symbols of the grammar */
1504 lem.nsymbol = Symbol_count();
1505 Symbol_new("{default}");
1506 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001507 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001508 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1509 (int(*)())Symbolcmpp);
1510 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1511 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1512 lem.nterminal = i;
1513
1514 /* Generate a reprint of the grammar, if requested on the command line */
1515 if( rpflag ){
1516 Reprint(&lem);
1517 }else{
1518 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001519 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001520
1521 /* Find the precedence for every production rule (that has one) */
1522 FindRulePrecedences(&lem);
1523
1524 /* Compute the lambda-nonterminals and the first-sets for every
1525 ** nonterminal */
1526 FindFirstSets(&lem);
1527
1528 /* Compute all LR(0) states. Also record follow-set propagation
1529 ** links so that the follow-set can be computed later */
1530 lem.nstate = 0;
1531 FindStates(&lem);
1532 lem.sorted = State_arrayof();
1533
1534 /* Tie up loose ends on the propagation links */
1535 FindLinks(&lem);
1536
1537 /* Compute the follow set of every reducible configuration */
1538 FindFollowSets(&lem);
1539
1540 /* Compute the action tables */
1541 FindActions(&lem);
1542
1543 /* Compress the action tables */
1544 if( compress==0 ) CompressTables(&lem);
1545
drhada354d2005-11-05 15:03:59 +00001546 /* Reorder and renumber the states so that states with fewer choices
1547 ** occur at the end. */
1548 ResortStates(&lem);
1549
drh75897232000-05-29 14:26:00 +00001550 /* Generate a report of the parser generated. (the "y.output" file) */
1551 if( !quiet ) ReportOutput(&lem);
1552
1553 /* Generate the source code for the parser */
1554 ReportTable(&lem, mhflag);
1555
1556 /* Produce a header file for use by the scanner. (This step is
1557 ** omitted if the "-m" option is used because makeheaders will
1558 ** generate the file for us.) */
1559 if( !mhflag ) ReportHeader(&lem);
1560 }
1561 if( statistics ){
1562 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1563 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1564 printf(" %d states, %d parser table entries, %d conflicts\n",
1565 lem.nstate, lem.tablesize, lem.nconflict);
1566 }
1567 if( lem.nconflict ){
1568 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1569 }
1570 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001571 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001572}
1573/******************** From the file "msort.c" *******************************/
1574/*
1575** A generic merge-sort program.
1576**
1577** USAGE:
1578** Let "ptr" be a pointer to some structure which is at the head of
1579** a null-terminated list. Then to sort the list call:
1580**
1581** ptr = msort(ptr,&(ptr->next),cmpfnc);
1582**
1583** In the above, "cmpfnc" is a pointer to a function which compares
1584** two instances of the structure and returns an integer, as in
1585** strcmp. The second argument is a pointer to the pointer to the
1586** second element of the linked list. This address is used to compute
1587** the offset to the "next" field within the structure. The offset to
1588** the "next" field must be constant for all structures in the list.
1589**
1590** The function returns a new pointer which is the head of the list
1591** after sorting.
1592**
1593** ALGORITHM:
1594** Merge-sort.
1595*/
1596
1597/*
1598** Return a pointer to the next structure in the linked list.
1599*/
drhba99af52001-10-25 20:37:16 +00001600#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001601
1602/*
1603** Inputs:
1604** a: A sorted, null-terminated linked list. (May be null).
1605** b: A sorted, null-terminated linked list. (May be null).
1606** cmp: A pointer to the comparison function.
1607** offset: Offset in the structure to the "next" field.
1608**
1609** Return Value:
1610** A pointer to the head of a sorted list containing the elements
1611** of both a and b.
1612**
1613** Side effects:
1614** The "next" pointers for elements in the lists a and b are
1615** changed.
1616*/
drhe9278182007-07-18 18:16:29 +00001617static char *merge(
1618 char *a,
1619 char *b,
1620 int (*cmp)(const char*,const char*),
1621 int offset
1622){
drh75897232000-05-29 14:26:00 +00001623 char *ptr, *head;
1624
1625 if( a==0 ){
1626 head = b;
1627 }else if( b==0 ){
1628 head = a;
1629 }else{
drhe594bc32009-11-03 13:02:25 +00001630 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001631 ptr = a;
1632 a = NEXT(a);
1633 }else{
1634 ptr = b;
1635 b = NEXT(b);
1636 }
1637 head = ptr;
1638 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001639 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001640 NEXT(ptr) = a;
1641 ptr = a;
1642 a = NEXT(a);
1643 }else{
1644 NEXT(ptr) = b;
1645 ptr = b;
1646 b = NEXT(b);
1647 }
1648 }
1649 if( a ) NEXT(ptr) = a;
1650 else NEXT(ptr) = b;
1651 }
1652 return head;
1653}
1654
1655/*
1656** Inputs:
1657** list: Pointer to a singly-linked list of structures.
1658** next: Pointer to pointer to the second element of the list.
1659** cmp: A comparison function.
1660**
1661** Return Value:
1662** A pointer to the head of a sorted list containing the elements
1663** orginally in list.
1664**
1665** Side effects:
1666** The "next" pointers for elements in list are changed.
1667*/
1668#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001669static char *msort(
1670 char *list,
1671 char **next,
1672 int (*cmp)(const char*,const char*)
1673){
drhba99af52001-10-25 20:37:16 +00001674 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001675 char *ep;
1676 char *set[LISTSIZE];
1677 int i;
drhba99af52001-10-25 20:37:16 +00001678 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001679 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1680 while( list ){
1681 ep = list;
1682 list = NEXT(list);
1683 NEXT(ep) = 0;
1684 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1685 ep = merge(ep,set[i],cmp,offset);
1686 set[i] = 0;
1687 }
1688 set[i] = ep;
1689 }
1690 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001691 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001692 return ep;
1693}
1694/************************ From the file "option.c" **************************/
1695static char **argv;
1696static struct s_options *op;
1697static FILE *errstream;
1698
1699#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1700
1701/*
1702** Print the command line with a carrot pointing to the k-th character
1703** of the n-th field.
1704*/
1705static void errline(n,k,err)
1706int n;
1707int k;
1708FILE *err;
1709{
1710 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001711 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001712 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001713 for(i=1; i<n && argv[i]; i++){
1714 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001715 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001716 }
1717 spcnt += k;
1718 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1719 if( spcnt<20 ){
1720 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1721 }else{
1722 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1723 }
1724}
1725
1726/*
1727** Return the index of the N-th non-switch argument. Return -1
1728** if N is out of range.
1729*/
1730static int argindex(n)
1731int n;
1732{
1733 int i;
1734 int dashdash = 0;
1735 if( argv!=0 && *argv!=0 ){
1736 for(i=1; argv[i]; i++){
1737 if( dashdash || !ISOPT(argv[i]) ){
1738 if( n==0 ) return i;
1739 n--;
1740 }
1741 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1742 }
1743 }
1744 return -1;
1745}
1746
1747static char emsg[] = "Command line syntax error: ";
1748
1749/*
1750** Process a flag command line argument.
1751*/
1752static int handleflags(i,err)
1753int i;
1754FILE *err;
1755{
1756 int v;
1757 int errcnt = 0;
1758 int j;
1759 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001760 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001761 }
1762 v = argv[i][0]=='-' ? 1 : 0;
1763 if( op[j].label==0 ){
1764 if( err ){
1765 fprintf(err,"%sundefined option.\n",emsg);
1766 errline(i,1,err);
1767 }
1768 errcnt++;
1769 }else if( op[j].type==OPT_FLAG ){
1770 *((int*)op[j].arg) = v;
1771 }else if( op[j].type==OPT_FFLAG ){
1772 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001773 }else if( op[j].type==OPT_FSTR ){
1774 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001775 }else{
1776 if( err ){
1777 fprintf(err,"%smissing argument on switch.\n",emsg);
1778 errline(i,1,err);
1779 }
1780 errcnt++;
1781 }
1782 return errcnt;
1783}
1784
1785/*
1786** Process a command line switch which has an argument.
1787*/
1788static int handleswitch(i,err)
1789int i;
1790FILE *err;
1791{
1792 int lv = 0;
1793 double dv = 0.0;
1794 char *sv = 0, *end;
1795 char *cp;
1796 int j;
1797 int errcnt = 0;
1798 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001799 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001800 *cp = 0;
1801 for(j=0; op[j].label; j++){
1802 if( strcmp(argv[i],op[j].label)==0 ) break;
1803 }
1804 *cp = '=';
1805 if( op[j].label==0 ){
1806 if( err ){
1807 fprintf(err,"%sundefined option.\n",emsg);
1808 errline(i,0,err);
1809 }
1810 errcnt++;
1811 }else{
1812 cp++;
1813 switch( op[j].type ){
1814 case OPT_FLAG:
1815 case OPT_FFLAG:
1816 if( err ){
1817 fprintf(err,"%soption requires an argument.\n",emsg);
1818 errline(i,0,err);
1819 }
1820 errcnt++;
1821 break;
1822 case OPT_DBL:
1823 case OPT_FDBL:
1824 dv = strtod(cp,&end);
1825 if( *end ){
1826 if( err ){
1827 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001828 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001829 }
1830 errcnt++;
1831 }
1832 break;
1833 case OPT_INT:
1834 case OPT_FINT:
1835 lv = strtol(cp,&end,0);
1836 if( *end ){
1837 if( err ){
1838 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001839 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001840 }
1841 errcnt++;
1842 }
1843 break;
1844 case OPT_STR:
1845 case OPT_FSTR:
1846 sv = cp;
1847 break;
1848 }
1849 switch( op[j].type ){
1850 case OPT_FLAG:
1851 case OPT_FFLAG:
1852 break;
1853 case OPT_DBL:
1854 *(double*)(op[j].arg) = dv;
1855 break;
1856 case OPT_FDBL:
1857 (*(void(*)())(op[j].arg))(dv);
1858 break;
1859 case OPT_INT:
1860 *(int*)(op[j].arg) = lv;
1861 break;
1862 case OPT_FINT:
1863 (*(void(*)())(op[j].arg))((int)lv);
1864 break;
1865 case OPT_STR:
1866 *(char**)(op[j].arg) = sv;
1867 break;
1868 case OPT_FSTR:
1869 (*(void(*)())(op[j].arg))(sv);
1870 break;
1871 }
1872 }
1873 return errcnt;
1874}
1875
drhb0c86772000-06-02 23:21:26 +00001876int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001877char **a;
1878struct s_options *o;
1879FILE *err;
1880{
1881 int errcnt = 0;
1882 argv = a;
1883 op = o;
1884 errstream = err;
1885 if( argv && *argv && op ){
1886 int i;
1887 for(i=1; argv[i]; i++){
1888 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1889 errcnt += handleflags(i,err);
1890 }else if( strchr(argv[i],'=') ){
1891 errcnt += handleswitch(i,err);
1892 }
1893 }
1894 }
1895 if( errcnt>0 ){
1896 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001897 OptPrint();
drh75897232000-05-29 14:26:00 +00001898 exit(1);
1899 }
1900 return 0;
1901}
1902
drhb0c86772000-06-02 23:21:26 +00001903int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001904 int cnt = 0;
1905 int dashdash = 0;
1906 int i;
1907 if( argv!=0 && argv[0]!=0 ){
1908 for(i=1; argv[i]; i++){
1909 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1910 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1911 }
1912 }
1913 return cnt;
1914}
1915
drhb0c86772000-06-02 23:21:26 +00001916char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001917int n;
1918{
1919 int i;
1920 i = argindex(n);
1921 return i>=0 ? argv[i] : 0;
1922}
1923
drhb0c86772000-06-02 23:21:26 +00001924void OptErr(n)
drh75897232000-05-29 14:26:00 +00001925int n;
1926{
1927 int i;
1928 i = argindex(n);
1929 if( i>=0 ) errline(i,0,errstream);
1930}
1931
drhb0c86772000-06-02 23:21:26 +00001932void OptPrint(){
drh75897232000-05-29 14:26:00 +00001933 int i;
1934 int max, len;
1935 max = 0;
1936 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001937 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001938 switch( op[i].type ){
1939 case OPT_FLAG:
1940 case OPT_FFLAG:
1941 break;
1942 case OPT_INT:
1943 case OPT_FINT:
1944 len += 9; /* length of "<integer>" */
1945 break;
1946 case OPT_DBL:
1947 case OPT_FDBL:
1948 len += 6; /* length of "<real>" */
1949 break;
1950 case OPT_STR:
1951 case OPT_FSTR:
1952 len += 8; /* length of "<string>" */
1953 break;
1954 }
1955 if( len>max ) max = len;
1956 }
1957 for(i=0; op[i].label; i++){
1958 switch( op[i].type ){
1959 case OPT_FLAG:
1960 case OPT_FFLAG:
1961 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1962 break;
1963 case OPT_INT:
1964 case OPT_FINT:
1965 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001966 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001967 break;
1968 case OPT_DBL:
1969 case OPT_FDBL:
1970 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001971 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001972 break;
1973 case OPT_STR:
1974 case OPT_FSTR:
1975 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001976 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001977 break;
1978 }
1979 }
1980}
1981/*********************** From the file "parse.c" ****************************/
1982/*
1983** Input file parser for the LEMON parser generator.
1984*/
1985
1986/* The state of the parser */
1987struct pstate {
1988 char *filename; /* Name of the input file */
1989 int tokenlineno; /* Linenumber at which current token starts */
1990 int errorcnt; /* Number of errors so far */
1991 char *tokenstart; /* Text of current token */
1992 struct lemon *gp; /* Global state vector */
1993 enum e_state {
1994 INITIALIZE,
1995 WAITING_FOR_DECL_OR_RULE,
1996 WAITING_FOR_DECL_KEYWORD,
1997 WAITING_FOR_DECL_ARG,
1998 WAITING_FOR_PRECEDENCE_SYMBOL,
1999 WAITING_FOR_ARROW,
2000 IN_RHS,
2001 LHS_ALIAS_1,
2002 LHS_ALIAS_2,
2003 LHS_ALIAS_3,
2004 RHS_ALIAS_1,
2005 RHS_ALIAS_2,
2006 PRECEDENCE_MARK_1,
2007 PRECEDENCE_MARK_2,
2008 RESYNC_AFTER_RULE_ERROR,
2009 RESYNC_AFTER_DECL_ERROR,
2010 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00002011 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00002012 WAITING_FOR_FALLBACK_ID,
2013 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00002014 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002015 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00002016 struct symbol *lhs; /* Left-hand side of current rule */
2017 char *lhsalias; /* Alias for the LHS */
2018 int nrhs; /* Number of right-hand side symbols seen */
2019 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2020 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2021 struct rule *prevrule; /* Previous rule parsed */
2022 char *declkeyword; /* Keyword of a declaration */
2023 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002024 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002025 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002026 enum e_assoc declassoc; /* Assign this association to decl arguments */
2027 int preccounter; /* Assign this precedence to decl arguments */
2028 struct rule *firstrule; /* Pointer to first rule in the grammar */
2029 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2030};
2031
2032/* Parse a single token */
2033static void parseonetoken(psp)
2034struct pstate *psp;
2035{
2036 char *x;
2037 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2038#if 0
2039 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2040 x,psp->state);
2041#endif
2042 switch( psp->state ){
2043 case INITIALIZE:
2044 psp->prevrule = 0;
2045 psp->preccounter = 0;
2046 psp->firstrule = psp->lastrule = 0;
2047 psp->gp->nrule = 0;
2048 /* Fall thru to next case */
2049 case WAITING_FOR_DECL_OR_RULE:
2050 if( x[0]=='%' ){
2051 psp->state = WAITING_FOR_DECL_KEYWORD;
2052 }else if( islower(x[0]) ){
2053 psp->lhs = Symbol_new(x);
2054 psp->nrhs = 0;
2055 psp->lhsalias = 0;
2056 psp->state = WAITING_FOR_ARROW;
2057 }else if( x[0]=='{' ){
2058 if( psp->prevrule==0 ){
2059 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002060"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002061fragment which begins on this line.");
2062 psp->errorcnt++;
2063 }else if( psp->prevrule->code!=0 ){
2064 ErrorMsg(psp->filename,psp->tokenlineno,
2065"Code fragment beginning on this line is not the first \
2066to follow the previous rule.");
2067 psp->errorcnt++;
2068 }else{
2069 psp->prevrule->line = psp->tokenlineno;
2070 psp->prevrule->code = &x[1];
2071 }
2072 }else if( x[0]=='[' ){
2073 psp->state = PRECEDENCE_MARK_1;
2074 }else{
2075 ErrorMsg(psp->filename,psp->tokenlineno,
2076 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2077 x);
2078 psp->errorcnt++;
2079 }
2080 break;
2081 case PRECEDENCE_MARK_1:
2082 if( !isupper(x[0]) ){
2083 ErrorMsg(psp->filename,psp->tokenlineno,
2084 "The precedence symbol must be a terminal.");
2085 psp->errorcnt++;
2086 }else if( psp->prevrule==0 ){
2087 ErrorMsg(psp->filename,psp->tokenlineno,
2088 "There is no prior rule to assign precedence \"[%s]\".",x);
2089 psp->errorcnt++;
2090 }else if( psp->prevrule->precsym!=0 ){
2091 ErrorMsg(psp->filename,psp->tokenlineno,
2092"Precedence mark on this line is not the first \
2093to follow the previous rule.");
2094 psp->errorcnt++;
2095 }else{
2096 psp->prevrule->precsym = Symbol_new(x);
2097 }
2098 psp->state = PRECEDENCE_MARK_2;
2099 break;
2100 case PRECEDENCE_MARK_2:
2101 if( x[0]!=']' ){
2102 ErrorMsg(psp->filename,psp->tokenlineno,
2103 "Missing \"]\" on precedence mark.");
2104 psp->errorcnt++;
2105 }
2106 psp->state = WAITING_FOR_DECL_OR_RULE;
2107 break;
2108 case WAITING_FOR_ARROW:
2109 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2110 psp->state = IN_RHS;
2111 }else if( x[0]=='(' ){
2112 psp->state = LHS_ALIAS_1;
2113 }else{
2114 ErrorMsg(psp->filename,psp->tokenlineno,
2115 "Expected to see a \":\" following the LHS symbol \"%s\".",
2116 psp->lhs->name);
2117 psp->errorcnt++;
2118 psp->state = RESYNC_AFTER_RULE_ERROR;
2119 }
2120 break;
2121 case LHS_ALIAS_1:
2122 if( isalpha(x[0]) ){
2123 psp->lhsalias = x;
2124 psp->state = LHS_ALIAS_2;
2125 }else{
2126 ErrorMsg(psp->filename,psp->tokenlineno,
2127 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2128 x,psp->lhs->name);
2129 psp->errorcnt++;
2130 psp->state = RESYNC_AFTER_RULE_ERROR;
2131 }
2132 break;
2133 case LHS_ALIAS_2:
2134 if( x[0]==')' ){
2135 psp->state = LHS_ALIAS_3;
2136 }else{
2137 ErrorMsg(psp->filename,psp->tokenlineno,
2138 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2139 psp->errorcnt++;
2140 psp->state = RESYNC_AFTER_RULE_ERROR;
2141 }
2142 break;
2143 case LHS_ALIAS_3:
2144 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2145 psp->state = IN_RHS;
2146 }else{
2147 ErrorMsg(psp->filename,psp->tokenlineno,
2148 "Missing \"->\" following: \"%s(%s)\".",
2149 psp->lhs->name,psp->lhsalias);
2150 psp->errorcnt++;
2151 psp->state = RESYNC_AFTER_RULE_ERROR;
2152 }
2153 break;
2154 case IN_RHS:
2155 if( x[0]=='.' ){
2156 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002157 rp = (struct rule *)calloc( sizeof(struct rule) +
2158 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002159 if( rp==0 ){
2160 ErrorMsg(psp->filename,psp->tokenlineno,
2161 "Can't allocate enough memory for this rule.");
2162 psp->errorcnt++;
2163 psp->prevrule = 0;
2164 }else{
2165 int i;
2166 rp->ruleline = psp->tokenlineno;
2167 rp->rhs = (struct symbol**)&rp[1];
2168 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2169 for(i=0; i<psp->nrhs; i++){
2170 rp->rhs[i] = psp->rhs[i];
2171 rp->rhsalias[i] = psp->alias[i];
2172 }
2173 rp->lhs = psp->lhs;
2174 rp->lhsalias = psp->lhsalias;
2175 rp->nrhs = psp->nrhs;
2176 rp->code = 0;
2177 rp->precsym = 0;
2178 rp->index = psp->gp->nrule++;
2179 rp->nextlhs = rp->lhs->rule;
2180 rp->lhs->rule = rp;
2181 rp->next = 0;
2182 if( psp->firstrule==0 ){
2183 psp->firstrule = psp->lastrule = rp;
2184 }else{
2185 psp->lastrule->next = rp;
2186 psp->lastrule = rp;
2187 }
2188 psp->prevrule = rp;
2189 }
2190 psp->state = WAITING_FOR_DECL_OR_RULE;
2191 }else if( isalpha(x[0]) ){
2192 if( psp->nrhs>=MAXRHS ){
2193 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002194 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002195 x);
2196 psp->errorcnt++;
2197 psp->state = RESYNC_AFTER_RULE_ERROR;
2198 }else{
2199 psp->rhs[psp->nrhs] = Symbol_new(x);
2200 psp->alias[psp->nrhs] = 0;
2201 psp->nrhs++;
2202 }
drhfd405312005-11-06 04:06:59 +00002203 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2204 struct symbol *msp = psp->rhs[psp->nrhs-1];
2205 if( msp->type!=MULTITERMINAL ){
2206 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002207 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002208 memset(msp, 0, sizeof(*msp));
2209 msp->type = MULTITERMINAL;
2210 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002211 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002212 msp->subsym[0] = origsp;
2213 msp->name = origsp->name;
2214 psp->rhs[psp->nrhs-1] = msp;
2215 }
2216 msp->nsubsym++;
2217 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2218 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2219 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2220 ErrorMsg(psp->filename,psp->tokenlineno,
2221 "Cannot form a compound containing a non-terminal");
2222 psp->errorcnt++;
2223 }
drh75897232000-05-29 14:26:00 +00002224 }else if( x[0]=='(' && psp->nrhs>0 ){
2225 psp->state = RHS_ALIAS_1;
2226 }else{
2227 ErrorMsg(psp->filename,psp->tokenlineno,
2228 "Illegal character on RHS of rule: \"%s\".",x);
2229 psp->errorcnt++;
2230 psp->state = RESYNC_AFTER_RULE_ERROR;
2231 }
2232 break;
2233 case RHS_ALIAS_1:
2234 if( isalpha(x[0]) ){
2235 psp->alias[psp->nrhs-1] = x;
2236 psp->state = RHS_ALIAS_2;
2237 }else{
2238 ErrorMsg(psp->filename,psp->tokenlineno,
2239 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2240 x,psp->rhs[psp->nrhs-1]->name);
2241 psp->errorcnt++;
2242 psp->state = RESYNC_AFTER_RULE_ERROR;
2243 }
2244 break;
2245 case RHS_ALIAS_2:
2246 if( x[0]==')' ){
2247 psp->state = IN_RHS;
2248 }else{
2249 ErrorMsg(psp->filename,psp->tokenlineno,
2250 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2251 psp->errorcnt++;
2252 psp->state = RESYNC_AFTER_RULE_ERROR;
2253 }
2254 break;
2255 case WAITING_FOR_DECL_KEYWORD:
2256 if( isalpha(x[0]) ){
2257 psp->declkeyword = x;
2258 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002259 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002260 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002261 psp->state = WAITING_FOR_DECL_ARG;
2262 if( strcmp(x,"name")==0 ){
2263 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002264 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002265 }else if( strcmp(x,"include")==0 ){
2266 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002267 }else if( strcmp(x,"code")==0 ){
2268 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002269 }else if( strcmp(x,"token_destructor")==0 ){
2270 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002271 }else if( strcmp(x,"default_destructor")==0 ){
2272 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002273 }else if( strcmp(x,"token_prefix")==0 ){
2274 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002275 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002276 }else if( strcmp(x,"syntax_error")==0 ){
2277 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002278 }else if( strcmp(x,"parse_accept")==0 ){
2279 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002280 }else if( strcmp(x,"parse_failure")==0 ){
2281 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002282 }else if( strcmp(x,"stack_overflow")==0 ){
2283 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002284 }else if( strcmp(x,"extra_argument")==0 ){
2285 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002286 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002287 }else if( strcmp(x,"token_type")==0 ){
2288 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002289 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002290 }else if( strcmp(x,"default_type")==0 ){
2291 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002292 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002293 }else if( strcmp(x,"stack_size")==0 ){
2294 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002295 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002296 }else if( strcmp(x,"start_symbol")==0 ){
2297 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002298 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002299 }else if( strcmp(x,"left")==0 ){
2300 psp->preccounter++;
2301 psp->declassoc = LEFT;
2302 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2303 }else if( strcmp(x,"right")==0 ){
2304 psp->preccounter++;
2305 psp->declassoc = RIGHT;
2306 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2307 }else if( strcmp(x,"nonassoc")==0 ){
2308 psp->preccounter++;
2309 psp->declassoc = NONE;
2310 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2311 }else if( strcmp(x,"destructor")==0 ){
2312 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2313 }else if( strcmp(x,"type")==0 ){
2314 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002315 }else if( strcmp(x,"fallback")==0 ){
2316 psp->fallback = 0;
2317 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002318 }else if( strcmp(x,"wildcard")==0 ){
2319 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002320 }else{
2321 ErrorMsg(psp->filename,psp->tokenlineno,
2322 "Unknown declaration keyword: \"%%%s\".",x);
2323 psp->errorcnt++;
2324 psp->state = RESYNC_AFTER_DECL_ERROR;
2325 }
2326 }else{
2327 ErrorMsg(psp->filename,psp->tokenlineno,
2328 "Illegal declaration keyword: \"%s\".",x);
2329 psp->errorcnt++;
2330 psp->state = RESYNC_AFTER_DECL_ERROR;
2331 }
2332 break;
2333 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2334 if( !isalpha(x[0]) ){
2335 ErrorMsg(psp->filename,psp->tokenlineno,
2336 "Symbol name missing after %destructor keyword");
2337 psp->errorcnt++;
2338 psp->state = RESYNC_AFTER_DECL_ERROR;
2339 }else{
2340 struct symbol *sp = Symbol_new(x);
2341 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002342 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002343 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002344 psp->state = WAITING_FOR_DECL_ARG;
2345 }
2346 break;
2347 case WAITING_FOR_DATATYPE_SYMBOL:
2348 if( !isalpha(x[0]) ){
2349 ErrorMsg(psp->filename,psp->tokenlineno,
2350 "Symbol name missing after %destructor keyword");
2351 psp->errorcnt++;
2352 psp->state = RESYNC_AFTER_DECL_ERROR;
2353 }else{
2354 struct symbol *sp = Symbol_new(x);
2355 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002356 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002357 psp->state = WAITING_FOR_DECL_ARG;
2358 }
2359 break;
2360 case WAITING_FOR_PRECEDENCE_SYMBOL:
2361 if( x[0]=='.' ){
2362 psp->state = WAITING_FOR_DECL_OR_RULE;
2363 }else if( isupper(x[0]) ){
2364 struct symbol *sp;
2365 sp = Symbol_new(x);
2366 if( sp->prec>=0 ){
2367 ErrorMsg(psp->filename,psp->tokenlineno,
2368 "Symbol \"%s\" has already be given a precedence.",x);
2369 psp->errorcnt++;
2370 }else{
2371 sp->prec = psp->preccounter;
2372 sp->assoc = psp->declassoc;
2373 }
2374 }else{
2375 ErrorMsg(psp->filename,psp->tokenlineno,
2376 "Can't assign a precedence to \"%s\".",x);
2377 psp->errorcnt++;
2378 }
2379 break;
2380 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002381 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2382 char *zOld, *zNew, *zBuf, *z;
2383 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002384 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002385 char zLine[50];
2386 zNew = x;
2387 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002388 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002389 if( *psp->declargslot ){
2390 zOld = *psp->declargslot;
2391 }else{
2392 zOld = "";
2393 }
drh87cf1372008-08-13 20:09:06 +00002394 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002395 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002396 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002397 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2398 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002399 for(z=psp->filename, nBack=0; *z; z++){
2400 if( *z=='\\' ) nBack++;
2401 }
2402 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002403 nLine = lemonStrlen(zLine);
2404 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002405 }
2406 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2407 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002408 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002409 if( nOld && zBuf[-1]!='\n' ){
2410 *(zBuf++) = '\n';
2411 }
2412 memcpy(zBuf, zLine, nLine);
2413 zBuf += nLine;
2414 *(zBuf++) = '"';
2415 for(z=psp->filename; *z; z++){
2416 if( *z=='\\' ){
2417 *(zBuf++) = '\\';
2418 }
2419 *(zBuf++) = *z;
2420 }
2421 *(zBuf++) = '"';
2422 *(zBuf++) = '\n';
2423 }
drh4dc8ef52008-07-01 17:13:57 +00002424 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2425 psp->decllinenoslot[0] = psp->tokenlineno;
2426 }
drha5808f32008-04-27 22:19:44 +00002427 memcpy(zBuf, zNew, nNew);
2428 zBuf += nNew;
2429 *zBuf = 0;
2430 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002431 }else{
2432 ErrorMsg(psp->filename,psp->tokenlineno,
2433 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2434 psp->errorcnt++;
2435 psp->state = RESYNC_AFTER_DECL_ERROR;
2436 }
2437 break;
drh0bd1f4e2002-06-06 18:54:39 +00002438 case WAITING_FOR_FALLBACK_ID:
2439 if( x[0]=='.' ){
2440 psp->state = WAITING_FOR_DECL_OR_RULE;
2441 }else if( !isupper(x[0]) ){
2442 ErrorMsg(psp->filename, psp->tokenlineno,
2443 "%%fallback argument \"%s\" should be a token", x);
2444 psp->errorcnt++;
2445 }else{
2446 struct symbol *sp = Symbol_new(x);
2447 if( psp->fallback==0 ){
2448 psp->fallback = sp;
2449 }else if( sp->fallback ){
2450 ErrorMsg(psp->filename, psp->tokenlineno,
2451 "More than one fallback assigned to token %s", x);
2452 psp->errorcnt++;
2453 }else{
2454 sp->fallback = psp->fallback;
2455 psp->gp->has_fallback = 1;
2456 }
2457 }
2458 break;
drhe09daa92006-06-10 13:29:31 +00002459 case WAITING_FOR_WILDCARD_ID:
2460 if( x[0]=='.' ){
2461 psp->state = WAITING_FOR_DECL_OR_RULE;
2462 }else if( !isupper(x[0]) ){
2463 ErrorMsg(psp->filename, psp->tokenlineno,
2464 "%%wildcard argument \"%s\" should be a token", x);
2465 psp->errorcnt++;
2466 }else{
2467 struct symbol *sp = Symbol_new(x);
2468 if( psp->gp->wildcard==0 ){
2469 psp->gp->wildcard = sp;
2470 }else{
2471 ErrorMsg(psp->filename, psp->tokenlineno,
2472 "Extra wildcard to token: %s", x);
2473 psp->errorcnt++;
2474 }
2475 }
2476 break;
drh75897232000-05-29 14:26:00 +00002477 case RESYNC_AFTER_RULE_ERROR:
2478/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2479** break; */
2480 case RESYNC_AFTER_DECL_ERROR:
2481 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2482 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2483 break;
2484 }
2485}
2486
drh34ff57b2008-07-14 12:27:51 +00002487/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002488** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2489** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2490** comments them out. Text in between is also commented out as appropriate.
2491*/
danielk1977940fac92005-01-23 22:41:37 +00002492static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002493 int i, j, k, n;
2494 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002495 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002496 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002497 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002498 for(i=0; z[i]; i++){
2499 if( z[i]=='\n' ) lineno++;
2500 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2501 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2502 if( exclude ){
2503 exclude--;
2504 if( exclude==0 ){
2505 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2506 }
2507 }
2508 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2509 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2510 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2511 if( exclude ){
2512 exclude++;
2513 }else{
2514 for(j=i+7; isspace(z[j]); j++){}
2515 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2516 exclude = 1;
2517 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002518 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002519 exclude = 0;
2520 break;
2521 }
2522 }
2523 if( z[i+3]=='n' ) exclude = !exclude;
2524 if( exclude ){
2525 start = i;
2526 start_lineno = lineno;
2527 }
2528 }
2529 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2530 }
2531 }
2532 if( exclude ){
2533 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2534 exit(1);
2535 }
2536}
2537
drh75897232000-05-29 14:26:00 +00002538/* In spite of its name, this function is really a scanner. It read
2539** in the entire input file (all at once) then tokenizes it. Each
2540** token is passed to the function "parseonetoken" which builds all
2541** the appropriate data structures in the global state vector "gp".
2542*/
2543void Parse(gp)
2544struct lemon *gp;
2545{
2546 struct pstate ps;
2547 FILE *fp;
2548 char *filebuf;
2549 int filesize;
2550 int lineno;
2551 int c;
2552 char *cp, *nextcp;
2553 int startline = 0;
2554
rse38514a92007-09-20 11:34:17 +00002555 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002556 ps.gp = gp;
2557 ps.filename = gp->filename;
2558 ps.errorcnt = 0;
2559 ps.state = INITIALIZE;
2560
2561 /* Begin by reading the input file */
2562 fp = fopen(ps.filename,"rb");
2563 if( fp==0 ){
2564 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2565 gp->errorcnt++;
2566 return;
2567 }
2568 fseek(fp,0,2);
2569 filesize = ftell(fp);
2570 rewind(fp);
2571 filebuf = (char *)malloc( filesize+1 );
2572 if( filebuf==0 ){
2573 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2574 filesize+1);
2575 gp->errorcnt++;
2576 return;
2577 }
2578 if( fread(filebuf,1,filesize,fp)!=filesize ){
2579 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2580 filesize);
2581 free(filebuf);
2582 gp->errorcnt++;
2583 return;
2584 }
2585 fclose(fp);
2586 filebuf[filesize] = 0;
2587
drh6d08b4d2004-07-20 12:45:22 +00002588 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2589 preprocess_input(filebuf);
2590
drh75897232000-05-29 14:26:00 +00002591 /* Now scan the text of the input file */
2592 lineno = 1;
2593 for(cp=filebuf; (c= *cp)!=0; ){
2594 if( c=='\n' ) lineno++; /* Keep track of the line number */
2595 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2596 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2597 cp+=2;
2598 while( (c= *cp)!=0 && c!='\n' ) cp++;
2599 continue;
2600 }
2601 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2602 cp+=2;
2603 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2604 if( c=='\n' ) lineno++;
2605 cp++;
2606 }
2607 if( c ) cp++;
2608 continue;
2609 }
2610 ps.tokenstart = cp; /* Mark the beginning of the token */
2611 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2612 if( c=='\"' ){ /* String literals */
2613 cp++;
2614 while( (c= *cp)!=0 && c!='\"' ){
2615 if( c=='\n' ) lineno++;
2616 cp++;
2617 }
2618 if( c==0 ){
2619 ErrorMsg(ps.filename,startline,
2620"String starting on this line is not terminated before the end of the file.");
2621 ps.errorcnt++;
2622 nextcp = cp;
2623 }else{
2624 nextcp = cp+1;
2625 }
2626 }else if( c=='{' ){ /* A block of C code */
2627 int level;
2628 cp++;
2629 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2630 if( c=='\n' ) lineno++;
2631 else if( c=='{' ) level++;
2632 else if( c=='}' ) level--;
2633 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2634 int prevc;
2635 cp = &cp[2];
2636 prevc = 0;
2637 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2638 if( c=='\n' ) lineno++;
2639 prevc = c;
2640 cp++;
2641 }
2642 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2643 cp = &cp[2];
2644 while( (c= *cp)!=0 && c!='\n' ) cp++;
2645 if( c ) lineno++;
2646 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2647 int startchar, prevc;
2648 startchar = c;
2649 prevc = 0;
2650 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2651 if( c=='\n' ) lineno++;
2652 if( prevc=='\\' ) prevc = 0;
2653 else prevc = c;
2654 }
2655 }
2656 }
2657 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002658 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002659"C code starting on this line is not terminated before the end of the file.");
2660 ps.errorcnt++;
2661 nextcp = cp;
2662 }else{
2663 nextcp = cp+1;
2664 }
2665 }else if( isalnum(c) ){ /* Identifiers */
2666 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2667 nextcp = cp;
2668 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2669 cp += 3;
2670 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002671 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2672 cp += 2;
2673 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2674 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002675 }else{ /* All other (one character) operators */
2676 cp++;
2677 nextcp = cp;
2678 }
2679 c = *cp;
2680 *cp = 0; /* Null terminate the token */
2681 parseonetoken(&ps); /* Parse the token */
2682 *cp = c; /* Restore the buffer */
2683 cp = nextcp;
2684 }
2685 free(filebuf); /* Release the buffer after parsing */
2686 gp->rule = ps.firstrule;
2687 gp->errorcnt = ps.errorcnt;
2688}
2689/*************************** From the file "plink.c" *********************/
2690/*
2691** Routines processing configuration follow-set propagation links
2692** in the LEMON parser generator.
2693*/
2694static struct plink *plink_freelist = 0;
2695
2696/* Allocate a new plink */
2697struct plink *Plink_new(){
2698 struct plink *new;
2699
2700 if( plink_freelist==0 ){
2701 int i;
2702 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002703 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002704 if( plink_freelist==0 ){
2705 fprintf(stderr,
2706 "Unable to allocate memory for a new follow-set propagation link.\n");
2707 exit(1);
2708 }
2709 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2710 plink_freelist[amt-1].next = 0;
2711 }
2712 new = plink_freelist;
2713 plink_freelist = plink_freelist->next;
2714 return new;
2715}
2716
2717/* Add a plink to a plink list */
2718void Plink_add(plpp,cfp)
2719struct plink **plpp;
2720struct config *cfp;
2721{
2722 struct plink *new;
2723 new = Plink_new();
2724 new->next = *plpp;
2725 *plpp = new;
2726 new->cfp = cfp;
2727}
2728
2729/* Transfer every plink on the list "from" to the list "to" */
2730void Plink_copy(to,from)
2731struct plink **to;
2732struct plink *from;
2733{
2734 struct plink *nextpl;
2735 while( from ){
2736 nextpl = from->next;
2737 from->next = *to;
2738 *to = from;
2739 from = nextpl;
2740 }
2741}
2742
2743/* Delete every plink on the list */
2744void Plink_delete(plp)
2745struct plink *plp;
2746{
2747 struct plink *nextpl;
2748
2749 while( plp ){
2750 nextpl = plp->next;
2751 plp->next = plink_freelist;
2752 plink_freelist = plp;
2753 plp = nextpl;
2754 }
2755}
2756/*********************** From the file "report.c" **************************/
2757/*
2758** Procedures for generating reports and tables in the LEMON parser generator.
2759*/
2760
2761/* Generate a filename with the given suffix. Space to hold the
2762** name comes from malloc() and must be freed by the calling
2763** function.
2764*/
2765PRIVATE char *file_makename(lemp,suffix)
2766struct lemon *lemp;
2767char *suffix;
2768{
2769 char *name;
2770 char *cp;
2771
drh87cf1372008-08-13 20:09:06 +00002772 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002773 if( name==0 ){
2774 fprintf(stderr,"Can't allocate space for a filename.\n");
2775 exit(1);
2776 }
2777 strcpy(name,lemp->filename);
2778 cp = strrchr(name,'.');
2779 if( cp ) *cp = 0;
2780 strcat(name,suffix);
2781 return name;
2782}
2783
2784/* Open a file with a name based on the name of the input file,
2785** but with a different (specified) suffix, and return a pointer
2786** to the stream */
2787PRIVATE FILE *file_open(lemp,suffix,mode)
2788struct lemon *lemp;
2789char *suffix;
2790char *mode;
2791{
2792 FILE *fp;
2793
2794 if( lemp->outname ) free(lemp->outname);
2795 lemp->outname = file_makename(lemp, suffix);
2796 fp = fopen(lemp->outname,mode);
2797 if( fp==0 && *mode=='w' ){
2798 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2799 lemp->errorcnt++;
2800 return 0;
2801 }
2802 return fp;
2803}
2804
2805/* Duplicate the input file without comments and without actions
2806** on rules */
2807void Reprint(lemp)
2808struct lemon *lemp;
2809{
2810 struct rule *rp;
2811 struct symbol *sp;
2812 int i, j, maxlen, len, ncolumns, skip;
2813 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2814 maxlen = 10;
2815 for(i=0; i<lemp->nsymbol; i++){
2816 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002817 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002818 if( len>maxlen ) maxlen = len;
2819 }
2820 ncolumns = 76/(maxlen+5);
2821 if( ncolumns<1 ) ncolumns = 1;
2822 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2823 for(i=0; i<skip; i++){
2824 printf("//");
2825 for(j=i; j<lemp->nsymbol; j+=skip){
2826 sp = lemp->symbols[j];
2827 assert( sp->index==j );
2828 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2829 }
2830 printf("\n");
2831 }
2832 for(rp=lemp->rule; rp; rp=rp->next){
2833 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002834 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002835 printf(" ::=");
2836 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002837 sp = rp->rhs[i];
2838 printf(" %s", sp->name);
2839 if( sp->type==MULTITERMINAL ){
2840 for(j=1; j<sp->nsubsym; j++){
2841 printf("|%s", sp->subsym[j]->name);
2842 }
2843 }
2844 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002845 }
2846 printf(".");
2847 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002848 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002849 printf("\n");
2850 }
2851}
2852
2853void ConfigPrint(fp,cfp)
2854FILE *fp;
2855struct config *cfp;
2856{
2857 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002858 struct symbol *sp;
2859 int i, j;
drh75897232000-05-29 14:26:00 +00002860 rp = cfp->rp;
2861 fprintf(fp,"%s ::=",rp->lhs->name);
2862 for(i=0; i<=rp->nrhs; i++){
2863 if( i==cfp->dot ) fprintf(fp," *");
2864 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002865 sp = rp->rhs[i];
2866 fprintf(fp," %s", sp->name);
2867 if( sp->type==MULTITERMINAL ){
2868 for(j=1; j<sp->nsubsym; j++){
2869 fprintf(fp,"|%s",sp->subsym[j]->name);
2870 }
2871 }
drh75897232000-05-29 14:26:00 +00002872 }
2873}
2874
2875/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002876#if 0
drh75897232000-05-29 14:26:00 +00002877/* Print a set */
2878PRIVATE void SetPrint(out,set,lemp)
2879FILE *out;
2880char *set;
2881struct lemon *lemp;
2882{
2883 int i;
2884 char *spacer;
2885 spacer = "";
2886 fprintf(out,"%12s[","");
2887 for(i=0; i<lemp->nterminal; i++){
2888 if( SetFind(set,i) ){
2889 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2890 spacer = " ";
2891 }
2892 }
2893 fprintf(out,"]\n");
2894}
2895
2896/* Print a plink chain */
2897PRIVATE void PlinkPrint(out,plp,tag)
2898FILE *out;
2899struct plink *plp;
2900char *tag;
2901{
2902 while( plp ){
drhada354d2005-11-05 15:03:59 +00002903 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002904 ConfigPrint(out,plp->cfp);
2905 fprintf(out,"\n");
2906 plp = plp->next;
2907 }
2908}
2909#endif
2910
2911/* Print an action to the given file descriptor. Return FALSE if
2912** nothing was actually printed.
2913*/
2914int PrintAction(struct action *ap, FILE *fp, int indent){
2915 int result = 1;
2916 switch( ap->type ){
2917 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002918 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002919 break;
2920 case REDUCE:
2921 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2922 break;
2923 case ACCEPT:
2924 fprintf(fp,"%*s accept",indent,ap->sp->name);
2925 break;
2926 case ERROR:
2927 fprintf(fp,"%*s error",indent,ap->sp->name);
2928 break;
drh9892c5d2007-12-21 00:02:11 +00002929 case SRCONFLICT:
2930 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002931 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2932 indent,ap->sp->name,ap->x.rp->index);
2933 break;
drh9892c5d2007-12-21 00:02:11 +00002934 case SSCONFLICT:
2935 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2936 indent,ap->sp->name,ap->x.stp->statenum);
2937 break;
drh75897232000-05-29 14:26:00 +00002938 case SH_RESOLVED:
2939 case RD_RESOLVED:
2940 case NOT_USED:
2941 result = 0;
2942 break;
2943 }
2944 return result;
2945}
2946
2947/* Generate the "y.output" log file */
2948void ReportOutput(lemp)
2949struct lemon *lemp;
2950{
2951 int i;
2952 struct state *stp;
2953 struct config *cfp;
2954 struct action *ap;
2955 FILE *fp;
2956
drh2aa6ca42004-09-10 00:14:04 +00002957 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002958 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002959 for(i=0; i<lemp->nstate; i++){
2960 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002961 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002962 if( lemp->basisflag ) cfp=stp->bp;
2963 else cfp=stp->cfp;
2964 while( cfp ){
2965 char buf[20];
2966 if( cfp->dot==cfp->rp->nrhs ){
2967 sprintf(buf,"(%d)",cfp->rp->index);
2968 fprintf(fp," %5s ",buf);
2969 }else{
2970 fprintf(fp," ");
2971 }
2972 ConfigPrint(fp,cfp);
2973 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002974#if 0
drh75897232000-05-29 14:26:00 +00002975 SetPrint(fp,cfp->fws,lemp);
2976 PlinkPrint(fp,cfp->fplp,"To ");
2977 PlinkPrint(fp,cfp->bplp,"From");
2978#endif
2979 if( lemp->basisflag ) cfp=cfp->bp;
2980 else cfp=cfp->next;
2981 }
2982 fprintf(fp,"\n");
2983 for(ap=stp->ap; ap; ap=ap->next){
2984 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2985 }
2986 fprintf(fp,"\n");
2987 }
drhe9278182007-07-18 18:16:29 +00002988 fprintf(fp, "----------------------------------------------------\n");
2989 fprintf(fp, "Symbols:\n");
2990 for(i=0; i<lemp->nsymbol; i++){
2991 int j;
2992 struct symbol *sp;
2993
2994 sp = lemp->symbols[i];
2995 fprintf(fp, " %3d: %s", i, sp->name);
2996 if( sp->type==NONTERMINAL ){
2997 fprintf(fp, ":");
2998 if( sp->lambda ){
2999 fprintf(fp, " <lambda>");
3000 }
3001 for(j=0; j<lemp->nterminal; j++){
3002 if( sp->firstset && SetFind(sp->firstset, j) ){
3003 fprintf(fp, " %s", lemp->symbols[j]->name);
3004 }
3005 }
3006 }
3007 fprintf(fp, "\n");
3008 }
drh75897232000-05-29 14:26:00 +00003009 fclose(fp);
3010 return;
3011}
3012
3013/* Search for the file "name" which is in the same directory as
3014** the exacutable */
3015PRIVATE char *pathsearch(argv0,name,modemask)
3016char *argv0;
3017char *name;
3018int modemask;
3019{
3020 char *pathlist;
3021 char *path,*cp;
3022 char c;
drh75897232000-05-29 14:26:00 +00003023
3024#ifdef __WIN32__
3025 cp = strrchr(argv0,'\\');
3026#else
3027 cp = strrchr(argv0,'/');
3028#endif
3029 if( cp ){
3030 c = *cp;
3031 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003032 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003033 if( path ) sprintf(path,"%s/%s",argv0,name);
3034 *cp = c;
3035 }else{
3036 extern char *getenv();
3037 pathlist = getenv("PATH");
3038 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00003039 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00003040 if( path!=0 ){
3041 while( *pathlist ){
3042 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00003043 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00003044 c = *cp;
3045 *cp = 0;
3046 sprintf(path,"%s/%s",pathlist,name);
3047 *cp = c;
3048 if( c==0 ) pathlist = "";
3049 else pathlist = &cp[1];
3050 if( access(path,modemask)==0 ) break;
3051 }
3052 }
3053 }
3054 return path;
3055}
3056
3057/* Given an action, compute the integer value for that action
3058** which is to be put in the action table of the generated machine.
3059** Return negative if no action should be generated.
3060*/
3061PRIVATE int compute_action(lemp,ap)
3062struct lemon *lemp;
3063struct action *ap;
3064{
3065 int act;
3066 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003067 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003068 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3069 case ERROR: act = lemp->nstate + lemp->nrule; break;
3070 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3071 default: act = -1; break;
3072 }
3073 return act;
3074}
3075
3076#define LINESIZE 1000
3077/* The next cluster of routines are for reading the template file
3078** and writing the results to the generated parser */
3079/* The first function transfers data from "in" to "out" until
3080** a line is seen which begins with "%%". The line number is
3081** tracked.
3082**
3083** if name!=0, then any word that begin with "Parse" is changed to
3084** begin with *name instead.
3085*/
3086PRIVATE void tplt_xfer(name,in,out,lineno)
3087char *name;
3088FILE *in;
3089FILE *out;
3090int *lineno;
3091{
3092 int i, iStart;
3093 char line[LINESIZE];
3094 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3095 (*lineno)++;
3096 iStart = 0;
3097 if( name ){
3098 for(i=0; line[i]; i++){
3099 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3100 && (i==0 || !isalpha(line[i-1]))
3101 ){
3102 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3103 fprintf(out,"%s",name);
3104 i += 4;
3105 iStart = i+1;
3106 }
3107 }
3108 }
3109 fprintf(out,"%s",&line[iStart]);
3110 }
3111}
3112
3113/* The next function finds the template file and opens it, returning
3114** a pointer to the opened file. */
3115PRIVATE FILE *tplt_open(lemp)
3116struct lemon *lemp;
3117{
3118 static char templatename[] = "lempar.c";
3119 char buf[1000];
3120 FILE *in;
3121 char *tpltname;
3122 char *cp;
3123
icculus3e143bd2010-02-14 00:48:49 +00003124 /* first, see if user specified a template filename on the command line. */
3125 if (user_templatename != 0) {
3126 if( access(user_templatename,004)==-1 ){
3127 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3128 user_templatename);
3129 lemp->errorcnt++;
3130 return 0;
3131 }
3132 in = fopen(user_templatename,"rb");
3133 if( in==0 ){
3134 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3135 lemp->errorcnt++;
3136 return 0;
3137 }
3138 return in;
3139 }
3140
drh75897232000-05-29 14:26:00 +00003141 cp = strrchr(lemp->filename,'.');
3142 if( cp ){
drh8b582012003-10-21 13:16:03 +00003143 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003144 }else{
3145 sprintf(buf,"%s.lt",lemp->filename);
3146 }
3147 if( access(buf,004)==0 ){
3148 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003149 }else if( access(templatename,004)==0 ){
3150 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003151 }else{
3152 tpltname = pathsearch(lemp->argv0,templatename,0);
3153 }
3154 if( tpltname==0 ){
3155 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3156 templatename);
3157 lemp->errorcnt++;
3158 return 0;
3159 }
drh2aa6ca42004-09-10 00:14:04 +00003160 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003161 if( in==0 ){
3162 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3163 lemp->errorcnt++;
3164 return 0;
3165 }
3166 return in;
3167}
3168
drhaf805ca2004-09-07 11:28:25 +00003169/* Print a #line directive line to the output file. */
3170PRIVATE void tplt_linedir(out,lineno,filename)
3171FILE *out;
3172int lineno;
3173char *filename;
3174{
3175 fprintf(out,"#line %d \"",lineno);
3176 while( *filename ){
3177 if( *filename == '\\' ) putc('\\',out);
3178 putc(*filename,out);
3179 filename++;
3180 }
3181 fprintf(out,"\"\n");
3182}
3183
drh75897232000-05-29 14:26:00 +00003184/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003185PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003186FILE *out;
3187struct lemon *lemp;
3188char *str;
drh75897232000-05-29 14:26:00 +00003189int *lineno;
3190{
3191 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003192 while( *str ){
drh75897232000-05-29 14:26:00 +00003193 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003194 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003195 str++;
3196 }
drh9db55df2004-09-09 14:01:21 +00003197 if( str[-1]!='\n' ){
3198 putc('\n',out);
3199 (*lineno)++;
3200 }
shane58543932008-12-10 20:10:04 +00003201 if (!lemp->nolinenosflag) {
3202 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3203 }
drh75897232000-05-29 14:26:00 +00003204 return;
3205}
3206
3207/*
3208** The following routine emits code for the destructor for the
3209** symbol sp
3210*/
3211void emit_destructor_code(out,sp,lemp,lineno)
3212FILE *out;
3213struct symbol *sp;
3214struct lemon *lemp;
3215int *lineno;
3216{
drhcc83b6e2004-04-23 23:38:42 +00003217 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003218
drh75897232000-05-29 14:26:00 +00003219 if( sp->type==TERMINAL ){
3220 cp = lemp->tokendest;
3221 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003222 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003223 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003224 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003225 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003226 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003227 }else if( lemp->vardest ){
3228 cp = lemp->vardest;
3229 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003230 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003231 }else{
3232 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003233 }
3234 for(; *cp; cp++){
3235 if( *cp=='$' && cp[1]=='$' ){
3236 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3237 cp++;
3238 continue;
3239 }
shane58543932008-12-10 20:10:04 +00003240 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003241 fputc(*cp,out);
3242 }
shane58543932008-12-10 20:10:04 +00003243 fprintf(out,"\n"); (*lineno)++;
3244 if (!lemp->nolinenosflag) {
3245 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3246 }
3247 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003248 return;
3249}
3250
3251/*
drh960e8c62001-04-03 16:53:21 +00003252** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003253*/
3254int has_destructor(sp, lemp)
3255struct symbol *sp;
3256struct lemon *lemp;
3257{
3258 int ret;
3259 if( sp->type==TERMINAL ){
3260 ret = lemp->tokendest!=0;
3261 }else{
drh960e8c62001-04-03 16:53:21 +00003262 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003263 }
3264 return ret;
3265}
3266
drh0bb132b2004-07-20 14:06:51 +00003267/*
3268** Append text to a dynamically allocated string. If zText is 0 then
3269** reset the string to be empty again. Always return the complete text
3270** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003271**
3272** n bytes of zText are stored. If n==0 then all of zText up to the first
3273** \000 terminator is stored. zText can contain up to two instances of
3274** %d. The values of p1 and p2 are written into the first and second
3275** %d.
3276**
3277** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003278*/
3279PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3280 static char *z = 0;
3281 static int alloced = 0;
3282 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003283 int c;
drh0bb132b2004-07-20 14:06:51 +00003284 char zInt[40];
3285
3286 if( zText==0 ){
3287 used = 0;
3288 return z;
3289 }
drh7ac25c72004-08-19 15:12:26 +00003290 if( n<=0 ){
3291 if( n<0 ){
3292 used += n;
3293 assert( used>=0 );
3294 }
drh87cf1372008-08-13 20:09:06 +00003295 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003296 }
drh0bb132b2004-07-20 14:06:51 +00003297 if( n+sizeof(zInt)*2+used >= alloced ){
3298 alloced = n + sizeof(zInt)*2 + used + 200;
3299 z = realloc(z, alloced);
3300 }
3301 if( z==0 ) return "";
3302 while( n-- > 0 ){
3303 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003304 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003305 sprintf(zInt, "%d", p1);
3306 p1 = p2;
3307 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003308 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003309 zText++;
3310 n--;
3311 }else{
3312 z[used++] = c;
3313 }
3314 }
3315 z[used] = 0;
3316 return z;
3317}
3318
3319/*
3320** zCode is a string that is the action associated with a rule. Expand
3321** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003322** stack.
drh0bb132b2004-07-20 14:06:51 +00003323*/
drhaf805ca2004-09-07 11:28:25 +00003324PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003325 char *cp, *xp;
3326 int i;
3327 char lhsused = 0; /* True if the LHS element has been used */
3328 char used[MAXRHS]; /* True for each RHS element which is used */
3329
3330 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3331 lhsused = 0;
3332
drh19c9e562007-03-29 20:13:53 +00003333 if( rp->code==0 ){
3334 rp->code = "\n";
3335 rp->line = rp->ruleline;
3336 }
3337
drh0bb132b2004-07-20 14:06:51 +00003338 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003339 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003340 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3341 char saved;
3342 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3343 saved = *xp;
3344 *xp = 0;
3345 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003346 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003347 cp = xp;
3348 lhsused = 1;
3349 }else{
3350 for(i=0; i<rp->nrhs; i++){
3351 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003352 if( cp!=rp->code && cp[-1]=='@' ){
3353 /* If the argument is of the form @X then substituted
3354 ** the token number of X, not the value of X */
3355 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3356 }else{
drhfd405312005-11-06 04:06:59 +00003357 struct symbol *sp = rp->rhs[i];
3358 int dtnum;
3359 if( sp->type==MULTITERMINAL ){
3360 dtnum = sp->subsym[0]->dtnum;
3361 }else{
3362 dtnum = sp->dtnum;
3363 }
3364 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003365 }
drh0bb132b2004-07-20 14:06:51 +00003366 cp = xp;
3367 used[i] = 1;
3368 break;
3369 }
3370 }
3371 }
3372 *xp = saved;
3373 }
3374 append_str(cp, 1, 0, 0);
3375 } /* End loop */
3376
3377 /* Check to make sure the LHS has been used */
3378 if( rp->lhsalias && !lhsused ){
3379 ErrorMsg(lemp->filename,rp->ruleline,
3380 "Label \"%s\" for \"%s(%s)\" is never used.",
3381 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3382 lemp->errorcnt++;
3383 }
3384
3385 /* Generate destructor code for RHS symbols which are not used in the
3386 ** reduce code */
3387 for(i=0; i<rp->nrhs; i++){
3388 if( rp->rhsalias[i] && !used[i] ){
3389 ErrorMsg(lemp->filename,rp->ruleline,
3390 "Label %s for \"%s(%s)\" is never used.",
3391 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3392 lemp->errorcnt++;
3393 }else if( rp->rhsalias[i]==0 ){
3394 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003395 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003396 rp->rhs[i]->index,i-rp->nrhs+1);
3397 }else{
3398 /* No destructor defined for this term */
3399 }
3400 }
3401 }
drh61e339a2007-01-16 03:09:02 +00003402 if( rp->code ){
3403 cp = append_str(0,0,0,0);
3404 rp->code = Strsafe(cp?cp:"");
3405 }
drh0bb132b2004-07-20 14:06:51 +00003406}
3407
drh75897232000-05-29 14:26:00 +00003408/*
3409** Generate code which executes when the rule "rp" is reduced. Write
3410** the code to "out". Make sure lineno stays up-to-date.
3411*/
3412PRIVATE void emit_code(out,rp,lemp,lineno)
3413FILE *out;
3414struct rule *rp;
3415struct lemon *lemp;
3416int *lineno;
3417{
drh0bb132b2004-07-20 14:06:51 +00003418 char *cp;
drh75897232000-05-29 14:26:00 +00003419
3420 /* Generate code to do the reduce action */
3421 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003422 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003423 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003424 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003425 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003426 } /* End loop */
shane58543932008-12-10 20:10:04 +00003427 fprintf(out,"}\n"); (*lineno)++;
3428 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003429 } /* End if( rp->code ) */
3430
drh75897232000-05-29 14:26:00 +00003431 return;
3432}
3433
3434/*
3435** Print the definition of the union used for the parser's data stack.
3436** This union contains fields for every possible data type for tokens
3437** and nonterminals. In the process of computing and printing this
3438** union, also set the ".dtnum" field of every terminal and nonterminal
3439** symbol.
3440*/
3441void print_stack_union(out,lemp,plineno,mhflag)
3442FILE *out; /* The output stream */
3443struct lemon *lemp; /* The main info structure for this parser */
3444int *plineno; /* Pointer to the line number */
3445int mhflag; /* True if generating makeheaders output */
3446{
3447 int lineno = *plineno; /* The line number of the output */
3448 char **types; /* A hash table of datatypes */
3449 int arraysize; /* Size of the "types" array */
3450 int maxdtlength; /* Maximum length of any ".datatype" field. */
3451 char *stddt; /* Standardized name for a datatype */
3452 int i,j; /* Loop counters */
3453 int hash; /* For hashing the name of a type */
3454 char *name; /* Name of the parser */
3455
3456 /* Allocate and initialize types[] and allocate stddt[] */
3457 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003458 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003459 for(i=0; i<arraysize; i++) types[i] = 0;
3460 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003461 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003462 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003463 }
drh75897232000-05-29 14:26:00 +00003464 for(i=0; i<lemp->nsymbol; i++){
3465 int len;
3466 struct symbol *sp = lemp->symbols[i];
3467 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003468 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003469 if( len>maxdtlength ) maxdtlength = len;
3470 }
3471 stddt = (char*)malloc( maxdtlength*2 + 1 );
3472 if( types==0 || stddt==0 ){
3473 fprintf(stderr,"Out of memory.\n");
3474 exit(1);
3475 }
3476
3477 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3478 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003479 ** used for terminal symbols. If there is no %default_type defined then
3480 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3481 ** a datatype using the %type directive.
3482 */
drh75897232000-05-29 14:26:00 +00003483 for(i=0; i<lemp->nsymbol; i++){
3484 struct symbol *sp = lemp->symbols[i];
3485 char *cp;
3486 if( sp==lemp->errsym ){
3487 sp->dtnum = arraysize+1;
3488 continue;
3489 }
drh960e8c62001-04-03 16:53:21 +00003490 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003491 sp->dtnum = 0;
3492 continue;
3493 }
3494 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003495 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003496 j = 0;
3497 while( isspace(*cp) ) cp++;
3498 while( *cp ) stddt[j++] = *cp++;
3499 while( j>0 && isspace(stddt[j-1]) ) j--;
3500 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003501 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003502 sp->dtnum = 0;
3503 continue;
3504 }
drh75897232000-05-29 14:26:00 +00003505 hash = 0;
3506 for(j=0; stddt[j]; j++){
3507 hash = hash*53 + stddt[j];
3508 }
drh3b2129c2003-05-13 00:34:21 +00003509 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003510 while( types[hash] ){
3511 if( strcmp(types[hash],stddt)==0 ){
3512 sp->dtnum = hash + 1;
3513 break;
3514 }
3515 hash++;
3516 if( hash>=arraysize ) hash = 0;
3517 }
3518 if( types[hash]==0 ){
3519 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003520 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003521 if( types[hash]==0 ){
3522 fprintf(stderr,"Out of memory.\n");
3523 exit(1);
3524 }
3525 strcpy(types[hash],stddt);
3526 }
3527 }
3528
3529 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3530 name = lemp->name ? lemp->name : "Parse";
3531 lineno = *plineno;
3532 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3533 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3534 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3535 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3536 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003537 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003538 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3539 for(i=0; i<arraysize; i++){
3540 if( types[i]==0 ) continue;
3541 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3542 free(types[i]);
3543 }
drhc4dd3fd2008-01-22 01:48:05 +00003544 if( lemp->errsym->useCnt ){
3545 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3546 }
drh75897232000-05-29 14:26:00 +00003547 free(stddt);
3548 free(types);
3549 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3550 *plineno = lineno;
3551}
3552
drhb29b0a52002-02-23 19:39:46 +00003553/*
3554** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003555** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003556*/
drh8b582012003-10-21 13:16:03 +00003557static const char *minimum_size_type(int lwr, int upr){
3558 if( lwr>=0 ){
3559 if( upr<=255 ){
3560 return "unsigned char";
3561 }else if( upr<65535 ){
3562 return "unsigned short int";
3563 }else{
3564 return "unsigned int";
3565 }
3566 }else if( lwr>=-127 && upr<=127 ){
3567 return "signed char";
3568 }else if( lwr>=-32767 && upr<32767 ){
3569 return "short";
drhb29b0a52002-02-23 19:39:46 +00003570 }else{
drh8b582012003-10-21 13:16:03 +00003571 return "int";
drhb29b0a52002-02-23 19:39:46 +00003572 }
3573}
3574
drhfdbf9282003-10-21 16:34:41 +00003575/*
3576** Each state contains a set of token transaction and a set of
3577** nonterminal transactions. Each of these sets makes an instance
3578** of the following structure. An array of these structures is used
3579** to order the creation of entries in the yy_action[] table.
3580*/
3581struct axset {
3582 struct state *stp; /* A pointer to a state */
3583 int isTkn; /* True to use tokens. False for non-terminals */
3584 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003585 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003586};
3587
3588/*
3589** Compare to axset structures for sorting purposes
3590*/
3591static int axset_compare(const void *a, const void *b){
3592 struct axset *p1 = (struct axset*)a;
3593 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003594 int c;
3595 c = p2->nAction - p1->nAction;
3596 if( c==0 ){
3597 c = p2->iOrder - p1->iOrder;
3598 }
3599 assert( c!=0 || p1==p2 );
3600 return c;
drhfdbf9282003-10-21 16:34:41 +00003601}
3602
drhc4dd3fd2008-01-22 01:48:05 +00003603/*
3604** Write text on "out" that describes the rule "rp".
3605*/
3606static void writeRuleText(FILE *out, struct rule *rp){
3607 int j;
3608 fprintf(out,"%s ::=", rp->lhs->name);
3609 for(j=0; j<rp->nrhs; j++){
3610 struct symbol *sp = rp->rhs[j];
3611 fprintf(out," %s", sp->name);
3612 if( sp->type==MULTITERMINAL ){
3613 int k;
3614 for(k=1; k<sp->nsubsym; k++){
3615 fprintf(out,"|%s",sp->subsym[k]->name);
3616 }
3617 }
3618 }
3619}
3620
3621
drh75897232000-05-29 14:26:00 +00003622/* Generate C source code for the parser */
3623void ReportTable(lemp, mhflag)
3624struct lemon *lemp;
3625int mhflag; /* Output in makeheaders format if true */
3626{
3627 FILE *out, *in;
3628 char line[LINESIZE];
3629 int lineno;
3630 struct state *stp;
3631 struct action *ap;
3632 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003633 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003634 int i, j, k, n;
drh75897232000-05-29 14:26:00 +00003635 char *name;
drh8b582012003-10-21 13:16:03 +00003636 int mnTknOfst, mxTknOfst;
3637 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003638 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003639
3640 in = tplt_open(lemp);
3641 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003642 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003643 if( out==0 ){
3644 fclose(in);
3645 return;
3646 }
3647 lineno = 1;
3648 tplt_xfer(lemp->name,in,out,&lineno);
3649
3650 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003651 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003652 if( mhflag ){
3653 char *name = file_makename(lemp, ".h");
3654 fprintf(out,"#include \"%s\"\n", name); lineno++;
3655 free(name);
3656 }
3657 tplt_xfer(lemp->name,in,out,&lineno);
3658
3659 /* Generate #defines for all tokens */
3660 if( mhflag ){
3661 char *prefix;
3662 fprintf(out,"#if INTERFACE\n"); lineno++;
3663 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3664 else prefix = "";
3665 for(i=1; i<lemp->nterminal; i++){
3666 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3667 lineno++;
3668 }
3669 fprintf(out,"#endif\n"); lineno++;
3670 }
3671 tplt_xfer(lemp->name,in,out,&lineno);
3672
3673 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003674 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003675 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003676 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3677 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003678 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003679 if( lemp->wildcard ){
3680 fprintf(out,"#define YYWILDCARD %d\n",
3681 lemp->wildcard->index); lineno++;
3682 }
drh75897232000-05-29 14:26:00 +00003683 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003684 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003685 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003686 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3687 }else{
3688 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3689 }
drhca44b5a2007-02-22 23:06:58 +00003690 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003691 if( mhflag ){
3692 fprintf(out,"#if INTERFACE\n"); lineno++;
3693 }
3694 name = lemp->name ? lemp->name : "Parse";
3695 if( lemp->arg && lemp->arg[0] ){
3696 int i;
drh87cf1372008-08-13 20:09:06 +00003697 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003698 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3699 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003700 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3701 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3702 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3703 name,lemp->arg,&lemp->arg[i]); lineno++;
3704 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3705 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003706 }else{
drh1f245e42002-03-11 13:55:50 +00003707 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3708 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3709 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3710 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003711 }
3712 if( mhflag ){
3713 fprintf(out,"#endif\n"); lineno++;
3714 }
3715 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3716 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003717 if( lemp->errsym->useCnt ){
3718 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3719 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3720 }
drh0bd1f4e2002-06-06 18:54:39 +00003721 if( lemp->has_fallback ){
3722 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3723 }
drh75897232000-05-29 14:26:00 +00003724 tplt_xfer(lemp->name,in,out,&lineno);
3725
drh8b582012003-10-21 13:16:03 +00003726 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003727 **
drh8b582012003-10-21 13:16:03 +00003728 ** yy_action[] A single table containing all actions.
3729 ** yy_lookahead[] A table containing the lookahead for each entry in
3730 ** yy_action. Used to detect hash collisions.
3731 ** yy_shift_ofst[] For each state, the offset into yy_action for
3732 ** shifting terminals.
3733 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3734 ** shifting non-terminals after a reduce.
3735 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003736 */
drh75897232000-05-29 14:26:00 +00003737
drh8b582012003-10-21 13:16:03 +00003738 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003739 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003740 if( ax==0 ){
3741 fprintf(stderr,"malloc failed\n");
3742 exit(1);
3743 }
drh75897232000-05-29 14:26:00 +00003744 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003745 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003746 ax[i*2].stp = stp;
3747 ax[i*2].isTkn = 1;
3748 ax[i*2].nAction = stp->nTknAct;
3749 ax[i*2+1].stp = stp;
3750 ax[i*2+1].isTkn = 0;
3751 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003752 }
drh8b582012003-10-21 13:16:03 +00003753 mxTknOfst = mnTknOfst = 0;
3754 mxNtOfst = mnNtOfst = 0;
3755
drhfdbf9282003-10-21 16:34:41 +00003756 /* Compute the action table. In order to try to keep the size of the
3757 ** action table to a minimum, the heuristic of placing the largest action
3758 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003759 */
drhe594bc32009-11-03 13:02:25 +00003760 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003761 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003762 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003763 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3764 stp = ax[i].stp;
3765 if( ax[i].isTkn ){
3766 for(ap=stp->ap; ap; ap=ap->next){
3767 int action;
3768 if( ap->sp->index>=lemp->nterminal ) continue;
3769 action = compute_action(lemp, ap);
3770 if( action<0 ) continue;
3771 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003772 }
drhfdbf9282003-10-21 16:34:41 +00003773 stp->iTknOfst = acttab_insert(pActtab);
3774 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3775 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3776 }else{
3777 for(ap=stp->ap; ap; ap=ap->next){
3778 int action;
3779 if( ap->sp->index<lemp->nterminal ) continue;
3780 if( ap->sp->index==lemp->nsymbol ) continue;
3781 action = compute_action(lemp, ap);
3782 if( action<0 ) continue;
3783 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003784 }
drhfdbf9282003-10-21 16:34:41 +00003785 stp->iNtOfst = acttab_insert(pActtab);
3786 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3787 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003788 }
3789 }
drhfdbf9282003-10-21 16:34:41 +00003790 free(ax);
drh8b582012003-10-21 13:16:03 +00003791
3792 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003793 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003794 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3795 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003796 for(i=j=0; i<n; i++){
3797 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003798 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003799 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003800 fprintf(out, " %4d,", action);
3801 if( j==9 || i==n-1 ){
3802 fprintf(out, "\n"); lineno++;
3803 j = 0;
3804 }else{
3805 j++;
3806 }
3807 }
3808 fprintf(out, "};\n"); lineno++;
3809
3810 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003811 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003812 for(i=j=0; i<n; i++){
3813 int la = acttab_yylookahead(pActtab, i);
3814 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003815 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003816 fprintf(out, " %4d,", la);
3817 if( j==9 || i==n-1 ){
3818 fprintf(out, "\n"); lineno++;
3819 j = 0;
3820 }else{
3821 j++;
3822 }
3823 }
3824 fprintf(out, "};\n"); lineno++;
3825
3826 /* Output the yy_shift_ofst[] table */
3827 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003828 n = lemp->nstate;
3829 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003830 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3831 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3832 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003833 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003834 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003835 for(i=j=0; i<n; i++){
3836 int ofst;
3837 stp = lemp->sorted[i];
3838 ofst = stp->iTknOfst;
3839 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003840 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003841 fprintf(out, " %4d,", ofst);
3842 if( j==9 || i==n-1 ){
3843 fprintf(out, "\n"); lineno++;
3844 j = 0;
3845 }else{
3846 j++;
3847 }
3848 }
3849 fprintf(out, "};\n"); lineno++;
3850
3851 /* Output the yy_reduce_ofst[] table */
3852 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003853 n = lemp->nstate;
3854 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003855 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3856 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3857 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003858 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003859 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003860 for(i=j=0; i<n; i++){
3861 int ofst;
3862 stp = lemp->sorted[i];
3863 ofst = stp->iNtOfst;
3864 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003865 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003866 fprintf(out, " %4d,", ofst);
3867 if( j==9 || i==n-1 ){
3868 fprintf(out, "\n"); lineno++;
3869 j = 0;
3870 }else{
3871 j++;
3872 }
3873 }
3874 fprintf(out, "};\n"); lineno++;
3875
3876 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003877 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003878 n = lemp->nstate;
3879 for(i=j=0; i<n; i++){
3880 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003881 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003882 fprintf(out, " %4d,", stp->iDflt);
3883 if( j==9 || i==n-1 ){
3884 fprintf(out, "\n"); lineno++;
3885 j = 0;
3886 }else{
3887 j++;
3888 }
3889 }
3890 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003891 tplt_xfer(lemp->name,in,out,&lineno);
3892
drh0bd1f4e2002-06-06 18:54:39 +00003893 /* Generate the table of fallback tokens.
3894 */
3895 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003896 int mx = lemp->nterminal - 1;
3897 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3898 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003899 struct symbol *p = lemp->symbols[i];
3900 if( p->fallback==0 ){
3901 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3902 }else{
3903 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3904 p->name, p->fallback->name);
3905 }
3906 lineno++;
3907 }
3908 }
3909 tplt_xfer(lemp->name, in, out, &lineno);
3910
3911 /* Generate a table containing the symbolic name of every symbol
3912 */
drh75897232000-05-29 14:26:00 +00003913 for(i=0; i<lemp->nsymbol; i++){
3914 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3915 fprintf(out," %-15s",line);
3916 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3917 }
3918 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3919 tplt_xfer(lemp->name,in,out,&lineno);
3920
drh0bd1f4e2002-06-06 18:54:39 +00003921 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003922 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003923 ** when tracing REDUCE actions.
3924 */
3925 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3926 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003927 fprintf(out," /* %3d */ \"", i);
3928 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003929 fprintf(out,"\",\n"); lineno++;
3930 }
3931 tplt_xfer(lemp->name,in,out,&lineno);
3932
drh75897232000-05-29 14:26:00 +00003933 /* Generate code which executes every time a symbol is popped from
3934 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003935 ** (In other words, generate the %destructor actions)
3936 */
drh75897232000-05-29 14:26:00 +00003937 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003938 int once = 1;
drh75897232000-05-29 14:26:00 +00003939 for(i=0; i<lemp->nsymbol; i++){
3940 struct symbol *sp = lemp->symbols[i];
3941 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003942 if( once ){
3943 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3944 once = 0;
3945 }
drhc53eed12009-06-12 17:46:19 +00003946 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003947 }
3948 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3949 if( i<lemp->nsymbol ){
3950 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3951 fprintf(out," break;\n"); lineno++;
3952 }
3953 }
drh8d659732005-01-13 23:54:06 +00003954 if( lemp->vardest ){
3955 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003956 int once = 1;
drh8d659732005-01-13 23:54:06 +00003957 for(i=0; i<lemp->nsymbol; i++){
3958 struct symbol *sp = lemp->symbols[i];
3959 if( sp==0 || sp->type==TERMINAL ||
3960 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003961 if( once ){
3962 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3963 once = 0;
3964 }
drhc53eed12009-06-12 17:46:19 +00003965 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003966 dflt_sp = sp;
3967 }
3968 if( dflt_sp!=0 ){
3969 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003970 }
drh4dc8ef52008-07-01 17:13:57 +00003971 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003972 }
drh75897232000-05-29 14:26:00 +00003973 for(i=0; i<lemp->nsymbol; i++){
3974 struct symbol *sp = lemp->symbols[i];
3975 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003976 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003977
3978 /* Combine duplicate destructors into a single case */
3979 for(j=i+1; j<lemp->nsymbol; j++){
3980 struct symbol *sp2 = lemp->symbols[j];
3981 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3982 && sp2->dtnum==sp->dtnum
3983 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003984 fprintf(out," case %d: /* %s */\n",
3985 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003986 sp2->destructor = 0;
3987 }
3988 }
3989
drh75897232000-05-29 14:26:00 +00003990 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3991 fprintf(out," break;\n"); lineno++;
3992 }
drh75897232000-05-29 14:26:00 +00003993 tplt_xfer(lemp->name,in,out,&lineno);
3994
3995 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003996 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003997 tplt_xfer(lemp->name,in,out,&lineno);
3998
3999 /* Generate the table of rule information
4000 **
4001 ** Note: This code depends on the fact that rules are number
4002 ** sequentually beginning with 0.
4003 */
4004 for(rp=lemp->rule; rp; rp=rp->next){
4005 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4006 }
4007 tplt_xfer(lemp->name,in,out,&lineno);
4008
4009 /* Generate code which execution during each REDUCE action */
4010 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004011 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004012 }
drhc53eed12009-06-12 17:46:19 +00004013 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004014 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004015 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004016 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004017 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004018 fprintf(out," case %d: /* ", rp->index);
4019 writeRuleText(out, rp);
4020 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004021 for(rp2=rp->next; rp2; rp2=rp2->next){
4022 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004023 fprintf(out," case %d: /* ", rp2->index);
4024 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004025 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004026 rp2->code = 0;
4027 }
4028 }
drh75897232000-05-29 14:26:00 +00004029 emit_code(out,rp,lemp,&lineno);
4030 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004031 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004032 }
drhc53eed12009-06-12 17:46:19 +00004033 /* Finally, output the default: rule. We choose as the default: all
4034 ** empty actions. */
4035 fprintf(out," default:\n"); lineno++;
4036 for(rp=lemp->rule; rp; rp=rp->next){
4037 if( rp->code==0 ) continue;
4038 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4039 fprintf(out," /* (%d) ", rp->index);
4040 writeRuleText(out, rp);
4041 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4042 }
4043 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004044 tplt_xfer(lemp->name,in,out,&lineno);
4045
4046 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004047 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004048 tplt_xfer(lemp->name,in,out,&lineno);
4049
4050 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004051 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004052 tplt_xfer(lemp->name,in,out,&lineno);
4053
4054 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004055 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004056 tplt_xfer(lemp->name,in,out,&lineno);
4057
4058 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004059 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004060
4061 fclose(in);
4062 fclose(out);
4063 return;
4064}
4065
4066/* Generate a header file for the parser */
4067void ReportHeader(lemp)
4068struct lemon *lemp;
4069{
4070 FILE *out, *in;
4071 char *prefix;
4072 char line[LINESIZE];
4073 char pattern[LINESIZE];
4074 int i;
4075
4076 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4077 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004078 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004079 if( in ){
4080 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4081 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4082 if( strcmp(line,pattern) ) break;
4083 }
4084 fclose(in);
4085 if( i==lemp->nterminal ){
4086 /* No change in the file. Don't rewrite it. */
4087 return;
4088 }
4089 }
drh2aa6ca42004-09-10 00:14:04 +00004090 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004091 if( out ){
4092 for(i=1; i<lemp->nterminal; i++){
4093 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4094 }
4095 fclose(out);
4096 }
4097 return;
4098}
4099
4100/* Reduce the size of the action tables, if possible, by making use
4101** of defaults.
4102**
drhb59499c2002-02-23 18:45:13 +00004103** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004104** it the default. Except, there is no default if the wildcard token
4105** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004106*/
4107void CompressTables(lemp)
4108struct lemon *lemp;
4109{
4110 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004111 struct action *ap, *ap2;
4112 struct rule *rp, *rp2, *rbest;
4113 int nbest, n;
drh75897232000-05-29 14:26:00 +00004114 int i;
drhe09daa92006-06-10 13:29:31 +00004115 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004116
4117 for(i=0; i<lemp->nstate; i++){
4118 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004119 nbest = 0;
4120 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004121 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004122
drhb59499c2002-02-23 18:45:13 +00004123 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004124 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4125 usesWildcard = 1;
4126 }
drhb59499c2002-02-23 18:45:13 +00004127 if( ap->type!=REDUCE ) continue;
4128 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004129 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004130 if( rp==rbest ) continue;
4131 n = 1;
4132 for(ap2=ap->next; ap2; ap2=ap2->next){
4133 if( ap2->type!=REDUCE ) continue;
4134 rp2 = ap2->x.rp;
4135 if( rp2==rbest ) continue;
4136 if( rp2==rp ) n++;
4137 }
4138 if( n>nbest ){
4139 nbest = n;
4140 rbest = rp;
drh75897232000-05-29 14:26:00 +00004141 }
4142 }
drhb59499c2002-02-23 18:45:13 +00004143
4144 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004145 ** is not at least 1 or if the wildcard token is a possible
4146 ** lookahead.
4147 */
4148 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004149
drhb59499c2002-02-23 18:45:13 +00004150
4151 /* Combine matching REDUCE actions into a single default */
4152 for(ap=stp->ap; ap; ap=ap->next){
4153 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4154 }
drh75897232000-05-29 14:26:00 +00004155 assert( ap );
4156 ap->sp = Symbol_new("{default}");
4157 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004158 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004159 }
4160 stp->ap = Action_sort(stp->ap);
4161 }
4162}
drhb59499c2002-02-23 18:45:13 +00004163
drhada354d2005-11-05 15:03:59 +00004164
4165/*
4166** Compare two states for sorting purposes. The smaller state is the
4167** one with the most non-terminal actions. If they have the same number
4168** of non-terminal actions, then the smaller is the one with the most
4169** token actions.
4170*/
4171static int stateResortCompare(const void *a, const void *b){
4172 const struct state *pA = *(const struct state**)a;
4173 const struct state *pB = *(const struct state**)b;
4174 int n;
4175
4176 n = pB->nNtAct - pA->nNtAct;
4177 if( n==0 ){
4178 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004179 if( n==0 ){
4180 n = pB->statenum - pA->statenum;
4181 }
drhada354d2005-11-05 15:03:59 +00004182 }
drhe594bc32009-11-03 13:02:25 +00004183 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004184 return n;
4185}
4186
4187
4188/*
4189** Renumber and resort states so that states with fewer choices
4190** occur at the end. Except, keep state 0 as the first state.
4191*/
4192void ResortStates(lemp)
4193struct lemon *lemp;
4194{
4195 int i;
4196 struct state *stp;
4197 struct action *ap;
4198
4199 for(i=0; i<lemp->nstate; i++){
4200 stp = lemp->sorted[i];
4201 stp->nTknAct = stp->nNtAct = 0;
4202 stp->iDflt = lemp->nstate + lemp->nrule;
4203 stp->iTknOfst = NO_OFFSET;
4204 stp->iNtOfst = NO_OFFSET;
4205 for(ap=stp->ap; ap; ap=ap->next){
4206 if( compute_action(lemp,ap)>=0 ){
4207 if( ap->sp->index<lemp->nterminal ){
4208 stp->nTknAct++;
4209 }else if( ap->sp->index<lemp->nsymbol ){
4210 stp->nNtAct++;
4211 }else{
4212 stp->iDflt = compute_action(lemp, ap);
4213 }
4214 }
4215 }
4216 }
4217 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4218 stateResortCompare);
4219 for(i=0; i<lemp->nstate; i++){
4220 lemp->sorted[i]->statenum = i;
4221 }
4222}
4223
4224
drh75897232000-05-29 14:26:00 +00004225/***************** From the file "set.c" ************************************/
4226/*
4227** Set manipulation routines for the LEMON parser generator.
4228*/
4229
4230static int size = 0;
4231
4232/* Set the set size */
4233void SetSize(n)
4234int n;
4235{
4236 size = n+1;
4237}
4238
4239/* Allocate a new set */
4240char *SetNew(){
4241 char *s;
drh9892c5d2007-12-21 00:02:11 +00004242 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004243 if( s==0 ){
4244 extern void memory_error();
4245 memory_error();
4246 }
drh75897232000-05-29 14:26:00 +00004247 return s;
4248}
4249
4250/* Deallocate a set */
4251void SetFree(s)
4252char *s;
4253{
4254 free(s);
4255}
4256
4257/* Add a new element to the set. Return TRUE if the element was added
4258** and FALSE if it was already there. */
4259int SetAdd(s,e)
4260char *s;
4261int e;
4262{
4263 int rv;
drh9892c5d2007-12-21 00:02:11 +00004264 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004265 rv = s[e];
4266 s[e] = 1;
4267 return !rv;
4268}
4269
4270/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4271int SetUnion(s1,s2)
4272char *s1;
4273char *s2;
4274{
4275 int i, progress;
4276 progress = 0;
4277 for(i=0; i<size; i++){
4278 if( s2[i]==0 ) continue;
4279 if( s1[i]==0 ){
4280 progress = 1;
4281 s1[i] = 1;
4282 }
4283 }
4284 return progress;
4285}
4286/********************** From the file "table.c" ****************************/
4287/*
4288** All code in this file has been automatically generated
4289** from a specification in the file
4290** "table.q"
4291** by the associative array code building program "aagen".
4292** Do not edit this file! Instead, edit the specification
4293** file, then rerun aagen.
4294*/
4295/*
4296** Code for processing tables in the LEMON parser generator.
4297*/
4298
4299PRIVATE int strhash(x)
4300char *x;
4301{
4302 int h = 0;
4303 while( *x) h = h*13 + *(x++);
4304 return h;
4305}
4306
4307/* Works like strdup, sort of. Save a string in malloced memory, but
4308** keep strings in a table so that the same string is not in more
4309** than one place.
4310*/
4311char *Strsafe(y)
4312char *y;
4313{
4314 char *z;
4315
drh916f75f2006-07-17 00:19:39 +00004316 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004317 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004318 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004319 strcpy(z,y);
4320 Strsafe_insert(z);
4321 }
4322 MemoryCheck(z);
4323 return z;
4324}
4325
4326/* There is one instance of the following structure for each
4327** associative array of type "x1".
4328*/
4329struct s_x1 {
4330 int size; /* The number of available slots. */
4331 /* Must be a power of 2 greater than or */
4332 /* equal to 1 */
4333 int count; /* Number of currently slots filled */
4334 struct s_x1node *tbl; /* The data stored here */
4335 struct s_x1node **ht; /* Hash table for lookups */
4336};
4337
4338/* There is one instance of this structure for every data element
4339** in an associative array of type "x1".
4340*/
4341typedef struct s_x1node {
4342 char *data; /* The data */
4343 struct s_x1node *next; /* Next entry with the same hash */
4344 struct s_x1node **from; /* Previous link */
4345} x1node;
4346
4347/* There is only one instance of the array, which is the following */
4348static struct s_x1 *x1a;
4349
4350/* Allocate a new associative array */
4351void Strsafe_init(){
4352 if( x1a ) return;
4353 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4354 if( x1a ){
4355 x1a->size = 1024;
4356 x1a->count = 0;
4357 x1a->tbl = (x1node*)malloc(
4358 (sizeof(x1node) + sizeof(x1node*))*1024 );
4359 if( x1a->tbl==0 ){
4360 free(x1a);
4361 x1a = 0;
4362 }else{
4363 int i;
4364 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4365 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4366 }
4367 }
4368}
4369/* Insert a new record into the array. Return TRUE if successful.
4370** Prior data with the same key is NOT overwritten */
4371int Strsafe_insert(data)
4372char *data;
4373{
4374 x1node *np;
4375 int h;
4376 int ph;
4377
4378 if( x1a==0 ) return 0;
4379 ph = strhash(data);
4380 h = ph & (x1a->size-1);
4381 np = x1a->ht[h];
4382 while( np ){
4383 if( strcmp(np->data,data)==0 ){
4384 /* An existing entry with the same key is found. */
4385 /* Fail because overwrite is not allows. */
4386 return 0;
4387 }
4388 np = np->next;
4389 }
4390 if( x1a->count>=x1a->size ){
4391 /* Need to make the hash table bigger */
4392 int i,size;
4393 struct s_x1 array;
4394 array.size = size = x1a->size*2;
4395 array.count = x1a->count;
4396 array.tbl = (x1node*)malloc(
4397 (sizeof(x1node) + sizeof(x1node*))*size );
4398 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4399 array.ht = (x1node**)&(array.tbl[size]);
4400 for(i=0; i<size; i++) array.ht[i] = 0;
4401 for(i=0; i<x1a->count; i++){
4402 x1node *oldnp, *newnp;
4403 oldnp = &(x1a->tbl[i]);
4404 h = strhash(oldnp->data) & (size-1);
4405 newnp = &(array.tbl[i]);
4406 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4407 newnp->next = array.ht[h];
4408 newnp->data = oldnp->data;
4409 newnp->from = &(array.ht[h]);
4410 array.ht[h] = newnp;
4411 }
4412 free(x1a->tbl);
4413 *x1a = array;
4414 }
4415 /* Insert the new data */
4416 h = ph & (x1a->size-1);
4417 np = &(x1a->tbl[x1a->count++]);
4418 np->data = data;
4419 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4420 np->next = x1a->ht[h];
4421 x1a->ht[h] = np;
4422 np->from = &(x1a->ht[h]);
4423 return 1;
4424}
4425
4426/* Return a pointer to data assigned to the given key. Return NULL
4427** if no such key. */
4428char *Strsafe_find(key)
4429char *key;
4430{
4431 int h;
4432 x1node *np;
4433
4434 if( x1a==0 ) return 0;
4435 h = strhash(key) & (x1a->size-1);
4436 np = x1a->ht[h];
4437 while( np ){
4438 if( strcmp(np->data,key)==0 ) break;
4439 np = np->next;
4440 }
4441 return np ? np->data : 0;
4442}
4443
4444/* Return a pointer to the (terminal or nonterminal) symbol "x".
4445** Create a new symbol if this is the first time "x" has been seen.
4446*/
4447struct symbol *Symbol_new(x)
4448char *x;
4449{
4450 struct symbol *sp;
4451
4452 sp = Symbol_find(x);
4453 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004454 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004455 MemoryCheck(sp);
4456 sp->name = Strsafe(x);
4457 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4458 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004459 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004460 sp->prec = -1;
4461 sp->assoc = UNK;
4462 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004463 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004464 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004465 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004466 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004467 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004468 Symbol_insert(sp,sp->name);
4469 }
drhc4dd3fd2008-01-22 01:48:05 +00004470 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004471 return sp;
4472}
4473
drh60d31652004-02-22 00:08:04 +00004474/* Compare two symbols for working purposes
4475**
4476** Symbols that begin with upper case letters (terminals or tokens)
4477** must sort before symbols that begin with lower case letters
4478** (non-terminals). Other than that, the order does not matter.
4479**
4480** We find experimentally that leaving the symbols in their original
4481** order (the order they appeared in the grammar file) gives the
4482** smallest parser tables in SQLite.
4483*/
4484int Symbolcmpp(struct symbol **a, struct symbol **b){
4485 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4486 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004487 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004488 return i1-i2;
drh75897232000-05-29 14:26:00 +00004489}
4490
4491/* There is one instance of the following structure for each
4492** associative array of type "x2".
4493*/
4494struct s_x2 {
4495 int size; /* The number of available slots. */
4496 /* Must be a power of 2 greater than or */
4497 /* equal to 1 */
4498 int count; /* Number of currently slots filled */
4499 struct s_x2node *tbl; /* The data stored here */
4500 struct s_x2node **ht; /* Hash table for lookups */
4501};
4502
4503/* There is one instance of this structure for every data element
4504** in an associative array of type "x2".
4505*/
4506typedef struct s_x2node {
4507 struct symbol *data; /* The data */
4508 char *key; /* The key */
4509 struct s_x2node *next; /* Next entry with the same hash */
4510 struct s_x2node **from; /* Previous link */
4511} x2node;
4512
4513/* There is only one instance of the array, which is the following */
4514static struct s_x2 *x2a;
4515
4516/* Allocate a new associative array */
4517void Symbol_init(){
4518 if( x2a ) return;
4519 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4520 if( x2a ){
4521 x2a->size = 128;
4522 x2a->count = 0;
4523 x2a->tbl = (x2node*)malloc(
4524 (sizeof(x2node) + sizeof(x2node*))*128 );
4525 if( x2a->tbl==0 ){
4526 free(x2a);
4527 x2a = 0;
4528 }else{
4529 int i;
4530 x2a->ht = (x2node**)&(x2a->tbl[128]);
4531 for(i=0; i<128; i++) x2a->ht[i] = 0;
4532 }
4533 }
4534}
4535/* Insert a new record into the array. Return TRUE if successful.
4536** Prior data with the same key is NOT overwritten */
4537int Symbol_insert(data,key)
4538struct symbol *data;
4539char *key;
4540{
4541 x2node *np;
4542 int h;
4543 int ph;
4544
4545 if( x2a==0 ) return 0;
4546 ph = strhash(key);
4547 h = ph & (x2a->size-1);
4548 np = x2a->ht[h];
4549 while( np ){
4550 if( strcmp(np->key,key)==0 ){
4551 /* An existing entry with the same key is found. */
4552 /* Fail because overwrite is not allows. */
4553 return 0;
4554 }
4555 np = np->next;
4556 }
4557 if( x2a->count>=x2a->size ){
4558 /* Need to make the hash table bigger */
4559 int i,size;
4560 struct s_x2 array;
4561 array.size = size = x2a->size*2;
4562 array.count = x2a->count;
4563 array.tbl = (x2node*)malloc(
4564 (sizeof(x2node) + sizeof(x2node*))*size );
4565 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4566 array.ht = (x2node**)&(array.tbl[size]);
4567 for(i=0; i<size; i++) array.ht[i] = 0;
4568 for(i=0; i<x2a->count; i++){
4569 x2node *oldnp, *newnp;
4570 oldnp = &(x2a->tbl[i]);
4571 h = strhash(oldnp->key) & (size-1);
4572 newnp = &(array.tbl[i]);
4573 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4574 newnp->next = array.ht[h];
4575 newnp->key = oldnp->key;
4576 newnp->data = oldnp->data;
4577 newnp->from = &(array.ht[h]);
4578 array.ht[h] = newnp;
4579 }
4580 free(x2a->tbl);
4581 *x2a = array;
4582 }
4583 /* Insert the new data */
4584 h = ph & (x2a->size-1);
4585 np = &(x2a->tbl[x2a->count++]);
4586 np->key = key;
4587 np->data = data;
4588 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4589 np->next = x2a->ht[h];
4590 x2a->ht[h] = np;
4591 np->from = &(x2a->ht[h]);
4592 return 1;
4593}
4594
4595/* Return a pointer to data assigned to the given key. Return NULL
4596** if no such key. */
4597struct symbol *Symbol_find(key)
4598char *key;
4599{
4600 int h;
4601 x2node *np;
4602
4603 if( x2a==0 ) return 0;
4604 h = strhash(key) & (x2a->size-1);
4605 np = x2a->ht[h];
4606 while( np ){
4607 if( strcmp(np->key,key)==0 ) break;
4608 np = np->next;
4609 }
4610 return np ? np->data : 0;
4611}
4612
4613/* Return the n-th data. Return NULL if n is out of range. */
4614struct symbol *Symbol_Nth(n)
4615int n;
4616{
4617 struct symbol *data;
4618 if( x2a && n>0 && n<=x2a->count ){
4619 data = x2a->tbl[n-1].data;
4620 }else{
4621 data = 0;
4622 }
4623 return data;
4624}
4625
4626/* Return the size of the array */
4627int Symbol_count()
4628{
4629 return x2a ? x2a->count : 0;
4630}
4631
4632/* Return an array of pointers to all data in the table.
4633** The array is obtained from malloc. Return NULL if memory allocation
4634** problems, or if the array is empty. */
4635struct symbol **Symbol_arrayof()
4636{
4637 struct symbol **array;
4638 int i,size;
4639 if( x2a==0 ) return 0;
4640 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004641 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004642 if( array ){
4643 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4644 }
4645 return array;
4646}
4647
4648/* Compare two configurations */
4649int Configcmp(a,b)
4650struct config *a;
4651struct config *b;
4652{
4653 int x;
4654 x = a->rp->index - b->rp->index;
4655 if( x==0 ) x = a->dot - b->dot;
4656 return x;
4657}
4658
4659/* Compare two states */
4660PRIVATE int statecmp(a,b)
4661struct config *a;
4662struct config *b;
4663{
4664 int rc;
4665 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4666 rc = a->rp->index - b->rp->index;
4667 if( rc==0 ) rc = a->dot - b->dot;
4668 }
4669 if( rc==0 ){
4670 if( a ) rc = 1;
4671 if( b ) rc = -1;
4672 }
4673 return rc;
4674}
4675
4676/* Hash a state */
4677PRIVATE int statehash(a)
4678struct config *a;
4679{
4680 int h=0;
4681 while( a ){
4682 h = h*571 + a->rp->index*37 + a->dot;
4683 a = a->bp;
4684 }
4685 return h;
4686}
4687
4688/* Allocate a new state structure */
4689struct state *State_new()
4690{
4691 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004692 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004693 MemoryCheck(new);
4694 return new;
4695}
4696
4697/* There is one instance of the following structure for each
4698** associative array of type "x3".
4699*/
4700struct s_x3 {
4701 int size; /* The number of available slots. */
4702 /* Must be a power of 2 greater than or */
4703 /* equal to 1 */
4704 int count; /* Number of currently slots filled */
4705 struct s_x3node *tbl; /* The data stored here */
4706 struct s_x3node **ht; /* Hash table for lookups */
4707};
4708
4709/* There is one instance of this structure for every data element
4710** in an associative array of type "x3".
4711*/
4712typedef struct s_x3node {
4713 struct state *data; /* The data */
4714 struct config *key; /* The key */
4715 struct s_x3node *next; /* Next entry with the same hash */
4716 struct s_x3node **from; /* Previous link */
4717} x3node;
4718
4719/* There is only one instance of the array, which is the following */
4720static struct s_x3 *x3a;
4721
4722/* Allocate a new associative array */
4723void State_init(){
4724 if( x3a ) return;
4725 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4726 if( x3a ){
4727 x3a->size = 128;
4728 x3a->count = 0;
4729 x3a->tbl = (x3node*)malloc(
4730 (sizeof(x3node) + sizeof(x3node*))*128 );
4731 if( x3a->tbl==0 ){
4732 free(x3a);
4733 x3a = 0;
4734 }else{
4735 int i;
4736 x3a->ht = (x3node**)&(x3a->tbl[128]);
4737 for(i=0; i<128; i++) x3a->ht[i] = 0;
4738 }
4739 }
4740}
4741/* Insert a new record into the array. Return TRUE if successful.
4742** Prior data with the same key is NOT overwritten */
4743int State_insert(data,key)
4744struct state *data;
4745struct config *key;
4746{
4747 x3node *np;
4748 int h;
4749 int ph;
4750
4751 if( x3a==0 ) return 0;
4752 ph = statehash(key);
4753 h = ph & (x3a->size-1);
4754 np = x3a->ht[h];
4755 while( np ){
4756 if( statecmp(np->key,key)==0 ){
4757 /* An existing entry with the same key is found. */
4758 /* Fail because overwrite is not allows. */
4759 return 0;
4760 }
4761 np = np->next;
4762 }
4763 if( x3a->count>=x3a->size ){
4764 /* Need to make the hash table bigger */
4765 int i,size;
4766 struct s_x3 array;
4767 array.size = size = x3a->size*2;
4768 array.count = x3a->count;
4769 array.tbl = (x3node*)malloc(
4770 (sizeof(x3node) + sizeof(x3node*))*size );
4771 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4772 array.ht = (x3node**)&(array.tbl[size]);
4773 for(i=0; i<size; i++) array.ht[i] = 0;
4774 for(i=0; i<x3a->count; i++){
4775 x3node *oldnp, *newnp;
4776 oldnp = &(x3a->tbl[i]);
4777 h = statehash(oldnp->key) & (size-1);
4778 newnp = &(array.tbl[i]);
4779 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4780 newnp->next = array.ht[h];
4781 newnp->key = oldnp->key;
4782 newnp->data = oldnp->data;
4783 newnp->from = &(array.ht[h]);
4784 array.ht[h] = newnp;
4785 }
4786 free(x3a->tbl);
4787 *x3a = array;
4788 }
4789 /* Insert the new data */
4790 h = ph & (x3a->size-1);
4791 np = &(x3a->tbl[x3a->count++]);
4792 np->key = key;
4793 np->data = data;
4794 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4795 np->next = x3a->ht[h];
4796 x3a->ht[h] = np;
4797 np->from = &(x3a->ht[h]);
4798 return 1;
4799}
4800
4801/* Return a pointer to data assigned to the given key. Return NULL
4802** if no such key. */
4803struct state *State_find(key)
4804struct config *key;
4805{
4806 int h;
4807 x3node *np;
4808
4809 if( x3a==0 ) return 0;
4810 h = statehash(key) & (x3a->size-1);
4811 np = x3a->ht[h];
4812 while( np ){
4813 if( statecmp(np->key,key)==0 ) break;
4814 np = np->next;
4815 }
4816 return np ? np->data : 0;
4817}
4818
4819/* Return an array of pointers to all data in the table.
4820** The array is obtained from malloc. Return NULL if memory allocation
4821** problems, or if the array is empty. */
4822struct state **State_arrayof()
4823{
4824 struct state **array;
4825 int i,size;
4826 if( x3a==0 ) return 0;
4827 size = x3a->count;
4828 array = (struct state **)malloc( sizeof(struct state *)*size );
4829 if( array ){
4830 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4831 }
4832 return array;
4833}
4834
4835/* Hash a configuration */
4836PRIVATE int confighash(a)
4837struct config *a;
4838{
4839 int h=0;
4840 h = h*571 + a->rp->index*37 + a->dot;
4841 return h;
4842}
4843
4844/* There is one instance of the following structure for each
4845** associative array of type "x4".
4846*/
4847struct s_x4 {
4848 int size; /* The number of available slots. */
4849 /* Must be a power of 2 greater than or */
4850 /* equal to 1 */
4851 int count; /* Number of currently slots filled */
4852 struct s_x4node *tbl; /* The data stored here */
4853 struct s_x4node **ht; /* Hash table for lookups */
4854};
4855
4856/* There is one instance of this structure for every data element
4857** in an associative array of type "x4".
4858*/
4859typedef struct s_x4node {
4860 struct config *data; /* The data */
4861 struct s_x4node *next; /* Next entry with the same hash */
4862 struct s_x4node **from; /* Previous link */
4863} x4node;
4864
4865/* There is only one instance of the array, which is the following */
4866static struct s_x4 *x4a;
4867
4868/* Allocate a new associative array */
4869void Configtable_init(){
4870 if( x4a ) return;
4871 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4872 if( x4a ){
4873 x4a->size = 64;
4874 x4a->count = 0;
4875 x4a->tbl = (x4node*)malloc(
4876 (sizeof(x4node) + sizeof(x4node*))*64 );
4877 if( x4a->tbl==0 ){
4878 free(x4a);
4879 x4a = 0;
4880 }else{
4881 int i;
4882 x4a->ht = (x4node**)&(x4a->tbl[64]);
4883 for(i=0; i<64; i++) x4a->ht[i] = 0;
4884 }
4885 }
4886}
4887/* Insert a new record into the array. Return TRUE if successful.
4888** Prior data with the same key is NOT overwritten */
4889int Configtable_insert(data)
4890struct config *data;
4891{
4892 x4node *np;
4893 int h;
4894 int ph;
4895
4896 if( x4a==0 ) return 0;
4897 ph = confighash(data);
4898 h = ph & (x4a->size-1);
4899 np = x4a->ht[h];
4900 while( np ){
4901 if( Configcmp(np->data,data)==0 ){
4902 /* An existing entry with the same key is found. */
4903 /* Fail because overwrite is not allows. */
4904 return 0;
4905 }
4906 np = np->next;
4907 }
4908 if( x4a->count>=x4a->size ){
4909 /* Need to make the hash table bigger */
4910 int i,size;
4911 struct s_x4 array;
4912 array.size = size = x4a->size*2;
4913 array.count = x4a->count;
4914 array.tbl = (x4node*)malloc(
4915 (sizeof(x4node) + sizeof(x4node*))*size );
4916 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4917 array.ht = (x4node**)&(array.tbl[size]);
4918 for(i=0; i<size; i++) array.ht[i] = 0;
4919 for(i=0; i<x4a->count; i++){
4920 x4node *oldnp, *newnp;
4921 oldnp = &(x4a->tbl[i]);
4922 h = confighash(oldnp->data) & (size-1);
4923 newnp = &(array.tbl[i]);
4924 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4925 newnp->next = array.ht[h];
4926 newnp->data = oldnp->data;
4927 newnp->from = &(array.ht[h]);
4928 array.ht[h] = newnp;
4929 }
4930 free(x4a->tbl);
4931 *x4a = array;
4932 }
4933 /* Insert the new data */
4934 h = ph & (x4a->size-1);
4935 np = &(x4a->tbl[x4a->count++]);
4936 np->data = data;
4937 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4938 np->next = x4a->ht[h];
4939 x4a->ht[h] = np;
4940 np->from = &(x4a->ht[h]);
4941 return 1;
4942}
4943
4944/* Return a pointer to data assigned to the given key. Return NULL
4945** if no such key. */
4946struct config *Configtable_find(key)
4947struct config *key;
4948{
4949 int h;
4950 x4node *np;
4951
4952 if( x4a==0 ) return 0;
4953 h = confighash(key) & (x4a->size-1);
4954 np = x4a->ht[h];
4955 while( np ){
4956 if( Configcmp(np->data,key)==0 ) break;
4957 np = np->next;
4958 }
4959 return np ? np->data : 0;
4960}
4961
4962/* Remove all data from the table. Pass each data to the function "f"
4963** as it is removed. ("f" may be null to avoid this step.) */
4964void Configtable_clear(f)
4965int(*f)(/* struct config * */);
4966{
4967 int i;
4968 if( x4a==0 || x4a->count==0 ) return;
4969 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4970 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4971 x4a->count = 0;
4972 return;
4973}