blob: 5c96a67324e78f88a072b1efc5a4d5f6451b490b [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 */
icculusd1912822010-02-14 05:42:46 +00001375static int noerrorclipping = 0;
drhf9a2e7b2003-04-15 01:49:48 +00001376void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001377 char errmsg[ERRMSGSIZE];
1378 char prefix[PREFIXLIMIT+10];
1379 int errmsgsize;
1380 int prefixsize;
1381 int availablewidth;
1382 va_list ap;
1383 int end, restart, base;
1384
icculusd1912822010-02-14 05:42:46 +00001385 if( noerrorclipping ) {
1386 fprintf(stderr, "%s:%d: ", filename, lineno);
1387 va_start(ap, format);
1388 vfprintf(stderr,format,ap);
1389 va_end(ap);
1390 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001391 }else{
icculusd1912822010-02-14 05:42:46 +00001392 va_start(ap, format);
1393 /* Prepare a prefix to be prepended to every output line */
1394 if( lineno>0 ){
1395 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1396 }else{
1397 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1398 }
1399 prefixsize = lemonStrlen(prefix);
1400 availablewidth = LINEWIDTH - prefixsize;
drh75897232000-05-29 14:26:00 +00001401
icculusd1912822010-02-14 05:42:46 +00001402 /* Generate the error message */
1403 vsprintf(errmsg,format,ap);
1404 va_end(ap);
1405 errmsgsize = lemonStrlen(errmsg);
1406 /* Remove trailing '\n's from the error message. */
1407 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1408 errmsg[--errmsgsize] = 0;
1409 }
drh75897232000-05-29 14:26:00 +00001410
icculusd1912822010-02-14 05:42:46 +00001411 /* Print the error message */
1412 base = 0;
1413 while( errmsg[base]!=0 ){
1414 end = restart = findbreak(&errmsg[base],0,availablewidth);
1415 restart += base;
1416 while( errmsg[restart]==' ' ) restart++;
1417 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1418 base = restart;
1419 }
drh75897232000-05-29 14:26:00 +00001420 }
1421}
1422/**************** From the file "main.c" ************************************/
1423/*
1424** Main program file for the LEMON parser generator.
1425*/
1426
1427/* Report an out-of-memory condition and abort. This function
1428** is used mostly by the "MemoryCheck" macro in struct.h
1429*/
1430void memory_error(){
1431 fprintf(stderr,"Out of memory. Aborting...\n");
1432 exit(1);
1433}
1434
drh6d08b4d2004-07-20 12:45:22 +00001435static int nDefine = 0; /* Number of -D options on the command line */
1436static char **azDefine = 0; /* Name of the -D macros */
1437
1438/* This routine is called with the argument to each -D command-line option.
1439** Add the macro defined to the azDefine array.
1440*/
1441static void handle_D_option(char *z){
1442 char **paz;
1443 nDefine++;
1444 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1445 if( azDefine==0 ){
1446 fprintf(stderr,"out of memory\n");
1447 exit(1);
1448 }
1449 paz = &azDefine[nDefine-1];
drh87cf1372008-08-13 20:09:06 +00001450 *paz = malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001451 if( *paz==0 ){
1452 fprintf(stderr,"out of memory\n");
1453 exit(1);
1454 }
1455 strcpy(*paz, z);
1456 for(z=*paz; *z && *z!='='; z++){}
1457 *z = 0;
1458}
1459
icculus3e143bd2010-02-14 00:48:49 +00001460static char *user_templatename = NULL;
1461static void handle_T_option(char *z){
1462 user_templatename = malloc( lemonStrlen(z)+1 );
1463 if( user_templatename==0 ){
1464 memory_error();
1465 }
1466 strcpy(user_templatename, z);
1467}
drh75897232000-05-29 14:26:00 +00001468
1469/* The main program. Parse the command line and do it... */
1470int main(argc,argv)
1471int argc;
1472char **argv;
1473{
1474 static int version = 0;
1475 static int rpflag = 0;
1476 static int basisflag = 0;
1477 static int compress = 0;
1478 static int quiet = 0;
1479 static int statistics = 0;
1480 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001481 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001482 static struct s_options options[] = {
1483 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
icculusd1912822010-02-14 05:42:46 +00001484 {OPT_FLAG, "e", (char*)&noerrorclipping, "Don't clip error output."},
drh75897232000-05-29 14:26:00 +00001485 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001486 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001487 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001488 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001489 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1490 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001491 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001492 {OPT_FLAG, "s", (char*)&statistics,
1493 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001494 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1495 {OPT_FLAG,0,0,0}
1496 };
1497 int i;
icculus42585cf2010-02-14 05:19:56 +00001498 int exitcode;
drh75897232000-05-29 14:26:00 +00001499 struct lemon lem;
1500
icculusf5ad8242010-02-14 05:34:42 +00001501 atexit(LemonAtExit);
1502
drhb0c86772000-06-02 23:21:26 +00001503 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001504 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001505 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001506 exit(0);
1507 }
drhb0c86772000-06-02 23:21:26 +00001508 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001509 fprintf(stderr,"Exactly one filename argument is required.\n");
1510 exit(1);
1511 }
drh954f6b42006-06-13 13:27:46 +00001512 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001513 lem.errorcnt = 0;
icculus42585cf2010-02-14 05:19:56 +00001514 lem.nexpected = -1;
drh75897232000-05-29 14:26:00 +00001515
1516 /* Initialize the machine */
1517 Strsafe_init();
1518 Symbol_init();
1519 State_init();
1520 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001521 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001522 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001523 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001524 Symbol_new("$");
1525 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001526 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001527
1528 /* Parse the input file */
1529 Parse(&lem);
1530 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001531 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001532 fprintf(stderr,"Empty grammar.\n");
1533 exit(1);
1534 }
1535
1536 /* Count and index the symbols of the grammar */
1537 lem.nsymbol = Symbol_count();
1538 Symbol_new("{default}");
1539 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001540 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001541 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1542 (int(*)())Symbolcmpp);
1543 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1544 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1545 lem.nterminal = i;
1546
1547 /* Generate a reprint of the grammar, if requested on the command line */
1548 if( rpflag ){
1549 Reprint(&lem);
1550 }else{
1551 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001552 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001553
1554 /* Find the precedence for every production rule (that has one) */
1555 FindRulePrecedences(&lem);
1556
1557 /* Compute the lambda-nonterminals and the first-sets for every
1558 ** nonterminal */
1559 FindFirstSets(&lem);
1560
1561 /* Compute all LR(0) states. Also record follow-set propagation
1562 ** links so that the follow-set can be computed later */
1563 lem.nstate = 0;
1564 FindStates(&lem);
1565 lem.sorted = State_arrayof();
1566
1567 /* Tie up loose ends on the propagation links */
1568 FindLinks(&lem);
1569
1570 /* Compute the follow set of every reducible configuration */
1571 FindFollowSets(&lem);
1572
1573 /* Compute the action tables */
1574 FindActions(&lem);
1575
1576 /* Compress the action tables */
1577 if( compress==0 ) CompressTables(&lem);
1578
drhada354d2005-11-05 15:03:59 +00001579 /* Reorder and renumber the states so that states with fewer choices
1580 ** occur at the end. */
1581 ResortStates(&lem);
1582
drh75897232000-05-29 14:26:00 +00001583 /* Generate a report of the parser generated. (the "y.output" file) */
1584 if( !quiet ) ReportOutput(&lem);
1585
1586 /* Generate the source code for the parser */
1587 ReportTable(&lem, mhflag);
1588
1589 /* Produce a header file for use by the scanner. (This step is
1590 ** omitted if the "-m" option is used because makeheaders will
1591 ** generate the file for us.) */
1592 if( !mhflag ) ReportHeader(&lem);
1593 }
1594 if( statistics ){
1595 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1596 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1597 printf(" %d states, %d parser table entries, %d conflicts\n",
1598 lem.nstate, lem.tablesize, lem.nconflict);
1599 }
icculus42585cf2010-02-14 05:19:56 +00001600 if( lem.nexpected < 0 ) {
1601 lem.nexpected = 0; /* grammar didn't have an %expect declaration. */
drh75897232000-05-29 14:26:00 +00001602 }
icculus42585cf2010-02-14 05:19:56 +00001603 if( lem.nconflict != lem.nexpected ){
1604 fprintf(stderr,"%d parsing conflicts (%d expected).\n",lem.nconflict,lem.nexpected);
1605 }
1606
1607 /* return 0 on success, 1 on failure. */
1608 exitcode = ((lem.errorcnt > 0) || (lem.nconflict != lem.nexpected)) ? 1 : 0;
icculusf5ad8242010-02-14 05:34:42 +00001609 successful_exit = (exitcode == 0);
icculus42585cf2010-02-14 05:19:56 +00001610 exit(exitcode);
1611 return (exitcode);
drh75897232000-05-29 14:26:00 +00001612}
1613/******************** From the file "msort.c" *******************************/
1614/*
1615** A generic merge-sort program.
1616**
1617** USAGE:
1618** Let "ptr" be a pointer to some structure which is at the head of
1619** a null-terminated list. Then to sort the list call:
1620**
1621** ptr = msort(ptr,&(ptr->next),cmpfnc);
1622**
1623** In the above, "cmpfnc" is a pointer to a function which compares
1624** two instances of the structure and returns an integer, as in
1625** strcmp. The second argument is a pointer to the pointer to the
1626** second element of the linked list. This address is used to compute
1627** the offset to the "next" field within the structure. The offset to
1628** the "next" field must be constant for all structures in the list.
1629**
1630** The function returns a new pointer which is the head of the list
1631** after sorting.
1632**
1633** ALGORITHM:
1634** Merge-sort.
1635*/
1636
1637/*
1638** Return a pointer to the next structure in the linked list.
1639*/
drhba99af52001-10-25 20:37:16 +00001640#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001641
1642/*
1643** Inputs:
1644** a: A sorted, null-terminated linked list. (May be null).
1645** b: A sorted, null-terminated linked list. (May be null).
1646** cmp: A pointer to the comparison function.
1647** offset: Offset in the structure to the "next" field.
1648**
1649** Return Value:
1650** A pointer to the head of a sorted list containing the elements
1651** of both a and b.
1652**
1653** Side effects:
1654** The "next" pointers for elements in the lists a and b are
1655** changed.
1656*/
drhe9278182007-07-18 18:16:29 +00001657static char *merge(
1658 char *a,
1659 char *b,
1660 int (*cmp)(const char*,const char*),
1661 int offset
1662){
drh75897232000-05-29 14:26:00 +00001663 char *ptr, *head;
1664
1665 if( a==0 ){
1666 head = b;
1667 }else if( b==0 ){
1668 head = a;
1669 }else{
drhe594bc32009-11-03 13:02:25 +00001670 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001671 ptr = a;
1672 a = NEXT(a);
1673 }else{
1674 ptr = b;
1675 b = NEXT(b);
1676 }
1677 head = ptr;
1678 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001679 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001680 NEXT(ptr) = a;
1681 ptr = a;
1682 a = NEXT(a);
1683 }else{
1684 NEXT(ptr) = b;
1685 ptr = b;
1686 b = NEXT(b);
1687 }
1688 }
1689 if( a ) NEXT(ptr) = a;
1690 else NEXT(ptr) = b;
1691 }
1692 return head;
1693}
1694
1695/*
1696** Inputs:
1697** list: Pointer to a singly-linked list of structures.
1698** next: Pointer to pointer to the second element of the list.
1699** cmp: A comparison function.
1700**
1701** Return Value:
1702** A pointer to the head of a sorted list containing the elements
1703** orginally in list.
1704**
1705** Side effects:
1706** The "next" pointers for elements in list are changed.
1707*/
1708#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001709static char *msort(
1710 char *list,
1711 char **next,
1712 int (*cmp)(const char*,const char*)
1713){
drhba99af52001-10-25 20:37:16 +00001714 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001715 char *ep;
1716 char *set[LISTSIZE];
1717 int i;
drhba99af52001-10-25 20:37:16 +00001718 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001719 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1720 while( list ){
1721 ep = list;
1722 list = NEXT(list);
1723 NEXT(ep) = 0;
1724 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1725 ep = merge(ep,set[i],cmp,offset);
1726 set[i] = 0;
1727 }
1728 set[i] = ep;
1729 }
1730 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001731 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001732 return ep;
1733}
1734/************************ From the file "option.c" **************************/
1735static char **argv;
1736static struct s_options *op;
1737static FILE *errstream;
1738
1739#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1740
1741/*
1742** Print the command line with a carrot pointing to the k-th character
1743** of the n-th field.
1744*/
1745static void errline(n,k,err)
1746int n;
1747int k;
1748FILE *err;
1749{
1750 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001751 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001752 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001753 for(i=1; i<n && argv[i]; i++){
1754 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001755 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001756 }
1757 spcnt += k;
1758 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1759 if( spcnt<20 ){
1760 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1761 }else{
1762 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1763 }
1764}
1765
1766/*
1767** Return the index of the N-th non-switch argument. Return -1
1768** if N is out of range.
1769*/
1770static int argindex(n)
1771int n;
1772{
1773 int i;
1774 int dashdash = 0;
1775 if( argv!=0 && *argv!=0 ){
1776 for(i=1; argv[i]; i++){
1777 if( dashdash || !ISOPT(argv[i]) ){
1778 if( n==0 ) return i;
1779 n--;
1780 }
1781 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1782 }
1783 }
1784 return -1;
1785}
1786
1787static char emsg[] = "Command line syntax error: ";
1788
1789/*
1790** Process a flag command line argument.
1791*/
1792static int handleflags(i,err)
1793int i;
1794FILE *err;
1795{
1796 int v;
1797 int errcnt = 0;
1798 int j;
1799 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001800 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001801 }
1802 v = argv[i][0]=='-' ? 1 : 0;
1803 if( op[j].label==0 ){
1804 if( err ){
1805 fprintf(err,"%sundefined option.\n",emsg);
1806 errline(i,1,err);
1807 }
1808 errcnt++;
1809 }else if( op[j].type==OPT_FLAG ){
1810 *((int*)op[j].arg) = v;
1811 }else if( op[j].type==OPT_FFLAG ){
1812 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001813 }else if( op[j].type==OPT_FSTR ){
1814 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001815 }else{
1816 if( err ){
1817 fprintf(err,"%smissing argument on switch.\n",emsg);
1818 errline(i,1,err);
1819 }
1820 errcnt++;
1821 }
1822 return errcnt;
1823}
1824
1825/*
1826** Process a command line switch which has an argument.
1827*/
1828static int handleswitch(i,err)
1829int i;
1830FILE *err;
1831{
1832 int lv = 0;
1833 double dv = 0.0;
1834 char *sv = 0, *end;
1835 char *cp;
1836 int j;
1837 int errcnt = 0;
1838 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001839 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001840 *cp = 0;
1841 for(j=0; op[j].label; j++){
1842 if( strcmp(argv[i],op[j].label)==0 ) break;
1843 }
1844 *cp = '=';
1845 if( op[j].label==0 ){
1846 if( err ){
1847 fprintf(err,"%sundefined option.\n",emsg);
1848 errline(i,0,err);
1849 }
1850 errcnt++;
1851 }else{
1852 cp++;
1853 switch( op[j].type ){
1854 case OPT_FLAG:
1855 case OPT_FFLAG:
1856 if( err ){
1857 fprintf(err,"%soption requires an argument.\n",emsg);
1858 errline(i,0,err);
1859 }
1860 errcnt++;
1861 break;
1862 case OPT_DBL:
1863 case OPT_FDBL:
1864 dv = strtod(cp,&end);
1865 if( *end ){
1866 if( err ){
1867 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001868 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001869 }
1870 errcnt++;
1871 }
1872 break;
1873 case OPT_INT:
1874 case OPT_FINT:
1875 lv = strtol(cp,&end,0);
1876 if( *end ){
1877 if( err ){
1878 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001879 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001880 }
1881 errcnt++;
1882 }
1883 break;
1884 case OPT_STR:
1885 case OPT_FSTR:
1886 sv = cp;
1887 break;
1888 }
1889 switch( op[j].type ){
1890 case OPT_FLAG:
1891 case OPT_FFLAG:
1892 break;
1893 case OPT_DBL:
1894 *(double*)(op[j].arg) = dv;
1895 break;
1896 case OPT_FDBL:
1897 (*(void(*)())(op[j].arg))(dv);
1898 break;
1899 case OPT_INT:
1900 *(int*)(op[j].arg) = lv;
1901 break;
1902 case OPT_FINT:
1903 (*(void(*)())(op[j].arg))((int)lv);
1904 break;
1905 case OPT_STR:
1906 *(char**)(op[j].arg) = sv;
1907 break;
1908 case OPT_FSTR:
1909 (*(void(*)())(op[j].arg))(sv);
1910 break;
1911 }
1912 }
1913 return errcnt;
1914}
1915
drhb0c86772000-06-02 23:21:26 +00001916int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001917char **a;
1918struct s_options *o;
1919FILE *err;
1920{
1921 int errcnt = 0;
1922 argv = a;
1923 op = o;
1924 errstream = err;
1925 if( argv && *argv && op ){
1926 int i;
1927 for(i=1; argv[i]; i++){
1928 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1929 errcnt += handleflags(i,err);
1930 }else if( strchr(argv[i],'=') ){
1931 errcnt += handleswitch(i,err);
1932 }
1933 }
1934 }
1935 if( errcnt>0 ){
1936 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001937 OptPrint();
drh75897232000-05-29 14:26:00 +00001938 exit(1);
1939 }
1940 return 0;
1941}
1942
drhb0c86772000-06-02 23:21:26 +00001943int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001944 int cnt = 0;
1945 int dashdash = 0;
1946 int i;
1947 if( argv!=0 && argv[0]!=0 ){
1948 for(i=1; argv[i]; i++){
1949 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1950 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1951 }
1952 }
1953 return cnt;
1954}
1955
drhb0c86772000-06-02 23:21:26 +00001956char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001957int n;
1958{
1959 int i;
1960 i = argindex(n);
1961 return i>=0 ? argv[i] : 0;
1962}
1963
drhb0c86772000-06-02 23:21:26 +00001964void OptErr(n)
drh75897232000-05-29 14:26:00 +00001965int n;
1966{
1967 int i;
1968 i = argindex(n);
1969 if( i>=0 ) errline(i,0,errstream);
1970}
1971
drhb0c86772000-06-02 23:21:26 +00001972void OptPrint(){
drh75897232000-05-29 14:26:00 +00001973 int i;
1974 int max, len;
1975 max = 0;
1976 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001977 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001978 switch( op[i].type ){
1979 case OPT_FLAG:
1980 case OPT_FFLAG:
1981 break;
1982 case OPT_INT:
1983 case OPT_FINT:
1984 len += 9; /* length of "<integer>" */
1985 break;
1986 case OPT_DBL:
1987 case OPT_FDBL:
1988 len += 6; /* length of "<real>" */
1989 break;
1990 case OPT_STR:
1991 case OPT_FSTR:
1992 len += 8; /* length of "<string>" */
1993 break;
1994 }
1995 if( len>max ) max = len;
1996 }
1997 for(i=0; op[i].label; i++){
1998 switch( op[i].type ){
1999 case OPT_FLAG:
2000 case OPT_FFLAG:
2001 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2002 break;
2003 case OPT_INT:
2004 case OPT_FINT:
2005 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002006 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002007 break;
2008 case OPT_DBL:
2009 case OPT_FDBL:
2010 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002011 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002012 break;
2013 case OPT_STR:
2014 case OPT_FSTR:
2015 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002016 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002017 break;
2018 }
2019 }
2020}
2021/*********************** From the file "parse.c" ****************************/
2022/*
2023** Input file parser for the LEMON parser generator.
2024*/
2025
2026/* The state of the parser */
2027struct pstate {
2028 char *filename; /* Name of the input file */
2029 int tokenlineno; /* Linenumber at which current token starts */
2030 int errorcnt; /* Number of errors so far */
2031 char *tokenstart; /* Text of current token */
2032 struct lemon *gp; /* Global state vector */
2033 enum e_state {
2034 INITIALIZE,
2035 WAITING_FOR_DECL_OR_RULE,
2036 WAITING_FOR_DECL_KEYWORD,
2037 WAITING_FOR_DECL_ARG,
2038 WAITING_FOR_PRECEDENCE_SYMBOL,
2039 WAITING_FOR_ARROW,
2040 IN_RHS,
2041 LHS_ALIAS_1,
2042 LHS_ALIAS_2,
2043 LHS_ALIAS_3,
2044 RHS_ALIAS_1,
2045 RHS_ALIAS_2,
2046 PRECEDENCE_MARK_1,
2047 PRECEDENCE_MARK_2,
2048 RESYNC_AFTER_RULE_ERROR,
2049 RESYNC_AFTER_DECL_ERROR,
2050 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00002051 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00002052 WAITING_FOR_FALLBACK_ID,
icculus42585cf2010-02-14 05:19:56 +00002053 WAITING_FOR_EXPECT_VALUE,
drhe09daa92006-06-10 13:29:31 +00002054 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00002055 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002056 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00002057 struct symbol *lhs; /* Left-hand side of current rule */
2058 char *lhsalias; /* Alias for the LHS */
2059 int nrhs; /* Number of right-hand side symbols seen */
2060 struct symbol *rhs[MAXRHS]; /* RHS symbols */
2061 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
2062 struct rule *prevrule; /* Previous rule parsed */
2063 char *declkeyword; /* Keyword of a declaration */
2064 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002065 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002066 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002067 enum e_assoc declassoc; /* Assign this association to decl arguments */
2068 int preccounter; /* Assign this precedence to decl arguments */
2069 struct rule *firstrule; /* Pointer to first rule in the grammar */
2070 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2071};
2072
2073/* Parse a single token */
2074static void parseonetoken(psp)
2075struct pstate *psp;
2076{
icculus42585cf2010-02-14 05:19:56 +00002077 char *endptr;
drh75897232000-05-29 14:26:00 +00002078 char *x;
2079 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2080#if 0
2081 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2082 x,psp->state);
2083#endif
2084 switch( psp->state ){
2085 case INITIALIZE:
2086 psp->prevrule = 0;
2087 psp->preccounter = 0;
2088 psp->firstrule = psp->lastrule = 0;
2089 psp->gp->nrule = 0;
2090 /* Fall thru to next case */
2091 case WAITING_FOR_DECL_OR_RULE:
2092 if( x[0]=='%' ){
2093 psp->state = WAITING_FOR_DECL_KEYWORD;
2094 }else if( islower(x[0]) ){
2095 psp->lhs = Symbol_new(x);
2096 psp->nrhs = 0;
2097 psp->lhsalias = 0;
2098 psp->state = WAITING_FOR_ARROW;
2099 }else if( x[0]=='{' ){
2100 if( psp->prevrule==0 ){
2101 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002102"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002103fragment which begins on this line.");
2104 psp->errorcnt++;
2105 }else if( psp->prevrule->code!=0 ){
2106 ErrorMsg(psp->filename,psp->tokenlineno,
2107"Code fragment beginning on this line is not the first \
2108to follow the previous rule.");
2109 psp->errorcnt++;
2110 }else{
2111 psp->prevrule->line = psp->tokenlineno;
2112 psp->prevrule->code = &x[1];
2113 }
2114 }else if( x[0]=='[' ){
2115 psp->state = PRECEDENCE_MARK_1;
2116 }else{
2117 ErrorMsg(psp->filename,psp->tokenlineno,
2118 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2119 x);
2120 psp->errorcnt++;
2121 }
2122 break;
2123 case PRECEDENCE_MARK_1:
2124 if( !isupper(x[0]) ){
2125 ErrorMsg(psp->filename,psp->tokenlineno,
2126 "The precedence symbol must be a terminal.");
2127 psp->errorcnt++;
2128 }else if( psp->prevrule==0 ){
2129 ErrorMsg(psp->filename,psp->tokenlineno,
2130 "There is no prior rule to assign precedence \"[%s]\".",x);
2131 psp->errorcnt++;
2132 }else if( psp->prevrule->precsym!=0 ){
2133 ErrorMsg(psp->filename,psp->tokenlineno,
2134"Precedence mark on this line is not the first \
2135to follow the previous rule.");
2136 psp->errorcnt++;
2137 }else{
2138 psp->prevrule->precsym = Symbol_new(x);
2139 }
2140 psp->state = PRECEDENCE_MARK_2;
2141 break;
2142 case PRECEDENCE_MARK_2:
2143 if( x[0]!=']' ){
2144 ErrorMsg(psp->filename,psp->tokenlineno,
2145 "Missing \"]\" on precedence mark.");
2146 psp->errorcnt++;
2147 }
2148 psp->state = WAITING_FOR_DECL_OR_RULE;
2149 break;
2150 case WAITING_FOR_ARROW:
2151 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2152 psp->state = IN_RHS;
2153 }else if( x[0]=='(' ){
2154 psp->state = LHS_ALIAS_1;
2155 }else{
2156 ErrorMsg(psp->filename,psp->tokenlineno,
2157 "Expected to see a \":\" following the LHS symbol \"%s\".",
2158 psp->lhs->name);
2159 psp->errorcnt++;
2160 psp->state = RESYNC_AFTER_RULE_ERROR;
2161 }
2162 break;
2163 case LHS_ALIAS_1:
2164 if( isalpha(x[0]) ){
2165 psp->lhsalias = x;
2166 psp->state = LHS_ALIAS_2;
2167 }else{
2168 ErrorMsg(psp->filename,psp->tokenlineno,
2169 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2170 x,psp->lhs->name);
2171 psp->errorcnt++;
2172 psp->state = RESYNC_AFTER_RULE_ERROR;
2173 }
2174 break;
2175 case LHS_ALIAS_2:
2176 if( x[0]==')' ){
2177 psp->state = LHS_ALIAS_3;
2178 }else{
2179 ErrorMsg(psp->filename,psp->tokenlineno,
2180 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2181 psp->errorcnt++;
2182 psp->state = RESYNC_AFTER_RULE_ERROR;
2183 }
2184 break;
2185 case LHS_ALIAS_3:
2186 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2187 psp->state = IN_RHS;
2188 }else{
2189 ErrorMsg(psp->filename,psp->tokenlineno,
2190 "Missing \"->\" following: \"%s(%s)\".",
2191 psp->lhs->name,psp->lhsalias);
2192 psp->errorcnt++;
2193 psp->state = RESYNC_AFTER_RULE_ERROR;
2194 }
2195 break;
2196 case IN_RHS:
2197 if( x[0]=='.' ){
2198 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002199 rp = (struct rule *)calloc( sizeof(struct rule) +
2200 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002201 if( rp==0 ){
2202 ErrorMsg(psp->filename,psp->tokenlineno,
2203 "Can't allocate enough memory for this rule.");
2204 psp->errorcnt++;
2205 psp->prevrule = 0;
2206 }else{
2207 int i;
2208 rp->ruleline = psp->tokenlineno;
2209 rp->rhs = (struct symbol**)&rp[1];
2210 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2211 for(i=0; i<psp->nrhs; i++){
2212 rp->rhs[i] = psp->rhs[i];
2213 rp->rhsalias[i] = psp->alias[i];
2214 }
2215 rp->lhs = psp->lhs;
2216 rp->lhsalias = psp->lhsalias;
2217 rp->nrhs = psp->nrhs;
2218 rp->code = 0;
2219 rp->precsym = 0;
2220 rp->index = psp->gp->nrule++;
2221 rp->nextlhs = rp->lhs->rule;
2222 rp->lhs->rule = rp;
2223 rp->next = 0;
2224 if( psp->firstrule==0 ){
2225 psp->firstrule = psp->lastrule = rp;
2226 }else{
2227 psp->lastrule->next = rp;
2228 psp->lastrule = rp;
2229 }
2230 psp->prevrule = rp;
2231 }
2232 psp->state = WAITING_FOR_DECL_OR_RULE;
2233 }else if( isalpha(x[0]) ){
2234 if( psp->nrhs>=MAXRHS ){
2235 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002236 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002237 x);
2238 psp->errorcnt++;
2239 psp->state = RESYNC_AFTER_RULE_ERROR;
2240 }else{
2241 psp->rhs[psp->nrhs] = Symbol_new(x);
2242 psp->alias[psp->nrhs] = 0;
2243 psp->nrhs++;
2244 }
drhfd405312005-11-06 04:06:59 +00002245 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2246 struct symbol *msp = psp->rhs[psp->nrhs-1];
2247 if( msp->type!=MULTITERMINAL ){
2248 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002249 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002250 memset(msp, 0, sizeof(*msp));
2251 msp->type = MULTITERMINAL;
2252 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002253 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002254 msp->subsym[0] = origsp;
2255 msp->name = origsp->name;
2256 psp->rhs[psp->nrhs-1] = msp;
2257 }
2258 msp->nsubsym++;
2259 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2260 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2261 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2262 ErrorMsg(psp->filename,psp->tokenlineno,
2263 "Cannot form a compound containing a non-terminal");
2264 psp->errorcnt++;
2265 }
drh75897232000-05-29 14:26:00 +00002266 }else if( x[0]=='(' && psp->nrhs>0 ){
2267 psp->state = RHS_ALIAS_1;
2268 }else{
2269 ErrorMsg(psp->filename,psp->tokenlineno,
2270 "Illegal character on RHS of rule: \"%s\".",x);
2271 psp->errorcnt++;
2272 psp->state = RESYNC_AFTER_RULE_ERROR;
2273 }
2274 break;
2275 case RHS_ALIAS_1:
2276 if( isalpha(x[0]) ){
2277 psp->alias[psp->nrhs-1] = x;
2278 psp->state = RHS_ALIAS_2;
2279 }else{
2280 ErrorMsg(psp->filename,psp->tokenlineno,
2281 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2282 x,psp->rhs[psp->nrhs-1]->name);
2283 psp->errorcnt++;
2284 psp->state = RESYNC_AFTER_RULE_ERROR;
2285 }
2286 break;
2287 case RHS_ALIAS_2:
2288 if( x[0]==')' ){
2289 psp->state = IN_RHS;
2290 }else{
2291 ErrorMsg(psp->filename,psp->tokenlineno,
2292 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2293 psp->errorcnt++;
2294 psp->state = RESYNC_AFTER_RULE_ERROR;
2295 }
2296 break;
2297 case WAITING_FOR_DECL_KEYWORD:
2298 if( isalpha(x[0]) ){
2299 psp->declkeyword = x;
2300 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002301 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002302 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002303 psp->state = WAITING_FOR_DECL_ARG;
2304 if( strcmp(x,"name")==0 ){
2305 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002306 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002307 }else if( strcmp(x,"include")==0 ){
2308 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002309 }else if( strcmp(x,"code")==0 ){
2310 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002311 }else if( strcmp(x,"token_destructor")==0 ){
2312 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002313 }else if( strcmp(x,"default_destructor")==0 ){
2314 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002315 }else if( strcmp(x,"token_prefix")==0 ){
2316 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002317 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002318 }else if( strcmp(x,"syntax_error")==0 ){
2319 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002320 }else if( strcmp(x,"parse_accept")==0 ){
2321 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002322 }else if( strcmp(x,"parse_failure")==0 ){
2323 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002324 }else if( strcmp(x,"stack_overflow")==0 ){
2325 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002326 }else if( strcmp(x,"extra_argument")==0 ){
2327 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002328 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002329 }else if( strcmp(x,"token_type")==0 ){
2330 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002331 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002332 }else if( strcmp(x,"default_type")==0 ){
2333 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002334 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002335 }else if( strcmp(x,"stack_size")==0 ){
2336 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002337 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002338 }else if( strcmp(x,"start_symbol")==0 ){
2339 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002340 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002341 }else if( strcmp(x,"left")==0 ){
2342 psp->preccounter++;
2343 psp->declassoc = LEFT;
2344 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2345 }else if( strcmp(x,"right")==0 ){
2346 psp->preccounter++;
2347 psp->declassoc = RIGHT;
2348 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2349 }else if( strcmp(x,"nonassoc")==0 ){
2350 psp->preccounter++;
2351 psp->declassoc = NONE;
2352 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2353 }else if( strcmp(x,"destructor")==0 ){
2354 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2355 }else if( strcmp(x,"type")==0 ){
2356 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002357 }else if( strcmp(x,"fallback")==0 ){
2358 psp->fallback = 0;
2359 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002360 }else if( strcmp(x,"wildcard")==0 ){
2361 psp->state = WAITING_FOR_WILDCARD_ID;
icculus42585cf2010-02-14 05:19:56 +00002362 }else if( strcmp(x,"expect")==0 ){
2363 if (psp->gp->nexpected >= 0) {
2364 ErrorMsg(psp->filename,psp->tokenlineno, "Multiple %expect declarations.");
2365 psp->errorcnt++;
2366 psp->state = RESYNC_AFTER_DECL_ERROR;
2367 } else {
2368 psp->state = WAITING_FOR_EXPECT_VALUE;
2369 }
drh75897232000-05-29 14:26:00 +00002370 }else{
2371 ErrorMsg(psp->filename,psp->tokenlineno,
2372 "Unknown declaration keyword: \"%%%s\".",x);
2373 psp->errorcnt++;
2374 psp->state = RESYNC_AFTER_DECL_ERROR;
2375 }
2376 }else{
2377 ErrorMsg(psp->filename,psp->tokenlineno,
2378 "Illegal declaration keyword: \"%s\".",x);
2379 psp->errorcnt++;
2380 psp->state = RESYNC_AFTER_DECL_ERROR;
2381 }
2382 break;
2383 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2384 if( !isalpha(x[0]) ){
2385 ErrorMsg(psp->filename,psp->tokenlineno,
2386 "Symbol name missing after %destructor keyword");
2387 psp->errorcnt++;
2388 psp->state = RESYNC_AFTER_DECL_ERROR;
2389 }else{
2390 struct symbol *sp = Symbol_new(x);
2391 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002392 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002393 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002394 psp->state = WAITING_FOR_DECL_ARG;
2395 }
2396 break;
icculus42585cf2010-02-14 05:19:56 +00002397 case WAITING_FOR_EXPECT_VALUE:
2398 psp->gp->nexpected = (int) strtol(x, &endptr, 10);
2399 if( (*endptr != '\0') || (endptr == x) ) {
2400 ErrorMsg(psp->filename,psp->tokenlineno,
2401 "Integer expected after %%expect keyword");
2402 psp->errorcnt++;
2403 } else if (psp->gp->nexpected < 0) {
2404 ErrorMsg(psp->filename,psp->tokenlineno,
2405 "Integer can't be negative after %%expect keyword");
2406 psp->errorcnt++;
2407 }
2408 psp->state = WAITING_FOR_DECL_OR_RULE;
2409 break;
drh75897232000-05-29 14:26:00 +00002410 case WAITING_FOR_DATATYPE_SYMBOL:
2411 if( !isalpha(x[0]) ){
2412 ErrorMsg(psp->filename,psp->tokenlineno,
2413 "Symbol name missing after %destructor keyword");
2414 psp->errorcnt++;
2415 psp->state = RESYNC_AFTER_DECL_ERROR;
2416 }else{
2417 struct symbol *sp = Symbol_new(x);
2418 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002419 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002420 psp->state = WAITING_FOR_DECL_ARG;
2421 }
2422 break;
2423 case WAITING_FOR_PRECEDENCE_SYMBOL:
2424 if( x[0]=='.' ){
2425 psp->state = WAITING_FOR_DECL_OR_RULE;
2426 }else if( isupper(x[0]) ){
2427 struct symbol *sp;
2428 sp = Symbol_new(x);
2429 if( sp->prec>=0 ){
2430 ErrorMsg(psp->filename,psp->tokenlineno,
2431 "Symbol \"%s\" has already be given a precedence.",x);
2432 psp->errorcnt++;
2433 }else{
2434 sp->prec = psp->preccounter;
2435 sp->assoc = psp->declassoc;
2436 }
2437 }else{
2438 ErrorMsg(psp->filename,psp->tokenlineno,
2439 "Can't assign a precedence to \"%s\".",x);
2440 psp->errorcnt++;
2441 }
2442 break;
2443 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002444 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2445 char *zOld, *zNew, *zBuf, *z;
2446 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002447 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002448 char zLine[50];
2449 zNew = x;
2450 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002451 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002452 if( *psp->declargslot ){
2453 zOld = *psp->declargslot;
2454 }else{
2455 zOld = "";
2456 }
drh87cf1372008-08-13 20:09:06 +00002457 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002458 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002459 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002460 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2461 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002462 for(z=psp->filename, nBack=0; *z; z++){
2463 if( *z=='\\' ) nBack++;
2464 }
2465 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002466 nLine = lemonStrlen(zLine);
2467 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002468 }
2469 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2470 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002471 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002472 if( nOld && zBuf[-1]!='\n' ){
2473 *(zBuf++) = '\n';
2474 }
2475 memcpy(zBuf, zLine, nLine);
2476 zBuf += nLine;
2477 *(zBuf++) = '"';
2478 for(z=psp->filename; *z; z++){
2479 if( *z=='\\' ){
2480 *(zBuf++) = '\\';
2481 }
2482 *(zBuf++) = *z;
2483 }
2484 *(zBuf++) = '"';
2485 *(zBuf++) = '\n';
2486 }
drh4dc8ef52008-07-01 17:13:57 +00002487 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2488 psp->decllinenoslot[0] = psp->tokenlineno;
2489 }
drha5808f32008-04-27 22:19:44 +00002490 memcpy(zBuf, zNew, nNew);
2491 zBuf += nNew;
2492 *zBuf = 0;
2493 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002494 }else{
2495 ErrorMsg(psp->filename,psp->tokenlineno,
2496 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2497 psp->errorcnt++;
2498 psp->state = RESYNC_AFTER_DECL_ERROR;
2499 }
2500 break;
drh0bd1f4e2002-06-06 18:54:39 +00002501 case WAITING_FOR_FALLBACK_ID:
2502 if( x[0]=='.' ){
2503 psp->state = WAITING_FOR_DECL_OR_RULE;
2504 }else if( !isupper(x[0]) ){
2505 ErrorMsg(psp->filename, psp->tokenlineno,
2506 "%%fallback argument \"%s\" should be a token", x);
2507 psp->errorcnt++;
2508 }else{
2509 struct symbol *sp = Symbol_new(x);
2510 if( psp->fallback==0 ){
2511 psp->fallback = sp;
2512 }else if( sp->fallback ){
2513 ErrorMsg(psp->filename, psp->tokenlineno,
2514 "More than one fallback assigned to token %s", x);
2515 psp->errorcnt++;
2516 }else{
2517 sp->fallback = psp->fallback;
2518 psp->gp->has_fallback = 1;
2519 }
2520 }
2521 break;
drhe09daa92006-06-10 13:29:31 +00002522 case WAITING_FOR_WILDCARD_ID:
2523 if( x[0]=='.' ){
2524 psp->state = WAITING_FOR_DECL_OR_RULE;
2525 }else if( !isupper(x[0]) ){
2526 ErrorMsg(psp->filename, psp->tokenlineno,
2527 "%%wildcard argument \"%s\" should be a token", x);
2528 psp->errorcnt++;
2529 }else{
2530 struct symbol *sp = Symbol_new(x);
2531 if( psp->gp->wildcard==0 ){
2532 psp->gp->wildcard = sp;
2533 }else{
2534 ErrorMsg(psp->filename, psp->tokenlineno,
2535 "Extra wildcard to token: %s", x);
2536 psp->errorcnt++;
2537 }
2538 }
2539 break;
drh75897232000-05-29 14:26:00 +00002540 case RESYNC_AFTER_RULE_ERROR:
2541/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2542** break; */
2543 case RESYNC_AFTER_DECL_ERROR:
2544 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2545 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2546 break;
2547 }
2548}
2549
drh34ff57b2008-07-14 12:27:51 +00002550/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002551** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2552** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2553** comments them out. Text in between is also commented out as appropriate.
2554*/
danielk1977940fac92005-01-23 22:41:37 +00002555static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002556 int i, j, k, n;
2557 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002558 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002559 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002560 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002561 for(i=0; z[i]; i++){
2562 if( z[i]=='\n' ) lineno++;
2563 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2564 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2565 if( exclude ){
2566 exclude--;
2567 if( exclude==0 ){
2568 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2569 }
2570 }
2571 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2572 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2573 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2574 if( exclude ){
2575 exclude++;
2576 }else{
2577 for(j=i+7; isspace(z[j]); j++){}
2578 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2579 exclude = 1;
2580 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002581 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002582 exclude = 0;
2583 break;
2584 }
2585 }
2586 if( z[i+3]=='n' ) exclude = !exclude;
2587 if( exclude ){
2588 start = i;
2589 start_lineno = lineno;
2590 }
2591 }
2592 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2593 }
2594 }
2595 if( exclude ){
2596 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2597 exit(1);
2598 }
2599}
2600
drh75897232000-05-29 14:26:00 +00002601/* In spite of its name, this function is really a scanner. It read
2602** in the entire input file (all at once) then tokenizes it. Each
2603** token is passed to the function "parseonetoken" which builds all
2604** the appropriate data structures in the global state vector "gp".
2605*/
2606void Parse(gp)
2607struct lemon *gp;
2608{
2609 struct pstate ps;
2610 FILE *fp;
2611 char *filebuf;
2612 int filesize;
2613 int lineno;
2614 int c;
2615 char *cp, *nextcp;
2616 int startline = 0;
2617
rse38514a92007-09-20 11:34:17 +00002618 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002619 ps.gp = gp;
2620 ps.filename = gp->filename;
2621 ps.errorcnt = 0;
2622 ps.state = INITIALIZE;
2623
2624 /* Begin by reading the input file */
2625 fp = fopen(ps.filename,"rb");
2626 if( fp==0 ){
2627 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2628 gp->errorcnt++;
2629 return;
2630 }
2631 fseek(fp,0,2);
2632 filesize = ftell(fp);
2633 rewind(fp);
2634 filebuf = (char *)malloc( filesize+1 );
2635 if( filebuf==0 ){
2636 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2637 filesize+1);
2638 gp->errorcnt++;
2639 return;
2640 }
2641 if( fread(filebuf,1,filesize,fp)!=filesize ){
2642 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2643 filesize);
2644 free(filebuf);
2645 gp->errorcnt++;
2646 return;
2647 }
2648 fclose(fp);
2649 filebuf[filesize] = 0;
2650
drh6d08b4d2004-07-20 12:45:22 +00002651 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2652 preprocess_input(filebuf);
2653
drh75897232000-05-29 14:26:00 +00002654 /* Now scan the text of the input file */
2655 lineno = 1;
2656 for(cp=filebuf; (c= *cp)!=0; ){
2657 if( c=='\n' ) lineno++; /* Keep track of the line number */
2658 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2659 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2660 cp+=2;
2661 while( (c= *cp)!=0 && c!='\n' ) cp++;
2662 continue;
2663 }
2664 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2665 cp+=2;
2666 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2667 if( c=='\n' ) lineno++;
2668 cp++;
2669 }
2670 if( c ) cp++;
2671 continue;
2672 }
2673 ps.tokenstart = cp; /* Mark the beginning of the token */
2674 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2675 if( c=='\"' ){ /* String literals */
2676 cp++;
2677 while( (c= *cp)!=0 && c!='\"' ){
2678 if( c=='\n' ) lineno++;
2679 cp++;
2680 }
2681 if( c==0 ){
2682 ErrorMsg(ps.filename,startline,
2683"String starting on this line is not terminated before the end of the file.");
2684 ps.errorcnt++;
2685 nextcp = cp;
2686 }else{
2687 nextcp = cp+1;
2688 }
2689 }else if( c=='{' ){ /* A block of C code */
2690 int level;
2691 cp++;
2692 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2693 if( c=='\n' ) lineno++;
2694 else if( c=='{' ) level++;
2695 else if( c=='}' ) level--;
2696 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2697 int prevc;
2698 cp = &cp[2];
2699 prevc = 0;
2700 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2701 if( c=='\n' ) lineno++;
2702 prevc = c;
2703 cp++;
2704 }
2705 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2706 cp = &cp[2];
2707 while( (c= *cp)!=0 && c!='\n' ) cp++;
2708 if( c ) lineno++;
2709 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2710 int startchar, prevc;
2711 startchar = c;
2712 prevc = 0;
2713 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2714 if( c=='\n' ) lineno++;
2715 if( prevc=='\\' ) prevc = 0;
2716 else prevc = c;
2717 }
2718 }
2719 }
2720 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002721 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002722"C code starting on this line is not terminated before the end of the file.");
2723 ps.errorcnt++;
2724 nextcp = cp;
2725 }else{
2726 nextcp = cp+1;
2727 }
2728 }else if( isalnum(c) ){ /* Identifiers */
2729 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2730 nextcp = cp;
2731 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2732 cp += 3;
2733 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002734 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2735 cp += 2;
2736 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2737 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002738 }else{ /* All other (one character) operators */
2739 cp++;
2740 nextcp = cp;
2741 }
2742 c = *cp;
2743 *cp = 0; /* Null terminate the token */
2744 parseonetoken(&ps); /* Parse the token */
2745 *cp = c; /* Restore the buffer */
2746 cp = nextcp;
2747 }
2748 free(filebuf); /* Release the buffer after parsing */
2749 gp->rule = ps.firstrule;
2750 gp->errorcnt = ps.errorcnt;
2751}
2752/*************************** From the file "plink.c" *********************/
2753/*
2754** Routines processing configuration follow-set propagation links
2755** in the LEMON parser generator.
2756*/
2757static struct plink *plink_freelist = 0;
2758
2759/* Allocate a new plink */
2760struct plink *Plink_new(){
2761 struct plink *new;
2762
2763 if( plink_freelist==0 ){
2764 int i;
2765 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002766 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002767 if( plink_freelist==0 ){
2768 fprintf(stderr,
2769 "Unable to allocate memory for a new follow-set propagation link.\n");
2770 exit(1);
2771 }
2772 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2773 plink_freelist[amt-1].next = 0;
2774 }
2775 new = plink_freelist;
2776 plink_freelist = plink_freelist->next;
2777 return new;
2778}
2779
2780/* Add a plink to a plink list */
2781void Plink_add(plpp,cfp)
2782struct plink **plpp;
2783struct config *cfp;
2784{
2785 struct plink *new;
2786 new = Plink_new();
2787 new->next = *plpp;
2788 *plpp = new;
2789 new->cfp = cfp;
2790}
2791
2792/* Transfer every plink on the list "from" to the list "to" */
2793void Plink_copy(to,from)
2794struct plink **to;
2795struct plink *from;
2796{
2797 struct plink *nextpl;
2798 while( from ){
2799 nextpl = from->next;
2800 from->next = *to;
2801 *to = from;
2802 from = nextpl;
2803 }
2804}
2805
2806/* Delete every plink on the list */
2807void Plink_delete(plp)
2808struct plink *plp;
2809{
2810 struct plink *nextpl;
2811
2812 while( plp ){
2813 nextpl = plp->next;
2814 plp->next = plink_freelist;
2815 plink_freelist = plp;
2816 plp = nextpl;
2817 }
2818}
2819/*********************** From the file "report.c" **************************/
2820/*
2821** Procedures for generating reports and tables in the LEMON parser generator.
2822*/
2823
2824/* Generate a filename with the given suffix. Space to hold the
2825** name comes from malloc() and must be freed by the calling
2826** function.
2827*/
2828PRIVATE char *file_makename(lemp,suffix)
2829struct lemon *lemp;
2830char *suffix;
2831{
2832 char *name;
2833 char *cp;
2834
drh87cf1372008-08-13 20:09:06 +00002835 name = malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002836 if( name==0 ){
2837 fprintf(stderr,"Can't allocate space for a filename.\n");
2838 exit(1);
2839 }
2840 strcpy(name,lemp->filename);
2841 cp = strrchr(name,'.');
2842 if( cp ) *cp = 0;
2843 strcat(name,suffix);
2844 return name;
2845}
2846
2847/* Open a file with a name based on the name of the input file,
2848** but with a different (specified) suffix, and return a pointer
2849** to the stream */
2850PRIVATE FILE *file_open(lemp,suffix,mode)
2851struct lemon *lemp;
2852char *suffix;
2853char *mode;
2854{
2855 FILE *fp;
2856
2857 if( lemp->outname ) free(lemp->outname);
2858 lemp->outname = file_makename(lemp, suffix);
2859 fp = fopen(lemp->outname,mode);
2860 if( fp==0 && *mode=='w' ){
2861 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2862 lemp->errorcnt++;
2863 return 0;
2864 }
icculusf5ad8242010-02-14 05:34:42 +00002865
2866 /* Add files we create to a list, so we can delete them if we fail. This
2867 ** is to keep makefiles from getting confused. We don't include .out files,
2868 ** though: this is debug information, and you don't want it deleted if there
2869 ** was an error you need to track down.
2870 */
2871 if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){
2872 const char **ptr = (const char **)
2873 realloc(made_files, sizeof (const char **) * (made_files_count + 1));
2874 char *fname = strdup(lemp->outname);
2875 if ((ptr == NULL) || (fname == NULL)) {
2876 free(ptr);
2877 free(fname);
2878 memory_error();
2879 }
2880 made_files = ptr;
2881 made_files[made_files_count++] = fname;
2882 }
drh75897232000-05-29 14:26:00 +00002883 return fp;
2884}
2885
2886/* Duplicate the input file without comments and without actions
2887** on rules */
2888void Reprint(lemp)
2889struct lemon *lemp;
2890{
2891 struct rule *rp;
2892 struct symbol *sp;
2893 int i, j, maxlen, len, ncolumns, skip;
2894 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2895 maxlen = 10;
2896 for(i=0; i<lemp->nsymbol; i++){
2897 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002898 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002899 if( len>maxlen ) maxlen = len;
2900 }
2901 ncolumns = 76/(maxlen+5);
2902 if( ncolumns<1 ) ncolumns = 1;
2903 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2904 for(i=0; i<skip; i++){
2905 printf("//");
2906 for(j=i; j<lemp->nsymbol; j+=skip){
2907 sp = lemp->symbols[j];
2908 assert( sp->index==j );
2909 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2910 }
2911 printf("\n");
2912 }
2913 for(rp=lemp->rule; rp; rp=rp->next){
2914 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002915 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002916 printf(" ::=");
2917 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002918 sp = rp->rhs[i];
2919 printf(" %s", sp->name);
2920 if( sp->type==MULTITERMINAL ){
2921 for(j=1; j<sp->nsubsym; j++){
2922 printf("|%s", sp->subsym[j]->name);
2923 }
2924 }
2925 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002926 }
2927 printf(".");
2928 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002929 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002930 printf("\n");
2931 }
2932}
2933
2934void ConfigPrint(fp,cfp)
2935FILE *fp;
2936struct config *cfp;
2937{
2938 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002939 struct symbol *sp;
2940 int i, j;
drh75897232000-05-29 14:26:00 +00002941 rp = cfp->rp;
2942 fprintf(fp,"%s ::=",rp->lhs->name);
2943 for(i=0; i<=rp->nrhs; i++){
2944 if( i==cfp->dot ) fprintf(fp," *");
2945 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002946 sp = rp->rhs[i];
2947 fprintf(fp," %s", sp->name);
2948 if( sp->type==MULTITERMINAL ){
2949 for(j=1; j<sp->nsubsym; j++){
2950 fprintf(fp,"|%s",sp->subsym[j]->name);
2951 }
2952 }
drh75897232000-05-29 14:26:00 +00002953 }
2954}
2955
2956/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002957#if 0
drh75897232000-05-29 14:26:00 +00002958/* Print a set */
2959PRIVATE void SetPrint(out,set,lemp)
2960FILE *out;
2961char *set;
2962struct lemon *lemp;
2963{
2964 int i;
2965 char *spacer;
2966 spacer = "";
2967 fprintf(out,"%12s[","");
2968 for(i=0; i<lemp->nterminal; i++){
2969 if( SetFind(set,i) ){
2970 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2971 spacer = " ";
2972 }
2973 }
2974 fprintf(out,"]\n");
2975}
2976
2977/* Print a plink chain */
2978PRIVATE void PlinkPrint(out,plp,tag)
2979FILE *out;
2980struct plink *plp;
2981char *tag;
2982{
2983 while( plp ){
drhada354d2005-11-05 15:03:59 +00002984 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002985 ConfigPrint(out,plp->cfp);
2986 fprintf(out,"\n");
2987 plp = plp->next;
2988 }
2989}
2990#endif
2991
2992/* Print an action to the given file descriptor. Return FALSE if
2993** nothing was actually printed.
2994*/
2995int PrintAction(struct action *ap, FILE *fp, int indent){
2996 int result = 1;
2997 switch( ap->type ){
2998 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002999 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00003000 break;
3001 case REDUCE:
3002 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
3003 break;
3004 case ACCEPT:
3005 fprintf(fp,"%*s accept",indent,ap->sp->name);
3006 break;
3007 case ERROR:
3008 fprintf(fp,"%*s error",indent,ap->sp->name);
3009 break;
drh9892c5d2007-12-21 00:02:11 +00003010 case SRCONFLICT:
3011 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00003012 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
3013 indent,ap->sp->name,ap->x.rp->index);
3014 break;
drh9892c5d2007-12-21 00:02:11 +00003015 case SSCONFLICT:
3016 fprintf(fp,"%*s shift %d ** Parsing conflict **",
3017 indent,ap->sp->name,ap->x.stp->statenum);
3018 break;
drh75897232000-05-29 14:26:00 +00003019 case SH_RESOLVED:
3020 case RD_RESOLVED:
3021 case NOT_USED:
3022 result = 0;
3023 break;
3024 }
3025 return result;
3026}
3027
3028/* Generate the "y.output" log file */
3029void ReportOutput(lemp)
3030struct lemon *lemp;
3031{
3032 int i;
3033 struct state *stp;
3034 struct config *cfp;
3035 struct action *ap;
3036 FILE *fp;
3037
drh2aa6ca42004-09-10 00:14:04 +00003038 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003039 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00003040 for(i=0; i<lemp->nstate; i++){
3041 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003042 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003043 if( lemp->basisflag ) cfp=stp->bp;
3044 else cfp=stp->cfp;
3045 while( cfp ){
3046 char buf[20];
3047 if( cfp->dot==cfp->rp->nrhs ){
3048 sprintf(buf,"(%d)",cfp->rp->index);
3049 fprintf(fp," %5s ",buf);
3050 }else{
3051 fprintf(fp," ");
3052 }
3053 ConfigPrint(fp,cfp);
3054 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003055#if 0
drh75897232000-05-29 14:26:00 +00003056 SetPrint(fp,cfp->fws,lemp);
3057 PlinkPrint(fp,cfp->fplp,"To ");
3058 PlinkPrint(fp,cfp->bplp,"From");
3059#endif
3060 if( lemp->basisflag ) cfp=cfp->bp;
3061 else cfp=cfp->next;
3062 }
3063 fprintf(fp,"\n");
3064 for(ap=stp->ap; ap; ap=ap->next){
3065 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3066 }
3067 fprintf(fp,"\n");
3068 }
drhe9278182007-07-18 18:16:29 +00003069 fprintf(fp, "----------------------------------------------------\n");
3070 fprintf(fp, "Symbols:\n");
3071 for(i=0; i<lemp->nsymbol; i++){
3072 int j;
3073 struct symbol *sp;
3074
3075 sp = lemp->symbols[i];
3076 fprintf(fp, " %3d: %s", i, sp->name);
3077 if( sp->type==NONTERMINAL ){
3078 fprintf(fp, ":");
3079 if( sp->lambda ){
3080 fprintf(fp, " <lambda>");
3081 }
3082 for(j=0; j<lemp->nterminal; j++){
3083 if( sp->firstset && SetFind(sp->firstset, j) ){
3084 fprintf(fp, " %s", lemp->symbols[j]->name);
3085 }
3086 }
3087 }
3088 fprintf(fp, "\n");
3089 }
drh75897232000-05-29 14:26:00 +00003090 fclose(fp);
3091 return;
3092}
3093
3094/* Search for the file "name" which is in the same directory as
3095** the exacutable */
3096PRIVATE char *pathsearch(argv0,name,modemask)
3097char *argv0;
3098char *name;
3099int modemask;
3100{
3101 char *pathlist;
3102 char *path,*cp;
3103 char c;
drh75897232000-05-29 14:26:00 +00003104
3105#ifdef __WIN32__
3106 cp = strrchr(argv0,'\\');
3107#else
3108 cp = strrchr(argv0,'/');
3109#endif
3110 if( cp ){
3111 c = *cp;
3112 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003113 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003114 if( path ) sprintf(path,"%s/%s",argv0,name);
3115 *cp = c;
3116 }else{
3117 extern char *getenv();
3118 pathlist = getenv("PATH");
3119 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
drh87cf1372008-08-13 20:09:06 +00003120 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
drh75897232000-05-29 14:26:00 +00003121 if( path!=0 ){
3122 while( *pathlist ){
3123 cp = strchr(pathlist,':');
drh87cf1372008-08-13 20:09:06 +00003124 if( cp==0 ) cp = &pathlist[lemonStrlen(pathlist)];
drh75897232000-05-29 14:26:00 +00003125 c = *cp;
3126 *cp = 0;
3127 sprintf(path,"%s/%s",pathlist,name);
3128 *cp = c;
3129 if( c==0 ) pathlist = "";
3130 else pathlist = &cp[1];
3131 if( access(path,modemask)==0 ) break;
3132 }
3133 }
3134 }
3135 return path;
3136}
3137
3138/* Given an action, compute the integer value for that action
3139** which is to be put in the action table of the generated machine.
3140** Return negative if no action should be generated.
3141*/
3142PRIVATE int compute_action(lemp,ap)
3143struct lemon *lemp;
3144struct action *ap;
3145{
3146 int act;
3147 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003148 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003149 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3150 case ERROR: act = lemp->nstate + lemp->nrule; break;
3151 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3152 default: act = -1; break;
3153 }
3154 return act;
3155}
3156
3157#define LINESIZE 1000
3158/* The next cluster of routines are for reading the template file
3159** and writing the results to the generated parser */
3160/* The first function transfers data from "in" to "out" until
3161** a line is seen which begins with "%%". The line number is
3162** tracked.
3163**
3164** if name!=0, then any word that begin with "Parse" is changed to
3165** begin with *name instead.
3166*/
3167PRIVATE void tplt_xfer(name,in,out,lineno)
3168char *name;
3169FILE *in;
3170FILE *out;
3171int *lineno;
3172{
3173 int i, iStart;
3174 char line[LINESIZE];
3175 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3176 (*lineno)++;
3177 iStart = 0;
3178 if( name ){
3179 for(i=0; line[i]; i++){
3180 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3181 && (i==0 || !isalpha(line[i-1]))
3182 ){
3183 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3184 fprintf(out,"%s",name);
3185 i += 4;
3186 iStart = i+1;
3187 }
3188 }
3189 }
3190 fprintf(out,"%s",&line[iStart]);
3191 }
3192}
3193
3194/* The next function finds the template file and opens it, returning
3195** a pointer to the opened file. */
3196PRIVATE FILE *tplt_open(lemp)
3197struct lemon *lemp;
3198{
3199 static char templatename[] = "lempar.c";
3200 char buf[1000];
3201 FILE *in;
3202 char *tpltname;
3203 char *cp;
3204
icculus3e143bd2010-02-14 00:48:49 +00003205 /* first, see if user specified a template filename on the command line. */
3206 if (user_templatename != 0) {
3207 if( access(user_templatename,004)==-1 ){
3208 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3209 user_templatename);
3210 lemp->errorcnt++;
3211 return 0;
3212 }
3213 in = fopen(user_templatename,"rb");
3214 if( in==0 ){
3215 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3216 lemp->errorcnt++;
3217 return 0;
3218 }
3219 return in;
3220 }
3221
drh75897232000-05-29 14:26:00 +00003222 cp = strrchr(lemp->filename,'.');
3223 if( cp ){
drh8b582012003-10-21 13:16:03 +00003224 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003225 }else{
3226 sprintf(buf,"%s.lt",lemp->filename);
3227 }
3228 if( access(buf,004)==0 ){
3229 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003230 }else if( access(templatename,004)==0 ){
3231 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003232 }else{
3233 tpltname = pathsearch(lemp->argv0,templatename,0);
3234 }
3235 if( tpltname==0 ){
3236 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3237 templatename);
3238 lemp->errorcnt++;
3239 return 0;
3240 }
drh2aa6ca42004-09-10 00:14:04 +00003241 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003242 if( in==0 ){
3243 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3244 lemp->errorcnt++;
3245 return 0;
3246 }
3247 return in;
3248}
3249
drhaf805ca2004-09-07 11:28:25 +00003250/* Print a #line directive line to the output file. */
3251PRIVATE void tplt_linedir(out,lineno,filename)
3252FILE *out;
3253int lineno;
3254char *filename;
3255{
3256 fprintf(out,"#line %d \"",lineno);
3257 while( *filename ){
3258 if( *filename == '\\' ) putc('\\',out);
3259 putc(*filename,out);
3260 filename++;
3261 }
3262 fprintf(out,"\"\n");
3263}
3264
drh75897232000-05-29 14:26:00 +00003265/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003266PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003267FILE *out;
3268struct lemon *lemp;
3269char *str;
drh75897232000-05-29 14:26:00 +00003270int *lineno;
3271{
3272 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003273 while( *str ){
drh75897232000-05-29 14:26:00 +00003274 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003275 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003276 str++;
3277 }
drh9db55df2004-09-09 14:01:21 +00003278 if( str[-1]!='\n' ){
3279 putc('\n',out);
3280 (*lineno)++;
3281 }
shane58543932008-12-10 20:10:04 +00003282 if (!lemp->nolinenosflag) {
3283 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3284 }
drh75897232000-05-29 14:26:00 +00003285 return;
3286}
3287
3288/*
3289** The following routine emits code for the destructor for the
3290** symbol sp
3291*/
3292void emit_destructor_code(out,sp,lemp,lineno)
3293FILE *out;
3294struct symbol *sp;
3295struct lemon *lemp;
3296int *lineno;
3297{
drhcc83b6e2004-04-23 23:38:42 +00003298 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003299
drh75897232000-05-29 14:26:00 +00003300 if( sp->type==TERMINAL ){
3301 cp = lemp->tokendest;
3302 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003303 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003304 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003305 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003306 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003307 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003308 }else if( lemp->vardest ){
3309 cp = lemp->vardest;
3310 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003311 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003312 }else{
3313 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003314 }
3315 for(; *cp; cp++){
3316 if( *cp=='$' && cp[1]=='$' ){
3317 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3318 cp++;
3319 continue;
3320 }
shane58543932008-12-10 20:10:04 +00003321 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003322 fputc(*cp,out);
3323 }
shane58543932008-12-10 20:10:04 +00003324 fprintf(out,"\n"); (*lineno)++;
3325 if (!lemp->nolinenosflag) {
3326 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3327 }
3328 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003329 return;
3330}
3331
3332/*
drh960e8c62001-04-03 16:53:21 +00003333** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003334*/
3335int has_destructor(sp, lemp)
3336struct symbol *sp;
3337struct lemon *lemp;
3338{
3339 int ret;
3340 if( sp->type==TERMINAL ){
3341 ret = lemp->tokendest!=0;
3342 }else{
drh960e8c62001-04-03 16:53:21 +00003343 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003344 }
3345 return ret;
3346}
3347
drh0bb132b2004-07-20 14:06:51 +00003348/*
3349** Append text to a dynamically allocated string. If zText is 0 then
3350** reset the string to be empty again. Always return the complete text
3351** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003352**
3353** n bytes of zText are stored. If n==0 then all of zText up to the first
3354** \000 terminator is stored. zText can contain up to two instances of
3355** %d. The values of p1 and p2 are written into the first and second
3356** %d.
3357**
3358** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003359*/
3360PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3361 static char *z = 0;
3362 static int alloced = 0;
3363 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003364 int c;
drh0bb132b2004-07-20 14:06:51 +00003365 char zInt[40];
3366
3367 if( zText==0 ){
3368 used = 0;
3369 return z;
3370 }
drh7ac25c72004-08-19 15:12:26 +00003371 if( n<=0 ){
3372 if( n<0 ){
3373 used += n;
3374 assert( used>=0 );
3375 }
drh87cf1372008-08-13 20:09:06 +00003376 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003377 }
drh0bb132b2004-07-20 14:06:51 +00003378 if( n+sizeof(zInt)*2+used >= alloced ){
3379 alloced = n + sizeof(zInt)*2 + used + 200;
3380 z = realloc(z, alloced);
3381 }
3382 if( z==0 ) return "";
3383 while( n-- > 0 ){
3384 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003385 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003386 sprintf(zInt, "%d", p1);
3387 p1 = p2;
3388 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003389 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003390 zText++;
3391 n--;
3392 }else{
3393 z[used++] = c;
3394 }
3395 }
3396 z[used] = 0;
3397 return z;
3398}
3399
3400/*
3401** zCode is a string that is the action associated with a rule. Expand
3402** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003403** stack.
drh0bb132b2004-07-20 14:06:51 +00003404*/
drhaf805ca2004-09-07 11:28:25 +00003405PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003406 char *cp, *xp;
3407 int i;
3408 char lhsused = 0; /* True if the LHS element has been used */
3409 char used[MAXRHS]; /* True for each RHS element which is used */
3410
3411 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3412 lhsused = 0;
3413
drh19c9e562007-03-29 20:13:53 +00003414 if( rp->code==0 ){
3415 rp->code = "\n";
3416 rp->line = rp->ruleline;
3417 }
3418
drh0bb132b2004-07-20 14:06:51 +00003419 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003420 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003421 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3422 char saved;
3423 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3424 saved = *xp;
3425 *xp = 0;
3426 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003427 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003428 cp = xp;
3429 lhsused = 1;
3430 }else{
3431 for(i=0; i<rp->nrhs; i++){
3432 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003433 if( cp!=rp->code && cp[-1]=='@' ){
3434 /* If the argument is of the form @X then substituted
3435 ** the token number of X, not the value of X */
3436 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3437 }else{
drhfd405312005-11-06 04:06:59 +00003438 struct symbol *sp = rp->rhs[i];
3439 int dtnum;
3440 if( sp->type==MULTITERMINAL ){
3441 dtnum = sp->subsym[0]->dtnum;
3442 }else{
3443 dtnum = sp->dtnum;
3444 }
3445 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003446 }
drh0bb132b2004-07-20 14:06:51 +00003447 cp = xp;
3448 used[i] = 1;
3449 break;
3450 }
3451 }
3452 }
3453 *xp = saved;
3454 }
3455 append_str(cp, 1, 0, 0);
3456 } /* End loop */
3457
3458 /* Check to make sure the LHS has been used */
3459 if( rp->lhsalias && !lhsused ){
3460 ErrorMsg(lemp->filename,rp->ruleline,
3461 "Label \"%s\" for \"%s(%s)\" is never used.",
3462 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3463 lemp->errorcnt++;
3464 }
3465
3466 /* Generate destructor code for RHS symbols which are not used in the
3467 ** reduce code */
3468 for(i=0; i<rp->nrhs; i++){
3469 if( rp->rhsalias[i] && !used[i] ){
3470 ErrorMsg(lemp->filename,rp->ruleline,
3471 "Label %s for \"%s(%s)\" is never used.",
3472 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3473 lemp->errorcnt++;
3474 }else if( rp->rhsalias[i]==0 ){
3475 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003476 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003477 rp->rhs[i]->index,i-rp->nrhs+1);
3478 }else{
3479 /* No destructor defined for this term */
3480 }
3481 }
3482 }
drh61e339a2007-01-16 03:09:02 +00003483 if( rp->code ){
3484 cp = append_str(0,0,0,0);
3485 rp->code = Strsafe(cp?cp:"");
3486 }
drh0bb132b2004-07-20 14:06:51 +00003487}
3488
drh75897232000-05-29 14:26:00 +00003489/*
3490** Generate code which executes when the rule "rp" is reduced. Write
3491** the code to "out". Make sure lineno stays up-to-date.
3492*/
3493PRIVATE void emit_code(out,rp,lemp,lineno)
3494FILE *out;
3495struct rule *rp;
3496struct lemon *lemp;
3497int *lineno;
3498{
drh0bb132b2004-07-20 14:06:51 +00003499 char *cp;
drh75897232000-05-29 14:26:00 +00003500
3501 /* Generate code to do the reduce action */
3502 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003503 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003504 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003505 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003506 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003507 } /* End loop */
shane58543932008-12-10 20:10:04 +00003508 fprintf(out,"}\n"); (*lineno)++;
3509 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003510 } /* End if( rp->code ) */
3511
drh75897232000-05-29 14:26:00 +00003512 return;
3513}
3514
3515/*
3516** Print the definition of the union used for the parser's data stack.
3517** This union contains fields for every possible data type for tokens
3518** and nonterminals. In the process of computing and printing this
3519** union, also set the ".dtnum" field of every terminal and nonterminal
3520** symbol.
3521*/
3522void print_stack_union(out,lemp,plineno,mhflag)
3523FILE *out; /* The output stream */
3524struct lemon *lemp; /* The main info structure for this parser */
3525int *plineno; /* Pointer to the line number */
3526int mhflag; /* True if generating makeheaders output */
3527{
3528 int lineno = *plineno; /* The line number of the output */
3529 char **types; /* A hash table of datatypes */
3530 int arraysize; /* Size of the "types" array */
3531 int maxdtlength; /* Maximum length of any ".datatype" field. */
3532 char *stddt; /* Standardized name for a datatype */
3533 int i,j; /* Loop counters */
3534 int hash; /* For hashing the name of a type */
3535 char *name; /* Name of the parser */
3536
3537 /* Allocate and initialize types[] and allocate stddt[] */
3538 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003539 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003540 for(i=0; i<arraysize; i++) types[i] = 0;
3541 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003542 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003543 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003544 }
drh75897232000-05-29 14:26:00 +00003545 for(i=0; i<lemp->nsymbol; i++){
3546 int len;
3547 struct symbol *sp = lemp->symbols[i];
3548 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003549 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003550 if( len>maxdtlength ) maxdtlength = len;
3551 }
3552 stddt = (char*)malloc( maxdtlength*2 + 1 );
3553 if( types==0 || stddt==0 ){
3554 fprintf(stderr,"Out of memory.\n");
3555 exit(1);
3556 }
3557
3558 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3559 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003560 ** used for terminal symbols. If there is no %default_type defined then
3561 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3562 ** a datatype using the %type directive.
3563 */
drh75897232000-05-29 14:26:00 +00003564 for(i=0; i<lemp->nsymbol; i++){
3565 struct symbol *sp = lemp->symbols[i];
3566 char *cp;
3567 if( sp==lemp->errsym ){
3568 sp->dtnum = arraysize+1;
3569 continue;
3570 }
drh960e8c62001-04-03 16:53:21 +00003571 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003572 sp->dtnum = 0;
3573 continue;
3574 }
3575 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003576 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003577 j = 0;
3578 while( isspace(*cp) ) cp++;
3579 while( *cp ) stddt[j++] = *cp++;
3580 while( j>0 && isspace(stddt[j-1]) ) j--;
3581 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003582 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003583 sp->dtnum = 0;
3584 continue;
3585 }
drh75897232000-05-29 14:26:00 +00003586 hash = 0;
3587 for(j=0; stddt[j]; j++){
3588 hash = hash*53 + stddt[j];
3589 }
drh3b2129c2003-05-13 00:34:21 +00003590 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003591 while( types[hash] ){
3592 if( strcmp(types[hash],stddt)==0 ){
3593 sp->dtnum = hash + 1;
3594 break;
3595 }
3596 hash++;
3597 if( hash>=arraysize ) hash = 0;
3598 }
3599 if( types[hash]==0 ){
3600 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003601 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003602 if( types[hash]==0 ){
3603 fprintf(stderr,"Out of memory.\n");
3604 exit(1);
3605 }
3606 strcpy(types[hash],stddt);
3607 }
3608 }
3609
3610 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3611 name = lemp->name ? lemp->name : "Parse";
3612 lineno = *plineno;
3613 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3614 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3615 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3616 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3617 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003618 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003619 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3620 for(i=0; i<arraysize; i++){
3621 if( types[i]==0 ) continue;
3622 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3623 free(types[i]);
3624 }
drhc4dd3fd2008-01-22 01:48:05 +00003625 if( lemp->errsym->useCnt ){
3626 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3627 }
drh75897232000-05-29 14:26:00 +00003628 free(stddt);
3629 free(types);
3630 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3631 *plineno = lineno;
3632}
3633
drhb29b0a52002-02-23 19:39:46 +00003634/*
3635** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003636** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003637*/
drh8b582012003-10-21 13:16:03 +00003638static const char *minimum_size_type(int lwr, int upr){
3639 if( lwr>=0 ){
3640 if( upr<=255 ){
3641 return "unsigned char";
3642 }else if( upr<65535 ){
3643 return "unsigned short int";
3644 }else{
3645 return "unsigned int";
3646 }
3647 }else if( lwr>=-127 && upr<=127 ){
3648 return "signed char";
3649 }else if( lwr>=-32767 && upr<32767 ){
3650 return "short";
drhb29b0a52002-02-23 19:39:46 +00003651 }else{
drh8b582012003-10-21 13:16:03 +00003652 return "int";
drhb29b0a52002-02-23 19:39:46 +00003653 }
3654}
3655
drhfdbf9282003-10-21 16:34:41 +00003656/*
3657** Each state contains a set of token transaction and a set of
3658** nonterminal transactions. Each of these sets makes an instance
3659** of the following structure. An array of these structures is used
3660** to order the creation of entries in the yy_action[] table.
3661*/
3662struct axset {
3663 struct state *stp; /* A pointer to a state */
3664 int isTkn; /* True to use tokens. False for non-terminals */
3665 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003666 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003667};
3668
3669/*
3670** Compare to axset structures for sorting purposes
3671*/
3672static int axset_compare(const void *a, const void *b){
3673 struct axset *p1 = (struct axset*)a;
3674 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003675 int c;
3676 c = p2->nAction - p1->nAction;
3677 if( c==0 ){
3678 c = p2->iOrder - p1->iOrder;
3679 }
3680 assert( c!=0 || p1==p2 );
3681 return c;
drhfdbf9282003-10-21 16:34:41 +00003682}
3683
drhc4dd3fd2008-01-22 01:48:05 +00003684/*
3685** Write text on "out" that describes the rule "rp".
3686*/
3687static void writeRuleText(FILE *out, struct rule *rp){
3688 int j;
3689 fprintf(out,"%s ::=", rp->lhs->name);
3690 for(j=0; j<rp->nrhs; j++){
3691 struct symbol *sp = rp->rhs[j];
3692 fprintf(out," %s", sp->name);
3693 if( sp->type==MULTITERMINAL ){
3694 int k;
3695 for(k=1; k<sp->nsubsym; k++){
3696 fprintf(out,"|%s",sp->subsym[k]->name);
3697 }
3698 }
3699 }
3700}
3701
3702
drh75897232000-05-29 14:26:00 +00003703/* Generate C source code for the parser */
3704void ReportTable(lemp, mhflag)
3705struct lemon *lemp;
3706int mhflag; /* Output in makeheaders format if true */
3707{
3708 FILE *out, *in;
3709 char line[LINESIZE];
3710 int lineno;
3711 struct state *stp;
3712 struct action *ap;
3713 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003714 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003715 int i, j, k, n;
drh75897232000-05-29 14:26:00 +00003716 char *name;
drh8b582012003-10-21 13:16:03 +00003717 int mnTknOfst, mxTknOfst;
3718 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003719 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003720
3721 in = tplt_open(lemp);
3722 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003723 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003724 if( out==0 ){
3725 fclose(in);
3726 return;
3727 }
3728 lineno = 1;
3729 tplt_xfer(lemp->name,in,out,&lineno);
3730
3731 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003732 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003733 if( mhflag ){
3734 char *name = file_makename(lemp, ".h");
3735 fprintf(out,"#include \"%s\"\n", name); lineno++;
3736 free(name);
3737 }
3738 tplt_xfer(lemp->name,in,out,&lineno);
3739
3740 /* Generate #defines for all tokens */
3741 if( mhflag ){
3742 char *prefix;
3743 fprintf(out,"#if INTERFACE\n"); lineno++;
3744 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3745 else prefix = "";
3746 for(i=1; i<lemp->nterminal; i++){
3747 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3748 lineno++;
3749 }
3750 fprintf(out,"#endif\n"); lineno++;
3751 }
3752 tplt_xfer(lemp->name,in,out,&lineno);
3753
3754 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003755 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003756 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003757 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3758 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003759 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003760 if( lemp->wildcard ){
3761 fprintf(out,"#define YYWILDCARD %d\n",
3762 lemp->wildcard->index); lineno++;
3763 }
drh75897232000-05-29 14:26:00 +00003764 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003765 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003766 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003767 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3768 }else{
3769 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3770 }
drhca44b5a2007-02-22 23:06:58 +00003771 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003772 if( mhflag ){
3773 fprintf(out,"#if INTERFACE\n"); lineno++;
3774 }
3775 name = lemp->name ? lemp->name : "Parse";
3776 if( lemp->arg && lemp->arg[0] ){
3777 int i;
drh87cf1372008-08-13 20:09:06 +00003778 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003779 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3780 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003781 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3782 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3783 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3784 name,lemp->arg,&lemp->arg[i]); lineno++;
3785 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3786 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003787 }else{
drh1f245e42002-03-11 13:55:50 +00003788 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3789 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3790 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3791 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003792 }
3793 if( mhflag ){
3794 fprintf(out,"#endif\n"); lineno++;
3795 }
3796 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3797 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003798 if( lemp->errsym->useCnt ){
3799 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3800 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3801 }
drh0bd1f4e2002-06-06 18:54:39 +00003802 if( lemp->has_fallback ){
3803 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3804 }
drh75897232000-05-29 14:26:00 +00003805 tplt_xfer(lemp->name,in,out,&lineno);
3806
drh8b582012003-10-21 13:16:03 +00003807 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003808 **
drh8b582012003-10-21 13:16:03 +00003809 ** yy_action[] A single table containing all actions.
3810 ** yy_lookahead[] A table containing the lookahead for each entry in
3811 ** yy_action. Used to detect hash collisions.
3812 ** yy_shift_ofst[] For each state, the offset into yy_action for
3813 ** shifting terminals.
3814 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3815 ** shifting non-terminals after a reduce.
3816 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003817 */
drh75897232000-05-29 14:26:00 +00003818
drh8b582012003-10-21 13:16:03 +00003819 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003820 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003821 if( ax==0 ){
3822 fprintf(stderr,"malloc failed\n");
3823 exit(1);
3824 }
drh75897232000-05-29 14:26:00 +00003825 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003826 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003827 ax[i*2].stp = stp;
3828 ax[i*2].isTkn = 1;
3829 ax[i*2].nAction = stp->nTknAct;
3830 ax[i*2+1].stp = stp;
3831 ax[i*2+1].isTkn = 0;
3832 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003833 }
drh8b582012003-10-21 13:16:03 +00003834 mxTknOfst = mnTknOfst = 0;
3835 mxNtOfst = mnNtOfst = 0;
3836
drhfdbf9282003-10-21 16:34:41 +00003837 /* Compute the action table. In order to try to keep the size of the
3838 ** action table to a minimum, the heuristic of placing the largest action
3839 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003840 */
drhe594bc32009-11-03 13:02:25 +00003841 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003842 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003843 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003844 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3845 stp = ax[i].stp;
3846 if( ax[i].isTkn ){
3847 for(ap=stp->ap; ap; ap=ap->next){
3848 int action;
3849 if( ap->sp->index>=lemp->nterminal ) continue;
3850 action = compute_action(lemp, ap);
3851 if( action<0 ) continue;
3852 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003853 }
drhfdbf9282003-10-21 16:34:41 +00003854 stp->iTknOfst = acttab_insert(pActtab);
3855 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3856 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3857 }else{
3858 for(ap=stp->ap; ap; ap=ap->next){
3859 int action;
3860 if( ap->sp->index<lemp->nterminal ) continue;
3861 if( ap->sp->index==lemp->nsymbol ) continue;
3862 action = compute_action(lemp, ap);
3863 if( action<0 ) continue;
3864 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003865 }
drhfdbf9282003-10-21 16:34:41 +00003866 stp->iNtOfst = acttab_insert(pActtab);
3867 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3868 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003869 }
3870 }
drhfdbf9282003-10-21 16:34:41 +00003871 free(ax);
drh8b582012003-10-21 13:16:03 +00003872
3873 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003874 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003875 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3876 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003877 for(i=j=0; i<n; i++){
3878 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003879 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003880 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003881 fprintf(out, " %4d,", action);
3882 if( j==9 || i==n-1 ){
3883 fprintf(out, "\n"); lineno++;
3884 j = 0;
3885 }else{
3886 j++;
3887 }
3888 }
3889 fprintf(out, "};\n"); lineno++;
3890
3891 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003892 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003893 for(i=j=0; i<n; i++){
3894 int la = acttab_yylookahead(pActtab, i);
3895 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003896 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003897 fprintf(out, " %4d,", la);
3898 if( j==9 || i==n-1 ){
3899 fprintf(out, "\n"); lineno++;
3900 j = 0;
3901 }else{
3902 j++;
3903 }
3904 }
3905 fprintf(out, "};\n"); lineno++;
3906
3907 /* Output the yy_shift_ofst[] table */
3908 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003909 n = lemp->nstate;
3910 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003911 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3912 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3913 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003914 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003915 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003916 for(i=j=0; i<n; i++){
3917 int ofst;
3918 stp = lemp->sorted[i];
3919 ofst = stp->iTknOfst;
3920 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003921 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003922 fprintf(out, " %4d,", ofst);
3923 if( j==9 || i==n-1 ){
3924 fprintf(out, "\n"); lineno++;
3925 j = 0;
3926 }else{
3927 j++;
3928 }
3929 }
3930 fprintf(out, "};\n"); lineno++;
3931
3932 /* Output the yy_reduce_ofst[] table */
3933 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003934 n = lemp->nstate;
3935 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003936 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3937 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3938 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003939 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003940 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003941 for(i=j=0; i<n; i++){
3942 int ofst;
3943 stp = lemp->sorted[i];
3944 ofst = stp->iNtOfst;
3945 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003946 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003947 fprintf(out, " %4d,", ofst);
3948 if( j==9 || i==n-1 ){
3949 fprintf(out, "\n"); lineno++;
3950 j = 0;
3951 }else{
3952 j++;
3953 }
3954 }
3955 fprintf(out, "};\n"); lineno++;
3956
3957 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003958 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003959 n = lemp->nstate;
3960 for(i=j=0; i<n; i++){
3961 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003962 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003963 fprintf(out, " %4d,", stp->iDflt);
3964 if( j==9 || i==n-1 ){
3965 fprintf(out, "\n"); lineno++;
3966 j = 0;
3967 }else{
3968 j++;
3969 }
3970 }
3971 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003972 tplt_xfer(lemp->name,in,out,&lineno);
3973
drh0bd1f4e2002-06-06 18:54:39 +00003974 /* Generate the table of fallback tokens.
3975 */
3976 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003977 int mx = lemp->nterminal - 1;
3978 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3979 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003980 struct symbol *p = lemp->symbols[i];
3981 if( p->fallback==0 ){
3982 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3983 }else{
3984 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3985 p->name, p->fallback->name);
3986 }
3987 lineno++;
3988 }
3989 }
3990 tplt_xfer(lemp->name, in, out, &lineno);
3991
3992 /* Generate a table containing the symbolic name of every symbol
3993 */
drh75897232000-05-29 14:26:00 +00003994 for(i=0; i<lemp->nsymbol; i++){
3995 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3996 fprintf(out," %-15s",line);
3997 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3998 }
3999 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4000 tplt_xfer(lemp->name,in,out,&lineno);
4001
drh0bd1f4e2002-06-06 18:54:39 +00004002 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004003 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004004 ** when tracing REDUCE actions.
4005 */
4006 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4007 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004008 fprintf(out," /* %3d */ \"", i);
4009 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004010 fprintf(out,"\",\n"); lineno++;
4011 }
4012 tplt_xfer(lemp->name,in,out,&lineno);
4013
drh75897232000-05-29 14:26:00 +00004014 /* Generate code which executes every time a symbol is popped from
4015 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004016 ** (In other words, generate the %destructor actions)
4017 */
drh75897232000-05-29 14:26:00 +00004018 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004019 int once = 1;
drh75897232000-05-29 14:26:00 +00004020 for(i=0; i<lemp->nsymbol; i++){
4021 struct symbol *sp = lemp->symbols[i];
4022 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004023 if( once ){
4024 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4025 once = 0;
4026 }
drhc53eed12009-06-12 17:46:19 +00004027 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004028 }
4029 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4030 if( i<lemp->nsymbol ){
4031 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4032 fprintf(out," break;\n"); lineno++;
4033 }
4034 }
drh8d659732005-01-13 23:54:06 +00004035 if( lemp->vardest ){
4036 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004037 int once = 1;
drh8d659732005-01-13 23:54:06 +00004038 for(i=0; i<lemp->nsymbol; i++){
4039 struct symbol *sp = lemp->symbols[i];
4040 if( sp==0 || sp->type==TERMINAL ||
4041 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004042 if( once ){
4043 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4044 once = 0;
4045 }
drhc53eed12009-06-12 17:46:19 +00004046 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004047 dflt_sp = sp;
4048 }
4049 if( dflt_sp!=0 ){
4050 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004051 }
drh4dc8ef52008-07-01 17:13:57 +00004052 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004053 }
drh75897232000-05-29 14:26:00 +00004054 for(i=0; i<lemp->nsymbol; i++){
4055 struct symbol *sp = lemp->symbols[i];
4056 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004057 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004058
4059 /* Combine duplicate destructors into a single case */
4060 for(j=i+1; j<lemp->nsymbol; j++){
4061 struct symbol *sp2 = lemp->symbols[j];
4062 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4063 && sp2->dtnum==sp->dtnum
4064 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004065 fprintf(out," case %d: /* %s */\n",
4066 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004067 sp2->destructor = 0;
4068 }
4069 }
4070
drh75897232000-05-29 14:26:00 +00004071 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4072 fprintf(out," break;\n"); lineno++;
4073 }
drh75897232000-05-29 14:26:00 +00004074 tplt_xfer(lemp->name,in,out,&lineno);
4075
4076 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004077 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004078 tplt_xfer(lemp->name,in,out,&lineno);
4079
4080 /* Generate the table of rule information
4081 **
4082 ** Note: This code depends on the fact that rules are number
4083 ** sequentually beginning with 0.
4084 */
4085 for(rp=lemp->rule; rp; rp=rp->next){
4086 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4087 }
4088 tplt_xfer(lemp->name,in,out,&lineno);
4089
4090 /* Generate code which execution during each REDUCE action */
4091 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004092 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004093 }
drhc53eed12009-06-12 17:46:19 +00004094 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004095 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004096 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004097 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004098 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004099 fprintf(out," case %d: /* ", rp->index);
4100 writeRuleText(out, rp);
4101 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004102 for(rp2=rp->next; rp2; rp2=rp2->next){
4103 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004104 fprintf(out," case %d: /* ", rp2->index);
4105 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004106 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004107 rp2->code = 0;
4108 }
4109 }
drh75897232000-05-29 14:26:00 +00004110 emit_code(out,rp,lemp,&lineno);
4111 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004112 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004113 }
drhc53eed12009-06-12 17:46:19 +00004114 /* Finally, output the default: rule. We choose as the default: all
4115 ** empty actions. */
4116 fprintf(out," default:\n"); lineno++;
4117 for(rp=lemp->rule; rp; rp=rp->next){
4118 if( rp->code==0 ) continue;
4119 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4120 fprintf(out," /* (%d) ", rp->index);
4121 writeRuleText(out, rp);
4122 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4123 }
4124 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004125 tplt_xfer(lemp->name,in,out,&lineno);
4126
4127 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004128 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004129 tplt_xfer(lemp->name,in,out,&lineno);
4130
4131 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004132 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004133 tplt_xfer(lemp->name,in,out,&lineno);
4134
4135 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004136 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004137 tplt_xfer(lemp->name,in,out,&lineno);
4138
4139 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004140 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004141
4142 fclose(in);
4143 fclose(out);
4144 return;
4145}
4146
4147/* Generate a header file for the parser */
4148void ReportHeader(lemp)
4149struct lemon *lemp;
4150{
4151 FILE *out, *in;
4152 char *prefix;
4153 char line[LINESIZE];
4154 char pattern[LINESIZE];
4155 int i;
4156
4157 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4158 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004159 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004160 if( in ){
4161 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4162 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4163 if( strcmp(line,pattern) ) break;
4164 }
4165 fclose(in);
4166 if( i==lemp->nterminal ){
4167 /* No change in the file. Don't rewrite it. */
4168 return;
4169 }
4170 }
drh2aa6ca42004-09-10 00:14:04 +00004171 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004172 if( out ){
4173 for(i=1; i<lemp->nterminal; i++){
4174 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4175 }
4176 fclose(out);
4177 }
4178 return;
4179}
4180
4181/* Reduce the size of the action tables, if possible, by making use
4182** of defaults.
4183**
drhb59499c2002-02-23 18:45:13 +00004184** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004185** it the default. Except, there is no default if the wildcard token
4186** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004187*/
4188void CompressTables(lemp)
4189struct lemon *lemp;
4190{
4191 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004192 struct action *ap, *ap2;
4193 struct rule *rp, *rp2, *rbest;
4194 int nbest, n;
drh75897232000-05-29 14:26:00 +00004195 int i;
drhe09daa92006-06-10 13:29:31 +00004196 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004197
4198 for(i=0; i<lemp->nstate; i++){
4199 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004200 nbest = 0;
4201 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004202 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004203
drhb59499c2002-02-23 18:45:13 +00004204 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004205 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4206 usesWildcard = 1;
4207 }
drhb59499c2002-02-23 18:45:13 +00004208 if( ap->type!=REDUCE ) continue;
4209 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004210 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004211 if( rp==rbest ) continue;
4212 n = 1;
4213 for(ap2=ap->next; ap2; ap2=ap2->next){
4214 if( ap2->type!=REDUCE ) continue;
4215 rp2 = ap2->x.rp;
4216 if( rp2==rbest ) continue;
4217 if( rp2==rp ) n++;
4218 }
4219 if( n>nbest ){
4220 nbest = n;
4221 rbest = rp;
drh75897232000-05-29 14:26:00 +00004222 }
4223 }
drhb59499c2002-02-23 18:45:13 +00004224
4225 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004226 ** is not at least 1 or if the wildcard token is a possible
4227 ** lookahead.
4228 */
4229 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004230
drhb59499c2002-02-23 18:45:13 +00004231
4232 /* Combine matching REDUCE actions into a single default */
4233 for(ap=stp->ap; ap; ap=ap->next){
4234 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4235 }
drh75897232000-05-29 14:26:00 +00004236 assert( ap );
4237 ap->sp = Symbol_new("{default}");
4238 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004239 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004240 }
4241 stp->ap = Action_sort(stp->ap);
4242 }
4243}
drhb59499c2002-02-23 18:45:13 +00004244
drhada354d2005-11-05 15:03:59 +00004245
4246/*
4247** Compare two states for sorting purposes. The smaller state is the
4248** one with the most non-terminal actions. If they have the same number
4249** of non-terminal actions, then the smaller is the one with the most
4250** token actions.
4251*/
4252static int stateResortCompare(const void *a, const void *b){
4253 const struct state *pA = *(const struct state**)a;
4254 const struct state *pB = *(const struct state**)b;
4255 int n;
4256
4257 n = pB->nNtAct - pA->nNtAct;
4258 if( n==0 ){
4259 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004260 if( n==0 ){
4261 n = pB->statenum - pA->statenum;
4262 }
drhada354d2005-11-05 15:03:59 +00004263 }
drhe594bc32009-11-03 13:02:25 +00004264 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004265 return n;
4266}
4267
4268
4269/*
4270** Renumber and resort states so that states with fewer choices
4271** occur at the end. Except, keep state 0 as the first state.
4272*/
4273void ResortStates(lemp)
4274struct lemon *lemp;
4275{
4276 int i;
4277 struct state *stp;
4278 struct action *ap;
4279
4280 for(i=0; i<lemp->nstate; i++){
4281 stp = lemp->sorted[i];
4282 stp->nTknAct = stp->nNtAct = 0;
4283 stp->iDflt = lemp->nstate + lemp->nrule;
4284 stp->iTknOfst = NO_OFFSET;
4285 stp->iNtOfst = NO_OFFSET;
4286 for(ap=stp->ap; ap; ap=ap->next){
4287 if( compute_action(lemp,ap)>=0 ){
4288 if( ap->sp->index<lemp->nterminal ){
4289 stp->nTknAct++;
4290 }else if( ap->sp->index<lemp->nsymbol ){
4291 stp->nNtAct++;
4292 }else{
4293 stp->iDflt = compute_action(lemp, ap);
4294 }
4295 }
4296 }
4297 }
4298 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4299 stateResortCompare);
4300 for(i=0; i<lemp->nstate; i++){
4301 lemp->sorted[i]->statenum = i;
4302 }
4303}
4304
4305
drh75897232000-05-29 14:26:00 +00004306/***************** From the file "set.c" ************************************/
4307/*
4308** Set manipulation routines for the LEMON parser generator.
4309*/
4310
4311static int size = 0;
4312
4313/* Set the set size */
4314void SetSize(n)
4315int n;
4316{
4317 size = n+1;
4318}
4319
4320/* Allocate a new set */
4321char *SetNew(){
4322 char *s;
drh9892c5d2007-12-21 00:02:11 +00004323 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004324 if( s==0 ){
4325 extern void memory_error();
4326 memory_error();
4327 }
drh75897232000-05-29 14:26:00 +00004328 return s;
4329}
4330
4331/* Deallocate a set */
4332void SetFree(s)
4333char *s;
4334{
4335 free(s);
4336}
4337
4338/* Add a new element to the set. Return TRUE if the element was added
4339** and FALSE if it was already there. */
4340int SetAdd(s,e)
4341char *s;
4342int e;
4343{
4344 int rv;
drh9892c5d2007-12-21 00:02:11 +00004345 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004346 rv = s[e];
4347 s[e] = 1;
4348 return !rv;
4349}
4350
4351/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4352int SetUnion(s1,s2)
4353char *s1;
4354char *s2;
4355{
4356 int i, progress;
4357 progress = 0;
4358 for(i=0; i<size; i++){
4359 if( s2[i]==0 ) continue;
4360 if( s1[i]==0 ){
4361 progress = 1;
4362 s1[i] = 1;
4363 }
4364 }
4365 return progress;
4366}
4367/********************** From the file "table.c" ****************************/
4368/*
4369** All code in this file has been automatically generated
4370** from a specification in the file
4371** "table.q"
4372** by the associative array code building program "aagen".
4373** Do not edit this file! Instead, edit the specification
4374** file, then rerun aagen.
4375*/
4376/*
4377** Code for processing tables in the LEMON parser generator.
4378*/
4379
4380PRIVATE int strhash(x)
4381char *x;
4382{
4383 int h = 0;
4384 while( *x) h = h*13 + *(x++);
4385 return h;
4386}
4387
4388/* Works like strdup, sort of. Save a string in malloced memory, but
4389** keep strings in a table so that the same string is not in more
4390** than one place.
4391*/
4392char *Strsafe(y)
4393char *y;
4394{
4395 char *z;
4396
drh916f75f2006-07-17 00:19:39 +00004397 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004398 z = Strsafe_find(y);
drh87cf1372008-08-13 20:09:06 +00004399 if( z==0 && (z=malloc( lemonStrlen(y)+1 ))!=0 ){
drh75897232000-05-29 14:26:00 +00004400 strcpy(z,y);
4401 Strsafe_insert(z);
4402 }
4403 MemoryCheck(z);
4404 return z;
4405}
4406
4407/* There is one instance of the following structure for each
4408** associative array of type "x1".
4409*/
4410struct s_x1 {
4411 int size; /* The number of available slots. */
4412 /* Must be a power of 2 greater than or */
4413 /* equal to 1 */
4414 int count; /* Number of currently slots filled */
4415 struct s_x1node *tbl; /* The data stored here */
4416 struct s_x1node **ht; /* Hash table for lookups */
4417};
4418
4419/* There is one instance of this structure for every data element
4420** in an associative array of type "x1".
4421*/
4422typedef struct s_x1node {
4423 char *data; /* The data */
4424 struct s_x1node *next; /* Next entry with the same hash */
4425 struct s_x1node **from; /* Previous link */
4426} x1node;
4427
4428/* There is only one instance of the array, which is the following */
4429static struct s_x1 *x1a;
4430
4431/* Allocate a new associative array */
4432void Strsafe_init(){
4433 if( x1a ) return;
4434 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4435 if( x1a ){
4436 x1a->size = 1024;
4437 x1a->count = 0;
4438 x1a->tbl = (x1node*)malloc(
4439 (sizeof(x1node) + sizeof(x1node*))*1024 );
4440 if( x1a->tbl==0 ){
4441 free(x1a);
4442 x1a = 0;
4443 }else{
4444 int i;
4445 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4446 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4447 }
4448 }
4449}
4450/* Insert a new record into the array. Return TRUE if successful.
4451** Prior data with the same key is NOT overwritten */
4452int Strsafe_insert(data)
4453char *data;
4454{
4455 x1node *np;
4456 int h;
4457 int ph;
4458
4459 if( x1a==0 ) return 0;
4460 ph = strhash(data);
4461 h = ph & (x1a->size-1);
4462 np = x1a->ht[h];
4463 while( np ){
4464 if( strcmp(np->data,data)==0 ){
4465 /* An existing entry with the same key is found. */
4466 /* Fail because overwrite is not allows. */
4467 return 0;
4468 }
4469 np = np->next;
4470 }
4471 if( x1a->count>=x1a->size ){
4472 /* Need to make the hash table bigger */
4473 int i,size;
4474 struct s_x1 array;
4475 array.size = size = x1a->size*2;
4476 array.count = x1a->count;
4477 array.tbl = (x1node*)malloc(
4478 (sizeof(x1node) + sizeof(x1node*))*size );
4479 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4480 array.ht = (x1node**)&(array.tbl[size]);
4481 for(i=0; i<size; i++) array.ht[i] = 0;
4482 for(i=0; i<x1a->count; i++){
4483 x1node *oldnp, *newnp;
4484 oldnp = &(x1a->tbl[i]);
4485 h = strhash(oldnp->data) & (size-1);
4486 newnp = &(array.tbl[i]);
4487 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4488 newnp->next = array.ht[h];
4489 newnp->data = oldnp->data;
4490 newnp->from = &(array.ht[h]);
4491 array.ht[h] = newnp;
4492 }
4493 free(x1a->tbl);
4494 *x1a = array;
4495 }
4496 /* Insert the new data */
4497 h = ph & (x1a->size-1);
4498 np = &(x1a->tbl[x1a->count++]);
4499 np->data = data;
4500 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4501 np->next = x1a->ht[h];
4502 x1a->ht[h] = np;
4503 np->from = &(x1a->ht[h]);
4504 return 1;
4505}
4506
4507/* Return a pointer to data assigned to the given key. Return NULL
4508** if no such key. */
4509char *Strsafe_find(key)
4510char *key;
4511{
4512 int h;
4513 x1node *np;
4514
4515 if( x1a==0 ) return 0;
4516 h = strhash(key) & (x1a->size-1);
4517 np = x1a->ht[h];
4518 while( np ){
4519 if( strcmp(np->data,key)==0 ) break;
4520 np = np->next;
4521 }
4522 return np ? np->data : 0;
4523}
4524
4525/* Return a pointer to the (terminal or nonterminal) symbol "x".
4526** Create a new symbol if this is the first time "x" has been seen.
4527*/
4528struct symbol *Symbol_new(x)
4529char *x;
4530{
4531 struct symbol *sp;
4532
4533 sp = Symbol_find(x);
4534 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004535 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004536 MemoryCheck(sp);
4537 sp->name = Strsafe(x);
4538 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4539 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004540 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004541 sp->prec = -1;
4542 sp->assoc = UNK;
4543 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004544 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004545 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004546 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004547 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004548 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004549 Symbol_insert(sp,sp->name);
4550 }
drhc4dd3fd2008-01-22 01:48:05 +00004551 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004552 return sp;
4553}
4554
drh60d31652004-02-22 00:08:04 +00004555/* Compare two symbols for working purposes
4556**
4557** Symbols that begin with upper case letters (terminals or tokens)
4558** must sort before symbols that begin with lower case letters
4559** (non-terminals). Other than that, the order does not matter.
4560**
4561** We find experimentally that leaving the symbols in their original
4562** order (the order they appeared in the grammar file) gives the
4563** smallest parser tables in SQLite.
4564*/
4565int Symbolcmpp(struct symbol **a, struct symbol **b){
4566 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4567 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004568 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004569 return i1-i2;
drh75897232000-05-29 14:26:00 +00004570}
4571
4572/* There is one instance of the following structure for each
4573** associative array of type "x2".
4574*/
4575struct s_x2 {
4576 int size; /* The number of available slots. */
4577 /* Must be a power of 2 greater than or */
4578 /* equal to 1 */
4579 int count; /* Number of currently slots filled */
4580 struct s_x2node *tbl; /* The data stored here */
4581 struct s_x2node **ht; /* Hash table for lookups */
4582};
4583
4584/* There is one instance of this structure for every data element
4585** in an associative array of type "x2".
4586*/
4587typedef struct s_x2node {
4588 struct symbol *data; /* The data */
4589 char *key; /* The key */
4590 struct s_x2node *next; /* Next entry with the same hash */
4591 struct s_x2node **from; /* Previous link */
4592} x2node;
4593
4594/* There is only one instance of the array, which is the following */
4595static struct s_x2 *x2a;
4596
4597/* Allocate a new associative array */
4598void Symbol_init(){
4599 if( x2a ) return;
4600 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4601 if( x2a ){
4602 x2a->size = 128;
4603 x2a->count = 0;
4604 x2a->tbl = (x2node*)malloc(
4605 (sizeof(x2node) + sizeof(x2node*))*128 );
4606 if( x2a->tbl==0 ){
4607 free(x2a);
4608 x2a = 0;
4609 }else{
4610 int i;
4611 x2a->ht = (x2node**)&(x2a->tbl[128]);
4612 for(i=0; i<128; i++) x2a->ht[i] = 0;
4613 }
4614 }
4615}
4616/* Insert a new record into the array. Return TRUE if successful.
4617** Prior data with the same key is NOT overwritten */
4618int Symbol_insert(data,key)
4619struct symbol *data;
4620char *key;
4621{
4622 x2node *np;
4623 int h;
4624 int ph;
4625
4626 if( x2a==0 ) return 0;
4627 ph = strhash(key);
4628 h = ph & (x2a->size-1);
4629 np = x2a->ht[h];
4630 while( np ){
4631 if( strcmp(np->key,key)==0 ){
4632 /* An existing entry with the same key is found. */
4633 /* Fail because overwrite is not allows. */
4634 return 0;
4635 }
4636 np = np->next;
4637 }
4638 if( x2a->count>=x2a->size ){
4639 /* Need to make the hash table bigger */
4640 int i,size;
4641 struct s_x2 array;
4642 array.size = size = x2a->size*2;
4643 array.count = x2a->count;
4644 array.tbl = (x2node*)malloc(
4645 (sizeof(x2node) + sizeof(x2node*))*size );
4646 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4647 array.ht = (x2node**)&(array.tbl[size]);
4648 for(i=0; i<size; i++) array.ht[i] = 0;
4649 for(i=0; i<x2a->count; i++){
4650 x2node *oldnp, *newnp;
4651 oldnp = &(x2a->tbl[i]);
4652 h = strhash(oldnp->key) & (size-1);
4653 newnp = &(array.tbl[i]);
4654 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4655 newnp->next = array.ht[h];
4656 newnp->key = oldnp->key;
4657 newnp->data = oldnp->data;
4658 newnp->from = &(array.ht[h]);
4659 array.ht[h] = newnp;
4660 }
4661 free(x2a->tbl);
4662 *x2a = array;
4663 }
4664 /* Insert the new data */
4665 h = ph & (x2a->size-1);
4666 np = &(x2a->tbl[x2a->count++]);
4667 np->key = key;
4668 np->data = data;
4669 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4670 np->next = x2a->ht[h];
4671 x2a->ht[h] = np;
4672 np->from = &(x2a->ht[h]);
4673 return 1;
4674}
4675
4676/* Return a pointer to data assigned to the given key. Return NULL
4677** if no such key. */
4678struct symbol *Symbol_find(key)
4679char *key;
4680{
4681 int h;
4682 x2node *np;
4683
4684 if( x2a==0 ) return 0;
4685 h = strhash(key) & (x2a->size-1);
4686 np = x2a->ht[h];
4687 while( np ){
4688 if( strcmp(np->key,key)==0 ) break;
4689 np = np->next;
4690 }
4691 return np ? np->data : 0;
4692}
4693
4694/* Return the n-th data. Return NULL if n is out of range. */
4695struct symbol *Symbol_Nth(n)
4696int n;
4697{
4698 struct symbol *data;
4699 if( x2a && n>0 && n<=x2a->count ){
4700 data = x2a->tbl[n-1].data;
4701 }else{
4702 data = 0;
4703 }
4704 return data;
4705}
4706
4707/* Return the size of the array */
4708int Symbol_count()
4709{
4710 return x2a ? x2a->count : 0;
4711}
4712
4713/* Return an array of pointers to all data in the table.
4714** The array is obtained from malloc. Return NULL if memory allocation
4715** problems, or if the array is empty. */
4716struct symbol **Symbol_arrayof()
4717{
4718 struct symbol **array;
4719 int i,size;
4720 if( x2a==0 ) return 0;
4721 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004722 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004723 if( array ){
4724 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4725 }
4726 return array;
4727}
4728
4729/* Compare two configurations */
4730int Configcmp(a,b)
4731struct config *a;
4732struct config *b;
4733{
4734 int x;
4735 x = a->rp->index - b->rp->index;
4736 if( x==0 ) x = a->dot - b->dot;
4737 return x;
4738}
4739
4740/* Compare two states */
4741PRIVATE int statecmp(a,b)
4742struct config *a;
4743struct config *b;
4744{
4745 int rc;
4746 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4747 rc = a->rp->index - b->rp->index;
4748 if( rc==0 ) rc = a->dot - b->dot;
4749 }
4750 if( rc==0 ){
4751 if( a ) rc = 1;
4752 if( b ) rc = -1;
4753 }
4754 return rc;
4755}
4756
4757/* Hash a state */
4758PRIVATE int statehash(a)
4759struct config *a;
4760{
4761 int h=0;
4762 while( a ){
4763 h = h*571 + a->rp->index*37 + a->dot;
4764 a = a->bp;
4765 }
4766 return h;
4767}
4768
4769/* Allocate a new state structure */
4770struct state *State_new()
4771{
4772 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004773 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004774 MemoryCheck(new);
4775 return new;
4776}
4777
4778/* There is one instance of the following structure for each
4779** associative array of type "x3".
4780*/
4781struct s_x3 {
4782 int size; /* The number of available slots. */
4783 /* Must be a power of 2 greater than or */
4784 /* equal to 1 */
4785 int count; /* Number of currently slots filled */
4786 struct s_x3node *tbl; /* The data stored here */
4787 struct s_x3node **ht; /* Hash table for lookups */
4788};
4789
4790/* There is one instance of this structure for every data element
4791** in an associative array of type "x3".
4792*/
4793typedef struct s_x3node {
4794 struct state *data; /* The data */
4795 struct config *key; /* The key */
4796 struct s_x3node *next; /* Next entry with the same hash */
4797 struct s_x3node **from; /* Previous link */
4798} x3node;
4799
4800/* There is only one instance of the array, which is the following */
4801static struct s_x3 *x3a;
4802
4803/* Allocate a new associative array */
4804void State_init(){
4805 if( x3a ) return;
4806 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4807 if( x3a ){
4808 x3a->size = 128;
4809 x3a->count = 0;
4810 x3a->tbl = (x3node*)malloc(
4811 (sizeof(x3node) + sizeof(x3node*))*128 );
4812 if( x3a->tbl==0 ){
4813 free(x3a);
4814 x3a = 0;
4815 }else{
4816 int i;
4817 x3a->ht = (x3node**)&(x3a->tbl[128]);
4818 for(i=0; i<128; i++) x3a->ht[i] = 0;
4819 }
4820 }
4821}
4822/* Insert a new record into the array. Return TRUE if successful.
4823** Prior data with the same key is NOT overwritten */
4824int State_insert(data,key)
4825struct state *data;
4826struct config *key;
4827{
4828 x3node *np;
4829 int h;
4830 int ph;
4831
4832 if( x3a==0 ) return 0;
4833 ph = statehash(key);
4834 h = ph & (x3a->size-1);
4835 np = x3a->ht[h];
4836 while( np ){
4837 if( statecmp(np->key,key)==0 ){
4838 /* An existing entry with the same key is found. */
4839 /* Fail because overwrite is not allows. */
4840 return 0;
4841 }
4842 np = np->next;
4843 }
4844 if( x3a->count>=x3a->size ){
4845 /* Need to make the hash table bigger */
4846 int i,size;
4847 struct s_x3 array;
4848 array.size = size = x3a->size*2;
4849 array.count = x3a->count;
4850 array.tbl = (x3node*)malloc(
4851 (sizeof(x3node) + sizeof(x3node*))*size );
4852 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4853 array.ht = (x3node**)&(array.tbl[size]);
4854 for(i=0; i<size; i++) array.ht[i] = 0;
4855 for(i=0; i<x3a->count; i++){
4856 x3node *oldnp, *newnp;
4857 oldnp = &(x3a->tbl[i]);
4858 h = statehash(oldnp->key) & (size-1);
4859 newnp = &(array.tbl[i]);
4860 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4861 newnp->next = array.ht[h];
4862 newnp->key = oldnp->key;
4863 newnp->data = oldnp->data;
4864 newnp->from = &(array.ht[h]);
4865 array.ht[h] = newnp;
4866 }
4867 free(x3a->tbl);
4868 *x3a = array;
4869 }
4870 /* Insert the new data */
4871 h = ph & (x3a->size-1);
4872 np = &(x3a->tbl[x3a->count++]);
4873 np->key = key;
4874 np->data = data;
4875 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4876 np->next = x3a->ht[h];
4877 x3a->ht[h] = np;
4878 np->from = &(x3a->ht[h]);
4879 return 1;
4880}
4881
4882/* Return a pointer to data assigned to the given key. Return NULL
4883** if no such key. */
4884struct state *State_find(key)
4885struct config *key;
4886{
4887 int h;
4888 x3node *np;
4889
4890 if( x3a==0 ) return 0;
4891 h = statehash(key) & (x3a->size-1);
4892 np = x3a->ht[h];
4893 while( np ){
4894 if( statecmp(np->key,key)==0 ) break;
4895 np = np->next;
4896 }
4897 return np ? np->data : 0;
4898}
4899
4900/* Return an array of pointers to all data in the table.
4901** The array is obtained from malloc. Return NULL if memory allocation
4902** problems, or if the array is empty. */
4903struct state **State_arrayof()
4904{
4905 struct state **array;
4906 int i,size;
4907 if( x3a==0 ) return 0;
4908 size = x3a->count;
4909 array = (struct state **)malloc( sizeof(struct state *)*size );
4910 if( array ){
4911 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4912 }
4913 return array;
4914}
4915
4916/* Hash a configuration */
4917PRIVATE int confighash(a)
4918struct config *a;
4919{
4920 int h=0;
4921 h = h*571 + a->rp->index*37 + a->dot;
4922 return h;
4923}
4924
4925/* There is one instance of the following structure for each
4926** associative array of type "x4".
4927*/
4928struct s_x4 {
4929 int size; /* The number of available slots. */
4930 /* Must be a power of 2 greater than or */
4931 /* equal to 1 */
4932 int count; /* Number of currently slots filled */
4933 struct s_x4node *tbl; /* The data stored here */
4934 struct s_x4node **ht; /* Hash table for lookups */
4935};
4936
4937/* There is one instance of this structure for every data element
4938** in an associative array of type "x4".
4939*/
4940typedef struct s_x4node {
4941 struct config *data; /* The data */
4942 struct s_x4node *next; /* Next entry with the same hash */
4943 struct s_x4node **from; /* Previous link */
4944} x4node;
4945
4946/* There is only one instance of the array, which is the following */
4947static struct s_x4 *x4a;
4948
4949/* Allocate a new associative array */
4950void Configtable_init(){
4951 if( x4a ) return;
4952 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4953 if( x4a ){
4954 x4a->size = 64;
4955 x4a->count = 0;
4956 x4a->tbl = (x4node*)malloc(
4957 (sizeof(x4node) + sizeof(x4node*))*64 );
4958 if( x4a->tbl==0 ){
4959 free(x4a);
4960 x4a = 0;
4961 }else{
4962 int i;
4963 x4a->ht = (x4node**)&(x4a->tbl[64]);
4964 for(i=0; i<64; i++) x4a->ht[i] = 0;
4965 }
4966 }
4967}
4968/* Insert a new record into the array. Return TRUE if successful.
4969** Prior data with the same key is NOT overwritten */
4970int Configtable_insert(data)
4971struct config *data;
4972{
4973 x4node *np;
4974 int h;
4975 int ph;
4976
4977 if( x4a==0 ) return 0;
4978 ph = confighash(data);
4979 h = ph & (x4a->size-1);
4980 np = x4a->ht[h];
4981 while( np ){
4982 if( Configcmp(np->data,data)==0 ){
4983 /* An existing entry with the same key is found. */
4984 /* Fail because overwrite is not allows. */
4985 return 0;
4986 }
4987 np = np->next;
4988 }
4989 if( x4a->count>=x4a->size ){
4990 /* Need to make the hash table bigger */
4991 int i,size;
4992 struct s_x4 array;
4993 array.size = size = x4a->size*2;
4994 array.count = x4a->count;
4995 array.tbl = (x4node*)malloc(
4996 (sizeof(x4node) + sizeof(x4node*))*size );
4997 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4998 array.ht = (x4node**)&(array.tbl[size]);
4999 for(i=0; i<size; i++) array.ht[i] = 0;
5000 for(i=0; i<x4a->count; i++){
5001 x4node *oldnp, *newnp;
5002 oldnp = &(x4a->tbl[i]);
5003 h = confighash(oldnp->data) & (size-1);
5004 newnp = &(array.tbl[i]);
5005 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5006 newnp->next = array.ht[h];
5007 newnp->data = oldnp->data;
5008 newnp->from = &(array.ht[h]);
5009 array.ht[h] = newnp;
5010 }
5011 free(x4a->tbl);
5012 *x4a = array;
5013 }
5014 /* Insert the new data */
5015 h = ph & (x4a->size-1);
5016 np = &(x4a->tbl[x4a->count++]);
5017 np->data = data;
5018 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5019 np->next = x4a->ht[h];
5020 x4a->ht[h] = np;
5021 np->from = &(x4a->ht[h]);
5022 return 1;
5023}
5024
5025/* Return a pointer to data assigned to the given key. Return NULL
5026** if no such key. */
5027struct config *Configtable_find(key)
5028struct config *key;
5029{
5030 int h;
5031 x4node *np;
5032
5033 if( x4a==0 ) return 0;
5034 h = confighash(key) & (x4a->size-1);
5035 np = x4a->ht[h];
5036 while( np ){
5037 if( Configcmp(np->data,key)==0 ) break;
5038 np = np->next;
5039 }
5040 return np ? np->data : 0;
5041}
5042
5043/* Remove all data from the table. Pass each data to the function "f"
5044** as it is removed. ("f" may be null to avoid this step.) */
5045void Configtable_clear(f)
5046int(*f)(/* struct config * */);
5047{
5048 int i;
5049 if( x4a==0 || x4a->count==0 ) return;
5050 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5051 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5052 x4a->count = 0;
5053 return;
5054}