blob: 4a3bfa1871d568b3638802825c2d00aec09ac381 [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
icculusf5ad8242010-02-14 05:34:42 +000037static const char **made_files = NULL;
38static int made_files_count = 0;
39static int successful_exit = 0;
40static void LemonAtExit(void)
41{
42 /* if we failed, delete (most) files we made, to unconfuse build tools. */
43 int i;
44 for (i = 0; i < made_files_count; i++) {
45 if (!successful_exit) {
46 remove(made_files[i]);
47 }
48 free((void *) made_files[i]);
49 }
50 free(made_files);
51 made_files_count = 0;
52 made_files = NULL;
53}
54
drhe9278182007-07-18 18:16:29 +000055static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000056
drh87cf1372008-08-13 20:09:06 +000057/*
58** Compilers are getting increasingly pedantic about type conversions
59** as C evolves ever closer to Ada.... To work around the latest problems
60** we have to define the following variant of strlen().
61*/
62#define lemonStrlen(X) ((int)strlen(X))
63
drhe9278182007-07-18 18:16:29 +000064static struct action *Action_new(void);
65static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000066
67/********** From the file "build.h" ************************************/
68void FindRulePrecedences();
69void FindFirstSets();
70void FindStates();
71void FindLinks();
72void FindFollowSets();
73void FindActions();
74
75/********* From the file "configlist.h" *********************************/
76void Configlist_init(/* void */);
77struct config *Configlist_add(/* struct rule *, int */);
78struct config *Configlist_addbasis(/* struct rule *, int */);
79void Configlist_closure(/* void */);
80void Configlist_sort(/* void */);
81void Configlist_sortbasis(/* void */);
82struct config *Configlist_return(/* void */);
83struct config *Configlist_basis(/* void */);
84void Configlist_eat(/* struct config * */);
85void Configlist_reset(/* void */);
86
87/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000088void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000089
90/****** From the file "option.h" ******************************************/
91struct s_options {
92 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
93 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
94 char *label;
95 char *arg;
96 char *message;
97};
drhb0c86772000-06-02 23:21:26 +000098int OptInit(/* char**,struct s_options*,FILE* */);
99int OptNArgs(/* void */);
100char *OptArg(/* int */);
101void OptErr(/* int */);
102void OptPrint(/* void */);
drh75897232000-05-29 14:26:00 +0000103
104/******** From the file "parse.h" *****************************************/
105void Parse(/* struct lemon *lemp */);
106
107/********* From the file "plink.h" ***************************************/
108struct plink *Plink_new(/* void */);
109void Plink_add(/* struct plink **, struct config * */);
110void Plink_copy(/* struct plink **, struct plink * */);
111void Plink_delete(/* struct plink * */);
112
113/********** From the file "report.h" *************************************/
114void Reprint(/* struct lemon * */);
115void ReportOutput(/* struct lemon * */);
116void ReportTable(/* struct lemon * */);
117void ReportHeader(/* struct lemon * */);
118void CompressTables(/* struct lemon * */);
drhada354d2005-11-05 15:03:59 +0000119void ResortStates(/* struct lemon * */);
drh75897232000-05-29 14:26:00 +0000120
121/********** From the file "set.h" ****************************************/
122void SetSize(/* int N */); /* All sets will be of size N */
123char *SetNew(/* void */); /* A new set for element 0..N */
124void SetFree(/* char* */); /* Deallocate a set */
125
126int SetAdd(/* char*,int */); /* Add element to a set */
127int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
128
129#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
130
131/********** From the file "struct.h" *************************************/
132/*
133** Principal data structures for the LEMON parser generator.
134*/
135
drhaa9f1122007-08-23 02:50:56 +0000136typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000137
138/* Symbols (terminals and nonterminals) of the grammar are stored
139** in the following: */
140struct symbol {
141 char *name; /* Name of the symbol */
142 int index; /* Index number for this symbol */
143 enum {
144 TERMINAL,
drhfd405312005-11-06 04:06:59 +0000145 NONTERMINAL,
146 MULTITERMINAL
drh75897232000-05-29 14:26:00 +0000147 } type; /* Symbols are all either TERMINALS or NTs */
148 struct rule *rule; /* Linked list of rules of this (if an NT) */
drh0bd1f4e2002-06-06 18:54:39 +0000149 struct symbol *fallback; /* fallback token in case this token doesn't parse */
drh75897232000-05-29 14:26:00 +0000150 int prec; /* Precedence if defined (-1 otherwise) */
151 enum e_assoc {
152 LEFT,
153 RIGHT,
154 NONE,
155 UNK
drh34ff57b2008-07-14 12:27:51 +0000156 } assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000157 char *firstset; /* First-set for all rules of this symbol */
158 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000159 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000160 char *destructor; /* Code which executes whenever this symbol is
161 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000162 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000163 char *datatype; /* The data type of information held by this
164 ** object. Only used if type==NONTERMINAL */
165 int dtnum; /* The data type number. In the parser, the value
166 ** stack is a union. The .yy%d element of this
167 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000168 /* The following fields are used by MULTITERMINALs only */
169 int nsubsym; /* Number of constituent symbols in the MULTI */
170 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000171};
172
173/* Each production rule in the grammar is stored in the following
174** structure. */
175struct rule {
176 struct symbol *lhs; /* Left-hand side of the rule */
177 char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000178 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000179 int ruleline; /* Line number for the rule */
180 int nrhs; /* Number of RHS symbols */
181 struct symbol **rhs; /* The RHS symbols */
182 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
183 int line; /* Line number at which code begins */
184 char *code; /* The code executed when this rule is reduced */
185 struct symbol *precsym; /* Precedence symbol for this rule */
186 int index; /* An index number for this rule */
187 Boolean canReduce; /* True if this rule is ever reduced */
188 struct rule *nextlhs; /* Next rule with the same LHS */
189 struct rule *next; /* Next rule in the global list */
190};
191
192/* A configuration is a production rule of the grammar together with
193** a mark (dot) showing how much of that rule has been processed so far.
194** Configurations also contain a follow-set which is a list of terminal
195** symbols which are allowed to immediately follow the end of the rule.
196** Every configuration is recorded as an instance of the following: */
197struct config {
198 struct rule *rp; /* The rule upon which the configuration is based */
199 int dot; /* The parse point */
200 char *fws; /* Follow-set for this configuration only */
201 struct plink *fplp; /* Follow-set forward propagation links */
202 struct plink *bplp; /* Follow-set backwards propagation links */
203 struct state *stp; /* Pointer to state which contains this */
204 enum {
205 COMPLETE, /* The status is used during followset and */
206 INCOMPLETE /* shift computations */
207 } status;
208 struct config *next; /* Next configuration in the state */
209 struct config *bp; /* The next basis configuration */
210};
211
212/* Every shift or reduce operation is stored as one of the following */
213struct action {
214 struct symbol *sp; /* The look-ahead symbol */
215 enum e_action {
216 SHIFT,
217 ACCEPT,
218 REDUCE,
219 ERROR,
drh9892c5d2007-12-21 00:02:11 +0000220 SSCONFLICT, /* A shift/shift conflict */
221 SRCONFLICT, /* Was a reduce, but part of a conflict */
222 RRCONFLICT, /* Was a reduce, but part of a conflict */
drh75897232000-05-29 14:26:00 +0000223 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
224 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
225 NOT_USED /* Deleted by compression */
226 } type;
227 union {
228 struct state *stp; /* The new state, if a shift */
229 struct rule *rp; /* The rule, if a reduce */
230 } x;
231 struct action *next; /* Next action for this state */
232 struct action *collide; /* Next action with the same hash */
233};
234
235/* Each state of the generated parser's finite state machine
236** is encoded as an instance of the following structure. */
237struct state {
238 struct config *bp; /* The basis configurations for this state */
239 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000240 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000241 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000242 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
243 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
244 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000245};
drh8b582012003-10-21 13:16:03 +0000246#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000247
248/* A followset propagation link indicates that the contents of one
249** configuration followset should be propagated to another whenever
250** the first changes. */
251struct plink {
252 struct config *cfp; /* The configuration to which linked */
253 struct plink *next; /* The next propagate link */
254};
255
256/* The state vector for the entire parser generator is recorded as
257** follows. (LEMON uses no global variables and makes little use of
258** static variables. Fields in the following structure can be thought
259** of as begin global variables in the program.) */
260struct lemon {
261 struct state **sorted; /* Table of states sorted by state number */
262 struct rule *rule; /* List of all rules */
263 int nstate; /* Number of states */
264 int nrule; /* Number of rules */
265 int nsymbol; /* Number of terminal and nonterminal symbols */
266 int nterminal; /* Number of terminal symbols */
267 struct symbol **symbols; /* Sorted array of pointers to symbols */
268 int errorcnt; /* Number of errors */
269 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000270 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000271 char *name; /* Name of the generated parser */
272 char *arg; /* Declaration of the 3th argument to parser */
273 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000274 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000275 char *start; /* Name of the start symbol for the grammar */
276 char *stacksize; /* Size of the parser stack */
277 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000278 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000279 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000280 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000281 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000282 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000283 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000284 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000285 char *filename; /* Name of the input file */
286 char *outname; /* Name of the current output file */
287 char *tokenprefix; /* A prefix added to token names in the .h file */
288 int nconflict; /* Number of parsing conflicts */
icculus42585cf2010-02-14 05:19:56 +0000289 int nexpected; /* Number of expected parsing conflicts */
drh75897232000-05-29 14:26:00 +0000290 int tablesize; /* Size of the parse tables */
291 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000292 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000293 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000294 char *argv0; /* Name of the program */
295};
296
297#define MemoryCheck(X) if((X)==0){ \
298 extern void memory_error(); \
299 memory_error(); \
300}
301
302/**************** From the file "table.h" *********************************/
303/*
304** All code in this file has been automatically generated
305** from a specification in the file
306** "table.q"
307** by the associative array code building program "aagen".
308** Do not edit this file! Instead, edit the specification
309** file, then rerun aagen.
310*/
311/*
312** Code for processing tables in the LEMON parser generator.
313*/
314
315/* Routines for handling a strings */
316
317char *Strsafe();
318
319void Strsafe_init(/* void */);
320int Strsafe_insert(/* char * */);
321char *Strsafe_find(/* char * */);
322
323/* Routines for handling symbols of the grammar */
324
325struct symbol *Symbol_new();
326int Symbolcmpp(/* struct symbol **, struct symbol ** */);
327void Symbol_init(/* void */);
328int Symbol_insert(/* struct symbol *, char * */);
329struct symbol *Symbol_find(/* char * */);
330struct symbol *Symbol_Nth(/* int */);
331int Symbol_count(/* */);
332struct symbol **Symbol_arrayof(/* */);
333
334/* Routines to manage the state table */
335
336int Configcmp(/* struct config *, struct config * */);
337struct state *State_new();
338void State_init(/* void */);
339int State_insert(/* struct state *, struct config * */);
340struct state *State_find(/* struct config * */);
341struct state **State_arrayof(/* */);
342
343/* Routines used for efficiency in Configlist_add */
344
345void Configtable_init(/* void */);
346int Configtable_insert(/* struct config * */);
347struct config *Configtable_find(/* struct config * */);
348void Configtable_clear(/* int(*)(struct config *) */);
349/****************** From the file "action.c" *******************************/
350/*
351** Routines processing parser actions in the LEMON parser generator.
352*/
353
354/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000355static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000356 static struct action *freelist = 0;
357 struct action *new;
358
359 if( freelist==0 ){
360 int i;
361 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000362 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000363 if( freelist==0 ){
364 fprintf(stderr,"Unable to allocate memory for a new parser action.");
365 exit(1);
366 }
367 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
368 freelist[amt-1].next = 0;
369 }
370 new = freelist;
371 freelist = freelist->next;
372 return new;
373}
374
drhe9278182007-07-18 18:16:29 +0000375/* Compare two actions for sorting purposes. Return negative, zero, or
376** positive if the first action is less than, equal to, or greater than
377** the first
378*/
379static int actioncmp(
380 struct action *ap1,
381 struct action *ap2
382){
drh75897232000-05-29 14:26:00 +0000383 int rc;
384 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000385 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000386 rc = (int)ap1->type - (int)ap2->type;
387 }
388 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000389 rc = ap1->x.rp->index - ap2->x.rp->index;
390 }
drhe594bc32009-11-03 13:02:25 +0000391 if( rc==0 ){
392 rc = ap2 - ap1;
393 }
drh75897232000-05-29 14:26:00 +0000394 return rc;
395}
396
397/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000398static struct action *Action_sort(
399 struct action *ap
400){
401 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
402 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000403 return ap;
404}
405
406void Action_add(app,type,sp,arg)
407struct action **app;
408enum e_action type;
409struct symbol *sp;
410char *arg;
411{
412 struct action *new;
413 new = Action_new();
414 new->next = *app;
415 *app = new;
416 new->type = type;
417 new->sp = sp;
418 if( type==SHIFT ){
419 new->x.stp = (struct state *)arg;
420 }else{
421 new->x.rp = (struct rule *)arg;
422 }
423}
drh8b582012003-10-21 13:16:03 +0000424/********************** New code to implement the "acttab" module ***********/
425/*
426** This module implements routines use to construct the yy_action[] table.
427*/
428
429/*
430** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000431** the following structure.
432**
433** The yy_action table maps the pair (state_number, lookahead) into an
434** action_number. The table is an array of integers pairs. The state_number
435** determines an initial offset into the yy_action array. The lookahead
436** value is then added to this initial offset to get an index X into the
437** yy_action array. If the aAction[X].lookahead equals the value of the
438** of the lookahead input, then the value of the action_number output is
439** aAction[X].action. If the lookaheads do not match then the
440** default action for the state_number is returned.
441**
442** All actions associated with a single state_number are first entered
443** into aLookahead[] using multiple calls to acttab_action(). Then the
444** actions for that single state_number are placed into the aAction[]
445** array with a single call to acttab_insert(). The acttab_insert() call
446** also resets the aLookahead[] array in preparation for the next
447** state number.
drh8b582012003-10-21 13:16:03 +0000448*/
449typedef struct acttab acttab;
450struct acttab {
451 int nAction; /* Number of used slots in aAction[] */
452 int nActionAlloc; /* Slots allocated for aAction[] */
453 struct {
454 int lookahead; /* Value of the lookahead token */
455 int action; /* Action to take on the given lookahead */
456 } *aAction, /* The yy_action[] table under construction */
457 *aLookahead; /* A single new transaction set */
458 int mnLookahead; /* Minimum aLookahead[].lookahead */
459 int mnAction; /* Action associated with mnLookahead */
460 int mxLookahead; /* Maximum aLookahead[].lookahead */
461 int nLookahead; /* Used slots in aLookahead[] */
462 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
463};
464
465/* Return the number of entries in the yy_action table */
466#define acttab_size(X) ((X)->nAction)
467
468/* The value for the N-th entry in yy_action */
469#define acttab_yyaction(X,N) ((X)->aAction[N].action)
470
471/* The value for the N-th entry in yy_lookahead */
472#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
473
474/* Free all memory associated with the given acttab */
475void acttab_free(acttab *p){
476 free( p->aAction );
477 free( p->aLookahead );
478 free( p );
479}
480
481/* Allocate a new acttab structure */
482acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000483 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000484 if( p==0 ){
485 fprintf(stderr,"Unable to allocate memory for a new acttab.");
486 exit(1);
487 }
488 memset(p, 0, sizeof(*p));
489 return p;
490}
491
drh8dc3e8f2010-01-07 03:53:03 +0000492/* Add a new action to the current transaction set.
493**
494** This routine is called once for each lookahead for a particular
495** state.
drh8b582012003-10-21 13:16:03 +0000496*/
497void acttab_action(acttab *p, int lookahead, int action){
498 if( p->nLookahead>=p->nLookaheadAlloc ){
499 p->nLookaheadAlloc += 25;
500 p->aLookahead = realloc( p->aLookahead,
501 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
502 if( p->aLookahead==0 ){
503 fprintf(stderr,"malloc failed\n");
504 exit(1);
505 }
506 }
507 if( p->nLookahead==0 ){
508 p->mxLookahead = lookahead;
509 p->mnLookahead = lookahead;
510 p->mnAction = action;
511 }else{
512 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
513 if( p->mnLookahead>lookahead ){
514 p->mnLookahead = lookahead;
515 p->mnAction = action;
516 }
517 }
518 p->aLookahead[p->nLookahead].lookahead = lookahead;
519 p->aLookahead[p->nLookahead].action = action;
520 p->nLookahead++;
521}
522
523/*
524** Add the transaction set built up with prior calls to acttab_action()
525** into the current action table. Then reset the transaction set back
526** to an empty set in preparation for a new round of acttab_action() calls.
527**
528** Return the offset into the action table of the new transaction.
529*/
530int acttab_insert(acttab *p){
531 int i, j, k, n;
532 assert( p->nLookahead>0 );
533
534 /* Make sure we have enough space to hold the expanded action table
535 ** in the worst case. The worst case occurs if the transaction set
536 ** must be appended to the current action table
537 */
drh784d86f2004-02-19 18:41:53 +0000538 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000539 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000540 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000541 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
542 p->aAction = realloc( p->aAction,
543 sizeof(p->aAction[0])*p->nActionAlloc);
544 if( p->aAction==0 ){
545 fprintf(stderr,"malloc failed\n");
546 exit(1);
547 }
drhfdbf9282003-10-21 16:34:41 +0000548 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000549 p->aAction[i].lookahead = -1;
550 p->aAction[i].action = -1;
551 }
552 }
553
drh8dc3e8f2010-01-07 03:53:03 +0000554 /* Scan the existing action table looking for an offset that is a
555 ** duplicate of the current transaction set. Fall out of the loop
556 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000557 **
558 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
559 */
drh8dc3e8f2010-01-07 03:53:03 +0000560 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000561 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000562 /* All lookaheads and actions in the aLookahead[] transaction
563 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000564 if( p->aAction[i].action!=p->mnAction ) continue;
565 for(j=0; j<p->nLookahead; j++){
566 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
567 if( k<0 || k>=p->nAction ) break;
568 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
569 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
570 }
571 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000572
573 /* No possible lookahead value that is not in the aLookahead[]
574 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000575 n = 0;
576 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000577 if( p->aAction[j].lookahead<0 ) continue;
578 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000579 }
drhfdbf9282003-10-21 16:34:41 +0000580 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000581 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000582 }
drh8b582012003-10-21 13:16:03 +0000583 }
584 }
drh8dc3e8f2010-01-07 03:53:03 +0000585
586 /* If no existing offsets exactly match the current transaction, find an
587 ** an empty offset in the aAction[] table in which we can add the
588 ** aLookahead[] transaction.
589 */
drhf16371d2009-11-03 19:18:31 +0000590 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000591 /* Look for holes in the aAction[] table that fit the current
592 ** aLookahead[] transaction. Leave i set to the offset of the hole.
593 ** If no holes are found, i is left at p->nAction, which means the
594 ** transaction will be appended. */
595 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000596 if( p->aAction[i].lookahead<0 ){
597 for(j=0; j<p->nLookahead; j++){
598 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
599 if( k<0 ) break;
600 if( p->aAction[k].lookahead>=0 ) break;
601 }
602 if( j<p->nLookahead ) continue;
603 for(j=0; j<p->nAction; j++){
604 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
605 }
606 if( j==p->nAction ){
607 break; /* Fits in empty slots */
608 }
609 }
610 }
611 }
drh8b582012003-10-21 13:16:03 +0000612 /* Insert transaction set at index i. */
613 for(j=0; j<p->nLookahead; j++){
614 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
615 p->aAction[k] = p->aLookahead[j];
616 if( k>=p->nAction ) p->nAction = k+1;
617 }
618 p->nLookahead = 0;
619
620 /* Return the offset that is added to the lookahead in order to get the
621 ** index into yy_action of the action */
622 return i - p->mnLookahead;
623}
624
drh75897232000-05-29 14:26:00 +0000625/********************** From the file "build.c" *****************************/
626/*
627** Routines to construction the finite state machine for the LEMON
628** parser generator.
629*/
630
631/* Find a precedence symbol of every rule in the grammar.
632**
633** Those rules which have a precedence symbol coded in the input
634** grammar using the "[symbol]" construct will already have the
635** rp->precsym field filled. Other rules take as their precedence
636** symbol the first RHS symbol with a defined precedence. If there
637** are not RHS symbols with a defined precedence, the precedence
638** symbol field is left blank.
639*/
640void FindRulePrecedences(xp)
641struct lemon *xp;
642{
643 struct rule *rp;
644 for(rp=xp->rule; rp; rp=rp->next){
645 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000646 int i, j;
647 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
648 struct symbol *sp = rp->rhs[i];
649 if( sp->type==MULTITERMINAL ){
650 for(j=0; j<sp->nsubsym; j++){
651 if( sp->subsym[j]->prec>=0 ){
652 rp->precsym = sp->subsym[j];
653 break;
654 }
655 }
656 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000657 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000658 }
659 }
660 }
661 }
662 return;
663}
664
665/* Find all nonterminals which will generate the empty string.
666** Then go back and compute the first sets of every nonterminal.
667** The first set is the set of all terminal symbols which can begin
668** a string generated by that nonterminal.
669*/
670void FindFirstSets(lemp)
671struct lemon *lemp;
672{
drhfd405312005-11-06 04:06:59 +0000673 int i, j;
drh75897232000-05-29 14:26:00 +0000674 struct rule *rp;
675 int progress;
676
677 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000678 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000679 }
680 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
681 lemp->symbols[i]->firstset = SetNew();
682 }
683
684 /* First compute all lambdas */
685 do{
686 progress = 0;
687 for(rp=lemp->rule; rp; rp=rp->next){
688 if( rp->lhs->lambda ) continue;
689 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000690 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000691 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000692 }
693 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000694 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000695 progress = 1;
696 }
697 }
698 }while( progress );
699
700 /* Now compute all first sets */
701 do{
702 struct symbol *s1, *s2;
703 progress = 0;
704 for(rp=lemp->rule; rp; rp=rp->next){
705 s1 = rp->lhs;
706 for(i=0; i<rp->nrhs; i++){
707 s2 = rp->rhs[i];
708 if( s2->type==TERMINAL ){
709 progress += SetAdd(s1->firstset,s2->index);
710 break;
drhfd405312005-11-06 04:06:59 +0000711 }else if( s2->type==MULTITERMINAL ){
712 for(j=0; j<s2->nsubsym; j++){
713 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
714 }
715 break;
drh75897232000-05-29 14:26:00 +0000716 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000717 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000718 }else{
719 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000720 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000721 }
722 }
723 }
724 }while( progress );
725 return;
726}
727
728/* Compute all LR(0) states for the grammar. Links
729** are added to between some states so that the LR(1) follow sets
730** can be computed later.
731*/
732PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
733void FindStates(lemp)
734struct lemon *lemp;
735{
736 struct symbol *sp;
737 struct rule *rp;
738
739 Configlist_init();
740
741 /* Find the start symbol */
742 if( lemp->start ){
743 sp = Symbol_find(lemp->start);
744 if( sp==0 ){
745 ErrorMsg(lemp->filename,0,
746"The specified start symbol \"%s\" is not \
747in a nonterminal of the grammar. \"%s\" will be used as the start \
748symbol instead.",lemp->start,lemp->rule->lhs->name);
749 lemp->errorcnt++;
750 sp = lemp->rule->lhs;
751 }
752 }else{
753 sp = lemp->rule->lhs;
754 }
755
756 /* Make sure the start symbol doesn't occur on the right-hand side of
757 ** any rule. Report an error if it does. (YACC would generate a new
758 ** start symbol in this case.) */
759 for(rp=lemp->rule; rp; rp=rp->next){
760 int i;
761 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000762 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000763 ErrorMsg(lemp->filename,0,
764"The start symbol \"%s\" occurs on the \
765right-hand side of a rule. This will result in a parser which \
766does not work properly.",sp->name);
767 lemp->errorcnt++;
768 }
769 }
770 }
771
772 /* The basis configuration set for the first state
773 ** is all rules which have the start symbol as their
774 ** left-hand side */
775 for(rp=sp->rule; rp; rp=rp->nextlhs){
776 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000777 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000778 newcfp = Configlist_addbasis(rp,0);
779 SetAdd(newcfp->fws,0);
780 }
781
782 /* Compute the first state. All other states will be
783 ** computed automatically during the computation of the first one.
784 ** The returned pointer to the first state is not used. */
785 (void)getstate(lemp);
786 return;
787}
788
789/* Return a pointer to a state which is described by the configuration
790** list which has been built from calls to Configlist_add.
791*/
792PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
793PRIVATE struct state *getstate(lemp)
794struct lemon *lemp;
795{
796 struct config *cfp, *bp;
797 struct state *stp;
798
799 /* Extract the sorted basis of the new state. The basis was constructed
800 ** by prior calls to "Configlist_addbasis()". */
801 Configlist_sortbasis();
802 bp = Configlist_basis();
803
804 /* Get a state with the same basis */
805 stp = State_find(bp);
806 if( stp ){
807 /* A state with the same basis already exists! Copy all the follow-set
808 ** propagation links from the state under construction into the
809 ** preexisting state, then return a pointer to the preexisting state */
810 struct config *x, *y;
811 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
812 Plink_copy(&y->bplp,x->bplp);
813 Plink_delete(x->fplp);
814 x->fplp = x->bplp = 0;
815 }
816 cfp = Configlist_return();
817 Configlist_eat(cfp);
818 }else{
819 /* This really is a new state. Construct all the details */
820 Configlist_closure(lemp); /* Compute the configuration closure */
821 Configlist_sort(); /* Sort the configuration closure */
822 cfp = Configlist_return(); /* Get a pointer to the config list */
823 stp = State_new(); /* A new state structure */
824 MemoryCheck(stp);
825 stp->bp = bp; /* Remember the configuration basis */
826 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000827 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000828 stp->ap = 0; /* No actions, yet. */
829 State_insert(stp,stp->bp); /* Add to the state table */
830 buildshifts(lemp,stp); /* Recursively compute successor states */
831 }
832 return stp;
833}
834
drhfd405312005-11-06 04:06:59 +0000835/*
836** Return true if two symbols are the same.
837*/
838int same_symbol(a,b)
839struct symbol *a;
840struct symbol *b;
841{
842 int i;
843 if( a==b ) return 1;
844 if( a->type!=MULTITERMINAL ) return 0;
845 if( b->type!=MULTITERMINAL ) return 0;
846 if( a->nsubsym!=b->nsubsym ) return 0;
847 for(i=0; i<a->nsubsym; i++){
848 if( a->subsym[i]!=b->subsym[i] ) return 0;
849 }
850 return 1;
851}
852
drh75897232000-05-29 14:26:00 +0000853/* Construct all successor states to the given state. A "successor"
854** state is any state which can be reached by a shift action.
855*/
856PRIVATE void buildshifts(lemp,stp)
857struct lemon *lemp;
858struct state *stp; /* The state from which successors are computed */
859{
860 struct config *cfp; /* For looping thru the config closure of "stp" */
861 struct config *bcfp; /* For the inner loop on config closure of "stp" */
862 struct config *new; /* */
863 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
864 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
865 struct state *newstp; /* A pointer to a successor state */
866
867 /* Each configuration becomes complete after it contibutes to a successor
868 ** state. Initially, all configurations are incomplete */
869 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
870
871 /* Loop through all configurations of the state "stp" */
872 for(cfp=stp->cfp; cfp; cfp=cfp->next){
873 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
874 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
875 Configlist_reset(); /* Reset the new config set */
876 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
877
878 /* For every configuration in the state "stp" which has the symbol "sp"
879 ** following its dot, add the same configuration to the basis set under
880 ** construction but with the dot shifted one symbol to the right. */
881 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
882 if( bcfp->status==COMPLETE ) continue; /* Already used */
883 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
884 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000885 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000886 bcfp->status = COMPLETE; /* Mark this config as used */
887 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
888 Plink_add(&new->bplp,bcfp);
889 }
890
891 /* Get a pointer to the state described by the basis configuration set
892 ** constructed in the preceding loop */
893 newstp = getstate(lemp);
894
895 /* The state "newstp" is reached from the state "stp" by a shift action
896 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000897 if( sp->type==MULTITERMINAL ){
898 int i;
899 for(i=0; i<sp->nsubsym; i++){
900 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
901 }
902 }else{
903 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
904 }
drh75897232000-05-29 14:26:00 +0000905 }
906}
907
908/*
909** Construct the propagation links
910*/
911void FindLinks(lemp)
912struct lemon *lemp;
913{
914 int i;
915 struct config *cfp, *other;
916 struct state *stp;
917 struct plink *plp;
918
919 /* Housekeeping detail:
920 ** Add to every propagate link a pointer back to the state to
921 ** which the link is attached. */
922 for(i=0; i<lemp->nstate; i++){
923 stp = lemp->sorted[i];
924 for(cfp=stp->cfp; cfp; cfp=cfp->next){
925 cfp->stp = stp;
926 }
927 }
928
929 /* Convert all backlinks into forward links. Only the forward
930 ** links are used in the follow-set computation. */
931 for(i=0; i<lemp->nstate; i++){
932 stp = lemp->sorted[i];
933 for(cfp=stp->cfp; cfp; cfp=cfp->next){
934 for(plp=cfp->bplp; plp; plp=plp->next){
935 other = plp->cfp;
936 Plink_add(&other->fplp,cfp);
937 }
938 }
939 }
940}
941
942/* Compute all followsets.
943**
944** A followset is the set of all symbols which can come immediately
945** after a configuration.
946*/
947void FindFollowSets(lemp)
948struct lemon *lemp;
949{
950 int i;
951 struct config *cfp;
952 struct plink *plp;
953 int progress;
954 int change;
955
956 for(i=0; i<lemp->nstate; i++){
957 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
958 cfp->status = INCOMPLETE;
959 }
960 }
961
962 do{
963 progress = 0;
964 for(i=0; i<lemp->nstate; i++){
965 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
966 if( cfp->status==COMPLETE ) continue;
967 for(plp=cfp->fplp; plp; plp=plp->next){
968 change = SetUnion(plp->cfp->fws,cfp->fws);
969 if( change ){
970 plp->cfp->status = INCOMPLETE;
971 progress = 1;
972 }
973 }
974 cfp->status = COMPLETE;
975 }
976 }
977 }while( progress );
978}
979
980static int resolve_conflict();
981
982/* Compute the reduce actions, and resolve conflicts.
983*/
984void FindActions(lemp)
985struct lemon *lemp;
986{
987 int i,j;
988 struct config *cfp;
989 struct state *stp;
990 struct symbol *sp;
991 struct rule *rp;
992
993 /* Add all of the reduce actions
994 ** A reduce action is added for each element of the followset of
995 ** a configuration which has its dot at the extreme right.
996 */
997 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
998 stp = lemp->sorted[i];
999 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1000 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1001 for(j=0; j<lemp->nterminal; j++){
1002 if( SetFind(cfp->fws,j) ){
1003 /* Add a reduce action to the state "stp" which will reduce by the
1004 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001005 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001006 }
1007 }
1008 }
1009 }
1010 }
1011
1012 /* Add the accepting token */
1013 if( lemp->start ){
1014 sp = Symbol_find(lemp->start);
1015 if( sp==0 ) sp = lemp->rule->lhs;
1016 }else{
1017 sp = lemp->rule->lhs;
1018 }
1019 /* Add to the first state (which is always the starting state of the
1020 ** finite state machine) an action to ACCEPT if the lookahead is the
1021 ** start nonterminal. */
1022 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1023
1024 /* Resolve conflicts */
1025 for(i=0; i<lemp->nstate; i++){
1026 struct action *ap, *nap;
1027 struct state *stp;
1028 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001029 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001030 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001031 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001032 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1033 /* The two actions "ap" and "nap" have the same lookahead.
1034 ** Figure out which one should be used */
1035 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1036 }
1037 }
1038 }
1039
1040 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001041 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001042 for(i=0; i<lemp->nstate; i++){
1043 struct action *ap;
1044 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001045 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001046 }
1047 }
1048 for(rp=lemp->rule; rp; rp=rp->next){
1049 if( rp->canReduce ) continue;
1050 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1051 lemp->errorcnt++;
1052 }
1053}
1054
1055/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001056** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001057**
1058** NO LONGER TRUE:
1059** To resolve a conflict, first look to see if either action
1060** is on an error rule. In that case, take the action which
1061** is not associated with the error rule. If neither or both
1062** actions are associated with an error rule, then try to
1063** use precedence to resolve the conflict.
1064**
1065** If either action is a SHIFT, then it must be apx. This
1066** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1067*/
1068static int resolve_conflict(apx,apy,errsym)
1069struct action *apx;
1070struct action *apy;
1071struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1072{
1073 struct symbol *spx, *spy;
1074 int errcnt = 0;
1075 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001076 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001077 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001078 errcnt++;
1079 }
drh75897232000-05-29 14:26:00 +00001080 if( apx->type==SHIFT && apy->type==REDUCE ){
1081 spx = apx->sp;
1082 spy = apy->x.rp->precsym;
1083 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1084 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001085 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001086 errcnt++;
1087 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1088 apy->type = RD_RESOLVED;
1089 }else if( spx->prec<spy->prec ){
1090 apx->type = SH_RESOLVED;
1091 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1092 apy->type = RD_RESOLVED; /* associativity */
1093 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1094 apx->type = SH_RESOLVED;
1095 }else{
1096 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001097 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001098 errcnt++;
1099 }
1100 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1101 spx = apx->x.rp->precsym;
1102 spy = apy->x.rp->precsym;
1103 if( spx==0 || spy==0 || spx->prec<0 ||
1104 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001105 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001106 errcnt++;
1107 }else if( spx->prec>spy->prec ){
1108 apy->type = RD_RESOLVED;
1109 }else if( spx->prec<spy->prec ){
1110 apx->type = RD_RESOLVED;
1111 }
1112 }else{
drhb59499c2002-02-23 18:45:13 +00001113 assert(
1114 apx->type==SH_RESOLVED ||
1115 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001116 apx->type==SSCONFLICT ||
1117 apx->type==SRCONFLICT ||
1118 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001119 apy->type==SH_RESOLVED ||
1120 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001121 apy->type==SSCONFLICT ||
1122 apy->type==SRCONFLICT ||
1123 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001124 );
1125 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1126 ** REDUCEs on the list. If we reach this point it must be because
1127 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001128 }
1129 return errcnt;
1130}
1131/********************* From the file "configlist.c" *************************/
1132/*
1133** Routines to processing a configuration list and building a state
1134** in the LEMON parser generator.
1135*/
1136
1137static struct config *freelist = 0; /* List of free configurations */
1138static struct config *current = 0; /* Top of list of configurations */
1139static struct config **currentend = 0; /* Last on list of configs */
1140static struct config *basis = 0; /* Top of list of basis configs */
1141static struct config **basisend = 0; /* End of list of basis configs */
1142
1143/* Return a pointer to a new configuration */
1144PRIVATE struct config *newconfig(){
1145 struct config *new;
1146 if( freelist==0 ){
1147 int i;
1148 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001149 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001150 if( freelist==0 ){
1151 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1152 exit(1);
1153 }
1154 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1155 freelist[amt-1].next = 0;
1156 }
1157 new = freelist;
1158 freelist = freelist->next;
1159 return new;
1160}
1161
1162/* The configuration "old" is no longer used */
1163PRIVATE void deleteconfig(old)
1164struct config *old;
1165{
1166 old->next = freelist;
1167 freelist = old;
1168}
1169
1170/* Initialized the configuration list builder */
1171void Configlist_init(){
1172 current = 0;
1173 currentend = &current;
1174 basis = 0;
1175 basisend = &basis;
1176 Configtable_init();
1177 return;
1178}
1179
1180/* Initialized the configuration list builder */
1181void Configlist_reset(){
1182 current = 0;
1183 currentend = &current;
1184 basis = 0;
1185 basisend = &basis;
1186 Configtable_clear(0);
1187 return;
1188}
1189
1190/* Add another configuration to the configuration list */
1191struct config *Configlist_add(rp,dot)
1192struct rule *rp; /* The rule */
1193int dot; /* Index into the RHS of the rule where the dot goes */
1194{
1195 struct config *cfp, model;
1196
1197 assert( currentend!=0 );
1198 model.rp = rp;
1199 model.dot = dot;
1200 cfp = Configtable_find(&model);
1201 if( cfp==0 ){
1202 cfp = newconfig();
1203 cfp->rp = rp;
1204 cfp->dot = dot;
1205 cfp->fws = SetNew();
1206 cfp->stp = 0;
1207 cfp->fplp = cfp->bplp = 0;
1208 cfp->next = 0;
1209 cfp->bp = 0;
1210 *currentend = cfp;
1211 currentend = &cfp->next;
1212 Configtable_insert(cfp);
1213 }
1214 return cfp;
1215}
1216
1217/* Add a basis configuration to the configuration list */
1218struct config *Configlist_addbasis(rp,dot)
1219struct rule *rp;
1220int dot;
1221{
1222 struct config *cfp, model;
1223
1224 assert( basisend!=0 );
1225 assert( currentend!=0 );
1226 model.rp = rp;
1227 model.dot = dot;
1228 cfp = Configtable_find(&model);
1229 if( cfp==0 ){
1230 cfp = newconfig();
1231 cfp->rp = rp;
1232 cfp->dot = dot;
1233 cfp->fws = SetNew();
1234 cfp->stp = 0;
1235 cfp->fplp = cfp->bplp = 0;
1236 cfp->next = 0;
1237 cfp->bp = 0;
1238 *currentend = cfp;
1239 currentend = &cfp->next;
1240 *basisend = cfp;
1241 basisend = &cfp->bp;
1242 Configtable_insert(cfp);
1243 }
1244 return cfp;
1245}
1246
1247/* Compute the closure of the configuration list */
1248void Configlist_closure(lemp)
1249struct lemon *lemp;
1250{
1251 struct config *cfp, *newcfp;
1252 struct rule *rp, *newrp;
1253 struct symbol *sp, *xsp;
1254 int i, dot;
1255
1256 assert( currentend!=0 );
1257 for(cfp=current; cfp; cfp=cfp->next){
1258 rp = cfp->rp;
1259 dot = cfp->dot;
1260 if( dot>=rp->nrhs ) continue;
1261 sp = rp->rhs[dot];
1262 if( sp->type==NONTERMINAL ){
1263 if( sp->rule==0 && sp!=lemp->errsym ){
1264 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1265 sp->name);
1266 lemp->errorcnt++;
1267 }
1268 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1269 newcfp = Configlist_add(newrp,0);
1270 for(i=dot+1; i<rp->nrhs; i++){
1271 xsp = rp->rhs[i];
1272 if( xsp->type==TERMINAL ){
1273 SetAdd(newcfp->fws,xsp->index);
1274 break;
drhfd405312005-11-06 04:06:59 +00001275 }else if( xsp->type==MULTITERMINAL ){
1276 int k;
1277 for(k=0; k<xsp->nsubsym; k++){
1278 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1279 }
1280 break;
drh75897232000-05-29 14:26:00 +00001281 }else{
1282 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001283 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001284 }
1285 }
1286 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1287 }
1288 }
1289 }
1290 return;
1291}
1292
1293/* Sort the configuration list */
1294void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001295 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001296 currentend = 0;
1297 return;
1298}
1299
1300/* Sort the basis configuration list */
1301void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001302 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001303 basisend = 0;
1304 return;
1305}
1306
1307/* Return a pointer to the head of the configuration list and
1308** reset the list */
1309struct config *Configlist_return(){
1310 struct config *old;
1311 old = current;
1312 current = 0;
1313 currentend = 0;
1314 return old;
1315}
1316
1317/* Return a pointer to the head of the configuration list and
1318** reset the list */
1319struct config *Configlist_basis(){
1320 struct config *old;
1321 old = basis;
1322 basis = 0;
1323 basisend = 0;
1324 return old;
1325}
1326
1327/* Free all elements of the given configuration list */
1328void Configlist_eat(cfp)
1329struct config *cfp;
1330{
1331 struct config *nextcfp;
1332 for(; cfp; cfp=nextcfp){
1333 nextcfp = cfp->next;
1334 assert( cfp->fplp==0 );
1335 assert( cfp->bplp==0 );
1336 if( cfp->fws ) SetFree(cfp->fws);
1337 deleteconfig(cfp);
1338 }
1339 return;
1340}
1341/***************** From the file "error.c" *********************************/
1342/*
1343** Code for printing error message.
1344*/
1345
1346/* Find a good place to break "msg" so that its length is at least "min"
1347** but no more than "max". Make the point as close to max as possible.
1348*/
1349static int findbreak(msg,min,max)
1350char *msg;
1351int min;
1352int max;
1353{
1354 int i,spot;
1355 char c;
1356 for(i=spot=min; i<=max; i++){
1357 c = msg[i];
1358 if( c=='\t' ) msg[i] = ' ';
1359 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1360 if( c==0 ){ spot = i; break; }
1361 if( c=='-' && i<max-1 ) spot = i+1;
1362 if( c==' ' ) spot = i;
1363 }
1364 return spot;
1365}
1366
1367/*
1368** The error message is split across multiple lines if necessary. The
1369** splits occur at a space, if there is a space available near the end
1370** of the line.
1371*/
1372#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1373#define LINEWIDTH 79 /* Max width of any output line */
1374#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001375void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001376 char errmsg[ERRMSGSIZE];
1377 char prefix[PREFIXLIMIT+10];
1378 int errmsgsize;
1379 int prefixsize;
1380 int availablewidth;
1381 va_list ap;
1382 int end, restart, base;
1383
drhf9a2e7b2003-04-15 01:49:48 +00001384 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001385 /* Prepare a prefix to be prepended to every output line */
1386 if( lineno>0 ){
1387 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1388 }else{
1389 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1390 }
drh87cf1372008-08-13 20:09:06 +00001391 prefixsize = lemonStrlen(prefix);
drh75897232000-05-29 14:26:00 +00001392 availablewidth = LINEWIDTH - prefixsize;
1393
1394 /* Generate the error message */
1395 vsprintf(errmsg,format,ap);
1396 va_end(ap);
drh87cf1372008-08-13 20:09:06 +00001397 errmsgsize = lemonStrlen(errmsg);
drh75897232000-05-29 14:26:00 +00001398 /* Remove trailing '\n's from the error message. */
1399 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1400 errmsg[--errmsgsize] = 0;
1401 }
1402
1403 /* Print the error message */
1404 base = 0;
1405 while( errmsg[base]!=0 ){
1406 end = restart = findbreak(&errmsg[base],0,availablewidth);
1407 restart += base;
1408 while( errmsg[restart]==' ' ) restart++;
1409 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1410 base = restart;
1411 }
1412}
1413/**************** From the file "main.c" ************************************/
1414/*
1415** Main program file for the LEMON parser generator.
1416*/
1417
1418/* Report an out-of-memory condition and abort. This function
1419** is used mostly by the "MemoryCheck" macro in struct.h
1420*/
1421void memory_error(){
1422 fprintf(stderr,"Out of memory. Aborting...\n");
1423 exit(1);
1424}
1425
drh6d08b4d2004-07-20 12:45:22 +00001426static int nDefine = 0; /* Number of -D options on the command line */
1427static char **azDefine = 0; /* Name of the -D macros */
1428
1429/* This routine is called with the argument to each -D command-line option.
1430** Add the macro defined to the azDefine array.
1431*/
1432static void handle_D_option(char *z){
1433 char **paz;
1434 nDefine++;
1435 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1436 if( azDefine==0 ){
1437 fprintf(stderr,"out of memory\n");
1438 exit(1);
1439 }
1440 paz = &azDefine[nDefine-1];
drh87cf1372008-08-13 20:09:06 +00001441 *paz = malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001442 if( *paz==0 ){
1443 fprintf(stderr,"out of memory\n");
1444 exit(1);
1445 }
1446 strcpy(*paz, z);
1447 for(z=*paz; *z && *z!='='; z++){}
1448 *z = 0;
1449}
1450
icculus3e143bd2010-02-14 00:48:49 +00001451static char *user_templatename = NULL;
1452static void handle_T_option(char *z){
1453 user_templatename = malloc( lemonStrlen(z)+1 );
1454 if( user_templatename==0 ){
1455 memory_error();
1456 }
1457 strcpy(user_templatename, z);
1458}
drh75897232000-05-29 14:26:00 +00001459
1460/* The main program. Parse the command line and do it... */
1461int main(argc,argv)
1462int argc;
1463char **argv;
1464{
1465 static int version = 0;
1466 static int rpflag = 0;
1467 static int basisflag = 0;
1468 static int compress = 0;
1469 static int quiet = 0;
1470 static int statistics = 0;
1471 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001472 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001473 static struct s_options options[] = {
1474 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1475 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001476 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001477 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001478 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001479 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1480 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001481 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001482 {OPT_FLAG, "s", (char*)&statistics,
1483 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001484 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1485 {OPT_FLAG,0,0,0}
1486 };
1487 int i;
icculus42585cf2010-02-14 05:19:56 +00001488 int exitcode;
drh75897232000-05-29 14:26:00 +00001489 struct lemon lem;
1490
icculusf5ad8242010-02-14 05:34:42 +00001491 atexit(LemonAtExit);
1492
drhb0c86772000-06-02 23:21:26 +00001493 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001494 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001495 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001496 exit(0);
1497 }
drhb0c86772000-06-02 23:21:26 +00001498 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001499 fprintf(stderr,"Exactly one filename argument is required.\n");
1500 exit(1);
1501 }
drh954f6b42006-06-13 13:27:46 +00001502 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001503 lem.errorcnt = 0;
icculus42585cf2010-02-14 05:19:56 +00001504 lem.nexpected = -1;
drh75897232000-05-29 14:26:00 +00001505
1506 /* Initialize the machine */
1507 Strsafe_init();
1508 Symbol_init();
1509 State_init();
1510 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001511 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001512 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001513 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001514 Symbol_new("$");
1515 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001516 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001517
1518 /* Parse the input file */
1519 Parse(&lem);
1520 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001521 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001522 fprintf(stderr,"Empty grammar.\n");
1523 exit(1);
1524 }
1525
1526 /* Count and index the symbols of the grammar */
1527 lem.nsymbol = Symbol_count();
1528 Symbol_new("{default}");
1529 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001530 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001531 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1532 (int(*)())Symbolcmpp);
1533 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1534 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1535 lem.nterminal = i;
1536
1537 /* Generate a reprint of the grammar, if requested on the command line */
1538 if( rpflag ){
1539 Reprint(&lem);
1540 }else{
1541 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001542 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001543
1544 /* Find the precedence for every production rule (that has one) */
1545 FindRulePrecedences(&lem);
1546
1547 /* Compute the lambda-nonterminals and the first-sets for every
1548 ** nonterminal */
1549 FindFirstSets(&lem);
1550
1551 /* Compute all LR(0) states. Also record follow-set propagation
1552 ** links so that the follow-set can be computed later */
1553 lem.nstate = 0;
1554 FindStates(&lem);
1555 lem.sorted = State_arrayof();
1556
1557 /* Tie up loose ends on the propagation links */
1558 FindLinks(&lem);
1559
1560 /* Compute the follow set of every reducible configuration */
1561 FindFollowSets(&lem);
1562
1563 /* Compute the action tables */
1564 FindActions(&lem);
1565
1566 /* Compress the action tables */
1567 if( compress==0 ) CompressTables(&lem);
1568
drhada354d2005-11-05 15:03:59 +00001569 /* Reorder and renumber the states so that states with fewer choices
1570 ** occur at the end. */
1571 ResortStates(&lem);
1572
drh75897232000-05-29 14:26:00 +00001573 /* Generate a report of the parser generated. (the "y.output" file) */
1574 if( !quiet ) ReportOutput(&lem);
1575
1576 /* Generate the source code for the parser */
1577 ReportTable(&lem, mhflag);
1578
1579 /* Produce a header file for use by the scanner. (This step is
1580 ** omitted if the "-m" option is used because makeheaders will
1581 ** generate the file for us.) */
1582 if( !mhflag ) ReportHeader(&lem);
1583 }
1584 if( statistics ){
1585 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1586 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1587 printf(" %d states, %d parser table entries, %d conflicts\n",
1588 lem.nstate, lem.tablesize, lem.nconflict);
1589 }
icculus42585cf2010-02-14 05:19:56 +00001590 if( lem.nexpected < 0 ) {
1591 lem.nexpected = 0; /* grammar didn't have an %expect declaration. */
drh75897232000-05-29 14:26:00 +00001592 }
icculus42585cf2010-02-14 05:19:56 +00001593 if( lem.nconflict != lem.nexpected ){
1594 fprintf(stderr,"%d parsing conflicts (%d expected).\n",lem.nconflict,lem.nexpected);
1595 }
1596
1597 /* return 0 on success, 1 on failure. */
1598 exitcode = ((lem.errorcnt > 0) || (lem.nconflict != lem.nexpected)) ? 1 : 0;
icculusf5ad8242010-02-14 05:34:42 +00001599 successful_exit = (exitcode == 0);
icculus42585cf2010-02-14 05:19:56 +00001600 exit(exitcode);
1601 return (exitcode);
drh75897232000-05-29 14:26:00 +00001602}
1603/******************** From the file "msort.c" *******************************/
1604/*
1605** A generic merge-sort program.
1606**
1607** USAGE:
1608** Let "ptr" be a pointer to some structure which is at the head of
1609** a null-terminated list. Then to sort the list call:
1610**
1611** ptr = msort(ptr,&(ptr->next),cmpfnc);
1612**
1613** In the above, "cmpfnc" is a pointer to a function which compares
1614** two instances of the structure and returns an integer, as in
1615** strcmp. The second argument is a pointer to the pointer to the
1616** second element of the linked list. This address is used to compute
1617** the offset to the "next" field within the structure. The offset to
1618** the "next" field must be constant for all structures in the list.
1619**
1620** The function returns a new pointer which is the head of the list
1621** after sorting.
1622**
1623** ALGORITHM:
1624** Merge-sort.
1625*/
1626
1627/*
1628** Return a pointer to the next structure in the linked list.
1629*/
drhba99af52001-10-25 20:37:16 +00001630#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001631
1632/*
1633** Inputs:
1634** a: A sorted, null-terminated linked list. (May be null).
1635** b: A sorted, null-terminated linked list. (May be null).
1636** cmp: A pointer to the comparison function.
1637** offset: Offset in the structure to the "next" field.
1638**
1639** Return Value:
1640** A pointer to the head of a sorted list containing the elements
1641** of both a and b.
1642**
1643** Side effects:
1644** The "next" pointers for elements in the lists a and b are
1645** changed.
1646*/
drhe9278182007-07-18 18:16:29 +00001647static char *merge(
1648 char *a,
1649 char *b,
1650 int (*cmp)(const char*,const char*),
1651 int offset
1652){
drh75897232000-05-29 14:26:00 +00001653 char *ptr, *head;
1654
1655 if( a==0 ){
1656 head = b;
1657 }else if( b==0 ){
1658 head = a;
1659 }else{
drhe594bc32009-11-03 13:02:25 +00001660 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001661 ptr = a;
1662 a = NEXT(a);
1663 }else{
1664 ptr = b;
1665 b = NEXT(b);
1666 }
1667 head = ptr;
1668 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001669 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001670 NEXT(ptr) = a;
1671 ptr = a;
1672 a = NEXT(a);
1673 }else{
1674 NEXT(ptr) = b;
1675 ptr = b;
1676 b = NEXT(b);
1677 }
1678 }
1679 if( a ) NEXT(ptr) = a;
1680 else NEXT(ptr) = b;
1681 }
1682 return head;
1683}
1684
1685/*
1686** Inputs:
1687** list: Pointer to a singly-linked list of structures.
1688** next: Pointer to pointer to the second element of the list.
1689** cmp: A comparison function.
1690**
1691** Return Value:
1692** A pointer to the head of a sorted list containing the elements
1693** orginally in list.
1694**
1695** Side effects:
1696** The "next" pointers for elements in list are changed.
1697*/
1698#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001699static char *msort(
1700 char *list,
1701 char **next,
1702 int (*cmp)(const char*,const char*)
1703){
drhba99af52001-10-25 20:37:16 +00001704 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001705 char *ep;
1706 char *set[LISTSIZE];
1707 int i;
drhba99af52001-10-25 20:37:16 +00001708 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001709 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1710 while( list ){
1711 ep = list;
1712 list = NEXT(list);
1713 NEXT(ep) = 0;
1714 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1715 ep = merge(ep,set[i],cmp,offset);
1716 set[i] = 0;
1717 }
1718 set[i] = ep;
1719 }
1720 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001721 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001722 return ep;
1723}
1724/************************ From the file "option.c" **************************/
1725static char **argv;
1726static struct s_options *op;
1727static FILE *errstream;
1728
1729#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1730
1731/*
1732** Print the command line with a carrot pointing to the k-th character
1733** of the n-th field.
1734*/
1735static void errline(n,k,err)
1736int n;
1737int k;
1738FILE *err;
1739{
1740 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001741 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001742 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001743 for(i=1; i<n && argv[i]; i++){
1744 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001745 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001746 }
1747 spcnt += k;
1748 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1749 if( spcnt<20 ){
1750 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1751 }else{
1752 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1753 }
1754}
1755
1756/*
1757** Return the index of the N-th non-switch argument. Return -1
1758** if N is out of range.
1759*/
1760static int argindex(n)
1761int n;
1762{
1763 int i;
1764 int dashdash = 0;
1765 if( argv!=0 && *argv!=0 ){
1766 for(i=1; argv[i]; i++){
1767 if( dashdash || !ISOPT(argv[i]) ){
1768 if( n==0 ) return i;
1769 n--;
1770 }
1771 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1772 }
1773 }
1774 return -1;
1775}
1776
1777static char emsg[] = "Command line syntax error: ";
1778
1779/*
1780** Process a flag command line argument.
1781*/
1782static int handleflags(i,err)
1783int i;
1784FILE *err;
1785{
1786 int v;
1787 int errcnt = 0;
1788 int j;
1789 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001790 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001791 }
1792 v = argv[i][0]=='-' ? 1 : 0;
1793 if( op[j].label==0 ){
1794 if( err ){
1795 fprintf(err,"%sundefined option.\n",emsg);
1796 errline(i,1,err);
1797 }
1798 errcnt++;
1799 }else if( op[j].type==OPT_FLAG ){
1800 *((int*)op[j].arg) = v;
1801 }else if( op[j].type==OPT_FFLAG ){
1802 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001803 }else if( op[j].type==OPT_FSTR ){
1804 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001805 }else{
1806 if( err ){
1807 fprintf(err,"%smissing argument on switch.\n",emsg);
1808 errline(i,1,err);
1809 }
1810 errcnt++;
1811 }
1812 return errcnt;
1813}
1814
1815/*
1816** Process a command line switch which has an argument.
1817*/
1818static int handleswitch(i,err)
1819int i;
1820FILE *err;
1821{
1822 int lv = 0;
1823 double dv = 0.0;
1824 char *sv = 0, *end;
1825 char *cp;
1826 int j;
1827 int errcnt = 0;
1828 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001829 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001830 *cp = 0;
1831 for(j=0; op[j].label; j++){
1832 if( strcmp(argv[i],op[j].label)==0 ) break;
1833 }
1834 *cp = '=';
1835 if( op[j].label==0 ){
1836 if( err ){
1837 fprintf(err,"%sundefined option.\n",emsg);
1838 errline(i,0,err);
1839 }
1840 errcnt++;
1841 }else{
1842 cp++;
1843 switch( op[j].type ){
1844 case OPT_FLAG:
1845 case OPT_FFLAG:
1846 if( err ){
1847 fprintf(err,"%soption requires an argument.\n",emsg);
1848 errline(i,0,err);
1849 }
1850 errcnt++;
1851 break;
1852 case OPT_DBL:
1853 case OPT_FDBL:
1854 dv = strtod(cp,&end);
1855 if( *end ){
1856 if( err ){
1857 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001858 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001859 }
1860 errcnt++;
1861 }
1862 break;
1863 case OPT_INT:
1864 case OPT_FINT:
1865 lv = strtol(cp,&end,0);
1866 if( *end ){
1867 if( err ){
1868 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001869 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001870 }
1871 errcnt++;
1872 }
1873 break;
1874 case OPT_STR:
1875 case OPT_FSTR:
1876 sv = cp;
1877 break;
1878 }
1879 switch( op[j].type ){
1880 case OPT_FLAG:
1881 case OPT_FFLAG:
1882 break;
1883 case OPT_DBL:
1884 *(double*)(op[j].arg) = dv;
1885 break;
1886 case OPT_FDBL:
1887 (*(void(*)())(op[j].arg))(dv);
1888 break;
1889 case OPT_INT:
1890 *(int*)(op[j].arg) = lv;
1891 break;
1892 case OPT_FINT:
1893 (*(void(*)())(op[j].arg))((int)lv);
1894 break;
1895 case OPT_STR:
1896 *(char**)(op[j].arg) = sv;
1897 break;
1898 case OPT_FSTR:
1899 (*(void(*)())(op[j].arg))(sv);
1900 break;
1901 }
1902 }
1903 return errcnt;
1904}
1905
drhb0c86772000-06-02 23:21:26 +00001906int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001907char **a;
1908struct s_options *o;
1909FILE *err;
1910{
1911 int errcnt = 0;
1912 argv = a;
1913 op = o;
1914 errstream = err;
1915 if( argv && *argv && op ){
1916 int i;
1917 for(i=1; argv[i]; i++){
1918 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1919 errcnt += handleflags(i,err);
1920 }else if( strchr(argv[i],'=') ){
1921 errcnt += handleswitch(i,err);
1922 }
1923 }
1924 }
1925 if( errcnt>0 ){
1926 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001927 OptPrint();
drh75897232000-05-29 14:26:00 +00001928 exit(1);
1929 }
1930 return 0;
1931}
1932
drhb0c86772000-06-02 23:21:26 +00001933int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001934 int cnt = 0;
1935 int dashdash = 0;
1936 int i;
1937 if( argv!=0 && argv[0]!=0 ){
1938 for(i=1; argv[i]; i++){
1939 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1940 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1941 }
1942 }
1943 return cnt;
1944}
1945
drhb0c86772000-06-02 23:21:26 +00001946char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001947int n;
1948{
1949 int i;
1950 i = argindex(n);
1951 return i>=0 ? argv[i] : 0;
1952}
1953
drhb0c86772000-06-02 23:21:26 +00001954void OptErr(n)
drh75897232000-05-29 14:26:00 +00001955int n;
1956{
1957 int i;
1958 i = argindex(n);
1959 if( i>=0 ) errline(i,0,errstream);
1960}
1961
drhb0c86772000-06-02 23:21:26 +00001962void OptPrint(){
drh75897232000-05-29 14:26:00 +00001963 int i;
1964 int max, len;
1965 max = 0;
1966 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001967 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001968 switch( op[i].type ){
1969 case OPT_FLAG:
1970 case OPT_FFLAG:
1971 break;
1972 case OPT_INT:
1973 case OPT_FINT:
1974 len += 9; /* length of "<integer>" */
1975 break;
1976 case OPT_DBL:
1977 case OPT_FDBL:
1978 len += 6; /* length of "<real>" */
1979 break;
1980 case OPT_STR:
1981 case OPT_FSTR:
1982 len += 8; /* length of "<string>" */
1983 break;
1984 }
1985 if( len>max ) max = len;
1986 }
1987 for(i=0; op[i].label; i++){
1988 switch( op[i].type ){
1989 case OPT_FLAG:
1990 case OPT_FFLAG:
1991 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1992 break;
1993 case OPT_INT:
1994 case OPT_FINT:
1995 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001996 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001997 break;
1998 case OPT_DBL:
1999 case OPT_FDBL:
2000 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002001 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002002 break;
2003 case OPT_STR:
2004 case OPT_FSTR:
2005 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002006 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002007 break;
2008 }
2009 }
2010}
2011/*********************** From the file "parse.c" ****************************/
2012/*
2013** Input file parser for the LEMON parser generator.
2014*/
2015
2016/* The state of the parser */
2017struct pstate {
2018 char *filename; /* Name of the input file */
2019 int tokenlineno; /* Linenumber at which current token starts */
2020 int errorcnt; /* Number of errors so far */
2021 char *tokenstart; /* Text of current token */
2022 struct lemon *gp; /* Global state vector */
2023 enum e_state {
2024 INITIALIZE,
2025 WAITING_FOR_DECL_OR_RULE,
2026 WAITING_FOR_DECL_KEYWORD,
2027 WAITING_FOR_DECL_ARG,
2028 WAITING_FOR_PRECEDENCE_SYMBOL,
2029 WAITING_FOR_ARROW,
2030 IN_RHS,
2031 LHS_ALIAS_1,
2032 LHS_ALIAS_2,
2033 LHS_ALIAS_3,
2034 RHS_ALIAS_1,
2035 RHS_ALIAS_2,
2036 PRECEDENCE_MARK_1,
2037 PRECEDENCE_MARK_2,
2038 RESYNC_AFTER_RULE_ERROR,
2039 RESYNC_AFTER_DECL_ERROR,
2040 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00002041 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00002042 WAITING_FOR_FALLBACK_ID,
icculus42585cf2010-02-14 05:19:56 +00002043 WAITING_FOR_EXPECT_VALUE,
drhe09daa92006-06-10 13:29:31 +00002044 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00002045 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002046 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00002047 struct symbol *lhs; /* Left-hand side of current rule */
2048 char *lhsalias; /* Alias for the LHS */
2049 int nrhs; /* Number of right-hand side symbols seen */
2050 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2051 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2052 struct rule *prevrule; /* Previous rule parsed */
2053 char *declkeyword; /* Keyword of a declaration */
2054 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002055 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002056 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002057 enum e_assoc declassoc; /* Assign this association to decl arguments */
2058 int preccounter; /* Assign this precedence to decl arguments */
2059 struct rule *firstrule; /* Pointer to first rule in the grammar */
2060 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2061};
2062
2063/* Parse a single token */
2064static void parseonetoken(psp)
2065struct pstate *psp;
2066{
icculus42585cf2010-02-14 05:19:56 +00002067 char *endptr;
drh75897232000-05-29 14:26:00 +00002068 char *x;
2069 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2070#if 0
2071 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2072 x,psp->state);
2073#endif
2074 switch( psp->state ){
2075 case INITIALIZE:
2076 psp->prevrule = 0;
2077 psp->preccounter = 0;
2078 psp->firstrule = psp->lastrule = 0;
2079 psp->gp->nrule = 0;
2080 /* Fall thru to next case */
2081 case WAITING_FOR_DECL_OR_RULE:
2082 if( x[0]=='%' ){
2083 psp->state = WAITING_FOR_DECL_KEYWORD;
2084 }else if( islower(x[0]) ){
2085 psp->lhs = Symbol_new(x);
2086 psp->nrhs = 0;
2087 psp->lhsalias = 0;
2088 psp->state = WAITING_FOR_ARROW;
2089 }else if( x[0]=='{' ){
2090 if( psp->prevrule==0 ){
2091 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002092"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002093fragment which begins on this line.");
2094 psp->errorcnt++;
2095 }else if( psp->prevrule->code!=0 ){
2096 ErrorMsg(psp->filename,psp->tokenlineno,
2097"Code fragment beginning on this line is not the first \
2098to follow the previous rule.");
2099 psp->errorcnt++;
2100 }else{
2101 psp->prevrule->line = psp->tokenlineno;
2102 psp->prevrule->code = &x[1];
2103 }
2104 }else if( x[0]=='[' ){
2105 psp->state = PRECEDENCE_MARK_1;
2106 }else{
2107 ErrorMsg(psp->filename,psp->tokenlineno,
2108 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2109 x);
2110 psp->errorcnt++;
2111 }
2112 break;
2113 case PRECEDENCE_MARK_1:
2114 if( !isupper(x[0]) ){
2115 ErrorMsg(psp->filename,psp->tokenlineno,
2116 "The precedence symbol must be a terminal.");
2117 psp->errorcnt++;
2118 }else if( psp->prevrule==0 ){
2119 ErrorMsg(psp->filename,psp->tokenlineno,
2120 "There is no prior rule to assign precedence \"[%s]\".",x);
2121 psp->errorcnt++;
2122 }else if( psp->prevrule->precsym!=0 ){
2123 ErrorMsg(psp->filename,psp->tokenlineno,
2124"Precedence mark on this line is not the first \
2125to follow the previous rule.");
2126 psp->errorcnt++;
2127 }else{
2128 psp->prevrule->precsym = Symbol_new(x);
2129 }
2130 psp->state = PRECEDENCE_MARK_2;
2131 break;
2132 case PRECEDENCE_MARK_2:
2133 if( x[0]!=']' ){
2134 ErrorMsg(psp->filename,psp->tokenlineno,
2135 "Missing \"]\" on precedence mark.");
2136 psp->errorcnt++;
2137 }
2138 psp->state = WAITING_FOR_DECL_OR_RULE;
2139 break;
2140 case WAITING_FOR_ARROW:
2141 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2142 psp->state = IN_RHS;
2143 }else if( x[0]=='(' ){
2144 psp->state = LHS_ALIAS_1;
2145 }else{
2146 ErrorMsg(psp->filename,psp->tokenlineno,
2147 "Expected to see a \":\" following the LHS symbol \"%s\".",
2148 psp->lhs->name);
2149 psp->errorcnt++;
2150 psp->state = RESYNC_AFTER_RULE_ERROR;
2151 }
2152 break;
2153 case LHS_ALIAS_1:
2154 if( isalpha(x[0]) ){
2155 psp->lhsalias = x;
2156 psp->state = LHS_ALIAS_2;
2157 }else{
2158 ErrorMsg(psp->filename,psp->tokenlineno,
2159 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2160 x,psp->lhs->name);
2161 psp->errorcnt++;
2162 psp->state = RESYNC_AFTER_RULE_ERROR;
2163 }
2164 break;
2165 case LHS_ALIAS_2:
2166 if( x[0]==')' ){
2167 psp->state = LHS_ALIAS_3;
2168 }else{
2169 ErrorMsg(psp->filename,psp->tokenlineno,
2170 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2171 psp->errorcnt++;
2172 psp->state = RESYNC_AFTER_RULE_ERROR;
2173 }
2174 break;
2175 case LHS_ALIAS_3:
2176 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2177 psp->state = IN_RHS;
2178 }else{
2179 ErrorMsg(psp->filename,psp->tokenlineno,
2180 "Missing \"->\" following: \"%s(%s)\".",
2181 psp->lhs->name,psp->lhsalias);
2182 psp->errorcnt++;
2183 psp->state = RESYNC_AFTER_RULE_ERROR;
2184 }
2185 break;
2186 case IN_RHS:
2187 if( x[0]=='.' ){
2188 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002189 rp = (struct rule *)calloc( sizeof(struct rule) +
2190 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002191 if( rp==0 ){
2192 ErrorMsg(psp->filename,psp->tokenlineno,
2193 "Can't allocate enough memory for this rule.");
2194 psp->errorcnt++;
2195 psp->prevrule = 0;
2196 }else{
2197 int i;
2198 rp->ruleline = psp->tokenlineno;
2199 rp->rhs = (struct symbol**)&rp[1];
2200 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2201 for(i=0; i<psp->nrhs; i++){
2202 rp->rhs[i] = psp->rhs[i];
2203 rp->rhsalias[i] = psp->alias[i];
2204 }
2205 rp->lhs = psp->lhs;
2206 rp->lhsalias = psp->lhsalias;
2207 rp->nrhs = psp->nrhs;
2208 rp->code = 0;
2209 rp->precsym = 0;
2210 rp->index = psp->gp->nrule++;
2211 rp->nextlhs = rp->lhs->rule;
2212 rp->lhs->rule = rp;
2213 rp->next = 0;
2214 if( psp->firstrule==0 ){
2215 psp->firstrule = psp->lastrule = rp;
2216 }else{
2217 psp->lastrule->next = rp;
2218 psp->lastrule = rp;
2219 }
2220 psp->prevrule = rp;
2221 }
2222 psp->state = WAITING_FOR_DECL_OR_RULE;
2223 }else if( isalpha(x[0]) ){
2224 if( psp->nrhs>=MAXRHS ){
2225 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002226 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002227 x);
2228 psp->errorcnt++;
2229 psp->state = RESYNC_AFTER_RULE_ERROR;
2230 }else{
2231 psp->rhs[psp->nrhs] = Symbol_new(x);
2232 psp->alias[psp->nrhs] = 0;
2233 psp->nrhs++;
2234 }
drhfd405312005-11-06 04:06:59 +00002235 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2236 struct symbol *msp = psp->rhs[psp->nrhs-1];
2237 if( msp->type!=MULTITERMINAL ){
2238 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002239 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002240 memset(msp, 0, sizeof(*msp));
2241 msp->type = MULTITERMINAL;
2242 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002243 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002244 msp->subsym[0] = origsp;
2245 msp->name = origsp->name;
2246 psp->rhs[psp->nrhs-1] = msp;
2247 }
2248 msp->nsubsym++;
2249 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2250 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2251 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2252 ErrorMsg(psp->filename,psp->tokenlineno,
2253 "Cannot form a compound containing a non-terminal");
2254 psp->errorcnt++;
2255 }
drh75897232000-05-29 14:26:00 +00002256 }else if( x[0]=='(' && psp->nrhs>0 ){
2257 psp->state = RHS_ALIAS_1;
2258 }else{
2259 ErrorMsg(psp->filename,psp->tokenlineno,
2260 "Illegal character on RHS of rule: \"%s\".",x);
2261 psp->errorcnt++;
2262 psp->state = RESYNC_AFTER_RULE_ERROR;
2263 }
2264 break;
2265 case RHS_ALIAS_1:
2266 if( isalpha(x[0]) ){
2267 psp->alias[psp->nrhs-1] = x;
2268 psp->state = RHS_ALIAS_2;
2269 }else{
2270 ErrorMsg(psp->filename,psp->tokenlineno,
2271 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2272 x,psp->rhs[psp->nrhs-1]->name);
2273 psp->errorcnt++;
2274 psp->state = RESYNC_AFTER_RULE_ERROR;
2275 }
2276 break;
2277 case RHS_ALIAS_2:
2278 if( x[0]==')' ){
2279 psp->state = IN_RHS;
2280 }else{
2281 ErrorMsg(psp->filename,psp->tokenlineno,
2282 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2283 psp->errorcnt++;
2284 psp->state = RESYNC_AFTER_RULE_ERROR;
2285 }
2286 break;
2287 case WAITING_FOR_DECL_KEYWORD:
2288 if( isalpha(x[0]) ){
2289 psp->declkeyword = x;
2290 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002291 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002292 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002293 psp->state = WAITING_FOR_DECL_ARG;
2294 if( strcmp(x,"name")==0 ){
2295 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002296 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002297 }else if( strcmp(x,"include")==0 ){
2298 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002299 }else if( strcmp(x,"code")==0 ){
2300 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002301 }else if( strcmp(x,"token_destructor")==0 ){
2302 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002303 }else if( strcmp(x,"default_destructor")==0 ){
2304 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002305 }else if( strcmp(x,"token_prefix")==0 ){
2306 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002307 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002308 }else if( strcmp(x,"syntax_error")==0 ){
2309 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002310 }else if( strcmp(x,"parse_accept")==0 ){
2311 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002312 }else if( strcmp(x,"parse_failure")==0 ){
2313 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002314 }else if( strcmp(x,"stack_overflow")==0 ){
2315 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002316 }else if( strcmp(x,"extra_argument")==0 ){
2317 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002318 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002319 }else if( strcmp(x,"token_type")==0 ){
2320 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002321 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002322 }else if( strcmp(x,"default_type")==0 ){
2323 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002324 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002325 }else if( strcmp(x,"stack_size")==0 ){
2326 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002327 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002328 }else if( strcmp(x,"start_symbol")==0 ){
2329 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002330 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002331 }else if( strcmp(x,"left")==0 ){
2332 psp->preccounter++;
2333 psp->declassoc = LEFT;
2334 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2335 }else if( strcmp(x,"right")==0 ){
2336 psp->preccounter++;
2337 psp->declassoc = RIGHT;
2338 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2339 }else if( strcmp(x,"nonassoc")==0 ){
2340 psp->preccounter++;
2341 psp->declassoc = NONE;
2342 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2343 }else if( strcmp(x,"destructor")==0 ){
2344 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2345 }else if( strcmp(x,"type")==0 ){
2346 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002347 }else if( strcmp(x,"fallback")==0 ){
2348 psp->fallback = 0;
2349 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002350 }else if( strcmp(x,"wildcard")==0 ){
2351 psp->state = WAITING_FOR_WILDCARD_ID;
icculus42585cf2010-02-14 05:19:56 +00002352 }else if( strcmp(x,"expect")==0 ){
2353 if (psp->gp->nexpected >= 0) {
2354 ErrorMsg(psp->filename,psp->tokenlineno, "Multiple %expect declarations.");
2355 psp->errorcnt++;
2356 psp->state = RESYNC_AFTER_DECL_ERROR;
2357 } else {
2358 psp->state = WAITING_FOR_EXPECT_VALUE;
2359 }
drh75897232000-05-29 14:26:00 +00002360 }else{
2361 ErrorMsg(psp->filename,psp->tokenlineno,
2362 "Unknown declaration keyword: \"%%%s\".",x);
2363 psp->errorcnt++;
2364 psp->state = RESYNC_AFTER_DECL_ERROR;
2365 }
2366 }else{
2367 ErrorMsg(psp->filename,psp->tokenlineno,
2368 "Illegal declaration keyword: \"%s\".",x);
2369 psp->errorcnt++;
2370 psp->state = RESYNC_AFTER_DECL_ERROR;
2371 }
2372 break;
2373 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2374 if( !isalpha(x[0]) ){
2375 ErrorMsg(psp->filename,psp->tokenlineno,
2376 "Symbol name missing after %destructor keyword");
2377 psp->errorcnt++;
2378 psp->state = RESYNC_AFTER_DECL_ERROR;
2379 }else{
2380 struct symbol *sp = Symbol_new(x);
2381 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002382 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002383 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002384 psp->state = WAITING_FOR_DECL_ARG;
2385 }
2386 break;
icculus42585cf2010-02-14 05:19:56 +00002387 case WAITING_FOR_EXPECT_VALUE:
2388 psp->gp->nexpected = (int) strtol(x, &endptr, 10);
2389 if( (*endptr != '\0') || (endptr == x) ) {
2390 ErrorMsg(psp->filename,psp->tokenlineno,
2391 "Integer expected after %%expect keyword");
2392 psp->errorcnt++;
2393 } else if (psp->gp->nexpected < 0) {
2394 ErrorMsg(psp->filename,psp->tokenlineno,
2395 "Integer can't be negative after %%expect keyword");
2396 psp->errorcnt++;
2397 }
2398 psp->state = WAITING_FOR_DECL_OR_RULE;
2399 break;
drh75897232000-05-29 14:26:00 +00002400 case WAITING_FOR_DATATYPE_SYMBOL:
2401 if( !isalpha(x[0]) ){
2402 ErrorMsg(psp->filename,psp->tokenlineno,
2403 "Symbol name missing after %destructor keyword");
2404 psp->errorcnt++;
2405 psp->state = RESYNC_AFTER_DECL_ERROR;
2406 }else{
2407 struct symbol *sp = Symbol_new(x);
2408 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002409 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002410 psp->state = WAITING_FOR_DECL_ARG;
2411 }
2412 break;
2413 case WAITING_FOR_PRECEDENCE_SYMBOL:
2414 if( x[0]=='.' ){
2415 psp->state = WAITING_FOR_DECL_OR_RULE;
2416 }else if( isupper(x[0]) ){
2417 struct symbol *sp;
2418 sp = Symbol_new(x);
2419 if( sp->prec>=0 ){
2420 ErrorMsg(psp->filename,psp->tokenlineno,
2421 "Symbol \"%s\" has already be given a precedence.",x);
2422 psp->errorcnt++;
2423 }else{
2424 sp->prec = psp->preccounter;
2425 sp->assoc = psp->declassoc;
2426 }
2427 }else{
2428 ErrorMsg(psp->filename,psp->tokenlineno,
2429 "Can't assign a precedence to \"%s\".",x);
2430 psp->errorcnt++;
2431 }
2432 break;
2433 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002434 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2435 char *zOld, *zNew, *zBuf, *z;
2436 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002437 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002438 char zLine[50];
2439 zNew = x;
2440 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002441 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002442 if( *psp->declargslot ){
2443 zOld = *psp->declargslot;
2444 }else{
2445 zOld = "";
2446 }
drh87cf1372008-08-13 20:09:06 +00002447 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002448 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002449 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002450 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2451 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002452 for(z=psp->filename, nBack=0; *z; z++){
2453 if( *z=='\\' ) nBack++;
2454 }
2455 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002456 nLine = lemonStrlen(zLine);
2457 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002458 }
2459 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2460 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002461 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002462 if( nOld && zBuf[-1]!='\n' ){
2463 *(zBuf++) = '\n';
2464 }
2465 memcpy(zBuf, zLine, nLine);
2466 zBuf += nLine;
2467 *(zBuf++) = '"';
2468 for(z=psp->filename; *z; z++){
2469 if( *z=='\\' ){
2470 *(zBuf++) = '\\';
2471 }
2472 *(zBuf++) = *z;
2473 }
2474 *(zBuf++) = '"';
2475 *(zBuf++) = '\n';
2476 }
drh4dc8ef52008-07-01 17:13:57 +00002477 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2478 psp->decllinenoslot[0] = psp->tokenlineno;
2479 }
drha5808f32008-04-27 22:19:44 +00002480 memcpy(zBuf, zNew, nNew);
2481 zBuf += nNew;
2482 *zBuf = 0;
2483 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002484 }else{
2485 ErrorMsg(psp->filename,psp->tokenlineno,
2486 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2487 psp->errorcnt++;
2488 psp->state = RESYNC_AFTER_DECL_ERROR;
2489 }
2490 break;
drh0bd1f4e2002-06-06 18:54:39 +00002491 case WAITING_FOR_FALLBACK_ID:
2492 if( x[0]=='.' ){
2493 psp->state = WAITING_FOR_DECL_OR_RULE;
2494 }else if( !isupper(x[0]) ){
2495 ErrorMsg(psp->filename, psp->tokenlineno,
2496 "%%fallback argument \"%s\" should be a token", x);
2497 psp->errorcnt++;
2498 }else{
2499 struct symbol *sp = Symbol_new(x);
2500 if( psp->fallback==0 ){
2501 psp->fallback = sp;
2502 }else if( sp->fallback ){
2503 ErrorMsg(psp->filename, psp->tokenlineno,
2504 "More than one fallback assigned to token %s", x);
2505 psp->errorcnt++;
2506 }else{
2507 sp->fallback = psp->fallback;
2508 psp->gp->has_fallback = 1;
2509 }
2510 }
2511 break;
drhe09daa92006-06-10 13:29:31 +00002512 case WAITING_FOR_WILDCARD_ID:
2513 if( x[0]=='.' ){
2514 psp->state = WAITING_FOR_DECL_OR_RULE;
2515 }else if( !isupper(x[0]) ){
2516 ErrorMsg(psp->filename, psp->tokenlineno,
2517 "%%wildcard argument \"%s\" should be a token", x);
2518 psp->errorcnt++;
2519 }else{
2520 struct symbol *sp = Symbol_new(x);
2521 if( psp->gp->wildcard==0 ){
2522 psp->gp->wildcard = sp;
2523 }else{
2524 ErrorMsg(psp->filename, psp->tokenlineno,
2525 "Extra wildcard to token: %s", x);
2526 psp->errorcnt++;
2527 }
2528 }
2529 break;
drh75897232000-05-29 14:26:00 +00002530 case RESYNC_AFTER_RULE_ERROR:
2531/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2532** break; */
2533 case RESYNC_AFTER_DECL_ERROR:
2534 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2535 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2536 break;
2537 }
2538}
2539
drh34ff57b2008-07-14 12:27:51 +00002540/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002541** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2542** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2543** comments them out. Text in between is also commented out as appropriate.
2544*/
danielk1977940fac92005-01-23 22:41:37 +00002545static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002546 int i, j, k, n;
2547 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002548 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002549 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002550 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002551 for(i=0; z[i]; i++){
2552 if( z[i]=='\n' ) lineno++;
2553 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2554 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2555 if( exclude ){
2556 exclude--;
2557 if( exclude==0 ){
2558 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2559 }
2560 }
2561 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2562 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2563 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2564 if( exclude ){
2565 exclude++;
2566 }else{
2567 for(j=i+7; isspace(z[j]); j++){}
2568 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2569 exclude = 1;
2570 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002571 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002572 exclude = 0;
2573 break;
2574 }
2575 }
2576 if( z[i+3]=='n' ) exclude = !exclude;
2577 if( exclude ){
2578 start = i;
2579 start_lineno = lineno;
2580 }
2581 }
2582 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2583 }
2584 }
2585 if( exclude ){
2586 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2587 exit(1);
2588 }
2589}
2590
drh75897232000-05-29 14:26:00 +00002591/* In spite of its name, this function is really a scanner. It read
2592** in the entire input file (all at once) then tokenizes it. Each
2593** token is passed to the function "parseonetoken" which builds all
2594** the appropriate data structures in the global state vector "gp".
2595*/
2596void Parse(gp)
2597struct lemon *gp;
2598{
2599 struct pstate ps;
2600 FILE *fp;
2601 char *filebuf;
2602 int filesize;
2603 int lineno;
2604 int c;
2605 char *cp, *nextcp;
2606 int startline = 0;
2607
rse38514a92007-09-20 11:34:17 +00002608 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002609 ps.gp = gp;
2610 ps.filename = gp->filename;
2611 ps.errorcnt = 0;
2612 ps.state = INITIALIZE;
2613
2614 /* Begin by reading the input file */
2615 fp = fopen(ps.filename,"rb");
2616 if( fp==0 ){
2617 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2618 gp->errorcnt++;
2619 return;
2620 }
2621 fseek(fp,0,2);
2622 filesize = ftell(fp);
2623 rewind(fp);
2624 filebuf = (char *)malloc( filesize+1 );
2625 if( filebuf==0 ){
2626 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2627 filesize+1);
2628 gp->errorcnt++;
2629 return;
2630 }
2631 if( fread(filebuf,1,filesize,fp)!=filesize ){
2632 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2633 filesize);
2634 free(filebuf);
2635 gp->errorcnt++;
2636 return;
2637 }
2638 fclose(fp);
2639 filebuf[filesize] = 0;
2640
drh6d08b4d2004-07-20 12:45:22 +00002641 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2642 preprocess_input(filebuf);
2643
drh75897232000-05-29 14:26:00 +00002644 /* Now scan the text of the input file */
2645 lineno = 1;
2646 for(cp=filebuf; (c= *cp)!=0; ){
2647 if( c=='\n' ) lineno++; /* Keep track of the line number */
2648 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2649 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2650 cp+=2;
2651 while( (c= *cp)!=0 && c!='\n' ) cp++;
2652 continue;
2653 }
2654 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2655 cp+=2;
2656 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2657 if( c=='\n' ) lineno++;
2658 cp++;
2659 }
2660 if( c ) cp++;
2661 continue;
2662 }
2663 ps.tokenstart = cp; /* Mark the beginning of the token */
2664 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2665 if( c=='\"' ){ /* String literals */
2666 cp++;
2667 while( (c= *cp)!=0 && c!='\"' ){
2668 if( c=='\n' ) lineno++;
2669 cp++;
2670 }
2671 if( c==0 ){
2672 ErrorMsg(ps.filename,startline,
2673"String starting on this line is not terminated before the end of the file.");
2674 ps.errorcnt++;
2675 nextcp = cp;
2676 }else{
2677 nextcp = cp+1;
2678 }
2679 }else if( c=='{' ){ /* A block of C code */
2680 int level;
2681 cp++;
2682 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2683 if( c=='\n' ) lineno++;
2684 else if( c=='{' ) level++;
2685 else if( c=='}' ) level--;
2686 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2687 int prevc;
2688 cp = &cp[2];
2689 prevc = 0;
2690 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2691 if( c=='\n' ) lineno++;
2692 prevc = c;
2693 cp++;
2694 }
2695 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2696 cp = &cp[2];
2697 while( (c= *cp)!=0 && c!='\n' ) cp++;
2698 if( c ) lineno++;
2699 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2700 int startchar, prevc;
2701 startchar = c;
2702 prevc = 0;
2703 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2704 if( c=='\n' ) lineno++;
2705 if( prevc=='\\' ) prevc = 0;
2706 else prevc = c;
2707 }
2708 }
2709 }
2710 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002711 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002712"C code starting on this line is not terminated before the end of the file.");
2713 ps.errorcnt++;
2714 nextcp = cp;
2715 }else{
2716 nextcp = cp+1;
2717 }
2718 }else if( isalnum(c) ){ /* Identifiers */
2719 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2720 nextcp = cp;
2721 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2722 cp += 3;
2723 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002724 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2725 cp += 2;
2726 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2727 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002728 }else{ /* All other (one character) operators */
2729 cp++;
2730 nextcp = cp;
2731 }
2732 c = *cp;
2733 *cp = 0; /* Null terminate the token */
2734 parseonetoken(&ps); /* Parse the token */
2735 *cp = c; /* Restore the buffer */
2736 cp = nextcp;
2737 }
2738 free(filebuf); /* Release the buffer after parsing */
2739 gp->rule = ps.firstrule;
2740 gp->errorcnt = ps.errorcnt;
2741}
2742/*************************** From the file "plink.c" *********************/
2743/*
2744** Routines processing configuration follow-set propagation links
2745** in the LEMON parser generator.
2746*/
2747static struct plink *plink_freelist = 0;
2748
2749/* Allocate a new plink */
2750struct plink *Plink_new(){
2751 struct plink *new;
2752
2753 if( plink_freelist==0 ){
2754 int i;
2755 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002756 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002757 if( plink_freelist==0 ){
2758 fprintf(stderr,
2759 "Unable to allocate memory for a new follow-set propagation link.\n");
2760 exit(1);
2761 }
2762 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2763 plink_freelist[amt-1].next = 0;
2764 }
2765 new = plink_freelist;
2766 plink_freelist = plink_freelist->next;
2767 return new;
2768}
2769
2770/* Add a plink to a plink list */
2771void Plink_add(plpp,cfp)
2772struct plink **plpp;
2773struct config *cfp;
2774{
2775 struct plink *new;
2776 new = Plink_new();
2777 new->next = *plpp;
2778 *plpp = new;
2779 new->cfp = cfp;
2780}
2781
2782/* Transfer every plink on the list "from" to the list "to" */
2783void Plink_copy(to,from)
2784struct plink **to;
2785struct plink *from;
2786{
2787 struct plink *nextpl;
2788 while( from ){
2789 nextpl = from->next;
2790 from->next = *to;
2791 *to = from;
2792 from = nextpl;
2793 }
2794}
2795
2796/* Delete every plink on the list */
2797void Plink_delete(plp)
2798struct plink *plp;
2799{
2800 struct plink *nextpl;
2801
2802 while( plp ){
2803 nextpl = plp->next;
2804 plp->next = plink_freelist;
2805 plink_freelist = plp;
2806 plp = nextpl;
2807 }
2808}
2809/*********************** From the file "report.c" **************************/
2810/*
2811** Procedures for generating reports and tables in the LEMON parser generator.
2812*/
2813
2814/* Generate a filename with the given suffix. Space to hold the
2815** name comes from malloc() and must be freed by the calling
2816** function.
2817*/
2818PRIVATE char *file_makename(lemp,suffix)
2819struct lemon *lemp;
2820char *suffix;
2821{
2822 char *name;
2823 char *cp;
2824
drh87cf1372008-08-13 20:09:06 +00002825 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002826 if( name==0 ){
2827 fprintf(stderr,"Can't allocate space for a filename.\n");
2828 exit(1);
2829 }
2830 strcpy(name,lemp->filename);
2831 cp = strrchr(name,'.');
2832 if( cp ) *cp = 0;
2833 strcat(name,suffix);
2834 return name;
2835}
2836
2837/* Open a file with a name based on the name of the input file,
2838** but with a different (specified) suffix, and return a pointer
2839** to the stream */
2840PRIVATE FILE *file_open(lemp,suffix,mode)
2841struct lemon *lemp;
2842char *suffix;
2843char *mode;
2844{
2845 FILE *fp;
2846
2847 if( lemp->outname ) free(lemp->outname);
2848 lemp->outname = file_makename(lemp, suffix);
2849 fp = fopen(lemp->outname,mode);
2850 if( fp==0 && *mode=='w' ){
2851 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2852 lemp->errorcnt++;
2853 return 0;
2854 }
icculusf5ad8242010-02-14 05:34:42 +00002855
2856 /* Add files we create to a list, so we can delete them if we fail. This
2857 ** is to keep makefiles from getting confused. We don't include .out files,
2858 ** though: this is debug information, and you don't want it deleted if there
2859 ** was an error you need to track down.
2860 */
2861 if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){
2862 const char **ptr = (const char **)
2863 realloc(made_files, sizeof (const char **) * (made_files_count + 1));
2864 char *fname = strdup(lemp->outname);
2865 if ((ptr == NULL) || (fname == NULL)) {
2866 free(ptr);
2867 free(fname);
2868 memory_error();
2869 }
2870 made_files = ptr;
2871 made_files[made_files_count++] = fname;
2872 }
drh75897232000-05-29 14:26:00 +00002873 return fp;
2874}
2875
2876/* Duplicate the input file without comments and without actions
2877** on rules */
2878void Reprint(lemp)
2879struct lemon *lemp;
2880{
2881 struct rule *rp;
2882 struct symbol *sp;
2883 int i, j, maxlen, len, ncolumns, skip;
2884 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2885 maxlen = 10;
2886 for(i=0; i<lemp->nsymbol; i++){
2887 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002888 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002889 if( len>maxlen ) maxlen = len;
2890 }
2891 ncolumns = 76/(maxlen+5);
2892 if( ncolumns<1 ) ncolumns = 1;
2893 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2894 for(i=0; i<skip; i++){
2895 printf("//");
2896 for(j=i; j<lemp->nsymbol; j+=skip){
2897 sp = lemp->symbols[j];
2898 assert( sp->index==j );
2899 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2900 }
2901 printf("\n");
2902 }
2903 for(rp=lemp->rule; rp; rp=rp->next){
2904 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002905 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002906 printf(" ::=");
2907 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002908 sp = rp->rhs[i];
2909 printf(" %s", sp->name);
2910 if( sp->type==MULTITERMINAL ){
2911 for(j=1; j<sp->nsubsym; j++){
2912 printf("|%s", sp->subsym[j]->name);
2913 }
2914 }
2915 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002916 }
2917 printf(".");
2918 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002919 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002920 printf("\n");
2921 }
2922}
2923
2924void ConfigPrint(fp,cfp)
2925FILE *fp;
2926struct config *cfp;
2927{
2928 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002929 struct symbol *sp;
2930 int i, j;
drh75897232000-05-29 14:26:00 +00002931 rp = cfp->rp;
2932 fprintf(fp,"%s ::=",rp->lhs->name);
2933 for(i=0; i<=rp->nrhs; i++){
2934 if( i==cfp->dot ) fprintf(fp," *");
2935 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002936 sp = rp->rhs[i];
2937 fprintf(fp," %s", sp->name);
2938 if( sp->type==MULTITERMINAL ){
2939 for(j=1; j<sp->nsubsym; j++){
2940 fprintf(fp,"|%s",sp->subsym[j]->name);
2941 }
2942 }
drh75897232000-05-29 14:26:00 +00002943 }
2944}
2945
2946/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002947#if 0
drh75897232000-05-29 14:26:00 +00002948/* Print a set */
2949PRIVATE void SetPrint(out,set,lemp)
2950FILE *out;
2951char *set;
2952struct lemon *lemp;
2953{
2954 int i;
2955 char *spacer;
2956 spacer = "";
2957 fprintf(out,"%12s[","");
2958 for(i=0; i<lemp->nterminal; i++){
2959 if( SetFind(set,i) ){
2960 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2961 spacer = " ";
2962 }
2963 }
2964 fprintf(out,"]\n");
2965}
2966
2967/* Print a plink chain */
2968PRIVATE void PlinkPrint(out,plp,tag)
2969FILE *out;
2970struct plink *plp;
2971char *tag;
2972{
2973 while( plp ){
drhada354d2005-11-05 15:03:59 +00002974 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002975 ConfigPrint(out,plp->cfp);
2976 fprintf(out,"\n");
2977 plp = plp->next;
2978 }
2979}
2980#endif
2981
2982/* Print an action to the given file descriptor. Return FALSE if
2983** nothing was actually printed.
2984*/
2985int PrintAction(struct action *ap, FILE *fp, int indent){
2986 int result = 1;
2987 switch( ap->type ){
2988 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002989 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002990 break;
2991 case REDUCE:
2992 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2993 break;
2994 case ACCEPT:
2995 fprintf(fp,"%*s accept",indent,ap->sp->name);
2996 break;
2997 case ERROR:
2998 fprintf(fp,"%*s error",indent,ap->sp->name);
2999 break;
drh9892c5d2007-12-21 00:02:11 +00003000 case SRCONFLICT:
3001 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00003002 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
3003 indent,ap->sp->name,ap->x.rp->index);
3004 break;
drh9892c5d2007-12-21 00:02:11 +00003005 case SSCONFLICT:
3006 fprintf(fp,"%*s shift %d ** Parsing conflict **",
3007 indent,ap->sp->name,ap->x.stp->statenum);
3008 break;
drh75897232000-05-29 14:26:00 +00003009 case SH_RESOLVED:
3010 case RD_RESOLVED:
3011 case NOT_USED:
3012 result = 0;
3013 break;
3014 }
3015 return result;
3016}
3017
3018/* Generate the "y.output" log file */
3019void ReportOutput(lemp)
3020struct lemon *lemp;
3021{
3022 int i;
3023 struct state *stp;
3024 struct config *cfp;
3025 struct action *ap;
3026 FILE *fp;
3027
drh2aa6ca42004-09-10 00:14:04 +00003028 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003029 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00003030 for(i=0; i<lemp->nstate; i++){
3031 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003032 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003033 if( lemp->basisflag ) cfp=stp->bp;
3034 else cfp=stp->cfp;
3035 while( cfp ){
3036 char buf[20];
3037 if( cfp->dot==cfp->rp->nrhs ){
3038 sprintf(buf,"(%d)",cfp->rp->index);
3039 fprintf(fp," %5s ",buf);
3040 }else{
3041 fprintf(fp," ");
3042 }
3043 ConfigPrint(fp,cfp);
3044 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003045#if 0
drh75897232000-05-29 14:26:00 +00003046 SetPrint(fp,cfp->fws,lemp);
3047 PlinkPrint(fp,cfp->fplp,"To ");
3048 PlinkPrint(fp,cfp->bplp,"From");
3049#endif
3050 if( lemp->basisflag ) cfp=cfp->bp;
3051 else cfp=cfp->next;
3052 }
3053 fprintf(fp,"\n");
3054 for(ap=stp->ap; ap; ap=ap->next){
3055 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3056 }
3057 fprintf(fp,"\n");
3058 }
drhe9278182007-07-18 18:16:29 +00003059 fprintf(fp, "----------------------------------------------------\n");
3060 fprintf(fp, "Symbols:\n");
3061 for(i=0; i<lemp->nsymbol; i++){
3062 int j;
3063 struct symbol *sp;
3064
3065 sp = lemp->symbols[i];
3066 fprintf(fp, " %3d: %s", i, sp->name);
3067 if( sp->type==NONTERMINAL ){
3068 fprintf(fp, ":");
3069 if( sp->lambda ){
3070 fprintf(fp, " <lambda>");
3071 }
3072 for(j=0; j<lemp->nterminal; j++){
3073 if( sp->firstset && SetFind(sp->firstset, j) ){
3074 fprintf(fp, " %s", lemp->symbols[j]->name);
3075 }
3076 }
3077 }
3078 fprintf(fp, "\n");
3079 }
drh75897232000-05-29 14:26:00 +00003080 fclose(fp);
3081 return;
3082}
3083
3084/* Search for the file "name" which is in the same directory as
3085** the exacutable */
3086PRIVATE char *pathsearch(argv0,name,modemask)
3087char *argv0;
3088char *name;
3089int modemask;
3090{
3091 char *pathlist;
3092 char *path,*cp;
3093 char c;
drh75897232000-05-29 14:26:00 +00003094
3095#ifdef __WIN32__
3096 cp = strrchr(argv0,'\\');
3097#else
3098 cp = strrchr(argv0,'/');
3099#endif
3100 if( cp ){
3101 c = *cp;
3102 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003103 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003104 if( path ) sprintf(path,"%s/%s",argv0,name);
3105 *cp = c;
3106 }else{
3107 extern char *getenv();
3108 pathlist = getenv("PATH");
3109 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00003110 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00003111 if( path!=0 ){
3112 while( *pathlist ){
3113 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00003114 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00003115 c = *cp;
3116 *cp = 0;
3117 sprintf(path,"%s/%s",pathlist,name);
3118 *cp = c;
3119 if( c==0 ) pathlist = "";
3120 else pathlist = &cp[1];
3121 if( access(path,modemask)==0 ) break;
3122 }
3123 }
3124 }
3125 return path;
3126}
3127
3128/* Given an action, compute the integer value for that action
3129** which is to be put in the action table of the generated machine.
3130** Return negative if no action should be generated.
3131*/
3132PRIVATE int compute_action(lemp,ap)
3133struct lemon *lemp;
3134struct action *ap;
3135{
3136 int act;
3137 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003138 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003139 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3140 case ERROR: act = lemp->nstate + lemp->nrule; break;
3141 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3142 default: act = -1; break;
3143 }
3144 return act;
3145}
3146
3147#define LINESIZE 1000
3148/* The next cluster of routines are for reading the template file
3149** and writing the results to the generated parser */
3150/* The first function transfers data from "in" to "out" until
3151** a line is seen which begins with "%%". The line number is
3152** tracked.
3153**
3154** if name!=0, then any word that begin with "Parse" is changed to
3155** begin with *name instead.
3156*/
3157PRIVATE void tplt_xfer(name,in,out,lineno)
3158char *name;
3159FILE *in;
3160FILE *out;
3161int *lineno;
3162{
3163 int i, iStart;
3164 char line[LINESIZE];
3165 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3166 (*lineno)++;
3167 iStart = 0;
3168 if( name ){
3169 for(i=0; line[i]; i++){
3170 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3171 && (i==0 || !isalpha(line[i-1]))
3172 ){
3173 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3174 fprintf(out,"%s",name);
3175 i += 4;
3176 iStart = i+1;
3177 }
3178 }
3179 }
3180 fprintf(out,"%s",&line[iStart]);
3181 }
3182}
3183
3184/* The next function finds the template file and opens it, returning
3185** a pointer to the opened file. */
3186PRIVATE FILE *tplt_open(lemp)
3187struct lemon *lemp;
3188{
3189 static char templatename[] = "lempar.c";
3190 char buf[1000];
3191 FILE *in;
3192 char *tpltname;
3193 char *cp;
3194
icculus3e143bd2010-02-14 00:48:49 +00003195 /* first, see if user specified a template filename on the command line. */
3196 if (user_templatename != 0) {
3197 if( access(user_templatename,004)==-1 ){
3198 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3199 user_templatename);
3200 lemp->errorcnt++;
3201 return 0;
3202 }
3203 in = fopen(user_templatename,"rb");
3204 if( in==0 ){
3205 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3206 lemp->errorcnt++;
3207 return 0;
3208 }
3209 return in;
3210 }
3211
drh75897232000-05-29 14:26:00 +00003212 cp = strrchr(lemp->filename,'.');
3213 if( cp ){
drh8b582012003-10-21 13:16:03 +00003214 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003215 }else{
3216 sprintf(buf,"%s.lt",lemp->filename);
3217 }
3218 if( access(buf,004)==0 ){
3219 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003220 }else if( access(templatename,004)==0 ){
3221 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003222 }else{
3223 tpltname = pathsearch(lemp->argv0,templatename,0);
3224 }
3225 if( tpltname==0 ){
3226 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3227 templatename);
3228 lemp->errorcnt++;
3229 return 0;
3230 }
drh2aa6ca42004-09-10 00:14:04 +00003231 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003232 if( in==0 ){
3233 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3234 lemp->errorcnt++;
3235 return 0;
3236 }
3237 return in;
3238}
3239
drhaf805ca2004-09-07 11:28:25 +00003240/* Print a #line directive line to the output file. */
3241PRIVATE void tplt_linedir(out,lineno,filename)
3242FILE *out;
3243int lineno;
3244char *filename;
3245{
3246 fprintf(out,"#line %d \"",lineno);
3247 while( *filename ){
3248 if( *filename == '\\' ) putc('\\',out);
3249 putc(*filename,out);
3250 filename++;
3251 }
3252 fprintf(out,"\"\n");
3253}
3254
drh75897232000-05-29 14:26:00 +00003255/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003256PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003257FILE *out;
3258struct lemon *lemp;
3259char *str;
drh75897232000-05-29 14:26:00 +00003260int *lineno;
3261{
3262 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003263 while( *str ){
drh75897232000-05-29 14:26:00 +00003264 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003265 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003266 str++;
3267 }
drh9db55df2004-09-09 14:01:21 +00003268 if( str[-1]!='\n' ){
3269 putc('\n',out);
3270 (*lineno)++;
3271 }
shane58543932008-12-10 20:10:04 +00003272 if (!lemp->nolinenosflag) {
3273 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3274 }
drh75897232000-05-29 14:26:00 +00003275 return;
3276}
3277
3278/*
3279** The following routine emits code for the destructor for the
3280** symbol sp
3281*/
3282void emit_destructor_code(out,sp,lemp,lineno)
3283FILE *out;
3284struct symbol *sp;
3285struct lemon *lemp;
3286int *lineno;
3287{
drhcc83b6e2004-04-23 23:38:42 +00003288 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003289
drh75897232000-05-29 14:26:00 +00003290 if( sp->type==TERMINAL ){
3291 cp = lemp->tokendest;
3292 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003293 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003294 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003295 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003296 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003297 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003298 }else if( lemp->vardest ){
3299 cp = lemp->vardest;
3300 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003301 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003302 }else{
3303 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003304 }
3305 for(; *cp; cp++){
3306 if( *cp=='$' && cp[1]=='$' ){
3307 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3308 cp++;
3309 continue;
3310 }
shane58543932008-12-10 20:10:04 +00003311 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003312 fputc(*cp,out);
3313 }
shane58543932008-12-10 20:10:04 +00003314 fprintf(out,"\n"); (*lineno)++;
3315 if (!lemp->nolinenosflag) {
3316 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3317 }
3318 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003319 return;
3320}
3321
3322/*
drh960e8c62001-04-03 16:53:21 +00003323** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003324*/
3325int has_destructor(sp, lemp)
3326struct symbol *sp;
3327struct lemon *lemp;
3328{
3329 int ret;
3330 if( sp->type==TERMINAL ){
3331 ret = lemp->tokendest!=0;
3332 }else{
drh960e8c62001-04-03 16:53:21 +00003333 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003334 }
3335 return ret;
3336}
3337
drh0bb132b2004-07-20 14:06:51 +00003338/*
3339** Append text to a dynamically allocated string. If zText is 0 then
3340** reset the string to be empty again. Always return the complete text
3341** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003342**
3343** n bytes of zText are stored. If n==0 then all of zText up to the first
3344** \000 terminator is stored. zText can contain up to two instances of
3345** %d. The values of p1 and p2 are written into the first and second
3346** %d.
3347**
3348** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003349*/
3350PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3351 static char *z = 0;
3352 static int alloced = 0;
3353 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003354 int c;
drh0bb132b2004-07-20 14:06:51 +00003355 char zInt[40];
3356
3357 if( zText==0 ){
3358 used = 0;
3359 return z;
3360 }
drh7ac25c72004-08-19 15:12:26 +00003361 if( n<=0 ){
3362 if( n<0 ){
3363 used += n;
3364 assert( used>=0 );
3365 }
drh87cf1372008-08-13 20:09:06 +00003366 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003367 }
drh0bb132b2004-07-20 14:06:51 +00003368 if( n+sizeof(zInt)*2+used >= alloced ){
3369 alloced = n + sizeof(zInt)*2 + used + 200;
3370 z = realloc(z, alloced);
3371 }
3372 if( z==0 ) return "";
3373 while( n-- > 0 ){
3374 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003375 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003376 sprintf(zInt, "%d", p1);
3377 p1 = p2;
3378 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003379 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003380 zText++;
3381 n--;
3382 }else{
3383 z[used++] = c;
3384 }
3385 }
3386 z[used] = 0;
3387 return z;
3388}
3389
3390/*
3391** zCode is a string that is the action associated with a rule. Expand
3392** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003393** stack.
drh0bb132b2004-07-20 14:06:51 +00003394*/
drhaf805ca2004-09-07 11:28:25 +00003395PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003396 char *cp, *xp;
3397 int i;
3398 char lhsused = 0; /* True if the LHS element has been used */
3399 char used[MAXRHS]; /* True for each RHS element which is used */
3400
3401 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3402 lhsused = 0;
3403
drh19c9e562007-03-29 20:13:53 +00003404 if( rp->code==0 ){
3405 rp->code = "\n";
3406 rp->line = rp->ruleline;
3407 }
3408
drh0bb132b2004-07-20 14:06:51 +00003409 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003410 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003411 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3412 char saved;
3413 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3414 saved = *xp;
3415 *xp = 0;
3416 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003417 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003418 cp = xp;
3419 lhsused = 1;
3420 }else{
3421 for(i=0; i<rp->nrhs; i++){
3422 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003423 if( cp!=rp->code && cp[-1]=='@' ){
3424 /* If the argument is of the form @X then substituted
3425 ** the token number of X, not the value of X */
3426 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3427 }else{
drhfd405312005-11-06 04:06:59 +00003428 struct symbol *sp = rp->rhs[i];
3429 int dtnum;
3430 if( sp->type==MULTITERMINAL ){
3431 dtnum = sp->subsym[0]->dtnum;
3432 }else{
3433 dtnum = sp->dtnum;
3434 }
3435 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003436 }
drh0bb132b2004-07-20 14:06:51 +00003437 cp = xp;
3438 used[i] = 1;
3439 break;
3440 }
3441 }
3442 }
3443 *xp = saved;
3444 }
3445 append_str(cp, 1, 0, 0);
3446 } /* End loop */
3447
3448 /* Check to make sure the LHS has been used */
3449 if( rp->lhsalias && !lhsused ){
3450 ErrorMsg(lemp->filename,rp->ruleline,
3451 "Label \"%s\" for \"%s(%s)\" is never used.",
3452 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3453 lemp->errorcnt++;
3454 }
3455
3456 /* Generate destructor code for RHS symbols which are not used in the
3457 ** reduce code */
3458 for(i=0; i<rp->nrhs; i++){
3459 if( rp->rhsalias[i] && !used[i] ){
3460 ErrorMsg(lemp->filename,rp->ruleline,
3461 "Label %s for \"%s(%s)\" is never used.",
3462 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3463 lemp->errorcnt++;
3464 }else if( rp->rhsalias[i]==0 ){
3465 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003466 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003467 rp->rhs[i]->index,i-rp->nrhs+1);
3468 }else{
3469 /* No destructor defined for this term */
3470 }
3471 }
3472 }
drh61e339a2007-01-16 03:09:02 +00003473 if( rp->code ){
3474 cp = append_str(0,0,0,0);
3475 rp->code = Strsafe(cp?cp:"");
3476 }
drh0bb132b2004-07-20 14:06:51 +00003477}
3478
drh75897232000-05-29 14:26:00 +00003479/*
3480** Generate code which executes when the rule "rp" is reduced. Write
3481** the code to "out". Make sure lineno stays up-to-date.
3482*/
3483PRIVATE void emit_code(out,rp,lemp,lineno)
3484FILE *out;
3485struct rule *rp;
3486struct lemon *lemp;
3487int *lineno;
3488{
drh0bb132b2004-07-20 14:06:51 +00003489 char *cp;
drh75897232000-05-29 14:26:00 +00003490
3491 /* Generate code to do the reduce action */
3492 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003493 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003494 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003495 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003496 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003497 } /* End loop */
shane58543932008-12-10 20:10:04 +00003498 fprintf(out,"}\n"); (*lineno)++;
3499 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003500 } /* End if( rp->code ) */
3501
drh75897232000-05-29 14:26:00 +00003502 return;
3503}
3504
3505/*
3506** Print the definition of the union used for the parser's data stack.
3507** This union contains fields for every possible data type for tokens
3508** and nonterminals. In the process of computing and printing this
3509** union, also set the ".dtnum" field of every terminal and nonterminal
3510** symbol.
3511*/
3512void print_stack_union(out,lemp,plineno,mhflag)
3513FILE *out; /* The output stream */
3514struct lemon *lemp; /* The main info structure for this parser */
3515int *plineno; /* Pointer to the line number */
3516int mhflag; /* True if generating makeheaders output */
3517{
3518 int lineno = *plineno; /* The line number of the output */
3519 char **types; /* A hash table of datatypes */
3520 int arraysize; /* Size of the "types" array */
3521 int maxdtlength; /* Maximum length of any ".datatype" field. */
3522 char *stddt; /* Standardized name for a datatype */
3523 int i,j; /* Loop counters */
3524 int hash; /* For hashing the name of a type */
3525 char *name; /* Name of the parser */
3526
3527 /* Allocate and initialize types[] and allocate stddt[] */
3528 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003529 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003530 for(i=0; i<arraysize; i++) types[i] = 0;
3531 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003532 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003533 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003534 }
drh75897232000-05-29 14:26:00 +00003535 for(i=0; i<lemp->nsymbol; i++){
3536 int len;
3537 struct symbol *sp = lemp->symbols[i];
3538 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003539 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003540 if( len>maxdtlength ) maxdtlength = len;
3541 }
3542 stddt = (char*)malloc( maxdtlength*2 + 1 );
3543 if( types==0 || stddt==0 ){
3544 fprintf(stderr,"Out of memory.\n");
3545 exit(1);
3546 }
3547
3548 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3549 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003550 ** used for terminal symbols. If there is no %default_type defined then
3551 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3552 ** a datatype using the %type directive.
3553 */
drh75897232000-05-29 14:26:00 +00003554 for(i=0; i<lemp->nsymbol; i++){
3555 struct symbol *sp = lemp->symbols[i];
3556 char *cp;
3557 if( sp==lemp->errsym ){
3558 sp->dtnum = arraysize+1;
3559 continue;
3560 }
drh960e8c62001-04-03 16:53:21 +00003561 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003562 sp->dtnum = 0;
3563 continue;
3564 }
3565 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003566 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003567 j = 0;
3568 while( isspace(*cp) ) cp++;
3569 while( *cp ) stddt[j++] = *cp++;
3570 while( j>0 && isspace(stddt[j-1]) ) j--;
3571 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003572 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003573 sp->dtnum = 0;
3574 continue;
3575 }
drh75897232000-05-29 14:26:00 +00003576 hash = 0;
3577 for(j=0; stddt[j]; j++){
3578 hash = hash*53 + stddt[j];
3579 }
drh3b2129c2003-05-13 00:34:21 +00003580 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003581 while( types[hash] ){
3582 if( strcmp(types[hash],stddt)==0 ){
3583 sp->dtnum = hash + 1;
3584 break;
3585 }
3586 hash++;
3587 if( hash>=arraysize ) hash = 0;
3588 }
3589 if( types[hash]==0 ){
3590 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003591 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003592 if( types[hash]==0 ){
3593 fprintf(stderr,"Out of memory.\n");
3594 exit(1);
3595 }
3596 strcpy(types[hash],stddt);
3597 }
3598 }
3599
3600 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3601 name = lemp->name ? lemp->name : "Parse";
3602 lineno = *plineno;
3603 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3604 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3605 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3606 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3607 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003608 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003609 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3610 for(i=0; i<arraysize; i++){
3611 if( types[i]==0 ) continue;
3612 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3613 free(types[i]);
3614 }
drhc4dd3fd2008-01-22 01:48:05 +00003615 if( lemp->errsym->useCnt ){
3616 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3617 }
drh75897232000-05-29 14:26:00 +00003618 free(stddt);
3619 free(types);
3620 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3621 *plineno = lineno;
3622}
3623
drhb29b0a52002-02-23 19:39:46 +00003624/*
3625** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003626** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003627*/
drh8b582012003-10-21 13:16:03 +00003628static const char *minimum_size_type(int lwr, int upr){
3629 if( lwr>=0 ){
3630 if( upr<=255 ){
3631 return "unsigned char";
3632 }else if( upr<65535 ){
3633 return "unsigned short int";
3634 }else{
3635 return "unsigned int";
3636 }
3637 }else if( lwr>=-127 && upr<=127 ){
3638 return "signed char";
3639 }else if( lwr>=-32767 && upr<32767 ){
3640 return "short";
drhb29b0a52002-02-23 19:39:46 +00003641 }else{
drh8b582012003-10-21 13:16:03 +00003642 return "int";
drhb29b0a52002-02-23 19:39:46 +00003643 }
3644}
3645
drhfdbf9282003-10-21 16:34:41 +00003646/*
3647** Each state contains a set of token transaction and a set of
3648** nonterminal transactions. Each of these sets makes an instance
3649** of the following structure. An array of these structures is used
3650** to order the creation of entries in the yy_action[] table.
3651*/
3652struct axset {
3653 struct state *stp; /* A pointer to a state */
3654 int isTkn; /* True to use tokens. False for non-terminals */
3655 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003656 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003657};
3658
3659/*
3660** Compare to axset structures for sorting purposes
3661*/
3662static int axset_compare(const void *a, const void *b){
3663 struct axset *p1 = (struct axset*)a;
3664 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003665 int c;
3666 c = p2->nAction - p1->nAction;
3667 if( c==0 ){
3668 c = p2->iOrder - p1->iOrder;
3669 }
3670 assert( c!=0 || p1==p2 );
3671 return c;
drhfdbf9282003-10-21 16:34:41 +00003672}
3673
drhc4dd3fd2008-01-22 01:48:05 +00003674/*
3675** Write text on "out" that describes the rule "rp".
3676*/
3677static void writeRuleText(FILE *out, struct rule *rp){
3678 int j;
3679 fprintf(out,"%s ::=", rp->lhs->name);
3680 for(j=0; j<rp->nrhs; j++){
3681 struct symbol *sp = rp->rhs[j];
3682 fprintf(out," %s", sp->name);
3683 if( sp->type==MULTITERMINAL ){
3684 int k;
3685 for(k=1; k<sp->nsubsym; k++){
3686 fprintf(out,"|%s",sp->subsym[k]->name);
3687 }
3688 }
3689 }
3690}
3691
3692
drh75897232000-05-29 14:26:00 +00003693/* Generate C source code for the parser */
3694void ReportTable(lemp, mhflag)
3695struct lemon *lemp;
3696int mhflag; /* Output in makeheaders format if true */
3697{
3698 FILE *out, *in;
3699 char line[LINESIZE];
3700 int lineno;
3701 struct state *stp;
3702 struct action *ap;
3703 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003704 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003705 int i, j, k, n;
drh75897232000-05-29 14:26:00 +00003706 char *name;
drh8b582012003-10-21 13:16:03 +00003707 int mnTknOfst, mxTknOfst;
3708 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003709 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003710
3711 in = tplt_open(lemp);
3712 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003713 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003714 if( out==0 ){
3715 fclose(in);
3716 return;
3717 }
3718 lineno = 1;
3719 tplt_xfer(lemp->name,in,out,&lineno);
3720
3721 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003722 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003723 if( mhflag ){
3724 char *name = file_makename(lemp, ".h");
3725 fprintf(out,"#include \"%s\"\n", name); lineno++;
3726 free(name);
3727 }
3728 tplt_xfer(lemp->name,in,out,&lineno);
3729
3730 /* Generate #defines for all tokens */
3731 if( mhflag ){
3732 char *prefix;
3733 fprintf(out,"#if INTERFACE\n"); lineno++;
3734 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3735 else prefix = "";
3736 for(i=1; i<lemp->nterminal; i++){
3737 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3738 lineno++;
3739 }
3740 fprintf(out,"#endif\n"); lineno++;
3741 }
3742 tplt_xfer(lemp->name,in,out,&lineno);
3743
3744 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003745 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003746 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003747 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3748 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003749 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003750 if( lemp->wildcard ){
3751 fprintf(out,"#define YYWILDCARD %d\n",
3752 lemp->wildcard->index); lineno++;
3753 }
drh75897232000-05-29 14:26:00 +00003754 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003755 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003756 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003757 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3758 }else{
3759 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3760 }
drhca44b5a2007-02-22 23:06:58 +00003761 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003762 if( mhflag ){
3763 fprintf(out,"#if INTERFACE\n"); lineno++;
3764 }
3765 name = lemp->name ? lemp->name : "Parse";
3766 if( lemp->arg && lemp->arg[0] ){
3767 int i;
drh87cf1372008-08-13 20:09:06 +00003768 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003769 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3770 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003771 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3772 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3773 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3774 name,lemp->arg,&lemp->arg[i]); lineno++;
3775 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3776 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003777 }else{
drh1f245e42002-03-11 13:55:50 +00003778 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3779 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3780 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3781 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003782 }
3783 if( mhflag ){
3784 fprintf(out,"#endif\n"); lineno++;
3785 }
3786 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3787 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003788 if( lemp->errsym->useCnt ){
3789 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3790 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3791 }
drh0bd1f4e2002-06-06 18:54:39 +00003792 if( lemp->has_fallback ){
3793 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3794 }
drh75897232000-05-29 14:26:00 +00003795 tplt_xfer(lemp->name,in,out,&lineno);
3796
drh8b582012003-10-21 13:16:03 +00003797 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003798 **
drh8b582012003-10-21 13:16:03 +00003799 ** yy_action[] A single table containing all actions.
3800 ** yy_lookahead[] A table containing the lookahead for each entry in
3801 ** yy_action. Used to detect hash collisions.
3802 ** yy_shift_ofst[] For each state, the offset into yy_action for
3803 ** shifting terminals.
3804 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3805 ** shifting non-terminals after a reduce.
3806 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003807 */
drh75897232000-05-29 14:26:00 +00003808
drh8b582012003-10-21 13:16:03 +00003809 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003810 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003811 if( ax==0 ){
3812 fprintf(stderr,"malloc failed\n");
3813 exit(1);
3814 }
drh75897232000-05-29 14:26:00 +00003815 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003816 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003817 ax[i*2].stp = stp;
3818 ax[i*2].isTkn = 1;
3819 ax[i*2].nAction = stp->nTknAct;
3820 ax[i*2+1].stp = stp;
3821 ax[i*2+1].isTkn = 0;
3822 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003823 }
drh8b582012003-10-21 13:16:03 +00003824 mxTknOfst = mnTknOfst = 0;
3825 mxNtOfst = mnNtOfst = 0;
3826
drhfdbf9282003-10-21 16:34:41 +00003827 /* Compute the action table. In order to try to keep the size of the
3828 ** action table to a minimum, the heuristic of placing the largest action
3829 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003830 */
drhe594bc32009-11-03 13:02:25 +00003831 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003832 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003833 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003834 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3835 stp = ax[i].stp;
3836 if( ax[i].isTkn ){
3837 for(ap=stp->ap; ap; ap=ap->next){
3838 int action;
3839 if( ap->sp->index>=lemp->nterminal ) continue;
3840 action = compute_action(lemp, ap);
3841 if( action<0 ) continue;
3842 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003843 }
drhfdbf9282003-10-21 16:34:41 +00003844 stp->iTknOfst = acttab_insert(pActtab);
3845 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3846 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3847 }else{
3848 for(ap=stp->ap; ap; ap=ap->next){
3849 int action;
3850 if( ap->sp->index<lemp->nterminal ) continue;
3851 if( ap->sp->index==lemp->nsymbol ) continue;
3852 action = compute_action(lemp, ap);
3853 if( action<0 ) continue;
3854 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003855 }
drhfdbf9282003-10-21 16:34:41 +00003856 stp->iNtOfst = acttab_insert(pActtab);
3857 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3858 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003859 }
3860 }
drhfdbf9282003-10-21 16:34:41 +00003861 free(ax);
drh8b582012003-10-21 13:16:03 +00003862
3863 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003864 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003865 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3866 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003867 for(i=j=0; i<n; i++){
3868 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003869 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003870 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003871 fprintf(out, " %4d,", action);
3872 if( j==9 || i==n-1 ){
3873 fprintf(out, "\n"); lineno++;
3874 j = 0;
3875 }else{
3876 j++;
3877 }
3878 }
3879 fprintf(out, "};\n"); lineno++;
3880
3881 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003882 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003883 for(i=j=0; i<n; i++){
3884 int la = acttab_yylookahead(pActtab, i);
3885 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003886 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003887 fprintf(out, " %4d,", la);
3888 if( j==9 || i==n-1 ){
3889 fprintf(out, "\n"); lineno++;
3890 j = 0;
3891 }else{
3892 j++;
3893 }
3894 }
3895 fprintf(out, "};\n"); lineno++;
3896
3897 /* Output the yy_shift_ofst[] table */
3898 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003899 n = lemp->nstate;
3900 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003901 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3902 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3903 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003904 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003905 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003906 for(i=j=0; i<n; i++){
3907 int ofst;
3908 stp = lemp->sorted[i];
3909 ofst = stp->iTknOfst;
3910 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003911 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003912 fprintf(out, " %4d,", ofst);
3913 if( j==9 || i==n-1 ){
3914 fprintf(out, "\n"); lineno++;
3915 j = 0;
3916 }else{
3917 j++;
3918 }
3919 }
3920 fprintf(out, "};\n"); lineno++;
3921
3922 /* Output the yy_reduce_ofst[] table */
3923 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003924 n = lemp->nstate;
3925 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003926 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3927 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3928 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003929 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003930 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003931 for(i=j=0; i<n; i++){
3932 int ofst;
3933 stp = lemp->sorted[i];
3934 ofst = stp->iNtOfst;
3935 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003936 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003937 fprintf(out, " %4d,", ofst);
3938 if( j==9 || i==n-1 ){
3939 fprintf(out, "\n"); lineno++;
3940 j = 0;
3941 }else{
3942 j++;
3943 }
3944 }
3945 fprintf(out, "};\n"); lineno++;
3946
3947 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003948 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003949 n = lemp->nstate;
3950 for(i=j=0; i<n; i++){
3951 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003952 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003953 fprintf(out, " %4d,", stp->iDflt);
3954 if( j==9 || i==n-1 ){
3955 fprintf(out, "\n"); lineno++;
3956 j = 0;
3957 }else{
3958 j++;
3959 }
3960 }
3961 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003962 tplt_xfer(lemp->name,in,out,&lineno);
3963
drh0bd1f4e2002-06-06 18:54:39 +00003964 /* Generate the table of fallback tokens.
3965 */
3966 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003967 int mx = lemp->nterminal - 1;
3968 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3969 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003970 struct symbol *p = lemp->symbols[i];
3971 if( p->fallback==0 ){
3972 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3973 }else{
3974 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3975 p->name, p->fallback->name);
3976 }
3977 lineno++;
3978 }
3979 }
3980 tplt_xfer(lemp->name, in, out, &lineno);
3981
3982 /* Generate a table containing the symbolic name of every symbol
3983 */
drh75897232000-05-29 14:26:00 +00003984 for(i=0; i<lemp->nsymbol; i++){
3985 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3986 fprintf(out," %-15s",line);
3987 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3988 }
3989 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3990 tplt_xfer(lemp->name,in,out,&lineno);
3991
drh0bd1f4e2002-06-06 18:54:39 +00003992 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003993 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003994 ** when tracing REDUCE actions.
3995 */
3996 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3997 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003998 fprintf(out," /* %3d */ \"", i);
3999 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004000 fprintf(out,"\",\n"); lineno++;
4001 }
4002 tplt_xfer(lemp->name,in,out,&lineno);
4003
drh75897232000-05-29 14:26:00 +00004004 /* Generate code which executes every time a symbol is popped from
4005 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004006 ** (In other words, generate the %destructor actions)
4007 */
drh75897232000-05-29 14:26:00 +00004008 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004009 int once = 1;
drh75897232000-05-29 14:26:00 +00004010 for(i=0; i<lemp->nsymbol; i++){
4011 struct symbol *sp = lemp->symbols[i];
4012 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004013 if( once ){
4014 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4015 once = 0;
4016 }
drhc53eed12009-06-12 17:46:19 +00004017 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004018 }
4019 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4020 if( i<lemp->nsymbol ){
4021 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4022 fprintf(out," break;\n"); lineno++;
4023 }
4024 }
drh8d659732005-01-13 23:54:06 +00004025 if( lemp->vardest ){
4026 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004027 int once = 1;
drh8d659732005-01-13 23:54:06 +00004028 for(i=0; i<lemp->nsymbol; i++){
4029 struct symbol *sp = lemp->symbols[i];
4030 if( sp==0 || sp->type==TERMINAL ||
4031 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004032 if( once ){
4033 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4034 once = 0;
4035 }
drhc53eed12009-06-12 17:46:19 +00004036 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004037 dflt_sp = sp;
4038 }
4039 if( dflt_sp!=0 ){
4040 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004041 }
drh4dc8ef52008-07-01 17:13:57 +00004042 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004043 }
drh75897232000-05-29 14:26:00 +00004044 for(i=0; i<lemp->nsymbol; i++){
4045 struct symbol *sp = lemp->symbols[i];
4046 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004047 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004048
4049 /* Combine duplicate destructors into a single case */
4050 for(j=i+1; j<lemp->nsymbol; j++){
4051 struct symbol *sp2 = lemp->symbols[j];
4052 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4053 && sp2->dtnum==sp->dtnum
4054 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004055 fprintf(out," case %d: /* %s */\n",
4056 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004057 sp2->destructor = 0;
4058 }
4059 }
4060
drh75897232000-05-29 14:26:00 +00004061 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4062 fprintf(out," break;\n"); lineno++;
4063 }
drh75897232000-05-29 14:26:00 +00004064 tplt_xfer(lemp->name,in,out,&lineno);
4065
4066 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004067 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004068 tplt_xfer(lemp->name,in,out,&lineno);
4069
4070 /* Generate the table of rule information
4071 **
4072 ** Note: This code depends on the fact that rules are number
4073 ** sequentually beginning with 0.
4074 */
4075 for(rp=lemp->rule; rp; rp=rp->next){
4076 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4077 }
4078 tplt_xfer(lemp->name,in,out,&lineno);
4079
4080 /* Generate code which execution during each REDUCE action */
4081 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004082 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004083 }
drhc53eed12009-06-12 17:46:19 +00004084 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004085 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004086 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004087 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004088 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004089 fprintf(out," case %d: /* ", rp->index);
4090 writeRuleText(out, rp);
4091 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004092 for(rp2=rp->next; rp2; rp2=rp2->next){
4093 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004094 fprintf(out," case %d: /* ", rp2->index);
4095 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004096 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004097 rp2->code = 0;
4098 }
4099 }
drh75897232000-05-29 14:26:00 +00004100 emit_code(out,rp,lemp,&lineno);
4101 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004102 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004103 }
drhc53eed12009-06-12 17:46:19 +00004104 /* Finally, output the default: rule. We choose as the default: all
4105 ** empty actions. */
4106 fprintf(out," default:\n"); lineno++;
4107 for(rp=lemp->rule; rp; rp=rp->next){
4108 if( rp->code==0 ) continue;
4109 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4110 fprintf(out," /* (%d) ", rp->index);
4111 writeRuleText(out, rp);
4112 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4113 }
4114 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004115 tplt_xfer(lemp->name,in,out,&lineno);
4116
4117 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004118 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004119 tplt_xfer(lemp->name,in,out,&lineno);
4120
4121 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004122 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004123 tplt_xfer(lemp->name,in,out,&lineno);
4124
4125 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004126 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004127 tplt_xfer(lemp->name,in,out,&lineno);
4128
4129 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004130 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004131
4132 fclose(in);
4133 fclose(out);
4134 return;
4135}
4136
4137/* Generate a header file for the parser */
4138void ReportHeader(lemp)
4139struct lemon *lemp;
4140{
4141 FILE *out, *in;
4142 char *prefix;
4143 char line[LINESIZE];
4144 char pattern[LINESIZE];
4145 int i;
4146
4147 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4148 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004149 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004150 if( in ){
4151 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4152 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4153 if( strcmp(line,pattern) ) break;
4154 }
4155 fclose(in);
4156 if( i==lemp->nterminal ){
4157 /* No change in the file. Don't rewrite it. */
4158 return;
4159 }
4160 }
drh2aa6ca42004-09-10 00:14:04 +00004161 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004162 if( out ){
4163 for(i=1; i<lemp->nterminal; i++){
4164 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4165 }
4166 fclose(out);
4167 }
4168 return;
4169}
4170
4171/* Reduce the size of the action tables, if possible, by making use
4172** of defaults.
4173**
drhb59499c2002-02-23 18:45:13 +00004174** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004175** it the default. Except, there is no default if the wildcard token
4176** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004177*/
4178void CompressTables(lemp)
4179struct lemon *lemp;
4180{
4181 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004182 struct action *ap, *ap2;
4183 struct rule *rp, *rp2, *rbest;
4184 int nbest, n;
drh75897232000-05-29 14:26:00 +00004185 int i;
drhe09daa92006-06-10 13:29:31 +00004186 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004187
4188 for(i=0; i<lemp->nstate; i++){
4189 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004190 nbest = 0;
4191 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004192 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004193
drhb59499c2002-02-23 18:45:13 +00004194 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004195 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4196 usesWildcard = 1;
4197 }
drhb59499c2002-02-23 18:45:13 +00004198 if( ap->type!=REDUCE ) continue;
4199 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004200 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004201 if( rp==rbest ) continue;
4202 n = 1;
4203 for(ap2=ap->next; ap2; ap2=ap2->next){
4204 if( ap2->type!=REDUCE ) continue;
4205 rp2 = ap2->x.rp;
4206 if( rp2==rbest ) continue;
4207 if( rp2==rp ) n++;
4208 }
4209 if( n>nbest ){
4210 nbest = n;
4211 rbest = rp;
drh75897232000-05-29 14:26:00 +00004212 }
4213 }
drhb59499c2002-02-23 18:45:13 +00004214
4215 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004216 ** is not at least 1 or if the wildcard token is a possible
4217 ** lookahead.
4218 */
4219 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004220
drhb59499c2002-02-23 18:45:13 +00004221
4222 /* Combine matching REDUCE actions into a single default */
4223 for(ap=stp->ap; ap; ap=ap->next){
4224 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4225 }
drh75897232000-05-29 14:26:00 +00004226 assert( ap );
4227 ap->sp = Symbol_new("{default}");
4228 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004229 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004230 }
4231 stp->ap = Action_sort(stp->ap);
4232 }
4233}
drhb59499c2002-02-23 18:45:13 +00004234
drhada354d2005-11-05 15:03:59 +00004235
4236/*
4237** Compare two states for sorting purposes. The smaller state is the
4238** one with the most non-terminal actions. If they have the same number
4239** of non-terminal actions, then the smaller is the one with the most
4240** token actions.
4241*/
4242static int stateResortCompare(const void *a, const void *b){
4243 const struct state *pA = *(const struct state**)a;
4244 const struct state *pB = *(const struct state**)b;
4245 int n;
4246
4247 n = pB->nNtAct - pA->nNtAct;
4248 if( n==0 ){
4249 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004250 if( n==0 ){
4251 n = pB->statenum - pA->statenum;
4252 }
drhada354d2005-11-05 15:03:59 +00004253 }
drhe594bc32009-11-03 13:02:25 +00004254 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004255 return n;
4256}
4257
4258
4259/*
4260** Renumber and resort states so that states with fewer choices
4261** occur at the end. Except, keep state 0 as the first state.
4262*/
4263void ResortStates(lemp)
4264struct lemon *lemp;
4265{
4266 int i;
4267 struct state *stp;
4268 struct action *ap;
4269
4270 for(i=0; i<lemp->nstate; i++){
4271 stp = lemp->sorted[i];
4272 stp->nTknAct = stp->nNtAct = 0;
4273 stp->iDflt = lemp->nstate + lemp->nrule;
4274 stp->iTknOfst = NO_OFFSET;
4275 stp->iNtOfst = NO_OFFSET;
4276 for(ap=stp->ap; ap; ap=ap->next){
4277 if( compute_action(lemp,ap)>=0 ){
4278 if( ap->sp->index<lemp->nterminal ){
4279 stp->nTknAct++;
4280 }else if( ap->sp->index<lemp->nsymbol ){
4281 stp->nNtAct++;
4282 }else{
4283 stp->iDflt = compute_action(lemp, ap);
4284 }
4285 }
4286 }
4287 }
4288 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4289 stateResortCompare);
4290 for(i=0; i<lemp->nstate; i++){
4291 lemp->sorted[i]->statenum = i;
4292 }
4293}
4294
4295
drh75897232000-05-29 14:26:00 +00004296/***************** From the file "set.c" ************************************/
4297/*
4298** Set manipulation routines for the LEMON parser generator.
4299*/
4300
4301static int size = 0;
4302
4303/* Set the set size */
4304void SetSize(n)
4305int n;
4306{
4307 size = n+1;
4308}
4309
4310/* Allocate a new set */
4311char *SetNew(){
4312 char *s;
drh9892c5d2007-12-21 00:02:11 +00004313 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004314 if( s==0 ){
4315 extern void memory_error();
4316 memory_error();
4317 }
drh75897232000-05-29 14:26:00 +00004318 return s;
4319}
4320
4321/* Deallocate a set */
4322void SetFree(s)
4323char *s;
4324{
4325 free(s);
4326}
4327
4328/* Add a new element to the set. Return TRUE if the element was added
4329** and FALSE if it was already there. */
4330int SetAdd(s,e)
4331char *s;
4332int e;
4333{
4334 int rv;
drh9892c5d2007-12-21 00:02:11 +00004335 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004336 rv = s[e];
4337 s[e] = 1;
4338 return !rv;
4339}
4340
4341/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4342int SetUnion(s1,s2)
4343char *s1;
4344char *s2;
4345{
4346 int i, progress;
4347 progress = 0;
4348 for(i=0; i<size; i++){
4349 if( s2[i]==0 ) continue;
4350 if( s1[i]==0 ){
4351 progress = 1;
4352 s1[i] = 1;
4353 }
4354 }
4355 return progress;
4356}
4357/********************** From the file "table.c" ****************************/
4358/*
4359** All code in this file has been automatically generated
4360** from a specification in the file
4361** "table.q"
4362** by the associative array code building program "aagen".
4363** Do not edit this file! Instead, edit the specification
4364** file, then rerun aagen.
4365*/
4366/*
4367** Code for processing tables in the LEMON parser generator.
4368*/
4369
4370PRIVATE int strhash(x)
4371char *x;
4372{
4373 int h = 0;
4374 while( *x) h = h*13 + *(x++);
4375 return h;
4376}
4377
4378/* Works like strdup, sort of. Save a string in malloced memory, but
4379** keep strings in a table so that the same string is not in more
4380** than one place.
4381*/
4382char *Strsafe(y)
4383char *y;
4384{
4385 char *z;
4386
drh916f75f2006-07-17 00:19:39 +00004387 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004388 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004389 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004390 strcpy(z,y);
4391 Strsafe_insert(z);
4392 }
4393 MemoryCheck(z);
4394 return z;
4395}
4396
4397/* There is one instance of the following structure for each
4398** associative array of type "x1".
4399*/
4400struct s_x1 {
4401 int size; /* The number of available slots. */
4402 /* Must be a power of 2 greater than or */
4403 /* equal to 1 */
4404 int count; /* Number of currently slots filled */
4405 struct s_x1node *tbl; /* The data stored here */
4406 struct s_x1node **ht; /* Hash table for lookups */
4407};
4408
4409/* There is one instance of this structure for every data element
4410** in an associative array of type "x1".
4411*/
4412typedef struct s_x1node {
4413 char *data; /* The data */
4414 struct s_x1node *next; /* Next entry with the same hash */
4415 struct s_x1node **from; /* Previous link */
4416} x1node;
4417
4418/* There is only one instance of the array, which is the following */
4419static struct s_x1 *x1a;
4420
4421/* Allocate a new associative array */
4422void Strsafe_init(){
4423 if( x1a ) return;
4424 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4425 if( x1a ){
4426 x1a->size = 1024;
4427 x1a->count = 0;
4428 x1a->tbl = (x1node*)malloc(
4429 (sizeof(x1node) + sizeof(x1node*))*1024 );
4430 if( x1a->tbl==0 ){
4431 free(x1a);
4432 x1a = 0;
4433 }else{
4434 int i;
4435 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4436 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4437 }
4438 }
4439}
4440/* Insert a new record into the array. Return TRUE if successful.
4441** Prior data with the same key is NOT overwritten */
4442int Strsafe_insert(data)
4443char *data;
4444{
4445 x1node *np;
4446 int h;
4447 int ph;
4448
4449 if( x1a==0 ) return 0;
4450 ph = strhash(data);
4451 h = ph & (x1a->size-1);
4452 np = x1a->ht[h];
4453 while( np ){
4454 if( strcmp(np->data,data)==0 ){
4455 /* An existing entry with the same key is found. */
4456 /* Fail because overwrite is not allows. */
4457 return 0;
4458 }
4459 np = np->next;
4460 }
4461 if( x1a->count>=x1a->size ){
4462 /* Need to make the hash table bigger */
4463 int i,size;
4464 struct s_x1 array;
4465 array.size = size = x1a->size*2;
4466 array.count = x1a->count;
4467 array.tbl = (x1node*)malloc(
4468 (sizeof(x1node) + sizeof(x1node*))*size );
4469 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4470 array.ht = (x1node**)&(array.tbl[size]);
4471 for(i=0; i<size; i++) array.ht[i] = 0;
4472 for(i=0; i<x1a->count; i++){
4473 x1node *oldnp, *newnp;
4474 oldnp = &(x1a->tbl[i]);
4475 h = strhash(oldnp->data) & (size-1);
4476 newnp = &(array.tbl[i]);
4477 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4478 newnp->next = array.ht[h];
4479 newnp->data = oldnp->data;
4480 newnp->from = &(array.ht[h]);
4481 array.ht[h] = newnp;
4482 }
4483 free(x1a->tbl);
4484 *x1a = array;
4485 }
4486 /* Insert the new data */
4487 h = ph & (x1a->size-1);
4488 np = &(x1a->tbl[x1a->count++]);
4489 np->data = data;
4490 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4491 np->next = x1a->ht[h];
4492 x1a->ht[h] = np;
4493 np->from = &(x1a->ht[h]);
4494 return 1;
4495}
4496
4497/* Return a pointer to data assigned to the given key. Return NULL
4498** if no such key. */
4499char *Strsafe_find(key)
4500char *key;
4501{
4502 int h;
4503 x1node *np;
4504
4505 if( x1a==0 ) return 0;
4506 h = strhash(key) & (x1a->size-1);
4507 np = x1a->ht[h];
4508 while( np ){
4509 if( strcmp(np->data,key)==0 ) break;
4510 np = np->next;
4511 }
4512 return np ? np->data : 0;
4513}
4514
4515/* Return a pointer to the (terminal or nonterminal) symbol "x".
4516** Create a new symbol if this is the first time "x" has been seen.
4517*/
4518struct symbol *Symbol_new(x)
4519char *x;
4520{
4521 struct symbol *sp;
4522
4523 sp = Symbol_find(x);
4524 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004525 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004526 MemoryCheck(sp);
4527 sp->name = Strsafe(x);
4528 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4529 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004530 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004531 sp->prec = -1;
4532 sp->assoc = UNK;
4533 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004534 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004535 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004536 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004537 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004538 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004539 Symbol_insert(sp,sp->name);
4540 }
drhc4dd3fd2008-01-22 01:48:05 +00004541 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004542 return sp;
4543}
4544
drh60d31652004-02-22 00:08:04 +00004545/* Compare two symbols for working purposes
4546**
4547** Symbols that begin with upper case letters (terminals or tokens)
4548** must sort before symbols that begin with lower case letters
4549** (non-terminals). Other than that, the order does not matter.
4550**
4551** We find experimentally that leaving the symbols in their original
4552** order (the order they appeared in the grammar file) gives the
4553** smallest parser tables in SQLite.
4554*/
4555int Symbolcmpp(struct symbol **a, struct symbol **b){
4556 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4557 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004558 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004559 return i1-i2;
drh75897232000-05-29 14:26:00 +00004560}
4561
4562/* There is one instance of the following structure for each
4563** associative array of type "x2".
4564*/
4565struct s_x2 {
4566 int size; /* The number of available slots. */
4567 /* Must be a power of 2 greater than or */
4568 /* equal to 1 */
4569 int count; /* Number of currently slots filled */
4570 struct s_x2node *tbl; /* The data stored here */
4571 struct s_x2node **ht; /* Hash table for lookups */
4572};
4573
4574/* There is one instance of this structure for every data element
4575** in an associative array of type "x2".
4576*/
4577typedef struct s_x2node {
4578 struct symbol *data; /* The data */
4579 char *key; /* The key */
4580 struct s_x2node *next; /* Next entry with the same hash */
4581 struct s_x2node **from; /* Previous link */
4582} x2node;
4583
4584/* There is only one instance of the array, which is the following */
4585static struct s_x2 *x2a;
4586
4587/* Allocate a new associative array */
4588void Symbol_init(){
4589 if( x2a ) return;
4590 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4591 if( x2a ){
4592 x2a->size = 128;
4593 x2a->count = 0;
4594 x2a->tbl = (x2node*)malloc(
4595 (sizeof(x2node) + sizeof(x2node*))*128 );
4596 if( x2a->tbl==0 ){
4597 free(x2a);
4598 x2a = 0;
4599 }else{
4600 int i;
4601 x2a->ht = (x2node**)&(x2a->tbl[128]);
4602 for(i=0; i<128; i++) x2a->ht[i] = 0;
4603 }
4604 }
4605}
4606/* Insert a new record into the array. Return TRUE if successful.
4607** Prior data with the same key is NOT overwritten */
4608int Symbol_insert(data,key)
4609struct symbol *data;
4610char *key;
4611{
4612 x2node *np;
4613 int h;
4614 int ph;
4615
4616 if( x2a==0 ) return 0;
4617 ph = strhash(key);
4618 h = ph & (x2a->size-1);
4619 np = x2a->ht[h];
4620 while( np ){
4621 if( strcmp(np->key,key)==0 ){
4622 /* An existing entry with the same key is found. */
4623 /* Fail because overwrite is not allows. */
4624 return 0;
4625 }
4626 np = np->next;
4627 }
4628 if( x2a->count>=x2a->size ){
4629 /* Need to make the hash table bigger */
4630 int i,size;
4631 struct s_x2 array;
4632 array.size = size = x2a->size*2;
4633 array.count = x2a->count;
4634 array.tbl = (x2node*)malloc(
4635 (sizeof(x2node) + sizeof(x2node*))*size );
4636 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4637 array.ht = (x2node**)&(array.tbl[size]);
4638 for(i=0; i<size; i++) array.ht[i] = 0;
4639 for(i=0; i<x2a->count; i++){
4640 x2node *oldnp, *newnp;
4641 oldnp = &(x2a->tbl[i]);
4642 h = strhash(oldnp->key) & (size-1);
4643 newnp = &(array.tbl[i]);
4644 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4645 newnp->next = array.ht[h];
4646 newnp->key = oldnp->key;
4647 newnp->data = oldnp->data;
4648 newnp->from = &(array.ht[h]);
4649 array.ht[h] = newnp;
4650 }
4651 free(x2a->tbl);
4652 *x2a = array;
4653 }
4654 /* Insert the new data */
4655 h = ph & (x2a->size-1);
4656 np = &(x2a->tbl[x2a->count++]);
4657 np->key = key;
4658 np->data = data;
4659 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4660 np->next = x2a->ht[h];
4661 x2a->ht[h] = np;
4662 np->from = &(x2a->ht[h]);
4663 return 1;
4664}
4665
4666/* Return a pointer to data assigned to the given key. Return NULL
4667** if no such key. */
4668struct symbol *Symbol_find(key)
4669char *key;
4670{
4671 int h;
4672 x2node *np;
4673
4674 if( x2a==0 ) return 0;
4675 h = strhash(key) & (x2a->size-1);
4676 np = x2a->ht[h];
4677 while( np ){
4678 if( strcmp(np->key,key)==0 ) break;
4679 np = np->next;
4680 }
4681 return np ? np->data : 0;
4682}
4683
4684/* Return the n-th data. Return NULL if n is out of range. */
4685struct symbol *Symbol_Nth(n)
4686int n;
4687{
4688 struct symbol *data;
4689 if( x2a && n>0 && n<=x2a->count ){
4690 data = x2a->tbl[n-1].data;
4691 }else{
4692 data = 0;
4693 }
4694 return data;
4695}
4696
4697/* Return the size of the array */
4698int Symbol_count()
4699{
4700 return x2a ? x2a->count : 0;
4701}
4702
4703/* Return an array of pointers to all data in the table.
4704** The array is obtained from malloc. Return NULL if memory allocation
4705** problems, or if the array is empty. */
4706struct symbol **Symbol_arrayof()
4707{
4708 struct symbol **array;
4709 int i,size;
4710 if( x2a==0 ) return 0;
4711 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004712 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004713 if( array ){
4714 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4715 }
4716 return array;
4717}
4718
4719/* Compare two configurations */
4720int Configcmp(a,b)
4721struct config *a;
4722struct config *b;
4723{
4724 int x;
4725 x = a->rp->index - b->rp->index;
4726 if( x==0 ) x = a->dot - b->dot;
4727 return x;
4728}
4729
4730/* Compare two states */
4731PRIVATE int statecmp(a,b)
4732struct config *a;
4733struct config *b;
4734{
4735 int rc;
4736 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4737 rc = a->rp->index - b->rp->index;
4738 if( rc==0 ) rc = a->dot - b->dot;
4739 }
4740 if( rc==0 ){
4741 if( a ) rc = 1;
4742 if( b ) rc = -1;
4743 }
4744 return rc;
4745}
4746
4747/* Hash a state */
4748PRIVATE int statehash(a)
4749struct config *a;
4750{
4751 int h=0;
4752 while( a ){
4753 h = h*571 + a->rp->index*37 + a->dot;
4754 a = a->bp;
4755 }
4756 return h;
4757}
4758
4759/* Allocate a new state structure */
4760struct state *State_new()
4761{
4762 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004763 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004764 MemoryCheck(new);
4765 return new;
4766}
4767
4768/* There is one instance of the following structure for each
4769** associative array of type "x3".
4770*/
4771struct s_x3 {
4772 int size; /* The number of available slots. */
4773 /* Must be a power of 2 greater than or */
4774 /* equal to 1 */
4775 int count; /* Number of currently slots filled */
4776 struct s_x3node *tbl; /* The data stored here */
4777 struct s_x3node **ht; /* Hash table for lookups */
4778};
4779
4780/* There is one instance of this structure for every data element
4781** in an associative array of type "x3".
4782*/
4783typedef struct s_x3node {
4784 struct state *data; /* The data */
4785 struct config *key; /* The key */
4786 struct s_x3node *next; /* Next entry with the same hash */
4787 struct s_x3node **from; /* Previous link */
4788} x3node;
4789
4790/* There is only one instance of the array, which is the following */
4791static struct s_x3 *x3a;
4792
4793/* Allocate a new associative array */
4794void State_init(){
4795 if( x3a ) return;
4796 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4797 if( x3a ){
4798 x3a->size = 128;
4799 x3a->count = 0;
4800 x3a->tbl = (x3node*)malloc(
4801 (sizeof(x3node) + sizeof(x3node*))*128 );
4802 if( x3a->tbl==0 ){
4803 free(x3a);
4804 x3a = 0;
4805 }else{
4806 int i;
4807 x3a->ht = (x3node**)&(x3a->tbl[128]);
4808 for(i=0; i<128; i++) x3a->ht[i] = 0;
4809 }
4810 }
4811}
4812/* Insert a new record into the array. Return TRUE if successful.
4813** Prior data with the same key is NOT overwritten */
4814int State_insert(data,key)
4815struct state *data;
4816struct config *key;
4817{
4818 x3node *np;
4819 int h;
4820 int ph;
4821
4822 if( x3a==0 ) return 0;
4823 ph = statehash(key);
4824 h = ph & (x3a->size-1);
4825 np = x3a->ht[h];
4826 while( np ){
4827 if( statecmp(np->key,key)==0 ){
4828 /* An existing entry with the same key is found. */
4829 /* Fail because overwrite is not allows. */
4830 return 0;
4831 }
4832 np = np->next;
4833 }
4834 if( x3a->count>=x3a->size ){
4835 /* Need to make the hash table bigger */
4836 int i,size;
4837 struct s_x3 array;
4838 array.size = size = x3a->size*2;
4839 array.count = x3a->count;
4840 array.tbl = (x3node*)malloc(
4841 (sizeof(x3node) + sizeof(x3node*))*size );
4842 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4843 array.ht = (x3node**)&(array.tbl[size]);
4844 for(i=0; i<size; i++) array.ht[i] = 0;
4845 for(i=0; i<x3a->count; i++){
4846 x3node *oldnp, *newnp;
4847 oldnp = &(x3a->tbl[i]);
4848 h = statehash(oldnp->key) & (size-1);
4849 newnp = &(array.tbl[i]);
4850 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4851 newnp->next = array.ht[h];
4852 newnp->key = oldnp->key;
4853 newnp->data = oldnp->data;
4854 newnp->from = &(array.ht[h]);
4855 array.ht[h] = newnp;
4856 }
4857 free(x3a->tbl);
4858 *x3a = array;
4859 }
4860 /* Insert the new data */
4861 h = ph & (x3a->size-1);
4862 np = &(x3a->tbl[x3a->count++]);
4863 np->key = key;
4864 np->data = data;
4865 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4866 np->next = x3a->ht[h];
4867 x3a->ht[h] = np;
4868 np->from = &(x3a->ht[h]);
4869 return 1;
4870}
4871
4872/* Return a pointer to data assigned to the given key. Return NULL
4873** if no such key. */
4874struct state *State_find(key)
4875struct config *key;
4876{
4877 int h;
4878 x3node *np;
4879
4880 if( x3a==0 ) return 0;
4881 h = statehash(key) & (x3a->size-1);
4882 np = x3a->ht[h];
4883 while( np ){
4884 if( statecmp(np->key,key)==0 ) break;
4885 np = np->next;
4886 }
4887 return np ? np->data : 0;
4888}
4889
4890/* Return an array of pointers to all data in the table.
4891** The array is obtained from malloc. Return NULL if memory allocation
4892** problems, or if the array is empty. */
4893struct state **State_arrayof()
4894{
4895 struct state **array;
4896 int i,size;
4897 if( x3a==0 ) return 0;
4898 size = x3a->count;
4899 array = (struct state **)malloc( sizeof(struct state *)*size );
4900 if( array ){
4901 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4902 }
4903 return array;
4904}
4905
4906/* Hash a configuration */
4907PRIVATE int confighash(a)
4908struct config *a;
4909{
4910 int h=0;
4911 h = h*571 + a->rp->index*37 + a->dot;
4912 return h;
4913}
4914
4915/* There is one instance of the following structure for each
4916** associative array of type "x4".
4917*/
4918struct s_x4 {
4919 int size; /* The number of available slots. */
4920 /* Must be a power of 2 greater than or */
4921 /* equal to 1 */
4922 int count; /* Number of currently slots filled */
4923 struct s_x4node *tbl; /* The data stored here */
4924 struct s_x4node **ht; /* Hash table for lookups */
4925};
4926
4927/* There is one instance of this structure for every data element
4928** in an associative array of type "x4".
4929*/
4930typedef struct s_x4node {
4931 struct config *data; /* The data */
4932 struct s_x4node *next; /* Next entry with the same hash */
4933 struct s_x4node **from; /* Previous link */
4934} x4node;
4935
4936/* There is only one instance of the array, which is the following */
4937static struct s_x4 *x4a;
4938
4939/* Allocate a new associative array */
4940void Configtable_init(){
4941 if( x4a ) return;
4942 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4943 if( x4a ){
4944 x4a->size = 64;
4945 x4a->count = 0;
4946 x4a->tbl = (x4node*)malloc(
4947 (sizeof(x4node) + sizeof(x4node*))*64 );
4948 if( x4a->tbl==0 ){
4949 free(x4a);
4950 x4a = 0;
4951 }else{
4952 int i;
4953 x4a->ht = (x4node**)&(x4a->tbl[64]);
4954 for(i=0; i<64; i++) x4a->ht[i] = 0;
4955 }
4956 }
4957}
4958/* Insert a new record into the array. Return TRUE if successful.
4959** Prior data with the same key is NOT overwritten */
4960int Configtable_insert(data)
4961struct config *data;
4962{
4963 x4node *np;
4964 int h;
4965 int ph;
4966
4967 if( x4a==0 ) return 0;
4968 ph = confighash(data);
4969 h = ph & (x4a->size-1);
4970 np = x4a->ht[h];
4971 while( np ){
4972 if( Configcmp(np->data,data)==0 ){
4973 /* An existing entry with the same key is found. */
4974 /* Fail because overwrite is not allows. */
4975 return 0;
4976 }
4977 np = np->next;
4978 }
4979 if( x4a->count>=x4a->size ){
4980 /* Need to make the hash table bigger */
4981 int i,size;
4982 struct s_x4 array;
4983 array.size = size = x4a->size*2;
4984 array.count = x4a->count;
4985 array.tbl = (x4node*)malloc(
4986 (sizeof(x4node) + sizeof(x4node*))*size );
4987 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4988 array.ht = (x4node**)&(array.tbl[size]);
4989 for(i=0; i<size; i++) array.ht[i] = 0;
4990 for(i=0; i<x4a->count; i++){
4991 x4node *oldnp, *newnp;
4992 oldnp = &(x4a->tbl[i]);
4993 h = confighash(oldnp->data) & (size-1);
4994 newnp = &(array.tbl[i]);
4995 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4996 newnp->next = array.ht[h];
4997 newnp->data = oldnp->data;
4998 newnp->from = &(array.ht[h]);
4999 array.ht[h] = newnp;
5000 }
5001 free(x4a->tbl);
5002 *x4a = array;
5003 }
5004 /* Insert the new data */
5005 h = ph & (x4a->size-1);
5006 np = &(x4a->tbl[x4a->count++]);
5007 np->data = data;
5008 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5009 np->next = x4a->ht[h];
5010 x4a->ht[h] = np;
5011 np->from = &(x4a->ht[h]);
5012 return 1;
5013}
5014
5015/* Return a pointer to data assigned to the given key. Return NULL
5016** if no such key. */
5017struct config *Configtable_find(key)
5018struct config *key;
5019{
5020 int h;
5021 x4node *np;
5022
5023 if( x4a==0 ) return 0;
5024 h = confighash(key) & (x4a->size-1);
5025 np = x4a->ht[h];
5026 while( np ){
5027 if( Configcmp(np->data,key)==0 ) break;
5028 np = np->next;
5029 }
5030 return np ? np->data : 0;
5031}
5032
5033/* Remove all data from the table. Pass each data to the function "f"
5034** as it is removed. ("f" may be null to avoid this step.) */
5035void Configtable_clear(f)
5036int(*f)(/* struct config * */);
5037{
5038 int i;
5039 if( x4a==0 || x4a->count==0 ) return;
5040 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5041 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5042 x4a->count = 0;
5043 return;
5044}