blob: 94ca5498032d8ac9a353c26d1513bdbc23b4e096 [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
drh34ff57b2008-07-14 12:27:51 +0000131 } assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000132 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 */
drh4dc8ef52008-07-01 17:13:57 +0000137 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000138 char *datatype; /* The data type of information held by this
139 ** object. Only used if type==NONTERMINAL */
140 int dtnum; /* The data type number. In the parser, the value
141 ** stack is a union. The .yy%d element of this
142 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000143 /* The following fields are used by MULTITERMINALs only */
144 int nsubsym; /* Number of constituent symbols in the MULTI */
145 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000146};
147
148/* Each production rule in the grammar is stored in the following
149** structure. */
150struct rule {
151 struct symbol *lhs; /* Left-hand side of the rule */
152 char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000153 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000154 int ruleline; /* Line number for the rule */
155 int nrhs; /* Number of RHS symbols */
156 struct symbol **rhs; /* The RHS symbols */
157 char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
158 int line; /* Line number at which code begins */
159 char *code; /* The code executed when this rule is reduced */
160 struct symbol *precsym; /* Precedence symbol for this rule */
161 int index; /* An index number for this rule */
162 Boolean canReduce; /* True if this rule is ever reduced */
163 struct rule *nextlhs; /* Next rule with the same LHS */
164 struct rule *next; /* Next rule in the global list */
165};
166
167/* A configuration is a production rule of the grammar together with
168** a mark (dot) showing how much of that rule has been processed so far.
169** Configurations also contain a follow-set which is a list of terminal
170** symbols which are allowed to immediately follow the end of the rule.
171** Every configuration is recorded as an instance of the following: */
172struct config {
173 struct rule *rp; /* The rule upon which the configuration is based */
174 int dot; /* The parse point */
175 char *fws; /* Follow-set for this configuration only */
176 struct plink *fplp; /* Follow-set forward propagation links */
177 struct plink *bplp; /* Follow-set backwards propagation links */
178 struct state *stp; /* Pointer to state which contains this */
179 enum {
180 COMPLETE, /* The status is used during followset and */
181 INCOMPLETE /* shift computations */
182 } status;
183 struct config *next; /* Next configuration in the state */
184 struct config *bp; /* The next basis configuration */
185};
186
187/* Every shift or reduce operation is stored as one of the following */
188struct action {
189 struct symbol *sp; /* The look-ahead symbol */
190 enum e_action {
191 SHIFT,
192 ACCEPT,
193 REDUCE,
194 ERROR,
drh9892c5d2007-12-21 00:02:11 +0000195 SSCONFLICT, /* A shift/shift conflict */
196 SRCONFLICT, /* Was a reduce, but part of a conflict */
197 RRCONFLICT, /* Was a reduce, but part of a conflict */
drh75897232000-05-29 14:26:00 +0000198 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
199 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
200 NOT_USED /* Deleted by compression */
201 } type;
202 union {
203 struct state *stp; /* The new state, if a shift */
204 struct rule *rp; /* The rule, if a reduce */
205 } x;
206 struct action *next; /* Next action for this state */
207 struct action *collide; /* Next action with the same hash */
208};
209
210/* Each state of the generated parser's finite state machine
211** is encoded as an instance of the following structure. */
212struct state {
213 struct config *bp; /* The basis configurations for this state */
214 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000215 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000216 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000217 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
218 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
219 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000220};
drh8b582012003-10-21 13:16:03 +0000221#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000222
223/* A followset propagation link indicates that the contents of one
224** configuration followset should be propagated to another whenever
225** the first changes. */
226struct plink {
227 struct config *cfp; /* The configuration to which linked */
228 struct plink *next; /* The next propagate link */
229};
230
231/* The state vector for the entire parser generator is recorded as
232** follows. (LEMON uses no global variables and makes little use of
233** static variables. Fields in the following structure can be thought
234** of as begin global variables in the program.) */
235struct lemon {
236 struct state **sorted; /* Table of states sorted by state number */
237 struct rule *rule; /* List of all rules */
238 int nstate; /* Number of states */
239 int nrule; /* Number of rules */
240 int nsymbol; /* Number of terminal and nonterminal symbols */
241 int nterminal; /* Number of terminal symbols */
242 struct symbol **symbols; /* Sorted array of pointers to symbols */
243 int errorcnt; /* Number of errors */
244 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000245 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000246 char *name; /* Name of the generated parser */
247 char *arg; /* Declaration of the 3th argument to parser */
248 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000249 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000250 char *start; /* Name of the start symbol for the grammar */
251 char *stacksize; /* Size of the parser stack */
252 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000253 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000254 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000255 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000256 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000257 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000258 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000259 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000260 char *filename; /* Name of the input file */
261 char *outname; /* Name of the current output file */
262 char *tokenprefix; /* A prefix added to token names in the .h file */
263 int nconflict; /* Number of parsing conflicts */
264 int tablesize; /* Size of the parse tables */
265 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000266 int has_fallback; /* True if any %fallback is seen in the grammar */
drh75897232000-05-29 14:26:00 +0000267 char *argv0; /* Name of the program */
268};
269
270#define MemoryCheck(X) if((X)==0){ \
271 extern void memory_error(); \
272 memory_error(); \
273}
274
275/**************** From the file "table.h" *********************************/
276/*
277** All code in this file has been automatically generated
278** from a specification in the file
279** "table.q"
280** by the associative array code building program "aagen".
281** Do not edit this file! Instead, edit the specification
282** file, then rerun aagen.
283*/
284/*
285** Code for processing tables in the LEMON parser generator.
286*/
287
288/* Routines for handling a strings */
289
290char *Strsafe();
291
292void Strsafe_init(/* void */);
293int Strsafe_insert(/* char * */);
294char *Strsafe_find(/* char * */);
295
296/* Routines for handling symbols of the grammar */
297
298struct symbol *Symbol_new();
299int Symbolcmpp(/* struct symbol **, struct symbol ** */);
300void Symbol_init(/* void */);
301int Symbol_insert(/* struct symbol *, char * */);
302struct symbol *Symbol_find(/* char * */);
303struct symbol *Symbol_Nth(/* int */);
304int Symbol_count(/* */);
305struct symbol **Symbol_arrayof(/* */);
306
307/* Routines to manage the state table */
308
309int Configcmp(/* struct config *, struct config * */);
310struct state *State_new();
311void State_init(/* void */);
312int State_insert(/* struct state *, struct config * */);
313struct state *State_find(/* struct config * */);
314struct state **State_arrayof(/* */);
315
316/* Routines used for efficiency in Configlist_add */
317
318void Configtable_init(/* void */);
319int Configtable_insert(/* struct config * */);
320struct config *Configtable_find(/* struct config * */);
321void Configtable_clear(/* int(*)(struct config *) */);
322/****************** From the file "action.c" *******************************/
323/*
324** Routines processing parser actions in the LEMON parser generator.
325*/
326
327/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000328static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000329 static struct action *freelist = 0;
330 struct action *new;
331
332 if( freelist==0 ){
333 int i;
334 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000335 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000336 if( freelist==0 ){
337 fprintf(stderr,"Unable to allocate memory for a new parser action.");
338 exit(1);
339 }
340 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
341 freelist[amt-1].next = 0;
342 }
343 new = freelist;
344 freelist = freelist->next;
345 return new;
346}
347
drhe9278182007-07-18 18:16:29 +0000348/* Compare two actions for sorting purposes. Return negative, zero, or
349** positive if the first action is less than, equal to, or greater than
350** the first
351*/
352static int actioncmp(
353 struct action *ap1,
354 struct action *ap2
355){
drh75897232000-05-29 14:26:00 +0000356 int rc;
357 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000358 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000359 rc = (int)ap1->type - (int)ap2->type;
360 }
361 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000362 rc = ap1->x.rp->index - ap2->x.rp->index;
363 }
364 return rc;
365}
366
367/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000368static struct action *Action_sort(
369 struct action *ap
370){
371 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
372 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000373 return ap;
374}
375
376void Action_add(app,type,sp,arg)
377struct action **app;
378enum e_action type;
379struct symbol *sp;
380char *arg;
381{
382 struct action *new;
383 new = Action_new();
384 new->next = *app;
385 *app = new;
386 new->type = type;
387 new->sp = sp;
388 if( type==SHIFT ){
389 new->x.stp = (struct state *)arg;
390 }else{
391 new->x.rp = (struct rule *)arg;
392 }
393}
drh8b582012003-10-21 13:16:03 +0000394/********************** New code to implement the "acttab" module ***********/
395/*
396** This module implements routines use to construct the yy_action[] table.
397*/
398
399/*
400** The state of the yy_action table under construction is an instance of
401** the following structure
402*/
403typedef struct acttab acttab;
404struct acttab {
405 int nAction; /* Number of used slots in aAction[] */
406 int nActionAlloc; /* Slots allocated for aAction[] */
407 struct {
408 int lookahead; /* Value of the lookahead token */
409 int action; /* Action to take on the given lookahead */
410 } *aAction, /* The yy_action[] table under construction */
411 *aLookahead; /* A single new transaction set */
412 int mnLookahead; /* Minimum aLookahead[].lookahead */
413 int mnAction; /* Action associated with mnLookahead */
414 int mxLookahead; /* Maximum aLookahead[].lookahead */
415 int nLookahead; /* Used slots in aLookahead[] */
416 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
417};
418
419/* Return the number of entries in the yy_action table */
420#define acttab_size(X) ((X)->nAction)
421
422/* The value for the N-th entry in yy_action */
423#define acttab_yyaction(X,N) ((X)->aAction[N].action)
424
425/* The value for the N-th entry in yy_lookahead */
426#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
427
428/* Free all memory associated with the given acttab */
429void acttab_free(acttab *p){
430 free( p->aAction );
431 free( p->aLookahead );
432 free( p );
433}
434
435/* Allocate a new acttab structure */
436acttab *acttab_alloc(void){
drh9892c5d2007-12-21 00:02:11 +0000437 acttab *p = calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000438 if( p==0 ){
439 fprintf(stderr,"Unable to allocate memory for a new acttab.");
440 exit(1);
441 }
442 memset(p, 0, sizeof(*p));
443 return p;
444}
445
446/* Add a new action to the current transaction set
447*/
448void acttab_action(acttab *p, int lookahead, int action){
449 if( p->nLookahead>=p->nLookaheadAlloc ){
450 p->nLookaheadAlloc += 25;
451 p->aLookahead = realloc( p->aLookahead,
452 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
453 if( p->aLookahead==0 ){
454 fprintf(stderr,"malloc failed\n");
455 exit(1);
456 }
457 }
458 if( p->nLookahead==0 ){
459 p->mxLookahead = lookahead;
460 p->mnLookahead = lookahead;
461 p->mnAction = action;
462 }else{
463 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
464 if( p->mnLookahead>lookahead ){
465 p->mnLookahead = lookahead;
466 p->mnAction = action;
467 }
468 }
469 p->aLookahead[p->nLookahead].lookahead = lookahead;
470 p->aLookahead[p->nLookahead].action = action;
471 p->nLookahead++;
472}
473
474/*
475** Add the transaction set built up with prior calls to acttab_action()
476** into the current action table. Then reset the transaction set back
477** to an empty set in preparation for a new round of acttab_action() calls.
478**
479** Return the offset into the action table of the new transaction.
480*/
481int acttab_insert(acttab *p){
482 int i, j, k, n;
483 assert( p->nLookahead>0 );
484
485 /* Make sure we have enough space to hold the expanded action table
486 ** in the worst case. The worst case occurs if the transaction set
487 ** must be appended to the current action table
488 */
drh784d86f2004-02-19 18:41:53 +0000489 n = p->mxLookahead + 1;
drh8b582012003-10-21 13:16:03 +0000490 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000491 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000492 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
493 p->aAction = realloc( p->aAction,
494 sizeof(p->aAction[0])*p->nActionAlloc);
495 if( p->aAction==0 ){
496 fprintf(stderr,"malloc failed\n");
497 exit(1);
498 }
drhfdbf9282003-10-21 16:34:41 +0000499 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000500 p->aAction[i].lookahead = -1;
501 p->aAction[i].action = -1;
502 }
503 }
504
505 /* Scan the existing action table looking for an offset where we can
506 ** insert the current transaction set. Fall out of the loop when that
507 ** offset is found. In the worst case, we fall out of the loop when
508 ** i reaches p->nAction, which means we append the new transaction set.
509 **
510 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
511 */
drh784d86f2004-02-19 18:41:53 +0000512 for(i=0; i<p->nAction+p->mnLookahead; i++){
drh8b582012003-10-21 13:16:03 +0000513 if( p->aAction[i].lookahead<0 ){
514 for(j=0; j<p->nLookahead; j++){
515 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
516 if( k<0 ) break;
517 if( p->aAction[k].lookahead>=0 ) break;
518 }
drhfdbf9282003-10-21 16:34:41 +0000519 if( j<p->nLookahead ) continue;
520 for(j=0; j<p->nAction; j++){
521 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
522 }
523 if( j==p->nAction ){
524 break; /* Fits in empty slots */
525 }
drh8b582012003-10-21 13:16:03 +0000526 }else if( p->aAction[i].lookahead==p->mnLookahead ){
527 if( p->aAction[i].action!=p->mnAction ) continue;
528 for(j=0; j<p->nLookahead; j++){
529 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
530 if( k<0 || k>=p->nAction ) break;
531 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
532 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
533 }
534 if( j<p->nLookahead ) continue;
535 n = 0;
536 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000537 if( p->aAction[j].lookahead<0 ) continue;
538 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000539 }
drhfdbf9282003-10-21 16:34:41 +0000540 if( n==p->nLookahead ){
541 break; /* Same as a prior transaction set */
542 }
drh8b582012003-10-21 13:16:03 +0000543 }
544 }
545 /* Insert transaction set at index i. */
546 for(j=0; j<p->nLookahead; j++){
547 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
548 p->aAction[k] = p->aLookahead[j];
549 if( k>=p->nAction ) p->nAction = k+1;
550 }
551 p->nLookahead = 0;
552
553 /* Return the offset that is added to the lookahead in order to get the
554 ** index into yy_action of the action */
555 return i - p->mnLookahead;
556}
557
drh75897232000-05-29 14:26:00 +0000558/********************** From the file "build.c" *****************************/
559/*
560** Routines to construction the finite state machine for the LEMON
561** parser generator.
562*/
563
564/* Find a precedence symbol of every rule in the grammar.
565**
566** Those rules which have a precedence symbol coded in the input
567** grammar using the "[symbol]" construct will already have the
568** rp->precsym field filled. Other rules take as their precedence
569** symbol the first RHS symbol with a defined precedence. If there
570** are not RHS symbols with a defined precedence, the precedence
571** symbol field is left blank.
572*/
573void FindRulePrecedences(xp)
574struct lemon *xp;
575{
576 struct rule *rp;
577 for(rp=xp->rule; rp; rp=rp->next){
578 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000579 int i, j;
580 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
581 struct symbol *sp = rp->rhs[i];
582 if( sp->type==MULTITERMINAL ){
583 for(j=0; j<sp->nsubsym; j++){
584 if( sp->subsym[j]->prec>=0 ){
585 rp->precsym = sp->subsym[j];
586 break;
587 }
588 }
589 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000590 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000591 }
592 }
593 }
594 }
595 return;
596}
597
598/* Find all nonterminals which will generate the empty string.
599** Then go back and compute the first sets of every nonterminal.
600** The first set is the set of all terminal symbols which can begin
601** a string generated by that nonterminal.
602*/
603void FindFirstSets(lemp)
604struct lemon *lemp;
605{
drhfd405312005-11-06 04:06:59 +0000606 int i, j;
drh75897232000-05-29 14:26:00 +0000607 struct rule *rp;
608 int progress;
609
610 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000611 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000612 }
613 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
614 lemp->symbols[i]->firstset = SetNew();
615 }
616
617 /* First compute all lambdas */
618 do{
619 progress = 0;
620 for(rp=lemp->rule; rp; rp=rp->next){
621 if( rp->lhs->lambda ) continue;
622 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000623 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000624 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000625 }
626 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000627 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000628 progress = 1;
629 }
630 }
631 }while( progress );
632
633 /* Now compute all first sets */
634 do{
635 struct symbol *s1, *s2;
636 progress = 0;
637 for(rp=lemp->rule; rp; rp=rp->next){
638 s1 = rp->lhs;
639 for(i=0; i<rp->nrhs; i++){
640 s2 = rp->rhs[i];
641 if( s2->type==TERMINAL ){
642 progress += SetAdd(s1->firstset,s2->index);
643 break;
drhfd405312005-11-06 04:06:59 +0000644 }else if( s2->type==MULTITERMINAL ){
645 for(j=0; j<s2->nsubsym; j++){
646 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
647 }
648 break;
drh75897232000-05-29 14:26:00 +0000649 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000650 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000651 }else{
652 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000653 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000654 }
655 }
656 }
657 }while( progress );
658 return;
659}
660
661/* Compute all LR(0) states for the grammar. Links
662** are added to between some states so that the LR(1) follow sets
663** can be computed later.
664*/
665PRIVATE struct state *getstate(/* struct lemon * */); /* forward reference */
666void FindStates(lemp)
667struct lemon *lemp;
668{
669 struct symbol *sp;
670 struct rule *rp;
671
672 Configlist_init();
673
674 /* Find the start symbol */
675 if( lemp->start ){
676 sp = Symbol_find(lemp->start);
677 if( sp==0 ){
678 ErrorMsg(lemp->filename,0,
679"The specified start symbol \"%s\" is not \
680in a nonterminal of the grammar. \"%s\" will be used as the start \
681symbol instead.",lemp->start,lemp->rule->lhs->name);
682 lemp->errorcnt++;
683 sp = lemp->rule->lhs;
684 }
685 }else{
686 sp = lemp->rule->lhs;
687 }
688
689 /* Make sure the start symbol doesn't occur on the right-hand side of
690 ** any rule. Report an error if it does. (YACC would generate a new
691 ** start symbol in this case.) */
692 for(rp=lemp->rule; rp; rp=rp->next){
693 int i;
694 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000695 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000696 ErrorMsg(lemp->filename,0,
697"The start symbol \"%s\" occurs on the \
698right-hand side of a rule. This will result in a parser which \
699does not work properly.",sp->name);
700 lemp->errorcnt++;
701 }
702 }
703 }
704
705 /* The basis configuration set for the first state
706 ** is all rules which have the start symbol as their
707 ** left-hand side */
708 for(rp=sp->rule; rp; rp=rp->nextlhs){
709 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000710 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000711 newcfp = Configlist_addbasis(rp,0);
712 SetAdd(newcfp->fws,0);
713 }
714
715 /* Compute the first state. All other states will be
716 ** computed automatically during the computation of the first one.
717 ** The returned pointer to the first state is not used. */
718 (void)getstate(lemp);
719 return;
720}
721
722/* Return a pointer to a state which is described by the configuration
723** list which has been built from calls to Configlist_add.
724*/
725PRIVATE void buildshifts(/* struct lemon *, struct state * */); /* Forwd ref */
726PRIVATE struct state *getstate(lemp)
727struct lemon *lemp;
728{
729 struct config *cfp, *bp;
730 struct state *stp;
731
732 /* Extract the sorted basis of the new state. The basis was constructed
733 ** by prior calls to "Configlist_addbasis()". */
734 Configlist_sortbasis();
735 bp = Configlist_basis();
736
737 /* Get a state with the same basis */
738 stp = State_find(bp);
739 if( stp ){
740 /* A state with the same basis already exists! Copy all the follow-set
741 ** propagation links from the state under construction into the
742 ** preexisting state, then return a pointer to the preexisting state */
743 struct config *x, *y;
744 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
745 Plink_copy(&y->bplp,x->bplp);
746 Plink_delete(x->fplp);
747 x->fplp = x->bplp = 0;
748 }
749 cfp = Configlist_return();
750 Configlist_eat(cfp);
751 }else{
752 /* This really is a new state. Construct all the details */
753 Configlist_closure(lemp); /* Compute the configuration closure */
754 Configlist_sort(); /* Sort the configuration closure */
755 cfp = Configlist_return(); /* Get a pointer to the config list */
756 stp = State_new(); /* A new state structure */
757 MemoryCheck(stp);
758 stp->bp = bp; /* Remember the configuration basis */
759 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000760 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000761 stp->ap = 0; /* No actions, yet. */
762 State_insert(stp,stp->bp); /* Add to the state table */
763 buildshifts(lemp,stp); /* Recursively compute successor states */
764 }
765 return stp;
766}
767
drhfd405312005-11-06 04:06:59 +0000768/*
769** Return true if two symbols are the same.
770*/
771int same_symbol(a,b)
772struct symbol *a;
773struct symbol *b;
774{
775 int i;
776 if( a==b ) return 1;
777 if( a->type!=MULTITERMINAL ) return 0;
778 if( b->type!=MULTITERMINAL ) return 0;
779 if( a->nsubsym!=b->nsubsym ) return 0;
780 for(i=0; i<a->nsubsym; i++){
781 if( a->subsym[i]!=b->subsym[i] ) return 0;
782 }
783 return 1;
784}
785
drh75897232000-05-29 14:26:00 +0000786/* Construct all successor states to the given state. A "successor"
787** state is any state which can be reached by a shift action.
788*/
789PRIVATE void buildshifts(lemp,stp)
790struct lemon *lemp;
791struct state *stp; /* The state from which successors are computed */
792{
793 struct config *cfp; /* For looping thru the config closure of "stp" */
794 struct config *bcfp; /* For the inner loop on config closure of "stp" */
795 struct config *new; /* */
796 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
797 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
798 struct state *newstp; /* A pointer to a successor state */
799
800 /* Each configuration becomes complete after it contibutes to a successor
801 ** state. Initially, all configurations are incomplete */
802 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
803
804 /* Loop through all configurations of the state "stp" */
805 for(cfp=stp->cfp; cfp; cfp=cfp->next){
806 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
807 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
808 Configlist_reset(); /* Reset the new config set */
809 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
810
811 /* For every configuration in the state "stp" which has the symbol "sp"
812 ** following its dot, add the same configuration to the basis set under
813 ** construction but with the dot shifted one symbol to the right. */
814 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
815 if( bcfp->status==COMPLETE ) continue; /* Already used */
816 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
817 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000818 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000819 bcfp->status = COMPLETE; /* Mark this config as used */
820 new = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
821 Plink_add(&new->bplp,bcfp);
822 }
823
824 /* Get a pointer to the state described by the basis configuration set
825 ** constructed in the preceding loop */
826 newstp = getstate(lemp);
827
828 /* The state "newstp" is reached from the state "stp" by a shift action
829 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000830 if( sp->type==MULTITERMINAL ){
831 int i;
832 for(i=0; i<sp->nsubsym; i++){
833 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
834 }
835 }else{
836 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
837 }
drh75897232000-05-29 14:26:00 +0000838 }
839}
840
841/*
842** Construct the propagation links
843*/
844void FindLinks(lemp)
845struct lemon *lemp;
846{
847 int i;
848 struct config *cfp, *other;
849 struct state *stp;
850 struct plink *plp;
851
852 /* Housekeeping detail:
853 ** Add to every propagate link a pointer back to the state to
854 ** which the link is attached. */
855 for(i=0; i<lemp->nstate; i++){
856 stp = lemp->sorted[i];
857 for(cfp=stp->cfp; cfp; cfp=cfp->next){
858 cfp->stp = stp;
859 }
860 }
861
862 /* Convert all backlinks into forward links. Only the forward
863 ** links are used in the follow-set computation. */
864 for(i=0; i<lemp->nstate; i++){
865 stp = lemp->sorted[i];
866 for(cfp=stp->cfp; cfp; cfp=cfp->next){
867 for(plp=cfp->bplp; plp; plp=plp->next){
868 other = plp->cfp;
869 Plink_add(&other->fplp,cfp);
870 }
871 }
872 }
873}
874
875/* Compute all followsets.
876**
877** A followset is the set of all symbols which can come immediately
878** after a configuration.
879*/
880void FindFollowSets(lemp)
881struct lemon *lemp;
882{
883 int i;
884 struct config *cfp;
885 struct plink *plp;
886 int progress;
887 int change;
888
889 for(i=0; i<lemp->nstate; i++){
890 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
891 cfp->status = INCOMPLETE;
892 }
893 }
894
895 do{
896 progress = 0;
897 for(i=0; i<lemp->nstate; i++){
898 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
899 if( cfp->status==COMPLETE ) continue;
900 for(plp=cfp->fplp; plp; plp=plp->next){
901 change = SetUnion(plp->cfp->fws,cfp->fws);
902 if( change ){
903 plp->cfp->status = INCOMPLETE;
904 progress = 1;
905 }
906 }
907 cfp->status = COMPLETE;
908 }
909 }
910 }while( progress );
911}
912
913static int resolve_conflict();
914
915/* Compute the reduce actions, and resolve conflicts.
916*/
917void FindActions(lemp)
918struct lemon *lemp;
919{
920 int i,j;
921 struct config *cfp;
922 struct state *stp;
923 struct symbol *sp;
924 struct rule *rp;
925
926 /* Add all of the reduce actions
927 ** A reduce action is added for each element of the followset of
928 ** a configuration which has its dot at the extreme right.
929 */
930 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
931 stp = lemp->sorted[i];
932 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
933 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
934 for(j=0; j<lemp->nterminal; j++){
935 if( SetFind(cfp->fws,j) ){
936 /* Add a reduce action to the state "stp" which will reduce by the
937 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000938 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000939 }
940 }
941 }
942 }
943 }
944
945 /* Add the accepting token */
946 if( lemp->start ){
947 sp = Symbol_find(lemp->start);
948 if( sp==0 ) sp = lemp->rule->lhs;
949 }else{
950 sp = lemp->rule->lhs;
951 }
952 /* Add to the first state (which is always the starting state of the
953 ** finite state machine) an action to ACCEPT if the lookahead is the
954 ** start nonterminal. */
955 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
956
957 /* Resolve conflicts */
958 for(i=0; i<lemp->nstate; i++){
959 struct action *ap, *nap;
960 struct state *stp;
961 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +0000962 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +0000963 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +0000964 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +0000965 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
966 /* The two actions "ap" and "nap" have the same lookahead.
967 ** Figure out which one should be used */
968 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
969 }
970 }
971 }
972
973 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +0000974 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000975 for(i=0; i<lemp->nstate; i++){
976 struct action *ap;
977 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +0000978 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000979 }
980 }
981 for(rp=lemp->rule; rp; rp=rp->next){
982 if( rp->canReduce ) continue;
983 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
984 lemp->errorcnt++;
985 }
986}
987
988/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +0000989** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +0000990**
991** NO LONGER TRUE:
992** To resolve a conflict, first look to see if either action
993** is on an error rule. In that case, take the action which
994** is not associated with the error rule. If neither or both
995** actions are associated with an error rule, then try to
996** use precedence to resolve the conflict.
997**
998** If either action is a SHIFT, then it must be apx. This
999** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1000*/
1001static int resolve_conflict(apx,apy,errsym)
1002struct action *apx;
1003struct action *apy;
1004struct symbol *errsym; /* The error symbol (if defined. NULL otherwise) */
1005{
1006 struct symbol *spx, *spy;
1007 int errcnt = 0;
1008 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001009 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001010 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001011 errcnt++;
1012 }
drh75897232000-05-29 14:26:00 +00001013 if( apx->type==SHIFT && apy->type==REDUCE ){
1014 spx = apx->sp;
1015 spy = apy->x.rp->precsym;
1016 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1017 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001018 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001019 errcnt++;
1020 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1021 apy->type = RD_RESOLVED;
1022 }else if( spx->prec<spy->prec ){
1023 apx->type = SH_RESOLVED;
1024 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1025 apy->type = RD_RESOLVED; /* associativity */
1026 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1027 apx->type = SH_RESOLVED;
1028 }else{
1029 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001030 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001031 errcnt++;
1032 }
1033 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1034 spx = apx->x.rp->precsym;
1035 spy = apy->x.rp->precsym;
1036 if( spx==0 || spy==0 || spx->prec<0 ||
1037 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001038 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001039 errcnt++;
1040 }else if( spx->prec>spy->prec ){
1041 apy->type = RD_RESOLVED;
1042 }else if( spx->prec<spy->prec ){
1043 apx->type = RD_RESOLVED;
1044 }
1045 }else{
drhb59499c2002-02-23 18:45:13 +00001046 assert(
1047 apx->type==SH_RESOLVED ||
1048 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001049 apx->type==SSCONFLICT ||
1050 apx->type==SRCONFLICT ||
1051 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001052 apy->type==SH_RESOLVED ||
1053 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001054 apy->type==SSCONFLICT ||
1055 apy->type==SRCONFLICT ||
1056 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001057 );
1058 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1059 ** REDUCEs on the list. If we reach this point it must be because
1060 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001061 }
1062 return errcnt;
1063}
1064/********************* From the file "configlist.c" *************************/
1065/*
1066** Routines to processing a configuration list and building a state
1067** in the LEMON parser generator.
1068*/
1069
1070static struct config *freelist = 0; /* List of free configurations */
1071static struct config *current = 0; /* Top of list of configurations */
1072static struct config **currentend = 0; /* Last on list of configs */
1073static struct config *basis = 0; /* Top of list of basis configs */
1074static struct config **basisend = 0; /* End of list of basis configs */
1075
1076/* Return a pointer to a new configuration */
1077PRIVATE struct config *newconfig(){
1078 struct config *new;
1079 if( freelist==0 ){
1080 int i;
1081 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001082 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001083 if( freelist==0 ){
1084 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1085 exit(1);
1086 }
1087 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1088 freelist[amt-1].next = 0;
1089 }
1090 new = freelist;
1091 freelist = freelist->next;
1092 return new;
1093}
1094
1095/* The configuration "old" is no longer used */
1096PRIVATE void deleteconfig(old)
1097struct config *old;
1098{
1099 old->next = freelist;
1100 freelist = old;
1101}
1102
1103/* Initialized the configuration list builder */
1104void Configlist_init(){
1105 current = 0;
1106 currentend = &current;
1107 basis = 0;
1108 basisend = &basis;
1109 Configtable_init();
1110 return;
1111}
1112
1113/* Initialized the configuration list builder */
1114void Configlist_reset(){
1115 current = 0;
1116 currentend = &current;
1117 basis = 0;
1118 basisend = &basis;
1119 Configtable_clear(0);
1120 return;
1121}
1122
1123/* Add another configuration to the configuration list */
1124struct config *Configlist_add(rp,dot)
1125struct rule *rp; /* The rule */
1126int dot; /* Index into the RHS of the rule where the dot goes */
1127{
1128 struct config *cfp, model;
1129
1130 assert( currentend!=0 );
1131 model.rp = rp;
1132 model.dot = dot;
1133 cfp = Configtable_find(&model);
1134 if( cfp==0 ){
1135 cfp = newconfig();
1136 cfp->rp = rp;
1137 cfp->dot = dot;
1138 cfp->fws = SetNew();
1139 cfp->stp = 0;
1140 cfp->fplp = cfp->bplp = 0;
1141 cfp->next = 0;
1142 cfp->bp = 0;
1143 *currentend = cfp;
1144 currentend = &cfp->next;
1145 Configtable_insert(cfp);
1146 }
1147 return cfp;
1148}
1149
1150/* Add a basis configuration to the configuration list */
1151struct config *Configlist_addbasis(rp,dot)
1152struct rule *rp;
1153int dot;
1154{
1155 struct config *cfp, model;
1156
1157 assert( basisend!=0 );
1158 assert( currentend!=0 );
1159 model.rp = rp;
1160 model.dot = dot;
1161 cfp = Configtable_find(&model);
1162 if( cfp==0 ){
1163 cfp = newconfig();
1164 cfp->rp = rp;
1165 cfp->dot = dot;
1166 cfp->fws = SetNew();
1167 cfp->stp = 0;
1168 cfp->fplp = cfp->bplp = 0;
1169 cfp->next = 0;
1170 cfp->bp = 0;
1171 *currentend = cfp;
1172 currentend = &cfp->next;
1173 *basisend = cfp;
1174 basisend = &cfp->bp;
1175 Configtable_insert(cfp);
1176 }
1177 return cfp;
1178}
1179
1180/* Compute the closure of the configuration list */
1181void Configlist_closure(lemp)
1182struct lemon *lemp;
1183{
1184 struct config *cfp, *newcfp;
1185 struct rule *rp, *newrp;
1186 struct symbol *sp, *xsp;
1187 int i, dot;
1188
1189 assert( currentend!=0 );
1190 for(cfp=current; cfp; cfp=cfp->next){
1191 rp = cfp->rp;
1192 dot = cfp->dot;
1193 if( dot>=rp->nrhs ) continue;
1194 sp = rp->rhs[dot];
1195 if( sp->type==NONTERMINAL ){
1196 if( sp->rule==0 && sp!=lemp->errsym ){
1197 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1198 sp->name);
1199 lemp->errorcnt++;
1200 }
1201 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1202 newcfp = Configlist_add(newrp,0);
1203 for(i=dot+1; i<rp->nrhs; i++){
1204 xsp = rp->rhs[i];
1205 if( xsp->type==TERMINAL ){
1206 SetAdd(newcfp->fws,xsp->index);
1207 break;
drhfd405312005-11-06 04:06:59 +00001208 }else if( xsp->type==MULTITERMINAL ){
1209 int k;
1210 for(k=0; k<xsp->nsubsym; k++){
1211 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1212 }
1213 break;
drh75897232000-05-29 14:26:00 +00001214 }else{
1215 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001216 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001217 }
1218 }
1219 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1220 }
1221 }
1222 }
1223 return;
1224}
1225
1226/* Sort the configuration list */
1227void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001228 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001229 currentend = 0;
1230 return;
1231}
1232
1233/* Sort the basis configuration list */
1234void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001235 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001236 basisend = 0;
1237 return;
1238}
1239
1240/* Return a pointer to the head of the configuration list and
1241** reset the list */
1242struct config *Configlist_return(){
1243 struct config *old;
1244 old = current;
1245 current = 0;
1246 currentend = 0;
1247 return old;
1248}
1249
1250/* Return a pointer to the head of the configuration list and
1251** reset the list */
1252struct config *Configlist_basis(){
1253 struct config *old;
1254 old = basis;
1255 basis = 0;
1256 basisend = 0;
1257 return old;
1258}
1259
1260/* Free all elements of the given configuration list */
1261void Configlist_eat(cfp)
1262struct config *cfp;
1263{
1264 struct config *nextcfp;
1265 for(; cfp; cfp=nextcfp){
1266 nextcfp = cfp->next;
1267 assert( cfp->fplp==0 );
1268 assert( cfp->bplp==0 );
1269 if( cfp->fws ) SetFree(cfp->fws);
1270 deleteconfig(cfp);
1271 }
1272 return;
1273}
1274/***************** From the file "error.c" *********************************/
1275/*
1276** Code for printing error message.
1277*/
1278
1279/* Find a good place to break "msg" so that its length is at least "min"
1280** but no more than "max". Make the point as close to max as possible.
1281*/
1282static int findbreak(msg,min,max)
1283char *msg;
1284int min;
1285int max;
1286{
1287 int i,spot;
1288 char c;
1289 for(i=spot=min; i<=max; i++){
1290 c = msg[i];
1291 if( c=='\t' ) msg[i] = ' ';
1292 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1293 if( c==0 ){ spot = i; break; }
1294 if( c=='-' && i<max-1 ) spot = i+1;
1295 if( c==' ' ) spot = i;
1296 }
1297 return spot;
1298}
1299
1300/*
1301** The error message is split across multiple lines if necessary. The
1302** splits occur at a space, if there is a space available near the end
1303** of the line.
1304*/
1305#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1306#define LINEWIDTH 79 /* Max width of any output line */
1307#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
drhf9a2e7b2003-04-15 01:49:48 +00001308void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001309 char errmsg[ERRMSGSIZE];
1310 char prefix[PREFIXLIMIT+10];
1311 int errmsgsize;
1312 int prefixsize;
1313 int availablewidth;
1314 va_list ap;
1315 int end, restart, base;
1316
drhf9a2e7b2003-04-15 01:49:48 +00001317 va_start(ap, format);
drh75897232000-05-29 14:26:00 +00001318 /* Prepare a prefix to be prepended to every output line */
1319 if( lineno>0 ){
1320 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1321 }else{
1322 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1323 }
1324 prefixsize = strlen(prefix);
1325 availablewidth = LINEWIDTH - prefixsize;
1326
1327 /* Generate the error message */
1328 vsprintf(errmsg,format,ap);
1329 va_end(ap);
1330 errmsgsize = strlen(errmsg);
1331 /* Remove trailing '\n's from the error message. */
1332 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1333 errmsg[--errmsgsize] = 0;
1334 }
1335
1336 /* Print the error message */
1337 base = 0;
1338 while( errmsg[base]!=0 ){
1339 end = restart = findbreak(&errmsg[base],0,availablewidth);
1340 restart += base;
1341 while( errmsg[restart]==' ' ) restart++;
1342 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1343 base = restart;
1344 }
1345}
1346/**************** From the file "main.c" ************************************/
1347/*
1348** Main program file for the LEMON parser generator.
1349*/
1350
1351/* Report an out-of-memory condition and abort. This function
1352** is used mostly by the "MemoryCheck" macro in struct.h
1353*/
1354void memory_error(){
1355 fprintf(stderr,"Out of memory. Aborting...\n");
1356 exit(1);
1357}
1358
drh6d08b4d2004-07-20 12:45:22 +00001359static int nDefine = 0; /* Number of -D options on the command line */
1360static char **azDefine = 0; /* Name of the -D macros */
1361
1362/* This routine is called with the argument to each -D command-line option.
1363** Add the macro defined to the azDefine array.
1364*/
1365static void handle_D_option(char *z){
1366 char **paz;
1367 nDefine++;
1368 azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine);
1369 if( azDefine==0 ){
1370 fprintf(stderr,"out of memory\n");
1371 exit(1);
1372 }
1373 paz = &azDefine[nDefine-1];
1374 *paz = malloc( strlen(z)+1 );
1375 if( *paz==0 ){
1376 fprintf(stderr,"out of memory\n");
1377 exit(1);
1378 }
1379 strcpy(*paz, z);
1380 for(z=*paz; *z && *z!='='; z++){}
1381 *z = 0;
1382}
1383
drh75897232000-05-29 14:26:00 +00001384
1385/* The main program. Parse the command line and do it... */
1386int main(argc,argv)
1387int argc;
1388char **argv;
1389{
1390 static int version = 0;
1391 static int rpflag = 0;
1392 static int basisflag = 0;
1393 static int compress = 0;
1394 static int quiet = 0;
1395 static int statistics = 0;
1396 static int mhflag = 0;
1397 static struct s_options options[] = {
1398 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1399 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001400 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh75897232000-05-29 14:26:00 +00001401 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
1402 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
1403 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001404 {OPT_FLAG, "s", (char*)&statistics,
1405 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001406 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1407 {OPT_FLAG,0,0,0}
1408 };
1409 int i;
1410 struct lemon lem;
1411
drhb0c86772000-06-02 23:21:26 +00001412 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001413 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001414 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001415 exit(0);
1416 }
drhb0c86772000-06-02 23:21:26 +00001417 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001418 fprintf(stderr,"Exactly one filename argument is required.\n");
1419 exit(1);
1420 }
drh954f6b42006-06-13 13:27:46 +00001421 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001422 lem.errorcnt = 0;
1423
1424 /* Initialize the machine */
1425 Strsafe_init();
1426 Symbol_init();
1427 State_init();
1428 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001429 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001430 lem.basisflag = basisflag;
drh75897232000-05-29 14:26:00 +00001431 Symbol_new("$");
1432 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001433 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001434
1435 /* Parse the input file */
1436 Parse(&lem);
1437 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001438 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001439 fprintf(stderr,"Empty grammar.\n");
1440 exit(1);
1441 }
1442
1443 /* Count and index the symbols of the grammar */
1444 lem.nsymbol = Symbol_count();
1445 Symbol_new("{default}");
1446 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001447 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
drh75897232000-05-29 14:26:00 +00001448 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
1449 (int(*)())Symbolcmpp);
1450 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1451 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1452 lem.nterminal = i;
1453
1454 /* Generate a reprint of the grammar, if requested on the command line */
1455 if( rpflag ){
1456 Reprint(&lem);
1457 }else{
1458 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001459 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001460
1461 /* Find the precedence for every production rule (that has one) */
1462 FindRulePrecedences(&lem);
1463
1464 /* Compute the lambda-nonterminals and the first-sets for every
1465 ** nonterminal */
1466 FindFirstSets(&lem);
1467
1468 /* Compute all LR(0) states. Also record follow-set propagation
1469 ** links so that the follow-set can be computed later */
1470 lem.nstate = 0;
1471 FindStates(&lem);
1472 lem.sorted = State_arrayof();
1473
1474 /* Tie up loose ends on the propagation links */
1475 FindLinks(&lem);
1476
1477 /* Compute the follow set of every reducible configuration */
1478 FindFollowSets(&lem);
1479
1480 /* Compute the action tables */
1481 FindActions(&lem);
1482
1483 /* Compress the action tables */
1484 if( compress==0 ) CompressTables(&lem);
1485
drhada354d2005-11-05 15:03:59 +00001486 /* Reorder and renumber the states so that states with fewer choices
1487 ** occur at the end. */
1488 ResortStates(&lem);
1489
drh75897232000-05-29 14:26:00 +00001490 /* Generate a report of the parser generated. (the "y.output" file) */
1491 if( !quiet ) ReportOutput(&lem);
1492
1493 /* Generate the source code for the parser */
1494 ReportTable(&lem, mhflag);
1495
1496 /* Produce a header file for use by the scanner. (This step is
1497 ** omitted if the "-m" option is used because makeheaders will
1498 ** generate the file for us.) */
1499 if( !mhflag ) ReportHeader(&lem);
1500 }
1501 if( statistics ){
1502 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1503 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1504 printf(" %d states, %d parser table entries, %d conflicts\n",
1505 lem.nstate, lem.tablesize, lem.nconflict);
1506 }
1507 if( lem.nconflict ){
1508 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
1509 }
1510 exit(lem.errorcnt + lem.nconflict);
drh218dc692004-05-31 23:13:45 +00001511 return (lem.errorcnt + lem.nconflict);
drh75897232000-05-29 14:26:00 +00001512}
1513/******************** From the file "msort.c" *******************************/
1514/*
1515** A generic merge-sort program.
1516**
1517** USAGE:
1518** Let "ptr" be a pointer to some structure which is at the head of
1519** a null-terminated list. Then to sort the list call:
1520**
1521** ptr = msort(ptr,&(ptr->next),cmpfnc);
1522**
1523** In the above, "cmpfnc" is a pointer to a function which compares
1524** two instances of the structure and returns an integer, as in
1525** strcmp. The second argument is a pointer to the pointer to the
1526** second element of the linked list. This address is used to compute
1527** the offset to the "next" field within the structure. The offset to
1528** the "next" field must be constant for all structures in the list.
1529**
1530** The function returns a new pointer which is the head of the list
1531** after sorting.
1532**
1533** ALGORITHM:
1534** Merge-sort.
1535*/
1536
1537/*
1538** Return a pointer to the next structure in the linked list.
1539*/
drhba99af52001-10-25 20:37:16 +00001540#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001541
1542/*
1543** Inputs:
1544** a: A sorted, null-terminated linked list. (May be null).
1545** b: A sorted, null-terminated linked list. (May be null).
1546** cmp: A pointer to the comparison function.
1547** offset: Offset in the structure to the "next" field.
1548**
1549** Return Value:
1550** A pointer to the head of a sorted list containing the elements
1551** of both a and b.
1552**
1553** Side effects:
1554** The "next" pointers for elements in the lists a and b are
1555** changed.
1556*/
drhe9278182007-07-18 18:16:29 +00001557static char *merge(
1558 char *a,
1559 char *b,
1560 int (*cmp)(const char*,const char*),
1561 int offset
1562){
drh75897232000-05-29 14:26:00 +00001563 char *ptr, *head;
1564
1565 if( a==0 ){
1566 head = b;
1567 }else if( b==0 ){
1568 head = a;
1569 }else{
1570 if( (*cmp)(a,b)<0 ){
1571 ptr = a;
1572 a = NEXT(a);
1573 }else{
1574 ptr = b;
1575 b = NEXT(b);
1576 }
1577 head = ptr;
1578 while( a && b ){
1579 if( (*cmp)(a,b)<0 ){
1580 NEXT(ptr) = a;
1581 ptr = a;
1582 a = NEXT(a);
1583 }else{
1584 NEXT(ptr) = b;
1585 ptr = b;
1586 b = NEXT(b);
1587 }
1588 }
1589 if( a ) NEXT(ptr) = a;
1590 else NEXT(ptr) = b;
1591 }
1592 return head;
1593}
1594
1595/*
1596** Inputs:
1597** list: Pointer to a singly-linked list of structures.
1598** next: Pointer to pointer to the second element of the list.
1599** cmp: A comparison function.
1600**
1601** Return Value:
1602** A pointer to the head of a sorted list containing the elements
1603** orginally in list.
1604**
1605** Side effects:
1606** The "next" pointers for elements in list are changed.
1607*/
1608#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001609static char *msort(
1610 char *list,
1611 char **next,
1612 int (*cmp)(const char*,const char*)
1613){
drhba99af52001-10-25 20:37:16 +00001614 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001615 char *ep;
1616 char *set[LISTSIZE];
1617 int i;
drhba99af52001-10-25 20:37:16 +00001618 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001619 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1620 while( list ){
1621 ep = list;
1622 list = NEXT(list);
1623 NEXT(ep) = 0;
1624 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1625 ep = merge(ep,set[i],cmp,offset);
1626 set[i] = 0;
1627 }
1628 set[i] = ep;
1629 }
1630 ep = 0;
1631 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(ep,set[i],cmp,offset);
1632 return ep;
1633}
1634/************************ From the file "option.c" **************************/
1635static char **argv;
1636static struct s_options *op;
1637static FILE *errstream;
1638
1639#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1640
1641/*
1642** Print the command line with a carrot pointing to the k-th character
1643** of the n-th field.
1644*/
1645static void errline(n,k,err)
1646int n;
1647int k;
1648FILE *err;
1649{
1650 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001651 if( argv[0] ) fprintf(err,"%s",argv[0]);
1652 spcnt = strlen(argv[0]) + 1;
1653 for(i=1; i<n && argv[i]; i++){
1654 fprintf(err," %s",argv[i]);
drhdc30dd32005-02-16 03:35:15 +00001655 spcnt += strlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001656 }
1657 spcnt += k;
1658 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1659 if( spcnt<20 ){
1660 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1661 }else{
1662 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1663 }
1664}
1665
1666/*
1667** Return the index of the N-th non-switch argument. Return -1
1668** if N is out of range.
1669*/
1670static int argindex(n)
1671int n;
1672{
1673 int i;
1674 int dashdash = 0;
1675 if( argv!=0 && *argv!=0 ){
1676 for(i=1; argv[i]; i++){
1677 if( dashdash || !ISOPT(argv[i]) ){
1678 if( n==0 ) return i;
1679 n--;
1680 }
1681 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1682 }
1683 }
1684 return -1;
1685}
1686
1687static char emsg[] = "Command line syntax error: ";
1688
1689/*
1690** Process a flag command line argument.
1691*/
1692static int handleflags(i,err)
1693int i;
1694FILE *err;
1695{
1696 int v;
1697 int errcnt = 0;
1698 int j;
1699 for(j=0; op[j].label; j++){
drh6d08b4d2004-07-20 12:45:22 +00001700 if( strncmp(&argv[i][1],op[j].label,strlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001701 }
1702 v = argv[i][0]=='-' ? 1 : 0;
1703 if( op[j].label==0 ){
1704 if( err ){
1705 fprintf(err,"%sundefined option.\n",emsg);
1706 errline(i,1,err);
1707 }
1708 errcnt++;
1709 }else if( op[j].type==OPT_FLAG ){
1710 *((int*)op[j].arg) = v;
1711 }else if( op[j].type==OPT_FFLAG ){
1712 (*(void(*)())(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001713 }else if( op[j].type==OPT_FSTR ){
1714 (*(void(*)())(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001715 }else{
1716 if( err ){
1717 fprintf(err,"%smissing argument on switch.\n",emsg);
1718 errline(i,1,err);
1719 }
1720 errcnt++;
1721 }
1722 return errcnt;
1723}
1724
1725/*
1726** Process a command line switch which has an argument.
1727*/
1728static int handleswitch(i,err)
1729int i;
1730FILE *err;
1731{
1732 int lv = 0;
1733 double dv = 0.0;
1734 char *sv = 0, *end;
1735 char *cp;
1736 int j;
1737 int errcnt = 0;
1738 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001739 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001740 *cp = 0;
1741 for(j=0; op[j].label; j++){
1742 if( strcmp(argv[i],op[j].label)==0 ) break;
1743 }
1744 *cp = '=';
1745 if( op[j].label==0 ){
1746 if( err ){
1747 fprintf(err,"%sundefined option.\n",emsg);
1748 errline(i,0,err);
1749 }
1750 errcnt++;
1751 }else{
1752 cp++;
1753 switch( op[j].type ){
1754 case OPT_FLAG:
1755 case OPT_FFLAG:
1756 if( err ){
1757 fprintf(err,"%soption requires an argument.\n",emsg);
1758 errline(i,0,err);
1759 }
1760 errcnt++;
1761 break;
1762 case OPT_DBL:
1763 case OPT_FDBL:
1764 dv = strtod(cp,&end);
1765 if( *end ){
1766 if( err ){
1767 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001768 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001769 }
1770 errcnt++;
1771 }
1772 break;
1773 case OPT_INT:
1774 case OPT_FINT:
1775 lv = strtol(cp,&end,0);
1776 if( *end ){
1777 if( err ){
1778 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001779 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001780 }
1781 errcnt++;
1782 }
1783 break;
1784 case OPT_STR:
1785 case OPT_FSTR:
1786 sv = cp;
1787 break;
1788 }
1789 switch( op[j].type ){
1790 case OPT_FLAG:
1791 case OPT_FFLAG:
1792 break;
1793 case OPT_DBL:
1794 *(double*)(op[j].arg) = dv;
1795 break;
1796 case OPT_FDBL:
1797 (*(void(*)())(op[j].arg))(dv);
1798 break;
1799 case OPT_INT:
1800 *(int*)(op[j].arg) = lv;
1801 break;
1802 case OPT_FINT:
1803 (*(void(*)())(op[j].arg))((int)lv);
1804 break;
1805 case OPT_STR:
1806 *(char**)(op[j].arg) = sv;
1807 break;
1808 case OPT_FSTR:
1809 (*(void(*)())(op[j].arg))(sv);
1810 break;
1811 }
1812 }
1813 return errcnt;
1814}
1815
drhb0c86772000-06-02 23:21:26 +00001816int OptInit(a,o,err)
drh75897232000-05-29 14:26:00 +00001817char **a;
1818struct s_options *o;
1819FILE *err;
1820{
1821 int errcnt = 0;
1822 argv = a;
1823 op = o;
1824 errstream = err;
1825 if( argv && *argv && op ){
1826 int i;
1827 for(i=1; argv[i]; i++){
1828 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1829 errcnt += handleflags(i,err);
1830 }else if( strchr(argv[i],'=') ){
1831 errcnt += handleswitch(i,err);
1832 }
1833 }
1834 }
1835 if( errcnt>0 ){
1836 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001837 OptPrint();
drh75897232000-05-29 14:26:00 +00001838 exit(1);
1839 }
1840 return 0;
1841}
1842
drhb0c86772000-06-02 23:21:26 +00001843int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001844 int cnt = 0;
1845 int dashdash = 0;
1846 int i;
1847 if( argv!=0 && argv[0]!=0 ){
1848 for(i=1; argv[i]; i++){
1849 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1850 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1851 }
1852 }
1853 return cnt;
1854}
1855
drhb0c86772000-06-02 23:21:26 +00001856char *OptArg(n)
drh75897232000-05-29 14:26:00 +00001857int n;
1858{
1859 int i;
1860 i = argindex(n);
1861 return i>=0 ? argv[i] : 0;
1862}
1863
drhb0c86772000-06-02 23:21:26 +00001864void OptErr(n)
drh75897232000-05-29 14:26:00 +00001865int n;
1866{
1867 int i;
1868 i = argindex(n);
1869 if( i>=0 ) errline(i,0,errstream);
1870}
1871
drhb0c86772000-06-02 23:21:26 +00001872void OptPrint(){
drh75897232000-05-29 14:26:00 +00001873 int i;
1874 int max, len;
1875 max = 0;
1876 for(i=0; op[i].label; i++){
1877 len = strlen(op[i].label) + 1;
1878 switch( op[i].type ){
1879 case OPT_FLAG:
1880 case OPT_FFLAG:
1881 break;
1882 case OPT_INT:
1883 case OPT_FINT:
1884 len += 9; /* length of "<integer>" */
1885 break;
1886 case OPT_DBL:
1887 case OPT_FDBL:
1888 len += 6; /* length of "<real>" */
1889 break;
1890 case OPT_STR:
1891 case OPT_FSTR:
1892 len += 8; /* length of "<string>" */
1893 break;
1894 }
1895 if( len>max ) max = len;
1896 }
1897 for(i=0; op[i].label; i++){
1898 switch( op[i].type ){
1899 case OPT_FLAG:
1900 case OPT_FFLAG:
1901 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1902 break;
1903 case OPT_INT:
1904 case OPT_FINT:
1905 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001906 (int)(max-strlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001907 break;
1908 case OPT_DBL:
1909 case OPT_FDBL:
1910 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001911 (int)(max-strlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001912 break;
1913 case OPT_STR:
1914 case OPT_FSTR:
1915 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh8b582012003-10-21 13:16:03 +00001916 (int)(max-strlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001917 break;
1918 }
1919 }
1920}
1921/*********************** From the file "parse.c" ****************************/
1922/*
1923** Input file parser for the LEMON parser generator.
1924*/
1925
1926/* The state of the parser */
1927struct pstate {
1928 char *filename; /* Name of the input file */
1929 int tokenlineno; /* Linenumber at which current token starts */
1930 int errorcnt; /* Number of errors so far */
1931 char *tokenstart; /* Text of current token */
1932 struct lemon *gp; /* Global state vector */
1933 enum e_state {
1934 INITIALIZE,
1935 WAITING_FOR_DECL_OR_RULE,
1936 WAITING_FOR_DECL_KEYWORD,
1937 WAITING_FOR_DECL_ARG,
1938 WAITING_FOR_PRECEDENCE_SYMBOL,
1939 WAITING_FOR_ARROW,
1940 IN_RHS,
1941 LHS_ALIAS_1,
1942 LHS_ALIAS_2,
1943 LHS_ALIAS_3,
1944 RHS_ALIAS_1,
1945 RHS_ALIAS_2,
1946 PRECEDENCE_MARK_1,
1947 PRECEDENCE_MARK_2,
1948 RESYNC_AFTER_RULE_ERROR,
1949 RESYNC_AFTER_DECL_ERROR,
1950 WAITING_FOR_DESTRUCTOR_SYMBOL,
drh0bd1f4e2002-06-06 18:54:39 +00001951 WAITING_FOR_DATATYPE_SYMBOL,
drhe09daa92006-06-10 13:29:31 +00001952 WAITING_FOR_FALLBACK_ID,
1953 WAITING_FOR_WILDCARD_ID
drh75897232000-05-29 14:26:00 +00001954 } state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001955 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001956 struct symbol *lhs; /* Left-hand side of current rule */
1957 char *lhsalias; /* Alias for the LHS */
1958 int nrhs; /* Number of right-hand side symbols seen */
1959 struct symbol *rhs[MAXRHS]; /* RHS symbols */
1960 char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
1961 struct rule *prevrule; /* Previous rule parsed */
1962 char *declkeyword; /* Keyword of a declaration */
1963 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001964 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001965 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001966 enum e_assoc declassoc; /* Assign this association to decl arguments */
1967 int preccounter; /* Assign this precedence to decl arguments */
1968 struct rule *firstrule; /* Pointer to first rule in the grammar */
1969 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1970};
1971
1972/* Parse a single token */
1973static void parseonetoken(psp)
1974struct pstate *psp;
1975{
1976 char *x;
1977 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1978#if 0
1979 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1980 x,psp->state);
1981#endif
1982 switch( psp->state ){
1983 case INITIALIZE:
1984 psp->prevrule = 0;
1985 psp->preccounter = 0;
1986 psp->firstrule = psp->lastrule = 0;
1987 psp->gp->nrule = 0;
1988 /* Fall thru to next case */
1989 case WAITING_FOR_DECL_OR_RULE:
1990 if( x[0]=='%' ){
1991 psp->state = WAITING_FOR_DECL_KEYWORD;
1992 }else if( islower(x[0]) ){
1993 psp->lhs = Symbol_new(x);
1994 psp->nrhs = 0;
1995 psp->lhsalias = 0;
1996 psp->state = WAITING_FOR_ARROW;
1997 }else if( x[0]=='{' ){
1998 if( psp->prevrule==0 ){
1999 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002000"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002001fragment which begins on this line.");
2002 psp->errorcnt++;
2003 }else if( psp->prevrule->code!=0 ){
2004 ErrorMsg(psp->filename,psp->tokenlineno,
2005"Code fragment beginning on this line is not the first \
2006to follow the previous rule.");
2007 psp->errorcnt++;
2008 }else{
2009 psp->prevrule->line = psp->tokenlineno;
2010 psp->prevrule->code = &x[1];
2011 }
2012 }else if( x[0]=='[' ){
2013 psp->state = PRECEDENCE_MARK_1;
2014 }else{
2015 ErrorMsg(psp->filename,psp->tokenlineno,
2016 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2017 x);
2018 psp->errorcnt++;
2019 }
2020 break;
2021 case PRECEDENCE_MARK_1:
2022 if( !isupper(x[0]) ){
2023 ErrorMsg(psp->filename,psp->tokenlineno,
2024 "The precedence symbol must be a terminal.");
2025 psp->errorcnt++;
2026 }else if( psp->prevrule==0 ){
2027 ErrorMsg(psp->filename,psp->tokenlineno,
2028 "There is no prior rule to assign precedence \"[%s]\".",x);
2029 psp->errorcnt++;
2030 }else if( psp->prevrule->precsym!=0 ){
2031 ErrorMsg(psp->filename,psp->tokenlineno,
2032"Precedence mark on this line is not the first \
2033to follow the previous rule.");
2034 psp->errorcnt++;
2035 }else{
2036 psp->prevrule->precsym = Symbol_new(x);
2037 }
2038 psp->state = PRECEDENCE_MARK_2;
2039 break;
2040 case PRECEDENCE_MARK_2:
2041 if( x[0]!=']' ){
2042 ErrorMsg(psp->filename,psp->tokenlineno,
2043 "Missing \"]\" on precedence mark.");
2044 psp->errorcnt++;
2045 }
2046 psp->state = WAITING_FOR_DECL_OR_RULE;
2047 break;
2048 case WAITING_FOR_ARROW:
2049 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2050 psp->state = IN_RHS;
2051 }else if( x[0]=='(' ){
2052 psp->state = LHS_ALIAS_1;
2053 }else{
2054 ErrorMsg(psp->filename,psp->tokenlineno,
2055 "Expected to see a \":\" following the LHS symbol \"%s\".",
2056 psp->lhs->name);
2057 psp->errorcnt++;
2058 psp->state = RESYNC_AFTER_RULE_ERROR;
2059 }
2060 break;
2061 case LHS_ALIAS_1:
2062 if( isalpha(x[0]) ){
2063 psp->lhsalias = x;
2064 psp->state = LHS_ALIAS_2;
2065 }else{
2066 ErrorMsg(psp->filename,psp->tokenlineno,
2067 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2068 x,psp->lhs->name);
2069 psp->errorcnt++;
2070 psp->state = RESYNC_AFTER_RULE_ERROR;
2071 }
2072 break;
2073 case LHS_ALIAS_2:
2074 if( x[0]==')' ){
2075 psp->state = LHS_ALIAS_3;
2076 }else{
2077 ErrorMsg(psp->filename,psp->tokenlineno,
2078 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2079 psp->errorcnt++;
2080 psp->state = RESYNC_AFTER_RULE_ERROR;
2081 }
2082 break;
2083 case LHS_ALIAS_3:
2084 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2085 psp->state = IN_RHS;
2086 }else{
2087 ErrorMsg(psp->filename,psp->tokenlineno,
2088 "Missing \"->\" following: \"%s(%s)\".",
2089 psp->lhs->name,psp->lhsalias);
2090 psp->errorcnt++;
2091 psp->state = RESYNC_AFTER_RULE_ERROR;
2092 }
2093 break;
2094 case IN_RHS:
2095 if( x[0]=='.' ){
2096 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002097 rp = (struct rule *)calloc( sizeof(struct rule) +
2098 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002099 if( rp==0 ){
2100 ErrorMsg(psp->filename,psp->tokenlineno,
2101 "Can't allocate enough memory for this rule.");
2102 psp->errorcnt++;
2103 psp->prevrule = 0;
2104 }else{
2105 int i;
2106 rp->ruleline = psp->tokenlineno;
2107 rp->rhs = (struct symbol**)&rp[1];
2108 rp->rhsalias = (char**)&(rp->rhs[psp->nrhs]);
2109 for(i=0; i<psp->nrhs; i++){
2110 rp->rhs[i] = psp->rhs[i];
2111 rp->rhsalias[i] = psp->alias[i];
2112 }
2113 rp->lhs = psp->lhs;
2114 rp->lhsalias = psp->lhsalias;
2115 rp->nrhs = psp->nrhs;
2116 rp->code = 0;
2117 rp->precsym = 0;
2118 rp->index = psp->gp->nrule++;
2119 rp->nextlhs = rp->lhs->rule;
2120 rp->lhs->rule = rp;
2121 rp->next = 0;
2122 if( psp->firstrule==0 ){
2123 psp->firstrule = psp->lastrule = rp;
2124 }else{
2125 psp->lastrule->next = rp;
2126 psp->lastrule = rp;
2127 }
2128 psp->prevrule = rp;
2129 }
2130 psp->state = WAITING_FOR_DECL_OR_RULE;
2131 }else if( isalpha(x[0]) ){
2132 if( psp->nrhs>=MAXRHS ){
2133 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002134 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002135 x);
2136 psp->errorcnt++;
2137 psp->state = RESYNC_AFTER_RULE_ERROR;
2138 }else{
2139 psp->rhs[psp->nrhs] = Symbol_new(x);
2140 psp->alias[psp->nrhs] = 0;
2141 psp->nrhs++;
2142 }
drhfd405312005-11-06 04:06:59 +00002143 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2144 struct symbol *msp = psp->rhs[psp->nrhs-1];
2145 if( msp->type!=MULTITERMINAL ){
2146 struct symbol *origsp = msp;
drh9892c5d2007-12-21 00:02:11 +00002147 msp = calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002148 memset(msp, 0, sizeof(*msp));
2149 msp->type = MULTITERMINAL;
2150 msp->nsubsym = 1;
drh9892c5d2007-12-21 00:02:11 +00002151 msp->subsym = calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002152 msp->subsym[0] = origsp;
2153 msp->name = origsp->name;
2154 psp->rhs[psp->nrhs-1] = msp;
2155 }
2156 msp->nsubsym++;
2157 msp->subsym = realloc(msp->subsym, sizeof(struct symbol*)*msp->nsubsym);
2158 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2159 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2160 ErrorMsg(psp->filename,psp->tokenlineno,
2161 "Cannot form a compound containing a non-terminal");
2162 psp->errorcnt++;
2163 }
drh75897232000-05-29 14:26:00 +00002164 }else if( x[0]=='(' && psp->nrhs>0 ){
2165 psp->state = RHS_ALIAS_1;
2166 }else{
2167 ErrorMsg(psp->filename,psp->tokenlineno,
2168 "Illegal character on RHS of rule: \"%s\".",x);
2169 psp->errorcnt++;
2170 psp->state = RESYNC_AFTER_RULE_ERROR;
2171 }
2172 break;
2173 case RHS_ALIAS_1:
2174 if( isalpha(x[0]) ){
2175 psp->alias[psp->nrhs-1] = x;
2176 psp->state = RHS_ALIAS_2;
2177 }else{
2178 ErrorMsg(psp->filename,psp->tokenlineno,
2179 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2180 x,psp->rhs[psp->nrhs-1]->name);
2181 psp->errorcnt++;
2182 psp->state = RESYNC_AFTER_RULE_ERROR;
2183 }
2184 break;
2185 case RHS_ALIAS_2:
2186 if( x[0]==')' ){
2187 psp->state = IN_RHS;
2188 }else{
2189 ErrorMsg(psp->filename,psp->tokenlineno,
2190 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2191 psp->errorcnt++;
2192 psp->state = RESYNC_AFTER_RULE_ERROR;
2193 }
2194 break;
2195 case WAITING_FOR_DECL_KEYWORD:
2196 if( isalpha(x[0]) ){
2197 psp->declkeyword = x;
2198 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002199 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002200 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002201 psp->state = WAITING_FOR_DECL_ARG;
2202 if( strcmp(x,"name")==0 ){
2203 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002204 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002205 }else if( strcmp(x,"include")==0 ){
2206 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002207 }else if( strcmp(x,"code")==0 ){
2208 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002209 }else if( strcmp(x,"token_destructor")==0 ){
2210 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002211 }else if( strcmp(x,"default_destructor")==0 ){
2212 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002213 }else if( strcmp(x,"token_prefix")==0 ){
2214 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002215 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002216 }else if( strcmp(x,"syntax_error")==0 ){
2217 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002218 }else if( strcmp(x,"parse_accept")==0 ){
2219 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002220 }else if( strcmp(x,"parse_failure")==0 ){
2221 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002222 }else if( strcmp(x,"stack_overflow")==0 ){
2223 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002224 }else if( strcmp(x,"extra_argument")==0 ){
2225 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002226 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002227 }else if( strcmp(x,"token_type")==0 ){
2228 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002229 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002230 }else if( strcmp(x,"default_type")==0 ){
2231 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002232 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002233 }else if( strcmp(x,"stack_size")==0 ){
2234 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002235 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002236 }else if( strcmp(x,"start_symbol")==0 ){
2237 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002238 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002239 }else if( strcmp(x,"left")==0 ){
2240 psp->preccounter++;
2241 psp->declassoc = LEFT;
2242 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2243 }else if( strcmp(x,"right")==0 ){
2244 psp->preccounter++;
2245 psp->declassoc = RIGHT;
2246 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2247 }else if( strcmp(x,"nonassoc")==0 ){
2248 psp->preccounter++;
2249 psp->declassoc = NONE;
2250 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2251 }else if( strcmp(x,"destructor")==0 ){
2252 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2253 }else if( strcmp(x,"type")==0 ){
2254 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002255 }else if( strcmp(x,"fallback")==0 ){
2256 psp->fallback = 0;
2257 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002258 }else if( strcmp(x,"wildcard")==0 ){
2259 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002260 }else{
2261 ErrorMsg(psp->filename,psp->tokenlineno,
2262 "Unknown declaration keyword: \"%%%s\".",x);
2263 psp->errorcnt++;
2264 psp->state = RESYNC_AFTER_DECL_ERROR;
2265 }
2266 }else{
2267 ErrorMsg(psp->filename,psp->tokenlineno,
2268 "Illegal declaration keyword: \"%s\".",x);
2269 psp->errorcnt++;
2270 psp->state = RESYNC_AFTER_DECL_ERROR;
2271 }
2272 break;
2273 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2274 if( !isalpha(x[0]) ){
2275 ErrorMsg(psp->filename,psp->tokenlineno,
2276 "Symbol name missing after %destructor keyword");
2277 psp->errorcnt++;
2278 psp->state = RESYNC_AFTER_DECL_ERROR;
2279 }else{
2280 struct symbol *sp = Symbol_new(x);
2281 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002282 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002283 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002284 psp->state = WAITING_FOR_DECL_ARG;
2285 }
2286 break;
2287 case WAITING_FOR_DATATYPE_SYMBOL:
2288 if( !isalpha(x[0]) ){
2289 ErrorMsg(psp->filename,psp->tokenlineno,
2290 "Symbol name missing after %destructor keyword");
2291 psp->errorcnt++;
2292 psp->state = RESYNC_AFTER_DECL_ERROR;
2293 }else{
2294 struct symbol *sp = Symbol_new(x);
2295 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002296 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002297 psp->state = WAITING_FOR_DECL_ARG;
2298 }
2299 break;
2300 case WAITING_FOR_PRECEDENCE_SYMBOL:
2301 if( x[0]=='.' ){
2302 psp->state = WAITING_FOR_DECL_OR_RULE;
2303 }else if( isupper(x[0]) ){
2304 struct symbol *sp;
2305 sp = Symbol_new(x);
2306 if( sp->prec>=0 ){
2307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "Symbol \"%s\" has already be given a precedence.",x);
2309 psp->errorcnt++;
2310 }else{
2311 sp->prec = psp->preccounter;
2312 sp->assoc = psp->declassoc;
2313 }
2314 }else{
2315 ErrorMsg(psp->filename,psp->tokenlineno,
2316 "Can't assign a precedence to \"%s\".",x);
2317 psp->errorcnt++;
2318 }
2319 break;
2320 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002321 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
2322 char *zOld, *zNew, *zBuf, *z;
2323 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002324 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002325 char zLine[50];
2326 zNew = x;
2327 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
2328 nNew = strlen(zNew);
2329 if( *psp->declargslot ){
2330 zOld = *psp->declargslot;
2331 }else{
2332 zOld = "";
2333 }
2334 nOld = strlen(zOld);
2335 n = nOld + nNew + 20;
drhb5bd49e2008-07-14 12:21:08 +00002336 addLineMacro = psp->insertLineMacro &&
2337 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2338 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002339 for(z=psp->filename, nBack=0; *z; z++){
2340 if( *z=='\\' ) nBack++;
2341 }
2342 sprintf(zLine, "#line %d ", psp->tokenlineno);
2343 nLine = strlen(zLine);
2344 n += nLine + strlen(psp->filename) + nBack;
2345 }
2346 *psp->declargslot = zBuf = realloc(*psp->declargslot, n);
2347 zBuf += nOld;
drhb5bd49e2008-07-14 12:21:08 +00002348 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002349 if( nOld && zBuf[-1]!='\n' ){
2350 *(zBuf++) = '\n';
2351 }
2352 memcpy(zBuf, zLine, nLine);
2353 zBuf += nLine;
2354 *(zBuf++) = '"';
2355 for(z=psp->filename; *z; z++){
2356 if( *z=='\\' ){
2357 *(zBuf++) = '\\';
2358 }
2359 *(zBuf++) = *z;
2360 }
2361 *(zBuf++) = '"';
2362 *(zBuf++) = '\n';
2363 }
drh4dc8ef52008-07-01 17:13:57 +00002364 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2365 psp->decllinenoslot[0] = psp->tokenlineno;
2366 }
drha5808f32008-04-27 22:19:44 +00002367 memcpy(zBuf, zNew, nNew);
2368 zBuf += nNew;
2369 *zBuf = 0;
2370 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002371 }else{
2372 ErrorMsg(psp->filename,psp->tokenlineno,
2373 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2374 psp->errorcnt++;
2375 psp->state = RESYNC_AFTER_DECL_ERROR;
2376 }
2377 break;
drh0bd1f4e2002-06-06 18:54:39 +00002378 case WAITING_FOR_FALLBACK_ID:
2379 if( x[0]=='.' ){
2380 psp->state = WAITING_FOR_DECL_OR_RULE;
2381 }else if( !isupper(x[0]) ){
2382 ErrorMsg(psp->filename, psp->tokenlineno,
2383 "%%fallback argument \"%s\" should be a token", x);
2384 psp->errorcnt++;
2385 }else{
2386 struct symbol *sp = Symbol_new(x);
2387 if( psp->fallback==0 ){
2388 psp->fallback = sp;
2389 }else if( sp->fallback ){
2390 ErrorMsg(psp->filename, psp->tokenlineno,
2391 "More than one fallback assigned to token %s", x);
2392 psp->errorcnt++;
2393 }else{
2394 sp->fallback = psp->fallback;
2395 psp->gp->has_fallback = 1;
2396 }
2397 }
2398 break;
drhe09daa92006-06-10 13:29:31 +00002399 case WAITING_FOR_WILDCARD_ID:
2400 if( x[0]=='.' ){
2401 psp->state = WAITING_FOR_DECL_OR_RULE;
2402 }else if( !isupper(x[0]) ){
2403 ErrorMsg(psp->filename, psp->tokenlineno,
2404 "%%wildcard argument \"%s\" should be a token", x);
2405 psp->errorcnt++;
2406 }else{
2407 struct symbol *sp = Symbol_new(x);
2408 if( psp->gp->wildcard==0 ){
2409 psp->gp->wildcard = sp;
2410 }else{
2411 ErrorMsg(psp->filename, psp->tokenlineno,
2412 "Extra wildcard to token: %s", x);
2413 psp->errorcnt++;
2414 }
2415 }
2416 break;
drh75897232000-05-29 14:26:00 +00002417 case RESYNC_AFTER_RULE_ERROR:
2418/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2419** break; */
2420 case RESYNC_AFTER_DECL_ERROR:
2421 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2422 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2423 break;
2424 }
2425}
2426
drh34ff57b2008-07-14 12:27:51 +00002427/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002428** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2429** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2430** comments them out. Text in between is also commented out as appropriate.
2431*/
danielk1977940fac92005-01-23 22:41:37 +00002432static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002433 int i, j, k, n;
2434 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002435 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002436 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002437 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002438 for(i=0; z[i]; i++){
2439 if( z[i]=='\n' ) lineno++;
2440 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2441 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2442 if( exclude ){
2443 exclude--;
2444 if( exclude==0 ){
2445 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2446 }
2447 }
2448 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2449 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2450 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2451 if( exclude ){
2452 exclude++;
2453 }else{
2454 for(j=i+7; isspace(z[j]); j++){}
2455 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2456 exclude = 1;
2457 for(k=0; k<nDefine; k++){
2458 if( strncmp(azDefine[k],&z[j],n)==0 && strlen(azDefine[k])==n ){
2459 exclude = 0;
2460 break;
2461 }
2462 }
2463 if( z[i+3]=='n' ) exclude = !exclude;
2464 if( exclude ){
2465 start = i;
2466 start_lineno = lineno;
2467 }
2468 }
2469 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2470 }
2471 }
2472 if( exclude ){
2473 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2474 exit(1);
2475 }
2476}
2477
drh75897232000-05-29 14:26:00 +00002478/* In spite of its name, this function is really a scanner. It read
2479** in the entire input file (all at once) then tokenizes it. Each
2480** token is passed to the function "parseonetoken" which builds all
2481** the appropriate data structures in the global state vector "gp".
2482*/
2483void Parse(gp)
2484struct lemon *gp;
2485{
2486 struct pstate ps;
2487 FILE *fp;
2488 char *filebuf;
2489 int filesize;
2490 int lineno;
2491 int c;
2492 char *cp, *nextcp;
2493 int startline = 0;
2494
rse38514a92007-09-20 11:34:17 +00002495 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002496 ps.gp = gp;
2497 ps.filename = gp->filename;
2498 ps.errorcnt = 0;
2499 ps.state = INITIALIZE;
2500
2501 /* Begin by reading the input file */
2502 fp = fopen(ps.filename,"rb");
2503 if( fp==0 ){
2504 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2505 gp->errorcnt++;
2506 return;
2507 }
2508 fseek(fp,0,2);
2509 filesize = ftell(fp);
2510 rewind(fp);
2511 filebuf = (char *)malloc( filesize+1 );
2512 if( filebuf==0 ){
2513 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2514 filesize+1);
2515 gp->errorcnt++;
2516 return;
2517 }
2518 if( fread(filebuf,1,filesize,fp)!=filesize ){
2519 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2520 filesize);
2521 free(filebuf);
2522 gp->errorcnt++;
2523 return;
2524 }
2525 fclose(fp);
2526 filebuf[filesize] = 0;
2527
drh6d08b4d2004-07-20 12:45:22 +00002528 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2529 preprocess_input(filebuf);
2530
drh75897232000-05-29 14:26:00 +00002531 /* Now scan the text of the input file */
2532 lineno = 1;
2533 for(cp=filebuf; (c= *cp)!=0; ){
2534 if( c=='\n' ) lineno++; /* Keep track of the line number */
2535 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2536 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2537 cp+=2;
2538 while( (c= *cp)!=0 && c!='\n' ) cp++;
2539 continue;
2540 }
2541 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2542 cp+=2;
2543 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2544 if( c=='\n' ) lineno++;
2545 cp++;
2546 }
2547 if( c ) cp++;
2548 continue;
2549 }
2550 ps.tokenstart = cp; /* Mark the beginning of the token */
2551 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2552 if( c=='\"' ){ /* String literals */
2553 cp++;
2554 while( (c= *cp)!=0 && c!='\"' ){
2555 if( c=='\n' ) lineno++;
2556 cp++;
2557 }
2558 if( c==0 ){
2559 ErrorMsg(ps.filename,startline,
2560"String starting on this line is not terminated before the end of the file.");
2561 ps.errorcnt++;
2562 nextcp = cp;
2563 }else{
2564 nextcp = cp+1;
2565 }
2566 }else if( c=='{' ){ /* A block of C code */
2567 int level;
2568 cp++;
2569 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2570 if( c=='\n' ) lineno++;
2571 else if( c=='{' ) level++;
2572 else if( c=='}' ) level--;
2573 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2574 int prevc;
2575 cp = &cp[2];
2576 prevc = 0;
2577 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2578 if( c=='\n' ) lineno++;
2579 prevc = c;
2580 cp++;
2581 }
2582 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2583 cp = &cp[2];
2584 while( (c= *cp)!=0 && c!='\n' ) cp++;
2585 if( c ) lineno++;
2586 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2587 int startchar, prevc;
2588 startchar = c;
2589 prevc = 0;
2590 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2591 if( c=='\n' ) lineno++;
2592 if( prevc=='\\' ) prevc = 0;
2593 else prevc = c;
2594 }
2595 }
2596 }
2597 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002598 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002599"C code starting on this line is not terminated before the end of the file.");
2600 ps.errorcnt++;
2601 nextcp = cp;
2602 }else{
2603 nextcp = cp+1;
2604 }
2605 }else if( isalnum(c) ){ /* Identifiers */
2606 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2607 nextcp = cp;
2608 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2609 cp += 3;
2610 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002611 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2612 cp += 2;
2613 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2614 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002615 }else{ /* All other (one character) operators */
2616 cp++;
2617 nextcp = cp;
2618 }
2619 c = *cp;
2620 *cp = 0; /* Null terminate the token */
2621 parseonetoken(&ps); /* Parse the token */
2622 *cp = c; /* Restore the buffer */
2623 cp = nextcp;
2624 }
2625 free(filebuf); /* Release the buffer after parsing */
2626 gp->rule = ps.firstrule;
2627 gp->errorcnt = ps.errorcnt;
2628}
2629/*************************** From the file "plink.c" *********************/
2630/*
2631** Routines processing configuration follow-set propagation links
2632** in the LEMON parser generator.
2633*/
2634static struct plink *plink_freelist = 0;
2635
2636/* Allocate a new plink */
2637struct plink *Plink_new(){
2638 struct plink *new;
2639
2640 if( plink_freelist==0 ){
2641 int i;
2642 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002643 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002644 if( plink_freelist==0 ){
2645 fprintf(stderr,
2646 "Unable to allocate memory for a new follow-set propagation link.\n");
2647 exit(1);
2648 }
2649 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2650 plink_freelist[amt-1].next = 0;
2651 }
2652 new = plink_freelist;
2653 plink_freelist = plink_freelist->next;
2654 return new;
2655}
2656
2657/* Add a plink to a plink list */
2658void Plink_add(plpp,cfp)
2659struct plink **plpp;
2660struct config *cfp;
2661{
2662 struct plink *new;
2663 new = Plink_new();
2664 new->next = *plpp;
2665 *plpp = new;
2666 new->cfp = cfp;
2667}
2668
2669/* Transfer every plink on the list "from" to the list "to" */
2670void Plink_copy(to,from)
2671struct plink **to;
2672struct plink *from;
2673{
2674 struct plink *nextpl;
2675 while( from ){
2676 nextpl = from->next;
2677 from->next = *to;
2678 *to = from;
2679 from = nextpl;
2680 }
2681}
2682
2683/* Delete every plink on the list */
2684void Plink_delete(plp)
2685struct plink *plp;
2686{
2687 struct plink *nextpl;
2688
2689 while( plp ){
2690 nextpl = plp->next;
2691 plp->next = plink_freelist;
2692 plink_freelist = plp;
2693 plp = nextpl;
2694 }
2695}
2696/*********************** From the file "report.c" **************************/
2697/*
2698** Procedures for generating reports and tables in the LEMON parser generator.
2699*/
2700
2701/* Generate a filename with the given suffix. Space to hold the
2702** name comes from malloc() and must be freed by the calling
2703** function.
2704*/
2705PRIVATE char *file_makename(lemp,suffix)
2706struct lemon *lemp;
2707char *suffix;
2708{
2709 char *name;
2710 char *cp;
2711
2712 name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 );
2713 if( name==0 ){
2714 fprintf(stderr,"Can't allocate space for a filename.\n");
2715 exit(1);
2716 }
2717 strcpy(name,lemp->filename);
2718 cp = strrchr(name,'.');
2719 if( cp ) *cp = 0;
2720 strcat(name,suffix);
2721 return name;
2722}
2723
2724/* Open a file with a name based on the name of the input file,
2725** but with a different (specified) suffix, and return a pointer
2726** to the stream */
2727PRIVATE FILE *file_open(lemp,suffix,mode)
2728struct lemon *lemp;
2729char *suffix;
2730char *mode;
2731{
2732 FILE *fp;
2733
2734 if( lemp->outname ) free(lemp->outname);
2735 lemp->outname = file_makename(lemp, suffix);
2736 fp = fopen(lemp->outname,mode);
2737 if( fp==0 && *mode=='w' ){
2738 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2739 lemp->errorcnt++;
2740 return 0;
2741 }
2742 return fp;
2743}
2744
2745/* Duplicate the input file without comments and without actions
2746** on rules */
2747void Reprint(lemp)
2748struct lemon *lemp;
2749{
2750 struct rule *rp;
2751 struct symbol *sp;
2752 int i, j, maxlen, len, ncolumns, skip;
2753 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2754 maxlen = 10;
2755 for(i=0; i<lemp->nsymbol; i++){
2756 sp = lemp->symbols[i];
2757 len = strlen(sp->name);
2758 if( len>maxlen ) maxlen = len;
2759 }
2760 ncolumns = 76/(maxlen+5);
2761 if( ncolumns<1 ) ncolumns = 1;
2762 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2763 for(i=0; i<skip; i++){
2764 printf("//");
2765 for(j=i; j<lemp->nsymbol; j+=skip){
2766 sp = lemp->symbols[j];
2767 assert( sp->index==j );
2768 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2769 }
2770 printf("\n");
2771 }
2772 for(rp=lemp->rule; rp; rp=rp->next){
2773 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002774 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002775 printf(" ::=");
2776 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002777 sp = rp->rhs[i];
2778 printf(" %s", sp->name);
2779 if( sp->type==MULTITERMINAL ){
2780 for(j=1; j<sp->nsubsym; j++){
2781 printf("|%s", sp->subsym[j]->name);
2782 }
2783 }
2784 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002785 }
2786 printf(".");
2787 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002788 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002789 printf("\n");
2790 }
2791}
2792
2793void ConfigPrint(fp,cfp)
2794FILE *fp;
2795struct config *cfp;
2796{
2797 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002798 struct symbol *sp;
2799 int i, j;
drh75897232000-05-29 14:26:00 +00002800 rp = cfp->rp;
2801 fprintf(fp,"%s ::=",rp->lhs->name);
2802 for(i=0; i<=rp->nrhs; i++){
2803 if( i==cfp->dot ) fprintf(fp," *");
2804 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002805 sp = rp->rhs[i];
2806 fprintf(fp," %s", sp->name);
2807 if( sp->type==MULTITERMINAL ){
2808 for(j=1; j<sp->nsubsym; j++){
2809 fprintf(fp,"|%s",sp->subsym[j]->name);
2810 }
2811 }
drh75897232000-05-29 14:26:00 +00002812 }
2813}
2814
2815/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002816#if 0
drh75897232000-05-29 14:26:00 +00002817/* Print a set */
2818PRIVATE void SetPrint(out,set,lemp)
2819FILE *out;
2820char *set;
2821struct lemon *lemp;
2822{
2823 int i;
2824 char *spacer;
2825 spacer = "";
2826 fprintf(out,"%12s[","");
2827 for(i=0; i<lemp->nterminal; i++){
2828 if( SetFind(set,i) ){
2829 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2830 spacer = " ";
2831 }
2832 }
2833 fprintf(out,"]\n");
2834}
2835
2836/* Print a plink chain */
2837PRIVATE void PlinkPrint(out,plp,tag)
2838FILE *out;
2839struct plink *plp;
2840char *tag;
2841{
2842 while( plp ){
drhada354d2005-11-05 15:03:59 +00002843 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002844 ConfigPrint(out,plp->cfp);
2845 fprintf(out,"\n");
2846 plp = plp->next;
2847 }
2848}
2849#endif
2850
2851/* Print an action to the given file descriptor. Return FALSE if
2852** nothing was actually printed.
2853*/
2854int PrintAction(struct action *ap, FILE *fp, int indent){
2855 int result = 1;
2856 switch( ap->type ){
2857 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002858 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002859 break;
2860 case REDUCE:
2861 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2862 break;
2863 case ACCEPT:
2864 fprintf(fp,"%*s accept",indent,ap->sp->name);
2865 break;
2866 case ERROR:
2867 fprintf(fp,"%*s error",indent,ap->sp->name);
2868 break;
drh9892c5d2007-12-21 00:02:11 +00002869 case SRCONFLICT:
2870 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002871 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2872 indent,ap->sp->name,ap->x.rp->index);
2873 break;
drh9892c5d2007-12-21 00:02:11 +00002874 case SSCONFLICT:
2875 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2876 indent,ap->sp->name,ap->x.stp->statenum);
2877 break;
drh75897232000-05-29 14:26:00 +00002878 case SH_RESOLVED:
2879 case RD_RESOLVED:
2880 case NOT_USED:
2881 result = 0;
2882 break;
2883 }
2884 return result;
2885}
2886
2887/* Generate the "y.output" log file */
2888void ReportOutput(lemp)
2889struct lemon *lemp;
2890{
2891 int i;
2892 struct state *stp;
2893 struct config *cfp;
2894 struct action *ap;
2895 FILE *fp;
2896
drh2aa6ca42004-09-10 00:14:04 +00002897 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002898 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002899 for(i=0; i<lemp->nstate; i++){
2900 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002901 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002902 if( lemp->basisflag ) cfp=stp->bp;
2903 else cfp=stp->cfp;
2904 while( cfp ){
2905 char buf[20];
2906 if( cfp->dot==cfp->rp->nrhs ){
2907 sprintf(buf,"(%d)",cfp->rp->index);
2908 fprintf(fp," %5s ",buf);
2909 }else{
2910 fprintf(fp," ");
2911 }
2912 ConfigPrint(fp,cfp);
2913 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002914#if 0
drh75897232000-05-29 14:26:00 +00002915 SetPrint(fp,cfp->fws,lemp);
2916 PlinkPrint(fp,cfp->fplp,"To ");
2917 PlinkPrint(fp,cfp->bplp,"From");
2918#endif
2919 if( lemp->basisflag ) cfp=cfp->bp;
2920 else cfp=cfp->next;
2921 }
2922 fprintf(fp,"\n");
2923 for(ap=stp->ap; ap; ap=ap->next){
2924 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2925 }
2926 fprintf(fp,"\n");
2927 }
drhe9278182007-07-18 18:16:29 +00002928 fprintf(fp, "----------------------------------------------------\n");
2929 fprintf(fp, "Symbols:\n");
2930 for(i=0; i<lemp->nsymbol; i++){
2931 int j;
2932 struct symbol *sp;
2933
2934 sp = lemp->symbols[i];
2935 fprintf(fp, " %3d: %s", i, sp->name);
2936 if( sp->type==NONTERMINAL ){
2937 fprintf(fp, ":");
2938 if( sp->lambda ){
2939 fprintf(fp, " <lambda>");
2940 }
2941 for(j=0; j<lemp->nterminal; j++){
2942 if( sp->firstset && SetFind(sp->firstset, j) ){
2943 fprintf(fp, " %s", lemp->symbols[j]->name);
2944 }
2945 }
2946 }
2947 fprintf(fp, "\n");
2948 }
drh75897232000-05-29 14:26:00 +00002949 fclose(fp);
2950 return;
2951}
2952
2953/* Search for the file "name" which is in the same directory as
2954** the exacutable */
2955PRIVATE char *pathsearch(argv0,name,modemask)
2956char *argv0;
2957char *name;
2958int modemask;
2959{
2960 char *pathlist;
2961 char *path,*cp;
2962 char c;
drh75897232000-05-29 14:26:00 +00002963
2964#ifdef __WIN32__
2965 cp = strrchr(argv0,'\\');
2966#else
2967 cp = strrchr(argv0,'/');
2968#endif
2969 if( cp ){
2970 c = *cp;
2971 *cp = 0;
2972 path = (char *)malloc( strlen(argv0) + strlen(name) + 2 );
2973 if( path ) sprintf(path,"%s/%s",argv0,name);
2974 *cp = c;
2975 }else{
2976 extern char *getenv();
2977 pathlist = getenv("PATH");
2978 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
2979 path = (char *)malloc( strlen(pathlist)+strlen(name)+2 );
2980 if( path!=0 ){
2981 while( *pathlist ){
2982 cp = strchr(pathlist,':');
2983 if( cp==0 ) cp = &pathlist[strlen(pathlist)];
2984 c = *cp;
2985 *cp = 0;
2986 sprintf(path,"%s/%s",pathlist,name);
2987 *cp = c;
2988 if( c==0 ) pathlist = "";
2989 else pathlist = &cp[1];
2990 if( access(path,modemask)==0 ) break;
2991 }
2992 }
2993 }
2994 return path;
2995}
2996
2997/* Given an action, compute the integer value for that action
2998** which is to be put in the action table of the generated machine.
2999** Return negative if no action should be generated.
3000*/
3001PRIVATE int compute_action(lemp,ap)
3002struct lemon *lemp;
3003struct action *ap;
3004{
3005 int act;
3006 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003007 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003008 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3009 case ERROR: act = lemp->nstate + lemp->nrule; break;
3010 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3011 default: act = -1; break;
3012 }
3013 return act;
3014}
3015
3016#define LINESIZE 1000
3017/* The next cluster of routines are for reading the template file
3018** and writing the results to the generated parser */
3019/* The first function transfers data from "in" to "out" until
3020** a line is seen which begins with "%%". The line number is
3021** tracked.
3022**
3023** if name!=0, then any word that begin with "Parse" is changed to
3024** begin with *name instead.
3025*/
3026PRIVATE void tplt_xfer(name,in,out,lineno)
3027char *name;
3028FILE *in;
3029FILE *out;
3030int *lineno;
3031{
3032 int i, iStart;
3033 char line[LINESIZE];
3034 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3035 (*lineno)++;
3036 iStart = 0;
3037 if( name ){
3038 for(i=0; line[i]; i++){
3039 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3040 && (i==0 || !isalpha(line[i-1]))
3041 ){
3042 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3043 fprintf(out,"%s",name);
3044 i += 4;
3045 iStart = i+1;
3046 }
3047 }
3048 }
3049 fprintf(out,"%s",&line[iStart]);
3050 }
3051}
3052
3053/* The next function finds the template file and opens it, returning
3054** a pointer to the opened file. */
3055PRIVATE FILE *tplt_open(lemp)
3056struct lemon *lemp;
3057{
3058 static char templatename[] = "lempar.c";
3059 char buf[1000];
3060 FILE *in;
3061 char *tpltname;
3062 char *cp;
3063
3064 cp = strrchr(lemp->filename,'.');
3065 if( cp ){
drh8b582012003-10-21 13:16:03 +00003066 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003067 }else{
3068 sprintf(buf,"%s.lt",lemp->filename);
3069 }
3070 if( access(buf,004)==0 ){
3071 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003072 }else if( access(templatename,004)==0 ){
3073 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003074 }else{
3075 tpltname = pathsearch(lemp->argv0,templatename,0);
3076 }
3077 if( tpltname==0 ){
3078 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3079 templatename);
3080 lemp->errorcnt++;
3081 return 0;
3082 }
drh2aa6ca42004-09-10 00:14:04 +00003083 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003084 if( in==0 ){
3085 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3086 lemp->errorcnt++;
3087 return 0;
3088 }
3089 return in;
3090}
3091
drhaf805ca2004-09-07 11:28:25 +00003092/* Print a #line directive line to the output file. */
3093PRIVATE void tplt_linedir(out,lineno,filename)
3094FILE *out;
3095int lineno;
3096char *filename;
3097{
3098 fprintf(out,"#line %d \"",lineno);
3099 while( *filename ){
3100 if( *filename == '\\' ) putc('\\',out);
3101 putc(*filename,out);
3102 filename++;
3103 }
3104 fprintf(out,"\"\n");
3105}
3106
drh75897232000-05-29 14:26:00 +00003107/* Print a string to the file and keep the linenumber up to date */
drha5808f32008-04-27 22:19:44 +00003108PRIVATE void tplt_print(out,lemp,str,lineno)
drh75897232000-05-29 14:26:00 +00003109FILE *out;
3110struct lemon *lemp;
3111char *str;
drh75897232000-05-29 14:26:00 +00003112int *lineno;
3113{
3114 if( str==0 ) return;
drhaf805ca2004-09-07 11:28:25 +00003115 (*lineno)++;
drh75897232000-05-29 14:26:00 +00003116 while( *str ){
3117 if( *str=='\n' ) (*lineno)++;
3118 putc(*str,out);
3119 str++;
3120 }
drh9db55df2004-09-09 14:01:21 +00003121 if( str[-1]!='\n' ){
3122 putc('\n',out);
3123 (*lineno)++;
3124 }
drhaf805ca2004-09-07 11:28:25 +00003125 tplt_linedir(out,*lineno+2,lemp->outname);
3126 (*lineno)+=2;
drh75897232000-05-29 14:26:00 +00003127 return;
3128}
3129
3130/*
3131** The following routine emits code for the destructor for the
3132** symbol sp
3133*/
3134void emit_destructor_code(out,sp,lemp,lineno)
3135FILE *out;
3136struct symbol *sp;
3137struct lemon *lemp;
3138int *lineno;
3139{
drhcc83b6e2004-04-23 23:38:42 +00003140 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003141
3142 int linecnt = 0;
3143 if( sp->type==TERMINAL ){
3144 cp = lemp->tokendest;
3145 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003146 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003147 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003148 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003149 fprintf(out,"{\n"); (*lineno)++;
drh4dc8ef52008-07-01 17:13:57 +00003150 tplt_linedir(out,sp->destLineno,lemp->outname); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003151 }else if( lemp->vardest ){
3152 cp = lemp->vardest;
3153 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003154 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003155 }else{
3156 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003157 }
3158 for(; *cp; cp++){
3159 if( *cp=='$' && cp[1]=='$' ){
3160 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3161 cp++;
3162 continue;
3163 }
3164 if( *cp=='\n' ) linecnt++;
3165 fputc(*cp,out);
3166 }
3167 (*lineno) += 3 + linecnt;
drha5808f32008-04-27 22:19:44 +00003168 fprintf(out,"\n");
drhaf805ca2004-09-07 11:28:25 +00003169 tplt_linedir(out,*lineno,lemp->outname);
drha5808f32008-04-27 22:19:44 +00003170 fprintf(out,"}\n");
drh75897232000-05-29 14:26:00 +00003171 return;
3172}
3173
3174/*
drh960e8c62001-04-03 16:53:21 +00003175** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003176*/
3177int has_destructor(sp, lemp)
3178struct symbol *sp;
3179struct lemon *lemp;
3180{
3181 int ret;
3182 if( sp->type==TERMINAL ){
3183 ret = lemp->tokendest!=0;
3184 }else{
drh960e8c62001-04-03 16:53:21 +00003185 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003186 }
3187 return ret;
3188}
3189
drh0bb132b2004-07-20 14:06:51 +00003190/*
3191** Append text to a dynamically allocated string. If zText is 0 then
3192** reset the string to be empty again. Always return the complete text
3193** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003194**
3195** n bytes of zText are stored. If n==0 then all of zText up to the first
3196** \000 terminator is stored. zText can contain up to two instances of
3197** %d. The values of p1 and p2 are written into the first and second
3198** %d.
3199**
3200** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003201*/
3202PRIVATE char *append_str(char *zText, int n, int p1, int p2){
3203 static char *z = 0;
3204 static int alloced = 0;
3205 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003206 int c;
drh0bb132b2004-07-20 14:06:51 +00003207 char zInt[40];
3208
3209 if( zText==0 ){
3210 used = 0;
3211 return z;
3212 }
drh7ac25c72004-08-19 15:12:26 +00003213 if( n<=0 ){
3214 if( n<0 ){
3215 used += n;
3216 assert( used>=0 );
3217 }
3218 n = strlen(zText);
3219 }
drh0bb132b2004-07-20 14:06:51 +00003220 if( n+sizeof(zInt)*2+used >= alloced ){
3221 alloced = n + sizeof(zInt)*2 + used + 200;
3222 z = realloc(z, alloced);
3223 }
3224 if( z==0 ) return "";
3225 while( n-- > 0 ){
3226 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003227 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003228 sprintf(zInt, "%d", p1);
3229 p1 = p2;
3230 strcpy(&z[used], zInt);
3231 used += strlen(&z[used]);
3232 zText++;
3233 n--;
3234 }else{
3235 z[used++] = c;
3236 }
3237 }
3238 z[used] = 0;
3239 return z;
3240}
3241
3242/*
3243** zCode is a string that is the action associated with a rule. Expand
3244** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003245** stack.
drh0bb132b2004-07-20 14:06:51 +00003246*/
drhaf805ca2004-09-07 11:28:25 +00003247PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003248 char *cp, *xp;
3249 int i;
3250 char lhsused = 0; /* True if the LHS element has been used */
3251 char used[MAXRHS]; /* True for each RHS element which is used */
3252
3253 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3254 lhsused = 0;
3255
drh19c9e562007-03-29 20:13:53 +00003256 if( rp->code==0 ){
3257 rp->code = "\n";
3258 rp->line = rp->ruleline;
3259 }
3260
drh0bb132b2004-07-20 14:06:51 +00003261 append_str(0,0,0,0);
drh19c9e562007-03-29 20:13:53 +00003262 for(cp=rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003263 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3264 char saved;
3265 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3266 saved = *xp;
3267 *xp = 0;
3268 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003269 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003270 cp = xp;
3271 lhsused = 1;
3272 }else{
3273 for(i=0; i<rp->nrhs; i++){
3274 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003275 if( cp!=rp->code && cp[-1]=='@' ){
3276 /* If the argument is of the form @X then substituted
3277 ** the token number of X, not the value of X */
3278 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3279 }else{
drhfd405312005-11-06 04:06:59 +00003280 struct symbol *sp = rp->rhs[i];
3281 int dtnum;
3282 if( sp->type==MULTITERMINAL ){
3283 dtnum = sp->subsym[0]->dtnum;
3284 }else{
3285 dtnum = sp->dtnum;
3286 }
3287 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003288 }
drh0bb132b2004-07-20 14:06:51 +00003289 cp = xp;
3290 used[i] = 1;
3291 break;
3292 }
3293 }
3294 }
3295 *xp = saved;
3296 }
3297 append_str(cp, 1, 0, 0);
3298 } /* End loop */
3299
3300 /* Check to make sure the LHS has been used */
3301 if( rp->lhsalias && !lhsused ){
3302 ErrorMsg(lemp->filename,rp->ruleline,
3303 "Label \"%s\" for \"%s(%s)\" is never used.",
3304 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3305 lemp->errorcnt++;
3306 }
3307
3308 /* Generate destructor code for RHS symbols which are not used in the
3309 ** reduce code */
3310 for(i=0; i<rp->nrhs; i++){
3311 if( rp->rhsalias[i] && !used[i] ){
3312 ErrorMsg(lemp->filename,rp->ruleline,
3313 "Label %s for \"%s(%s)\" is never used.",
3314 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3315 lemp->errorcnt++;
3316 }else if( rp->rhsalias[i]==0 ){
3317 if( has_destructor(rp->rhs[i],lemp) ){
drh7ac25c72004-08-19 15:12:26 +00003318 append_str(" yy_destructor(%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003319 rp->rhs[i]->index,i-rp->nrhs+1);
3320 }else{
3321 /* No destructor defined for this term */
3322 }
3323 }
3324 }
drh61e339a2007-01-16 03:09:02 +00003325 if( rp->code ){
3326 cp = append_str(0,0,0,0);
3327 rp->code = Strsafe(cp?cp:"");
3328 }
drh0bb132b2004-07-20 14:06:51 +00003329}
3330
drh75897232000-05-29 14:26:00 +00003331/*
3332** Generate code which executes when the rule "rp" is reduced. Write
3333** the code to "out". Make sure lineno stays up-to-date.
3334*/
3335PRIVATE void emit_code(out,rp,lemp,lineno)
3336FILE *out;
3337struct rule *rp;
3338struct lemon *lemp;
3339int *lineno;
3340{
drh0bb132b2004-07-20 14:06:51 +00003341 char *cp;
drh75897232000-05-29 14:26:00 +00003342 int linecnt = 0;
drh75897232000-05-29 14:26:00 +00003343
3344 /* Generate code to do the reduce action */
3345 if( rp->code ){
drhaf805ca2004-09-07 11:28:25 +00003346 tplt_linedir(out,rp->line,lemp->filename);
3347 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003348 for(cp=rp->code; *cp; cp++){
drh75897232000-05-29 14:26:00 +00003349 if( *cp=='\n' ) linecnt++;
drh75897232000-05-29 14:26:00 +00003350 } /* End loop */
3351 (*lineno) += 3 + linecnt;
drhaf805ca2004-09-07 11:28:25 +00003352 fprintf(out,"}\n");
3353 tplt_linedir(out,*lineno,lemp->outname);
drh75897232000-05-29 14:26:00 +00003354 } /* End if( rp->code ) */
3355
drh75897232000-05-29 14:26:00 +00003356 return;
3357}
3358
3359/*
3360** Print the definition of the union used for the parser's data stack.
3361** This union contains fields for every possible data type for tokens
3362** and nonterminals. In the process of computing and printing this
3363** union, also set the ".dtnum" field of every terminal and nonterminal
3364** symbol.
3365*/
3366void print_stack_union(out,lemp,plineno,mhflag)
3367FILE *out; /* The output stream */
3368struct lemon *lemp; /* The main info structure for this parser */
3369int *plineno; /* Pointer to the line number */
3370int mhflag; /* True if generating makeheaders output */
3371{
3372 int lineno = *plineno; /* The line number of the output */
3373 char **types; /* A hash table of datatypes */
3374 int arraysize; /* Size of the "types" array */
3375 int maxdtlength; /* Maximum length of any ".datatype" field. */
3376 char *stddt; /* Standardized name for a datatype */
3377 int i,j; /* Loop counters */
3378 int hash; /* For hashing the name of a type */
3379 char *name; /* Name of the parser */
3380
3381 /* Allocate and initialize types[] and allocate stddt[] */
3382 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003383 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003384 for(i=0; i<arraysize; i++) types[i] = 0;
3385 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003386 if( lemp->vartype ){
3387 maxdtlength = strlen(lemp->vartype);
3388 }
drh75897232000-05-29 14:26:00 +00003389 for(i=0; i<lemp->nsymbol; i++){
3390 int len;
3391 struct symbol *sp = lemp->symbols[i];
3392 if( sp->datatype==0 ) continue;
3393 len = strlen(sp->datatype);
3394 if( len>maxdtlength ) maxdtlength = len;
3395 }
3396 stddt = (char*)malloc( maxdtlength*2 + 1 );
3397 if( types==0 || stddt==0 ){
3398 fprintf(stderr,"Out of memory.\n");
3399 exit(1);
3400 }
3401
3402 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3403 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003404 ** used for terminal symbols. If there is no %default_type defined then
3405 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3406 ** a datatype using the %type directive.
3407 */
drh75897232000-05-29 14:26:00 +00003408 for(i=0; i<lemp->nsymbol; i++){
3409 struct symbol *sp = lemp->symbols[i];
3410 char *cp;
3411 if( sp==lemp->errsym ){
3412 sp->dtnum = arraysize+1;
3413 continue;
3414 }
drh960e8c62001-04-03 16:53:21 +00003415 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003416 sp->dtnum = 0;
3417 continue;
3418 }
3419 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003420 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003421 j = 0;
3422 while( isspace(*cp) ) cp++;
3423 while( *cp ) stddt[j++] = *cp++;
3424 while( j>0 && isspace(stddt[j-1]) ) j--;
3425 stddt[j] = 0;
drh32c4d742008-07-01 16:34:49 +00003426 if( strcmp(stddt, lemp->tokentype)==0 ){
3427 sp->dtnum = 0;
3428 continue;
3429 }
drh75897232000-05-29 14:26:00 +00003430 hash = 0;
3431 for(j=0; stddt[j]; j++){
3432 hash = hash*53 + stddt[j];
3433 }
drh3b2129c2003-05-13 00:34:21 +00003434 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003435 while( types[hash] ){
3436 if( strcmp(types[hash],stddt)==0 ){
3437 sp->dtnum = hash + 1;
3438 break;
3439 }
3440 hash++;
3441 if( hash>=arraysize ) hash = 0;
3442 }
3443 if( types[hash]==0 ){
3444 sp->dtnum = hash + 1;
3445 types[hash] = (char*)malloc( strlen(stddt)+1 );
3446 if( types[hash]==0 ){
3447 fprintf(stderr,"Out of memory.\n");
3448 exit(1);
3449 }
3450 strcpy(types[hash],stddt);
3451 }
3452 }
3453
3454 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3455 name = lemp->name ? lemp->name : "Parse";
3456 lineno = *plineno;
3457 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3458 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3459 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3460 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3461 fprintf(out,"typedef union {\n"); lineno++;
3462 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3463 for(i=0; i<arraysize; i++){
3464 if( types[i]==0 ) continue;
3465 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3466 free(types[i]);
3467 }
drhc4dd3fd2008-01-22 01:48:05 +00003468 if( lemp->errsym->useCnt ){
3469 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3470 }
drh75897232000-05-29 14:26:00 +00003471 free(stddt);
3472 free(types);
3473 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3474 *plineno = lineno;
3475}
3476
drhb29b0a52002-02-23 19:39:46 +00003477/*
3478** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003479** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003480*/
drh8b582012003-10-21 13:16:03 +00003481static const char *minimum_size_type(int lwr, int upr){
3482 if( lwr>=0 ){
3483 if( upr<=255 ){
3484 return "unsigned char";
3485 }else if( upr<65535 ){
3486 return "unsigned short int";
3487 }else{
3488 return "unsigned int";
3489 }
3490 }else if( lwr>=-127 && upr<=127 ){
3491 return "signed char";
3492 }else if( lwr>=-32767 && upr<32767 ){
3493 return "short";
drhb29b0a52002-02-23 19:39:46 +00003494 }else{
drh8b582012003-10-21 13:16:03 +00003495 return "int";
drhb29b0a52002-02-23 19:39:46 +00003496 }
3497}
3498
drhfdbf9282003-10-21 16:34:41 +00003499/*
3500** Each state contains a set of token transaction and a set of
3501** nonterminal transactions. Each of these sets makes an instance
3502** of the following structure. An array of these structures is used
3503** to order the creation of entries in the yy_action[] table.
3504*/
3505struct axset {
3506 struct state *stp; /* A pointer to a state */
3507 int isTkn; /* True to use tokens. False for non-terminals */
3508 int nAction; /* Number of actions */
3509};
3510
3511/*
3512** Compare to axset structures for sorting purposes
3513*/
3514static int axset_compare(const void *a, const void *b){
3515 struct axset *p1 = (struct axset*)a;
3516 struct axset *p2 = (struct axset*)b;
3517 return p2->nAction - p1->nAction;
3518}
3519
drhc4dd3fd2008-01-22 01:48:05 +00003520/*
3521** Write text on "out" that describes the rule "rp".
3522*/
3523static void writeRuleText(FILE *out, struct rule *rp){
3524 int j;
3525 fprintf(out,"%s ::=", rp->lhs->name);
3526 for(j=0; j<rp->nrhs; j++){
3527 struct symbol *sp = rp->rhs[j];
3528 fprintf(out," %s", sp->name);
3529 if( sp->type==MULTITERMINAL ){
3530 int k;
3531 for(k=1; k<sp->nsubsym; k++){
3532 fprintf(out,"|%s",sp->subsym[k]->name);
3533 }
3534 }
3535 }
3536}
3537
3538
drh75897232000-05-29 14:26:00 +00003539/* Generate C source code for the parser */
3540void ReportTable(lemp, mhflag)
3541struct lemon *lemp;
3542int mhflag; /* Output in makeheaders format if true */
3543{
3544 FILE *out, *in;
3545 char line[LINESIZE];
3546 int lineno;
3547 struct state *stp;
3548 struct action *ap;
3549 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003550 struct acttab *pActtab;
3551 int i, j, n;
drh75897232000-05-29 14:26:00 +00003552 char *name;
drh8b582012003-10-21 13:16:03 +00003553 int mnTknOfst, mxTknOfst;
3554 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003555 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003556
3557 in = tplt_open(lemp);
3558 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003559 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003560 if( out==0 ){
3561 fclose(in);
3562 return;
3563 }
3564 lineno = 1;
3565 tplt_xfer(lemp->name,in,out,&lineno);
3566
3567 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003568 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003569 if( mhflag ){
3570 char *name = file_makename(lemp, ".h");
3571 fprintf(out,"#include \"%s\"\n", name); lineno++;
3572 free(name);
3573 }
3574 tplt_xfer(lemp->name,in,out,&lineno);
3575
3576 /* Generate #defines for all tokens */
3577 if( mhflag ){
3578 char *prefix;
3579 fprintf(out,"#if INTERFACE\n"); lineno++;
3580 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3581 else prefix = "";
3582 for(i=1; i<lemp->nterminal; i++){
3583 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3584 lineno++;
3585 }
3586 fprintf(out,"#endif\n"); lineno++;
3587 }
3588 tplt_xfer(lemp->name,in,out,&lineno);
3589
3590 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003591 fprintf(out,"#define YYCODETYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003592 minimum_size_type(0, lemp->nsymbol+5)); lineno++;
drh75897232000-05-29 14:26:00 +00003593 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3594 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003595 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003596 if( lemp->wildcard ){
3597 fprintf(out,"#define YYWILDCARD %d\n",
3598 lemp->wildcard->index); lineno++;
3599 }
drh75897232000-05-29 14:26:00 +00003600 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003601 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003602 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003603 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3604 }else{
3605 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3606 }
drhca44b5a2007-02-22 23:06:58 +00003607 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003608 if( mhflag ){
3609 fprintf(out,"#if INTERFACE\n"); lineno++;
3610 }
3611 name = lemp->name ? lemp->name : "Parse";
3612 if( lemp->arg && lemp->arg[0] ){
3613 int i;
3614 i = strlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003615 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3616 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003617 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3618 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3619 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3620 name,lemp->arg,&lemp->arg[i]); lineno++;
3621 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3622 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003623 }else{
drh1f245e42002-03-11 13:55:50 +00003624 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3625 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3626 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3627 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003628 }
3629 if( mhflag ){
3630 fprintf(out,"#endif\n"); lineno++;
3631 }
3632 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3633 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003634 if( lemp->errsym->useCnt ){
3635 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3636 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3637 }
drh0bd1f4e2002-06-06 18:54:39 +00003638 if( lemp->has_fallback ){
3639 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3640 }
drh75897232000-05-29 14:26:00 +00003641 tplt_xfer(lemp->name,in,out,&lineno);
3642
drh8b582012003-10-21 13:16:03 +00003643 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003644 **
drh8b582012003-10-21 13:16:03 +00003645 ** yy_action[] A single table containing all actions.
3646 ** yy_lookahead[] A table containing the lookahead for each entry in
3647 ** yy_action. Used to detect hash collisions.
3648 ** yy_shift_ofst[] For each state, the offset into yy_action for
3649 ** shifting terminals.
3650 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3651 ** shifting non-terminals after a reduce.
3652 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003653 */
drh75897232000-05-29 14:26:00 +00003654
drh8b582012003-10-21 13:16:03 +00003655 /* Compute the actions on all states and count them up */
drh9892c5d2007-12-21 00:02:11 +00003656 ax = calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003657 if( ax==0 ){
3658 fprintf(stderr,"malloc failed\n");
3659 exit(1);
3660 }
drh75897232000-05-29 14:26:00 +00003661 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003662 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003663 ax[i*2].stp = stp;
3664 ax[i*2].isTkn = 1;
3665 ax[i*2].nAction = stp->nTknAct;
3666 ax[i*2+1].stp = stp;
3667 ax[i*2+1].isTkn = 0;
3668 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003669 }
drh8b582012003-10-21 13:16:03 +00003670 mxTknOfst = mnTknOfst = 0;
3671 mxNtOfst = mnNtOfst = 0;
3672
drhfdbf9282003-10-21 16:34:41 +00003673 /* Compute the action table. In order to try to keep the size of the
3674 ** action table to a minimum, the heuristic of placing the largest action
3675 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003676 */
drhfdbf9282003-10-21 16:34:41 +00003677 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003678 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003679 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3680 stp = ax[i].stp;
3681 if( ax[i].isTkn ){
3682 for(ap=stp->ap; ap; ap=ap->next){
3683 int action;
3684 if( ap->sp->index>=lemp->nterminal ) continue;
3685 action = compute_action(lemp, ap);
3686 if( action<0 ) continue;
3687 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003688 }
drhfdbf9282003-10-21 16:34:41 +00003689 stp->iTknOfst = acttab_insert(pActtab);
3690 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3691 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3692 }else{
3693 for(ap=stp->ap; ap; ap=ap->next){
3694 int action;
3695 if( ap->sp->index<lemp->nterminal ) continue;
3696 if( ap->sp->index==lemp->nsymbol ) continue;
3697 action = compute_action(lemp, ap);
3698 if( action<0 ) continue;
3699 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003700 }
drhfdbf9282003-10-21 16:34:41 +00003701 stp->iNtOfst = acttab_insert(pActtab);
3702 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3703 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003704 }
3705 }
drhfdbf9282003-10-21 16:34:41 +00003706 free(ax);
drh8b582012003-10-21 13:16:03 +00003707
3708 /* Output the yy_action table */
drh57196282004-10-06 15:41:16 +00003709 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003710 n = acttab_size(pActtab);
3711 for(i=j=0; i<n; i++){
3712 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003713 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003714 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003715 fprintf(out, " %4d,", action);
3716 if( j==9 || i==n-1 ){
3717 fprintf(out, "\n"); lineno++;
3718 j = 0;
3719 }else{
3720 j++;
3721 }
3722 }
3723 fprintf(out, "};\n"); lineno++;
3724
3725 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003726 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003727 for(i=j=0; i<n; i++){
3728 int la = acttab_yylookahead(pActtab, i);
3729 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003730 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003731 fprintf(out, " %4d,", la);
3732 if( j==9 || i==n-1 ){
3733 fprintf(out, "\n"); lineno++;
3734 j = 0;
3735 }else{
3736 j++;
3737 }
3738 }
3739 fprintf(out, "};\n"); lineno++;
3740
3741 /* Output the yy_shift_ofst[] table */
3742 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003743 n = lemp->nstate;
3744 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
3745 fprintf(out, "#define YY_SHIFT_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003746 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003747 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003748 for(i=j=0; i<n; i++){
3749 int ofst;
3750 stp = lemp->sorted[i];
3751 ofst = stp->iTknOfst;
3752 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003753 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003754 fprintf(out, " %4d,", ofst);
3755 if( j==9 || i==n-1 ){
3756 fprintf(out, "\n"); lineno++;
3757 j = 0;
3758 }else{
3759 j++;
3760 }
3761 }
3762 fprintf(out, "};\n"); lineno++;
3763
3764 /* Output the yy_reduce_ofst[] table */
3765 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003766 n = lemp->nstate;
3767 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
3768 fprintf(out, "#define YY_REDUCE_MAX %d\n", n-1); lineno++;
drh57196282004-10-06 15:41:16 +00003769 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003770 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003771 for(i=j=0; i<n; i++){
3772 int ofst;
3773 stp = lemp->sorted[i];
3774 ofst = stp->iNtOfst;
3775 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003776 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003777 fprintf(out, " %4d,", ofst);
3778 if( j==9 || i==n-1 ){
3779 fprintf(out, "\n"); lineno++;
3780 j = 0;
3781 }else{
3782 j++;
3783 }
3784 }
3785 fprintf(out, "};\n"); lineno++;
3786
3787 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003788 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003789 n = lemp->nstate;
3790 for(i=j=0; i<n; i++){
3791 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003792 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003793 fprintf(out, " %4d,", stp->iDflt);
3794 if( j==9 || i==n-1 ){
3795 fprintf(out, "\n"); lineno++;
3796 j = 0;
3797 }else{
3798 j++;
3799 }
3800 }
3801 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003802 tplt_xfer(lemp->name,in,out,&lineno);
3803
drh0bd1f4e2002-06-06 18:54:39 +00003804 /* Generate the table of fallback tokens.
3805 */
3806 if( lemp->has_fallback ){
3807 for(i=0; i<lemp->nterminal; i++){
3808 struct symbol *p = lemp->symbols[i];
3809 if( p->fallback==0 ){
3810 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3811 }else{
3812 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3813 p->name, p->fallback->name);
3814 }
3815 lineno++;
3816 }
3817 }
3818 tplt_xfer(lemp->name, in, out, &lineno);
3819
3820 /* Generate a table containing the symbolic name of every symbol
3821 */
drh75897232000-05-29 14:26:00 +00003822 for(i=0; i<lemp->nsymbol; i++){
3823 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3824 fprintf(out," %-15s",line);
3825 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3826 }
3827 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3828 tplt_xfer(lemp->name,in,out,&lineno);
3829
drh0bd1f4e2002-06-06 18:54:39 +00003830 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003831 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003832 ** when tracing REDUCE actions.
3833 */
3834 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3835 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003836 fprintf(out," /* %3d */ \"", i);
3837 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003838 fprintf(out,"\",\n"); lineno++;
3839 }
3840 tplt_xfer(lemp->name,in,out,&lineno);
3841
drh75897232000-05-29 14:26:00 +00003842 /* Generate code which executes every time a symbol is popped from
3843 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003844 ** (In other words, generate the %destructor actions)
3845 */
drh75897232000-05-29 14:26:00 +00003846 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003847 int once = 1;
drh75897232000-05-29 14:26:00 +00003848 for(i=0; i<lemp->nsymbol; i++){
3849 struct symbol *sp = lemp->symbols[i];
3850 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003851 if( once ){
3852 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3853 once = 0;
3854 }
drhc4dd3fd2008-01-22 01:48:05 +00003855 fprintf(out," case %d: /* %s */\n",
3856 sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003857 }
3858 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3859 if( i<lemp->nsymbol ){
3860 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3861 fprintf(out," break;\n"); lineno++;
3862 }
3863 }
drh8d659732005-01-13 23:54:06 +00003864 if( lemp->vardest ){
3865 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003866 int once = 1;
drh8d659732005-01-13 23:54:06 +00003867 for(i=0; i<lemp->nsymbol; i++){
3868 struct symbol *sp = lemp->symbols[i];
3869 if( sp==0 || sp->type==TERMINAL ||
3870 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003871 if( once ){
3872 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3873 once = 0;
3874 }
drhc4dd3fd2008-01-22 01:48:05 +00003875 fprintf(out," case %d: /* %s */\n",
3876 sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003877 dflt_sp = sp;
3878 }
3879 if( dflt_sp!=0 ){
3880 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003881 }
drh4dc8ef52008-07-01 17:13:57 +00003882 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003883 }
drh75897232000-05-29 14:26:00 +00003884 for(i=0; i<lemp->nsymbol; i++){
3885 struct symbol *sp = lemp->symbols[i];
3886 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003887 fprintf(out," case %d: /* %s */\n",
3888 sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003889
3890 /* Combine duplicate destructors into a single case */
3891 for(j=i+1; j<lemp->nsymbol; j++){
3892 struct symbol *sp2 = lemp->symbols[j];
3893 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3894 && sp2->dtnum==sp->dtnum
3895 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc4dd3fd2008-01-22 01:48:05 +00003896 fprintf(out," case %d: /* %s */\n",
3897 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003898 sp2->destructor = 0;
3899 }
3900 }
3901
drh75897232000-05-29 14:26:00 +00003902 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3903 fprintf(out," break;\n"); lineno++;
3904 }
drh75897232000-05-29 14:26:00 +00003905 tplt_xfer(lemp->name,in,out,&lineno);
3906
3907 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003908 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003909 tplt_xfer(lemp->name,in,out,&lineno);
3910
3911 /* Generate the table of rule information
3912 **
3913 ** Note: This code depends on the fact that rules are number
3914 ** sequentually beginning with 0.
3915 */
3916 for(rp=lemp->rule; rp; rp=rp->next){
3917 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3918 }
3919 tplt_xfer(lemp->name,in,out,&lineno);
3920
3921 /* Generate code which execution during each REDUCE action */
3922 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003923 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003924 }
3925 for(rp=lemp->rule; rp; rp=rp->next){
3926 struct rule *rp2;
3927 if( rp->code==0 ) continue;
drhc4dd3fd2008-01-22 01:48:05 +00003928 fprintf(out," case %d: /* ", rp->index);
3929 writeRuleText(out, rp);
3930 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003931 for(rp2=rp->next; rp2; rp2=rp2->next){
3932 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003933 fprintf(out," case %d: /* ", rp2->index);
3934 writeRuleText(out, rp2);
3935 fprintf(out," */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003936 rp2->code = 0;
3937 }
3938 }
drh75897232000-05-29 14:26:00 +00003939 emit_code(out,rp,lemp,&lineno);
3940 fprintf(out," break;\n"); lineno++;
3941 }
3942 tplt_xfer(lemp->name,in,out,&lineno);
3943
3944 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003945 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00003946 tplt_xfer(lemp->name,in,out,&lineno);
3947
3948 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00003949 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00003950 tplt_xfer(lemp->name,in,out,&lineno);
3951
3952 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00003953 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00003954 tplt_xfer(lemp->name,in,out,&lineno);
3955
3956 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00003957 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00003958
3959 fclose(in);
3960 fclose(out);
3961 return;
3962}
3963
3964/* Generate a header file for the parser */
3965void ReportHeader(lemp)
3966struct lemon *lemp;
3967{
3968 FILE *out, *in;
3969 char *prefix;
3970 char line[LINESIZE];
3971 char pattern[LINESIZE];
3972 int i;
3973
3974 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3975 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00003976 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00003977 if( in ){
3978 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
3979 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3980 if( strcmp(line,pattern) ) break;
3981 }
3982 fclose(in);
3983 if( i==lemp->nterminal ){
3984 /* No change in the file. Don't rewrite it. */
3985 return;
3986 }
3987 }
drh2aa6ca42004-09-10 00:14:04 +00003988 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00003989 if( out ){
3990 for(i=1; i<lemp->nterminal; i++){
3991 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3992 }
3993 fclose(out);
3994 }
3995 return;
3996}
3997
3998/* Reduce the size of the action tables, if possible, by making use
3999** of defaults.
4000**
drhb59499c2002-02-23 18:45:13 +00004001** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004002** it the default. Except, there is no default if the wildcard token
4003** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004004*/
4005void CompressTables(lemp)
4006struct lemon *lemp;
4007{
4008 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004009 struct action *ap, *ap2;
4010 struct rule *rp, *rp2, *rbest;
4011 int nbest, n;
drh75897232000-05-29 14:26:00 +00004012 int i;
drhe09daa92006-06-10 13:29:31 +00004013 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004014
4015 for(i=0; i<lemp->nstate; i++){
4016 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004017 nbest = 0;
4018 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004019 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004020
drhb59499c2002-02-23 18:45:13 +00004021 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004022 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4023 usesWildcard = 1;
4024 }
drhb59499c2002-02-23 18:45:13 +00004025 if( ap->type!=REDUCE ) continue;
4026 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004027 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004028 if( rp==rbest ) continue;
4029 n = 1;
4030 for(ap2=ap->next; ap2; ap2=ap2->next){
4031 if( ap2->type!=REDUCE ) continue;
4032 rp2 = ap2->x.rp;
4033 if( rp2==rbest ) continue;
4034 if( rp2==rp ) n++;
4035 }
4036 if( n>nbest ){
4037 nbest = n;
4038 rbest = rp;
drh75897232000-05-29 14:26:00 +00004039 }
4040 }
drhb59499c2002-02-23 18:45:13 +00004041
4042 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004043 ** is not at least 1 or if the wildcard token is a possible
4044 ** lookahead.
4045 */
4046 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004047
drhb59499c2002-02-23 18:45:13 +00004048
4049 /* Combine matching REDUCE actions into a single default */
4050 for(ap=stp->ap; ap; ap=ap->next){
4051 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4052 }
drh75897232000-05-29 14:26:00 +00004053 assert( ap );
4054 ap->sp = Symbol_new("{default}");
4055 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004056 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004057 }
4058 stp->ap = Action_sort(stp->ap);
4059 }
4060}
drhb59499c2002-02-23 18:45:13 +00004061
drhada354d2005-11-05 15:03:59 +00004062
4063/*
4064** Compare two states for sorting purposes. The smaller state is the
4065** one with the most non-terminal actions. If they have the same number
4066** of non-terminal actions, then the smaller is the one with the most
4067** token actions.
4068*/
4069static int stateResortCompare(const void *a, const void *b){
4070 const struct state *pA = *(const struct state**)a;
4071 const struct state *pB = *(const struct state**)b;
4072 int n;
4073
4074 n = pB->nNtAct - pA->nNtAct;
4075 if( n==0 ){
4076 n = pB->nTknAct - pA->nTknAct;
4077 }
4078 return n;
4079}
4080
4081
4082/*
4083** Renumber and resort states so that states with fewer choices
4084** occur at the end. Except, keep state 0 as the first state.
4085*/
4086void ResortStates(lemp)
4087struct lemon *lemp;
4088{
4089 int i;
4090 struct state *stp;
4091 struct action *ap;
4092
4093 for(i=0; i<lemp->nstate; i++){
4094 stp = lemp->sorted[i];
4095 stp->nTknAct = stp->nNtAct = 0;
4096 stp->iDflt = lemp->nstate + lemp->nrule;
4097 stp->iTknOfst = NO_OFFSET;
4098 stp->iNtOfst = NO_OFFSET;
4099 for(ap=stp->ap; ap; ap=ap->next){
4100 if( compute_action(lemp,ap)>=0 ){
4101 if( ap->sp->index<lemp->nterminal ){
4102 stp->nTknAct++;
4103 }else if( ap->sp->index<lemp->nsymbol ){
4104 stp->nNtAct++;
4105 }else{
4106 stp->iDflt = compute_action(lemp, ap);
4107 }
4108 }
4109 }
4110 }
4111 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4112 stateResortCompare);
4113 for(i=0; i<lemp->nstate; i++){
4114 lemp->sorted[i]->statenum = i;
4115 }
4116}
4117
4118
drh75897232000-05-29 14:26:00 +00004119/***************** From the file "set.c" ************************************/
4120/*
4121** Set manipulation routines for the LEMON parser generator.
4122*/
4123
4124static int size = 0;
4125
4126/* Set the set size */
4127void SetSize(n)
4128int n;
4129{
4130 size = n+1;
4131}
4132
4133/* Allocate a new set */
4134char *SetNew(){
4135 char *s;
drh9892c5d2007-12-21 00:02:11 +00004136 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004137 if( s==0 ){
4138 extern void memory_error();
4139 memory_error();
4140 }
drh75897232000-05-29 14:26:00 +00004141 return s;
4142}
4143
4144/* Deallocate a set */
4145void SetFree(s)
4146char *s;
4147{
4148 free(s);
4149}
4150
4151/* Add a new element to the set. Return TRUE if the element was added
4152** and FALSE if it was already there. */
4153int SetAdd(s,e)
4154char *s;
4155int e;
4156{
4157 int rv;
drh9892c5d2007-12-21 00:02:11 +00004158 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004159 rv = s[e];
4160 s[e] = 1;
4161 return !rv;
4162}
4163
4164/* Add every element of s2 to s1. Return TRUE if s1 changes. */
4165int SetUnion(s1,s2)
4166char *s1;
4167char *s2;
4168{
4169 int i, progress;
4170 progress = 0;
4171 for(i=0; i<size; i++){
4172 if( s2[i]==0 ) continue;
4173 if( s1[i]==0 ){
4174 progress = 1;
4175 s1[i] = 1;
4176 }
4177 }
4178 return progress;
4179}
4180/********************** From the file "table.c" ****************************/
4181/*
4182** All code in this file has been automatically generated
4183** from a specification in the file
4184** "table.q"
4185** by the associative array code building program "aagen".
4186** Do not edit this file! Instead, edit the specification
4187** file, then rerun aagen.
4188*/
4189/*
4190** Code for processing tables in the LEMON parser generator.
4191*/
4192
4193PRIVATE int strhash(x)
4194char *x;
4195{
4196 int h = 0;
4197 while( *x) h = h*13 + *(x++);
4198 return h;
4199}
4200
4201/* Works like strdup, sort of. Save a string in malloced memory, but
4202** keep strings in a table so that the same string is not in more
4203** than one place.
4204*/
4205char *Strsafe(y)
4206char *y;
4207{
4208 char *z;
4209
drh916f75f2006-07-17 00:19:39 +00004210 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004211 z = Strsafe_find(y);
4212 if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){
4213 strcpy(z,y);
4214 Strsafe_insert(z);
4215 }
4216 MemoryCheck(z);
4217 return z;
4218}
4219
4220/* There is one instance of the following structure for each
4221** associative array of type "x1".
4222*/
4223struct s_x1 {
4224 int size; /* The number of available slots. */
4225 /* Must be a power of 2 greater than or */
4226 /* equal to 1 */
4227 int count; /* Number of currently slots filled */
4228 struct s_x1node *tbl; /* The data stored here */
4229 struct s_x1node **ht; /* Hash table for lookups */
4230};
4231
4232/* There is one instance of this structure for every data element
4233** in an associative array of type "x1".
4234*/
4235typedef struct s_x1node {
4236 char *data; /* The data */
4237 struct s_x1node *next; /* Next entry with the same hash */
4238 struct s_x1node **from; /* Previous link */
4239} x1node;
4240
4241/* There is only one instance of the array, which is the following */
4242static struct s_x1 *x1a;
4243
4244/* Allocate a new associative array */
4245void Strsafe_init(){
4246 if( x1a ) return;
4247 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4248 if( x1a ){
4249 x1a->size = 1024;
4250 x1a->count = 0;
4251 x1a->tbl = (x1node*)malloc(
4252 (sizeof(x1node) + sizeof(x1node*))*1024 );
4253 if( x1a->tbl==0 ){
4254 free(x1a);
4255 x1a = 0;
4256 }else{
4257 int i;
4258 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4259 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4260 }
4261 }
4262}
4263/* Insert a new record into the array. Return TRUE if successful.
4264** Prior data with the same key is NOT overwritten */
4265int Strsafe_insert(data)
4266char *data;
4267{
4268 x1node *np;
4269 int h;
4270 int ph;
4271
4272 if( x1a==0 ) return 0;
4273 ph = strhash(data);
4274 h = ph & (x1a->size-1);
4275 np = x1a->ht[h];
4276 while( np ){
4277 if( strcmp(np->data,data)==0 ){
4278 /* An existing entry with the same key is found. */
4279 /* Fail because overwrite is not allows. */
4280 return 0;
4281 }
4282 np = np->next;
4283 }
4284 if( x1a->count>=x1a->size ){
4285 /* Need to make the hash table bigger */
4286 int i,size;
4287 struct s_x1 array;
4288 array.size = size = x1a->size*2;
4289 array.count = x1a->count;
4290 array.tbl = (x1node*)malloc(
4291 (sizeof(x1node) + sizeof(x1node*))*size );
4292 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4293 array.ht = (x1node**)&(array.tbl[size]);
4294 for(i=0; i<size; i++) array.ht[i] = 0;
4295 for(i=0; i<x1a->count; i++){
4296 x1node *oldnp, *newnp;
4297 oldnp = &(x1a->tbl[i]);
4298 h = strhash(oldnp->data) & (size-1);
4299 newnp = &(array.tbl[i]);
4300 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4301 newnp->next = array.ht[h];
4302 newnp->data = oldnp->data;
4303 newnp->from = &(array.ht[h]);
4304 array.ht[h] = newnp;
4305 }
4306 free(x1a->tbl);
4307 *x1a = array;
4308 }
4309 /* Insert the new data */
4310 h = ph & (x1a->size-1);
4311 np = &(x1a->tbl[x1a->count++]);
4312 np->data = data;
4313 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4314 np->next = x1a->ht[h];
4315 x1a->ht[h] = np;
4316 np->from = &(x1a->ht[h]);
4317 return 1;
4318}
4319
4320/* Return a pointer to data assigned to the given key. Return NULL
4321** if no such key. */
4322char *Strsafe_find(key)
4323char *key;
4324{
4325 int h;
4326 x1node *np;
4327
4328 if( x1a==0 ) return 0;
4329 h = strhash(key) & (x1a->size-1);
4330 np = x1a->ht[h];
4331 while( np ){
4332 if( strcmp(np->data,key)==0 ) break;
4333 np = np->next;
4334 }
4335 return np ? np->data : 0;
4336}
4337
4338/* Return a pointer to the (terminal or nonterminal) symbol "x".
4339** Create a new symbol if this is the first time "x" has been seen.
4340*/
4341struct symbol *Symbol_new(x)
4342char *x;
4343{
4344 struct symbol *sp;
4345
4346 sp = Symbol_find(x);
4347 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004348 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004349 MemoryCheck(sp);
4350 sp->name = Strsafe(x);
4351 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4352 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004353 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004354 sp->prec = -1;
4355 sp->assoc = UNK;
4356 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004357 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004358 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004359 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004360 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004361 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004362 Symbol_insert(sp,sp->name);
4363 }
drhc4dd3fd2008-01-22 01:48:05 +00004364 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004365 return sp;
4366}
4367
drh60d31652004-02-22 00:08:04 +00004368/* Compare two symbols for working purposes
4369**
4370** Symbols that begin with upper case letters (terminals or tokens)
4371** must sort before symbols that begin with lower case letters
4372** (non-terminals). Other than that, the order does not matter.
4373**
4374** We find experimentally that leaving the symbols in their original
4375** order (the order they appeared in the grammar file) gives the
4376** smallest parser tables in SQLite.
4377*/
4378int Symbolcmpp(struct symbol **a, struct symbol **b){
4379 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4380 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
4381 return i1-i2;
drh75897232000-05-29 14:26:00 +00004382}
4383
4384/* There is one instance of the following structure for each
4385** associative array of type "x2".
4386*/
4387struct s_x2 {
4388 int size; /* The number of available slots. */
4389 /* Must be a power of 2 greater than or */
4390 /* equal to 1 */
4391 int count; /* Number of currently slots filled */
4392 struct s_x2node *tbl; /* The data stored here */
4393 struct s_x2node **ht; /* Hash table for lookups */
4394};
4395
4396/* There is one instance of this structure for every data element
4397** in an associative array of type "x2".
4398*/
4399typedef struct s_x2node {
4400 struct symbol *data; /* The data */
4401 char *key; /* The key */
4402 struct s_x2node *next; /* Next entry with the same hash */
4403 struct s_x2node **from; /* Previous link */
4404} x2node;
4405
4406/* There is only one instance of the array, which is the following */
4407static struct s_x2 *x2a;
4408
4409/* Allocate a new associative array */
4410void Symbol_init(){
4411 if( x2a ) return;
4412 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4413 if( x2a ){
4414 x2a->size = 128;
4415 x2a->count = 0;
4416 x2a->tbl = (x2node*)malloc(
4417 (sizeof(x2node) + sizeof(x2node*))*128 );
4418 if( x2a->tbl==0 ){
4419 free(x2a);
4420 x2a = 0;
4421 }else{
4422 int i;
4423 x2a->ht = (x2node**)&(x2a->tbl[128]);
4424 for(i=0; i<128; i++) x2a->ht[i] = 0;
4425 }
4426 }
4427}
4428/* Insert a new record into the array. Return TRUE if successful.
4429** Prior data with the same key is NOT overwritten */
4430int Symbol_insert(data,key)
4431struct symbol *data;
4432char *key;
4433{
4434 x2node *np;
4435 int h;
4436 int ph;
4437
4438 if( x2a==0 ) return 0;
4439 ph = strhash(key);
4440 h = ph & (x2a->size-1);
4441 np = x2a->ht[h];
4442 while( np ){
4443 if( strcmp(np->key,key)==0 ){
4444 /* An existing entry with the same key is found. */
4445 /* Fail because overwrite is not allows. */
4446 return 0;
4447 }
4448 np = np->next;
4449 }
4450 if( x2a->count>=x2a->size ){
4451 /* Need to make the hash table bigger */
4452 int i,size;
4453 struct s_x2 array;
4454 array.size = size = x2a->size*2;
4455 array.count = x2a->count;
4456 array.tbl = (x2node*)malloc(
4457 (sizeof(x2node) + sizeof(x2node*))*size );
4458 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4459 array.ht = (x2node**)&(array.tbl[size]);
4460 for(i=0; i<size; i++) array.ht[i] = 0;
4461 for(i=0; i<x2a->count; i++){
4462 x2node *oldnp, *newnp;
4463 oldnp = &(x2a->tbl[i]);
4464 h = strhash(oldnp->key) & (size-1);
4465 newnp = &(array.tbl[i]);
4466 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4467 newnp->next = array.ht[h];
4468 newnp->key = oldnp->key;
4469 newnp->data = oldnp->data;
4470 newnp->from = &(array.ht[h]);
4471 array.ht[h] = newnp;
4472 }
4473 free(x2a->tbl);
4474 *x2a = array;
4475 }
4476 /* Insert the new data */
4477 h = ph & (x2a->size-1);
4478 np = &(x2a->tbl[x2a->count++]);
4479 np->key = key;
4480 np->data = data;
4481 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4482 np->next = x2a->ht[h];
4483 x2a->ht[h] = np;
4484 np->from = &(x2a->ht[h]);
4485 return 1;
4486}
4487
4488/* Return a pointer to data assigned to the given key. Return NULL
4489** if no such key. */
4490struct symbol *Symbol_find(key)
4491char *key;
4492{
4493 int h;
4494 x2node *np;
4495
4496 if( x2a==0 ) return 0;
4497 h = strhash(key) & (x2a->size-1);
4498 np = x2a->ht[h];
4499 while( np ){
4500 if( strcmp(np->key,key)==0 ) break;
4501 np = np->next;
4502 }
4503 return np ? np->data : 0;
4504}
4505
4506/* Return the n-th data. Return NULL if n is out of range. */
4507struct symbol *Symbol_Nth(n)
4508int n;
4509{
4510 struct symbol *data;
4511 if( x2a && n>0 && n<=x2a->count ){
4512 data = x2a->tbl[n-1].data;
4513 }else{
4514 data = 0;
4515 }
4516 return data;
4517}
4518
4519/* Return the size of the array */
4520int Symbol_count()
4521{
4522 return x2a ? x2a->count : 0;
4523}
4524
4525/* Return an array of pointers to all data in the table.
4526** The array is obtained from malloc. Return NULL if memory allocation
4527** problems, or if the array is empty. */
4528struct symbol **Symbol_arrayof()
4529{
4530 struct symbol **array;
4531 int i,size;
4532 if( x2a==0 ) return 0;
4533 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004534 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004535 if( array ){
4536 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4537 }
4538 return array;
4539}
4540
4541/* Compare two configurations */
4542int Configcmp(a,b)
4543struct config *a;
4544struct config *b;
4545{
4546 int x;
4547 x = a->rp->index - b->rp->index;
4548 if( x==0 ) x = a->dot - b->dot;
4549 return x;
4550}
4551
4552/* Compare two states */
4553PRIVATE int statecmp(a,b)
4554struct config *a;
4555struct config *b;
4556{
4557 int rc;
4558 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4559 rc = a->rp->index - b->rp->index;
4560 if( rc==0 ) rc = a->dot - b->dot;
4561 }
4562 if( rc==0 ){
4563 if( a ) rc = 1;
4564 if( b ) rc = -1;
4565 }
4566 return rc;
4567}
4568
4569/* Hash a state */
4570PRIVATE int statehash(a)
4571struct config *a;
4572{
4573 int h=0;
4574 while( a ){
4575 h = h*571 + a->rp->index*37 + a->dot;
4576 a = a->bp;
4577 }
4578 return h;
4579}
4580
4581/* Allocate a new state structure */
4582struct state *State_new()
4583{
4584 struct state *new;
drh9892c5d2007-12-21 00:02:11 +00004585 new = (struct state *)calloc(1, sizeof(struct state) );
drh75897232000-05-29 14:26:00 +00004586 MemoryCheck(new);
4587 return new;
4588}
4589
4590/* There is one instance of the following structure for each
4591** associative array of type "x3".
4592*/
4593struct s_x3 {
4594 int size; /* The number of available slots. */
4595 /* Must be a power of 2 greater than or */
4596 /* equal to 1 */
4597 int count; /* Number of currently slots filled */
4598 struct s_x3node *tbl; /* The data stored here */
4599 struct s_x3node **ht; /* Hash table for lookups */
4600};
4601
4602/* There is one instance of this structure for every data element
4603** in an associative array of type "x3".
4604*/
4605typedef struct s_x3node {
4606 struct state *data; /* The data */
4607 struct config *key; /* The key */
4608 struct s_x3node *next; /* Next entry with the same hash */
4609 struct s_x3node **from; /* Previous link */
4610} x3node;
4611
4612/* There is only one instance of the array, which is the following */
4613static struct s_x3 *x3a;
4614
4615/* Allocate a new associative array */
4616void State_init(){
4617 if( x3a ) return;
4618 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4619 if( x3a ){
4620 x3a->size = 128;
4621 x3a->count = 0;
4622 x3a->tbl = (x3node*)malloc(
4623 (sizeof(x3node) + sizeof(x3node*))*128 );
4624 if( x3a->tbl==0 ){
4625 free(x3a);
4626 x3a = 0;
4627 }else{
4628 int i;
4629 x3a->ht = (x3node**)&(x3a->tbl[128]);
4630 for(i=0; i<128; i++) x3a->ht[i] = 0;
4631 }
4632 }
4633}
4634/* Insert a new record into the array. Return TRUE if successful.
4635** Prior data with the same key is NOT overwritten */
4636int State_insert(data,key)
4637struct state *data;
4638struct config *key;
4639{
4640 x3node *np;
4641 int h;
4642 int ph;
4643
4644 if( x3a==0 ) return 0;
4645 ph = statehash(key);
4646 h = ph & (x3a->size-1);
4647 np = x3a->ht[h];
4648 while( np ){
4649 if( statecmp(np->key,key)==0 ){
4650 /* An existing entry with the same key is found. */
4651 /* Fail because overwrite is not allows. */
4652 return 0;
4653 }
4654 np = np->next;
4655 }
4656 if( x3a->count>=x3a->size ){
4657 /* Need to make the hash table bigger */
4658 int i,size;
4659 struct s_x3 array;
4660 array.size = size = x3a->size*2;
4661 array.count = x3a->count;
4662 array.tbl = (x3node*)malloc(
4663 (sizeof(x3node) + sizeof(x3node*))*size );
4664 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4665 array.ht = (x3node**)&(array.tbl[size]);
4666 for(i=0; i<size; i++) array.ht[i] = 0;
4667 for(i=0; i<x3a->count; i++){
4668 x3node *oldnp, *newnp;
4669 oldnp = &(x3a->tbl[i]);
4670 h = statehash(oldnp->key) & (size-1);
4671 newnp = &(array.tbl[i]);
4672 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4673 newnp->next = array.ht[h];
4674 newnp->key = oldnp->key;
4675 newnp->data = oldnp->data;
4676 newnp->from = &(array.ht[h]);
4677 array.ht[h] = newnp;
4678 }
4679 free(x3a->tbl);
4680 *x3a = array;
4681 }
4682 /* Insert the new data */
4683 h = ph & (x3a->size-1);
4684 np = &(x3a->tbl[x3a->count++]);
4685 np->key = key;
4686 np->data = data;
4687 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4688 np->next = x3a->ht[h];
4689 x3a->ht[h] = np;
4690 np->from = &(x3a->ht[h]);
4691 return 1;
4692}
4693
4694/* Return a pointer to data assigned to the given key. Return NULL
4695** if no such key. */
4696struct state *State_find(key)
4697struct config *key;
4698{
4699 int h;
4700 x3node *np;
4701
4702 if( x3a==0 ) return 0;
4703 h = statehash(key) & (x3a->size-1);
4704 np = x3a->ht[h];
4705 while( np ){
4706 if( statecmp(np->key,key)==0 ) break;
4707 np = np->next;
4708 }
4709 return np ? np->data : 0;
4710}
4711
4712/* Return an array of pointers to all data in the table.
4713** The array is obtained from malloc. Return NULL if memory allocation
4714** problems, or if the array is empty. */
4715struct state **State_arrayof()
4716{
4717 struct state **array;
4718 int i,size;
4719 if( x3a==0 ) return 0;
4720 size = x3a->count;
4721 array = (struct state **)malloc( sizeof(struct state *)*size );
4722 if( array ){
4723 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4724 }
4725 return array;
4726}
4727
4728/* Hash a configuration */
4729PRIVATE int confighash(a)
4730struct config *a;
4731{
4732 int h=0;
4733 h = h*571 + a->rp->index*37 + a->dot;
4734 return h;
4735}
4736
4737/* There is one instance of the following structure for each
4738** associative array of type "x4".
4739*/
4740struct s_x4 {
4741 int size; /* The number of available slots. */
4742 /* Must be a power of 2 greater than or */
4743 /* equal to 1 */
4744 int count; /* Number of currently slots filled */
4745 struct s_x4node *tbl; /* The data stored here */
4746 struct s_x4node **ht; /* Hash table for lookups */
4747};
4748
4749/* There is one instance of this structure for every data element
4750** in an associative array of type "x4".
4751*/
4752typedef struct s_x4node {
4753 struct config *data; /* The data */
4754 struct s_x4node *next; /* Next entry with the same hash */
4755 struct s_x4node **from; /* Previous link */
4756} x4node;
4757
4758/* There is only one instance of the array, which is the following */
4759static struct s_x4 *x4a;
4760
4761/* Allocate a new associative array */
4762void Configtable_init(){
4763 if( x4a ) return;
4764 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4765 if( x4a ){
4766 x4a->size = 64;
4767 x4a->count = 0;
4768 x4a->tbl = (x4node*)malloc(
4769 (sizeof(x4node) + sizeof(x4node*))*64 );
4770 if( x4a->tbl==0 ){
4771 free(x4a);
4772 x4a = 0;
4773 }else{
4774 int i;
4775 x4a->ht = (x4node**)&(x4a->tbl[64]);
4776 for(i=0; i<64; i++) x4a->ht[i] = 0;
4777 }
4778 }
4779}
4780/* Insert a new record into the array. Return TRUE if successful.
4781** Prior data with the same key is NOT overwritten */
4782int Configtable_insert(data)
4783struct config *data;
4784{
4785 x4node *np;
4786 int h;
4787 int ph;
4788
4789 if( x4a==0 ) return 0;
4790 ph = confighash(data);
4791 h = ph & (x4a->size-1);
4792 np = x4a->ht[h];
4793 while( np ){
4794 if( Configcmp(np->data,data)==0 ){
4795 /* An existing entry with the same key is found. */
4796 /* Fail because overwrite is not allows. */
4797 return 0;
4798 }
4799 np = np->next;
4800 }
4801 if( x4a->count>=x4a->size ){
4802 /* Need to make the hash table bigger */
4803 int i,size;
4804 struct s_x4 array;
4805 array.size = size = x4a->size*2;
4806 array.count = x4a->count;
4807 array.tbl = (x4node*)malloc(
4808 (sizeof(x4node) + sizeof(x4node*))*size );
4809 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4810 array.ht = (x4node**)&(array.tbl[size]);
4811 for(i=0; i<size; i++) array.ht[i] = 0;
4812 for(i=0; i<x4a->count; i++){
4813 x4node *oldnp, *newnp;
4814 oldnp = &(x4a->tbl[i]);
4815 h = confighash(oldnp->data) & (size-1);
4816 newnp = &(array.tbl[i]);
4817 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4818 newnp->next = array.ht[h];
4819 newnp->data = oldnp->data;
4820 newnp->from = &(array.ht[h]);
4821 array.ht[h] = newnp;
4822 }
4823 free(x4a->tbl);
4824 *x4a = array;
4825 }
4826 /* Insert the new data */
4827 h = ph & (x4a->size-1);
4828 np = &(x4a->tbl[x4a->count++]);
4829 np->data = data;
4830 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4831 np->next = x4a->ht[h];
4832 x4a->ht[h] = np;
4833 np->from = &(x4a->ht[h]);
4834 return 1;
4835}
4836
4837/* Return a pointer to data assigned to the given key. Return NULL
4838** if no such key. */
4839struct config *Configtable_find(key)
4840struct config *key;
4841{
4842 int h;
4843 x4node *np;
4844
4845 if( x4a==0 ) return 0;
4846 h = confighash(key) & (x4a->size-1);
4847 np = x4a->ht[h];
4848 while( np ){
4849 if( Configcmp(np->data,key)==0 ) break;
4850 np = np->next;
4851 }
4852 return np ? np->data : 0;
4853}
4854
4855/* Remove all data from the table. Pass each data to the function "f"
4856** as it is removed. ("f" may be null to avoid this step.) */
4857void Configtable_clear(f)
4858int(*f)(/* struct config * */);
4859{
4860 int i;
4861 if( x4a==0 || x4a->count==0 ) return;
4862 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4863 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4864 x4a->count = 0;
4865 return;
4866}