blob: 85baf4200b1db9a1672c1471432d12f3066317f7 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
drhf9a2e7b2003-04-15 01:49:48 +000010#include <stdarg.h>
drh75897232000-05-29 14:26:00 +000011#include <string.h>
12#include <ctype.h>
drh8b582012003-10-21 13:16:03 +000013#include <stdlib.h>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drh75897232000-05-29 14:26:00 +000016#ifndef __WIN32__
17# if defined(_WIN32) || defined(WIN32)
18# define __WIN32__
19# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
23extern int access();
24#else
25#include <unistd.h>
26#endif
27
drh75897232000-05-29 14:26:00 +000028/* #define PRIVATE static */
29#define PRIVATE
30
31#ifdef TEST
32#define MAXRHS 5 /* Set low to exercise exception code */
33#else
34#define MAXRHS 1000
35#endif
36
drhe9278182007-07-18 18:16:29 +000037static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000038
drhe9278182007-07-18 18:16:29 +000039static struct action *Action_new(void);
40static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000041
42/********** From the file "build.h" ************************************/
43void FindRulePrecedences();
44void FindFirstSets();
45void FindStates();
46void FindLinks();
47void FindFollowSets();
48void FindActions();
49
50/********* From the file "configlist.h" *********************************/
51void Configlist_init(/* void */);
52struct config *Configlist_add(/* struct rule *, int */);
53struct config *Configlist_addbasis(/* struct rule *, int */);
54void Configlist_closure(/* void */);
55void Configlist_sort(/* void */);
56void Configlist_sortbasis(/* void */);
57struct config *Configlist_return(/* void */);
58struct config *Configlist_basis(/* void */);
59void Configlist_eat(/* struct config * */);
60void Configlist_reset(/* void */);
61
62/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000063void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000064
65/****** From the file "option.h" ******************************************/
66struct s_options {
67 enum { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
68 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR} type;
69 char *label;
70 char *arg;
71 char *message;
72};
drhb0c86772000-06-02 23:21:26 +000073int OptInit(/* char**,struct s_options*,FILE* */);
74int OptNArgs(/* void */);
75char *OptArg(/* int */);
76void OptErr(/* int */);
77void OptPrint(/* void */);
drh75897232000-05-29 14:26:00 +000078
79/******** From the file "parse.h" *****************************************/
80void Parse(/* struct lemon *lemp */);
81
82/********* From the file "plink.h" ***************************************/
83struct plink *Plink_new(/* void */);
84void Plink_add(/* struct plink **, struct config * */);
85void Plink_copy(/* struct plink **, struct plink * */);
86void Plink_delete(/* struct plink * */);
87
88/********** From the file "report.h" *************************************/
89void Reprint(/* struct lemon * */);
90void ReportOutput(/* struct lemon * */);
91void ReportTable(/* struct lemon * */);
92void ReportHeader(/* struct lemon * */);
93void CompressTables(/* struct lemon * */);
drhada354d2005-11-05 15:03:59 +000094void ResortStates(/* struct lemon * */);
drh75897232000-05-29 14:26:00 +000095
96/********** From the file "set.h" ****************************************/
97void SetSize(/* int N */); /* All sets will be of size N */
98char *SetNew(/* void */); /* A new set for element 0..N */
99void SetFree(/* char* */); /* Deallocate a set */
100
101int SetAdd(/* char*,int */); /* Add element to a set */
102int SetUnion(/* char *A,char *B */); /* A <- A U B, thru element N */
103
104#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
105
106/********** From the file "struct.h" *************************************/
107/*
108** Principal data structures for the LEMON parser generator.
109*/
110
drhaa9f1122007-08-23 02:50:56 +0000111typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000112
113/* Symbols (terminals and nonterminals) of the grammar are stored
114** in the following: */
115struct symbol {
116 char *name; /* Name of the symbol */
117 int index; /* Index number for this symbol */
118 enum {
119 TERMINAL,
drhfd405312005-11-06 04:06:59 +0000120 NONTERMINAL,
121 MULTITERMINAL
drh75897232000-05-29 14:26:00 +0000122 } type; /* Symbols are all either TERMINALS or NTs */
123 struct rule *rule; /* Linked list of rules of this (if an NT) */
drh0bd1f4e2002-06-06 18:54:39 +0000124 struct symbol *fallback; /* fallback token in case this token doesn't parse */
drh75897232000-05-29 14:26:00 +0000125 int prec; /* Precedence if defined (-1 otherwise) */
126 enum e_assoc {
127 LEFT,
128 RIGHT,
129 NONE,
130 UNK
131 } assoc; /* Associativity if predecence is defined */
132 char *firstset; /* First-set for all rules of this symbol */
133 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000134 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000135 char *destructor; /* Code which executes whenever this symbol is
136 ** popped from the stack during error processing */
drh75897232000-05-29 14:26:00 +0000137 char *datatype; /* The data type of information held by this
138 ** object. Only used if type==NONTERMINAL */
139 int dtnum; /* The data type number. In the parser, the value
140 ** stack is a union. The .yy%d element of this
141 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000142 /* The following fields are used by MULTITERMINALs only */
143 int nsubsym; /* Number of constituent symbols in the MULTI */
144 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000145};
146
147/* Each production rule in the grammar is stored in the following
148** structure. */
149struct rule {
150 struct symbol *lhs; /* Left-hand side of the rule */
151 char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000152 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000153 int ruleline; /* Line number for the rule */
154 int nrhs; /* Number of RHS symbols */
155 struct symbol **rhs; /* The RHS symbols */
156 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
157 int line; /* Line number at which code begins */
158 char *code; /* The code executed when this rule is reduced */
159 struct symbol *precsym; /* Precedence symbol for this rule */
160 int index; /* An index number for this rule */
161 Boolean canReduce; /* True if this rule is ever reduced */
162 struct rule *nextlhs; /* Next rule with the same LHS */
163 struct rule *next; /* Next rule in the global list */
164};
165
166/* A configuration is a production rule of the grammar together with
167** a mark (dot) showing how much of that rule has been processed so far.
168** Configurations also contain a follow-set which is a list of terminal
169** symbols which are allowed to immediately follow the end of the rule.
170** Every configuration is recorded as an instance of the following: */
171struct config {
172 struct rule *rp; /* The rule upon which the configuration is based */
173 int dot; /* The parse point */
174 char *fws; /* Follow-set for this configuration only */
175 struct plink *fplp; /* Follow-set forward propagation links */
176 struct plink *bplp; /* Follow-set backwards propagation links */
177 struct state *stp; /* Pointer to state which contains this */
178 enum {
179 COMPLETE, /* The status is used during followset and */
180 INCOMPLETE /* shift computations */
181 } status;
182 struct config *next; /* Next configuration in the state */
183 struct config *bp; /* The next basis configuration */
184};
185
186/* Every shift or reduce operation is stored as one of the following */
187struct action {
188 struct symbol *sp; /* The look-ahead symbol */
189 enum e_action {
190 SHIFT,
191 ACCEPT,
192 REDUCE,
193 ERROR,
drh9892c5d2007-12-21 00:02:11 +0000194 SSCONFLICT, /* A shift/shift conflict */
195 SRCONFLICT, /* Was a reduce, but part of a conflict */
196 RRCONFLICT, /* Was a reduce, but part of a conflict */
drh75897232000-05-29 14:26:00 +0000197 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
198 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
199 NOT_USED /* Deleted by compression */
200 } type;
201 union {
202 struct state *stp; /* The new state, if a shift */
203 struct rule *rp; /* The rule, if a reduce */
204 } x;
205 struct action *next; /* Next action for this state */
206 struct action *collide; /* Next action with the same hash */
207};
208
209/* Each state of the generated parser's finite state machine
210** is encoded as an instance of the following structure. */
211struct state {
212 struct config *bp; /* The basis configurations for this state */
213 struct config *cfp; /* All configurations in this set */
drhada354d2005-11-05 15:03:59 +0000214 int statenum; /* Sequencial number for this state */
drh75897232000-05-29 14:26:00 +0000215 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000216 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
217 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
218 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000219};
drh8b582012003-10-21 13:16:03 +0000220#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000221
222/* A followset propagation link indicates that the contents of one
223** configuration followset should be propagated to another whenever
224** the first changes. */
225struct plink {
226 struct config *cfp; /* The configuration to which linked */
227 struct plink *next; /* The next propagate link */
228};
229
230/* The state vector for the entire parser generator is recorded as
231** follows. (LEMON uses no global variables and makes little use of
232** static variables. Fields in the following structure can be thought
233** of as begin global variables in the program.) */
234struct lemon {
235 struct state **sorted; /* Table of states sorted by state number */
236 struct rule *rule; /* List of all rules */
237 int nstate; /* Number of states */
238 int nrule; /* Number of rules */
239 int nsymbol; /* Number of terminal and nonterminal symbols */
240 int nterminal; /* Number of terminal symbols */
241 struct symbol **symbols; /* Sorted array of pointers to symbols */
242 int errorcnt; /* Number of errors */
243 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000244 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000245 char *name; /* Name of the generated parser */
246 char *arg; /* Declaration of the 3th argument to parser */
247 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000248 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000249 char *start; /* Name of the start symbol for the grammar */
250 char *stacksize; /* Size of the parser stack */
251 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000252 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000253 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000254 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000255 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000256 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000257 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000258 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000259 char *filename; /* Name of the input file */
260 char *outname; /* Name of the current output file */
261 char *tokenprefix; /* A prefix added to token names in the .h file */
262 int nconflict; /* Number of parsing conflicts */
263 int tablesize; /* Size of the parse tables */
264 int basisflag; /* Print only basis configurations */
drh0bd1f4e2002-06-06 18:54:39 +0000265 int has_fallback; /* True if any %fallback is seen in the grammer */
drh75897232000-05-29 14:26:00 +0000266 char *argv0; /* Name of the program */
267};
268
269#define MemoryCheck(X) if((X)==0){ \
270 extern void memory_error(); \
271 memory_error(); \
272}
273
274/**************** From the file "table.h" *********************************/
275/*
276** All code in this file has been automatically generated
277** from a specification in the file
278** "table.q"
279** by the associative array code building program "aagen".
280** Do not edit this file! Instead, edit the specification
281** file, then rerun aagen.
282*/
283/*
284** Code for processing tables in the LEMON parser generator.
285*/
286
287/* Routines for handling a strings */
288
289char *Strsafe();
290
291void Strsafe_init(/* void */);
292int Strsafe_insert(/* char * */);
293char *Strsafe_find(/* char * */);
294
295/* Routines for handling symbols of the grammar */
296
297struct symbol *Symbol_new();
298int Symbolcmpp(/* struct symbol **, struct symbol ** */);
299void Symbol_init(/* void */);
300int Symbol_insert(/* struct symbol *, char * */);
301struct symbol *Symbol_find(/* char * */);
302struct symbol *Symbol_Nth(/* int */);
303int Symbol_count(/* */);
304struct symbol **Symbol_arrayof(/* */);
305
306/* Routines to manage the state table */
307
308int Configcmp(/* struct config *, struct config * */);
309struct state *State_new();
310void State_init(/* void */);
311int State_insert(/* struct state *, struct config * */);
312struct state *State_find(/* struct config * */);
313struct state **State_arrayof(/* */);
314
315/* Routines used for efficiency in Configlist_add */
316
317void Configtable_init(/* void */);
318int Configtable_insert(/* struct config * */);
319struct config *Configtable_find(/* struct config * */);
320void Configtable_clear(/* int(*)(struct config *) */);
321/****************** From the file "action.c" *******************************/
322/*
323** Routines processing parser actions in the LEMON parser generator.
324*/
325
326/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000327static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000328 static struct action *freelist = 0;
329 struct action *new;
330
331 if( freelist==0 ){
332 int i;
333 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000334 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000335 if( freelist==0 ){
336 fprintf(stderr,"Unable to allocate memory for a new parser action.");
337 exit(1);
338 }
339 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
340 freelist[amt-1].next = 0;
341 }
342 new = freelist;
343 freelist = freelist->next;
344 return new;
345}
346
drhe9278182007-07-18 18:16:29 +0000347/* Compare two actions for sorting purposes. Return negative, zero, or
348** positive if the first action is less than, equal to, or greater than
349** the first
350*/
351static int actioncmp(
352 struct action *ap1,
353 struct action *ap2
354){
drh75897232000-05-29 14:26:00 +0000355 int rc;
356 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000357 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000358 rc = (int)ap1->type - (int)ap2->type;
359 }
360 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000361 rc = ap1->x.rp->index - ap2->x.rp->index;
362 }
363 return rc;
364}
365
366/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000367static struct action *Action_sort(
368 struct action *ap
369){
370 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
371 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000372 return ap;
373}
374
375void Action_add(app,type,sp,arg)
376struct action **app;
377enum e_action type;
378struct symbol *sp;
379char *arg;
380{
381 struct action *new;
382 new = Action_new();
383 new->next = *app;
384 *app = new;
385 new->type = type;
386 new->sp = sp;
387 if( type==SHIFT ){
388 new->x.stp = (struct state *)arg;
389 }else{
390 new->x.rp = (struct rule *)arg;
391 }
392}
drh8b582012003-10-21 13:16:03 +0000393/********************** New code to implement the "acttab" module ***********/
394/*
395** This module implements routines use to construct the yy_action[] table.
396*/
397
398/*
399** The state of the yy_action table under construction is an instance of
400** the following structure
401*/
402typedef struct acttab acttab;
403struct acttab {
404 int nAction; /* Number of used slots in aAction[] */
405 int nActionAlloc; /* Slots allocated for aAction[] */
406 struct {
407 int lookahead; /* Value of the lookahead token */
408 int action; /* Action to take on the given lookahead */
409 } *aAction, /* The yy_action[] table under construction */
410 *aLookahead; /* A single new transaction set */
411 int mnLookahead; /* Minimum aLookahead[].lookahead */
412 int mnAction; /* Action associated with mnLookahead */
413 int mxLookahead; /* Maximum aLookahead[].lookahead */
414 int nLookahead; /* Used slots in aLookahead[] */
415 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
416};
417
418/* Return the number of entries in the yy_action table */
419#define acttab_size(X) ((X)->nAction)
420
421/* The value for the N-th entry in yy_action */
422#define acttab_yyaction(X,N) ((X)->aAction[N].action)
423
424/* The value for the N-th entry in yy_lookahead */
425#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
426
427/* Free all memory associated with the given acttab */
428void acttab_free(acttab *p){
429 free( p->aAction );
430 free( p->aLookahead );
431 free( p );
432}
433
434/* Allocate a new acttab structure */
435acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000436 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000437 if( p==0 ){
438 fprintf(stderr,"Unable to allocate memory for a new acttab.");
439 exit(1);
440 }
441 memset(p, 0, sizeof(*p));
442 return p;
443}
444
445/* Add a new action to the current transaction set
446*/
447void acttab_action(acttab *p, int lookahead, int action){
448 if( p->nLookahead>=p->nLookaheadAlloc ){
449 p->nLookaheadAlloc += 25;
450 p->aLookahead = realloc( p->aLookahead,
451 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
452 if( p->aLookahead==0 ){
453 fprintf(stderr,"malloc failed\n");
454 exit(1);
455 }
456 }
457 if( p->nLookahead==0 ){
458 p->mxLookahead = lookahead;
459 p->mnLookahead = lookahead;
460 p->mnAction = action;
461 }else{
462 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
463 if( p->mnLookahead>lookahead ){
464 p->mnLookahead = lookahead;
465 p->mnAction = action;
466 }
467 }
468 p->aLookahead[p->nLookahead].lookahead = lookahead;
469 p->aLookahead[p->nLookahead].action = action;
470 p->nLookahead++;
471}
472
473/*
474** Add the transaction set built up with prior calls to acttab_action()
475** into the current action table. Then reset the transaction set back
476** to an empty set in preparation for a new round of acttab_action() calls.
477**
478** Return the offset into the action table of the new transaction.
479*/
480int acttab_insert(acttab *p){
481 int i, j, k, n;
482 assert( p->nLookahead>0 );
483
484 /* Make sure we have enough space to hold the expanded action table
485 ** in the worst case. The worst case occurs if the transaction set
486 ** must be appended to the current action table
487 */
drh784d86f2004-02-19 18:41:53 +0000488 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000489 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000490 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000491 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
492 p->aAction = realloc( p->aAction,
493 sizeof(p->aAction[0])*p->nActionAlloc);
494 if( p->aAction==0 ){
495 fprintf(stderr,"malloc failed\n");
496 exit(1);
497 }
drhfdbf9282003-10-21 16:34:41 +0000498 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000499 p->aAction[i].lookahead = -1;
500 p->aAction[i].action = -1;
501 }
502 }
503
504 /* Scan the existing action table looking for an offset where we can
505 ** insert the current transaction set. Fall out of the loop when that
506 ** offset is found. In the worst case, we fall out of the loop when
507 ** i reaches p->nAction, which means we append the new transaction set.
508 **
509 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
510 */
drh784d86f2004-02-19 18:41:53 +0000511 for(i=0; i<p->nAction+p->mnLookahead; i++){
drh8b582012003-10-21 13:16:03 +0000512 if( p->aAction[i].lookahead<0 ){
513 for(j=0; j<p->nLookahead; j++){
514 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
515 if( k<0 ) break;
516 if( p->aAction[k].lookahead>=0 ) break;
517 }
drhfdbf9282003-10-21 16:34:41 +0000518 if( j<p->nLookahead ) continue;
519 for(j=0; j<p->nAction; j++){
520 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
521 }
522 if( j==p->nAction ){
523 break; /* Fits in empty slots */
524 }
drh8b582012003-10-21 13:16:03 +0000525 }else if( p->aAction[i].lookahead==p->mnLookahead ){
526 if( p->aAction[i].action!=p->mnAction ) continue;
527 for(j=0; j<p->nLookahead; j++){
528 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
529 if( k<0 || k>=p->nAction ) break;
530 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
531 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
532 }
533 if( j<p->nLookahead ) continue;
534 n = 0;
535 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000536 if( p->aAction[j].lookahead<0 ) continue;
537 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000538 }
drhfdbf9282003-10-21 16:34:41 +0000539 if( n==p->nLookahead ){
540 break; /* Same as a prior transaction set */
541 }
drh8b582012003-10-21 13:16:03 +0000542 }
543 }
544 /* Insert transaction set at index i. */
545 for(j=0; j<p->nLookahead; j++){
546 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
547 p->aAction[k] = p->aLookahead[j];
548 if( k>=p->nAction ) p->nAction = k+1;
549 }
550 p->nLookahead = 0;
551
552 /* Return the offset that is added to the lookahead in order to get the
553 ** index into yy_action of the action */
554 return i - p->mnLookahead;
555}
556
drh75897232000-05-29 14:26:00 +0000557/********************** From the file "build.c" *****************************/
558/*
559** Routines to construction the finite state machine for the LEMON
560** parser generator.
561*/
562
563/* Find a precedence symbol of every rule in the grammar.
564**
565** Those rules which have a precedence symbol coded in the input
566** grammar using the "[symbol]" construct will already have the
567** rp->precsym field filled. Other rules take as their precedence
568** symbol the first RHS symbol with a defined precedence. If there
569** are not RHS symbols with a defined precedence, the precedence
570** symbol field is left blank.
571*/
572void FindRulePrecedences(xp)
573struct lemon *xp;
574{
575 struct rule *rp;
576 for(rp=xp->rule; rp; rp=rp->next){
577 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000578 int i, j;
579 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
580 struct symbol *sp = rp->rhs[i];
581 if( sp->type==MULTITERMINAL ){
582 for(j=0; j<sp->nsubsym; j++){
583 if( sp->subsym[j]->prec>=0 ){
584 rp->precsym = sp->subsym[j];
585 break;
586 }
587 }
588 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000589 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000590 }
591 }
592 }
593 }
594 return;
595}
596
597/* Find all nonterminals which will generate the empty string.
598** Then go back and compute the first sets of every nonterminal.
599** The first set is the set of all terminal symbols which can begin
600** a string generated by that nonterminal.
601*/
602void FindFirstSets(lemp)
603struct lemon *lemp;
604{
drhfd405312005-11-06 04:06:59 +0000605 int i, j;
drh75897232000-05-29 14:26:00 +0000606 struct rule *rp;
607 int progress;
608
609 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000610 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000611 }
612 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
613 lemp->symbols[i]->firstset = SetNew();
614 }
615
616 /* First compute all lambdas */
617 do{
618 progress = 0;
619 for(rp=lemp->rule; rp; rp=rp->next){
620 if( rp->lhs->lambda ) continue;
621 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000622 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000623 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000624 }
625 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000626 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000627 progress = 1;
628 }
629 }
630 }while( progress );
631
632 /* Now compute all first sets */
633 do{
634 struct symbol *s1, *s2;
635 progress = 0;
636 for(rp=lemp->rule; rp; rp=rp->next){
637 s1 = rp->lhs;
638 for(i=0; i<rp->nrhs; i++){
639 s2 = rp->rhs[i];
640 if( s2->type==TERMINAL ){
641 progress += SetAdd(s1->firstset,s2->index);
642 break;
drhfd405312005-11-06 04:06:59 +0000643 }else if( s2->type==MULTITERMINAL ){
644 for(j=0; j<s2->nsubsym; j++){
645 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
646 }
647 break;
drh75897232000-05-29 14:26:00 +0000648 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000649 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000650 }else{
651 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000652 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000653 }
654 }
655 }
656 }while( progress );
657 return;
658}
659
660/* Compute all LR(0) states for the grammar. Links
661** are added to between some states so that the LR(1) follow sets
662** can be computed later.
663*/
664PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
665void FindStates(lemp)
666struct lemon *lemp;
667{
668 struct symbol *sp;
669 struct rule *rp;
670
671 Configlist_init();
672
673 /* Find the start symbol */
674 if( lemp->start ){
675 sp = Symbol_find(lemp->start);
676 if( sp==0 ){
677 ErrorMsg(lemp->filename,0,
678"The specified start symbol \"%s\" is not \
679in a nonterminal of the grammar. \"%s\" will be used as the start \
680symbol instead.",lemp->start,lemp->rule->lhs->name);
681 lemp->errorcnt++;
682 sp = lemp->rule->lhs;
683 }
684 }else{
685 sp = lemp->rule->lhs;
686 }
687
688 /* Make sure the start symbol doesn't occur on the right-hand side of
689 ** any rule. Report an error if it does. (YACC would generate a new
690 ** start symbol in this case.) */
691 for(rp=lemp->rule; rp; rp=rp->next){
692 int i;
693 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000694 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000695 ErrorMsg(lemp->filename,0,
696"The start symbol \"%s\" occurs on the \
697right-hand side of a rule. This will result in a parser which \
698does not work properly.",sp->name);
699 lemp->errorcnt++;
700 }
701 }
702 }
703
704 /* The basis configuration set for the first state
705 ** is all rules which have the start symbol as their
706 ** left-hand side */
707 for(rp=sp->rule; rp; rp=rp->nextlhs){
708 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000709 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000710 newcfp = Configlist_addbasis(rp,0);
711 SetAdd(newcfp->fws,0);
712 }
713
714 /* Compute the first state. All other states will be
715 ** computed automatically during the computation of the first one.
716 ** The returned pointer to the first state is not used. */
717 (void)getstate(lemp);
718 return;
719}
720
721/* Return a pointer to a state which is described by the configuration
722** list which has been built from calls to Configlist_add.
723*/
724PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
725PRIVATE struct state *getstate(lemp)
726struct lemon *lemp;
727{
728 struct config *cfp, *bp;
729 struct state *stp;
730
731 /* Extract the sorted basis of the new state. The basis was constructed
732 ** by prior calls to "Configlist_addbasis()". */
733 Configlist_sortbasis();
734 bp = Configlist_basis();
735
736 /* Get a state with the same basis */
737 stp = State_find(bp);
738 if( stp ){
739 /* A state with the same basis already exists! Copy all the follow-set
740 ** propagation links from the state under construction into the
741 ** preexisting state, then return a pointer to the preexisting state */
742 struct config *x, *y;
743 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
744 Plink_copy(&y->bplp,x->bplp);
745 Plink_delete(x->fplp);
746 x->fplp = x->bplp = 0;
747 }
748 cfp = Configlist_return();
749 Configlist_eat(cfp);
750 }else{
751 /* This really is a new state. Construct all the details */
752 Configlist_closure(lemp); /* Compute the configuration closure */
753 Configlist_sort(); /* Sort the configuration closure */
754 cfp = Configlist_return(); /* Get a pointer to the config list */
755 stp = State_new(); /* A new state structure */
756 MemoryCheck(stp);
757 stp->bp = bp; /* Remember the configuration basis */
758 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000759 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000760 stp->ap = 0; /* No actions, yet. */
761 State_insert(stp,stp->bp); /* Add to the state table */
762 buildshifts(lemp,stp); /* Recursively compute successor states */
763 }
764 return stp;
765}
766
drhfd405312005-11-06 04:06:59 +0000767/*
768** Return true if two symbols are the same.
769*/
770int same_symbol(a,b)
771struct symbol *a;
772struct symbol *b;
773{
774 int i;
775 if( a==b ) return 1;
776 if( a->type!=MULTITERMINAL ) return 0;
777 if( b->type!=MULTITERMINAL ) return 0;
778 if( a->nsubsym!=b->nsubsym ) return 0;
779 for(i=0; i<a->nsubsym; i++){
780 if( a->subsym[i]!=b->subsym[i] ) return 0;
781 }
782 return 1;
783}
784
drh75897232000-05-29 14:26:00 +0000785/* Construct all successor states to the given state. A "successor"
786** state is any state which can be reached by a shift action.
787*/
788PRIVATE void buildshifts(lemp,stp)
789struct lemon *lemp;
790struct state *stp; /* The state from which successors are computed */
791{
792 struct config *cfp; /* For looping thru the config closure of "stp" */
793 struct config *bcfp; /* For the inner loop on config closure of "stp" */
794 struct config *new; /* */
795 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
796 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
797 struct state *newstp; /* A pointer to a successor state */
798
799 /* Each configuration becomes complete after it contibutes to a successor
800 ** state. Initially, all configurations are incomplete */
801 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
802
803 /* Loop through all configurations of the state "stp" */
804 for(cfp=stp->cfp; cfp; cfp=cfp->next){
805 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
806 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
807 Configlist_reset(); /* Reset the new config set */
808 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
809
810 /* For every configuration in the state "stp" which has the symbol "sp"
811 ** following its dot, add the same configuration to the basis set under
812 ** construction but with the dot shifted one symbol to the right. */
813 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
814 if( bcfp->status==COMPLETE ) continue; /* Already used */
815 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
816 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000817 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000818 bcfp->status = COMPLETE; /* Mark this config as used */
819 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
820 Plink_add(&new->bplp,bcfp);
821 }
822
823 /* Get a pointer to the state described by the basis configuration set
824 ** constructed in the preceding loop */
825 newstp = getstate(lemp);
826
827 /* The state "newstp" is reached from the state "stp" by a shift action
828 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000829 if( sp->type==MULTITERMINAL ){
830 int i;
831 for(i=0; i<sp->nsubsym; i++){
832 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
833 }
834 }else{
835 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
836 }
drh75897232000-05-29 14:26:00 +0000837 }
838}
839
840/*
841** Construct the propagation links
842*/
843void FindLinks(lemp)
844struct lemon *lemp;
845{
846 int i;
847 struct config *cfp, *other;
848 struct state *stp;
849 struct plink *plp;
850
851 /* Housekeeping detail:
852 ** Add to every propagate link a pointer back to the state to
853 ** which the link is attached. */
854 for(i=0; i<lemp->nstate; i++){
855 stp = lemp->sorted[i];
856 for(cfp=stp->cfp; cfp; cfp=cfp->next){
857 cfp->stp = stp;
858 }
859 }
860
861 /* Convert all backlinks into forward links. Only the forward
862 ** links are used in the follow-set computation. */
863 for(i=0; i<lemp->nstate; i++){
864 stp = lemp->sorted[i];
865 for(cfp=stp->cfp; cfp; cfp=cfp->next){
866 for(plp=cfp->bplp; plp; plp=plp->next){
867 other = plp->cfp;
868 Plink_add(&other->fplp,cfp);
869 }
870 }
871 }
872}
873
874/* Compute all followsets.
875**
876** A followset is the set of all symbols which can come immediately
877** after a configuration.
878*/
879void FindFollowSets(lemp)
880struct lemon *lemp;
881{
882 int i;
883 struct config *cfp;
884 struct plink *plp;
885 int progress;
886 int change;
887
888 for(i=0; i<lemp->nstate; i++){
889 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
890 cfp->status = INCOMPLETE;
891 }
892 }
893
894 do{
895 progress = 0;
896 for(i=0; i<lemp->nstate; i++){
897 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
898 if( cfp->status==COMPLETE ) continue;
899 for(plp=cfp->fplp; plp; plp=plp->next){
900 change = SetUnion(plp->cfp->fws,cfp->fws);
901 if( change ){
902 plp->cfp->status = INCOMPLETE;
903 progress = 1;
904 }
905 }
906 cfp->status = COMPLETE;
907 }
908 }
909 }while( progress );
910}
911
912static int resolve_conflict();
913
914/* Compute the reduce actions, and resolve conflicts.
915*/
916void FindActions(lemp)
917struct lemon *lemp;
918{
919 int i,j;
920 struct config *cfp;
921 struct state *stp;
922 struct symbol *sp;
923 struct rule *rp;
924
925 /* Add all of the reduce actions
926 ** A reduce action is added for each element of the followset of
927 ** a configuration which has its dot at the extreme right.
928 */
929 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
930 stp = lemp->sorted[i];
931 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
932 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
933 for(j=0; j<lemp->nterminal; j++){
934 if( SetFind(cfp->fws,j) ){
935 /* Add a reduce action to the state "stp" which will reduce by the
936 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000937 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000938 }
939 }
940 }
941 }
942 }
943
944 /* Add the accepting token */
945 if( lemp->start ){
946 sp = Symbol_find(lemp->start);
947 if( sp==0 ) sp = lemp->rule->lhs;
948 }else{
949 sp = lemp->rule->lhs;
950 }
951 /* Add to the first state (which is always the starting state of the
952 ** finite state machine) an action to ACCEPT if the lookahead is the
953 ** start nonterminal. */
954 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
955
956 /* Resolve conflicts */
957 for(i=0; i<lemp->nstate; i++){
958 struct action *ap, *nap;
959 struct state *stp;
960 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000961 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000962 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000963 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000964 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
965 /* The two actions "ap" and "nap" have the same lookahead.
966 ** Figure out which one should be used */
967 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
968 }
969 }
970 }
971
972 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000973 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000974 for(i=0; i<lemp->nstate; i++){
975 struct action *ap;
976 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000977 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000978 }
979 }
980 for(rp=lemp->rule; rp; rp=rp->next){
981 if( rp->canReduce ) continue;
982 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
983 lemp->errorcnt++;
984 }
985}
986
987/* Resolve a conflict between the two given actions. If the
988** conflict can't be resolve, return non-zero.
989**
990** NO LONGER TRUE:
991** To resolve a conflict, first look to see if either action
992** is on an error rule. In that case, take the action which
993** is not associated with the error rule. If neither or both
994** actions are associated with an error rule, then try to
995** use precedence to resolve the conflict.
996**
997** If either action is a SHIFT, then it must be apx. This
998** function won't work if apx->type==REDUCE and apy->type==SHIFT.
999*/
1000static int resolve_conflict(apx,apy,errsym)
1001struct action *apx;
1002struct action *apy;
1003struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1004{
1005 struct symbol *spx, *spy;
1006 int errcnt = 0;
1007 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001008 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001009 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001010 errcnt++;
1011 }
drh75897232000-05-29 14:26:00 +00001012 if( apx->type==SHIFT && apy->type==REDUCE ){
1013 spx = apx->sp;
1014 spy = apy->x.rp->precsym;
1015 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1016 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001017 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001018 errcnt++;
1019 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1020 apy->type = RD_RESOLVED;
1021 }else if( spx->prec<spy->prec ){
1022 apx->type = SH_RESOLVED;
1023 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1024 apy->type = RD_RESOLVED; /* associativity */
1025 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1026 apx->type = SH_RESOLVED;
1027 }else{
1028 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001029 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001030 errcnt++;
1031 }
1032 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1033 spx = apx->x.rp->precsym;
1034 spy = apy->x.rp->precsym;
1035 if( spx==0 || spy==0 || spx->prec<0 ||
1036 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001037 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001038 errcnt++;
1039 }else if( spx->prec>spy->prec ){
1040 apy->type = RD_RESOLVED;
1041 }else if( spx->prec<spy->prec ){
1042 apx->type = RD_RESOLVED;
1043 }
1044 }else{
drhb59499c2002-02-23 18:45:13 +00001045 assert(
1046 apx->type==SH_RESOLVED ||
1047 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001048 apx->type==SSCONFLICT ||
1049 apx->type==SRCONFLICT ||
1050 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001051 apy->type==SH_RESOLVED ||
1052 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001053 apy->type==SSCONFLICT ||
1054 apy->type==SRCONFLICT ||
1055 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001056 );
1057 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1058 ** REDUCEs on the list. If we reach this point it must be because
1059 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001060 }
1061 return errcnt;
1062}
1063/********************* From the file "configlist.c" *************************/
1064/*
1065** Routines to processing a configuration list and building a state
1066** in the LEMON parser generator.
1067*/
1068
1069static struct config *freelist = 0; /* List of free configurations */
1070static struct config *current = 0; /* Top of list of configurations */
1071static struct config **currentend = 0; /* Last on list of configs */
1072static struct config *basis = 0; /* Top of list of basis configs */
1073static struct config **basisend = 0; /* End of list of basis configs */
1074
1075/* Return a pointer to a new configuration */
1076PRIVATE struct config *newconfig(){
1077 struct config *new;
1078 if( freelist==0 ){
1079 int i;
1080 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001081 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001082 if( freelist==0 ){
1083 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1084 exit(1);
1085 }
1086 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1087 freelist[amt-1].next = 0;
1088 }
1089 new = freelist;
1090 freelist = freelist->next;
1091 return new;
1092}
1093
1094/* The configuration "old" is no longer used */
1095PRIVATE void deleteconfig(old)
1096struct config *old;
1097{
1098 old->next = freelist;
1099 freelist = old;
1100}
1101
1102/* Initialized the configuration list builder */
1103void Configlist_init(){
1104 current = 0;
1105 currentend = &current;
1106 basis = 0;
1107 basisend = &basis;
1108 Configtable_init();
1109 return;
1110}
1111
1112/* Initialized the configuration list builder */
1113void Configlist_reset(){
1114 current = 0;
1115 currentend = &current;
1116 basis = 0;
1117 basisend = &basis;
1118 Configtable_clear(0);
1119 return;
1120}
1121
1122/* Add another configuration to the configuration list */
1123struct config *Configlist_add(rp,dot)
1124struct rule *rp; /* The rule */
1125int dot; /* Index into the RHS of the rule where the dot goes */
1126{
1127 struct config *cfp, model;
1128
1129 assert( currentend!=0 );
1130 model.rp = rp;
1131 model.dot = dot;
1132 cfp = Configtable_find(&model);
1133 if( cfp==0 ){
1134 cfp = newconfig();
1135 cfp->rp = rp;
1136 cfp->dot = dot;
1137 cfp->fws = SetNew();
1138 cfp->stp = 0;
1139 cfp->fplp = cfp->bplp = 0;
1140 cfp->next = 0;
1141 cfp->bp = 0;
1142 *currentend = cfp;
1143 currentend = &cfp->next;
1144 Configtable_insert(cfp);
1145 }
1146 return cfp;
1147}
1148
1149/* Add a basis configuration to the configuration list */
1150struct config *Configlist_addbasis(rp,dot)
1151struct rule *rp;
1152int dot;
1153{
1154 struct config *cfp, model;
1155
1156 assert( basisend!=0 );
1157 assert( currentend!=0 );
1158 model.rp = rp;
1159 model.dot = dot;
1160 cfp = Configtable_find(&model);
1161 if( cfp==0 ){
1162 cfp = newconfig();
1163 cfp->rp = rp;
1164 cfp->dot = dot;
1165 cfp->fws = SetNew();
1166 cfp->stp = 0;
1167 cfp->fplp = cfp->bplp = 0;
1168 cfp->next = 0;
1169 cfp->bp = 0;
1170 *currentend = cfp;
1171 currentend = &cfp->next;
1172 *basisend = cfp;
1173 basisend = &cfp->bp;
1174 Configtable_insert(cfp);
1175 }
1176 return cfp;
1177}
1178
1179/* Compute the closure of the configuration list */
1180void Configlist_closure(lemp)
1181struct lemon *lemp;
1182{
1183 struct config *cfp, *newcfp;
1184 struct rule *rp, *newrp;
1185 struct symbol *sp, *xsp;
1186 int i, dot;
1187
1188 assert( currentend!=0 );
1189 for(cfp=current; cfp; cfp=cfp->next){
1190 rp = cfp->rp;
1191 dot = cfp->dot;
1192 if( dot>=rp->nrhs ) continue;
1193 sp = rp->rhs[dot];
1194 if( sp->type==NONTERMINAL ){
1195 if( sp->rule==0 && sp!=lemp->errsym ){
1196 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1197 sp->name);
1198 lemp->errorcnt++;
1199 }
1200 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1201 newcfp = Configlist_add(newrp,0);
1202 for(i=dot+1; i<rp->nrhs; i++){
1203 xsp = rp->rhs[i];
1204 if( xsp->type==TERMINAL ){
1205 SetAdd(newcfp->fws,xsp->index);
1206 break;
drhfd405312005-11-06 04:06:59 +00001207 }else if( xsp->type==MULTITERMINAL ){
1208 int k;
1209 for(k=0; k<xsp->nsubsym; k++){
1210 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1211 }
1212 break;
drh75897232000-05-29 14:26:00 +00001213 }else{
1214 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001215 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001216 }
1217 }
1218 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1219 }
1220 }
1221 }
1222 return;
1223}
1224
1225/* Sort the configuration list */
1226void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001227 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001228 currentend = 0;
1229 return;
1230}
1231
1232/* Sort the basis configuration list */
1233void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001234 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001235 basisend = 0;
1236 return;
1237}
1238
1239/* Return a pointer to the head of the configuration list and
1240** reset the list */
1241struct config *Configlist_return(){
1242 struct config *old;
1243 old = current;
1244 current = 0;
1245 currentend = 0;
1246 return old;
1247}
1248
1249/* Return a pointer to the head of the configuration list and
1250** reset the list */
1251struct config *Configlist_basis(){
1252 struct config *old;
1253 old = basis;
1254 basis = 0;
1255 basisend = 0;
1256 return old;
1257}
1258
1259/* Free all elements of the given configuration list */
1260void Configlist_eat(cfp)
1261struct config *cfp;
1262{
1263 struct config *nextcfp;
1264 for(; cfp; cfp=nextcfp){
1265 nextcfp = cfp->next;
1266 assert( cfp->fplp==0 );
1267 assert( cfp->bplp==0 );
1268 if( cfp->fws ) SetFree(cfp->fws);
1269 deleteconfig(cfp);
1270 }
1271 return;
1272}
1273/***************** From the file "error.c" *********************************/
1274/*
1275** Code for printing error message.
1276*/
1277
1278/* Find a good place to break "msg" so that its length is at least "min"
1279** but no more than "max". Make the point as close to max as possible.
1280*/
1281static int findbreak(msg,min,max)
1282char *msg;
1283int min;
1284int max;
1285{
1286 int i,spot;
1287 char c;
1288 for(i=spot=min; i<=max; i++){
1289 c = msg[i];
1290 if( c=='\t' ) msg[i] = ' ';
1291 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1292 if( c==0 ){ spot = i; break; }
1293 if( c=='-' && i<max-1 ) spot = i+1;
1294 if( c==' ' ) spot = i;
1295 }
1296 return spot;
1297}
1298
1299/*
1300** The error message is split across multiple lines if necessary. The
1301** splits occur at a space, if there is a space available near the end
1302** of the line.
1303*/
1304#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1305#define LINEWIDTH 79 /* Max width of any output line */
1306#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001307void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001308 char errmsg[ERRMSGSIZE];
1309 char prefix[PREFIXLIMIT+10];
1310 int errmsgsize;
1311 int prefixsize;
1312 int availablewidth;
1313 va_list ap;
1314 int end, restart, base;
1315
drhf9a2e7b2003-04-15 01:49:48 +00001316 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001317 /* Prepare a prefix to be prepended to every output line */
1318 if( lineno>0 ){
1319 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1320 }else{
1321 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1322 }
1323 prefixsize = strlen(prefix);
1324 availablewidth = LINEWIDTH - prefixsize;
1325
1326 /* Generate the error message */
1327 vsprintf(errmsg,format,ap);
1328 va_end(ap);
1329 errmsgsize = strlen(errmsg);
1330 /* Remove trailing '\n's from the error message. */
1331 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1332 errmsg[--errmsgsize] = 0;
1333 }
1334
1335 /* Print the error message */
1336 base = 0;
1337 while( errmsg[base]!=0 ){
1338 end = restart = findbreak(&errmsg[base],0,availablewidth);
1339 restart += base;
1340 while( errmsg[restart]==' ' ) restart++;
1341 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1342 base = restart;
1343 }
1344}
1345/**************** From the file "main.c" ************************************/
1346/*
1347** Main program file for the LEMON parser generator.
1348*/
1349
1350/* Report an out-of-memory condition and abort. This function
1351** is used mostly by the "MemoryCheck" macro in struct.h
1352*/
1353void memory_error(){
1354 fprintf(stderr,"Out of memory. Aborting...\n");
1355 exit(1);
1356}
1357
drh6d08b4d2004-07-20 12:45:22 +00001358static int nDefine = 0; /* Number of -D options on the command line */
1359static char **azDefine = 0; /* Name of the -D macros */
1360
1361/* This routine is called with the argument to each -D command-line option.
1362** Add the macro defined to the azDefine array.
1363*/
1364static void handle_D_option(char *z){
1365 char **paz;
1366 nDefine++;
1367 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1368 if( azDefine==0 ){
1369 fprintf(stderr,"out of memory\n");
1370 exit(1);
1371 }
1372 paz = &azDefine[nDefine-1];
1373 *paz = malloc( strlen(z)+1 );
1374 if( *paz==0 ){
1375 fprintf(stderr,"out of memory\n");
1376 exit(1);
1377 }
1378 strcpy(*paz, z);
1379 for(z=*paz; *z && *z!='='; z++){}
1380 *z = 0;
1381}
1382
drh75897232000-05-29 14:26:00 +00001383
1384/* The main program. Parse the command line and do it... */
1385int main(argc,argv)
1386int argc;
1387char **argv;
1388{
1389 static int version = 0;
1390 static int rpflag = 0;
1391 static int basisflag = 0;
1392 static int compress = 0;
1393 static int quiet = 0;
1394 static int statistics = 0;
1395 static int mhflag = 0;
1396 static struct s_options options[] = {
1397 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1398 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001399 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001400 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1401 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1402 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001403 {OPT_FLAG, "s", (char*)&statistics,
1404 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001405 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1406 {OPT_FLAG,0,0,0}
1407 };
1408 int i;
1409 struct lemon lem;
1410
drhb0c86772000-06-02 23:21:26 +00001411 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001412 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001413 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001414 exit(0);
1415 }
drhb0c86772000-06-02 23:21:26 +00001416 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001417 fprintf(stderr,"Exactly one filename argument is required.\n");
1418 exit(1);
1419 }
drh954f6b42006-06-13 13:27:46 +00001420 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001421 lem.errorcnt = 0;
1422
1423 /* Initialize the machine */
1424 Strsafe_init();
1425 Symbol_init();
1426 State_init();
1427 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001428 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001429 lem.basisflag = basisflag;
drh75897232000-05-29 14:26:00 +00001430 Symbol_new("$");
1431 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001432 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001433
1434 /* Parse the input file */
1435 Parse(&lem);
1436 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001437 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001438 fprintf(stderr,"Empty grammar.\n");
1439 exit(1);
1440 }
1441
1442 /* Count and index the symbols of the grammar */
1443 lem.nsymbol = Symbol_count();
1444 Symbol_new("{default}");
1445 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001446 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001447 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1448 (int(*)())Symbolcmpp);
1449 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1450 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1451 lem.nterminal = i;
1452
1453 /* Generate a reprint of the grammar, if requested on the command line */
1454 if( rpflag ){
1455 Reprint(&lem);
1456 }else{
1457 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001458 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001459
1460 /* Find the precedence for every production rule (that has one) */
1461 FindRulePrecedences(&lem);
1462
1463 /* Compute the lambda-nonterminals and the first-sets for every
1464 ** nonterminal */
1465 FindFirstSets(&lem);
1466
1467 /* Compute all LR(0) states. Also record follow-set propagation
1468 ** links so that the follow-set can be computed later */
1469 lem.nstate = 0;
1470 FindStates(&lem);
1471 lem.sorted = State_arrayof();
1472
1473 /* Tie up loose ends on the propagation links */
1474 FindLinks(&lem);
1475
1476 /* Compute the follow set of every reducible configuration */
1477 FindFollowSets(&lem);
1478
1479 /* Compute the action tables */
1480 FindActions(&lem);
1481
1482 /* Compress the action tables */
1483 if( compress==0 ) CompressTables(&lem);
1484
drhada354d2005-11-05 15:03:59 +00001485 /* Reorder and renumber the states so that states with fewer choices
1486 ** occur at the end. */
1487 ResortStates(&lem);
1488
drh75897232000-05-29 14:26:00 +00001489 /* Generate a report of the parser generated. (the "y.output" file) */
1490 if( !quiet ) ReportOutput(&lem);
1491
1492 /* Generate the source code for the parser */
1493 ReportTable(&lem, mhflag);
1494
1495 /* Produce a header file for use by the scanner. (This step is
1496 ** omitted if the "-m" option is used because makeheaders will
1497 ** generate the file for us.) */
1498 if( !mhflag ) ReportHeader(&lem);
1499 }
1500 if( statistics ){
1501 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1502 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1503 printf(" %d states, %d parser table entries, %d conflicts\n",
1504 lem.nstate, lem.tablesize, lem.nconflict);
1505 }
1506 if( lem.nconflict ){
1507 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1508 }
1509 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001510 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001511}
1512/******************** From the file "msort.c" *******************************/
1513/*
1514** A generic merge-sort program.
1515**
1516** USAGE:
1517** Let "ptr" be a pointer to some structure which is at the head of
1518** a null-terminated list. Then to sort the list call:
1519**
1520** ptr = msort(ptr,&(ptr->next),cmpfnc);
1521**
1522** In the above, "cmpfnc" is a pointer to a function which compares
1523** two instances of the structure and returns an integer, as in
1524** strcmp. The second argument is a pointer to the pointer to the
1525** second element of the linked list. This address is used to compute
1526** the offset to the "next" field within the structure. The offset to
1527** the "next" field must be constant for all structures in the list.
1528**
1529** The function returns a new pointer which is the head of the list
1530** after sorting.
1531**
1532** ALGORITHM:
1533** Merge-sort.
1534*/
1535
1536/*
1537** Return a pointer to the next structure in the linked list.
1538*/
drhba99af52001-10-25 20:37:16 +00001539#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001540
1541/*
1542** Inputs:
1543** a: A sorted, null-terminated linked list. (May be null).
1544** b: A sorted, null-terminated linked list. (May be null).
1545** cmp: A pointer to the comparison function.
1546** offset: Offset in the structure to the "next" field.
1547**
1548** Return Value:
1549** A pointer to the head of a sorted list containing the elements
1550** of both a and b.
1551**
1552** Side effects:
1553** The "next" pointers for elements in the lists a and b are
1554** changed.
1555*/
drhe9278182007-07-18 18:16:29 +00001556static char *merge(
1557 char *a,
1558 char *b,
1559 int (*cmp)(const char*,const char*),
1560 int offset
1561){
drh75897232000-05-29 14:26:00 +00001562 char *ptr, *head;
1563
1564 if( a==0 ){
1565 head = b;
1566 }else if( b==0 ){
1567 head = a;
1568 }else{
1569 if( (*cmp)(a,b)<0 ){
1570 ptr = a;
1571 a = NEXT(a);
1572 }else{
1573 ptr = b;
1574 b = NEXT(b);
1575 }
1576 head = ptr;
1577 while( a && b ){
1578 if( (*cmp)(a,b)<0 ){
1579 NEXT(ptr) = a;
1580 ptr = a;
1581 a = NEXT(a);
1582 }else{
1583 NEXT(ptr) = b;
1584 ptr = b;
1585 b = NEXT(b);
1586 }
1587 }
1588 if( a ) NEXT(ptr) = a;
1589 else NEXT(ptr) = b;
1590 }
1591 return head;
1592}
1593
1594/*
1595** Inputs:
1596** list: Pointer to a singly-linked list of structures.
1597** next: Pointer to pointer to the second element of the list.
1598** cmp: A comparison function.
1599**
1600** Return Value:
1601** A pointer to the head of a sorted list containing the elements
1602** orginally in list.
1603**
1604** Side effects:
1605** The "next" pointers for elements in list are changed.
1606*/
1607#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001608static char *msort(
1609 char *list,
1610 char **next,
1611 int (*cmp)(const char*,const char*)
1612){
drhba99af52001-10-25 20:37:16 +00001613 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001614 char *ep;
1615 char *set[LISTSIZE];
1616 int i;
drhba99af52001-10-25 20:37:16 +00001617 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001618 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1619 while( list ){
1620 ep = list;
1621 list = NEXT(list);
1622 NEXT(ep) = 0;
1623 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1624 ep = merge(ep,set[i],cmp,offset);
1625 set[i] = 0;
1626 }
1627 set[i] = ep;
1628 }
1629 ep = 0;
1630 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1631 return ep;
1632}
1633/************************ From the file "option.c" **************************/
1634static char **argv;
1635static struct s_options *op;
1636static FILE *errstream;
1637
1638#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1639
1640/*
1641** Print the command line with a carrot pointing to the k-th character
1642** of the n-th field.
1643*/
1644static void errline(n,k,err)
1645int n;
1646int k;
1647FILE *err;
1648{
1649 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001650 if( argv[0] ) fprintf(err,"%s",argv[0]);
1651 spcnt = strlen(argv[0]) + 1;
1652 for(i=1; i<n && argv[i]; i++){
1653 fprintf(err," %s",argv[i]);
drhdc30dd32005-02-16 03:35:15 +00001654 spcnt += strlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001655 }
1656 spcnt += k;
1657 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1658 if( spcnt<20 ){
1659 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1660 }else{
1661 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1662 }
1663}
1664
1665/*
1666** Return the index of the N-th non-switch argument. Return -1
1667** if N is out of range.
1668*/
1669static int argindex(n)
1670int n;
1671{
1672 int i;
1673 int dashdash = 0;
1674 if( argv!=0 && *argv!=0 ){
1675 for(i=1; argv[i]; i++){
1676 if( dashdash || !ISOPT(argv[i]) ){
1677 if( n==0 ) return i;
1678 n--;
1679 }
1680 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1681 }
1682 }
1683 return -1;
1684}
1685
1686static char emsg[] = "Command line syntax error: ";
1687
1688/*
1689** Process a flag command line argument.
1690*/
1691static int handleflags(i,err)
1692int i;
1693FILE *err;
1694{
1695 int v;
1696 int errcnt = 0;
1697 int j;
1698 for(j=0; op[j].label; j++){
drh6d08b4d2004-07-20 12:45:22 +00001699 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001700 }
1701 v = argv[i][0]=='-' ? 1 : 0;
1702 if( op[j].label==0 ){
1703 if( err ){
1704 fprintf(err,"%sundefined option.\n",emsg);
1705 errline(i,1,err);
1706 }
1707 errcnt++;
1708 }else if( op[j].type==OPT_FLAG ){
1709 *((int*)op[j].arg) = v;
1710 }else if( op[j].type==OPT_FFLAG ){
1711 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001712 }else if( op[j].type==OPT_FSTR ){
1713 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001714 }else{
1715 if( err ){
1716 fprintf(err,"%smissing argument on switch.\n",emsg);
1717 errline(i,1,err);
1718 }
1719 errcnt++;
1720 }
1721 return errcnt;
1722}
1723
1724/*
1725** Process a command line switch which has an argument.
1726*/
1727static int handleswitch(i,err)
1728int i;
1729FILE *err;
1730{
1731 int lv = 0;
1732 double dv = 0.0;
1733 char *sv = 0, *end;
1734 char *cp;
1735 int j;
1736 int errcnt = 0;
1737 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001738 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001739 *cp = 0;
1740 for(j=0; op[j].label; j++){
1741 if( strcmp(argv[i],op[j].label)==0 ) break;
1742 }
1743 *cp = '=';
1744 if( op[j].label==0 ){
1745 if( err ){
1746 fprintf(err,"%sundefined option.\n",emsg);
1747 errline(i,0,err);
1748 }
1749 errcnt++;
1750 }else{
1751 cp++;
1752 switch( op[j].type ){
1753 case OPT_FLAG:
1754 case OPT_FFLAG:
1755 if( err ){
1756 fprintf(err,"%soption requires an argument.\n",emsg);
1757 errline(i,0,err);
1758 }
1759 errcnt++;
1760 break;
1761 case OPT_DBL:
1762 case OPT_FDBL:
1763 dv = strtod(cp,&end);
1764 if( *end ){
1765 if( err ){
1766 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001767 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001768 }
1769 errcnt++;
1770 }
1771 break;
1772 case OPT_INT:
1773 case OPT_FINT:
1774 lv = strtol(cp,&end,0);
1775 if( *end ){
1776 if( err ){
1777 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001778 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001779 }
1780 errcnt++;
1781 }
1782 break;
1783 case OPT_STR:
1784 case OPT_FSTR:
1785 sv = cp;
1786 break;
1787 }
1788 switch( op[j].type ){
1789 case OPT_FLAG:
1790 case OPT_FFLAG:
1791 break;
1792 case OPT_DBL:
1793 *(double*)(op[j].arg) = dv;
1794 break;
1795 case OPT_FDBL:
1796 (*(void(*)())(op[j].arg))(dv);
1797 break;
1798 case OPT_INT:
1799 *(int*)(op[j].arg) = lv;
1800 break;
1801 case OPT_FINT:
1802 (*(void(*)())(op[j].arg))((int)lv);
1803 break;
1804 case OPT_STR:
1805 *(char**)(op[j].arg) = sv;
1806 break;
1807 case OPT_FSTR:
1808 (*(void(*)())(op[j].arg))(sv);
1809 break;
1810 }
1811 }
1812 return errcnt;
1813}
1814
drhb0c86772000-06-02 23:21:26 +00001815int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001816char **a;
1817struct s_options *o;
1818FILE *err;
1819{
1820 int errcnt = 0;
1821 argv = a;
1822 op = o;
1823 errstream = err;
1824 if( argv && *argv && op ){
1825 int i;
1826 for(i=1; argv[i]; i++){
1827 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1828 errcnt += handleflags(i,err);
1829 }else if( strchr(argv[i],'=') ){
1830 errcnt += handleswitch(i,err);
1831 }
1832 }
1833 }
1834 if( errcnt>0 ){
1835 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001836 OptPrint();
drh75897232000-05-29 14:26:00 +00001837 exit(1);
1838 }
1839 return 0;
1840}
1841
drhb0c86772000-06-02 23:21:26 +00001842int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001843 int cnt = 0;
1844 int dashdash = 0;
1845 int i;
1846 if( argv!=0 && argv[0]!=0 ){
1847 for(i=1; argv[i]; i++){
1848 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1849 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1850 }
1851 }
1852 return cnt;
1853}
1854
drhb0c86772000-06-02 23:21:26 +00001855char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001856int n;
1857{
1858 int i;
1859 i = argindex(n);
1860 return i>=0 ? argv[i] : 0;
1861}
1862
drhb0c86772000-06-02 23:21:26 +00001863void OptErr(n)
drh75897232000-05-29 14:26:00 +00001864int n;
1865{
1866 int i;
1867 i = argindex(n);
1868 if( i>=0 ) errline(i,0,errstream);
1869}
1870
drhb0c86772000-06-02 23:21:26 +00001871void OptPrint(){
drh75897232000-05-29 14:26:00 +00001872 int i;
1873 int max, len;
1874 max = 0;
1875 for(i=0; op[i].label; i++){
1876 len = strlen(op[i].label) + 1;
1877 switch( op[i].type ){
1878 case OPT_FLAG:
1879 case OPT_FFLAG:
1880 break;
1881 case OPT_INT:
1882 case OPT_FINT:
1883 len += 9; /* length of "<integer>" */
1884 break;
1885 case OPT_DBL:
1886 case OPT_FDBL:
1887 len += 6; /* length of "<real>" */
1888 break;
1889 case OPT_STR:
1890 case OPT_FSTR:
1891 len += 8; /* length of "<string>" */
1892 break;
1893 }
1894 if( len>max ) max = len;
1895 }
1896 for(i=0; op[i].label; i++){
1897 switch( op[i].type ){
1898 case OPT_FLAG:
1899 case OPT_FFLAG:
1900 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1901 break;
1902 case OPT_INT:
1903 case OPT_FINT:
1904 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001905 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001906 break;
1907 case OPT_DBL:
1908 case OPT_FDBL:
1909 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001910 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001911 break;
1912 case OPT_STR:
1913 case OPT_FSTR:
1914 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001915 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001916 break;
1917 }
1918 }
1919}
1920/*********************** From the file "parse.c" ****************************/
1921/*
1922** Input file parser for the LEMON parser generator.
1923*/
1924
1925/* The state of the parser */
1926struct pstate {
1927 char *filename; /* Name of the input file */
1928 int tokenlineno; /* Linenumber at which current token starts */
1929 int errorcnt; /* Number of errors so far */
1930 char *tokenstart; /* Text of current token */
1931 struct lemon *gp; /* Global state vector */
1932 enum e_state {
1933 INITIALIZE,
1934 WAITING_FOR_DECL_OR_RULE,
1935 WAITING_FOR_DECL_KEYWORD,
1936 WAITING_FOR_DECL_ARG,
1937 WAITING_FOR_PRECEDENCE_SYMBOL,
1938 WAITING_FOR_ARROW,
1939 IN_RHS,
1940 LHS_ALIAS_1,
1941 LHS_ALIAS_2,
1942 LHS_ALIAS_3,
1943 RHS_ALIAS_1,
1944 RHS_ALIAS_2,
1945 PRECEDENCE_MARK_1,
1946 PRECEDENCE_MARK_2,
1947 RESYNC_AFTER_RULE_ERROR,
1948 RESYNC_AFTER_DECL_ERROR,
1949 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001950 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001951 WAITING_FOR_FALLBACK_ID,
1952 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001953 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001954 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001955 struct symbol *lhs; /* Left-hand side of current rule */
1956 char *lhsalias; /* Alias for the LHS */
1957 int nrhs; /* Number of right-hand side symbols seen */
1958 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1959 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1960 struct rule *prevrule; /* Previous rule parsed */
1961 char *declkeyword; /* Keyword of a declaration */
1962 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001963 int insertLineMacro; /* Add #line before declaration insert */
drh75897232000-05-29 14:26:00 +00001964 enum e_assoc declassoc; /* Assign this association to decl arguments */
1965 int preccounter; /* Assign this precedence to decl arguments */
1966 struct rule *firstrule; /* Pointer to first rule in the grammar */
1967 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1968};
1969
1970/* Parse a single token */
1971static void parseonetoken(psp)
1972struct pstate *psp;
1973{
1974 char *x;
1975 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1976#if 0
1977 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1978 x,psp->state);
1979#endif
1980 switch( psp->state ){
1981 case INITIALIZE:
1982 psp->prevrule = 0;
1983 psp->preccounter = 0;
1984 psp->firstrule = psp->lastrule = 0;
1985 psp->gp->nrule = 0;
1986 /* Fall thru to next case */
1987 case WAITING_FOR_DECL_OR_RULE:
1988 if( x[0]=='%' ){
1989 psp->state = WAITING_FOR_DECL_KEYWORD;
1990 }else if( islower(x[0]) ){
1991 psp->lhs = Symbol_new(x);
1992 psp->nrhs = 0;
1993 psp->lhsalias = 0;
1994 psp->state = WAITING_FOR_ARROW;
1995 }else if( x[0]=='{' ){
1996 if( psp->prevrule==0 ){
1997 ErrorMsg(psp->filename,psp->tokenlineno,
1998"There is not prior rule opon which to attach the code \
1999fragment which begins on this line.");
2000 psp->errorcnt++;
2001 }else if( psp->prevrule->code!=0 ){
2002 ErrorMsg(psp->filename,psp->tokenlineno,
2003"Code fragment beginning on this line is not the first \
2004to follow the previous rule.");
2005 psp->errorcnt++;
2006 }else{
2007 psp->prevrule->line = psp->tokenlineno;
2008 psp->prevrule->code = &x[1];
2009 }
2010 }else if( x[0]=='[' ){
2011 psp->state = PRECEDENCE_MARK_1;
2012 }else{
2013 ErrorMsg(psp->filename,psp->tokenlineno,
2014 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2015 x);
2016 psp->errorcnt++;
2017 }
2018 break;
2019 case PRECEDENCE_MARK_1:
2020 if( !isupper(x[0]) ){
2021 ErrorMsg(psp->filename,psp->tokenlineno,
2022 "The precedence symbol must be a terminal.");
2023 psp->errorcnt++;
2024 }else if( psp->prevrule==0 ){
2025 ErrorMsg(psp->filename,psp->tokenlineno,
2026 "There is no prior rule to assign precedence \"[%s]\".",x);
2027 psp->errorcnt++;
2028 }else if( psp->prevrule->precsym!=0 ){
2029 ErrorMsg(psp->filename,psp->tokenlineno,
2030"Precedence mark on this line is not the first \
2031to follow the previous rule.");
2032 psp->errorcnt++;
2033 }else{
2034 psp->prevrule->precsym = Symbol_new(x);
2035 }
2036 psp->state = PRECEDENCE_MARK_2;
2037 break;
2038 case PRECEDENCE_MARK_2:
2039 if( x[0]!=']' ){
2040 ErrorMsg(psp->filename,psp->tokenlineno,
2041 "Missing \"]\" on precedence mark.");
2042 psp->errorcnt++;
2043 }
2044 psp->state = WAITING_FOR_DECL_OR_RULE;
2045 break;
2046 case WAITING_FOR_ARROW:
2047 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2048 psp->state = IN_RHS;
2049 }else if( x[0]=='(' ){
2050 psp->state = LHS_ALIAS_1;
2051 }else{
2052 ErrorMsg(psp->filename,psp->tokenlineno,
2053 "Expected to see a \":\" following the LHS symbol \"%s\".",
2054 psp->lhs->name);
2055 psp->errorcnt++;
2056 psp->state = RESYNC_AFTER_RULE_ERROR;
2057 }
2058 break;
2059 case LHS_ALIAS_1:
2060 if( isalpha(x[0]) ){
2061 psp->lhsalias = x;
2062 psp->state = LHS_ALIAS_2;
2063 }else{
2064 ErrorMsg(psp->filename,psp->tokenlineno,
2065 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2066 x,psp->lhs->name);
2067 psp->errorcnt++;
2068 psp->state = RESYNC_AFTER_RULE_ERROR;
2069 }
2070 break;
2071 case LHS_ALIAS_2:
2072 if( x[0]==')' ){
2073 psp->state = LHS_ALIAS_3;
2074 }else{
2075 ErrorMsg(psp->filename,psp->tokenlineno,
2076 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2077 psp->errorcnt++;
2078 psp->state = RESYNC_AFTER_RULE_ERROR;
2079 }
2080 break;
2081 case LHS_ALIAS_3:
2082 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2083 psp->state = IN_RHS;
2084 }else{
2085 ErrorMsg(psp->filename,psp->tokenlineno,
2086 "Missing \"->\" following: \"%s(%s)\".",
2087 psp->lhs->name,psp->lhsalias);
2088 psp->errorcnt++;
2089 psp->state = RESYNC_AFTER_RULE_ERROR;
2090 }
2091 break;
2092 case IN_RHS:
2093 if( x[0]=='.' ){
2094 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002095 rp = (struct rule *)calloc( sizeof(struct rule) +
2096 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002097 if( rp==0 ){
2098 ErrorMsg(psp->filename,psp->tokenlineno,
2099 "Can't allocate enough memory for this rule.");
2100 psp->errorcnt++;
2101 psp->prevrule = 0;
2102 }else{
2103 int i;
2104 rp->ruleline = psp->tokenlineno;
2105 rp->rhs = (struct symbol**)&rp[1];
2106 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2107 for(i=0; i<psp->nrhs; i++){
2108 rp->rhs[i] = psp->rhs[i];
2109 rp->rhsalias[i] = psp->alias[i];
2110 }
2111 rp->lhs = psp->lhs;
2112 rp->lhsalias = psp->lhsalias;
2113 rp->nrhs = psp->nrhs;
2114 rp->code = 0;
2115 rp->precsym = 0;
2116 rp->index = psp->gp->nrule++;
2117 rp->nextlhs = rp->lhs->rule;
2118 rp->lhs->rule = rp;
2119 rp->next = 0;
2120 if( psp->firstrule==0 ){
2121 psp->firstrule = psp->lastrule = rp;
2122 }else{
2123 psp->lastrule->next = rp;
2124 psp->lastrule = rp;
2125 }
2126 psp->prevrule = rp;
2127 }
2128 psp->state = WAITING_FOR_DECL_OR_RULE;
2129 }else if( isalpha(x[0]) ){
2130 if( psp->nrhs>=MAXRHS ){
2131 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002132 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002133 x);
2134 psp->errorcnt++;
2135 psp->state = RESYNC_AFTER_RULE_ERROR;
2136 }else{
2137 psp->rhs[psp->nrhs] = Symbol_new(x);
2138 psp->alias[psp->nrhs] = 0;
2139 psp->nrhs++;
2140 }
drhfd405312005-11-06 04:06:59 +00002141 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2142 struct symbol *msp = psp->rhs[psp->nrhs-1];
2143 if( msp->type!=MULTITERMINAL ){
2144 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002145 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002146 memset(msp, 0, sizeof(*msp));
2147 msp->type = MULTITERMINAL;
2148 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002149 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002150 msp->subsym[0] = origsp;
2151 msp->name = origsp->name;
2152 psp->rhs[psp->nrhs-1] = msp;
2153 }
2154 msp->nsubsym++;
2155 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2156 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2157 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2158 ErrorMsg(psp->filename,psp->tokenlineno,
2159 "Cannot form a compound containing a non-terminal");
2160 psp->errorcnt++;
2161 }
drh75897232000-05-29 14:26:00 +00002162 }else if( x[0]=='(' && psp->nrhs>0 ){
2163 psp->state = RHS_ALIAS_1;
2164 }else{
2165 ErrorMsg(psp->filename,psp->tokenlineno,
2166 "Illegal character on RHS of rule: \"%s\".",x);
2167 psp->errorcnt++;
2168 psp->state = RESYNC_AFTER_RULE_ERROR;
2169 }
2170 break;
2171 case RHS_ALIAS_1:
2172 if( isalpha(x[0]) ){
2173 psp->alias[psp->nrhs-1] = x;
2174 psp->state = RHS_ALIAS_2;
2175 }else{
2176 ErrorMsg(psp->filename,psp->tokenlineno,
2177 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2178 x,psp->rhs[psp->nrhs-1]->name);
2179 psp->errorcnt++;
2180 psp->state = RESYNC_AFTER_RULE_ERROR;
2181 }
2182 break;
2183 case RHS_ALIAS_2:
2184 if( x[0]==')' ){
2185 psp->state = IN_RHS;
2186 }else{
2187 ErrorMsg(psp->filename,psp->tokenlineno,
2188 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2189 psp->errorcnt++;
2190 psp->state = RESYNC_AFTER_RULE_ERROR;
2191 }
2192 break;
2193 case WAITING_FOR_DECL_KEYWORD:
2194 if( isalpha(x[0]) ){
2195 psp->declkeyword = x;
2196 psp->declargslot = 0;
drha5808f32008-04-27 22:19:44 +00002197 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002198 psp->state = WAITING_FOR_DECL_ARG;
2199 if( strcmp(x,"name")==0 ){
2200 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002201 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002202 }else if( strcmp(x,"include")==0 ){
2203 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002204 }else if( strcmp(x,"code")==0 ){
2205 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002206 }else if( strcmp(x,"token_destructor")==0 ){
2207 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002208 }else if( strcmp(x,"default_destructor")==0 ){
2209 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002210 }else if( strcmp(x,"token_prefix")==0 ){
2211 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002212 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002213 }else if( strcmp(x,"syntax_error")==0 ){
2214 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002215 }else if( strcmp(x,"parse_accept")==0 ){
2216 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002217 }else if( strcmp(x,"parse_failure")==0 ){
2218 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002219 }else if( strcmp(x,"stack_overflow")==0 ){
2220 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002221 }else if( strcmp(x,"extra_argument")==0 ){
2222 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002223 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002224 }else if( strcmp(x,"token_type")==0 ){
2225 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002226 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002227 }else if( strcmp(x,"default_type")==0 ){
2228 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002229 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002230 }else if( strcmp(x,"stack_size")==0 ){
2231 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002232 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002233 }else if( strcmp(x,"start_symbol")==0 ){
2234 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002235 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002236 }else if( strcmp(x,"left")==0 ){
2237 psp->preccounter++;
2238 psp->declassoc = LEFT;
2239 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2240 }else if( strcmp(x,"right")==0 ){
2241 psp->preccounter++;
2242 psp->declassoc = RIGHT;
2243 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2244 }else if( strcmp(x,"nonassoc")==0 ){
2245 psp->preccounter++;
2246 psp->declassoc = NONE;
2247 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2248 }else if( strcmp(x,"destructor")==0 ){
2249 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2250 }else if( strcmp(x,"type")==0 ){
2251 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002252 }else if( strcmp(x,"fallback")==0 ){
2253 psp->fallback = 0;
2254 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002255 }else if( strcmp(x,"wildcard")==0 ){
2256 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002257 }else{
2258 ErrorMsg(psp->filename,psp->tokenlineno,
2259 "Unknown declaration keyword: \"%%%s\".",x);
2260 psp->errorcnt++;
2261 psp->state = RESYNC_AFTER_DECL_ERROR;
2262 }
2263 }else{
2264 ErrorMsg(psp->filename,psp->tokenlineno,
2265 "Illegal declaration keyword: \"%s\".",x);
2266 psp->errorcnt++;
2267 psp->state = RESYNC_AFTER_DECL_ERROR;
2268 }
2269 break;
2270 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2271 if( !isalpha(x[0]) ){
2272 ErrorMsg(psp->filename,psp->tokenlineno,
2273 "Symbol name missing after %destructor keyword");
2274 psp->errorcnt++;
2275 psp->state = RESYNC_AFTER_DECL_ERROR;
2276 }else{
2277 struct symbol *sp = Symbol_new(x);
2278 psp->declargslot = &sp->destructor;
drha5808f32008-04-27 22:19:44 +00002279 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002280 psp->state = WAITING_FOR_DECL_ARG;
2281 }
2282 break;
2283 case WAITING_FOR_DATATYPE_SYMBOL:
2284 if( !isalpha(x[0]) ){
2285 ErrorMsg(psp->filename,psp->tokenlineno,
2286 "Symbol name missing after %destructor keyword");
2287 psp->errorcnt++;
2288 psp->state = RESYNC_AFTER_DECL_ERROR;
2289 }else{
2290 struct symbol *sp = Symbol_new(x);
2291 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002292 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002293 psp->state = WAITING_FOR_DECL_ARG;
2294 }
2295 break;
2296 case WAITING_FOR_PRECEDENCE_SYMBOL:
2297 if( x[0]=='.' ){
2298 psp->state = WAITING_FOR_DECL_OR_RULE;
2299 }else if( isupper(x[0]) ){
2300 struct symbol *sp;
2301 sp = Symbol_new(x);
2302 if( sp->prec>=0 ){
2303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "Symbol \"%s\" has already be given a precedence.",x);
2305 psp->errorcnt++;
2306 }else{
2307 sp->prec = psp->preccounter;
2308 sp->assoc = psp->declassoc;
2309 }
2310 }else{
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "Can't assign a precedence to \"%s\".",x);
2313 psp->errorcnt++;
2314 }
2315 break;
2316 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002317 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2318 char *zOld, *zNew, *zBuf, *z;
2319 int nOld, n, nLine, nNew, nBack;
2320 char zLine[50];
2321 zNew = x;
2322 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2323 nNew = strlen(zNew);
2324 if( *psp->declargslot ){
2325 zOld = *psp->declargslot;
2326 }else{
2327 zOld = "";
2328 }
2329 nOld = strlen(zOld);
2330 n = nOld + nNew + 20;
2331 if( psp->insertLineMacro ){
2332 for(z=psp->filename, nBack=0; *z; z++){
2333 if( *z=='\\' ) nBack++;
2334 }
2335 sprintf(zLine, "#line %d ", psp->tokenlineno);
2336 nLine = strlen(zLine);
2337 n += nLine + strlen(psp->filename) + nBack;
2338 }
2339 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2340 zBuf += nOld;
2341 if( psp->insertLineMacro ){
2342 if( nOld && zBuf[-1]!='\n' ){
2343 *(zBuf++) = '\n';
2344 }
2345 memcpy(zBuf, zLine, nLine);
2346 zBuf += nLine;
2347 *(zBuf++) = '"';
2348 for(z=psp->filename; *z; z++){
2349 if( *z=='\\' ){
2350 *(zBuf++) = '\\';
2351 }
2352 *(zBuf++) = *z;
2353 }
2354 *(zBuf++) = '"';
2355 *(zBuf++) = '\n';
2356 }
2357 memcpy(zBuf, zNew, nNew);
2358 zBuf += nNew;
2359 *zBuf = 0;
2360 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002361 }else{
2362 ErrorMsg(psp->filename,psp->tokenlineno,
2363 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2364 psp->errorcnt++;
2365 psp->state = RESYNC_AFTER_DECL_ERROR;
2366 }
2367 break;
drh0bd1f4e2002-06-06 18:54:39 +00002368 case WAITING_FOR_FALLBACK_ID:
2369 if( x[0]=='.' ){
2370 psp->state = WAITING_FOR_DECL_OR_RULE;
2371 }else if( !isupper(x[0]) ){
2372 ErrorMsg(psp->filename, psp->tokenlineno,
2373 "%%fallback argument \"%s\" should be a token", x);
2374 psp->errorcnt++;
2375 }else{
2376 struct symbol *sp = Symbol_new(x);
2377 if( psp->fallback==0 ){
2378 psp->fallback = sp;
2379 }else if( sp->fallback ){
2380 ErrorMsg(psp->filename, psp->tokenlineno,
2381 "More than one fallback assigned to token %s", x);
2382 psp->errorcnt++;
2383 }else{
2384 sp->fallback = psp->fallback;
2385 psp->gp->has_fallback = 1;
2386 }
2387 }
2388 break;
drhe09daa92006-06-10 13:29:31 +00002389 case WAITING_FOR_WILDCARD_ID:
2390 if( x[0]=='.' ){
2391 psp->state = WAITING_FOR_DECL_OR_RULE;
2392 }else if( !isupper(x[0]) ){
2393 ErrorMsg(psp->filename, psp->tokenlineno,
2394 "%%wildcard argument \"%s\" should be a token", x);
2395 psp->errorcnt++;
2396 }else{
2397 struct symbol *sp = Symbol_new(x);
2398 if( psp->gp->wildcard==0 ){
2399 psp->gp->wildcard = sp;
2400 }else{
2401 ErrorMsg(psp->filename, psp->tokenlineno,
2402 "Extra wildcard to token: %s", x);
2403 psp->errorcnt++;
2404 }
2405 }
2406 break;
drh75897232000-05-29 14:26:00 +00002407 case RESYNC_AFTER_RULE_ERROR:
2408/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2409** break; */
2410 case RESYNC_AFTER_DECL_ERROR:
2411 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2412 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2413 break;
2414 }
2415}
2416
drh6d08b4d2004-07-20 12:45:22 +00002417/* Run the proprocessor over the input file text. The global variables
2418** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2419** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2420** comments them out. Text in between is also commented out as appropriate.
2421*/
danielk1977940fac92005-01-23 22:41:37 +00002422static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002423 int i, j, k, n;
2424 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002425 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002426 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002427 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002428 for(i=0; z[i]; i++){
2429 if( z[i]=='\n' ) lineno++;
2430 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2431 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2432 if( exclude ){
2433 exclude--;
2434 if( exclude==0 ){
2435 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2436 }
2437 }
2438 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2439 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2440 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2441 if( exclude ){
2442 exclude++;
2443 }else{
2444 for(j=i+7; isspace(z[j]); j++){}
2445 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2446 exclude = 1;
2447 for(k=0; k<nDefine; k++){
2448 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2449 exclude = 0;
2450 break;
2451 }
2452 }
2453 if( z[i+3]=='n' ) exclude = !exclude;
2454 if( exclude ){
2455 start = i;
2456 start_lineno = lineno;
2457 }
2458 }
2459 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2460 }
2461 }
2462 if( exclude ){
2463 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2464 exit(1);
2465 }
2466}
2467
drh75897232000-05-29 14:26:00 +00002468/* In spite of its name, this function is really a scanner. It read
2469** in the entire input file (all at once) then tokenizes it. Each
2470** token is passed to the function "parseonetoken" which builds all
2471** the appropriate data structures in the global state vector "gp".
2472*/
2473void Parse(gp)
2474struct lemon *gp;
2475{
2476 struct pstate ps;
2477 FILE *fp;
2478 char *filebuf;
2479 int filesize;
2480 int lineno;
2481 int c;
2482 char *cp, *nextcp;
2483 int startline = 0;
2484
rse38514a92007-09-20 11:34:17 +00002485 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002486 ps.gp = gp;
2487 ps.filename = gp->filename;
2488 ps.errorcnt = 0;
2489 ps.state = INITIALIZE;
2490
2491 /* Begin by reading the input file */
2492 fp = fopen(ps.filename,"rb");
2493 if( fp==0 ){
2494 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2495 gp->errorcnt++;
2496 return;
2497 }
2498 fseek(fp,0,2);
2499 filesize = ftell(fp);
2500 rewind(fp);
2501 filebuf = (char *)malloc( filesize+1 );
2502 if( filebuf==0 ){
2503 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2504 filesize+1);
2505 gp->errorcnt++;
2506 return;
2507 }
2508 if( fread(filebuf,1,filesize,fp)!=filesize ){
2509 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2510 filesize);
2511 free(filebuf);
2512 gp->errorcnt++;
2513 return;
2514 }
2515 fclose(fp);
2516 filebuf[filesize] = 0;
2517
drh6d08b4d2004-07-20 12:45:22 +00002518 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2519 preprocess_input(filebuf);
2520
drh75897232000-05-29 14:26:00 +00002521 /* Now scan the text of the input file */
2522 lineno = 1;
2523 for(cp=filebuf; (c= *cp)!=0; ){
2524 if( c=='\n' ) lineno++; /* Keep track of the line number */
2525 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2526 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2527 cp+=2;
2528 while( (c= *cp)!=0 && c!='\n' ) cp++;
2529 continue;
2530 }
2531 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2532 cp+=2;
2533 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2534 if( c=='\n' ) lineno++;
2535 cp++;
2536 }
2537 if( c ) cp++;
2538 continue;
2539 }
2540 ps.tokenstart = cp; /* Mark the beginning of the token */
2541 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2542 if( c=='\"' ){ /* String literals */
2543 cp++;
2544 while( (c= *cp)!=0 && c!='\"' ){
2545 if( c=='\n' ) lineno++;
2546 cp++;
2547 }
2548 if( c==0 ){
2549 ErrorMsg(ps.filename,startline,
2550"String starting on this line is not terminated before the end of the file.");
2551 ps.errorcnt++;
2552 nextcp = cp;
2553 }else{
2554 nextcp = cp+1;
2555 }
2556 }else if( c=='{' ){ /* A block of C code */
2557 int level;
2558 cp++;
2559 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2560 if( c=='\n' ) lineno++;
2561 else if( c=='{' ) level++;
2562 else if( c=='}' ) level--;
2563 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2564 int prevc;
2565 cp = &cp[2];
2566 prevc = 0;
2567 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2568 if( c=='\n' ) lineno++;
2569 prevc = c;
2570 cp++;
2571 }
2572 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2573 cp = &cp[2];
2574 while( (c= *cp)!=0 && c!='\n' ) cp++;
2575 if( c ) lineno++;
2576 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2577 int startchar, prevc;
2578 startchar = c;
2579 prevc = 0;
2580 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2581 if( c=='\n' ) lineno++;
2582 if( prevc=='\\' ) prevc = 0;
2583 else prevc = c;
2584 }
2585 }
2586 }
2587 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002588 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002589"C code starting on this line is not terminated before the end of the file.");
2590 ps.errorcnt++;
2591 nextcp = cp;
2592 }else{
2593 nextcp = cp+1;
2594 }
2595 }else if( isalnum(c) ){ /* Identifiers */
2596 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2597 nextcp = cp;
2598 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2599 cp += 3;
2600 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002601 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2602 cp += 2;
2603 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2604 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002605 }else{ /* All other (one character) operators */
2606 cp++;
2607 nextcp = cp;
2608 }
2609 c = *cp;
2610 *cp = 0; /* Null terminate the token */
2611 parseonetoken(&ps); /* Parse the token */
2612 *cp = c; /* Restore the buffer */
2613 cp = nextcp;
2614 }
2615 free(filebuf); /* Release the buffer after parsing */
2616 gp->rule = ps.firstrule;
2617 gp->errorcnt = ps.errorcnt;
2618}
2619/*************************** From the file "plink.c" *********************/
2620/*
2621** Routines processing configuration follow-set propagation links
2622** in the LEMON parser generator.
2623*/
2624static struct plink *plink_freelist = 0;
2625
2626/* Allocate a new plink */
2627struct plink *Plink_new(){
2628 struct plink *new;
2629
2630 if( plink_freelist==0 ){
2631 int i;
2632 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002633 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002634 if( plink_freelist==0 ){
2635 fprintf(stderr,
2636 "Unable to allocate memory for a new follow-set propagation link.\n");
2637 exit(1);
2638 }
2639 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2640 plink_freelist[amt-1].next = 0;
2641 }
2642 new = plink_freelist;
2643 plink_freelist = plink_freelist->next;
2644 return new;
2645}
2646
2647/* Add a plink to a plink list */
2648void Plink_add(plpp,cfp)
2649struct plink **plpp;
2650struct config *cfp;
2651{
2652 struct plink *new;
2653 new = Plink_new();
2654 new->next = *plpp;
2655 *plpp = new;
2656 new->cfp = cfp;
2657}
2658
2659/* Transfer every plink on the list "from" to the list "to" */
2660void Plink_copy(to,from)
2661struct plink **to;
2662struct plink *from;
2663{
2664 struct plink *nextpl;
2665 while( from ){
2666 nextpl = from->next;
2667 from->next = *to;
2668 *to = from;
2669 from = nextpl;
2670 }
2671}
2672
2673/* Delete every plink on the list */
2674void Plink_delete(plp)
2675struct plink *plp;
2676{
2677 struct plink *nextpl;
2678
2679 while( plp ){
2680 nextpl = plp->next;
2681 plp->next = plink_freelist;
2682 plink_freelist = plp;
2683 plp = nextpl;
2684 }
2685}
2686/*********************** From the file "report.c" **************************/
2687/*
2688** Procedures for generating reports and tables in the LEMON parser generator.
2689*/
2690
2691/* Generate a filename with the given suffix. Space to hold the
2692** name comes from malloc() and must be freed by the calling
2693** function.
2694*/
2695PRIVATE char *file_makename(lemp,suffix)
2696struct lemon *lemp;
2697char *suffix;
2698{
2699 char *name;
2700 char *cp;
2701
2702 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2703 if( name==0 ){
2704 fprintf(stderr,"Can't allocate space for a filename.\n");
2705 exit(1);
2706 }
2707 strcpy(name,lemp->filename);
2708 cp = strrchr(name,'.');
2709 if( cp ) *cp = 0;
2710 strcat(name,suffix);
2711 return name;
2712}
2713
2714/* Open a file with a name based on the name of the input file,
2715** but with a different (specified) suffix, and return a pointer
2716** to the stream */
2717PRIVATE FILE *file_open(lemp,suffix,mode)
2718struct lemon *lemp;
2719char *suffix;
2720char *mode;
2721{
2722 FILE *fp;
2723
2724 if( lemp->outname ) free(lemp->outname);
2725 lemp->outname = file_makename(lemp, suffix);
2726 fp = fopen(lemp->outname,mode);
2727 if( fp==0 && *mode=='w' ){
2728 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2729 lemp->errorcnt++;
2730 return 0;
2731 }
2732 return fp;
2733}
2734
2735/* Duplicate the input file without comments and without actions
2736** on rules */
2737void Reprint(lemp)
2738struct lemon *lemp;
2739{
2740 struct rule *rp;
2741 struct symbol *sp;
2742 int i, j, maxlen, len, ncolumns, skip;
2743 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2744 maxlen = 10;
2745 for(i=0; i<lemp->nsymbol; i++){
2746 sp = lemp->symbols[i];
2747 len = strlen(sp->name);
2748 if( len>maxlen ) maxlen = len;
2749 }
2750 ncolumns = 76/(maxlen+5);
2751 if( ncolumns<1 ) ncolumns = 1;
2752 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2753 for(i=0; i<skip; i++){
2754 printf("//");
2755 for(j=i; j<lemp->nsymbol; j+=skip){
2756 sp = lemp->symbols[j];
2757 assert( sp->index==j );
2758 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2759 }
2760 printf("\n");
2761 }
2762 for(rp=lemp->rule; rp; rp=rp->next){
2763 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002764 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002765 printf(" ::=");
2766 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002767 sp = rp->rhs[i];
2768 printf(" %s", sp->name);
2769 if( sp->type==MULTITERMINAL ){
2770 for(j=1; j<sp->nsubsym; j++){
2771 printf("|%s", sp->subsym[j]->name);
2772 }
2773 }
2774 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002775 }
2776 printf(".");
2777 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002778 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002779 printf("\n");
2780 }
2781}
2782
2783void ConfigPrint(fp,cfp)
2784FILE *fp;
2785struct config *cfp;
2786{
2787 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002788 struct symbol *sp;
2789 int i, j;
drh75897232000-05-29 14:26:00 +00002790 rp = cfp->rp;
2791 fprintf(fp,"%s ::=",rp->lhs->name);
2792 for(i=0; i<=rp->nrhs; i++){
2793 if( i==cfp->dot ) fprintf(fp," *");
2794 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002795 sp = rp->rhs[i];
2796 fprintf(fp," %s", sp->name);
2797 if( sp->type==MULTITERMINAL ){
2798 for(j=1; j<sp->nsubsym; j++){
2799 fprintf(fp,"|%s",sp->subsym[j]->name);
2800 }
2801 }
drh75897232000-05-29 14:26:00 +00002802 }
2803}
2804
2805/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002806#if 0
drh75897232000-05-29 14:26:00 +00002807/* Print a set */
2808PRIVATE void SetPrint(out,set,lemp)
2809FILE *out;
2810char *set;
2811struct lemon *lemp;
2812{
2813 int i;
2814 char *spacer;
2815 spacer = "";
2816 fprintf(out,"%12s[","");
2817 for(i=0; i<lemp->nterminal; i++){
2818 if( SetFind(set,i) ){
2819 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2820 spacer = " ";
2821 }
2822 }
2823 fprintf(out,"]\n");
2824}
2825
2826/* Print a plink chain */
2827PRIVATE void PlinkPrint(out,plp,tag)
2828FILE *out;
2829struct plink *plp;
2830char *tag;
2831{
2832 while( plp ){
drhada354d2005-11-05 15:03:59 +00002833 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002834 ConfigPrint(out,plp->cfp);
2835 fprintf(out,"\n");
2836 plp = plp->next;
2837 }
2838}
2839#endif
2840
2841/* Print an action to the given file descriptor. Return FALSE if
2842** nothing was actually printed.
2843*/
2844int PrintAction(struct action *ap, FILE *fp, int indent){
2845 int result = 1;
2846 switch( ap->type ){
2847 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002848 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002849 break;
2850 case REDUCE:
2851 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2852 break;
2853 case ACCEPT:
2854 fprintf(fp,"%*s accept",indent,ap->sp->name);
2855 break;
2856 case ERROR:
2857 fprintf(fp,"%*s error",indent,ap->sp->name);
2858 break;
drh9892c5d2007-12-21 00:02:11 +00002859 case SRCONFLICT:
2860 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002861 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2862 indent,ap->sp->name,ap->x.rp->index);
2863 break;
drh9892c5d2007-12-21 00:02:11 +00002864 case SSCONFLICT:
2865 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2866 indent,ap->sp->name,ap->x.stp->statenum);
2867 break;
drh75897232000-05-29 14:26:00 +00002868 case SH_RESOLVED:
2869 case RD_RESOLVED:
2870 case NOT_USED:
2871 result = 0;
2872 break;
2873 }
2874 return result;
2875}
2876
2877/* Generate the "y.output" log file */
2878void ReportOutput(lemp)
2879struct lemon *lemp;
2880{
2881 int i;
2882 struct state *stp;
2883 struct config *cfp;
2884 struct action *ap;
2885 FILE *fp;
2886
drh2aa6ca42004-09-10 00:14:04 +00002887 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002888 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002889 for(i=0; i<lemp->nstate; i++){
2890 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002891 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002892 if( lemp->basisflag ) cfp=stp->bp;
2893 else cfp=stp->cfp;
2894 while( cfp ){
2895 char buf[20];
2896 if( cfp->dot==cfp->rp->nrhs ){
2897 sprintf(buf,"(%d)",cfp->rp->index);
2898 fprintf(fp," %5s ",buf);
2899 }else{
2900 fprintf(fp," ");
2901 }
2902 ConfigPrint(fp,cfp);
2903 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002904#if 0
drh75897232000-05-29 14:26:00 +00002905 SetPrint(fp,cfp->fws,lemp);
2906 PlinkPrint(fp,cfp->fplp,"To ");
2907 PlinkPrint(fp,cfp->bplp,"From");
2908#endif
2909 if( lemp->basisflag ) cfp=cfp->bp;
2910 else cfp=cfp->next;
2911 }
2912 fprintf(fp,"\n");
2913 for(ap=stp->ap; ap; ap=ap->next){
2914 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2915 }
2916 fprintf(fp,"\n");
2917 }
drhe9278182007-07-18 18:16:29 +00002918 fprintf(fp, "----------------------------------------------------\n");
2919 fprintf(fp, "Symbols:\n");
2920 for(i=0; i<lemp->nsymbol; i++){
2921 int j;
2922 struct symbol *sp;
2923
2924 sp = lemp->symbols[i];
2925 fprintf(fp, " %3d: %s", i, sp->name);
2926 if( sp->type==NONTERMINAL ){
2927 fprintf(fp, ":");
2928 if( sp->lambda ){
2929 fprintf(fp, " <lambda>");
2930 }
2931 for(j=0; j<lemp->nterminal; j++){
2932 if( sp->firstset && SetFind(sp->firstset, j) ){
2933 fprintf(fp, " %s", lemp->symbols[j]->name);
2934 }
2935 }
2936 }
2937 fprintf(fp, "\n");
2938 }
drh75897232000-05-29 14:26:00 +00002939 fclose(fp);
2940 return;
2941}
2942
2943/* Search for the file "name" which is in the same directory as
2944** the exacutable */
2945PRIVATE char *pathsearch(argv0,name,modemask)
2946char *argv0;
2947char *name;
2948int modemask;
2949{
2950 char *pathlist;
2951 char *path,*cp;
2952 char c;
drh75897232000-05-29 14:26:00 +00002953
2954#ifdef __WIN32__
2955 cp = strrchr(argv0,'\\');
2956#else
2957 cp = strrchr(argv0,'/');
2958#endif
2959 if( cp ){
2960 c = *cp;
2961 *cp = 0;
2962 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2963 if( path ) sprintf(path,"%s/%s",argv0,name);
2964 *cp = c;
2965 }else{
2966 extern char *getenv();
2967 pathlist = getenv("PATH");
2968 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2969 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2970 if( path!=0 ){
2971 while( *pathlist ){
2972 cp = strchr(pathlist,':');
2973 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2974 c = *cp;
2975 *cp = 0;
2976 sprintf(path,"%s/%s",pathlist,name);
2977 *cp = c;
2978 if( c==0 ) pathlist = "";
2979 else pathlist = &cp[1];
2980 if( access(path,modemask)==0 ) break;
2981 }
2982 }
2983 }
2984 return path;
2985}
2986
2987/* Given an action, compute the integer value for that action
2988** which is to be put in the action table of the generated machine.
2989** Return negative if no action should be generated.
2990*/
2991PRIVATE int compute_action(lemp,ap)
2992struct lemon *lemp;
2993struct action *ap;
2994{
2995 int act;
2996 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00002997 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00002998 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
2999 case ERROR: act = lemp->nstate + lemp->nrule; break;
3000 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3001 default: act = -1; break;
3002 }
3003 return act;
3004}
3005
3006#define LINESIZE 1000
3007/* The next cluster of routines are for reading the template file
3008** and writing the results to the generated parser */
3009/* The first function transfers data from "in" to "out" until
3010** a line is seen which begins with "%%". The line number is
3011** tracked.
3012**
3013** if name!=0, then any word that begin with "Parse" is changed to
3014** begin with *name instead.
3015*/
3016PRIVATE void tplt_xfer(name,in,out,lineno)
3017char *name;
3018FILE *in;
3019FILE *out;
3020int *lineno;
3021{
3022 int i, iStart;
3023 char line[LINESIZE];
3024 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3025 (*lineno)++;
3026 iStart = 0;
3027 if( name ){
3028 for(i=0; line[i]; i++){
3029 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3030 && (i==0 || !isalpha(line[i-1]))
3031 ){
3032 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3033 fprintf(out,"%s",name);
3034 i += 4;
3035 iStart = i+1;
3036 }
3037 }
3038 }
3039 fprintf(out,"%s",&line[iStart]);
3040 }
3041}
3042
3043/* The next function finds the template file and opens it, returning
3044** a pointer to the opened file. */
3045PRIVATE FILE *tplt_open(lemp)
3046struct lemon *lemp;
3047{
3048 static char templatename[] = "lempar.c";
3049 char buf[1000];
3050 FILE *in;
3051 char *tpltname;
3052 char *cp;
3053
3054 cp = strrchr(lemp->filename,'.');
3055 if( cp ){
drh8b582012003-10-21 13:16:03 +00003056 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003057 }else{
3058 sprintf(buf,"%s.lt",lemp->filename);
3059 }
3060 if( access(buf,004)==0 ){
3061 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003062 }else if( access(templatename,004)==0 ){
3063 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003064 }else{
3065 tpltname = pathsearch(lemp->argv0,templatename,0);
3066 }
3067 if( tpltname==0 ){
3068 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3069 templatename);
3070 lemp->errorcnt++;
3071 return 0;
3072 }
drh2aa6ca42004-09-10 00:14:04 +00003073 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003074 if( in==0 ){
3075 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3076 lemp->errorcnt++;
3077 return 0;
3078 }
3079 return in;
3080}
3081
drhaf805ca2004-09-07 11:28:25 +00003082/* Print a #line directive line to the output file. */
3083PRIVATE void tplt_linedir(out,lineno,filename)
3084FILE *out;
3085int lineno;
3086char *filename;
3087{
3088 fprintf(out,"#line %d \"",lineno);
3089 while( *filename ){
3090 if( *filename == '\\' ) putc('\\',out);
3091 putc(*filename,out);
3092 filename++;
3093 }
3094 fprintf(out,"\"\n");
3095}
3096
drh75897232000-05-29 14:26:00 +00003097/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003098PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003099FILE *out;
3100struct lemon *lemp;
3101char *str;
drh75897232000-05-29 14:26:00 +00003102int *lineno;
3103{
3104 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003105 (*lineno)++;
drh75897232000-05-29 14:26:00 +00003106 while( *str ){
3107 if( *str=='\n' ) (*lineno)++;
3108 putc(*str,out);
3109 str++;
3110 }
drh9db55df2004-09-09 14:01:21 +00003111 if( str[-1]!='\n' ){
3112 putc('\n',out);
3113 (*lineno)++;
3114 }
drhaf805ca2004-09-07 11:28:25 +00003115 tplt_linedir(out,*lineno+2,lemp->outname);
3116 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00003117 return;
3118}
3119
3120/*
3121** The following routine emits code for the destructor for the
3122** symbol sp
3123*/
3124void emit_destructor_code(out,sp,lemp,lineno)
3125FILE *out;
3126struct symbol *sp;
3127struct lemon *lemp;
3128int *lineno;
3129{
drhcc83b6e2004-04-23 23:38:42 +00003130 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003131
3132 int linecnt = 0;
3133 if( sp->type==TERMINAL ){
3134 cp = lemp->tokendest;
3135 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003136 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003137 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003138 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003139 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003140 }else if( lemp->vardest ){
3141 cp = lemp->vardest;
3142 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003143 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003144 }else{
3145 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003146 }
3147 for(; *cp; cp++){
3148 if( *cp=='$' && cp[1]=='$' ){
3149 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3150 cp++;
3151 continue;
3152 }
3153 if( *cp=='\n' ) linecnt++;
3154 fputc(*cp,out);
3155 }
3156 (*lineno) += 3 + linecnt;
drha5808f32008-04-27 22:19:44 +00003157 fprintf(out,"\n");
drhaf805ca2004-09-07 11:28:25 +00003158 tplt_linedir(out,*lineno,lemp->outname);
drha5808f32008-04-27 22:19:44 +00003159 fprintf(out,"}\n");
drh75897232000-05-29 14:26:00 +00003160 return;
3161}
3162
3163/*
drh960e8c62001-04-03 16:53:21 +00003164** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003165*/
3166int has_destructor(sp, lemp)
3167struct symbol *sp;
3168struct lemon *lemp;
3169{
3170 int ret;
3171 if( sp->type==TERMINAL ){
3172 ret = lemp->tokendest!=0;
3173 }else{
drh960e8c62001-04-03 16:53:21 +00003174 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003175 }
3176 return ret;
3177}
3178
drh0bb132b2004-07-20 14:06:51 +00003179/*
3180** Append text to a dynamically allocated string. If zText is 0 then
3181** reset the string to be empty again. Always return the complete text
3182** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003183**
3184** n bytes of zText are stored. If n==0 then all of zText up to the first
3185** \000 terminator is stored. zText can contain up to two instances of
3186** %d. The values of p1 and p2 are written into the first and second
3187** %d.
3188**
3189** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003190*/
3191PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3192 static char *z = 0;
3193 static int alloced = 0;
3194 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003195 int c;
drh0bb132b2004-07-20 14:06:51 +00003196 char zInt[40];
3197
3198 if( zText==0 ){
3199 used = 0;
3200 return z;
3201 }
drh7ac25c72004-08-19 15:12:26 +00003202 if( n<=0 ){
3203 if( n<0 ){
3204 used += n;
3205 assert( used>=0 );
3206 }
3207 n = strlen(zText);
3208 }
drh0bb132b2004-07-20 14:06:51 +00003209 if( n+sizeof(zInt)*2+used >= alloced ){
3210 alloced = n + sizeof(zInt)*2 + used + 200;
3211 z = realloc(z, alloced);
3212 }
3213 if( z==0 ) return "";
3214 while( n-- > 0 ){
3215 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003216 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003217 sprintf(zInt, "%d", p1);
3218 p1 = p2;
3219 strcpy(&z[used], zInt);
3220 used += strlen(&z[used]);
3221 zText++;
3222 n--;
3223 }else{
3224 z[used++] = c;
3225 }
3226 }
3227 z[used] = 0;
3228 return z;
3229}
3230
3231/*
3232** zCode is a string that is the action associated with a rule. Expand
3233** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003234** stack.
drh0bb132b2004-07-20 14:06:51 +00003235*/
drhaf805ca2004-09-07 11:28:25 +00003236PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003237 char *cp, *xp;
3238 int i;
3239 char lhsused = 0; /* True if the LHS element has been used */
3240 char used[MAXRHS]; /* True for each RHS element which is used */
3241
3242 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3243 lhsused = 0;
3244
drh19c9e562007-03-29 20:13:53 +00003245 if( rp->code==0 ){
3246 rp->code = "\n";
3247 rp->line = rp->ruleline;
3248 }
3249
drh0bb132b2004-07-20 14:06:51 +00003250 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003251 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003252 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3253 char saved;
3254 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3255 saved = *xp;
3256 *xp = 0;
3257 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003258 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003259 cp = xp;
3260 lhsused = 1;
3261 }else{
3262 for(i=0; i<rp->nrhs; i++){
3263 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003264 if( cp!=rp->code && cp[-1]=='@' ){
3265 /* If the argument is of the form @X then substituted
3266 ** the token number of X, not the value of X */
3267 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3268 }else{
drhfd405312005-11-06 04:06:59 +00003269 struct symbol *sp = rp->rhs[i];
3270 int dtnum;
3271 if( sp->type==MULTITERMINAL ){
3272 dtnum = sp->subsym[0]->dtnum;
3273 }else{
3274 dtnum = sp->dtnum;
3275 }
3276 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003277 }
drh0bb132b2004-07-20 14:06:51 +00003278 cp = xp;
3279 used[i] = 1;
3280 break;
3281 }
3282 }
3283 }
3284 *xp = saved;
3285 }
3286 append_str(cp, 1, 0, 0);
3287 } /* End loop */
3288
3289 /* Check to make sure the LHS has been used */
3290 if( rp->lhsalias && !lhsused ){
3291 ErrorMsg(lemp->filename,rp->ruleline,
3292 "Label \"%s\" for \"%s(%s)\" is never used.",
3293 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3294 lemp->errorcnt++;
3295 }
3296
3297 /* Generate destructor code for RHS symbols which are not used in the
3298 ** reduce code */
3299 for(i=0; i<rp->nrhs; i++){
3300 if( rp->rhsalias[i] && !used[i] ){
3301 ErrorMsg(lemp->filename,rp->ruleline,
3302 "Label %s for \"%s(%s)\" is never used.",
3303 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3304 lemp->errorcnt++;
3305 }else if( rp->rhsalias[i]==0 ){
3306 if( has_destructor(rp->rhs[i],lemp) ){
drh7ac25c72004-08-19 15:12:26 +00003307 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003308 rp->rhs[i]->index,i-rp->nrhs+1);
3309 }else{
3310 /* No destructor defined for this term */
3311 }
3312 }
3313 }
drh61e339a2007-01-16 03:09:02 +00003314 if( rp->code ){
3315 cp = append_str(0,0,0,0);
3316 rp->code = Strsafe(cp?cp:"");
3317 }
drh0bb132b2004-07-20 14:06:51 +00003318}
3319
drh75897232000-05-29 14:26:00 +00003320/*
3321** Generate code which executes when the rule "rp" is reduced. Write
3322** the code to "out". Make sure lineno stays up-to-date.
3323*/
3324PRIVATE void emit_code(out,rp,lemp,lineno)
3325FILE *out;
3326struct rule *rp;
3327struct lemon *lemp;
3328int *lineno;
3329{
drh0bb132b2004-07-20 14:06:51 +00003330 char *cp;
drh75897232000-05-29 14:26:00 +00003331 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003332
3333 /* Generate code to do the reduce action */
3334 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003335 tplt_linedir(out,rp->line,lemp->filename);
3336 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003337 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003338 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003339 } /* End loop */
3340 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003341 fprintf(out,"}\n");
3342 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003343 } /* End if( rp->code ) */
3344
drh75897232000-05-29 14:26:00 +00003345 return;
3346}
3347
3348/*
3349** Print the definition of the union used for the parser's data stack.
3350** This union contains fields for every possible data type for tokens
3351** and nonterminals. In the process of computing and printing this
3352** union, also set the ".dtnum" field of every terminal and nonterminal
3353** symbol.
3354*/
3355void print_stack_union(out,lemp,plineno,mhflag)
3356FILE *out; /* The output stream */
3357struct lemon *lemp; /* The main info structure for this parser */
3358int *plineno; /* Pointer to the line number */
3359int mhflag; /* True if generating makeheaders output */
3360{
3361 int lineno = *plineno; /* The line number of the output */
3362 char **types; /* A hash table of datatypes */
3363 int arraysize; /* Size of the "types" array */
3364 int maxdtlength; /* Maximum length of any ".datatype" field. */
3365 char *stddt; /* Standardized name for a datatype */
3366 int i,j; /* Loop counters */
3367 int hash; /* For hashing the name of a type */
3368 char *name; /* Name of the parser */
3369
3370 /* Allocate and initialize types[] and allocate stddt[] */
3371 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003372 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003373 for(i=0; i<arraysize; i++) types[i] = 0;
3374 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003375 if( lemp->vartype ){
3376 maxdtlength = strlen(lemp->vartype);
3377 }
drh75897232000-05-29 14:26:00 +00003378 for(i=0; i<lemp->nsymbol; i++){
3379 int len;
3380 struct symbol *sp = lemp->symbols[i];
3381 if( sp->datatype==0 ) continue;
3382 len = strlen(sp->datatype);
3383 if( len>maxdtlength ) maxdtlength = len;
3384 }
3385 stddt = (char*)malloc( maxdtlength*2 + 1 );
3386 if( types==0 || stddt==0 ){
3387 fprintf(stderr,"Out of memory.\n");
3388 exit(1);
3389 }
3390
3391 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3392 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003393 ** used for terminal symbols. If there is no %default_type defined then
3394 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3395 ** a datatype using the %type directive.
3396 */
drh75897232000-05-29 14:26:00 +00003397 for(i=0; i<lemp->nsymbol; i++){
3398 struct symbol *sp = lemp->symbols[i];
3399 char *cp;
3400 if( sp==lemp->errsym ){
3401 sp->dtnum = arraysize+1;
3402 continue;
3403 }
drh960e8c62001-04-03 16:53:21 +00003404 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003405 sp->dtnum = 0;
3406 continue;
3407 }
3408 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003409 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003410 j = 0;
3411 while( isspace(*cp) ) cp++;
3412 while( *cp ) stddt[j++] = *cp++;
3413 while( j>0 && isspace(stddt[j-1]) ) j--;
3414 stddt[j] = 0;
drh32c4d742008-07-01 16:34:49 +00003415 if( strcmp(stddt, lemp->tokentype)==0 ){
3416 sp->dtnum = 0;
3417 continue;
3418 }
drh75897232000-05-29 14:26:00 +00003419 hash = 0;
3420 for(j=0; stddt[j]; j++){
3421 hash = hash*53 + stddt[j];
3422 }
drh3b2129c2003-05-13 00:34:21 +00003423 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003424 while( types[hash] ){
3425 if( strcmp(types[hash],stddt)==0 ){
3426 sp->dtnum = hash + 1;
3427 break;
3428 }
3429 hash++;
3430 if( hash>=arraysize ) hash = 0;
3431 }
3432 if( types[hash]==0 ){
3433 sp->dtnum = hash + 1;
3434 types[hash] = (char*)malloc( strlen(stddt)+1 );
3435 if( types[hash]==0 ){
3436 fprintf(stderr,"Out of memory.\n");
3437 exit(1);
3438 }
3439 strcpy(types[hash],stddt);
3440 }
3441 }
3442
3443 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3444 name = lemp->name ? lemp->name : "Parse";
3445 lineno = *plineno;
3446 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3447 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3448 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3449 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3450 fprintf(out,"typedef union {\n"); lineno++;
3451 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3452 for(i=0; i<arraysize; i++){
3453 if( types[i]==0 ) continue;
3454 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3455 free(types[i]);
3456 }
drhc4dd3fd2008-01-22 01:48:05 +00003457 if( lemp->errsym->useCnt ){
3458 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3459 }
drh75897232000-05-29 14:26:00 +00003460 free(stddt);
3461 free(types);
3462 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3463 *plineno = lineno;
3464}
3465
drhb29b0a52002-02-23 19:39:46 +00003466/*
3467** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003468** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003469*/
drh8b582012003-10-21 13:16:03 +00003470static const char *minimum_size_type(int lwr, int upr){
3471 if( lwr>=0 ){
3472 if( upr<=255 ){
3473 return "unsigned char";
3474 }else if( upr<65535 ){
3475 return "unsigned short int";
3476 }else{
3477 return "unsigned int";
3478 }
3479 }else if( lwr>=-127 && upr<=127 ){
3480 return "signed char";
3481 }else if( lwr>=-32767 && upr<32767 ){
3482 return "short";
drhb29b0a52002-02-23 19:39:46 +00003483 }else{
drh8b582012003-10-21 13:16:03 +00003484 return "int";
drhb29b0a52002-02-23 19:39:46 +00003485 }
3486}
3487
drhfdbf9282003-10-21 16:34:41 +00003488/*
3489** Each state contains a set of token transaction and a set of
3490** nonterminal transactions. Each of these sets makes an instance
3491** of the following structure. An array of these structures is used
3492** to order the creation of entries in the yy_action[] table.
3493*/
3494struct axset {
3495 struct state *stp; /* A pointer to a state */
3496 int isTkn; /* True to use tokens. False for non-terminals */
3497 int nAction; /* Number of actions */
3498};
3499
3500/*
3501** Compare to axset structures for sorting purposes
3502*/
3503static int axset_compare(const void *a, const void *b){
3504 struct axset *p1 = (struct axset*)a;
3505 struct axset *p2 = (struct axset*)b;
3506 return p2->nAction - p1->nAction;
3507}
3508
drhc4dd3fd2008-01-22 01:48:05 +00003509/*
3510** Write text on "out" that describes the rule "rp".
3511*/
3512static void writeRuleText(FILE *out, struct rule *rp){
3513 int j;
3514 fprintf(out,"%s ::=", rp->lhs->name);
3515 for(j=0; j<rp->nrhs; j++){
3516 struct symbol *sp = rp->rhs[j];
3517 fprintf(out," %s", sp->name);
3518 if( sp->type==MULTITERMINAL ){
3519 int k;
3520 for(k=1; k<sp->nsubsym; k++){
3521 fprintf(out,"|%s",sp->subsym[k]->name);
3522 }
3523 }
3524 }
3525}
3526
3527
drh75897232000-05-29 14:26:00 +00003528/* Generate C source code for the parser */
3529void ReportTable(lemp, mhflag)
3530struct lemon *lemp;
3531int mhflag; /* Output in makeheaders format if true */
3532{
3533 FILE *out, *in;
3534 char line[LINESIZE];
3535 int lineno;
3536 struct state *stp;
3537 struct action *ap;
3538 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003539 struct acttab *pActtab;
3540 int i, j, n;
drh75897232000-05-29 14:26:00 +00003541 char *name;
drh8b582012003-10-21 13:16:03 +00003542 int mnTknOfst, mxTknOfst;
3543 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003544 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003545
3546 in = tplt_open(lemp);
3547 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003548 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003549 if( out==0 ){
3550 fclose(in);
3551 return;
3552 }
3553 lineno = 1;
3554 tplt_xfer(lemp->name,in,out,&lineno);
3555
3556 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003557 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003558 if( mhflag ){
3559 char *name = file_makename(lemp, ".h");
3560 fprintf(out,"#include \"%s\"\n", name); lineno++;
3561 free(name);
3562 }
3563 tplt_xfer(lemp->name,in,out,&lineno);
3564
3565 /* Generate #defines for all tokens */
3566 if( mhflag ){
3567 char *prefix;
3568 fprintf(out,"#if INTERFACE\n"); lineno++;
3569 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3570 else prefix = "";
3571 for(i=1; i<lemp->nterminal; i++){
3572 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3573 lineno++;
3574 }
3575 fprintf(out,"#endif\n"); lineno++;
3576 }
3577 tplt_xfer(lemp->name,in,out,&lineno);
3578
3579 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003580 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003581 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003582 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3583 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003584 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003585 if( lemp->wildcard ){
3586 fprintf(out,"#define YYWILDCARD %d\n",
3587 lemp->wildcard->index); lineno++;
3588 }
drh75897232000-05-29 14:26:00 +00003589 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003590 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003591 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003592 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3593 }else{
3594 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3595 }
drhca44b5a2007-02-22 23:06:58 +00003596 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003597 if( mhflag ){
3598 fprintf(out,"#if INTERFACE\n"); lineno++;
3599 }
3600 name = lemp->name ? lemp->name : "Parse";
3601 if( lemp->arg && lemp->arg[0] ){
3602 int i;
3603 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003604 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3605 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003606 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3607 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3608 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3609 name,lemp->arg,&lemp->arg[i]); lineno++;
3610 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3611 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003612 }else{
drh1f245e42002-03-11 13:55:50 +00003613 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3614 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3615 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3616 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003617 }
3618 if( mhflag ){
3619 fprintf(out,"#endif\n"); lineno++;
3620 }
3621 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3622 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003623 if( lemp->errsym->useCnt ){
3624 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3625 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3626 }
drh0bd1f4e2002-06-06 18:54:39 +00003627 if( lemp->has_fallback ){
3628 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3629 }
drh75897232000-05-29 14:26:00 +00003630 tplt_xfer(lemp->name,in,out,&lineno);
3631
drh8b582012003-10-21 13:16:03 +00003632 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003633 **
drh8b582012003-10-21 13:16:03 +00003634 ** yy_action[] A single table containing all actions.
3635 ** yy_lookahead[] A table containing the lookahead for each entry in
3636 ** yy_action. Used to detect hash collisions.
3637 ** yy_shift_ofst[] For each state, the offset into yy_action for
3638 ** shifting terminals.
3639 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3640 ** shifting non-terminals after a reduce.
3641 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003642 */
drh75897232000-05-29 14:26:00 +00003643
drh8b582012003-10-21 13:16:03 +00003644 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003645 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003646 if( ax==0 ){
3647 fprintf(stderr,"malloc failed\n");
3648 exit(1);
3649 }
drh75897232000-05-29 14:26:00 +00003650 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003651 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003652 ax[i*2].stp = stp;
3653 ax[i*2].isTkn = 1;
3654 ax[i*2].nAction = stp->nTknAct;
3655 ax[i*2+1].stp = stp;
3656 ax[i*2+1].isTkn = 0;
3657 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003658 }
drh8b582012003-10-21 13:16:03 +00003659 mxTknOfst = mnTknOfst = 0;
3660 mxNtOfst = mnNtOfst = 0;
3661
drhfdbf9282003-10-21 16:34:41 +00003662 /* Compute the action table. In order to try to keep the size of the
3663 ** action table to a minimum, the heuristic of placing the largest action
3664 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003665 */
drhfdbf9282003-10-21 16:34:41 +00003666 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003667 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003668 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3669 stp = ax[i].stp;
3670 if( ax[i].isTkn ){
3671 for(ap=stp->ap; ap; ap=ap->next){
3672 int action;
3673 if( ap->sp->index>=lemp->nterminal ) continue;
3674 action = compute_action(lemp, ap);
3675 if( action<0 ) continue;
3676 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003677 }
drhfdbf9282003-10-21 16:34:41 +00003678 stp->iTknOfst = acttab_insert(pActtab);
3679 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3680 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3681 }else{
3682 for(ap=stp->ap; ap; ap=ap->next){
3683 int action;
3684 if( ap->sp->index<lemp->nterminal ) continue;
3685 if( ap->sp->index==lemp->nsymbol ) continue;
3686 action = compute_action(lemp, ap);
3687 if( action<0 ) continue;
3688 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003689 }
drhfdbf9282003-10-21 16:34:41 +00003690 stp->iNtOfst = acttab_insert(pActtab);
3691 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3692 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003693 }
3694 }
drhfdbf9282003-10-21 16:34:41 +00003695 free(ax);
drh8b582012003-10-21 13:16:03 +00003696
3697 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003698 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003699 n = acttab_size(pActtab);
3700 for(i=j=0; i<n; i++){
3701 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003702 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003703 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003704 fprintf(out, " %4d,", action);
3705 if( j==9 || i==n-1 ){
3706 fprintf(out, "\n"); lineno++;
3707 j = 0;
3708 }else{
3709 j++;
3710 }
3711 }
3712 fprintf(out, "};\n"); lineno++;
3713
3714 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003715 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003716 for(i=j=0; i<n; i++){
3717 int la = acttab_yylookahead(pActtab, i);
3718 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003719 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003720 fprintf(out, " %4d,", la);
3721 if( j==9 || i==n-1 ){
3722 fprintf(out, "\n"); lineno++;
3723 j = 0;
3724 }else{
3725 j++;
3726 }
3727 }
3728 fprintf(out, "};\n"); lineno++;
3729
3730 /* Output the yy_shift_ofst[] table */
3731 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003732 n = lemp->nstate;
3733 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3734 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003735 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003736 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003737 for(i=j=0; i<n; i++){
3738 int ofst;
3739 stp = lemp->sorted[i];
3740 ofst = stp->iTknOfst;
3741 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003742 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003743 fprintf(out, " %4d,", ofst);
3744 if( j==9 || i==n-1 ){
3745 fprintf(out, "\n"); lineno++;
3746 j = 0;
3747 }else{
3748 j++;
3749 }
3750 }
3751 fprintf(out, "};\n"); lineno++;
3752
3753 /* Output the yy_reduce_ofst[] table */
3754 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003755 n = lemp->nstate;
3756 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3757 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003758 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003759 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003760 for(i=j=0; i<n; i++){
3761 int ofst;
3762 stp = lemp->sorted[i];
3763 ofst = stp->iNtOfst;
3764 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003765 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003766 fprintf(out, " %4d,", ofst);
3767 if( j==9 || i==n-1 ){
3768 fprintf(out, "\n"); lineno++;
3769 j = 0;
3770 }else{
3771 j++;
3772 }
3773 }
3774 fprintf(out, "};\n"); lineno++;
3775
3776 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003777 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003778 n = lemp->nstate;
3779 for(i=j=0; i<n; i++){
3780 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003781 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003782 fprintf(out, " %4d,", stp->iDflt);
3783 if( j==9 || i==n-1 ){
3784 fprintf(out, "\n"); lineno++;
3785 j = 0;
3786 }else{
3787 j++;
3788 }
3789 }
3790 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003791 tplt_xfer(lemp->name,in,out,&lineno);
3792
drh0bd1f4e2002-06-06 18:54:39 +00003793 /* Generate the table of fallback tokens.
3794 */
3795 if( lemp->has_fallback ){
3796 for(i=0; i<lemp->nterminal; i++){
3797 struct symbol *p = lemp->symbols[i];
3798 if( p->fallback==0 ){
3799 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3800 }else{
3801 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3802 p->name, p->fallback->name);
3803 }
3804 lineno++;
3805 }
3806 }
3807 tplt_xfer(lemp->name, in, out, &lineno);
3808
3809 /* Generate a table containing the symbolic name of every symbol
3810 */
drh75897232000-05-29 14:26:00 +00003811 for(i=0; i<lemp->nsymbol; i++){
3812 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3813 fprintf(out," %-15s",line);
3814 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3815 }
3816 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3817 tplt_xfer(lemp->name,in,out,&lineno);
3818
drh0bd1f4e2002-06-06 18:54:39 +00003819 /* Generate a table containing a text string that describes every
3820 ** rule in the rule set of the grammer. This information is used
3821 ** when tracing REDUCE actions.
3822 */
3823 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3824 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003825 fprintf(out," /* %3d */ \"", i);
3826 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003827 fprintf(out,"\",\n"); lineno++;
3828 }
3829 tplt_xfer(lemp->name,in,out,&lineno);
3830
drh75897232000-05-29 14:26:00 +00003831 /* Generate code which executes every time a symbol is popped from
3832 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003833 ** (In other words, generate the %destructor actions)
3834 */
drh75897232000-05-29 14:26:00 +00003835 if( lemp->tokendest ){
3836 for(i=0; i<lemp->nsymbol; i++){
3837 struct symbol *sp = lemp->symbols[i];
3838 if( sp==0 || sp->type!=TERMINAL ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003839 fprintf(out," case %d: /* %s */\n",
3840 sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003841 }
3842 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3843 if( i<lemp->nsymbol ){
3844 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3845 fprintf(out," break;\n"); lineno++;
3846 }
3847 }
drh8d659732005-01-13 23:54:06 +00003848 if( lemp->vardest ){
3849 struct symbol *dflt_sp = 0;
3850 for(i=0; i<lemp->nsymbol; i++){
3851 struct symbol *sp = lemp->symbols[i];
3852 if( sp==0 || sp->type==TERMINAL ||
3853 sp->index<=0 || sp->destructor!=0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003854 fprintf(out," case %d: /* %s */\n",
3855 sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003856 dflt_sp = sp;
3857 }
3858 if( dflt_sp!=0 ){
3859 emit_destructor_code(out,dflt_sp,lemp,&lineno);
3860 fprintf(out," break;\n"); lineno++;
3861 }
3862 }
drh75897232000-05-29 14:26:00 +00003863 for(i=0; i<lemp->nsymbol; i++){
3864 struct symbol *sp = lemp->symbols[i];
3865 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003866 fprintf(out," case %d: /* %s */\n",
3867 sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003868
3869 /* Combine duplicate destructors into a single case */
3870 for(j=i+1; j<lemp->nsymbol; j++){
3871 struct symbol *sp2 = lemp->symbols[j];
3872 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3873 && sp2->dtnum==sp->dtnum
3874 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc4dd3fd2008-01-22 01:48:05 +00003875 fprintf(out," case %d: /* %s */\n",
3876 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003877 sp2->destructor = 0;
3878 }
3879 }
3880
drh75897232000-05-29 14:26:00 +00003881 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3882 fprintf(out," break;\n"); lineno++;
3883 }
drh75897232000-05-29 14:26:00 +00003884 tplt_xfer(lemp->name,in,out,&lineno);
3885
3886 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003887 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003888 tplt_xfer(lemp->name,in,out,&lineno);
3889
3890 /* Generate the table of rule information
3891 **
3892 ** Note: This code depends on the fact that rules are number
3893 ** sequentually beginning with 0.
3894 */
3895 for(rp=lemp->rule; rp; rp=rp->next){
3896 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3897 }
3898 tplt_xfer(lemp->name,in,out,&lineno);
3899
3900 /* Generate code which execution during each REDUCE action */
3901 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003902 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003903 }
3904 for(rp=lemp->rule; rp; rp=rp->next){
3905 struct rule *rp2;
3906 if( rp->code==0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003907 fprintf(out," case %d: /* ", rp->index);
3908 writeRuleText(out, rp);
3909 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003910 for(rp2=rp->next; rp2; rp2=rp2->next){
3911 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003912 fprintf(out," case %d: /* ", rp2->index);
3913 writeRuleText(out, rp2);
3914 fprintf(out," */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003915 rp2->code = 0;
3916 }
3917 }
drh75897232000-05-29 14:26:00 +00003918 emit_code(out,rp,lemp,&lineno);
3919 fprintf(out," break;\n"); lineno++;
3920 }
3921 tplt_xfer(lemp->name,in,out,&lineno);
3922
3923 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003924 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00003925 tplt_xfer(lemp->name,in,out,&lineno);
3926
3927 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00003928 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00003929 tplt_xfer(lemp->name,in,out,&lineno);
3930
3931 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00003932 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00003933 tplt_xfer(lemp->name,in,out,&lineno);
3934
3935 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00003936 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00003937
3938 fclose(in);
3939 fclose(out);
3940 return;
3941}
3942
3943/* Generate a header file for the parser */
3944void ReportHeader(lemp)
3945struct lemon *lemp;
3946{
3947 FILE *out, *in;
3948 char *prefix;
3949 char line[LINESIZE];
3950 char pattern[LINESIZE];
3951 int i;
3952
3953 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3954 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003955 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003956 if( in ){
3957 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3958 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3959 if( strcmp(line,pattern) ) break;
3960 }
3961 fclose(in);
3962 if( i==lemp->nterminal ){
3963 /* No change in the file. Don't rewrite it. */
3964 return;
3965 }
3966 }
drh2aa6ca42004-09-10 00:14:04 +00003967 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003968 if( out ){
3969 for(i=1; i<lemp->nterminal; i++){
3970 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3971 }
3972 fclose(out);
3973 }
3974 return;
3975}
3976
3977/* Reduce the size of the action tables, if possible, by making use
3978** of defaults.
3979**
drhb59499c2002-02-23 18:45:13 +00003980** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00003981** it the default. Except, there is no default if the wildcard token
3982** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00003983*/
3984void CompressTables(lemp)
3985struct lemon *lemp;
3986{
3987 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00003988 struct action *ap, *ap2;
3989 struct rule *rp, *rp2, *rbest;
3990 int nbest, n;
drh75897232000-05-29 14:26:00 +00003991 int i;
drhe09daa92006-06-10 13:29:31 +00003992 int usesWildcard;
drh75897232000-05-29 14:26:00 +00003993
3994 for(i=0; i<lemp->nstate; i++){
3995 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00003996 nbest = 0;
3997 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00003998 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00003999
drhb59499c2002-02-23 18:45:13 +00004000 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004001 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4002 usesWildcard = 1;
4003 }
drhb59499c2002-02-23 18:45:13 +00004004 if( ap->type!=REDUCE ) continue;
4005 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004006 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004007 if( rp==rbest ) continue;
4008 n = 1;
4009 for(ap2=ap->next; ap2; ap2=ap2->next){
4010 if( ap2->type!=REDUCE ) continue;
4011 rp2 = ap2->x.rp;
4012 if( rp2==rbest ) continue;
4013 if( rp2==rp ) n++;
4014 }
4015 if( n>nbest ){
4016 nbest = n;
4017 rbest = rp;
drh75897232000-05-29 14:26:00 +00004018 }
4019 }
drhb59499c2002-02-23 18:45:13 +00004020
4021 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004022 ** is not at least 1 or if the wildcard token is a possible
4023 ** lookahead.
4024 */
4025 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004026
drhb59499c2002-02-23 18:45:13 +00004027
4028 /* Combine matching REDUCE actions into a single default */
4029 for(ap=stp->ap; ap; ap=ap->next){
4030 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4031 }
drh75897232000-05-29 14:26:00 +00004032 assert( ap );
4033 ap->sp = Symbol_new("{default}");
4034 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004035 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004036 }
4037 stp->ap = Action_sort(stp->ap);
4038 }
4039}
drhb59499c2002-02-23 18:45:13 +00004040
drhada354d2005-11-05 15:03:59 +00004041
4042/*
4043** Compare two states for sorting purposes. The smaller state is the
4044** one with the most non-terminal actions. If they have the same number
4045** of non-terminal actions, then the smaller is the one with the most
4046** token actions.
4047*/
4048static int stateResortCompare(const void *a, const void *b){
4049 const struct state *pA = *(const struct state**)a;
4050 const struct state *pB = *(const struct state**)b;
4051 int n;
4052
4053 n = pB->nNtAct - pA->nNtAct;
4054 if( n==0 ){
4055 n = pB->nTknAct - pA->nTknAct;
4056 }
4057 return n;
4058}
4059
4060
4061/*
4062** Renumber and resort states so that states with fewer choices
4063** occur at the end. Except, keep state 0 as the first state.
4064*/
4065void ResortStates(lemp)
4066struct lemon *lemp;
4067{
4068 int i;
4069 struct state *stp;
4070 struct action *ap;
4071
4072 for(i=0; i<lemp->nstate; i++){
4073 stp = lemp->sorted[i];
4074 stp->nTknAct = stp->nNtAct = 0;
4075 stp->iDflt = lemp->nstate + lemp->nrule;
4076 stp->iTknOfst = NO_OFFSET;
4077 stp->iNtOfst = NO_OFFSET;
4078 for(ap=stp->ap; ap; ap=ap->next){
4079 if( compute_action(lemp,ap)>=0 ){
4080 if( ap->sp->index<lemp->nterminal ){
4081 stp->nTknAct++;
4082 }else if( ap->sp->index<lemp->nsymbol ){
4083 stp->nNtAct++;
4084 }else{
4085 stp->iDflt = compute_action(lemp, ap);
4086 }
4087 }
4088 }
4089 }
4090 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4091 stateResortCompare);
4092 for(i=0; i<lemp->nstate; i++){
4093 lemp->sorted[i]->statenum = i;
4094 }
4095}
4096
4097
drh75897232000-05-29 14:26:00 +00004098/***************** From the file "set.c" ************************************/
4099/*
4100** Set manipulation routines for the LEMON parser generator.
4101*/
4102
4103static int size = 0;
4104
4105/* Set the set size */
4106void SetSize(n)
4107int n;
4108{
4109 size = n+1;
4110}
4111
4112/* Allocate a new set */
4113char *SetNew(){
4114 char *s;
drh9892c5d2007-12-21 00:02:11 +00004115 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004116 if( s==0 ){
4117 extern void memory_error();
4118 memory_error();
4119 }
drh75897232000-05-29 14:26:00 +00004120 return s;
4121}
4122
4123/* Deallocate a set */
4124void SetFree(s)
4125char *s;
4126{
4127 free(s);
4128}
4129
4130/* Add a new element to the set. Return TRUE if the element was added
4131** and FALSE if it was already there. */
4132int SetAdd(s,e)
4133char *s;
4134int e;
4135{
4136 int rv;
drh9892c5d2007-12-21 00:02:11 +00004137 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004138 rv = s[e];
4139 s[e] = 1;
4140 return !rv;
4141}
4142
4143/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4144int SetUnion(s1,s2)
4145char *s1;
4146char *s2;
4147{
4148 int i, progress;
4149 progress = 0;
4150 for(i=0; i<size; i++){
4151 if( s2[i]==0 ) continue;
4152 if( s1[i]==0 ){
4153 progress = 1;
4154 s1[i] = 1;
4155 }
4156 }
4157 return progress;
4158}
4159/********************** From the file "table.c" ****************************/
4160/*
4161** All code in this file has been automatically generated
4162** from a specification in the file
4163** "table.q"
4164** by the associative array code building program "aagen".
4165** Do not edit this file! Instead, edit the specification
4166** file, then rerun aagen.
4167*/
4168/*
4169** Code for processing tables in the LEMON parser generator.
4170*/
4171
4172PRIVATE int strhash(x)
4173char *x;
4174{
4175 int h = 0;
4176 while( *x) h = h*13 + *(x++);
4177 return h;
4178}
4179
4180/* Works like strdup, sort of. Save a string in malloced memory, but
4181** keep strings in a table so that the same string is not in more
4182** than one place.
4183*/
4184char *Strsafe(y)
4185char *y;
4186{
4187 char *z;
4188
drh916f75f2006-07-17 00:19:39 +00004189 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004190 z = Strsafe_find(y);
4191 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4192 strcpy(z,y);
4193 Strsafe_insert(z);
4194 }
4195 MemoryCheck(z);
4196 return z;
4197}
4198
4199/* There is one instance of the following structure for each
4200** associative array of type "x1".
4201*/
4202struct s_x1 {
4203 int size; /* The number of available slots. */
4204 /* Must be a power of 2 greater than or */
4205 /* equal to 1 */
4206 int count; /* Number of currently slots filled */
4207 struct s_x1node *tbl; /* The data stored here */
4208 struct s_x1node **ht; /* Hash table for lookups */
4209};
4210
4211/* There is one instance of this structure for every data element
4212** in an associative array of type "x1".
4213*/
4214typedef struct s_x1node {
4215 char *data; /* The data */
4216 struct s_x1node *next; /* Next entry with the same hash */
4217 struct s_x1node **from; /* Previous link */
4218} x1node;
4219
4220/* There is only one instance of the array, which is the following */
4221static struct s_x1 *x1a;
4222
4223/* Allocate a new associative array */
4224void Strsafe_init(){
4225 if( x1a ) return;
4226 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4227 if( x1a ){
4228 x1a->size = 1024;
4229 x1a->count = 0;
4230 x1a->tbl = (x1node*)malloc(
4231 (sizeof(x1node) + sizeof(x1node*))*1024 );
4232 if( x1a->tbl==0 ){
4233 free(x1a);
4234 x1a = 0;
4235 }else{
4236 int i;
4237 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4238 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4239 }
4240 }
4241}
4242/* Insert a new record into the array. Return TRUE if successful.
4243** Prior data with the same key is NOT overwritten */
4244int Strsafe_insert(data)
4245char *data;
4246{
4247 x1node *np;
4248 int h;
4249 int ph;
4250
4251 if( x1a==0 ) return 0;
4252 ph = strhash(data);
4253 h = ph & (x1a->size-1);
4254 np = x1a->ht[h];
4255 while( np ){
4256 if( strcmp(np->data,data)==0 ){
4257 /* An existing entry with the same key is found. */
4258 /* Fail because overwrite is not allows. */
4259 return 0;
4260 }
4261 np = np->next;
4262 }
4263 if( x1a->count>=x1a->size ){
4264 /* Need to make the hash table bigger */
4265 int i,size;
4266 struct s_x1 array;
4267 array.size = size = x1a->size*2;
4268 array.count = x1a->count;
4269 array.tbl = (x1node*)malloc(
4270 (sizeof(x1node) + sizeof(x1node*))*size );
4271 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4272 array.ht = (x1node**)&(array.tbl[size]);
4273 for(i=0; i<size; i++) array.ht[i] = 0;
4274 for(i=0; i<x1a->count; i++){
4275 x1node *oldnp, *newnp;
4276 oldnp = &(x1a->tbl[i]);
4277 h = strhash(oldnp->data) & (size-1);
4278 newnp = &(array.tbl[i]);
4279 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4280 newnp->next = array.ht[h];
4281 newnp->data = oldnp->data;
4282 newnp->from = &(array.ht[h]);
4283 array.ht[h] = newnp;
4284 }
4285 free(x1a->tbl);
4286 *x1a = array;
4287 }
4288 /* Insert the new data */
4289 h = ph & (x1a->size-1);
4290 np = &(x1a->tbl[x1a->count++]);
4291 np->data = data;
4292 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4293 np->next = x1a->ht[h];
4294 x1a->ht[h] = np;
4295 np->from = &(x1a->ht[h]);
4296 return 1;
4297}
4298
4299/* Return a pointer to data assigned to the given key. Return NULL
4300** if no such key. */
4301char *Strsafe_find(key)
4302char *key;
4303{
4304 int h;
4305 x1node *np;
4306
4307 if( x1a==0 ) return 0;
4308 h = strhash(key) & (x1a->size-1);
4309 np = x1a->ht[h];
4310 while( np ){
4311 if( strcmp(np->data,key)==0 ) break;
4312 np = np->next;
4313 }
4314 return np ? np->data : 0;
4315}
4316
4317/* Return a pointer to the (terminal or nonterminal) symbol "x".
4318** Create a new symbol if this is the first time "x" has been seen.
4319*/
4320struct symbol *Symbol_new(x)
4321char *x;
4322{
4323 struct symbol *sp;
4324
4325 sp = Symbol_find(x);
4326 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004327 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004328 MemoryCheck(sp);
4329 sp->name = Strsafe(x);
4330 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4331 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004332 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004333 sp->prec = -1;
4334 sp->assoc = UNK;
4335 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004336 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004337 sp->destructor = 0;
4338 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004339 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004340 Symbol_insert(sp,sp->name);
4341 }
drhc4dd3fd2008-01-22 01:48:05 +00004342 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004343 return sp;
4344}
4345
drh60d31652004-02-22 00:08:04 +00004346/* Compare two symbols for working purposes
4347**
4348** Symbols that begin with upper case letters (terminals or tokens)
4349** must sort before symbols that begin with lower case letters
4350** (non-terminals). Other than that, the order does not matter.
4351**
4352** We find experimentally that leaving the symbols in their original
4353** order (the order they appeared in the grammar file) gives the
4354** smallest parser tables in SQLite.
4355*/
4356int Symbolcmpp(struct symbol **a, struct symbol **b){
4357 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4358 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4359 return i1-i2;
drh75897232000-05-29 14:26:00 +00004360}
4361
4362/* There is one instance of the following structure for each
4363** associative array of type "x2".
4364*/
4365struct s_x2 {
4366 int size; /* The number of available slots. */
4367 /* Must be a power of 2 greater than or */
4368 /* equal to 1 */
4369 int count; /* Number of currently slots filled */
4370 struct s_x2node *tbl; /* The data stored here */
4371 struct s_x2node **ht; /* Hash table for lookups */
4372};
4373
4374/* There is one instance of this structure for every data element
4375** in an associative array of type "x2".
4376*/
4377typedef struct s_x2node {
4378 struct symbol *data; /* The data */
4379 char *key; /* The key */
4380 struct s_x2node *next; /* Next entry with the same hash */
4381 struct s_x2node **from; /* Previous link */
4382} x2node;
4383
4384/* There is only one instance of the array, which is the following */
4385static struct s_x2 *x2a;
4386
4387/* Allocate a new associative array */
4388void Symbol_init(){
4389 if( x2a ) return;
4390 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4391 if( x2a ){
4392 x2a->size = 128;
4393 x2a->count = 0;
4394 x2a->tbl = (x2node*)malloc(
4395 (sizeof(x2node) + sizeof(x2node*))*128 );
4396 if( x2a->tbl==0 ){
4397 free(x2a);
4398 x2a = 0;
4399 }else{
4400 int i;
4401 x2a->ht = (x2node**)&(x2a->tbl[128]);
4402 for(i=0; i<128; i++) x2a->ht[i] = 0;
4403 }
4404 }
4405}
4406/* Insert a new record into the array. Return TRUE if successful.
4407** Prior data with the same key is NOT overwritten */
4408int Symbol_insert(data,key)
4409struct symbol *data;
4410char *key;
4411{
4412 x2node *np;
4413 int h;
4414 int ph;
4415
4416 if( x2a==0 ) return 0;
4417 ph = strhash(key);
4418 h = ph & (x2a->size-1);
4419 np = x2a->ht[h];
4420 while( np ){
4421 if( strcmp(np->key,key)==0 ){
4422 /* An existing entry with the same key is found. */
4423 /* Fail because overwrite is not allows. */
4424 return 0;
4425 }
4426 np = np->next;
4427 }
4428 if( x2a->count>=x2a->size ){
4429 /* Need to make the hash table bigger */
4430 int i,size;
4431 struct s_x2 array;
4432 array.size = size = x2a->size*2;
4433 array.count = x2a->count;
4434 array.tbl = (x2node*)malloc(
4435 (sizeof(x2node) + sizeof(x2node*))*size );
4436 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4437 array.ht = (x2node**)&(array.tbl[size]);
4438 for(i=0; i<size; i++) array.ht[i] = 0;
4439 for(i=0; i<x2a->count; i++){
4440 x2node *oldnp, *newnp;
4441 oldnp = &(x2a->tbl[i]);
4442 h = strhash(oldnp->key) & (size-1);
4443 newnp = &(array.tbl[i]);
4444 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4445 newnp->next = array.ht[h];
4446 newnp->key = oldnp->key;
4447 newnp->data = oldnp->data;
4448 newnp->from = &(array.ht[h]);
4449 array.ht[h] = newnp;
4450 }
4451 free(x2a->tbl);
4452 *x2a = array;
4453 }
4454 /* Insert the new data */
4455 h = ph & (x2a->size-1);
4456 np = &(x2a->tbl[x2a->count++]);
4457 np->key = key;
4458 np->data = data;
4459 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4460 np->next = x2a->ht[h];
4461 x2a->ht[h] = np;
4462 np->from = &(x2a->ht[h]);
4463 return 1;
4464}
4465
4466/* Return a pointer to data assigned to the given key. Return NULL
4467** if no such key. */
4468struct symbol *Symbol_find(key)
4469char *key;
4470{
4471 int h;
4472 x2node *np;
4473
4474 if( x2a==0 ) return 0;
4475 h = strhash(key) & (x2a->size-1);
4476 np = x2a->ht[h];
4477 while( np ){
4478 if( strcmp(np->key,key)==0 ) break;
4479 np = np->next;
4480 }
4481 return np ? np->data : 0;
4482}
4483
4484/* Return the n-th data. Return NULL if n is out of range. */
4485struct symbol *Symbol_Nth(n)
4486int n;
4487{
4488 struct symbol *data;
4489 if( x2a && n>0 && n<=x2a->count ){
4490 data = x2a->tbl[n-1].data;
4491 }else{
4492 data = 0;
4493 }
4494 return data;
4495}
4496
4497/* Return the size of the array */
4498int Symbol_count()
4499{
4500 return x2a ? x2a->count : 0;
4501}
4502
4503/* Return an array of pointers to all data in the table.
4504** The array is obtained from malloc. Return NULL if memory allocation
4505** problems, or if the array is empty. */
4506struct symbol **Symbol_arrayof()
4507{
4508 struct symbol **array;
4509 int i,size;
4510 if( x2a==0 ) return 0;
4511 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004512 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004513 if( array ){
4514 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4515 }
4516 return array;
4517}
4518
4519/* Compare two configurations */
4520int Configcmp(a,b)
4521struct config *a;
4522struct config *b;
4523{
4524 int x;
4525 x = a->rp->index - b->rp->index;
4526 if( x==0 ) x = a->dot - b->dot;
4527 return x;
4528}
4529
4530/* Compare two states */
4531PRIVATE int statecmp(a,b)
4532struct config *a;
4533struct config *b;
4534{
4535 int rc;
4536 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4537 rc = a->rp->index - b->rp->index;
4538 if( rc==0 ) rc = a->dot - b->dot;
4539 }
4540 if( rc==0 ){
4541 if( a ) rc = 1;
4542 if( b ) rc = -1;
4543 }
4544 return rc;
4545}
4546
4547/* Hash a state */
4548PRIVATE int statehash(a)
4549struct config *a;
4550{
4551 int h=0;
4552 while( a ){
4553 h = h*571 + a->rp->index*37 + a->dot;
4554 a = a->bp;
4555 }
4556 return h;
4557}
4558
4559/* Allocate a new state structure */
4560struct state *State_new()
4561{
4562 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004563 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004564 MemoryCheck(new);
4565 return new;
4566}
4567
4568/* There is one instance of the following structure for each
4569** associative array of type "x3".
4570*/
4571struct s_x3 {
4572 int size; /* The number of available slots. */
4573 /* Must be a power of 2 greater than or */
4574 /* equal to 1 */
4575 int count; /* Number of currently slots filled */
4576 struct s_x3node *tbl; /* The data stored here */
4577 struct s_x3node **ht; /* Hash table for lookups */
4578};
4579
4580/* There is one instance of this structure for every data element
4581** in an associative array of type "x3".
4582*/
4583typedef struct s_x3node {
4584 struct state *data; /* The data */
4585 struct config *key; /* The key */
4586 struct s_x3node *next; /* Next entry with the same hash */
4587 struct s_x3node **from; /* Previous link */
4588} x3node;
4589
4590/* There is only one instance of the array, which is the following */
4591static struct s_x3 *x3a;
4592
4593/* Allocate a new associative array */
4594void State_init(){
4595 if( x3a ) return;
4596 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4597 if( x3a ){
4598 x3a->size = 128;
4599 x3a->count = 0;
4600 x3a->tbl = (x3node*)malloc(
4601 (sizeof(x3node) + sizeof(x3node*))*128 );
4602 if( x3a->tbl==0 ){
4603 free(x3a);
4604 x3a = 0;
4605 }else{
4606 int i;
4607 x3a->ht = (x3node**)&(x3a->tbl[128]);
4608 for(i=0; i<128; i++) x3a->ht[i] = 0;
4609 }
4610 }
4611}
4612/* Insert a new record into the array. Return TRUE if successful.
4613** Prior data with the same key is NOT overwritten */
4614int State_insert(data,key)
4615struct state *data;
4616struct config *key;
4617{
4618 x3node *np;
4619 int h;
4620 int ph;
4621
4622 if( x3a==0 ) return 0;
4623 ph = statehash(key);
4624 h = ph & (x3a->size-1);
4625 np = x3a->ht[h];
4626 while( np ){
4627 if( statecmp(np->key,key)==0 ){
4628 /* An existing entry with the same key is found. */
4629 /* Fail because overwrite is not allows. */
4630 return 0;
4631 }
4632 np = np->next;
4633 }
4634 if( x3a->count>=x3a->size ){
4635 /* Need to make the hash table bigger */
4636 int i,size;
4637 struct s_x3 array;
4638 array.size = size = x3a->size*2;
4639 array.count = x3a->count;
4640 array.tbl = (x3node*)malloc(
4641 (sizeof(x3node) + sizeof(x3node*))*size );
4642 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4643 array.ht = (x3node**)&(array.tbl[size]);
4644 for(i=0; i<size; i++) array.ht[i] = 0;
4645 for(i=0; i<x3a->count; i++){
4646 x3node *oldnp, *newnp;
4647 oldnp = &(x3a->tbl[i]);
4648 h = statehash(oldnp->key) & (size-1);
4649 newnp = &(array.tbl[i]);
4650 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4651 newnp->next = array.ht[h];
4652 newnp->key = oldnp->key;
4653 newnp->data = oldnp->data;
4654 newnp->from = &(array.ht[h]);
4655 array.ht[h] = newnp;
4656 }
4657 free(x3a->tbl);
4658 *x3a = array;
4659 }
4660 /* Insert the new data */
4661 h = ph & (x3a->size-1);
4662 np = &(x3a->tbl[x3a->count++]);
4663 np->key = key;
4664 np->data = data;
4665 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4666 np->next = x3a->ht[h];
4667 x3a->ht[h] = np;
4668 np->from = &(x3a->ht[h]);
4669 return 1;
4670}
4671
4672/* Return a pointer to data assigned to the given key. Return NULL
4673** if no such key. */
4674struct state *State_find(key)
4675struct config *key;
4676{
4677 int h;
4678 x3node *np;
4679
4680 if( x3a==0 ) return 0;
4681 h = statehash(key) & (x3a->size-1);
4682 np = x3a->ht[h];
4683 while( np ){
4684 if( statecmp(np->key,key)==0 ) break;
4685 np = np->next;
4686 }
4687 return np ? np->data : 0;
4688}
4689
4690/* Return an array of pointers to all data in the table.
4691** The array is obtained from malloc. Return NULL if memory allocation
4692** problems, or if the array is empty. */
4693struct state **State_arrayof()
4694{
4695 struct state **array;
4696 int i,size;
4697 if( x3a==0 ) return 0;
4698 size = x3a->count;
4699 array = (struct state **)malloc( sizeof(struct state *)*size );
4700 if( array ){
4701 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4702 }
4703 return array;
4704}
4705
4706/* Hash a configuration */
4707PRIVATE int confighash(a)
4708struct config *a;
4709{
4710 int h=0;
4711 h = h*571 + a->rp->index*37 + a->dot;
4712 return h;
4713}
4714
4715/* There is one instance of the following structure for each
4716** associative array of type "x4".
4717*/
4718struct s_x4 {
4719 int size; /* The number of available slots. */
4720 /* Must be a power of 2 greater than or */
4721 /* equal to 1 */
4722 int count; /* Number of currently slots filled */
4723 struct s_x4node *tbl; /* The data stored here */
4724 struct s_x4node **ht; /* Hash table for lookups */
4725};
4726
4727/* There is one instance of this structure for every data element
4728** in an associative array of type "x4".
4729*/
4730typedef struct s_x4node {
4731 struct config *data; /* The data */
4732 struct s_x4node *next; /* Next entry with the same hash */
4733 struct s_x4node **from; /* Previous link */
4734} x4node;
4735
4736/* There is only one instance of the array, which is the following */
4737static struct s_x4 *x4a;
4738
4739/* Allocate a new associative array */
4740void Configtable_init(){
4741 if( x4a ) return;
4742 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4743 if( x4a ){
4744 x4a->size = 64;
4745 x4a->count = 0;
4746 x4a->tbl = (x4node*)malloc(
4747 (sizeof(x4node) + sizeof(x4node*))*64 );
4748 if( x4a->tbl==0 ){
4749 free(x4a);
4750 x4a = 0;
4751 }else{
4752 int i;
4753 x4a->ht = (x4node**)&(x4a->tbl[64]);
4754 for(i=0; i<64; i++) x4a->ht[i] = 0;
4755 }
4756 }
4757}
4758/* Insert a new record into the array. Return TRUE if successful.
4759** Prior data with the same key is NOT overwritten */
4760int Configtable_insert(data)
4761struct config *data;
4762{
4763 x4node *np;
4764 int h;
4765 int ph;
4766
4767 if( x4a==0 ) return 0;
4768 ph = confighash(data);
4769 h = ph & (x4a->size-1);
4770 np = x4a->ht[h];
4771 while( np ){
4772 if( Configcmp(np->data,data)==0 ){
4773 /* An existing entry with the same key is found. */
4774 /* Fail because overwrite is not allows. */
4775 return 0;
4776 }
4777 np = np->next;
4778 }
4779 if( x4a->count>=x4a->size ){
4780 /* Need to make the hash table bigger */
4781 int i,size;
4782 struct s_x4 array;
4783 array.size = size = x4a->size*2;
4784 array.count = x4a->count;
4785 array.tbl = (x4node*)malloc(
4786 (sizeof(x4node) + sizeof(x4node*))*size );
4787 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4788 array.ht = (x4node**)&(array.tbl[size]);
4789 for(i=0; i<size; i++) array.ht[i] = 0;
4790 for(i=0; i<x4a->count; i++){
4791 x4node *oldnp, *newnp;
4792 oldnp = &(x4a->tbl[i]);
4793 h = confighash(oldnp->data) & (size-1);
4794 newnp = &(array.tbl[i]);
4795 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4796 newnp->next = array.ht[h];
4797 newnp->data = oldnp->data;
4798 newnp->from = &(array.ht[h]);
4799 array.ht[h] = newnp;
4800 }
4801 free(x4a->tbl);
4802 *x4a = array;
4803 }
4804 /* Insert the new data */
4805 h = ph & (x4a->size-1);
4806 np = &(x4a->tbl[x4a->count++]);
4807 np->data = data;
4808 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4809 np->next = x4a->ht[h];
4810 x4a->ht[h] = np;
4811 np->from = &(x4a->ht[h]);
4812 return 1;
4813}
4814
4815/* Return a pointer to data assigned to the given key. Return NULL
4816** if no such key. */
4817struct config *Configtable_find(key)
4818struct config *key;
4819{
4820 int h;
4821 x4node *np;
4822
4823 if( x4a==0 ) return 0;
4824 h = confighash(key) & (x4a->size-1);
4825 np = x4a->ht[h];
4826 while( np ){
4827 if( Configcmp(np->data,key)==0 ) break;
4828 np = np->next;
4829 }
4830 return np ? np->data : 0;
4831}
4832
4833/* Remove all data from the table. Pass each data to the function "f"
4834** as it is removed. ("f" may be null to avoid this step.) */
4835void Configtable_clear(f)
4836int(*f)(/* struct config * */);
4837{
4838 int i;
4839 if( x4a==0 || x4a->count==0 ) return;
4840 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4841 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4842 x4a->count = 0;
4843 return;
4844}