Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/tool/lemon.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / tool / lemon.c` 6073 lines ยท 186820 bytes Raw Blame History 1 /* 2 ** This file contains all sources (including headers) to the LEMON 3 ** LALR(1) parser generator. The sources have been combined into a 4 ** single file to make it easy to include LEMON in the source tree 5 ** and Makefile of another program. 6 ** 7 ** The author of this program disclaims copyright. 8 */ 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 16 #define ISSPACE(X) isspace((unsigned char)(X)) 17 #define ISDIGIT(X) isdigit((unsigned char)(X)) 18 #define ISALNUM(X) isalnum((unsigned char)(X)) 19 #define ISALPHA(X) isalpha((unsigned char)(X)) 20 #define ISUPPER(X) isupper((unsigned char)(X)) 21 #define ISLOWER(X) islower((unsigned char)(X)) 22 23 24 #ifndef __WIN32__ 25 # if defined(_WIN32) || defined(WIN32) 26 # define __WIN32__ 27 # endif 28 #endif 29 30 #ifdef __WIN32__ 31 #ifdef __cplusplus 32 extern "C" { 33 #endif 34 extern int access(const char *path, int mode); 35 #ifdef __cplusplus 36 } 37 #endif 38 #else 39 #include 40 #endif 41 42 /* #define PRIVATE static */ 43 #define PRIVATE 44 45 #ifdef TEST 46 #define MAXRHS 5 /* Set low to exercise exception code */ 47 #else 48 #define MAXRHS 1000 49 #endif 50 51 extern void memory_error(); 52 static int showPrecedenceConflict = 0; 53 static char *msort(char*,char**,int(*)(const char*,const char*)); 54 55 /* 56 ** Compilers are getting increasingly pedantic about type conversions 57 ** as C evolves ever closer to Ada.... To work around the latest problems 58 ** we have to define the following variant of strlen(). 59 */ 60 #define lemonStrlen(X) ((int)strlen(X)) 61 62 /* 63 ** Header on the linked list of memory allocations. 64 */ 65 typedef struct MemChunk MemChunk; 66 struct MemChunk { 67 MemChunk *pNext; 68 size_t sz; 69 /* Actually memory follows */ 70 }; 71 72 /* 73 ** Global linked list of all memory allocations. 74 */ 75 static MemChunk *memChunkList = 0; 76 77 /* 78 ** Wrappers around malloc(), calloc(), realloc() and free(). 79 ** 80 ** All memory allocations are kept on a doubly-linked list. The 81 ** lemon_free_all() function can be called prior to exit to clean 82 ** up any memory leaks. 83 ** 84 ** This is not necessary. But compilers and getting increasingly 85 ** fussy about memory leaks, even in command-line programs like Lemon 86 ** where they do not matter. So this code is provided to hush the 87 ** warnings. 88 */ 89 static void *lemon_malloc(size_t nByte){ 90 MemChunk *p; 91 p = malloc( nByte + sizeof(MemChunk) ); 92 if( p==0 ){ 93 fprintf(stderr, "Out of memory. Failed to allocate %lld bytes.\n", 94 (long long int)nByte); 95 exit(1); 96 } 97 p->pNext = memChunkList; 98 p->sz = nByte; 99 memChunkList = p; 100 return (void*)&p[1]; 101 } 102 static void *lemon_calloc(size_t nElem, size_t sz){ 103 void *p = lemon_malloc(nElem*sz); 104 memset(p, 0, nElem*sz); 105 return p; 106 } 107 static void lemon_free(void *pOld){ 108 if( pOld ){ 109 MemChunk *p = (MemChunk*)pOld; 110 p--; 111 memset(pOld, 0, p->sz); 112 } 113 } 114 static void *lemon_realloc(void *pOld, size_t nNew){ 115 void *pNew; 116 MemChunk *p; 117 if( pOld==0 ) return lemon_malloc(nNew); 118 p = (MemChunk*)pOld; 119 p--; 120 if( p->sz>=nNew ) return pOld; 121 pNew = lemon_malloc( nNew ); 122 memcpy(pNew, pOld, p->sz); 123 return pNew; 124 } 125 126 /* Free all outstanding memory allocations. 127 ** Do this right before exiting. 128 */ 129 static void lemon_free_all(void){ 130 while( memChunkList ){ 131 MemChunk *pNext = memChunkList->pNext; 132 free( memChunkList ); 133 memChunkList = pNext; 134 } 135 } 136 137 /* 138 ** Compilers are starting to complain about the use of sprintf() and strcpy(), 139 ** saying they are unsafe. So we define our own versions of those routines too. 140 ** 141 ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and 142 ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf(). 143 ** The third is a helper routine for vsnprintf() that adds texts to the end of a 144 ** buffer, making sure the buffer is always zero-terminated. 145 ** 146 ** The string formatter is a minimal subset of stdlib sprintf() supporting only 147 ** a few simply conversions: 148 ** 149 ** %d 150 ** %s 151 ** %.*s 152 ** 153 */ 154 static void lemon_addtext( 155 char *zBuf, /* The buffer to which text is added */ 156 int *pnUsed, /* Slots of the buffer used so far */ 157 const char *zIn, /* Text to add */ 158 int nIn, /* Bytes of text to add. -1 to use strlen() */ 159 int iWidth /* Field width. Negative to left justify */ 160 ){ 161 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){} 162 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; } 163 if( nIn==0 ) return; 164 memcpy(&zBuf[*pnUsed], zIn, nIn); 165 *pnUsed += nIn; 166 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; } 167 zBuf[*pnUsed] = 0; 168 } 169 static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){ 170 int i, j, k, c; 171 int nUsed = 0; 172 const char *z; 173 char zTemp[50]; 174 str[0] = 0; 175 for(i=j=0; (c = zFormat[i])!=0; i++){ 176 if( c=='%' ){ 177 int iWidth = 0; 178 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0); 179 c = zFormat[++i]; 180 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){ 181 if( c=='-' ) i++; 182 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0'; 183 if( c=='-' ) iWidth = -iWidth; 184 c = zFormat[i]; 185 } 186 if( c=='d' ){ 187 int v = va_arg(ap, int); 188 if( v<0 ){ 189 lemon_addtext(str, &nUsed, "-", 1, iWidth); 190 v = -v; 191 }else if( v==0 ){ 192 lemon_addtext(str, &nUsed, "0", 1, iWidth); 193 } 194 k = 0; 195 while( v>0 ){ 196 k++; 197 zTemp[sizeof(zTemp)-k] = (v%10) + '0'; 198 v /= 10; 199 } 200 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth); 201 }else if( c=='s' ){ 202 z = va_arg(ap, const char*); 203 lemon_addtext(str, &nUsed, z, -1, iWidth); 204 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){ 205 i += 2; 206 k = va_arg(ap, int); 207 z = va_arg(ap, const char*); 208 lemon_addtext(str, &nUsed, z, k, iWidth); 209 }else if( c=='%' ){ 210 lemon_addtext(str, &nUsed, "%", 1, 0); 211 }else{ 212 fprintf(stderr, "illegal format\n"); 213 exit(1); 214 } 215 j = i+1; 216 } 217 } 218 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0); 219 return nUsed; 220 } 221 static int lemon_sprintf(char *str, const char *format, ...){ 222 va_list ap; 223 int rc; 224 va_start(ap, format); 225 rc = lemon_vsprintf(str, format, ap); 226 va_end(ap); 227 return rc; 228 } 229 static void lemon_strcpy(char *dest, const char *src){ 230 while( (*(dest++) = *(src++))!=0 ){} 231 } 232 static void lemon_strcat(char *dest, const char *src){ 233 while( *dest ) dest++; 234 lemon_strcpy(dest, src); 235 } 236 237 238 /* a few forward declarations... */ 239 struct rule; 240 struct lemon; 241 struct action; 242 243 static struct action *Action_new(void); 244 static struct action *Action_sort(struct action *); 245 246 /********** From the file "build.h" ************************************/ 247 void FindRulePrecedences(struct lemon*); 248 void FindFirstSets(struct lemon*); 249 void FindStates(struct lemon*); 250 void FindLinks(struct lemon*); 251 void FindFollowSets(struct lemon*); 252 void FindActions(struct lemon*); 253 254 /********* From the file "configlist.h" *********************************/ 255 void Configlist_init(void); 256 struct config *Configlist_add(struct rule *, int); 257 struct config *Configlist_addbasis(struct rule *, int); 258 void Configlist_closure(struct lemon *); 259 void Configlist_sort(void); 260 void Configlist_sortbasis(void); 261 struct config *Configlist_return(void); 262 struct config *Configlist_basis(void); 263 void Configlist_eat(struct config *); 264 void Configlist_reset(void); 265 266 /********* From the file "error.h" ***************************************/ 267 void ErrorMsg(const char *, int,const char *, ...); 268 269 /****** From the file "option.h" ******************************************/ 270 enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, 271 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR}; 272 struct s_options { 273 enum option_type type; 274 const char *label; 275 char *arg; 276 const char *message; 277 }; 278 int OptInit(char**,struct s_options*,FILE*); 279 int OptNArgs(void); 280 char *OptArg(int); 281 void OptErr(int); 282 void OptPrint(void); 283 284 /******** From the file "parse.h" *****************************************/ 285 void Parse(struct lemon *lemp); 286 287 /********* From the file "plink.h" ***************************************/ 288 struct plink *Plink_new(void); 289 void Plink_add(struct plink **, struct config *); 290 void Plink_copy(struct plink **, struct plink *); 291 void Plink_delete(struct plink *); 292 293 /********** From the file "report.h" *************************************/ 294 void Reprint(struct lemon *); 295 void ReportOutput(struct lemon *); 296 void ReportTable(struct lemon *, int, int); 297 void ReportHeader(struct lemon *); 298 void CompressTables(struct lemon *); 299 void ResortStates(struct lemon *); 300 301 /********** From the file "set.h" ****************************************/ 302 void SetSize(int); /* All sets will be of size N */ 303 char *SetNew(void); /* A new set for element 0..N */ 304 void SetFree(char*); /* Deallocate a set */ 305 int SetAdd(char*,int); /* Add element to a set */ 306 int SetUnion(char *,char *); /* A <- A U B, thru element N */ 307 #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */ 308 309 /********** From the file "struct.h" *************************************/ 310 /* 311 ** Principal data structures for the LEMON parser generator. 312 */ 313 314 typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean; 315 316 /* Symbols (terminals and nonterminals) of the grammar are stored 317 ** in the following: */ 318 enum symbol_type { 319 TERMINAL, 320 NONTERMINAL, 321 MULTITERMINAL 322 }; 323 enum e_assoc { 324 LEFT, 325 RIGHT, 326 NONE, 327 UNK 328 }; 329 struct symbol { 330 const char *name; /* Name of the symbol */ 331 int index; /* Index number for this symbol */ 332 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */ 333 struct rule *rule; /* Linked list of rules of this (if an NT) */ 334 struct symbol *fallback; /* fallback token in case this token doesn't parse */ 335 int prec; /* Precedence if defined (-1 otherwise) */ 336 enum e_assoc assoc; /* Associativity if precedence is defined */ 337 char *firstset; /* First-set for all rules of this symbol */ 338 Boolean lambda; /* True if NT and can generate an empty string */ 339 int useCnt; /* Number of times used */ 340 char *destructor; /* Code which executes whenever this symbol is 341 ** popped from the stack during error processing */ 342 int destLineno; /* Line number for start of destructor. Set to 343 ** -1 for duplicate destructors. */ 344 char *datatype; /* The data type of information held by this 345 ** object. Only used if type==NONTERMINAL */ 346 int dtnum; /* The data type number. In the parser, the value 347 ** stack is a union. The .yy%d element of this 348 ** union is the correct data type for this object */ 349 int bContent; /* True if this symbol ever carries content - if 350 ** it is ever more than just syntax */ 351 /* The following fields are used by MULTITERMINALs only */ 352 int nsubsym; /* Number of constituent symbols in the MULTI */ 353 struct symbol **subsym; /* Array of constituent symbols */ 354 }; 355 356 /* Each production rule in the grammar is stored in the following 357 ** structure. */ 358 struct rule { 359 struct symbol *lhs; /* Left-hand side of the rule */ 360 const char *lhsalias; /* Alias for the LHS (NULL if none) */ 361 int lhsStart; /* True if left-hand side is the start symbol */ 362 int ruleline; /* Line number for the rule */ 363 int nrhs; /* Number of RHS symbols */ 364 struct symbol **rhs; /* The RHS symbols */ 365 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ 366 int line; /* Line number at which code begins */ 367 const char *code; /* The code executed when this rule is reduced */ 368 const char *codePrefix; /* Setup code before code[] above */ 369 const char *codeSuffix; /* Breakdown code after code[] above */ 370 struct symbol *precsym; /* Precedence symbol for this rule */ 371 int index; /* An index number for this rule */ 372 int iRule; /* Rule number as used in the generated tables */ 373 Boolean noCode; /* True if this rule has no associated C code */ 374 Boolean codeEmitted; /* True if the code has been emitted already */ 375 Boolean canReduce; /* True if this rule is ever reduced */ 376 Boolean doesReduce; /* Reduce actions occur after optimization */ 377 Boolean neverReduce; /* Reduce is theoretically possible, but prevented 378 ** by actions or other outside implementation */ 379 struct rule *nextlhs; /* Next rule with the same LHS */ 380 struct rule *next; /* Next rule in the global list */ 381 }; 382 383 /* A configuration is a production rule of the grammar together with 384 ** a mark (dot) showing how much of that rule has been processed so far. 385 ** Configurations also contain a follow-set which is a list of terminal 386 ** symbols which are allowed to immediately follow the end of the rule. 387 ** Every configuration is recorded as an instance of the following: */ 388 enum cfgstatus { 389 COMPLETE, 390 INCOMPLETE 391 }; 392 struct config { 393 struct rule *rp; /* The rule upon which the configuration is based */ 394 int dot; /* The parse point */ 395 char *fws; /* Follow-set for this configuration only */ 396 struct plink *fplp; /* Follow-set forward propagation links */ 397 struct plink *bplp; /* Follow-set backwards propagation links */ 398 struct state *stp; /* Pointer to state which contains this */ 399 enum cfgstatus status; /* used during followset and shift computations */ 400 struct config *next; /* Next configuration in the state */ 401 struct config *bp; /* The next basis configuration */ 402 }; 403 404 enum e_action { 405 SHIFT, 406 ACCEPT, 407 REDUCE, 408 ERROR, 409 SSCONFLICT, /* A shift/shift conflict */ 410 SRCONFLICT, /* Was a reduce, but part of a conflict */ 411 RRCONFLICT, /* Was a reduce, but part of a conflict */ 412 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */ 413 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */ 414 NOT_USED, /* Deleted by compression */ 415 SHIFTREDUCE /* Shift first, then reduce */ 416 }; 417 418 /* Every shift or reduce operation is stored as one of the following */ 419 struct action { 420 struct symbol *sp; /* The look-ahead symbol */ 421 enum e_action type; 422 union { 423 struct state *stp; /* The new state, if a shift */ 424 struct rule *rp; /* The rule, if a reduce */ 425 } x; 426 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */ 427 struct action *next; /* Next action for this state */ 428 struct action *collide; /* Next action with the same hash */ 429 }; 430 431 /* Each state of the generated parser's finite state machine 432 ** is encoded as an instance of the following structure. */ 433 struct state { 434 struct config *bp; /* The basis configurations for this state */ 435 struct config *cfp; /* All configurations in this set */ 436 int statenum; /* Sequential number for this state */ 437 struct action *ap; /* List of actions for this state */ 438 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */ 439 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */ 440 int iDfltReduce; /* Default action is to REDUCE by this rule */ 441 struct rule *pDfltReduce;/* The default REDUCE rule. */ 442 int autoReduce; /* True if this is an auto-reduce state */ 443 }; 444 #define NO_OFFSET (-`2147483647`) 445 446 /* A followset propagation link indicates that the contents of one 447 ** configuration followset should be propagated to another whenever 448 ** the first changes. */ 449 struct plink { 450 struct config *cfp; /* The configuration to which linked */ 451 struct plink *next; /* The next propagate link */ 452 }; 453 454 /* The state vector for the entire parser generator is recorded as 455 ** follows. (LEMON uses no global variables and makes little use of 456 ** static variables. Fields in the following structure can be thought 457 ** of as begin global variables in the program.) */ 458 struct lemon { 459 struct state **sorted; /* Table of states sorted by state number */ 460 struct rule *rule; /* List of all rules */ 461 struct rule *startRule; /* First rule */ 462 int nstate; /* Number of states */ 463 int nxstate; /* nstate with tail degenerate states removed */ 464 int nrule; /* Number of rules */ 465 int nruleWithAction; /* Number of rules with actions */ 466 int nsymbol; /* Number of terminal and nonterminal symbols */ 467 int nterminal; /* Number of terminal symbols */ 468 int minShiftReduce; /* Minimum shift-reduce action value */ 469 int errAction; /* Error action value */ 470 int accAction; /* Accept action value */ 471 int noAction; /* No-op action value */ 472 int minReduce; /* Minimum reduce action */ 473 int maxAction; /* Maximum action value of any kind */ 474 struct symbol **symbols; /* Sorted array of pointers to symbols */ 475 int errorcnt; /* Number of errors */ 476 struct symbol *errsym; /* The error symbol */ 477 struct symbol *wildcard; /* Token that matches anything */ 478 char *name; /* Name of the generated parser */ 479 char *arg; /* Declaration of the 3rd argument to parser */ 480 char *ctx; /* Declaration of 2nd argument to constructor */ 481 char *tokentype; /* Type of terminal symbols in the parser stack */ 482 char *vartype; /* The default type of non-terminal symbols */ 483 char *start; /* Name of the start symbol for the grammar */ 484 char *stacksize; /* Size of the parser stack */ 485 char *include; /* Code to put at the start of the C file */ 486 char *error; /* Code to execute when an error is seen */ 487 char *overflow; /* Code to execute on a stack overflow */ 488 char *failure; /* Code to execute on parser failure */ 489 char *accept; /* Code to execute when the parser excepts */ 490 char *extracode; /* Code appended to the generated file */ 491 char *tokendest; /* Code to execute to destroy token data */ 492 char *vardest; /* Code for the default non-terminal destructor */ 493 char *filename; /* Name of the input file */ 494 char *outname; /* Name of the current output file */ 495 char *tokenprefix; /* A prefix added to token names in the .h file */ 496 char *stackSizeLimit; /* Function to return the stack size limit */ 497 char *reallocFunc; /* Function to use to allocate stack space */ 498 char *freeFunc; /* Function to use to free stack space */ 499 int nconflict; /* Number of parsing conflicts */ 500 int nactiontab; /* Number of entries in the yy_action[] table */ 501 int nlookaheadtab; /* Number of entries in yy_lookahead[] */ 502 int tablesize; /* Total table size of all tables in bytes */ 503 int basisflag; /* Print only basis configurations */ 504 int printPreprocessed; /* Show preprocessor output on stdout */ 505 int has_fallback; /* True if any %fallback is seen in the grammar */ 506 int nolinenosflag; /* True if #line statements should not be printed */ 507 int argc; /* Number of command-line arguments */ 508 char **argv; /* Command-line arguments */ 509 }; 510 511 #define MemoryCheck(X) if((X)==0){ \ 512 extern void memory_error(); \ 513 memory_error(); \ 514 } 515 516 /**************** From the file "table.h" *********************************/ 517 /* 518 ** All code in this file has been automatically generated 519 ** from a specification in the file 520 ** "table.q" 521 ** by the associative array code building program "aagen". 522 ** Do not edit this file! Instead, edit the specification 523 ** file, then rerun aagen. 524 */ 525 /* 526 ** Code for processing tables in the LEMON parser generator. 527 */ 528 /* Routines for handling a strings */ 529 530 const char *Strsafe(const char *); 531 532 void Strsafe_init(void); 533 int Strsafe_insert(const char *); 534 const char *Strsafe_find(const char *); 535 536 /* Routines for handling symbols of the grammar */ 537 538 struct symbol *Symbol_new(const char *); 539 int Symbolcmpp(const void *, const void *); 540 void Symbol_init(void); 541 int Symbol_insert(struct symbol *, const char *); 542 struct symbol *Symbol_find(const char *); 543 struct symbol *Symbol_Nth(int); 544 int Symbol_count(void); 545 struct symbol **Symbol_arrayof(void); 546 547 /* Routines to manage the state table */ 548 549 int Configcmp(const char *, const char *); 550 struct state *State_new(void); 551 void State_init(void); 552 int State_insert(struct state *, struct config *); 553 struct state *State_find(struct config *); 554 struct state **State_arrayof(void); 555 556 /* Routines used for efficiency in Configlist_add */ 557 558 void Configtable_init(void); 559 int Configtable_insert(struct config *); 560 struct config *Configtable_find(struct config *); 561 void Configtable_clear(int(*)(struct config *)); 562 563 /****************** From the file "action.c" *******************************/ 564 /* 565 ** Routines processing parser actions in the LEMON parser generator. 566 */ 567 568 /* Allocate a new parser action */ 569 static struct action *Action_new(void){ 570 static struct action *actionfreelist = 0; 571 struct action *newaction; 572 573 if( actionfreelist==0 ){ 574 int i; 575 int amt = 100; 576 actionfreelist = (struct action *)lemon_calloc(amt, sizeof(struct action)); 577 if( actionfreelist==0 ){ 578 fprintf(stderr,"Unable to allocate memory for a new parser action."); 579 exit(1); 580 } 581 for(i=0; inext; 586 return newaction; 587 } 588 589 /* Compare two actions for sorting purposes. Return negative, zero, or 590 ** positive if the first action is less than, equal to, or greater than 591 ** the first 592 */ 593 static int actioncmp( 594 struct action *ap1, 595 struct action *ap2 596 ){ 597 int rc; 598 rc = ap1->sp->index - ap2->sp->index; 599 if( rc==0 ){ 600 rc = (int)ap1->type - (int)ap2->type; 601 } 602 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){ 603 rc = ap1->x.rp->index - ap2->x.rp->index; 604 } 605 if( rc==0 ){ 606 rc = (int) (ap2 - ap1); 607 } 608 return rc; 609 } 610 611 /* Sort parser actions */ 612 static struct action *Action_sort( 613 struct action *ap 614 ){ 615 ap = (struct action *)msort((char *)ap,(char **)&ap->next, 616 (int(*)(const char*,const char*))actioncmp); 617 return ap; 618 } 619 620 void Action_add( 621 struct action **app, 622 enum e_action type, 623 struct symbol *sp, 624 char *arg 625 ){ 626 struct action *newaction; 627 newaction = Action_new(); 628 newaction->next = *app; 629 *app = newaction; 630 newaction->type = type; 631 newaction->sp = sp; 632 newaction->spOpt = 0; 633 if( type==SHIFT ){ 634 newaction->x.stp = (struct state *)arg; 635 }else{ 636 newaction->x.rp = (struct rule *)arg; 637 } 638 } 639 /********************** New code to implement the "acttab" module ***********/ 640 /* 641 ** This module implements routines use to construct the yy_action[] table. 642 */ 643 644 /* 645 ** The state of the yy_action table under construction is an instance of 646 ** the following structure. 647 ** 648 ** The yy_action table maps the pair (state_number, lookahead) into an 649 ** action_number. The table is an array of integers pairs. The state_number 650 ** determines an initial offset into the yy_action array. The lookahead 651 ** value is then added to this initial offset to get an index X into the 652 ** yy_action array. If the aAction[X].lookahead equals the value of the 653 ** of the lookahead input, then the value of the action_number output is 654 ** aAction[X].action. If the lookaheads do not match then the 655 ** default action for the state_number is returned. 656 ** 657 ** All actions associated with a single state_number are first entered 658 ** into aLookahead[] using multiple calls to acttab_action(). Then the 659 ** actions for that single state_number are placed into the aAction[] 660 ** array with a single call to acttab_insert(). The acttab_insert() call 661 ** also resets the aLookahead[] array in preparation for the next 662 ** state number. 663 */ 664 struct lookahead_action { 665 int lookahead; /* Value of the lookahead token */ 666 int action; /* Action to take on the given lookahead */ 667 }; 668 typedef struct acttab acttab; 669 struct acttab { 670 int nAction; /* Number of used slots in aAction[] */ 671 int nActionAlloc; /* Slots allocated for aAction[] */ 672 struct lookahead_action 673 *aAction, /* The yy_action[] table under construction */ 674 *aLookahead; /* A single new transaction set */ 675 int mnLookahead; /* Minimum aLookahead[].lookahead */ 676 int mnAction; /* Action associated with mnLookahead */ 677 int mxLookahead; /* Maximum aLookahead[].lookahead */ 678 int nLookahead; /* Used slots in aLookahead[] */ 679 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */ 680 int nterminal; /* Number of terminal symbols */ 681 int nsymbol; /* total number of symbols */ 682 }; 683 684 /* Return the number of entries in the yy_action table */ 685 #define acttab_lookahead_size(X) ((X)->nAction) 686 687 /* The value for the N-th entry in yy_action */ 688 #define acttab_yyaction(X,N) ((X)->aAction[N].action) 689 690 /* The value for the N-th entry in yy_lookahead */ 691 #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead) 692 693 /* Free all memory associated with the given acttab */ 694 void acttab_free(acttab *p){ 695 lemon_free( p->aAction ); 696 lemon_free( p->aLookahead ); 697 lemon_free( p ); 698 } 699 700 /* Allocate a new acttab structure */ 701 acttab *acttab_alloc(int nsymbol, int nterminal){ 702 acttab *p = (acttab *) lemon_calloc( 1, sizeof(*p) ); 703 if( p==0 ){ 704 fprintf(stderr,"Unable to allocate memory for a new acttab."); 705 exit(1); 706 } 707 memset(p, 0, sizeof(*p)); 708 p->nsymbol = nsymbol; 709 p->nterminal = nterminal; 710 return p; 711 } 712 713 /* Add a new action to the current transaction set. 714 ** 715 ** This routine is called once for each lookahead for a particular 716 ** state. 717 */ 718 void acttab_action(acttab *p, int lookahead, int action){ 719 if( p->nLookahead>=p->nLookaheadAlloc ){ 720 p->nLookaheadAlloc += 25; 721 p->aLookahead = (struct lookahead_action *) lemon_realloc( p->aLookahead, 722 sizeof(p->aLookahead[0])*p->nLookaheadAlloc ); 723 if( p->aLookahead==0 ){ 724 fprintf(stderr,"malloc failed\n"); 725 exit(1); 726 } 727 } 728 if( p->nLookahead==0 ){ 729 p->mxLookahead = lookahead; 730 p->mnLookahead = lookahead; 731 p->mnAction = action; 732 }else{ 733 if( p->mxLookaheadmxLookahead = lookahead; 734 if( p->mnLookahead>lookahead ){ 735 p->mnLookahead = lookahead; 736 p->mnAction = action; 737 } 738 } 739 p->aLookahead[p->nLookahead].lookahead = lookahead; 740 p->aLookahead[p->nLookahead].action = action; 741 p->nLookahead++; 742 } 743 744 /* 745 ** Add the transaction set built up with prior calls to acttab_action() 746 ** into the current action table. Then reset the transaction set back 747 ** to an empty set in preparation for a new round of acttab_action() calls. 748 ** 749 ** Return the offset into the action table of the new transaction. 750 ** 751 ** If the makeItSafe parameter is true, then the offset is chosen so that 752 ** it is impossible to overread the yy_lookaside[] table regardless of 753 ** the lookaside token. This is done for the terminal symbols, as they 754 ** come from external inputs and can contain syntax errors. When makeItSafe 755 ** is false, there is more flexibility in selecting offsets, resulting in 756 ** a smaller table. For non-terminal symbols, which are never syntax errors, 757 ** makeItSafe can be false. 758 */ 759 int acttab_insert(acttab *p, int makeItSafe){ 760 int i, j, k, n, end; 761 assert( p->nLookahead>0 ); 762 763 /* Make sure we have enough space to hold the expanded action table 764 ** in the worst case. The worst case occurs if the transaction set 765 ** must be appended to the current action table 766 */ 767 n = p->nsymbol + 1; 768 if( p->nAction + n >= p->nActionAlloc ){ 769 int oldAlloc = p->nActionAlloc; 770 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; 771 p->aAction = (struct lookahead_action *) lemon_realloc( p->aAction, 772 sizeof(p->aAction[0])*p->nActionAlloc); 773 if( p->aAction==0 ){ 774 fprintf(stderr,"malloc failed\n"); 775 exit(1); 776 } 777 for(i=oldAlloc; inActionAlloc; i++){ 778 p->aAction[i].lookahead = -1; 779 p->aAction[i].action = -1; 780 } 781 } 782 783 /* Scan the existing action table looking for an offset that is a 784 ** duplicate of the current transaction set. Fall out of the loop 785 ** if and when the duplicate is found. 786 ** 787 ** i is the index in p->aAction[] where p->mnLookahead is inserted. 788 */ 789 end = makeItSafe ? p->mnLookahead : 0; 790 for(i=p->nAction-1; i>=end; i--){ 791 if( p->aAction[i].lookahead==p->mnLookahead ){ 792 /* All lookaheads and actions in the aLookahead[] transaction 793 ** must match against the candidate aAction[i] entry. */ 794 if( p->aAction[i].action!=p->mnAction ) continue; 795 for(j=0; jnLookahead; j++){ 796 k = p->aLookahead[j].lookahead - p->mnLookahead + i; 797 if( k<0 || k>=p->nAction ) break; 798 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break; 799 if( p->aLookahead[j].action!=p->aAction[k].action ) break; 800 } 801 if( jnLookahead ) continue; 802 803 /* No possible lookahead value that is not in the aLookahead[] 804 ** transaction is allowed to match aAction[i] */ 805 n = 0; 806 for(j=0; jnAction; j++){ 807 if( p->aAction[j].lookahead<0 ) continue; 808 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++; 809 } 810 if( n==p->nLookahead ){ 811 break; /* An exact match is found at offset i */ 812 } 813 } 814 } 815 816 /* If no existing offsets exactly match the current transaction, find an 817 ** an empty offset in the aAction[] table in which we can add the 818 ** aLookahead[] transaction. 819 */ 820 if( inAction, which means the 824 ** transaction will be appended. */ 825 i = makeItSafe ? p->mnLookahead : 0; 826 for(; inActionAlloc - p->mxLookahead; i++){ 827 if( p->aAction[i].lookahead<0 ){ 828 for(j=0; jnLookahead; j++){ 829 k = p->aLookahead[j].lookahead - p->mnLookahead + i; 830 if( k<0 ) break; 831 if( p->aAction[k].lookahead>=0 ) break; 832 } 833 if( jnLookahead ) continue; 834 for(j=0; jnAction; j++){ 835 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break; 836 } 837 if( j==p->nAction ){ 838 break; /* Fits in empty slots */ 839 } 840 } 841 } 842 } 843 /* Insert transaction set at index i. */ 844 #if 0 845 printf("Acttab:"); 846 for(j=0; jnLookahead; j++){ 847 printf(" %d", p->aLookahead[j].lookahead); 848 } 849 printf(" inserted at %d\n", i); 850 #endif 851 for(j=0; jnLookahead; j++){ 852 k = p->aLookahead[j].lookahead - p->mnLookahead + i; 853 p->aAction[k] = p->aLookahead[j]; 854 if( k>=p->nAction ) p->nAction = k+1; 855 } 856 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1; 857 p->nLookahead = 0; 858 859 /* Return the offset that is added to the lookahead in order to get the 860 ** index into yy_action of the action */ 861 return i - p->mnLookahead; 862 } 863 864 /* 865 ** Return the size of the action table without the trailing syntax error 866 ** entries. 867 */ 868 int acttab_action_size(acttab *p){ 869 int n = p->nAction; 870 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; } 871 return n; 872 } 873 874 /********************** From the file "build.c" *****************************/ 875 /* 876 ** Routines to construction the finite state machine for the LEMON 877 ** parser generator. 878 */ 879 880 /* Find a precedence symbol of every rule in the grammar. 881 ** 882 ** Those rules which have a precedence symbol coded in the input 883 ** grammar using the "[symbol]" construct will already have the 884 ** rp->precsym field filled. Other rules take as their precedence 885 ** symbol the first RHS symbol with a defined precedence. If there 886 ** are not RHS symbols with a defined precedence, the precedence 887 ** symbol field is left blank. 888 */ 889 void FindRulePrecedences(struct lemon *xp) 890 { 891 struct rule *rp; 892 for(rp=xp->rule; rp; rp=rp->next){ 893 if( rp->precsym==0 ){ 894 int i, j; 895 for(i=0; inrhs && rp->precsym==0; i++){ 896 struct symbol *sp = rp->rhs[i]; 897 if( sp->type==MULTITERMINAL ){ 898 for(j=0; jnsubsym; j++){ 899 if( sp->subsym[j]->prec>=0 ){ 900 rp->precsym = sp->subsym[j]; 901 break; 902 } 903 } 904 }else if( sp->prec>=0 ){ 905 rp->precsym = rp->rhs[i]; 906 } 907 } 908 } 909 } 910 return; 911 } 912 913 /* Find all nonterminals which will generate the empty string. 914 ** Then go back and compute the first sets of every nonterminal. 915 ** The first set is the set of all terminal symbols which can begin 916 ** a string generated by that nonterminal. 917 */ 918 void FindFirstSets(struct lemon *lemp) 919 { 920 int i, j; 921 struct rule *rp; 922 int progress; 923 924 for(i=0; insymbol; i++){ 925 lemp->symbols[i]->lambda = LEMON_FALSE; 926 } 927 for(i=lemp->nterminal; insymbol; i++){ 928 lemp->symbols[i]->firstset = SetNew(); 929 } 930 931 /* First compute all lambdas */ 932 do{ 933 progress = 0; 934 for(rp=lemp->rule; rp; rp=rp->next){ 935 if( rp->lhs->lambda ) continue; 936 for(i=0; inrhs; i++){ 937 struct symbol *sp = rp->rhs[i]; 938 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE ); 939 if( sp->lambda==LEMON_FALSE ) break; 940 } 941 if( i==rp->nrhs ){ 942 rp->lhs->lambda = LEMON_TRUE; 943 progress = 1; 944 } 945 } 946 }while( progress ); 947 948 /* Now compute all first sets */ 949 do{ 950 struct symbol *s1, *s2; 951 progress = 0; 952 for(rp=lemp->rule; rp; rp=rp->next){ 953 s1 = rp->lhs; 954 for(i=0; inrhs; i++){ 955 s2 = rp->rhs[i]; 956 if( s2->type==TERMINAL ){ 957 progress += SetAdd(s1->firstset,s2->index); 958 break; 959 }else if( s2->type==MULTITERMINAL ){ 960 for(j=0; jnsubsym; j++){ 961 progress += SetAdd(s1->firstset,s2->subsym[j]->index); 962 } 963 break; 964 }else if( s1==s2 ){ 965 if( s1->lambda==LEMON_FALSE ) break; 966 }else{ 967 progress += SetUnion(s1->firstset,s2->firstset); 968 if( s2->lambda==LEMON_FALSE ) break; 969 } 970 } 971 } 972 }while( progress ); 973 return; 974 } 975 976 /* Compute all LR(0) states for the grammar. Links 977 ** are added to between some states so that the LR(1) follow sets 978 ** can be computed later. 979 */ 980 PRIVATE struct state *getstate(struct lemon *); /* forward reference */ 981 void FindStates(struct lemon *lemp) 982 { 983 struct symbol *sp; 984 struct rule *rp; 985 986 Configlist_init(); 987 988 /* Find the start symbol */ 989 if( lemp->start ){ 990 sp = Symbol_find(lemp->start); 991 if( sp==0 ){ 992 ErrorMsg(lemp->filename,0, 993 "The specified start symbol \"%s\" is not " 994 "in a nonterminal of the grammar. \"%s\" will be used as the start " 995 "symbol instead.",lemp->start,lemp->startRule->lhs->name); 996 lemp->errorcnt++; 997 sp = lemp->startRule->lhs; 998 } 999 }else if( lemp->startRule ){ 1000 sp = lemp->startRule->lhs; 1001 }else{ 1002 ErrorMsg(lemp->filename,0,"Internal error - no start rule\n"); 1003 exit(1); 1004 } 1005 1006 /* Make sure the start symbol doesn't occur on the right-hand side of 1007 ** any rule. Report an error if it does. (YACC would generate a new 1008 ** start symbol in this case.) */ 1009 for(rp=lemp->rule; rp; rp=rp->next){ 1010 int i; 1011 for(i=0; inrhs; i++){ 1012 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */ 1013 ErrorMsg(lemp->filename,0, 1014 "The start symbol \"%s\" occurs on the " 1015 "right-hand side of a rule. This will result in a parser which " 1016 "does not work properly.",sp->name); 1017 lemp->errorcnt++; 1018 } 1019 } 1020 } 1021 1022 /* The basis configuration set for the first state 1023 ** is all rules which have the start symbol as their 1024 ** left-hand side */ 1025 for(rp=sp->rule; rp; rp=rp->nextlhs){ 1026 struct config *newcfp; 1027 rp->lhsStart = 1; 1028 newcfp = Configlist_addbasis(rp,0); 1029 SetAdd(newcfp->fws,0); 1030 } 1031 1032 /* Compute the first state. All other states will be 1033 ** computed automatically during the computation of the first one. 1034 ** The returned pointer to the first state is not used. */ 1035 (void)getstate(lemp); 1036 return; 1037 } 1038 1039 /* Return a pointer to a state which is described by the configuration 1040 ** list which has been built from calls to Configlist_add. 1041 */ 1042 PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */ 1043 PRIVATE struct state *getstate(struct lemon *lemp) 1044 { 1045 struct config *cfp, *bp; 1046 struct state *stp; 1047 1048 /* Extract the sorted basis of the new state. The basis was constructed 1049 ** by prior calls to "Configlist_addbasis()". */ 1050 Configlist_sortbasis(); 1051 bp = Configlist_basis(); 1052 1053 /* Get a state with the same basis */ 1054 stp = State_find(bp); 1055 if( stp ){ 1056 /* A state with the same basis already exists! Copy all the follow-set 1057 ** propagation links from the state under construction into the 1058 ** preexisting state, then return a pointer to the preexisting state */ 1059 struct config *x, *y; 1060 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){ 1061 Plink_copy(&y->bplp,x->bplp); 1062 Plink_delete(x->fplp); 1063 x->fplp = x->bplp = 0; 1064 } 1065 cfp = Configlist_return(); 1066 Configlist_eat(cfp); 1067 }else{ 1068 /* This really is a new state. Construct all the details */ 1069 Configlist_closure(lemp); /* Compute the configuration closure */ 1070 Configlist_sort(); /* Sort the configuration closure */ 1071 cfp = Configlist_return(); /* Get a pointer to the config list */ 1072 stp = State_new(); /* A new state structure */ 1073 MemoryCheck(stp); 1074 stp->bp = bp; /* Remember the configuration basis */ 1075 stp->cfp = cfp; /* Remember the configuration closure */ 1076 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */ 1077 stp->ap = 0; /* No actions, yet. */ 1078 State_insert(stp,stp->bp); /* Add to the state table */ 1079 buildshifts(lemp,stp); /* Recursively compute successor states */ 1080 } 1081 return stp; 1082 } 1083 1084 /* 1085 ** Return true if two symbols are the same. 1086 */ 1087 int same_symbol(struct symbol *a, struct symbol *b) 1088 { 1089 int i; 1090 if( a==b ) return 1; 1091 if( a->type!=MULTITERMINAL ) return 0; 1092 if( b->type!=MULTITERMINAL ) return 0; 1093 if( a->nsubsym!=b->nsubsym ) return 0; 1094 for(i=0; insubsym; i++){ 1095 if( a->subsym[i]!=b->subsym[i] ) return 0; 1096 } 1097 return 1; 1098 } 1099 1100 /* Construct all successor states to the given state. A "successor" 1101 ** state is any state which can be reached by a shift action. 1102 */ 1103 PRIVATE void buildshifts(struct lemon *lemp, struct state *stp) 1104 { 1105 struct config *cfp; /* For looping thru the config closure of "stp" */ 1106 struct config *bcfp; /* For the inner loop on config closure of "stp" */ 1107 struct config *newcfg; /* */ 1108 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */ 1109 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */ 1110 struct state *newstp; /* A pointer to a successor state */ 1111 1112 /* Each configuration becomes complete after it contributes to a successor 1113 ** state. Initially, all configurations are incomplete */ 1114 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE; 1115 1116 /* Loop through all configurations of the state "stp" */ 1117 for(cfp=stp->cfp; cfp; cfp=cfp->next){ 1118 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */ 1119 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */ 1120 Configlist_reset(); /* Reset the new config set */ 1121 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */ 1122 1123 /* For every configuration in the state "stp" which has the symbol "sp" 1124 ** following its dot, add the same configuration to the basis set under 1125 ** construction but with the dot shifted one symbol to the right. */ 1126 for(bcfp=cfp; bcfp; bcfp=bcfp->next){ 1127 if( bcfp->status==COMPLETE ) continue; /* Already used */ 1128 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */ 1129 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */ 1130 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */ 1131 bcfp->status = COMPLETE; /* Mark this config as used */ 1132 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1); 1133 Plink_add(&newcfg->bplp,bcfp); 1134 } 1135 1136 /* Get a pointer to the state described by the basis configuration set 1137 ** constructed in the preceding loop */ 1138 newstp = getstate(lemp); 1139 1140 /* The state "newstp" is reached from the state "stp" by a shift action 1141 ** on the symbol "sp" */ 1142 if( sp->type==MULTITERMINAL ){ 1143 int i; 1144 for(i=0; insubsym; i++){ 1145 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp); 1146 } 1147 }else{ 1148 Action_add(&stp->ap,SHIFT,sp,(char *)newstp); 1149 } 1150 } 1151 } 1152 1153 /* 1154 ** Construct the propagation links 1155 */ 1156 void FindLinks(struct lemon *lemp) 1157 { 1158 int i; 1159 struct config *cfp, *other; 1160 struct state *stp; 1161 struct plink *plp; 1162 1163 /* Housekeeping detail: 1164 ** Add to every propagate link a pointer back to the state to 1165 ** which the link is attached. */ 1166 for(i=0; instate; i++){ 1167 stp = lemp->sorted[i]; 1168 for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){ 1169 cfp->stp = stp; 1170 } 1171 } 1172 1173 /* Convert all backlinks into forward links. Only the forward 1174 ** links are used in the follow-set computation. */ 1175 for(i=0; instate; i++){ 1176 stp = lemp->sorted[i]; 1177 for(cfp=stp?stp->cfp:0; cfp; cfp=cfp->next){ 1178 for(plp=cfp->bplp; plp; plp=plp->next){ 1179 other = plp->cfp; 1180 Plink_add(&other->fplp,cfp); 1181 } 1182 } 1183 } 1184 } 1185 1186 /* Compute all followsets. 1187 ** 1188 ** A followset is the set of all symbols which can come immediately 1189 ** after a configuration. 1190 */ 1191 void FindFollowSets(struct lemon *lemp) 1192 { 1193 int i; 1194 struct config *cfp; 1195 struct plink *plp; 1196 int progress; 1197 int change; 1198 1199 for(i=0; instate; i++){ 1200 assert( lemp->sorted[i]!=0 ); 1201 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ 1202 cfp->status = INCOMPLETE; 1203 } 1204 } 1205 1206 do{ 1207 progress = 0; 1208 for(i=0; instate; i++){ 1209 assert( lemp->sorted[i]!=0 ); 1210 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ 1211 if( cfp->status==COMPLETE ) continue; 1212 for(plp=cfp->fplp; plp; plp=plp->next){ 1213 change = SetUnion(plp->cfp->fws,cfp->fws); 1214 if( change ){ 1215 plp->cfp->status = INCOMPLETE; 1216 progress = 1; 1217 } 1218 } 1219 cfp->status = COMPLETE; 1220 } 1221 } 1222 }while( progress ); 1223 } 1224 1225 static int resolve_conflict(struct action *,struct action *); 1226 1227 /* Compute the reduce actions, and resolve conflicts. 1228 */ 1229 void FindActions(struct lemon *lemp) 1230 { 1231 int i,j; 1232 struct config *cfp; 1233 struct state *stp; 1234 struct symbol *sp; 1235 struct rule *rp; 1236 1237 /* Add all of the reduce actions 1238 ** A reduce action is added for each element of the followset of 1239 ** a configuration which has its dot at the extreme right. 1240 */ 1241 for(i=0; instate; i++){ /* Loop over all states */ 1242 stp = lemp->sorted[i]; 1243 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */ 1244 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */ 1245 for(j=0; jnterminal; j++){ 1246 if( SetFind(cfp->fws,j) ){ 1247 /* Add a reduce action to the state "stp" which will reduce by the 1248 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */ 1249 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp); 1250 } 1251 } 1252 } 1253 } 1254 } 1255 1256 /* Add the accepting token */ 1257 if( lemp->start ){ 1258 sp = Symbol_find(lemp->start); 1259 if( sp==0 ){ 1260 if( lemp->startRule==0 ){ 1261 fprintf(stderr, "internal error on source line %d: no start rule\n", 1262 __LINE__); 1263 exit(1); 1264 } 1265 sp = lemp->startRule->lhs; 1266 } 1267 }else{ 1268 sp = lemp->startRule->lhs; 1269 } 1270 /* Add to the first state (which is always the starting state of the 1271 ** finite state machine) an action to ACCEPT if the lookahead is the 1272 ** start nonterminal. */ 1273 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0); 1274 1275 /* Resolve conflicts */ 1276 for(i=0; instate; i++){ 1277 struct action *ap, *nap; 1278 stp = lemp->sorted[i]; 1279 /* assert( stp->ap ); */ 1280 stp->ap = Action_sort(stp->ap); 1281 for(ap=stp->ap; ap && ap->next; ap=ap->next){ 1282 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){ 1283 /* The two actions "ap" and "nap" have the same lookahead. 1284 ** Figure out which one should be used */ 1285 lemp->nconflict += resolve_conflict(ap,nap); 1286 } 1287 } 1288 } 1289 1290 /* Report an error for each rule that can never be reduced. */ 1291 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE; 1292 for(i=0; instate; i++){ 1293 struct action *ap; 1294 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ 1295 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE; 1296 } 1297 } 1298 for(rp=lemp->rule; rp; rp=rp->next){ 1299 if( rp->canReduce ) continue; 1300 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n"); 1301 lemp->errorcnt++; 1302 } 1303 } 1304 1305 /* Resolve a conflict between the two given actions. If the 1306 ** conflict can't be resolved, return non-zero. 1307 ** 1308 ** NO LONGER TRUE: 1309 ** To resolve a conflict, first look to see if either action 1310 ** is on an error rule. In that case, take the action which 1311 ** is not associated with the error rule. If neither or both 1312 ** actions are associated with an error rule, then try to 1313 ** use precedence to resolve the conflict. 1314 ** 1315 ** If either action is a SHIFT, then it must be apx. This 1316 ** function won't work if apx->type==REDUCE and apy->type==SHIFT. 1317 */ 1318 static int resolve_conflict( 1319 struct action *apx, 1320 struct action *apy 1321 ){ 1322 struct symbol *spx, *spy; 1323 int errcnt = 0; 1324 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ 1325 if( apx->type==SHIFT && apy->type==SHIFT ){ 1326 apy->type = SSCONFLICT; 1327 errcnt++; 1328 } 1329 if( apx->type==SHIFT && apy->type==REDUCE ){ 1330 spx = apx->sp; 1331 spy = apy->x.rp->precsym; 1332 if( spy==0 || spx->prec<0 || spy->prec<0 ){ 1333 /* Not enough precedence information. */ 1334 apy->type = SRCONFLICT; 1335 errcnt++; 1336 }else if( spx->prec>spy->prec ){ /* higher precedence wins */ 1337 apy->type = RD_RESOLVED; 1338 }else if( spx->precprec ){ 1339 apx->type = SH_RESOLVED; 1340 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */ 1341 apy->type = RD_RESOLVED; /* associativity */ 1342 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */ 1343 apx->type = SH_RESOLVED; 1344 }else{ 1345 assert( spx->prec==spy->prec && spx->assoc==NONE ); 1346 apx->type = ERROR; 1347 } 1348 }else if( apx->type==REDUCE && apy->type==REDUCE ){ 1349 spx = apx->x.rp->precsym; 1350 spy = apy->x.rp->precsym; 1351 if( spx==0 || spy==0 || spx->prec<0 || 1352 spy->prec<0 || spx->prec==spy->prec ){ 1353 apy->type = RRCONFLICT; 1354 errcnt++; 1355 }else if( spx->prec>spy->prec ){ 1356 apy->type = RD_RESOLVED; 1357 }else if( spx->precprec ){ 1358 apx->type = RD_RESOLVED; 1359 } 1360 }else{ 1361 assert( 1362 apx->type==ERROR || 1363 apx->type==SH_RESOLVED || 1364 apx->type==RD_RESOLVED || 1365 apx->type==SSCONFLICT || 1366 apx->type==SRCONFLICT || 1367 apx->type==RRCONFLICT || 1368 apy->type==SH_RESOLVED || 1369 apy->type==RD_RESOLVED || 1370 apy->type==SSCONFLICT || 1371 apy->type==SRCONFLICT || 1372 apy->type==RRCONFLICT 1373 ); 1374 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before 1375 ** REDUCEs on the list. If we reach this point it must be because 1376 ** the parser conflict had already been resolved. */ 1377 } 1378 return errcnt; 1379 } 1380 /********************* From the file "configlist.c" *************************/ 1381 /* 1382 ** Routines to processing a configuration list and building a state 1383 ** in the LEMON parser generator. 1384 */ 1385 1386 static struct config *freelist = 0; /* List of free configurations */ 1387 static struct config *current = 0; /* Top of list of configurations */ 1388 static struct config **currentend = 0; /* Last on list of configs */ 1389 static struct config *basis = 0; /* Top of list of basis configs */ 1390 static struct config **basisend = 0; /* End of list of basis configs */ 1391 1392 /* Return a pointer to a new configuration */ 1393 PRIVATE struct config *newconfig(void){ 1394 return (struct config*)lemon_calloc(1, sizeof(struct config)); 1395 } 1396 1397 /* The configuration "old" is no longer used */ 1398 PRIVATE void deleteconfig(struct config *old) 1399 { 1400 old->next = freelist; 1401 freelist = old; 1402 } 1403 1404 /* Initialized the configuration list builder */ 1405 void Configlist_init(void){ 1406 current = 0; 1407 currentend = ¤t; 1408 basis = 0; 1409 basisend = &basis; 1410 Configtable_init(); 1411 return; 1412 } 1413 1414 /* Initialized the configuration list builder */ 1415 void Configlist_reset(void){ 1416 current = 0; 1417 currentend = ¤t; 1418 basis = 0; 1419 basisend = &basis; 1420 Configtable_clear(0); 1421 return; 1422 } 1423 1424 /* Add another configuration to the configuration list */ 1425 struct config *Configlist_add( 1426 struct rule *rp, /* The rule */ 1427 int dot /* Index into the RHS of the rule where the dot goes */ 1428 ){ 1429 struct config *cfp, model; 1430 1431 assert( currentend!=0 ); 1432 model.rp = rp; 1433 model.dot = dot; 1434 cfp = Configtable_find(&model); 1435 if( cfp==0 ){ 1436 cfp = newconfig(); 1437 cfp->rp = rp; 1438 cfp->dot = dot; 1439 cfp->fws = SetNew(); 1440 cfp->stp = 0; 1441 cfp->fplp = cfp->bplp = 0; 1442 cfp->next = 0; 1443 cfp->bp = 0; 1444 *currentend = cfp; 1445 currentend = &cfp->next; 1446 Configtable_insert(cfp); 1447 } 1448 return cfp; 1449 } 1450 1451 /* Add a basis configuration to the configuration list */ 1452 struct config *Configlist_addbasis(struct rule *rp, int dot) 1453 { 1454 struct config *cfp, model; 1455 1456 assert( basisend!=0 ); 1457 assert( currentend!=0 ); 1458 model.rp = rp; 1459 model.dot = dot; 1460 cfp = Configtable_find(&model); 1461 if( cfp==0 ){ 1462 cfp = newconfig(); 1463 cfp->rp = rp; 1464 cfp->dot = dot; 1465 cfp->fws = SetNew(); 1466 cfp->stp = 0; 1467 cfp->fplp = cfp->bplp = 0; 1468 cfp->next = 0; 1469 cfp->bp = 0; 1470 *currentend = cfp; 1471 currentend = &cfp->next; 1472 *basisend = cfp; 1473 basisend = &cfp->bp; 1474 Configtable_insert(cfp); 1475 } 1476 return cfp; 1477 } 1478 1479 /* Compute the closure of the configuration list */ 1480 void Configlist_closure(struct lemon *lemp) 1481 { 1482 struct config *cfp, *newcfp; 1483 struct rule *rp, *newrp; 1484 struct symbol *sp, *xsp; 1485 int i, dot; 1486 1487 assert( currentend!=0 ); 1488 for(cfp=current; cfp; cfp=cfp->next){ 1489 rp = cfp->rp; 1490 dot = cfp->dot; 1491 if( dot>=rp->nrhs ) continue; 1492 sp = rp->rhs[dot]; 1493 if( sp->type==NONTERMINAL ){ 1494 if( sp->rule==0 && sp!=lemp->errsym ){ 1495 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.", 1496 sp->name); 1497 lemp->errorcnt++; 1498 } 1499 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){ 1500 newcfp = Configlist_add(newrp,0); 1501 for(i=dot+1; inrhs; i++){ 1502 xsp = rp->rhs[i]; 1503 if( xsp->type==TERMINAL ){ 1504 SetAdd(newcfp->fws,xsp->index); 1505 break; 1506 }else if( xsp->type==MULTITERMINAL ){ 1507 int k; 1508 for(k=0; knsubsym; k++){ 1509 SetAdd(newcfp->fws, xsp->subsym[k]->index); 1510 } 1511 break; 1512 }else{ 1513 SetUnion(newcfp->fws,xsp->firstset); 1514 if( xsp->lambda==LEMON_FALSE ) break; 1515 } 1516 } 1517 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); 1518 } 1519 } 1520 } 1521 return; 1522 } 1523 1524 /* Sort the configuration list */ 1525 void Configlist_sort(void){ 1526 current = (struct config*)msort((char*)current,(char**)&(current->next), 1527 Configcmp); 1528 currentend = 0; 1529 return; 1530 } 1531 1532 /* Sort the basis configuration list */ 1533 void Configlist_sortbasis(void){ 1534 basis = (struct config*)msort((char*)current,(char**)&(current->bp), 1535 Configcmp); 1536 basisend = 0; 1537 return; 1538 } 1539 1540 /* Return a pointer to the head of the configuration list and 1541 ** reset the list */ 1542 struct config *Configlist_return(void){ 1543 struct config *old; 1544 old = current; 1545 current = 0; 1546 currentend = 0; 1547 return old; 1548 } 1549 1550 /* Return a pointer to the head of the configuration list and 1551 ** reset the list */ 1552 struct config *Configlist_basis(void){ 1553 struct config *old; 1554 old = basis; 1555 basis = 0; 1556 basisend = 0; 1557 return old; 1558 } 1559 1560 /* Free all elements of the given configuration list */ 1561 void Configlist_eat(struct config *cfp) 1562 { 1563 struct config *nextcfp; 1564 for(; cfp; cfp=nextcfp){ 1565 nextcfp = cfp->next; 1566 assert( cfp->fplp==0 ); 1567 assert( cfp->bplp==0 ); 1568 if( cfp->fws ) SetFree(cfp->fws); 1569 deleteconfig(cfp); 1570 } 1571 return; 1572 } 1573 /***************** From the file "error.c" *********************************/ 1574 /* 1575 ** Code for printing error message. 1576 */ 1577 1578 void ErrorMsg(const char *filename, int lineno, const char *format, ...){ 1579 va_list ap; 1580 fprintf(stderr, "%s:%d: ", filename, lineno); 1581 va_start(ap, format); 1582 vfprintf(stderr,format,ap); 1583 va_end(ap); 1584 fprintf(stderr, "\n"); 1585 } 1586 /**************** From the file "main.c" ************************************/ 1587 /* 1588 ** Main program file for the LEMON parser generator. 1589 */ 1590 1591 /* Report an out-of-memory condition and abort. This function 1592 ** is used mostly by the "MemoryCheck" macro in struct.h 1593 */ 1594 void memory_error(void){ 1595 fprintf(stderr,"Out of memory. Aborting...\n"); 1596 exit(1); 1597 } 1598 1599 static int nDefine = 0; /* Number of -D options on the command line */ 1600 static int nDefineUsed = 0; /* Number of -D options actually used */ 1601 static char **azDefine = 0; /* Name of the -D macros */ 1602 static char *bDefineUsed = 0; /* True for every -D macro actually used */ 1603 1604 /* This routine is called with the argument to each -D command-line option. 1605 ** Add the macro defined to the azDefine array. 1606 */ 1607 static void handle_D_option(char *z){ 1608 char **paz; 1609 nDefine++; 1610 azDefine = (char **) lemon_realloc(azDefine, sizeof(azDefine[0])*nDefine); 1611 if( azDefine==0 ){ 1612 fprintf(stderr,"out of memory\n"); 1613 exit(1); 1614 } 1615 bDefineUsed = (char*)lemon_realloc(bDefineUsed, nDefine); 1616 if( bDefineUsed==0 ){ 1617 fprintf(stderr,"out of memory\n"); 1618 exit(1); 1619 } 1620 bDefineUsed[nDefine-1] = 0; 1621 paz = &azDefine[nDefine-1]; 1622 *paz = (char *) lemon_malloc( lemonStrlen(z)+1 ); 1623 if( *paz==0 ){ 1624 fprintf(stderr,"out of memory\n"); 1625 exit(1); 1626 } 1627 lemon_strcpy(*paz, z); 1628 for(z=*paz; *z && *z!='='; z++){} 1629 *z = 0; 1630 } 1631 1632 /* This routine is called with the argument to each -U command-line option. 1633 ** Omit a previously defined macro. 1634 */ 1635 static void handle_U_option(char *z){ 1636 int i; 1637 for(i=0; iiRuleiRule ){ 1676 *ppPrev = pA; 1677 ppPrev = &pA->next; 1678 pA = pA->next; 1679 }else{ 1680 *ppPrev = pB; 1681 ppPrev = &pB->next; 1682 pB = pB->next; 1683 } 1684 } 1685 if( pA ){ 1686 *ppPrev = pA; 1687 }else{ 1688 *ppPrev = pB; 1689 } 1690 return pFirst; 1691 } 1692 1693 /* 1694 ** Sort a list of rules in order of increasing iRule value 1695 */ 1696 static struct rule *Rule_sort(struct rule *rp){ 1697 unsigned int i; 1698 struct rule *pNext; 1699 struct rule *x[32]; 1700 memset(x, 0, sizeof(x)); 1701 while( rp ){ 1702 pNext = rp->next; 1703 rp->next = 0; 1704 for(i=0; iindex = i; 1821 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp); 1822 for(i=0; iindex = i; 1823 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; } 1824 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 ); 1825 lem.nsymbol = i - 1; 1826 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++); 1827 lem.nterminal = i; 1828 1829 /* Assign sequential rule numbers. Start with 0. Put rules that have no 1830 ** reduce action C-code associated with them last, so that the switch() 1831 ** statement that selects reduction actions will have a smaller jump table. 1832 */ 1833 for(i=0, rp=lem.rule; rp; rp=rp->next){ 1834 rp->iRule = rp->code ? i++ : -1; 1835 } 1836 lem.nruleWithAction = i; 1837 for(rp=lem.rule; rp; rp=rp->next){ 1838 if( rp->iRule<0 ) rp->iRule = i++; 1839 } 1840 lem.startRule = lem.rule; 1841 lem.rule = Rule_sort(lem.rule); 1842 1843 /* Generate a reprint of the grammar, if requested on the command line */ 1844 if( rpflag ){ 1845 Reprint(&lem); 1846 }else{ 1847 /* Initialize the size for all follow and first sets */ 1848 SetSize(lem.nterminal+1); 1849 1850 /* Find the precedence for every production rule (that has one) */ 1851 FindRulePrecedences(&lem); 1852 1853 /* Compute the lambda-nonterminals and the first-sets for every 1854 ** nonterminal */ 1855 FindFirstSets(&lem); 1856 1857 /* Compute all LR(0) states. Also record follow-set propagation 1858 ** links so that the follow-set can be computed later */ 1859 lem.nstate = 0; 1860 FindStates(&lem); 1861 lem.sorted = State_arrayof(); 1862 1863 /* Tie up loose ends on the propagation links */ 1864 FindLinks(&lem); 1865 1866 /* Compute the follow set of every reducible configuration */ 1867 FindFollowSets(&lem); 1868 1869 /* Compute the action tables */ 1870 FindActions(&lem); 1871 1872 /* Compress the action tables */ 1873 CompressTables(&lem); 1874 1875 /* Reorder and renumber the states so that states with fewer choices 1876 ** occur at the end. This is an optimization that helps make the 1877 ** generated parser tables smaller. */ 1878 ResortStates(&lem); 1879 1880 /* Generate a report of the parser generated. (the "y.output" file) */ 1881 if( !quiet ) ReportOutput(&lem); 1882 1883 /* Generate the source code for the parser */ 1884 ReportTable(&lem, mhflag, sqlFlag); 1885 1886 /* Produce a header file for use by the scanner. (This step is 1887 ** omitted if the "-m" option is used because makeheaders will 1888 ** generate the file for us.) */ 1889 if( !mhflag ) ReportHeader(&lem); 1890 } 1891 if( statistics ){ 1892 printf("Parser statistics:\n"); 1893 stats_line("terminal symbols", lem.nterminal); 1894 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal); 1895 stats_line("total symbols", lem.nsymbol); 1896 stats_line("rules", lem.nrule); 1897 stats_line("states", lem.nxstate); 1898 stats_line("conflicts", lem.nconflict); 1899 stats_line("action table entries", lem.nactiontab); 1900 stats_line("lookahead table entries", lem.nlookaheadtab); 1901 stats_line("total table size (bytes)", lem.tablesize); 1902 } 1903 if( lem.nconflict > 0 ){ 1904 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); 1905 } 1906 1907 /* return 0 on success, 1 on failure. */ 1908 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0; 1909 lemon_free_all(); 1910 exit(exitcode); 1911 return (exitcode); 1912 } 1913 /******************** From the file "msort.c" *******************************/ 1914 /* 1915 ** A generic merge-sort program. 1916 ** 1917 ** USAGE: 1918 ** Let "ptr" be a pointer to some structure which is at the head of 1919 ** a null-terminated list. Then to sort the list call: 1920 ** 1921 ** ptr = msort(ptr,&(ptr->next),cmpfnc); 1922 ** 1923 ** In the above, "cmpfnc" is a pointer to a function which compares 1924 ** two instances of the structure and returns an integer, as in 1925 ** strcmp. The second argument is a pointer to the pointer to the 1926 ** second element of the linked list. This address is used to compute 1927 ** the offset to the "next" field within the structure. The offset to 1928 ** the "next" field must be constant for all structures in the list. 1929 ** 1930 ** The function returns a new pointer which is the head of the list 1931 ** after sorting. 1932 ** 1933 ** ALGORITHM: 1934 ** Merge-sort. 1935 */ 1936 1937 /* 1938 ** Return a pointer to the next structure in the linked list. 1939 */ 1940 #define NEXT(A) (*(char**)(((char*)A)+offset)) 1941 1942 /* 1943 ** Inputs: 1944 ** a: A sorted, null-terminated linked list. (May be null). 1945 ** b: A sorted, null-terminated linked list. (May be null). 1946 ** cmp: A pointer to the comparison function. 1947 ** offset: Offset in the structure to the "next" field. 1948 ** 1949 ** Return Value: 1950 ** A pointer to the head of a sorted list containing the elements 1951 ** of both a and b. 1952 ** 1953 ** Side effects: 1954 ** The "next" pointers for elements in the lists a and b are 1955 ** changed. 1956 */ 1957 static char *merge( 1958 char *a, 1959 char *b, 1960 int (*cmp)(const char*,const char*), 1961 int offset 1962 ){ 1963 char *ptr, *head; 1964 1965 if( a==0 ){ 1966 head = b; 1967 }else if( b==0 ){ 1968 head = a; 1969 }else{ 1970 if( (*cmp)(a,b)<=0 ){ 1971 ptr = a; 1972 a = NEXT(a); 1973 }else{ 1974 ptr = b; 1975 b = NEXT(b); 1976 } 1977 head = ptr; 1978 while( a && b ){ 1979 if( (*cmp)(a,b)<=0 ){ 1980 NEXT(ptr) = a; 1981 ptr = a; 1982 a = NEXT(a); 1983 }else{ 1984 NEXT(ptr) = b; 1985 ptr = b; 1986 b = NEXT(b); 1987 } 1988 } 1989 if( a ) NEXT(ptr) = a; 1990 else NEXT(ptr) = b; 1991 } 1992 return head; 1993 } 1994 1995 /* 1996 ** Inputs: 1997 ** list: Pointer to a singly-linked list of structures. 1998 ** next: Pointer to pointer to the second element of the list. 1999 ** cmp: A comparison function. 2000 ** 2001 ** Return Value: 2002 ** A pointer to the head of a sorted list containing the elements 2003 ** originally in list. 2004 ** 2005 ** Side effects: 2006 ** The "next" pointers for elements in list are changed. 2007 */ 2008 #define LISTSIZE 30 2009 static char *msort( 2010 char *list, 2011 char **next, 2012 int (*cmp)(const char*,const char*) 2013 ){ 2014 unsigned long offset; 2015 char *ep; 2016 char *set[LISTSIZE]; 2017 int i; 2018 offset = (unsigned long)((char*)next - (char*)list); 2019 for(i=0; istate = WAITING_FOR_DECL_KEYWORD; 2390 }else if( ISLOWER(x[0]) ){ 2391 psp->lhs = Symbol_new(x); 2392 psp->nrhs = 0; 2393 psp->lhsalias = 0; 2394 psp->state = WAITING_FOR_ARROW; 2395 }else if( x[0]=='{' ){ 2396 if( psp->prevrule==0 ){ 2397 ErrorMsg(psp->filename,psp->tokenlineno, 2398 "There is no prior rule upon which to attach the code " 2399 "fragment which begins on this line."); 2400 psp->errorcnt++; 2401 }else if( psp->prevrule->code!=0 ){ 2402 ErrorMsg(psp->filename,psp->tokenlineno, 2403 "Code fragment beginning on this line is not the first " 2404 "to follow the previous rule."); 2405 psp->errorcnt++; 2406 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){ 2407 psp->prevrule->neverReduce = 1; 2408 }else{ 2409 psp->prevrule->line = psp->tokenlineno; 2410 psp->prevrule->code = &x[1]; 2411 psp->prevrule->noCode = 0; 2412 } 2413 }else if( x[0]=='[' ){ 2414 psp->state = PRECEDENCE_MARK_1; 2415 }else{ 2416 ErrorMsg(psp->filename,psp->tokenlineno, 2417 "Token \"%s\" should be either \"%%\" or a nonterminal name.", 2418 x); 2419 psp->errorcnt++; 2420 } 2421 break; 2422 case PRECEDENCE_MARK_1: 2423 if( !ISUPPER(x[0]) ){ 2424 ErrorMsg(psp->filename,psp->tokenlineno, 2425 "The precedence symbol must be a terminal."); 2426 psp->errorcnt++; 2427 }else if( psp->prevrule==0 ){ 2428 ErrorMsg(psp->filename,psp->tokenlineno, 2429 "There is no prior rule to assign precedence \"[%s]\".",x); 2430 psp->errorcnt++; 2431 }else if( psp->prevrule->precsym!=0 ){ 2432 ErrorMsg(psp->filename,psp->tokenlineno, 2433 "Precedence mark on this line is not the first " 2434 "to follow the previous rule."); 2435 psp->errorcnt++; 2436 }else{ 2437 psp->prevrule->precsym = Symbol_new(x); 2438 } 2439 psp->state = PRECEDENCE_MARK_2; 2440 break; 2441 case PRECEDENCE_MARK_2: 2442 if( x[0]!=']' ){ 2443 ErrorMsg(psp->filename,psp->tokenlineno, 2444 "Missing \"]\" on precedence mark."); 2445 psp->errorcnt++; 2446 } 2447 psp->state = WAITING_FOR_DECL_OR_RULE; 2448 break; 2449 case WAITING_FOR_ARROW: 2450 if( x[0]==':' && x[1]==':' && x[2]=='=' ){ 2451 psp->state = IN_RHS; 2452 }else if( x[0]=='(' ){ 2453 psp->state = LHS_ALIAS_1; 2454 }else{ 2455 ErrorMsg(psp->filename,psp->tokenlineno, 2456 "Expected to see a \":\" following the LHS symbol \"%s\".", 2457 psp->lhs->name); 2458 psp->errorcnt++; 2459 psp->state = RESYNC_AFTER_RULE_ERROR; 2460 } 2461 break; 2462 case LHS_ALIAS_1: 2463 if( ISALPHA(x[0]) ){ 2464 psp->lhsalias = x; 2465 psp->state = LHS_ALIAS_2; 2466 }else{ 2467 ErrorMsg(psp->filename,psp->tokenlineno, 2468 "\"%s\" is not a valid alias for the LHS \"%s\"\n", 2469 x,psp->lhs->name); 2470 psp->errorcnt++; 2471 psp->state = RESYNC_AFTER_RULE_ERROR; 2472 } 2473 break; 2474 case LHS_ALIAS_2: 2475 if( x[0]==')' ){ 2476 psp->state = LHS_ALIAS_3; 2477 }else{ 2478 ErrorMsg(psp->filename,psp->tokenlineno, 2479 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); 2480 psp->errorcnt++; 2481 psp->state = RESYNC_AFTER_RULE_ERROR; 2482 } 2483 break; 2484 case LHS_ALIAS_3: 2485 if( x[0]==':' && x[1]==':' && x[2]=='=' ){ 2486 psp->state = IN_RHS; 2487 }else{ 2488 ErrorMsg(psp->filename,psp->tokenlineno, 2489 "Missing \"->\" following: \"%s(%s)\".", 2490 psp->lhs->name,psp->lhsalias); 2491 psp->errorcnt++; 2492 psp->state = RESYNC_AFTER_RULE_ERROR; 2493 } 2494 break; 2495 case IN_RHS: 2496 if( x[0]=='.' ){ 2497 struct rule *rp; 2498 rp = (struct rule *)lemon_calloc( sizeof(struct rule) + 2499 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1); 2500 if( rp==0 ){ 2501 ErrorMsg(psp->filename,psp->tokenlineno, 2502 "Can't allocate enough memory for this rule."); 2503 psp->errorcnt++; 2504 psp->prevrule = 0; 2505 }else{ 2506 int i; 2507 rp->ruleline = psp->tokenlineno; 2508 rp->rhs = (struct symbol**)&rp[1]; 2509 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]); 2510 for(i=0; inrhs; i++){ 2511 rp->rhs[i] = psp->rhs[i]; 2512 rp->rhsalias[i] = psp->alias[i]; 2513 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; } 2514 } 2515 rp->lhs = psp->lhs; 2516 rp->lhsalias = psp->lhsalias; 2517 rp->nrhs = psp->nrhs; 2518 rp->code = 0; 2519 rp->noCode = 1; 2520 rp->precsym = 0; 2521 rp->index = psp->gp->nrule++; 2522 rp->nextlhs = rp->lhs->rule; 2523 rp->lhs->rule = rp; 2524 rp->next = 0; 2525 if( psp->firstrule==0 ){ 2526 psp->firstrule = psp->lastrule = rp; 2527 }else{ 2528 psp->lastrule->next = rp; 2529 psp->lastrule = rp; 2530 } 2531 psp->prevrule = rp; 2532 } 2533 psp->state = WAITING_FOR_DECL_OR_RULE; 2534 }else if( ISALPHA(x[0]) ){ 2535 if( psp->nrhs>=MAXRHS ){ 2536 ErrorMsg(psp->filename,psp->tokenlineno, 2537 "Too many symbols on RHS of rule beginning at \"%s\".", 2538 x); 2539 psp->errorcnt++; 2540 psp->state = RESYNC_AFTER_RULE_ERROR; 2541 }else{ 2542 psp->rhs[psp->nrhs] = Symbol_new(x); 2543 psp->alias[psp->nrhs] = 0; 2544 psp->nrhs++; 2545 } 2546 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 && ISUPPER(x[1]) ){ 2547 struct symbol *msp = psp->rhs[psp->nrhs-1]; 2548 if( msp->type!=MULTITERMINAL ){ 2549 struct symbol *origsp = msp; 2550 msp = (struct symbol *) lemon_calloc(1,sizeof(*msp)); 2551 memset(msp, 0, sizeof(*msp)); 2552 msp->type = MULTITERMINAL; 2553 msp->nsubsym = 1; 2554 msp->subsym = (struct symbol**)lemon_calloc(1,sizeof(struct symbol*)); 2555 msp->subsym[0] = origsp; 2556 msp->name = origsp->name; 2557 psp->rhs[psp->nrhs-1] = msp; 2558 } 2559 msp->nsubsym++; 2560 msp->subsym = (struct symbol **) lemon_realloc(msp->subsym, 2561 sizeof(struct symbol*)*msp->nsubsym); 2562 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]); 2563 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){ 2564 ErrorMsg(psp->filename,psp->tokenlineno, 2565 "Cannot form a compound containing a non-terminal"); 2566 psp->errorcnt++; 2567 } 2568 }else if( x[0]=='(' && psp->nrhs>0 ){ 2569 psp->state = RHS_ALIAS_1; 2570 }else{ 2571 ErrorMsg(psp->filename,psp->tokenlineno, 2572 "Illegal character on RHS of rule: \"%s\".",x); 2573 psp->errorcnt++; 2574 psp->state = RESYNC_AFTER_RULE_ERROR; 2575 } 2576 break; 2577 case RHS_ALIAS_1: 2578 if( ISALPHA(x[0]) ){ 2579 psp->alias[psp->nrhs-1] = x; 2580 psp->state = RHS_ALIAS_2; 2581 }else{ 2582 ErrorMsg(psp->filename,psp->tokenlineno, 2583 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", 2584 x,psp->rhs[psp->nrhs-1]->name); 2585 psp->errorcnt++; 2586 psp->state = RESYNC_AFTER_RULE_ERROR; 2587 } 2588 break; 2589 case RHS_ALIAS_2: 2590 if( x[0]==')' ){ 2591 psp->state = IN_RHS; 2592 }else{ 2593 ErrorMsg(psp->filename,psp->tokenlineno, 2594 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); 2595 psp->errorcnt++; 2596 psp->state = RESYNC_AFTER_RULE_ERROR; 2597 } 2598 break; 2599 case WAITING_FOR_DECL_KEYWORD: 2600 if( ISALPHA(x[0]) ){ 2601 psp->declkeyword = x; 2602 psp->declargslot = 0; 2603 psp->decllinenoslot = 0; 2604 psp->insertLineMacro = 1; 2605 psp->state = WAITING_FOR_DECL_ARG; 2606 if( strcmp(x,"name")==0 ){ 2607 psp->declargslot = &(psp->gp->name); 2608 psp->insertLineMacro = 0; 2609 }else if( strcmp(x,"include")==0 ){ 2610 psp->declargslot = &(psp->gp->include); 2611 }else if( strcmp(x,"code")==0 ){ 2612 psp->declargslot = &(psp->gp->extracode); 2613 }else if( strcmp(x,"token_destructor")==0 ){ 2614 psp->declargslot = &psp->gp->tokendest; 2615 }else if( strcmp(x,"default_destructor")==0 ){ 2616 psp->declargslot = &psp->gp->vardest; 2617 }else if( strcmp(x,"token_prefix")==0 ){ 2618 psp->declargslot = &psp->gp->tokenprefix; 2619 psp->insertLineMacro = 0; 2620 }else if( strcmp(x,"syntax_error")==0 ){ 2621 psp->declargslot = &(psp->gp->error); 2622 }else if( strcmp(x,"parse_accept")==0 ){ 2623 psp->declargslot = &(psp->gp->accept); 2624 }else if( strcmp(x,"parse_failure")==0 ){ 2625 psp->declargslot = &(psp->gp->failure); 2626 }else if( strcmp(x,"stack_overflow")==0 ){ 2627 psp->declargslot = &(psp->gp->overflow); 2628 }else if( strcmp(x,"extra_argument")==0 ){ 2629 psp->declargslot = &(psp->gp->arg); 2630 psp->insertLineMacro = 0; 2631 }else if( strcmp(x,"extra_context")==0 ){ 2632 psp->declargslot = &(psp->gp->ctx); 2633 psp->insertLineMacro = 0; 2634 }else if( strcmp(x,"token_type")==0 ){ 2635 psp->declargslot = &(psp->gp->tokentype); 2636 psp->insertLineMacro = 0; 2637 }else if( strcmp(x,"default_type")==0 ){ 2638 psp->declargslot = &(psp->gp->vartype); 2639 psp->insertLineMacro = 0; 2640 }else if( strcmp(x,"stack_size_limit")==0 ){ 2641 psp->declargslot = &(psp->gp->stackSizeLimit); 2642 psp->insertLineMacro = 0; 2643 }else if( strcmp(x,"realloc")==0 ){ 2644 psp->declargslot = &(psp->gp->reallocFunc); 2645 psp->insertLineMacro = 0; 2646 }else if( strcmp(x,"free")==0 ){ 2647 psp->declargslot = &(psp->gp->freeFunc); 2648 psp->insertLineMacro = 0; 2649 }else if( strcmp(x,"stack_size")==0 ){ 2650 psp->declargslot = &(psp->gp->stacksize); 2651 psp->insertLineMacro = 0; 2652 }else if( strcmp(x,"start_symbol")==0 ){ 2653 psp->declargslot = &(psp->gp->start); 2654 psp->insertLineMacro = 0; 2655 }else if( strcmp(x,"left")==0 ){ 2656 psp->preccounter++; 2657 psp->declassoc = LEFT; 2658 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; 2659 }else if( strcmp(x,"right")==0 ){ 2660 psp->preccounter++; 2661 psp->declassoc = RIGHT; 2662 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; 2663 }else if( strcmp(x,"nonassoc")==0 ){ 2664 psp->preccounter++; 2665 psp->declassoc = NONE; 2666 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; 2667 }else if( strcmp(x,"destructor")==0 ){ 2668 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL; 2669 }else if( strcmp(x,"type")==0 ){ 2670 psp->state = WAITING_FOR_DATATYPE_SYMBOL; 2671 }else if( strcmp(x,"fallback")==0 ){ 2672 psp->fallback = 0; 2673 psp->state = WAITING_FOR_FALLBACK_ID; 2674 }else if( strcmp(x,"token")==0 ){ 2675 psp->state = WAITING_FOR_TOKEN_NAME; 2676 }else if( strcmp(x,"wildcard")==0 ){ 2677 psp->state = WAITING_FOR_WILDCARD_ID; 2678 }else if( strcmp(x,"token_class")==0 ){ 2679 psp->state = WAITING_FOR_CLASS_ID; 2680 }else{ 2681 ErrorMsg(psp->filename,psp->tokenlineno, 2682 "Unknown declaration keyword: \"%%%s\".",x); 2683 psp->errorcnt++; 2684 psp->state = RESYNC_AFTER_DECL_ERROR; 2685 } 2686 }else{ 2687 ErrorMsg(psp->filename,psp->tokenlineno, 2688 "Illegal declaration keyword: \"%s\".",x); 2689 psp->errorcnt++; 2690 psp->state = RESYNC_AFTER_DECL_ERROR; 2691 } 2692 break; 2693 case WAITING_FOR_DESTRUCTOR_SYMBOL: 2694 if( !ISALPHA(x[0]) ){ 2695 ErrorMsg(psp->filename,psp->tokenlineno, 2696 "Symbol name missing after %%destructor keyword"); 2697 psp->errorcnt++; 2698 psp->state = RESYNC_AFTER_DECL_ERROR; 2699 }else{ 2700 struct symbol *sp = Symbol_new(x); 2701 psp->declargslot = &sp->destructor; 2702 psp->decllinenoslot = &sp->destLineno; 2703 psp->insertLineMacro = 1; 2704 psp->state = WAITING_FOR_DECL_ARG; 2705 } 2706 break; 2707 case WAITING_FOR_DATATYPE_SYMBOL: 2708 if( !ISALPHA(x[0]) ){ 2709 ErrorMsg(psp->filename,psp->tokenlineno, 2710 "Symbol name missing after %%type keyword"); 2711 psp->errorcnt++; 2712 psp->state = RESYNC_AFTER_DECL_ERROR; 2713 }else{ 2714 struct symbol *sp = Symbol_find(x); 2715 if((sp) && (sp->datatype)){ 2716 ErrorMsg(psp->filename,psp->tokenlineno, 2717 "Symbol %%type \"%s\" already defined", x); 2718 psp->errorcnt++; 2719 psp->state = RESYNC_AFTER_DECL_ERROR; 2720 }else{ 2721 if (!sp){ 2722 sp = Symbol_new(x); 2723 } 2724 psp->declargslot = &sp->datatype; 2725 psp->insertLineMacro = 0; 2726 psp->state = WAITING_FOR_DECL_ARG; 2727 } 2728 } 2729 break; 2730 case WAITING_FOR_PRECEDENCE_SYMBOL: 2731 if( x[0]=='.' ){ 2732 psp->state = WAITING_FOR_DECL_OR_RULE; 2733 }else if( ISUPPER(x[0]) ){ 2734 struct symbol *sp; 2735 sp = Symbol_new(x); 2736 if( sp->prec>=0 ){ 2737 ErrorMsg(psp->filename,psp->tokenlineno, 2738 "Symbol \"%s\" has already be given a precedence.",x); 2739 psp->errorcnt++; 2740 }else{ 2741 sp->prec = psp->preccounter; 2742 sp->assoc = psp->declassoc; 2743 } 2744 }else{ 2745 ErrorMsg(psp->filename,psp->tokenlineno, 2746 "Can't assign a precedence to \"%s\".",x); 2747 psp->errorcnt++; 2748 } 2749 break; 2750 case WAITING_FOR_DECL_ARG: 2751 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){ 2752 const char *zOld, *zNew; 2753 char *zBuf, *z; 2754 int nOld, n, nLine = 0, nNew, nBack; 2755 int addLineMacro; 2756 char zLine[50]; 2757 zNew = x; 2758 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++; 2759 nNew = lemonStrlen(zNew); 2760 if( *psp->declargslot ){ 2761 zOld = *psp->declargslot; 2762 }else{ 2763 zOld = ""; 2764 } 2765 nOld = lemonStrlen(zOld); 2766 n = nOld + nNew + 20; 2767 addLineMacro = !psp->gp->nolinenosflag 2768 && psp->insertLineMacro 2769 && psp->tokenlineno>1 2770 && (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0); 2771 if( addLineMacro ){ 2772 for(z=psp->filename, nBack=0; *z; z++){ 2773 if( *z=='\\' ) nBack++; 2774 } 2775 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno); 2776 nLine = lemonStrlen(zLine); 2777 n += nLine + lemonStrlen(psp->filename) + nBack; 2778 } 2779 *psp->declargslot = (char *) lemon_realloc(*psp->declargslot, n); 2780 zBuf = *psp->declargslot + nOld; 2781 if( addLineMacro ){ 2782 if( nOld && zBuf[-1]!='\n' ){ 2783 *(zBuf++) = '\n'; 2784 } 2785 memcpy(zBuf, zLine, nLine); 2786 zBuf += nLine; 2787 *(zBuf++) = '"'; 2788 for(z=psp->filename; *z; z++){ 2789 if( *z=='\\' ){ 2790 *(zBuf++) = '\\'; 2791 } 2792 *(zBuf++) = *z; 2793 } 2794 *(zBuf++) = '"'; 2795 *(zBuf++) = '\n'; 2796 } 2797 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){ 2798 psp->decllinenoslot[0] = psp->tokenlineno; 2799 } 2800 memcpy(zBuf, zNew, nNew); 2801 zBuf += nNew; 2802 *zBuf = 0; 2803 psp->state = WAITING_FOR_DECL_OR_RULE; 2804 }else{ 2805 ErrorMsg(psp->filename,psp->tokenlineno, 2806 "Illegal argument to %%%s: %s",psp->declkeyword,x); 2807 psp->errorcnt++; 2808 psp->state = RESYNC_AFTER_DECL_ERROR; 2809 } 2810 break; 2811 case WAITING_FOR_FALLBACK_ID: 2812 if( x[0]=='.' ){ 2813 psp->state = WAITING_FOR_DECL_OR_RULE; 2814 }else if( !ISUPPER(x[0]) ){ 2815 ErrorMsg(psp->filename, psp->tokenlineno, 2816 "%%fallback argument \"%s\" should be a token", x); 2817 psp->errorcnt++; 2818 }else{ 2819 struct symbol *sp = Symbol_new(x); 2820 if( psp->fallback==0 ){ 2821 psp->fallback = sp; 2822 }else if( sp->fallback ){ 2823 ErrorMsg(psp->filename, psp->tokenlineno, 2824 "More than one fallback assigned to token %s", x); 2825 psp->errorcnt++; 2826 }else{ 2827 sp->fallback = psp->fallback; 2828 psp->gp->has_fallback = 1; 2829 } 2830 } 2831 break; 2832 case WAITING_FOR_TOKEN_NAME: 2833 /* Tokens do not have to be declared before use. But they can be 2834 ** in order to control their assigned integer number. The number for 2835 ** each token is assigned when it is first seen. So by including 2836 ** 2837 ** %token ONE TWO THREE. 2838 ** 2839 ** early in the grammar file, that assigns small consecutive values 2840 ** to each of the tokens ONE TWO and THREE. 2841 */ 2842 if( x[0]=='.' ){ 2843 psp->state = WAITING_FOR_DECL_OR_RULE; 2844 }else if( !ISUPPER(x[0]) ){ 2845 ErrorMsg(psp->filename, psp->tokenlineno, 2846 "%%token argument \"%s\" should be a token", x); 2847 psp->errorcnt++; 2848 }else{ 2849 (void)Symbol_new(x); 2850 } 2851 break; 2852 case WAITING_FOR_WILDCARD_ID: 2853 if( x[0]=='.' ){ 2854 psp->state = WAITING_FOR_DECL_OR_RULE; 2855 }else if( !ISUPPER(x[0]) ){ 2856 ErrorMsg(psp->filename, psp->tokenlineno, 2857 "%%wildcard argument \"%s\" should be a token", x); 2858 psp->errorcnt++; 2859 }else{ 2860 struct symbol *sp = Symbol_new(x); 2861 if( psp->gp->wildcard==0 ){ 2862 psp->gp->wildcard = sp; 2863 }else{ 2864 ErrorMsg(psp->filename, psp->tokenlineno, 2865 "Extra wildcard to token: %s", x); 2866 psp->errorcnt++; 2867 } 2868 } 2869 break; 2870 case WAITING_FOR_CLASS_ID: 2871 if( !ISLOWER(x[0]) ){ 2872 ErrorMsg(psp->filename, psp->tokenlineno, 2873 "%%token_class must be followed by an identifier: %s", x); 2874 psp->errorcnt++; 2875 psp->state = RESYNC_AFTER_DECL_ERROR; 2876 }else if( Symbol_find(x) ){ 2877 ErrorMsg(psp->filename, psp->tokenlineno, 2878 "Symbol \"%s\" already used", x); 2879 psp->errorcnt++; 2880 psp->state = RESYNC_AFTER_DECL_ERROR; 2881 }else{ 2882 psp->tkclass = Symbol_new(x); 2883 psp->tkclass->type = MULTITERMINAL; 2884 psp->state = WAITING_FOR_CLASS_TOKEN; 2885 } 2886 break; 2887 case WAITING_FOR_CLASS_TOKEN: 2888 if( x[0]=='.' ){ 2889 psp->state = WAITING_FOR_DECL_OR_RULE; 2890 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){ 2891 struct symbol *msp = psp->tkclass; 2892 msp->nsubsym++; 2893 msp->subsym = (struct symbol **) lemon_realloc(msp->subsym, 2894 sizeof(struct symbol*)*msp->nsubsym); 2895 if( !ISUPPER(x[0]) ) x++; 2896 msp->subsym[msp->nsubsym-1] = Symbol_new(x); 2897 }else{ 2898 ErrorMsg(psp->filename, psp->tokenlineno, 2899 "%%token_class argument \"%s\" should be a token", x); 2900 psp->errorcnt++; 2901 psp->state = RESYNC_AFTER_DECL_ERROR; 2902 } 2903 break; 2904 case RESYNC_AFTER_RULE_ERROR: 2905 /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; 2906 ** break; */ 2907 case RESYNC_AFTER_DECL_ERROR: 2908 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; 2909 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD; 2910 break; 2911 } 2912 } 2913 2914 /* The text in the input is part of the argument to an %ifdef or %ifndef. 2915 ** Evaluate the text as a boolean expression. Return true or false. 2916 */ 2917 static int eval_preprocessor_boolean(char *z, int lineno){ 2918 int neg = 0; 2919 int res = 0; 2920 int okTerm = 1; 2921 int i; 2922 for(i=0; z[i]!=0; i++){ 2923 if( ISSPACE(z[i]) ) continue; 2924 if( z[i]=='!' ){ 2925 if( !okTerm ) goto pp_syntax_error; 2926 neg = !neg; 2927 continue; 2928 } 2929 if( z[i]=='|' && z[i+1]=='|' ){ 2930 if( okTerm ) goto pp_syntax_error; 2931 if( res ) return 1; 2932 i++; 2933 okTerm = 1; 2934 continue; 2935 } 2936 if( z[i]=='&' && z[i+1]=='&' ){ 2937 if( okTerm ) goto pp_syntax_error; 2938 if( !res ) return 0; 2939 i++; 2940 okTerm = 1; 2941 continue; 2942 } 2943 if( z[i]=='(' ){ 2944 int k; 2945 int n = 1; 2946 if( !okTerm ) goto pp_syntax_error; 2947 for(k=i+1; z[k]; k++){ 2948 if( z[k]==')' ){ 2949 n--; 2950 if( n==0 ){ 2951 z[k] = 0; 2952 res = eval_preprocessor_boolean(&z[i+1], -1); 2953 z[k] = ')'; 2954 if( res<0 ){ 2955 i = i-res; 2956 goto pp_syntax_error; 2957 } 2958 i = k; 2959 break; 2960 } 2961 }else if( z[k]=='(' ){ 2962 n++; 2963 }else if( z[k]==0 ){ 2964 i = k; 2965 goto pp_syntax_error; 2966 } 2967 } 2968 if( neg ){ 2969 res = !res; 2970 neg = 0; 2971 } 2972 okTerm = 0; 2973 continue; 2974 } 2975 if( ISALPHA(z[i]) ){ 2976 int j, k, n; 2977 if( !okTerm ) goto pp_syntax_error; 2978 for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){} 2979 n = k - i; 2980 res = 0; 2981 for(j=0; j0 ){ 3005 fprintf(stderr, "%%if syntax error on line %d.\n", lineno); 3006 fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z); 3007 exit(1); 3008 }else{ 3009 return -(i+1); 3010 } 3011 } 3012 3013 /* Run the preprocessor over the input file text. The global variables 3014 ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined 3015 ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and 3016 ** comments them out. Text in between is also commented out as appropriate. 3017 */ 3018 static void preprocess_input(char *z){ 3019 int i, j, k; 3020 int exclude = 0; 3021 int start = 0; 3022 int lineno = 1; 3023 int start_lineno = 1; 3024 for(i=0; z[i]; i++){ 3025 if( z[i]=='\n' ) lineno++; 3026 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue; 3027 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){ 3028 if( exclude ){ 3029 exclude--; 3030 if( exclude==0 ){ 3031 for(j=start; jfilename; 3095 ps.errorcnt = 0; 3096 ps.state = INITIALIZE; 3097 3098 /* Begin by reading the input file */ 3099 fp = fopen(ps.filename,"rb"); 3100 if( fp==0 ){ 3101 ErrorMsg(ps.filename,0,"Can't open this file for reading."); 3102 gp->errorcnt++; 3103 return; 3104 } 3105 fseek(fp,0,2); 3106 filesize = ftell(fp); 3107 rewind(fp); 3108 filebuf = (char *)lemon_malloc( filesize+1 ); 3109 if( filesize>`100000000` || filebuf==0 ){ 3110 ErrorMsg(ps.filename,0,"Input file too large."); 3111 lemon_free(filebuf); 3112 gp->errorcnt++; 3113 fclose(fp); 3114 return; 3115 } 3116 if( fread(filebuf,1,filesize,fp)!=filesize ){ 3117 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.", 3118 filesize); 3119 lemon_free(filebuf); 3120 gp->errorcnt++; 3121 fclose(fp); 3122 return; 3123 } 3124 fclose(fp); 3125 filebuf[filesize] = 0; 3126 3127 /* Make an initial pass through the file to handle %ifdef and %ifndef */ 3128 preprocess_input(filebuf); 3129 if( gp->printPreprocessed ){ 3130 printf("%s\n", filebuf); 3131 return; 3132 } 3133 3134 /* Now scan the text of the input file */ 3135 lineno = 1; 3136 for(cp=filebuf; (c= *cp)!=0; ){ 3137 if( c=='\n' ) lineno++; /* Keep track of the line number */ 3138 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */ 3139 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */ 3140 cp+=2; 3141 while( (c= *cp)!=0 && c!='\n' ) cp++; 3142 continue; 3143 } 3144 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */ 3145 cp+=2; 3146 if( (*cp)=='/' ) cp++; 3147 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){ 3148 if( c=='\n' ) lineno++; 3149 cp++; 3150 } 3151 if( c ) cp++; 3152 continue; 3153 } 3154 ps.tokenstart = cp; /* Mark the beginning of the token */ 3155 ps.tokenlineno = lineno; /* Linenumber on which token begins */ 3156 if( c=='\"' ){ /* String literals */ 3157 cp++; 3158 while( (c= *cp)!=0 && c!='\"' ){ 3159 if( c=='\n' ) lineno++; 3160 cp++; 3161 } 3162 if( c==0 ){ 3163 ErrorMsg(ps.filename,startline, 3164 "String starting on this line is not terminated before " 3165 "the end of the file."); 3166 ps.errorcnt++; 3167 nextcp = cp; 3168 }else{ 3169 nextcp = cp+1; 3170 } 3171 }else if( c=='{' ){ /* A block of C code */ 3172 int level; 3173 cp++; 3174 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){ 3175 if( c=='\n' ) lineno++; 3176 else if( c=='{' ) level++; 3177 else if( c=='}' ) level--; 3178 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */ 3179 int prevc; 3180 cp = &cp[2]; 3181 prevc = 0; 3182 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){ 3183 if( c=='\n' ) lineno++; 3184 prevc = c; 3185 cp++; 3186 } 3187 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */ 3188 cp = &cp[2]; 3189 while( (c= *cp)!=0 && c!='\n' ) cp++; 3190 if( c ) lineno++; 3191 }else if( c=='\'' || c=='\"' ){ /* String a character literals */ 3192 int startchar, prevc; 3193 startchar = c; 3194 prevc = 0; 3195 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){ 3196 if( c=='\n' ) lineno++; 3197 if( prevc=='\\' ) prevc = 0; 3198 else prevc = c; 3199 } 3200 } 3201 } 3202 if( c==0 ){ 3203 ErrorMsg(ps.filename,ps.tokenlineno, 3204 "C code starting on this line is not terminated before " 3205 "the end of the file."); 3206 ps.errorcnt++; 3207 nextcp = cp; 3208 }else{ 3209 nextcp = cp+1; 3210 } 3211 }else if( ISALNUM(c) ){ /* Identifiers */ 3212 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++; 3213 nextcp = cp; 3214 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */ 3215 cp += 3; 3216 nextcp = cp; 3217 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){ 3218 cp += 2; 3219 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++; 3220 nextcp = cp; 3221 }else{ /* All other (one character) operators */ 3222 cp++; 3223 nextcp = cp; 3224 } 3225 c = *cp; 3226 *cp = 0; /* Null terminate the token */ 3227 parseonetoken(&ps); /* Parse the token */ 3228 *cp = (char)c; /* Restore the buffer */ 3229 cp = nextcp; 3230 } 3231 lemon_free(filebuf); /* Release the buffer after parsing */ 3232 gp->rule = ps.firstrule; 3233 gp->errorcnt = ps.errorcnt; 3234 } 3235 /*************************** From the file "plink.c" *********************/ 3236 /* 3237 ** Routines processing configuration follow-set propagation links 3238 ** in the LEMON parser generator. 3239 */ 3240 static struct plink *plink_freelist = 0; 3241 3242 /* Allocate a new plink */ 3243 struct plink *Plink_new(void){ 3244 struct plink *newlink; 3245 3246 if( plink_freelist==0 ){ 3247 int i; 3248 int amt = 100; 3249 plink_freelist = (struct plink *)lemon_calloc( amt, sizeof(struct plink) ); 3250 if( plink_freelist==0 ){ 3251 fprintf(stderr, 3252 "Unable to allocate memory for a new follow-set propagation link.\n"); 3253 exit(1); 3254 } 3255 for(i=0; inext; 3260 return newlink; 3261 } 3262 3263 /* Add a plink to a plink list */ 3264 void Plink_add(struct plink **plpp, struct config *cfp) 3265 { 3266 struct plink *newlink; 3267 newlink = Plink_new(); 3268 newlink->next = *plpp; 3269 *plpp = newlink; 3270 newlink->cfp = cfp; 3271 } 3272 3273 /* Transfer every plink on the list "from" to the list "to" */ 3274 void Plink_copy(struct plink **to, struct plink *from) 3275 { 3276 struct plink *nextpl; 3277 while( from ){ 3278 nextpl = from->next; 3279 from->next = *to; 3280 *to = from; 3281 from = nextpl; 3282 } 3283 } 3284 3285 /* Delete every plink on the list */ 3286 void Plink_delete(struct plink *plp) 3287 { 3288 struct plink *nextpl; 3289 3290 while( plp ){ 3291 nextpl = plp->next; 3292 plp->next = plink_freelist; 3293 plink_freelist = plp; 3294 plp = nextpl; 3295 } 3296 } 3297 /*********************** From the file "report.c" **************************/ 3298 /* 3299 ** Procedures for generating reports and tables in the LEMON parser generator. 3300 */ 3301 3302 /* Generate a filename with the given suffix. 3303 */ 3304 PRIVATE char *file_makename(struct lemon *lemp, const char *suffix) 3305 { 3306 char *name; 3307 char *cp; 3308 char *filename = lemp->filename; 3309 int sz; 3310 3311 if( outputDir ){ 3312 cp = strrchr(filename, '/'); 3313 if( cp ) filename = cp + 1; 3314 } 3315 sz = lemonStrlen(filename); 3316 sz += lemonStrlen(suffix); 3317 if( outputDir ) sz += lemonStrlen(outputDir) + 1; 3318 sz += 5; 3319 name = (char*)lemon_malloc( sz ); 3320 if( name==0 ){ 3321 fprintf(stderr,"Can't allocate space for a filename.\n"); 3322 exit(1); 3323 } 3324 name[0] = 0; 3325 if( outputDir ){ 3326 lemon_strcpy(name, outputDir); 3327 lemon_strcat(name, "/"); 3328 } 3329 lemon_strcat(name,filename); 3330 cp = strrchr(name,'.'); 3331 if( cp ) *cp = 0; 3332 lemon_strcat(name,suffix); 3333 return name; 3334 } 3335 3336 /* Open a file with a name based on the name of the input file, 3337 ** but with a different (specified) suffix, and return a pointer 3338 ** to the stream */ 3339 PRIVATE FILE *file_open( 3340 struct lemon *lemp, 3341 const char *suffix, 3342 const char *mode 3343 ){ 3344 FILE *fp; 3345 3346 if( lemp->outname ) lemon_free(lemp->outname); 3347 lemp->outname = file_makename(lemp, suffix); 3348 fp = fopen(lemp->outname,mode); 3349 if( fp==0 && *mode=='w' ){ 3350 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname); 3351 lemp->errorcnt++; 3352 return 0; 3353 } 3354 return fp; 3355 } 3356 3357 /* Print the text of a rule 3358 */ 3359 void rule_print(FILE *out, struct rule *rp){ 3360 int i, j; 3361 fprintf(out, "%s",rp->lhs->name); 3362 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */ 3363 fprintf(out," ::="); 3364 for(i=0; inrhs; i++){ 3365 struct symbol *sp = rp->rhs[i]; 3366 if( sp->type==MULTITERMINAL ){ 3367 fprintf(out," %s", sp->subsym[0]->name); 3368 for(j=1; jnsubsym; j++){ 3369 fprintf(out,"|%s", sp->subsym[j]->name); 3370 } 3371 }else{ 3372 fprintf(out," %s", sp->name); 3373 } 3374 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */ 3375 } 3376 } 3377 3378 /* Duplicate the input file without comments and without actions 3379 ** on rules */ 3380 void Reprint(struct lemon *lemp) 3381 { 3382 struct rule *rp; 3383 struct symbol *sp; 3384 int i, j, maxlen, len, ncolumns, skip; 3385 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename); 3386 maxlen = 10; 3387 for(i=0; insymbol; i++){ 3388 sp = lemp->symbols[i]; 3389 len = lemonStrlen(sp->name); 3390 if( len>maxlen ) maxlen = len; 3391 } 3392 ncolumns = 76/(maxlen+5); 3393 if( ncolumns<1 ) ncolumns = 1; 3394 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns; 3395 for(i=0; insymbol; j+=skip){ 3398 sp = lemp->symbols[j]; 3399 assert( sp->index==j ); 3400 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name); 3401 } 3402 printf("\n"); 3403 } 3404 for(rp=lemp->rule; rp; rp=rp->next){ 3405 rule_print(stdout, rp); 3406 printf("."); 3407 if( rp->precsym ) printf(" [%s]",rp->precsym->name); 3408 /* if( rp->code ) printf("\n %s",rp->code); */ 3409 printf("\n"); 3410 } 3411 } 3412 3413 /* Print a single rule. 3414 */ 3415 void RulePrint(FILE *fp, struct rule *rp, int iCursor){ 3416 struct symbol *sp; 3417 int i, j; 3418 fprintf(fp,"%s ::=",rp->lhs->name); 3419 for(i=0; i<=rp->nrhs; i++){ 3420 if( i==iCursor ) fprintf(fp," *"); 3421 if( i==rp->nrhs ) break; 3422 sp = rp->rhs[i]; 3423 if( sp->type==MULTITERMINAL ){ 3424 fprintf(fp," %s", sp->subsym[0]->name); 3425 for(j=1; jnsubsym; j++){ 3426 fprintf(fp,"|%s",sp->subsym[j]->name); 3427 } 3428 }else{ 3429 fprintf(fp," %s", sp->name); 3430 } 3431 } 3432 } 3433 3434 /* Print the rule for a configuration. 3435 */ 3436 void ConfigPrint(FILE *fp, struct config *cfp){ 3437 RulePrint(fp, cfp->rp, cfp->dot); 3438 } 3439 3440 /* #define TEST */ 3441 #if 0 3442 /* Print a set */ 3443 PRIVATE void SetPrint(out,set,lemp) 3444 FILE *out; 3445 char *set; 3446 struct lemon *lemp; 3447 { 3448 int i; 3449 char *spacer; 3450 spacer = ""; 3451 fprintf(out,"%12s[",""); 3452 for(i=0; interminal; i++){ 3453 if( SetFind(set,i) ){ 3454 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name); 3455 spacer = " "; 3456 } 3457 } 3458 fprintf(out,"]\n"); 3459 } 3460 3461 /* Print a plink chain */ 3462 PRIVATE void PlinkPrint(out,plp,tag) 3463 FILE *out; 3464 struct plink *plp; 3465 char *tag; 3466 { 3467 while( plp ){ 3468 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum); 3469 ConfigPrint(out,plp->cfp); 3470 fprintf(out,"\n"); 3471 plp = plp->next; 3472 } 3473 } 3474 #endif 3475 3476 /* Print an action to the given file descriptor. Return FALSE if 3477 ** nothing was actually printed. 3478 */ 3479 int PrintAction( 3480 struct action *ap, /* The action to print */ 3481 FILE *fp, /* Print the action here */ 3482 int indent /* Indent by this amount */ 3483 ){ 3484 int result = 1; 3485 switch( ap->type ){ 3486 case SHIFT: { 3487 struct state *stp = ap->x.stp; 3488 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum); 3489 break; 3490 } 3491 case REDUCE: { 3492 struct rule *rp = ap->x.rp; 3493 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule); 3494 RulePrint(fp, rp, -1); 3495 break; 3496 } 3497 case SHIFTREDUCE: { 3498 struct rule *rp = ap->x.rp; 3499 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule); 3500 RulePrint(fp, rp, -1); 3501 break; 3502 } 3503 case ACCEPT: 3504 fprintf(fp,"%*s accept",indent,ap->sp->name); 3505 break; 3506 case ERROR: 3507 fprintf(fp,"%*s error",indent,ap->sp->name); 3508 break; 3509 case SRCONFLICT: 3510 case RRCONFLICT: 3511 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **", 3512 indent,ap->sp->name,ap->x.rp->iRule); 3513 break; 3514 case SSCONFLICT: 3515 fprintf(fp,"%*s shift %-7d ** Parsing conflict **", 3516 indent,ap->sp->name,ap->x.stp->statenum); 3517 break; 3518 case SH_RESOLVED: 3519 if( showPrecedenceConflict ){ 3520 fprintf(fp,"%*s shift %-7d -- dropped by precedence", 3521 indent,ap->sp->name,ap->x.stp->statenum); 3522 }else{ 3523 result = 0; 3524 } 3525 break; 3526 case RD_RESOLVED: 3527 if( showPrecedenceConflict ){ 3528 fprintf(fp,"%*s reduce %-7d -- dropped by precedence", 3529 indent,ap->sp->name,ap->x.rp->iRule); 3530 }else{ 3531 result = 0; 3532 } 3533 break; 3534 case NOT_USED: 3535 result = 0; 3536 break; 3537 } 3538 if( result && ap->spOpt ){ 3539 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name); 3540 } 3541 return result; 3542 } 3543 3544 /* Generate the "*.out" log file */ 3545 void ReportOutput(struct lemon *lemp) 3546 { 3547 int i, n; 3548 struct state *stp; 3549 struct config *cfp; 3550 struct action *ap; 3551 struct rule *rp; 3552 FILE *fp; 3553 3554 fp = file_open(lemp,".out","wb"); 3555 if( fp==0 ) return; 3556 for(i=0; inxstate; i++){ 3557 stp = lemp->sorted[i]; 3558 fprintf(fp,"State %d:\n",stp->statenum); 3559 if( lemp->basisflag ) cfp=stp->bp; 3560 else cfp=stp->cfp; 3561 while( cfp ){ 3562 char buf[20]; 3563 if( cfp->dot==cfp->rp->nrhs ){ 3564 lemon_sprintf(buf,"(%d)",cfp->rp->iRule); 3565 fprintf(fp," %5s ",buf); 3566 }else{ 3567 fprintf(fp," "); 3568 } 3569 ConfigPrint(fp,cfp); 3570 fprintf(fp,"\n"); 3571 #if 0 3572 SetPrint(fp,cfp->fws,lemp); 3573 PlinkPrint(fp,cfp->fplp,"To "); 3574 PlinkPrint(fp,cfp->bplp,"From"); 3575 #endif 3576 if( lemp->basisflag ) cfp=cfp->bp; 3577 else cfp=cfp->next; 3578 } 3579 fprintf(fp,"\n"); 3580 for(ap=stp->ap; ap; ap=ap->next){ 3581 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n"); 3582 } 3583 fprintf(fp,"\n"); 3584 } 3585 fprintf(fp, "----------------------------------------------------\n"); 3586 fprintf(fp, "Symbols:\n"); 3587 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n"); 3588 for(i=0; insymbol; i++){ 3589 int j; 3590 struct symbol *sp; 3591 3592 sp = lemp->symbols[i]; 3593 fprintf(fp, " %3d: %s", i, sp->name); 3594 if( sp->type==NONTERMINAL ){ 3595 fprintf(fp, ":"); 3596 if( sp->lambda ){ 3597 fprintf(fp, " "); 3598 } 3599 for(j=0; jnterminal; j++){ 3600 if( sp->firstset && SetFind(sp->firstset, j) ){ 3601 fprintf(fp, " %s", lemp->symbols[j]->name); 3602 } 3603 } 3604 } 3605 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec); 3606 fprintf(fp, "\n"); 3607 } 3608 fprintf(fp, "----------------------------------------------------\n"); 3609 fprintf(fp, "Syntax-only Symbols:\n"); 3610 fprintf(fp, "The following symbols never carry semantic content.\n\n"); 3611 for(i=n=0; insymbol; i++){ 3612 int w; 3613 struct symbol *sp = lemp->symbols[i]; 3614 if( sp->bContent ) continue; 3615 w = (int)strlen(sp->name); 3616 if( n>0 && n+w>75 ){ 3617 fprintf(fp,"\n"); 3618 n = 0; 3619 } 3620 if( n>0 ){ 3621 fprintf(fp, " "); 3622 n++; 3623 } 3624 fprintf(fp, "%s", sp->name); 3625 n += w; 3626 } 3627 if( n>0 ) fprintf(fp, "\n"); 3628 fprintf(fp, "----------------------------------------------------\n"); 3629 fprintf(fp, "Rules:\n"); 3630 for(rp=lemp->rule; rp; rp=rp->next){ 3631 fprintf(fp, "%4d: ", rp->iRule); 3632 rule_print(fp, rp); 3633 fprintf(fp,"."); 3634 if( rp->precsym ){ 3635 fprintf(fp," [%s precedence=%d]", 3636 rp->precsym->name, rp->precsym->prec); 3637 } 3638 fprintf(fp,"\n"); 3639 } 3640 fclose(fp); 3641 return; 3642 } 3643 3644 /* Search for the file "name" which is in the same directory as 3645 ** the executable */ 3646 PRIVATE char *pathsearch(char *argv0, char *name, int modemask) 3647 { 3648 const char *pathlist; 3649 char *pathbufptr = 0; 3650 char *pathbuf = 0; 3651 char *path,*cp; 3652 char c; 3653 3654 #ifdef __WIN32__ 3655 cp = strrchr(argv0,'\\'); 3656 #else 3657 cp = strrchr(argv0,'/'); 3658 #endif 3659 if( cp ){ 3660 c = *cp; 3661 *cp = 0; 3662 path = (char *)lemon_malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 ); 3663 if( path ) lemon_sprintf(path,"%s/%s",argv0,name); 3664 *cp = c; 3665 }else{ 3666 pathlist = getenv("PATH"); 3667 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; 3668 pathbuf = (char *) lemon_malloc( lemonStrlen(pathlist) + 1 ); 3669 path = (char *)lemon_malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 ); 3670 if( (pathbuf != 0) && (path!=0) ){ 3671 pathbufptr = pathbuf; 3672 lemon_strcpy(pathbuf, pathlist); 3673 while( *pathbuf ){ 3674 cp = strchr(pathbuf,':'); 3675 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)]; 3676 c = *cp; 3677 *cp = 0; 3678 lemon_sprintf(path,"%s/%s",pathbuf,name); 3679 *cp = c; 3680 if( c==0 ) pathbuf[0] = 0; 3681 else pathbuf = &cp[1]; 3682 if( access(path,modemask)==0 ) break; 3683 } 3684 } 3685 lemon_free(pathbufptr); 3686 } 3687 return path; 3688 } 3689 3690 /* Given an action, compute the integer value for that action 3691 ** which is to be put in the action table of the generated machine. 3692 ** Return negative if no action should be generated. 3693 */ 3694 PRIVATE int compute_action(struct lemon *lemp, struct action *ap) 3695 { 3696 int act; 3697 switch( ap->type ){ 3698 case SHIFT: act = ap->x.stp->statenum; break; 3699 case SHIFTREDUCE: { 3700 /* Since a SHIFT is inherent after a prior REDUCE, convert any 3701 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple 3702 ** REDUCE action: */ 3703 if( ap->sp->index>=lemp->nterminal 3704 && (lemp->errsym==0 || ap->sp->index!=lemp->errsym->index) 3705 ){ 3706 act = lemp->minReduce + ap->x.rp->iRule; 3707 }else{ 3708 act = lemp->minShiftReduce + ap->x.rp->iRule; 3709 } 3710 break; 3711 } 3712 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break; 3713 case ERROR: act = lemp->errAction; break; 3714 case ACCEPT: act = lemp->accAction; break; 3715 default: act = -1; break; 3716 } 3717 return act; 3718 } 3719 3720 #define LINESIZE 10000 3721 /* The next cluster of routines are for reading the template file 3722 ** and writing the results to the generated parser */ 3723 /* The first function transfers data from "in" to "out" until 3724 ** a line is seen which begins with "%%". The line number is 3725 ** tracked. 3726 ** 3727 ** if name!=0, then any word that begin with "Parse" is changed to 3728 ** begin with *name instead. 3729 */ 3730 PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno) 3731 { 3732 int i, iStart; 3733 char line[LINESIZE]; 3734 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){ 3735 (*lineno)++; 3736 iStart = 0; 3737 if( name ){ 3738 for(i=0; line[i]; i++){ 3739 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0 3740 && (i==0 || !ISALPHA(line[i-1])) 3741 ){ 3742 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]); 3743 fprintf(out,"%s",name); 3744 i += 4; 3745 iStart = i+1; 3746 } 3747 } 3748 } 3749 fprintf(out,"%s",&line[iStart]); 3750 } 3751 } 3752 3753 /* Skip forward past the header of the template file to the first "%%" 3754 */ 3755 PRIVATE void tplt_skip_header(FILE *in){ 3756 char line[LINESIZE]; 3757 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){} 3758 } 3759 3760 /* The next function finds the template file and opens it, returning 3761 ** a pointer to the opened file. */ 3762 PRIVATE FILE *tplt_open(struct lemon *lemp) 3763 { 3764 static char templatename[] = "lempar.c"; 3765 char buf[1000]; 3766 FILE *in; 3767 char *tpltname; 3768 char *toFree = 0; 3769 char *cp; 3770 3771 /* first, see if user specified a template filename on the command line. */ 3772 if (user_templatename != 0) { 3773 if( access(user_templatename,004)==-1 ){ 3774 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", 3775 user_templatename); 3776 lemp->errorcnt++; 3777 return 0; 3778 } 3779 in = fopen(user_templatename,"rb"); 3780 if( in==0 ){ 3781 fprintf(stderr,"Can't open the template file \"%s\".\n", 3782 user_templatename); 3783 lemp->errorcnt++; 3784 return 0; 3785 } 3786 return in; 3787 } 3788 3789 cp = strrchr(lemp->filename,'.'); 3790 if( cp ){ 3791 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); 3792 }else{ 3793 lemon_sprintf(buf,"%s.lt",lemp->filename); 3794 } 3795 if( access(buf,004)==0 ){ 3796 tpltname = buf; 3797 }else if( access(templatename,004)==0 ){ 3798 tpltname = templatename; 3799 }else{ 3800 toFree = tpltname = pathsearch(lemp->argv[0],templatename,0); 3801 } 3802 if( tpltname==0 ){ 3803 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", 3804 templatename); 3805 lemp->errorcnt++; 3806 return 0; 3807 } 3808 in = fopen(tpltname,"rb"); 3809 if( in==0 ){ 3810 fprintf(stderr,"Can't open the template file \"%s\".\n",tpltname); 3811 lemp->errorcnt++; 3812 } 3813 lemon_free(toFree); 3814 return in; 3815 } 3816 3817 /* Print a #line directive line to the output file. */ 3818 PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename) 3819 { 3820 fprintf(out,"#line %d \"",lineno); 3821 while( *filename ){ 3822 if( *filename == '\\' ) putc('\\',out); 3823 putc(*filename,out); 3824 filename++; 3825 } 3826 fprintf(out,"\"\n"); 3827 fflush(out); 3828 } 3829 3830 /* Print a string to the file and keep the linenumber up to date */ 3831 PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno) 3832 { 3833 if( str==0 ) return; 3834 fflush(out); 3835 while( *str ){ 3836 putc(*str,out); 3837 if( *str=='\n' ) (*lineno)++; 3838 str++; 3839 } 3840 if( str[-1]!='\n' ){ 3841 putc('\n',out); 3842 (*lineno)++; 3843 } 3844 if (!lemp->nolinenosflag) { 3845 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); 3846 } 3847 fflush(out); 3848 return; 3849 } 3850 3851 /* 3852 ** The following routine emits code for the destructor for the 3853 ** symbol sp 3854 */ 3855 void emit_destructor_code( 3856 FILE *out, 3857 struct symbol *sp, 3858 struct lemon *lemp, 3859 int *lineno 3860 ){ 3861 char *cp = 0; 3862 3863 if( sp->type==TERMINAL ){ 3864 cp = lemp->tokendest; 3865 if( cp==0 ) return; 3866 fprintf(out,"{\n"); (*lineno)++; 3867 }else if( sp->destructor ){ 3868 cp = sp->destructor; 3869 fprintf(out,"{\n"); (*lineno)++; 3870 if( !lemp->nolinenosflag ){ 3871 (*lineno)++; 3872 tplt_linedir(out,sp->destLineno,lemp->filename); 3873 } 3874 }else if( lemp->vardest ){ 3875 cp = lemp->vardest; 3876 if( cp==0 ) return; 3877 fprintf(out,"{\n"); (*lineno)++; 3878 }else{ 3879 assert( 0 ); /* Cannot happen */ 3880 } 3881 for(; *cp; cp++){ 3882 if( *cp=='$' && cp[1]=='$' ){ 3883 fprintf(out,"(yypminor->yy%d)",sp->dtnum); 3884 cp++; 3885 continue; 3886 } 3887 if( *cp=='\n' ) (*lineno)++; 3888 fputc(*cp,out); 3889 } 3890 fprintf(out,"\n"); (*lineno)++; 3891 if (!lemp->nolinenosflag) { 3892 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); 3893 } 3894 fprintf(out,"}\n"); (*lineno)++; 3895 return; 3896 } 3897 3898 /* 3899 ** Return TRUE (non-zero) if the given symbol has a destructor. 3900 */ 3901 int has_destructor(struct symbol *sp, struct lemon *lemp) 3902 { 3903 int ret; 3904 if( sp->type==TERMINAL ){ 3905 ret = lemp->tokendest!=0; 3906 }else{ 3907 ret = lemp->vardest!=0 || sp->destructor!=0; 3908 } 3909 return ret; 3910 } 3911 3912 /* 3913 ** Append text to a dynamically allocated string. If zText is 0 then 3914 ** reset the string to be empty again. Always return the complete text 3915 ** of the string (which is overwritten with each call). 3916 ** 3917 ** n bytes of zText are stored. If n==0 then all of zText up to the first 3918 ** \000 terminator is stored. zText can contain up to two instances of 3919 ** %d. The values of p1 and p2 are written into the first and second 3920 ** %d. 3921 ** 3922 ** If n==-1, then the previous character is overwritten. 3923 */ 3924 PRIVATE char *append_str(const char *zText, int n, int p1, int p2){ 3925 static char empty[1] = { 0 }; 3926 static char *z = 0; 3927 static int alloced = 0; 3928 static int used = 0; 3929 int c; 3930 char zInt[40]; 3931 if( zText==0 ){ 3932 if( used==0 && z!=0 ) z[0] = 0; 3933 used = 0; 3934 return z; 3935 } 3936 if( n<=0 ){ 3937 if( n<0 ){ 3938 used += n; 3939 assert( used>=0 ); 3940 } 3941 n = lemonStrlen(zText); 3942 } 3943 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){ 3944 alloced = n + sizeof(zInt)*2 + used + 200; 3945 z = (char *) lemon_realloc(z, alloced); 3946 } 3947 if( z==0 ) return empty; 3948 while( n-- > 0 ){ 3949 c = *(zText++); 3950 if( c=='%' && n>0 && zText[0]=='d' ){ 3951 lemon_sprintf(zInt, "%d", p1); 3952 p1 = p2; 3953 lemon_strcpy(&z[used], zInt); 3954 used += lemonStrlen(&z[used]); 3955 zText++; 3956 n--; 3957 }else{ 3958 z[used++] = (char)c; 3959 } 3960 } 3961 z[used] = 0; 3962 return z; 3963 } 3964 3965 /* 3966 ** Write and transform the rp->code string so that symbols are expanded. 3967 ** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate. 3968 ** 3969 ** Return 1 if the expanded code requires that "yylhsminor" local variable 3970 ** to be defined. 3971 */ 3972 PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){ 3973 char *cp, *xp; 3974 int i; 3975 int rc = 0; /* True if yylhsminor is used */ 3976 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */ 3977 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */ 3978 char lhsused = 0; /* True if the LHS element has been used */ 3979 char lhsdirect; /* True if LHS writes directly into stack */ 3980 char used[MAXRHS]; /* True for each RHS element which is used */ 3981 char zLhs[50]; /* Convert the LHS symbol into this string */ 3982 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */ 3983 3984 for(i=0; inrhs; i++) used[i] = 0; 3985 lhsused = 0; 3986 3987 if( rp->code==0 ){ 3988 static char newlinestr[2] = { '\n', '\0' }; 3989 rp->code = newlinestr; 3990 rp->line = rp->ruleline; 3991 rp->noCode = 1; 3992 }else{ 3993 rp->noCode = 0; 3994 } 3995 3996 3997 if( rp->nrhs==0 ){ 3998 /* If there are no RHS symbols, then writing directly to the LHS is ok */ 3999 lhsdirect = 1; 4000 }else if( rp->rhsalias[0]==0 ){ 4001 /* The left-most RHS symbol has no value. LHS direct is ok. But 4002 ** we have to call the destructor on the RHS symbol first. */ 4003 lhsdirect = 1; 4004 if( has_destructor(rp->rhs[0],lemp) ){ 4005 append_str(0,0,0,0); 4006 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0, 4007 rp->rhs[0]->index,1-rp->nrhs); 4008 rp->codePrefix = Strsafe(append_str(0,0,0,0)); 4009 rp->noCode = 0; 4010 } 4011 }else if( rp->lhsalias==0 ){ 4012 /* There is no LHS value symbol. */ 4013 lhsdirect = 1; 4014 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){ 4015 /* The LHS symbol and the left-most RHS symbol are the same, so 4016 ** direct writing is allowed */ 4017 lhsdirect = 1; 4018 lhsused = 1; 4019 used[0] = 1; 4020 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){ 4021 ErrorMsg(lemp->filename,rp->ruleline, 4022 "%s(%s) and %s(%s) share the same label but have " 4023 "different datatypes.", 4024 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]); 4025 lemp->errorcnt++; 4026 } 4027 }else{ 4028 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/", 4029 rp->lhsalias, rp->rhsalias[0]); 4030 zSkip = strstr(rp->code, zOvwrt); 4031 if( zSkip!=0 ){ 4032 /* The code contains a special comment that indicates that it is safe 4033 ** for the LHS label to overwrite left-most RHS label. */ 4034 lhsdirect = 1; 4035 }else{ 4036 lhsdirect = 0; 4037 } 4038 } 4039 if( lhsdirect ){ 4040 lemon_sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum); 4041 }else{ 4042 rc = 1; 4043 lemon_sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum); 4044 } 4045 4046 append_str(0,0,0,0); 4047 4048 /* This const cast is wrong but harmless, if we're careful. */ 4049 for(cp=(char *)rp->code; *cp; cp++){ 4050 if( cp==zSkip ){ 4051 append_str(zOvwrt,0,0,0); 4052 cp += lemonStrlen(zOvwrt)-1; 4053 dontUseRhs0 = 1; 4054 continue; 4055 } 4056 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){ 4057 char saved; 4058 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++); 4059 saved = *xp; 4060 *xp = 0; 4061 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){ 4062 append_str(zLhs,0,0,0); 4063 cp = xp; 4064 lhsused = 1; 4065 }else{ 4066 for(i=0; inrhs; i++){ 4067 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ 4068 if( i==0 && dontUseRhs0 ){ 4069 ErrorMsg(lemp->filename,rp->ruleline, 4070 "Label %s used after '%s'.", 4071 rp->rhsalias[0], zOvwrt); 4072 lemp->errorcnt++; 4073 }else if( cp!=rp->code && cp[-1]=='@' ){ 4074 /* If the argument is of the form @X then substituted 4075 ** the token number of X, not the value of X */ 4076 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0); 4077 }else{ 4078 struct symbol *sp = rp->rhs[i]; 4079 int dtnum; 4080 if( sp->type==MULTITERMINAL ){ 4081 dtnum = sp->subsym[0]->dtnum; 4082 }else{ 4083 dtnum = sp->dtnum; 4084 } 4085 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum); 4086 } 4087 cp = xp; 4088 used[i] = 1; 4089 break; 4090 } 4091 } 4092 } 4093 *xp = saved; 4094 } 4095 append_str(cp, 1, 0, 0); 4096 } /* End loop */ 4097 4098 /* Main code generation completed */ 4099 cp = append_str(0,0,0,0); 4100 if( cp && cp[0] ) rp->code = Strsafe(cp); 4101 append_str(0,0,0,0); 4102 4103 /* Check to make sure the LHS has been used */ 4104 if( rp->lhsalias && !lhsused ){ 4105 ErrorMsg(lemp->filename,rp->ruleline, 4106 "Label \"%s\" for \"%s(%s)\" is never used.", 4107 rp->lhsalias,rp->lhs->name,rp->lhsalias); 4108 lemp->errorcnt++; 4109 } 4110 4111 /* Generate destructor code for RHS minor values which are not referenced. 4112 ** Generate error messages for unused labels and duplicate labels. 4113 */ 4114 for(i=0; inrhs; i++){ 4115 if( rp->rhsalias[i] ){ 4116 if( i>0 ){ 4117 int j; 4118 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){ 4119 ErrorMsg(lemp->filename,rp->ruleline, 4120 "%s(%s) has the same label as the LHS but is not the left-most " 4121 "symbol on the RHS.", 4122 rp->rhs[i]->name, rp->rhsalias[i]); 4123 lemp->errorcnt++; 4124 } 4125 for(j=0; jrhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){ 4127 ErrorMsg(lemp->filename,rp->ruleline, 4128 "Label %s used for multiple symbols on the RHS of a rule.", 4129 rp->rhsalias[i]); 4130 lemp->errorcnt++; 4131 break; 4132 } 4133 } 4134 } 4135 if( !used[i] ){ 4136 ErrorMsg(lemp->filename,rp->ruleline, 4137 "Label %s for \"%s(%s)\" is never used.", 4138 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]); 4139 lemp->errorcnt++; 4140 } 4141 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){ 4142 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0, 4143 rp->rhs[i]->index,i-rp->nrhs+1); 4144 } 4145 } 4146 4147 /* If unable to write LHS values directly into the stack, write the 4148 ** saved LHS value now. */ 4149 if( lhsdirect==0 ){ 4150 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum); 4151 append_str(zLhs, 0, 0, 0); 4152 append_str(";\n", 0, 0, 0); 4153 } 4154 4155 /* Suffix code generation complete */ 4156 cp = append_str(0,0,0,0); 4157 if( cp && cp[0] ){ 4158 rp->codeSuffix = Strsafe(cp); 4159 rp->noCode = 0; 4160 } 4161 4162 return rc; 4163 } 4164 4165 /* 4166 ** Generate code which executes when the rule "rp" is reduced. Write 4167 ** the code to "out". Make sure lineno stays up-to-date. 4168 */ 4169 PRIVATE void emit_code( 4170 FILE *out, 4171 struct rule *rp, 4172 struct lemon *lemp, 4173 int *lineno 4174 ){ 4175 const char *cp; 4176 4177 /* Setup code prior to the #line directive */ 4178 if( rp->codePrefix && rp->codePrefix[0] ){ 4179 fprintf(out, "{%s", rp->codePrefix); 4180 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; } 4181 } 4182 4183 /* Generate code to do the reduce action */ 4184 if( rp->code ){ 4185 if( !lemp->nolinenosflag ){ 4186 (*lineno)++; 4187 tplt_linedir(out,rp->line,lemp->filename); 4188 } 4189 fprintf(out,"{%s",rp->code); 4190 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; } 4191 fprintf(out,"}\n"); (*lineno)++; 4192 if( !lemp->nolinenosflag ){ 4193 (*lineno)++; 4194 tplt_linedir(out,*lineno,lemp->outname); 4195 } 4196 } 4197 4198 /* Generate breakdown code that occurs after the #line directive */ 4199 if( rp->codeSuffix && rp->codeSuffix[0] ){ 4200 fprintf(out, "%s", rp->codeSuffix); 4201 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; } 4202 } 4203 4204 if( rp->codePrefix ){ 4205 fprintf(out, "}\n"); (*lineno)++; 4206 } 4207 4208 return; 4209 } 4210 4211 /* 4212 ** Print the definition of the union used for the parser's data stack. 4213 ** This union contains fields for every possible data type for tokens 4214 ** and nonterminals. In the process of computing and printing this 4215 ** union, also set the ".dtnum" field of every terminal and nonterminal 4216 ** symbol. 4217 */ 4218 void print_stack_union( 4219 FILE *out, /* The output stream */ 4220 struct lemon *lemp, /* The main info structure for this parser */ 4221 int *plineno, /* Pointer to the line number */ 4222 int mhflag /* True if generating makeheaders output */ 4223 ){ 4224 int lineno; /* The line number of the output */ 4225 char **types; /* A hash table of datatypes */ 4226 int arraysize; /* Size of the "types" array */ 4227 int maxdtlength; /* Maximum length of any ".datatype" field. */ 4228 char *stddt; /* Standardized name for a datatype */ 4229 int i,j; /* Loop counters */ 4230 unsigned hash; /* For hashing the name of a type */ 4231 const char *name; /* Name of the parser */ 4232 4233 /* Allocate and initialize types[] and allocate stddt[] */ 4234 arraysize = lemp->nsymbol * 2; 4235 types = (char**)lemon_calloc( arraysize, sizeof(char*) ); 4236 if( types==0 ){ 4237 fprintf(stderr,"Out of memory.\n"); 4238 exit(1); 4239 } 4240 for(i=0; ivartype ){ 4243 maxdtlength = lemonStrlen(lemp->vartype); 4244 } 4245 for(i=0; insymbol; i++){ 4246 int len; 4247 struct symbol *sp = lemp->symbols[i]; 4248 if( sp->datatype==0 ) continue; 4249 len = lemonStrlen(sp->datatype); 4250 if( len>maxdtlength ) maxdtlength = len; 4251 } 4252 stddt = (char*)lemon_malloc( maxdtlength*2 + 1 ); 4253 if( stddt==0 ){ 4254 fprintf(stderr,"Out of memory.\n"); 4255 exit(1); 4256 } 4257 4258 /* Build a hash table of datatypes. The ".dtnum" field of each symbol 4259 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is 4260 ** used for terminal symbols. If there is no %default_type defined then 4261 ** 0 is also used as the .dtnum value for nonterminals which do not specify 4262 ** a datatype using the %type directive. 4263 */ 4264 for(i=0; insymbol; i++){ 4265 struct symbol *sp = lemp->symbols[i]; 4266 char *cp; 4267 if( sp==lemp->errsym ){ 4268 sp->dtnum = arraysize+1; 4269 continue; 4270 } 4271 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){ 4272 sp->dtnum = 0; 4273 continue; 4274 } 4275 cp = sp->datatype; 4276 if( cp==0 ) cp = lemp->vartype; 4277 j = 0; 4278 while( ISSPACE(*cp) ) cp++; 4279 while( *cp ) stddt[j++] = *cp++; 4280 while( j>0 && ISSPACE(stddt[j-1]) ) j--; 4281 stddt[j] = 0; 4282 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){ 4283 sp->dtnum = 0; 4284 continue; 4285 } 4286 hash = 0; 4287 for(j=0; stddt[j]; j++){ 4288 hash = hash*53 + stddt[j]; 4289 } 4290 hash = (hash & 0x7fffffff)%arraysize; 4291 while( types[hash] ){ 4292 if( strcmp(types[hash],stddt)==0 ){ 4293 sp->dtnum = hash + 1; 4294 break; 4295 } 4296 hash++; 4297 if( hash>=(unsigned)arraysize ) hash = 0; 4298 } 4299 if( types[hash]==0 ){ 4300 sp->dtnum = hash + 1; 4301 types[hash] = (char*)lemon_malloc( lemonStrlen(stddt)+1 ); 4302 if( types[hash]==0 ){ 4303 fprintf(stderr,"Out of memory.\n"); 4304 exit(1); 4305 } 4306 lemon_strcpy(types[hash],stddt); 4307 } 4308 } 4309 4310 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */ 4311 name = lemp->name ? lemp->name : "Parse"; 4312 lineno = *plineno; 4313 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } 4314 fprintf(out,"#define %sTOKENTYPE %s\n",name, 4315 lemp->tokentype?lemp->tokentype:"void*"); lineno++; 4316 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } 4317 fprintf(out,"typedef union {\n"); lineno++; 4318 fprintf(out," int yyinit;\n"); lineno++; 4319 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; 4320 for(i=0; ierrsym && lemp->errsym->useCnt ){ 4326 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++; 4327 } 4328 lemon_free(stddt); 4329 lemon_free(types); 4330 fprintf(out,"} YYMINORTYPE;\n"); lineno++; 4331 *plineno = lineno; 4332 } 4333 4334 /* 4335 ** Return the name of a C datatype able to represent values between 4336 ** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof 4337 ** for that type (1, 2, or 4) into *pnByte. 4338 */ 4339 static const char *minimum_size_type(int lwr, int upr, int *pnByte){ 4340 const char *zType = "int"; 4341 int nByte = 4; 4342 if( lwr>=0 ){ 4343 if( upr<=255 ){ 4344 zType = "unsigned char"; 4345 nByte = 1; 4346 }else if( upr<65535 ){ 4347 zType = "unsigned short int"; 4348 nByte = 2; 4349 }else{ 4350 zType = "unsigned int"; 4351 nByte = 4; 4352 } 4353 }else if( lwr>=-127 && upr<=127 ){ 4354 zType = "signed char"; 4355 nByte = 1; 4356 }else if( lwr>=-32767 && upr<32767 ){ 4357 zType = "short"; 4358 nByte = 2; 4359 } 4360 if( pnByte ) *pnByte = nByte; 4361 return zType; 4362 } 4363 4364 /* 4365 ** Each state contains a set of token transaction and a set of 4366 ** nonterminal transactions. Each of these sets makes an instance 4367 ** of the following structure. An array of these structures is used 4368 ** to order the creation of entries in the yy_action[] table. 4369 */ 4370 struct axset { 4371 struct state *stp; /* A pointer to a state */ 4372 int isTkn; /* True to use tokens. False for non-terminals */ 4373 int nAction; /* Number of actions */ 4374 int iOrder; /* Original order of action sets */ 4375 }; 4376 4377 /* 4378 ** Compare to axset structures for sorting purposes 4379 */ 4380 static int axset_compare(const void *a, const void *b){ 4381 struct axset *p1 = (struct axset*)a; 4382 struct axset *p2 = (struct axset*)b; 4383 int c; 4384 c = p2->nAction - p1->nAction; 4385 if( c==0 ){ 4386 c = p1->iOrder - p2->iOrder; 4387 } 4388 assert( c!=0 || p1==p2 ); 4389 return c; 4390 } 4391 4392 /* 4393 ** Write text on "out" that describes the rule "rp". 4394 */ 4395 static void writeRuleText(FILE *out, struct rule *rp){ 4396 int j; 4397 fprintf(out,"%s ::=", rp->lhs->name); 4398 for(j=0; jnrhs; j++){ 4399 struct symbol *sp = rp->rhs[j]; 4400 if( sp->type!=MULTITERMINAL ){ 4401 fprintf(out," %s", sp->name); 4402 }else{ 4403 int k; 4404 fprintf(out," %s", sp->subsym[0]->name); 4405 for(k=1; knsubsym; k++){ 4406 fprintf(out,"|%s",sp->subsym[k]->name); 4407 } 4408 } 4409 } 4410 } 4411 4412 /* 4413 ** Return true if the string is not NULL and not empty. 4414 */ 4415 static int notnull(const char *z){ 4416 return z && z[0]; 4417 } 4418 4419 4420 /* Generate C source code for the parser */ 4421 void ReportTable( 4422 struct lemon *lemp, 4423 int mhflag, /* Output in makeheaders format if true */ 4424 int sqlFlag /* Generate the *.sql file too */ 4425 ){ 4426 FILE *out, *in; 4427 int lineno; 4428 struct state *stp; 4429 struct action *ap; 4430 struct rule *rp; 4431 struct acttab *pActtab; 4432 int i, j, n, sz, mn, mx; 4433 int nLookAhead; 4434 int szActionType; /* sizeof(YYACTIONTYPE) */ 4435 int szCodeType; /* sizeof(YYCODETYPE) */ 4436 const char *name; 4437 int mnTknOfst, mxTknOfst; 4438 int mnNtOfst, mxNtOfst; 4439 struct axset *ax; 4440 char *prefix; 4441 4442 lemp->minShiftReduce = lemp->nstate; 4443 lemp->errAction = lemp->minShiftReduce + lemp->nrule; 4444 lemp->accAction = lemp->errAction + 1; 4445 lemp->noAction = lemp->accAction + 1; 4446 lemp->minReduce = lemp->noAction + 1; 4447 lemp->maxAction = lemp->minReduce + lemp->nrule; 4448 4449 in = tplt_open(lemp); 4450 if( in==0 ) return; 4451 if( sqlFlag ){ 4452 FILE *sql = file_open(lemp, ".sql", "wb"); 4453 if( sql==0 ){ 4454 fclose(in); 4455 return; 4456 } 4457 fprintf(sql, 4458 "BEGIN;\n" 4459 "CREATE TABLE symbol(\n" 4460 " id INTEGER PRIMARY KEY,\n" 4461 " name TEXT NOT NULL,\n" 4462 " isTerminal BOOLEAN NOT NULL,\n" 4463 " fallback INTEGER REFERENCES symbol" 4464 " DEFERRABLE INITIALLY DEFERRED\n" 4465 ");\n" 4466 ); 4467 for(i=0; insymbol; i++){ 4468 fprintf(sql, 4469 "INSERT INTO symbol(id,name,isTerminal,fallback)" 4470 "VALUES(%d,'%s',%s", 4471 i, lemp->symbols[i]->name, 4472 interminal ? "TRUE" : "FALSE" 4473 ); 4474 if( lemp->symbols[i]->fallback ){ 4475 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index); 4476 }else{ 4477 fprintf(sql, ",NULL);\n"); 4478 } 4479 } 4480 fprintf(sql, 4481 "CREATE TABLE rule(\n" 4482 " ruleid INTEGER PRIMARY KEY,\n" 4483 " lhs INTEGER REFERENCES symbol(id),\n" 4484 " txt TEXT\n" 4485 ");\n" 4486 "CREATE TABLE rulerhs(\n" 4487 " ruleid INTEGER REFERENCES rule(ruleid),\n" 4488 " pos INTEGER,\n" 4489 " sym INTEGER REFERENCES symbol(id)\n" 4490 ");\n" 4491 ); 4492 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ 4493 assert( i==rp->iRule ); 4494 fprintf(sql, 4495 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'", 4496 rp->iRule, rp->lhs->index 4497 ); 4498 writeRuleText(sql, rp); 4499 fprintf(sql,"');\n"); 4500 for(j=0; jnrhs; j++){ 4501 struct symbol *sp = rp->rhs[j]; 4502 if( sp->type!=MULTITERMINAL ){ 4503 fprintf(sql, 4504 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n", 4505 i,j,sp->index 4506 ); 4507 }else{ 4508 int k; 4509 for(k=0; knsubsym; k++){ 4510 fprintf(sql, 4511 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n", 4512 i,j,sp->subsym[k]->index 4513 ); 4514 } 4515 } 4516 } 4517 } 4518 fprintf(sql, "COMMIT;\n"); 4519 fclose(sql); 4520 } 4521 out = file_open(lemp,".c","wb"); 4522 if( out==0 ){ 4523 fclose(in); 4524 return; 4525 } 4526 lineno = 1; 4527 4528 fprintf(out, 4529 "/* This file is automatically generated by Lemon from input grammar\n" 4530 "** source file \"%s\"", lemp->filename); lineno++; 4531 if( nDefineUsed==0 ){ 4532 fprintf(out, ".\n*/\n"); lineno += 2; 4533 }else{ 4534 fprintf(out, " with these options:\n**\n"); lineno += 2; 4535 for(i=0; iinclude==0 ) lemp->include = ""; 4546 for(i=0; ISSPACE(lemp->include[i]); i++){ 4547 if( lemp->include[i]=='\n' ){ 4548 lemp->include += i+1; 4549 i = -1; 4550 } 4551 } 4552 if( lemp->include[0]=='/' ){ 4553 tplt_skip_header(in); 4554 }else{ 4555 tplt_xfer(lemp->name,in,out,&lineno); 4556 } 4557 4558 /* Generate the include code, if any */ 4559 tplt_print(out,lemp,lemp->include,&lineno); 4560 if( mhflag ){ 4561 char *incName = file_makename(lemp, ".h"); 4562 fprintf(out,"#include \"%s\"\n", incName); lineno++; 4563 lemon_free(incName); 4564 } 4565 tplt_xfer(lemp->name,in,out,&lineno); 4566 4567 /* Generate #defines for all tokens */ 4568 if( lemp->tokenprefix ) prefix = lemp->tokenprefix; 4569 else prefix = ""; 4570 if( mhflag ){ 4571 fprintf(out,"#if INTERFACE\n"); lineno++; 4572 }else{ 4573 fprintf(out,"#ifndef %s%s\n", prefix, lemp->symbols[1]->name); lineno++; 4574 } 4575 for(i=1; interminal; i++){ 4576 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); 4577 lineno++; 4578 } 4579 fprintf(out,"#endif\n"); lineno++; 4580 tplt_xfer(lemp->name,in,out,&lineno); 4581 4582 /* Generate the defines */ 4583 fprintf(out,"#define YYCODETYPE %s\n", 4584 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++; 4585 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++; 4586 fprintf(out,"#define YYACTIONTYPE %s\n", 4587 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++; 4588 if( lemp->wildcard ){ 4589 fprintf(out,"#define YYWILDCARD %d\n", 4590 lemp->wildcard->index); lineno++; 4591 } 4592 print_stack_union(out,lemp,&lineno,mhflag); 4593 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++; 4594 if( lemp->stacksize ){ 4595 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; 4596 }else{ 4597 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; 4598 } 4599 fprintf(out, "#endif\n"); lineno++; 4600 if( mhflag ){ 4601 fprintf(out,"#if INTERFACE\n"); lineno++; 4602 } 4603 name = lemp->name ? lemp->name : "Parse"; 4604 if( lemp->arg && lemp->arg[0] ){ 4605 i = lemonStrlen(lemp->arg); 4606 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--; 4607 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--; 4608 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++; 4609 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++; 4610 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++; 4611 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n", 4612 name,lemp->arg,&lemp->arg[i]); lineno++; 4613 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n", 4614 name,&lemp->arg[i],&lemp->arg[i]); lineno++; 4615 }else{ 4616 fprintf(out,"#define %sARG_SDECL\n",name); lineno++; 4617 fprintf(out,"#define %sARG_PDECL\n",name); lineno++; 4618 fprintf(out,"#define %sARG_PARAM\n",name); lineno++; 4619 fprintf(out,"#define %sARG_FETCH\n",name); lineno++; 4620 fprintf(out,"#define %sARG_STORE\n",name); lineno++; 4621 } 4622 fprintf(out, "#undef YYREALLOC\n"); lineno++; 4623 if( lemp->reallocFunc ){ 4624 fprintf(out,"#define YYREALLOC %s\n", lemp->reallocFunc); lineno++; 4625 }else{ 4626 fprintf(out,"#define YYREALLOC realloc\n"); lineno++; 4627 } 4628 fprintf(out, "#undef YYFREE\n"); lineno++; 4629 if( lemp->freeFunc ){ 4630 fprintf(out,"#define YYFREE %s\n", lemp->freeFunc); lineno++; 4631 }else{ 4632 fprintf(out,"#define YYFREE free\n"); lineno++; 4633 } 4634 fprintf(out, "#undef YYDYNSTACK\n"); lineno++; 4635 if( lemp->reallocFunc && lemp->freeFunc ){ 4636 fprintf(out,"#define YYDYNSTACK 1\n"); lineno++; 4637 }else{ 4638 fprintf(out,"#define YYDYNSTACK 0\n"); lineno++; 4639 } 4640 fprintf(out, "#undef YYSIZELIMIT\n"); lineno++; 4641 if( notnull(lemp->ctx) ){ 4642 i = lemonStrlen(lemp->ctx); 4643 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--; 4644 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--; 4645 if( notnull(lemp->stackSizeLimit) ){ 4646 fprintf(out,"#define YYSIZELIMIT %s\n", lemp->stackSizeLimit); lineno++; 4647 } 4648 fprintf(out,"#define %sCTX(P) ((P)->%s)\n",name,&lemp->ctx[i]); lineno++; 4649 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++; 4650 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++; 4651 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++; 4652 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n", 4653 name,lemp->ctx,&lemp->ctx[i]); lineno++; 4654 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n", 4655 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++; 4656 }else{ 4657 fprintf(out,"#define %sCTX(P) 0\n",name); lineno++; 4658 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++; 4659 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++; 4660 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++; 4661 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++; 4662 fprintf(out,"#define %sCTX_STORE\n",name); lineno++; 4663 } 4664 if( mhflag ){ 4665 fprintf(out,"#endif\n"); lineno++; 4666 } 4667 fprintf(out, "#undef YYERRORSYMBOL\n"); lineno++; 4668 fprintf(out, "#undef YYERRSYMDT\n"); lineno++; 4669 if( lemp->errsym && lemp->errsym->useCnt ){ 4670 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++; 4671 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++; 4672 } 4673 fprintf(out,"#undef YYFALLBACK\n"); lineno++; 4674 if( lemp->has_fallback ){ 4675 fprintf(out,"#define YYFALLBACK 1\n"); lineno++; 4676 } 4677 4678 /* Compute the action table, but do not output it yet. The action 4679 ** table must be computed before generating the YYNSTATE macro because 4680 ** we need to know how many states can be eliminated. 4681 */ 4682 ax = (struct axset *) lemon_calloc(lemp->nxstate*2, sizeof(ax[0])); 4683 if( ax==0 ){ 4684 fprintf(stderr,"malloc failed\n"); 4685 exit(1); 4686 } 4687 for(i=0; inxstate; i++){ 4688 stp = lemp->sorted[i]; 4689 ax[i*2].stp = stp; 4690 ax[i*2].isTkn = 1; 4691 ax[i*2].nAction = stp->nTknAct; 4692 ax[i*2+1].stp = stp; 4693 ax[i*2+1].isTkn = 0; 4694 ax[i*2+1].nAction = stp->nNtAct; 4695 } 4696 mxTknOfst = mnTknOfst = 0; 4697 mxNtOfst = mnNtOfst = 0; 4698 /* In an effort to minimize the action table size, use the heuristic 4699 ** of placing the largest action sets first */ 4700 for(i=0; inxstate*2; i++) ax[i].iOrder = i; 4701 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare); 4702 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal); 4703 for(i=0; inxstate*2 && ax[i].nAction>0; i++){ 4704 stp = ax[i].stp; 4705 if( ax[i].isTkn ){ 4706 for(ap=stp->ap; ap; ap=ap->next){ 4707 int action; 4708 if( ap->sp->index>=lemp->nterminal ) continue; 4709 action = compute_action(lemp, ap); 4710 if( action<0 ) continue; 4711 acttab_action(pActtab, ap->sp->index, action); 4712 } 4713 stp->iTknOfst = acttab_insert(pActtab, 1); 4714 if( stp->iTknOfstiTknOfst; 4715 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst; 4716 }else{ 4717 for(ap=stp->ap; ap; ap=ap->next){ 4718 int action; 4719 if( ap->sp->indexnterminal ) continue; 4720 if( ap->sp->index==lemp->nsymbol ) continue; 4721 action = compute_action(lemp, ap); 4722 if( action<0 ) continue; 4723 acttab_action(pActtab, ap->sp->index, action); 4724 } 4725 stp->iNtOfst = acttab_insert(pActtab, 0); 4726 if( stp->iNtOfstiNtOfst; 4727 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; 4728 } 4729 #if 0 /* Uncomment for a trace of how the yy_action[] table fills out */ 4730 { int jj, nn; 4731 for(jj=nn=0; jjnAction; jj++){ 4732 if( pActtab->aAction[jj].action<0 ) nn++; 4733 } 4734 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n", 4735 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ", 4736 ax[i].nAction, pActtab->nAction, nn); 4737 } 4738 #endif 4739 } 4740 lemon_free(ax); 4741 4742 /* Mark rules that are actually used for reduce actions after all 4743 ** optimizations have been applied 4744 */ 4745 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE; 4746 for(i=0; inxstate; i++){ 4747 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ 4748 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){ 4749 ap->x.rp->doesReduce = 1; 4750 } 4751 } 4752 } 4753 4754 /* Finish rendering the constants now that the action table has 4755 ** been computed */ 4756 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++; 4757 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; 4758 fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction); 4759 lineno++; 4760 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++; 4761 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++; 4762 i = lemp->minShiftReduce; 4763 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++; 4764 i += lemp->nrule; 4765 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++; 4766 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++; 4767 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++; 4768 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++; 4769 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++; 4770 i = lemp->minReduce + lemp->nrule; 4771 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++; 4772 4773 /* Minimum and maximum token values that have a destructor */ 4774 mn = mx = 0; 4775 for(i=0; insymbol; i++){ 4776 struct symbol *sp = lemp->symbols[i]; 4777 4778 if( sp && sp->type!=TERMINAL && sp->destructor ){ 4779 if( mn==0 || sp->indexindex; 4780 if( sp->index>mx ) mx = sp->index; 4781 } 4782 } 4783 if( lemp->tokendest ) mn = 0; 4784 if( lemp->vardest ) mx = lemp->nsymbol-1; 4785 fprintf(out,"#define YY_MIN_DSTRCTR %d\n", mn); lineno++; 4786 fprintf(out,"#define YY_MAX_DSTRCTR %d\n", mx); lineno++; 4787 4788 tplt_xfer(lemp->name,in,out,&lineno); 4789 4790 /* Now output the action table and its associates: 4791 ** 4792 ** yy_action[] A single table containing all actions. 4793 ** yy_lookahead[] A table containing the lookahead for each entry in 4794 ** yy_action. Used to detect hash collisions. 4795 ** yy_shift_ofst[] For each state, the offset into yy_action for 4796 ** shifting terminals. 4797 ** yy_reduce_ofst[] For each state, the offset into yy_action for 4798 ** shifting non-terminals after a reduce. 4799 ** yy_default[] Default action for each state. 4800 */ 4801 4802 /* Output the yy_action table */ 4803 lemp->nactiontab = n = acttab_action_size(pActtab); 4804 lemp->tablesize += n*szActionType; 4805 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++; 4806 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++; 4807 for(i=j=0; inoAction; 4810 if( j==0 ) fprintf(out," /* %5d */ ", i); 4811 fprintf(out, " %4d,", action); 4812 if( j==9 || i==n-1 ){ 4813 fprintf(out, "\n"); lineno++; 4814 j = 0; 4815 }else{ 4816 j++; 4817 } 4818 } 4819 fprintf(out, "};\n"); lineno++; 4820 4821 /* Output the yy_lookahead table */ 4822 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab); 4823 lemp->tablesize += n*szCodeType; 4824 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++; 4825 for(i=j=0; insymbol; 4828 if( j==0 ) fprintf(out," /* %5d */ ", i); 4829 fprintf(out, " %4d,", la); 4830 if( j==9 ){ 4831 fprintf(out, "\n"); lineno++; 4832 j = 0; 4833 }else{ 4834 j++; 4835 } 4836 } 4837 /* Add extra entries to the end of the yy_lookahead[] table so that 4838 ** yy_shift_ofst[]+iToken will always be a valid index into the array, 4839 ** even for the largest possible value of yy_shift_ofst[] and iToken. */ 4840 nLookAhead = lemp->nterminal + lemp->nactiontab; 4841 while( interminal); 4844 if( j==9 ){ 4845 fprintf(out, "\n"); lineno++; 4846 j = 0; 4847 }else{ 4848 j++; 4849 } 4850 i++; 4851 } 4852 if( j>0 ){ fprintf(out, "\n"); lineno++; } 4853 fprintf(out, "};\n"); lineno++; 4854 4855 /* Output the yy_shift_ofst[] table */ 4856 n = lemp->nxstate; 4857 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--; 4858 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++; 4859 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++; 4860 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++; 4861 fprintf(out, "static const %s yy_shift_ofst[] = {\n", 4862 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz)); 4863 lineno++; 4864 lemp->tablesize += n*sz; 4865 for(i=j=0; isorted[i]; 4868 ofst = stp->iTknOfst; 4869 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab; 4870 if( j==0 ) fprintf(out," /* %5d */ ", i); 4871 fprintf(out, " %4d,", ofst); 4872 if( j==9 || i==n-1 ){ 4873 fprintf(out, "\n"); lineno++; 4874 j = 0; 4875 }else{ 4876 j++; 4877 } 4878 } 4879 fprintf(out, "};\n"); lineno++; 4880 4881 /* Output the yy_reduce_ofst[] table */ 4882 n = lemp->nxstate; 4883 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--; 4884 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++; 4885 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++; 4886 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++; 4887 fprintf(out, "static const %s yy_reduce_ofst[] = {\n", 4888 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++; 4889 lemp->tablesize += n*sz; 4890 for(i=j=0; isorted[i]; 4893 ofst = stp->iNtOfst; 4894 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1; 4895 if( j==0 ) fprintf(out," /* %5d */ ", i); 4896 fprintf(out, " %4d,", ofst); 4897 if( j==9 || i==n-1 ){ 4898 fprintf(out, "\n"); lineno++; 4899 j = 0; 4900 }else{ 4901 j++; 4902 } 4903 } 4904 fprintf(out, "};\n"); lineno++; 4905 4906 /* Output the default action table */ 4907 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++; 4908 n = lemp->nxstate; 4909 lemp->tablesize += n*szActionType; 4910 for(i=j=0; isorted[i]; 4912 if( j==0 ) fprintf(out," /* %5d */ ", i); 4913 if( stp->iDfltReduce<0 ){ 4914 fprintf(out, " %4d,", lemp->errAction); 4915 }else{ 4916 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce); 4917 } 4918 if( j==9 || i==n-1 ){ 4919 fprintf(out, "\n"); lineno++; 4920 j = 0; 4921 }else{ 4922 j++; 4923 } 4924 } 4925 fprintf(out, "};\n"); lineno++; 4926 tplt_xfer(lemp->name,in,out,&lineno); 4927 4928 /* Generate the table of fallback tokens. 4929 */ 4930 if( lemp->has_fallback ){ 4931 mx = lemp->nterminal - 1; 4932 /* 2019-08-28: Generate fallback entries for every token to avoid 4933 ** having to do a range check on the index */ 4934 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */ 4935 lemp->tablesize += (mx+1)*szCodeType; 4936 for(i=0; i<=mx; i++){ 4937 struct symbol *p = lemp->symbols[i]; 4938 if( p->fallback==0 ){ 4939 fprintf(out, " 0, /* %10s => nothing */\n", p->name); 4940 }else{ 4941 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index, 4942 p->name, p->fallback->name); 4943 } 4944 lineno++; 4945 } 4946 } 4947 tplt_xfer(lemp->name, in, out, &lineno); 4948 4949 /* Generate a table containing the symbolic name of every symbol 4950 */ 4951 for(i=0; insymbol; i++){ 4952 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++; 4953 } 4954 tplt_xfer(lemp->name,in,out,&lineno); 4955 4956 /* Generate a table containing a text string that describes every 4957 ** rule in the rule set of the grammar. This information is used 4958 ** when tracing REDUCE actions. 4959 */ 4960 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ 4961 assert( rp->iRule==i ); 4962 fprintf(out," /* %3d */ \"", i); 4963 writeRuleText(out, rp); 4964 fprintf(out,"\",\n"); lineno++; 4965 } 4966 tplt_xfer(lemp->name,in,out,&lineno); 4967 4968 /* Generate code which executes every time a symbol is popped from 4969 ** the stack while processing errors or while destroying the parser. 4970 ** (In other words, generate the %destructor actions) 4971 */ 4972 if( lemp->tokendest ){ 4973 int once = 1; 4974 for(i=0; insymbol; i++){ 4975 struct symbol *sp = lemp->symbols[i]; 4976 if( sp==0 || sp->type!=TERMINAL ) continue; 4977 if( once ){ 4978 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++; 4979 once = 0; 4980 } 4981 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; 4982 } 4983 for(i=0; insymbol && lemp->symbols[i]->type!=TERMINAL; i++); 4984 if( insymbol ){ 4985 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); 4986 fprintf(out," break;\n"); lineno++; 4987 } 4988 } 4989 if( lemp->vardest ){ 4990 struct symbol *dflt_sp = 0; 4991 int once = 1; 4992 for(i=0; insymbol; i++){ 4993 struct symbol *sp = lemp->symbols[i]; 4994 if( sp==0 || sp->type==TERMINAL || 4995 sp->index<=0 || sp->destructor!=0 ) continue; 4996 if( once ){ 4997 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++; 4998 once = 0; 4999 } 5000 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; 5001 dflt_sp = sp; 5002 } 5003 if( dflt_sp!=0 ){ 5004 emit_destructor_code(out,dflt_sp,lemp,&lineno); 5005 } 5006 fprintf(out," break;\n"); lineno++; 5007 } 5008 for(i=0; insymbol; i++){ 5009 struct symbol *sp = lemp->symbols[i]; 5010 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; 5011 if( sp->destLineno<0 ) continue; /* Already emitted */ 5012 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; 5013 5014 /* Combine duplicate destructors into a single case */ 5015 for(j=i+1; jnsymbol; j++){ 5016 struct symbol *sp2 = lemp->symbols[j]; 5017 if( sp2 && sp2->type!=TERMINAL && sp2->destructor 5018 && sp2->dtnum==sp->dtnum 5019 && strcmp(sp->destructor,sp2->destructor)==0 ){ 5020 fprintf(out," case %d: /* %s */\n", 5021 sp2->index, sp2->name); lineno++; 5022 sp2->destLineno = -1; /* Avoid emitting this destructor again */ 5023 } 5024 } 5025 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); 5026 fprintf(out," break;\n"); lineno++; 5027 } 5028 tplt_xfer(lemp->name,in,out,&lineno); 5029 5030 /* Generate code which executes whenever the parser stack overflows */ 5031 tplt_print(out,lemp,lemp->overflow,&lineno); 5032 tplt_xfer(lemp->name,in,out,&lineno); 5033 5034 /* Generate the tables of rule information. yyRuleInfoLhs[] and 5035 ** yyRuleInfoNRhs[]. 5036 ** 5037 ** Note: This code depends on the fact that rules are number 5038 ** sequentially beginning with 0. 5039 */ 5040 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ 5041 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i); 5042 rule_print(out, rp); 5043 fprintf(out," */\n"); lineno++; 5044 } 5045 tplt_xfer(lemp->name,in,out,&lineno); 5046 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ 5047 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i); 5048 rule_print(out, rp); 5049 fprintf(out," */\n"); lineno++; 5050 } 5051 tplt_xfer(lemp->name,in,out,&lineno); 5052 5053 /* Generate code which execution during each REDUCE action */ 5054 i = 0; 5055 for(rp=lemp->rule; rp; rp=rp->next){ 5056 i += translate_code(lemp, rp); 5057 } 5058 if( i ){ 5059 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++; 5060 } 5061 /* First output rules other than the default: rule */ 5062 for(rp=lemp->rule; rp; rp=rp->next){ 5063 struct rule *rp2; /* Other rules with the same action */ 5064 if( rp->codeEmitted ) continue; 5065 if( rp->noCode ){ 5066 /* No C code actions, so this will be part of the "default:" rule */ 5067 continue; 5068 } 5069 fprintf(out," case %d: /* ", rp->iRule); 5070 writeRuleText(out, rp); 5071 fprintf(out, " */\n"); lineno++; 5072 for(rp2=rp->next; rp2; rp2=rp2->next){ 5073 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix 5074 && rp2->codeSuffix==rp->codeSuffix ){ 5075 fprintf(out," case %d: /* ", rp2->iRule); 5076 writeRuleText(out, rp2); 5077 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++; 5078 rp2->codeEmitted = 1; 5079 } 5080 } 5081 emit_code(out,rp,lemp,&lineno); 5082 fprintf(out," break;\n"); lineno++; 5083 rp->codeEmitted = 1; 5084 } 5085 /* Finally, output the default: rule. We choose as the default: all 5086 ** empty actions. */ 5087 fprintf(out," default:\n"); lineno++; 5088 for(rp=lemp->rule; rp; rp=rp->next){ 5089 if( rp->codeEmitted ) continue; 5090 assert( rp->noCode ); 5091 fprintf(out," /* (%d) ", rp->iRule); 5092 writeRuleText(out, rp); 5093 if( rp->neverReduce ){ 5094 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n", 5095 rp->iRule); lineno++; 5096 }else if( rp->doesReduce ){ 5097 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++; 5098 }else{ 5099 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n", 5100 rp->iRule); lineno++; 5101 } 5102 } 5103 fprintf(out," break;\n"); lineno++; 5104 tplt_xfer(lemp->name,in,out,&lineno); 5105 5106 /* Generate code which executes if a parse fails */ 5107 tplt_print(out,lemp,lemp->failure,&lineno); 5108 tplt_xfer(lemp->name,in,out,&lineno); 5109 5110 /* Generate code which executes when a syntax error occurs */ 5111 tplt_print(out,lemp,lemp->error,&lineno); 5112 tplt_xfer(lemp->name,in,out,&lineno); 5113 5114 /* Generate code which executes when the parser accepts its input */ 5115 tplt_print(out,lemp,lemp->accept,&lineno); 5116 tplt_xfer(lemp->name,in,out,&lineno); 5117 5118 /* Append any addition code the user desires */ 5119 tplt_print(out,lemp,lemp->extracode,&lineno); 5120 5121 acttab_free(pActtab); 5122 fclose(in); 5123 fclose(out); 5124 return; 5125 } 5126 5127 /* Generate a header file for the parser */ 5128 void ReportHeader(struct lemon *lemp) 5129 { 5130 FILE *out, *in; 5131 const char *prefix; 5132 char line[LINESIZE]; 5133 char pattern[LINESIZE]; 5134 int i; 5135 5136 if( lemp->tokenprefix ) prefix = lemp->tokenprefix; 5137 else prefix = ""; 5138 in = file_open(lemp,".h","rb"); 5139 if( in ){ 5140 int nextChar; 5141 for(i=1; interminal && fgets(line,LINESIZE,in); i++){ 5142 lemon_sprintf(pattern,"#define %s%-30s %3d\n", 5143 prefix,lemp->symbols[i]->name,i); 5144 if( strcmp(line,pattern) ) break; 5145 } 5146 nextChar = fgetc(in); 5147 fclose(in); 5148 if( i==lemp->nterminal && nextChar==EOF ){ 5149 /* No change in the file. Don't rewrite it. */ 5150 return; 5151 } 5152 } 5153 out = file_open(lemp,".h","wb"); 5154 if( out ){ 5155 for(i=1; interminal; i++){ 5156 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i); 5157 } 5158 fclose(out); 5159 } 5160 return; 5161 } 5162 5163 /* Reduce the size of the action tables, if possible, by making use 5164 ** of defaults. 5165 ** 5166 ** In this version, we take the most frequent REDUCE action and make 5167 ** it the default. Except, there is no default if the wildcard token 5168 ** is a possible look-ahead. 5169 */ 5170 void CompressTables(struct lemon *lemp) 5171 { 5172 struct state *stp; 5173 struct action *ap, *ap2, *nextap; 5174 struct rule *rp, *rp2, *rbest; 5175 int nbest, n; 5176 int i; 5177 int usesWildcard; 5178 5179 for(i=0; instate; i++){ 5180 stp = lemp->sorted[i]; 5181 nbest = 0; 5182 rbest = 0; 5183 usesWildcard = 0; 5184 5185 for(ap=stp->ap; ap; ap=ap->next){ 5186 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){ 5187 usesWildcard = 1; 5188 } 5189 if( ap->type!=REDUCE ) continue; 5190 rp = ap->x.rp; 5191 if( rp->lhsStart ) continue; 5192 if( rp==rbest ) continue; 5193 n = 1; 5194 for(ap2=ap->next; ap2; ap2=ap2->next){ 5195 if( ap2->type!=REDUCE ) continue; 5196 rp2 = ap2->x.rp; 5197 if( rp2==rbest ) continue; 5198 if( rp2==rp ) n++; 5199 } 5200 if( n>nbest ){ 5201 nbest = n; 5202 rbest = rp; 5203 } 5204 } 5205 5206 /* Do not make a default if the number of rules to default 5207 ** is not at least 1 or if the wildcard token is a possible 5208 ** lookahead. 5209 */ 5210 if( nbest<1 || usesWildcard ) continue; 5211 5212 5213 /* Combine matching REDUCE actions into a single default */ 5214 for(ap=stp->ap; ap; ap=ap->next){ 5215 if( ap->type==REDUCE && ap->x.rp==rbest ) break; 5216 } 5217 assert( ap ); 5218 ap->sp = Symbol_new("{default}"); 5219 for(ap=ap->next; ap; ap=ap->next){ 5220 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED; 5221 } 5222 stp->ap = Action_sort(stp->ap); 5223 5224 for(ap=stp->ap; ap; ap=ap->next){ 5225 if( ap->type==SHIFT ) break; 5226 if( ap->type==REDUCE && ap->x.rp!=rbest ) break; 5227 } 5228 if( ap==0 ){ 5229 stp->autoReduce = 1; 5230 stp->pDfltReduce = rbest; 5231 } 5232 } 5233 5234 /* Make a second pass over all states and actions. Convert 5235 ** every action that is a SHIFT to an autoReduce state into 5236 ** a SHIFTREDUCE action. 5237 */ 5238 for(i=0; instate; i++){ 5239 stp = lemp->sorted[i]; 5240 for(ap=stp->ap; ap; ap=ap->next){ 5241 struct state *pNextState; 5242 if( ap->type!=SHIFT ) continue; 5243 pNextState = ap->x.stp; 5244 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){ 5245 ap->type = SHIFTREDUCE; 5246 ap->x.rp = pNextState->pDfltReduce; 5247 } 5248 } 5249 } 5250 5251 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term 5252 ** (meaning that the SHIFTREDUCE will land back in the state where it 5253 ** started) and if there is no C-code associated with the reduce action, 5254 ** then we can go ahead and convert the action to be the same as the 5255 ** action for the RHS of the rule. 5256 */ 5257 for(i=0; instate; i++){ 5258 stp = lemp->sorted[i]; 5259 for(ap=stp->ap; ap; ap=nextap){ 5260 nextap = ap->next; 5261 if( ap->type!=SHIFTREDUCE ) continue; 5262 rp = ap->x.rp; 5263 if( rp->noCode==0 ) continue; 5264 if( rp->nrhs!=1 ) continue; 5265 #if 1 5266 /* Only apply this optimization to non-terminals. It would be OK to 5267 ** apply it to terminal symbols too, but that makes the parser tables 5268 ** larger. */ 5269 if( ap->sp->indexnterminal ) continue; 5270 #endif 5271 /* If we reach this point, it means the optimization can be applied */ 5272 nextap = ap; 5273 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){} 5274 assert( ap2!=0 ); 5275 ap->spOpt = ap2->sp; 5276 ap->type = ap2->type; 5277 ap->x = ap2->x; 5278 } 5279 } 5280 } 5281 5282 5283 /* 5284 ** Compare two states for sorting purposes. The smaller state is the 5285 ** one with the most non-terminal actions. If they have the same number 5286 ** of non-terminal actions, then the smaller is the one with the most 5287 ** token actions. 5288 */ 5289 static int stateResortCompare(const void *a, const void *b){ 5290 const struct state *pA = *(const struct state**)a; 5291 const struct state *pB = *(const struct state**)b; 5292 int n; 5293 5294 n = pB->nNtAct - pA->nNtAct; 5295 if( n==0 ){ 5296 n = pB->nTknAct - pA->nTknAct; 5297 if( n==0 ){ 5298 n = pB->statenum - pA->statenum; 5299 } 5300 } 5301 assert( n!=0 ); 5302 return n; 5303 } 5304 5305 5306 /* 5307 ** Renumber and resort states so that states with fewer choices 5308 ** occur at the end. Except, keep state 0 as the first state. 5309 */ 5310 void ResortStates(struct lemon *lemp) 5311 { 5312 int i; 5313 struct state *stp; 5314 struct action *ap; 5315 5316 for(i=0; instate; i++){ 5317 stp = lemp->sorted[i]; 5318 stp->nTknAct = stp->nNtAct = 0; 5319 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */ 5320 stp->iTknOfst = NO_OFFSET; 5321 stp->iNtOfst = NO_OFFSET; 5322 for(ap=stp->ap; ap; ap=ap->next){ 5323 int iAction = compute_action(lemp,ap); 5324 if( iAction>=0 ){ 5325 if( ap->sp->indexnterminal ){ 5326 stp->nTknAct++; 5327 }else if( ap->sp->indexnsymbol ){ 5328 stp->nNtAct++; 5329 }else{ 5330 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp ); 5331 stp->iDfltReduce = iAction; 5332 } 5333 } 5334 } 5335 } 5336 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]), 5337 stateResortCompare); 5338 for(i=0; instate; i++){ 5339 lemp->sorted[i]->statenum = i; 5340 } 5341 lemp->nxstate = lemp->nstate; 5342 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){ 5343 lemp->nxstate--; 5344 } 5345 } 5346 5347 5348 /***************** From the file "set.c" ************************************/ 5349 /* 5350 ** Set manipulation routines for the LEMON parser generator. 5351 */ 5352 5353 static int size = 0; 5354 5355 /* Set the set size */ 5356 void SetSize(int n) 5357 { 5358 size = n+1; 5359 } 5360 5361 /* Allocate a new set */ 5362 char *SetNew(void){ 5363 char *s; 5364 s = (char*)lemon_calloc( size, 1); 5365 if( s==0 ){ 5366 memory_error(); 5367 } 5368 return s; 5369 } 5370 5371 /* Deallocate a set */ 5372 void SetFree(char *s) 5373 { 5374 lemon_free(s); 5375 } 5376 5377 /* Add a new element to the set. Return TRUE if the element was added 5378 ** and FALSE if it was already there. */ 5379 int SetAdd(char *s, int e) 5380 { 5381 int rv; 5382 assert( e>=0 && esize = 1024; 5472 x1a->count = 0; 5473 x1a->tbl = (x1node*)lemon_calloc(1024, sizeof(x1node) + sizeof(x1node*)); 5474 if( x1a->tbl==0 ){ 5475 lemon_free(x1a); 5476 x1a = 0; 5477 }else{ 5478 int i; 5479 x1a->ht = (x1node**)&(x1a->tbl[1024]); 5480 for(i=0; i<1024; i++) x1a->ht[i] = 0; 5481 } 5482 } 5483 } 5484 /* Insert a new record into the array. Return TRUE if successful. 5485 ** Prior data with the same key is NOT overwritten */ 5486 int Strsafe_insert(const char *data) 5487 { 5488 x1node *np; 5489 unsigned h; 5490 unsigned ph; 5491 5492 if( x1a==0 ) return 0; 5493 ph = strhash(data); 5494 h = ph & (x1a->size-1); 5495 np = x1a->ht[h]; 5496 while( np ){ 5497 if( strcmp(np->data,data)==0 ){ 5498 /* An existing entry with the same key is found. */ 5499 /* Fail because overwrite is not allows. */ 5500 return 0; 5501 } 5502 np = np->next; 5503 } 5504 if( x1a->count>=x1a->size ){ 5505 /* Need to make the hash table bigger */ 5506 int i,arrSize; 5507 struct s_x1 array; 5508 array.size = arrSize = x1a->size*2; 5509 array.count = x1a->count; 5510 array.tbl = (x1node*)lemon_calloc(arrSize, sizeof(x1node)+sizeof(x1node*)); 5511 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 5512 array.ht = (x1node**)&(array.tbl[arrSize]); 5513 for(i=0; icount; i++){ 5515 x1node *oldnp, *newnp; 5516 oldnp = &(x1a->tbl[i]); 5517 h = strhash(oldnp->data) & (arrSize-1); 5518 newnp = &(array.tbl[i]); 5519 if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 5520 newnp->next = array.ht[h]; 5521 newnp->data = oldnp->data; 5522 newnp->from = &(array.ht[h]); 5523 array.ht[h] = newnp; 5524 } 5525 /* lemon_free(x1a->tbl); // This program was originally for 16-bit machines. 5526 ** Don't worry about freeing memory on modern platforms. */ 5527 *x1a = array; 5528 } 5529 /* Insert the new data */ 5530 h = ph & (x1a->size-1); 5531 np = &(x1a->tbl[x1a->count++]); 5532 np->data = data; 5533 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next); 5534 np->next = x1a->ht[h]; 5535 x1a->ht[h] = np; 5536 np->from = &(x1a->ht[h]); 5537 return 1; 5538 } 5539 5540 /* Return a pointer to data assigned to the given key. Return NULL 5541 ** if no such key. */ 5542 const char *Strsafe_find(const char *key) 5543 { 5544 unsigned h; 5545 x1node *np; 5546 5547 if( x1a==0 ) return 0; 5548 h = strhash(key) & (x1a->size-1); 5549 np = x1a->ht[h]; 5550 while( np ){ 5551 if( strcmp(np->data,key)==0 ) break; 5552 np = np->next; 5553 } 5554 return np ? np->data : 0; 5555 } 5556 5557 /* Return a pointer to the (terminal or nonterminal) symbol "x". 5558 ** Create a new symbol if this is the first time "x" has been seen. 5559 */ 5560 struct symbol *Symbol_new(const char *x) 5561 { 5562 struct symbol *sp; 5563 5564 sp = Symbol_find(x); 5565 if( sp==0 ){ 5566 sp = (struct symbol *)lemon_calloc(1, sizeof(struct symbol) ); 5567 MemoryCheck(sp); 5568 sp->name = Strsafe(x); 5569 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL; 5570 sp->rule = 0; 5571 sp->fallback = 0; 5572 sp->prec = -1; 5573 sp->assoc = UNK; 5574 sp->firstset = 0; 5575 sp->lambda = LEMON_FALSE; 5576 sp->destructor = 0; 5577 sp->destLineno = 0; 5578 sp->datatype = 0; 5579 sp->useCnt = 0; 5580 Symbol_insert(sp,sp->name); 5581 } 5582 sp->useCnt++; 5583 return sp; 5584 } 5585 5586 /* Compare two symbols for sorting purposes. Return negative, 5587 ** zero, or positive if a is less then, equal to, or greater 5588 ** than b. 5589 ** 5590 ** Symbols that begin with upper case letters (terminals or tokens) 5591 ** must sort before symbols that begin with lower case letters 5592 ** (non-terminals). And MULTITERMINAL symbols (created using the 5593 ** %token_class directive) must sort at the very end. Other than 5594 ** that, the order does not matter. 5595 ** 5596 ** We find experimentally that leaving the symbols in their original 5597 ** order (the order they appeared in the grammar file) gives the 5598 ** smallest parser tables in SQLite. 5599 */ 5600 int Symbolcmpp(const void *_a, const void *_b) 5601 { 5602 const struct symbol *a = *(const struct symbol **) _a; 5603 const struct symbol *b = *(const struct symbol **) _b; 5604 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1; 5605 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1; 5606 return i1==i2 ? a->index - b->index : i1 - i2; 5607 } 5608 5609 /* There is one instance of the following structure for each 5610 ** associative array of type "x2". 5611 */ 5612 struct s_x2 { 5613 int size; /* The number of available slots. */ 5614 /* Must be a power of 2 greater than or */ 5615 /* equal to 1 */ 5616 int count; /* Number of currently slots filled */ 5617 struct s_x2node *tbl; /* The data stored here */ 5618 struct s_x2node **ht; /* Hash table for lookups */ 5619 }; 5620 5621 /* There is one instance of this structure for every data element 5622 ** in an associative array of type "x2". 5623 */ 5624 typedef struct s_x2node { 5625 struct symbol *data; /* The data */ 5626 const char *key; /* The key */ 5627 struct s_x2node *next; /* Next entry with the same hash */ 5628 struct s_x2node **from; /* Previous link */ 5629 } x2node; 5630 5631 /* There is only one instance of the array, which is the following */ 5632 static struct s_x2 *x2a; 5633 5634 /* Allocate a new associative array */ 5635 void Symbol_init(void){ 5636 if( x2a ) return; 5637 x2a = (struct s_x2*)lemon_malloc( sizeof(struct s_x2) ); 5638 if( x2a ){ 5639 x2a->size = 128; 5640 x2a->count = 0; 5641 x2a->tbl = (x2node*)lemon_calloc(128, sizeof(x2node) + sizeof(x2node*)); 5642 if( x2a->tbl==0 ){ 5643 lemon_free(x2a); 5644 x2a = 0; 5645 }else{ 5646 int i; 5647 x2a->ht = (x2node**)&(x2a->tbl[128]); 5648 for(i=0; i<128; i++) x2a->ht[i] = 0; 5649 } 5650 } 5651 } 5652 /* Insert a new record into the array. Return TRUE if successful. 5653 ** Prior data with the same key is NOT overwritten */ 5654 int Symbol_insert(struct symbol *data, const char *key) 5655 { 5656 x2node *np; 5657 unsigned h; 5658 unsigned ph; 5659 5660 if( x2a==0 ) return 0; 5661 ph = strhash(key); 5662 h = ph & (x2a->size-1); 5663 np = x2a->ht[h]; 5664 while( np ){ 5665 if( strcmp(np->key,key)==0 ){ 5666 /* An existing entry with the same key is found. */ 5667 /* Fail because overwrite is not allows. */ 5668 return 0; 5669 } 5670 np = np->next; 5671 } 5672 if( x2a->count>=x2a->size ){ 5673 /* Need to make the hash table bigger */ 5674 int i,arrSize; 5675 struct s_x2 array; 5676 array.size = arrSize = x2a->size*2; 5677 array.count = x2a->count; 5678 array.tbl = (x2node*)lemon_calloc(arrSize, sizeof(x2node)+sizeof(x2node*)); 5679 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 5680 array.ht = (x2node**)&(array.tbl[arrSize]); 5681 for(i=0; icount; i++){ 5683 x2node *oldnp, *newnp; 5684 oldnp = &(x2a->tbl[i]); 5685 h = strhash(oldnp->key) & (arrSize-1); 5686 newnp = &(array.tbl[i]); 5687 if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 5688 newnp->next = array.ht[h]; 5689 newnp->key = oldnp->key; 5690 newnp->data = oldnp->data; 5691 newnp->from = &(array.ht[h]); 5692 array.ht[h] = newnp; 5693 } 5694 /* lemon_free(x2a->tbl); // This program was originally written for 16-bit 5695 ** machines. Don't worry about freeing this trivial amount of memory 5696 ** on modern platforms. Just leak it. */ 5697 *x2a = array; 5698 } 5699 /* Insert the new data */ 5700 h = ph & (x2a->size-1); 5701 np = &(x2a->tbl[x2a->count++]); 5702 np->key = key; 5703 np->data = data; 5704 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next); 5705 np->next = x2a->ht[h]; 5706 x2a->ht[h] = np; 5707 np->from = &(x2a->ht[h]); 5708 return 1; 5709 } 5710 5711 /* Return a pointer to data assigned to the given key. Return NULL 5712 ** if no such key. */ 5713 struct symbol *Symbol_find(const char *key) 5714 { 5715 unsigned h; 5716 x2node *np; 5717 5718 if( x2a==0 ) return 0; 5719 h = strhash(key) & (x2a->size-1); 5720 np = x2a->ht[h]; 5721 while( np ){ 5722 if( strcmp(np->key,key)==0 ) break; 5723 np = np->next; 5724 } 5725 return np ? np->data : 0; 5726 } 5727 5728 /* Return the n-th data. Return NULL if n is out of range. */ 5729 struct symbol *Symbol_Nth(int n) 5730 { 5731 struct symbol *data; 5732 if( x2a && n>0 && n<=x2a->count ){ 5733 data = x2a->tbl[n-1].data; 5734 }else{ 5735 data = 0; 5736 } 5737 return data; 5738 } 5739 5740 /* Return the size of the array */ 5741 int Symbol_count() 5742 { 5743 return x2a ? x2a->count : 0; 5744 } 5745 5746 /* Return an array of pointers to all data in the table. 5747 ** The array is obtained from malloc. Return NULL if memory allocation 5748 ** problems, or if the array is empty. */ 5749 struct symbol **Symbol_arrayof() 5750 { 5751 struct symbol **array; 5752 int i,arrSize; 5753 if( x2a==0 ) return 0; 5754 arrSize = x2a->count; 5755 array = (struct symbol **)lemon_calloc(arrSize, sizeof(struct symbol *)); 5756 if( array ){ 5757 for(i=0; itbl[i].data; 5758 } 5759 return array; 5760 } 5761 5762 /* Compare two configurations */ 5763 int Configcmp(const char *_a,const char *_b) 5764 { 5765 const struct config *a = (struct config *) _a; 5766 const struct config *b = (struct config *) _b; 5767 int x; 5768 x = a->rp->index - b->rp->index; 5769 if( x==0 ) x = a->dot - b->dot; 5770 return x; 5771 } 5772 5773 /* Compare two states */ 5774 PRIVATE int statecmp(struct config *a, struct config *b) 5775 { 5776 int rc; 5777 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){ 5778 rc = a->rp->index - b->rp->index; 5779 if( rc==0 ) rc = a->dot - b->dot; 5780 } 5781 if( rc==0 ){ 5782 if( a ) rc = 1; 5783 if( b ) rc = -1; 5784 } 5785 return rc; 5786 } 5787 5788 /* Hash a state */ 5789 PRIVATE unsigned statehash(struct config *a) 5790 { 5791 unsigned h=0; 5792 while( a ){ 5793 h = h*571 + a->rp->index*37 + a->dot; 5794 a = a->bp; 5795 } 5796 return h; 5797 } 5798 5799 /* Allocate a new state structure */ 5800 struct state *State_new() 5801 { 5802 struct state *newstate; 5803 newstate = (struct state *)lemon_calloc(1, sizeof(struct state) ); 5804 MemoryCheck(newstate); 5805 return newstate; 5806 } 5807 5808 /* There is one instance of the following structure for each 5809 ** associative array of type "x3". 5810 */ 5811 struct s_x3 { 5812 int size; /* The number of available slots. */ 5813 /* Must be a power of 2 greater than or */ 5814 /* equal to 1 */ 5815 int count; /* Number of currently slots filled */ 5816 struct s_x3node *tbl; /* The data stored here */ 5817 struct s_x3node **ht; /* Hash table for lookups */ 5818 }; 5819 5820 /* There is one instance of this structure for every data element 5821 ** in an associative array of type "x3". 5822 */ 5823 typedef struct s_x3node { 5824 struct state *data; /* The data */ 5825 struct config *key; /* The key */ 5826 struct s_x3node *next; /* Next entry with the same hash */ 5827 struct s_x3node **from; /* Previous link */ 5828 } x3node; 5829 5830 /* There is only one instance of the array, which is the following */ 5831 static struct s_x3 *x3a; 5832 5833 /* Allocate a new associative array */ 5834 void State_init(void){ 5835 if( x3a ) return; 5836 x3a = (struct s_x3*)lemon_malloc( sizeof(struct s_x3) ); 5837 if( x3a ){ 5838 x3a->size = 128; 5839 x3a->count = 0; 5840 x3a->tbl = (x3node*)lemon_calloc(128, sizeof(x3node) + sizeof(x3node*)); 5841 if( x3a->tbl==0 ){ 5842 lemon_free(x3a); 5843 x3a = 0; 5844 }else{ 5845 int i; 5846 x3a->ht = (x3node**)&(x3a->tbl[128]); 5847 for(i=0; i<128; i++) x3a->ht[i] = 0; 5848 } 5849 } 5850 } 5851 /* Insert a new record into the array. Return TRUE if successful. 5852 ** Prior data with the same key is NOT overwritten */ 5853 int State_insert(struct state *data, struct config *key) 5854 { 5855 x3node *np; 5856 unsigned h; 5857 unsigned ph; 5858 5859 if( x3a==0 ) return 0; 5860 ph = statehash(key); 5861 h = ph & (x3a->size-1); 5862 np = x3a->ht[h]; 5863 while( np ){ 5864 if( statecmp(np->key,key)==0 ){ 5865 /* An existing entry with the same key is found. */ 5866 /* Fail because overwrite is not allows. */ 5867 return 0; 5868 } 5869 np = np->next; 5870 } 5871 if( x3a->count>=x3a->size ){ 5872 /* Need to make the hash table bigger */ 5873 int i,arrSize; 5874 struct s_x3 array; 5875 array.size = arrSize = x3a->size*2; 5876 array.count = x3a->count; 5877 array.tbl = (x3node*)lemon_calloc(arrSize, sizeof(x3node)+sizeof(x3node*)); 5878 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 5879 array.ht = (x3node**)&(array.tbl[arrSize]); 5880 for(i=0; icount; i++){ 5882 x3node *oldnp, *newnp; 5883 oldnp = &(x3a->tbl[i]); 5884 h = statehash(oldnp->key) & (arrSize-1); 5885 newnp = &(array.tbl[i]); 5886 if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 5887 newnp->next = array.ht[h]; 5888 newnp->key = oldnp->key; 5889 newnp->data = oldnp->data; 5890 newnp->from = &(array.ht[h]); 5891 array.ht[h] = newnp; 5892 } 5893 lemon_free(x3a->tbl); 5894 *x3a = array; 5895 } 5896 /* Insert the new data */ 5897 h = ph & (x3a->size-1); 5898 np = &(x3a->tbl[x3a->count++]); 5899 np->key = key; 5900 np->data = data; 5901 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next); 5902 np->next = x3a->ht[h]; 5903 x3a->ht[h] = np; 5904 np->from = &(x3a->ht[h]); 5905 return 1; 5906 } 5907 5908 /* Return a pointer to data assigned to the given key. Return NULL 5909 ** if no such key. */ 5910 struct state *State_find(struct config *key) 5911 { 5912 unsigned h; 5913 x3node *np; 5914 5915 if( x3a==0 ) return 0; 5916 h = statehash(key) & (x3a->size-1); 5917 np = x3a->ht[h]; 5918 while( np ){ 5919 if( statecmp(np->key,key)==0 ) break; 5920 np = np->next; 5921 } 5922 return np ? np->data : 0; 5923 } 5924 5925 /* Return an array of pointers to all data in the table. 5926 ** The array is obtained from malloc. Return NULL if memory allocation 5927 ** problems, or if the array is empty. */ 5928 struct state **State_arrayof(void) 5929 { 5930 struct state **array; 5931 int i,arrSize; 5932 if( x3a==0 ) return 0; 5933 arrSize = x3a->count; 5934 array = (struct state **)lemon_calloc(arrSize, sizeof(struct state *)); 5935 if( array ){ 5936 for(i=0; itbl[i].data; 5937 } 5938 return array; 5939 } 5940 5941 /* Hash a configuration */ 5942 PRIVATE unsigned confighash(struct config *a) 5943 { 5944 unsigned h=0; 5945 h = a->rp->index*37 + a->dot; 5946 return h; 5947 } 5948 5949 /* There is one instance of the following structure for each 5950 ** associative array of type "x4". 5951 */ 5952 struct s_x4 { 5953 int size; /* The number of available slots. */ 5954 /* Must be a power of 2 greater than or */ 5955 /* equal to 1 */ 5956 int count; /* Number of currently slots filled */ 5957 struct s_x4node *tbl; /* The data stored here */ 5958 struct s_x4node **ht; /* Hash table for lookups */ 5959 }; 5960 5961 /* There is one instance of this structure for every data element 5962 ** in an associative array of type "x4". 5963 */ 5964 typedef struct s_x4node { 5965 struct config *data; /* The data */ 5966 struct s_x4node *next; /* Next entry with the same hash */ 5967 struct s_x4node **from; /* Previous link */ 5968 } x4node; 5969 5970 /* There is only one instance of the array, which is the following */ 5971 static struct s_x4 *x4a; 5972 5973 /* Allocate a new associative array */ 5974 void Configtable_init(void){ 5975 if( x4a ) return; 5976 x4a = (struct s_x4*)lemon_malloc( sizeof(struct s_x4) ); 5977 if( x4a ){ 5978 x4a->size = 64; 5979 x4a->count = 0; 5980 x4a->tbl = (x4node*)lemon_calloc(64, sizeof(x4node) + sizeof(x4node*)); 5981 if( x4a->tbl==0 ){ 5982 lemon_free(x4a); 5983 x4a = 0; 5984 }else{ 5985 int i; 5986 x4a->ht = (x4node**)&(x4a->tbl[64]); 5987 for(i=0; i<64; i++) x4a->ht[i] = 0; 5988 } 5989 } 5990 } 5991 /* Insert a new record into the array. Return TRUE if successful. 5992 ** Prior data with the same key is NOT overwritten */ 5993 int Configtable_insert(struct config *data) 5994 { 5995 x4node *np; 5996 unsigned h; 5997 unsigned ph; 5998 5999 if( x4a==0 ) return 0; 6000 ph = confighash(data); 6001 h = ph & (x4a->size-1); 6002 np = x4a->ht[h]; 6003 while( np ){ 6004 if( Configcmp((const char *) np->data,(const char *) data)==0 ){ 6005 /* An existing entry with the same key is found. */ 6006 /* Fail because overwrite is not allows. */ 6007 return 0; 6008 } 6009 np = np->next; 6010 } 6011 if( x4a->count>=x4a->size ){ 6012 /* Need to make the hash table bigger */ 6013 int i,arrSize; 6014 struct s_x4 array; 6015 array.size = arrSize = x4a->size*2; 6016 array.count = x4a->count; 6017 array.tbl = (x4node*)lemon_calloc(arrSize, 6018 sizeof(x4node) + sizeof(x4node*)); 6019 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 6020 array.ht = (x4node**)&(array.tbl[arrSize]); 6021 for(i=0; icount; i++){ 6023 x4node *oldnp, *newnp; 6024 oldnp = &(x4a->tbl[i]); 6025 h = confighash(oldnp->data) & (arrSize-1); 6026 newnp = &(array.tbl[i]); 6027 if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 6028 newnp->next = array.ht[h]; 6029 newnp->data = oldnp->data; 6030 newnp->from = &(array.ht[h]); 6031 array.ht[h] = newnp; 6032 } 6033 *x4a = array; 6034 } 6035 /* Insert the new data */ 6036 h = ph & (x4a->size-1); 6037 np = &(x4a->tbl[x4a->count++]); 6038 np->data = data; 6039 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next); 6040 np->next = x4a->ht[h]; 6041 x4a->ht[h] = np; 6042 np->from = &(x4a->ht[h]); 6043 return 1; 6044 } 6045 6046 /* Return a pointer to data assigned to the given key. Return NULL 6047 ** if no such key. */ 6048 struct config *Configtable_find(struct config *key) 6049 { 6050 int h; 6051 x4node *np; 6052 6053 if( x4a==0 ) return 0; 6054 h = confighash(key) & (x4a->size-1); 6055 np = x4a->ht[h]; 6056 while( np ){ 6057 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break; 6058 np = np->next; 6059 } 6060 return np ? np->data : 0; 6061 } 6062 6063 /* Remove all data from the table. Pass each data to the function "f" 6064 ** as it is removed. ("f" may be null to avoid this step.) */ 6065 void Configtable_clear(int(*f)(struct config *)) 6066 { 6067 int i; 6068 if( x4a==0 || x4a->count==0 ) return; 6069 if( f ) for(i=0; icount; i++) (*f)(x4a->tbl[i].data); 6070 for(i=0; isize; i++) x4a->ht[i] = 0; 6071 x4a->count = 0; 6072 return; 6073 }