├── .gitignore ├── CMakeLists.txt ├── README.md ├── lemon.c └── lempar.c /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | */ 3 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | PROJECT(lemon) 2 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8) 3 | 4 | ADD_EXECUTABLE(lemon lemon.c) 5 | 6 | MACRO(LEMON_TARGET Name Input Template) 7 | GET_FILENAME_COMPONENT(LEMON_INPUT_FILENAME ${Input} NAME_WE) 8 | GET_FILENAME_COMPONENT(LEMON_TEMPLATE_EXTENSION ${Template} EXT) 9 | GET_FILENAME_COMPONENT(LEMON_TEMPLATE_PATH ${Template} PATH) 10 | 11 | IF(LEMON_TEMPLATE_PATH STREQUAL "") 12 | SET(LEMON_TEMPLATE_PATH ${lemon_SOURCE_DIR}/${Template}) 13 | ELSE() 14 | SET(LEMON_TEMPLATE_PATH ${Template}) 15 | ENDIF() 16 | 17 | SET(LEMON_${Name}_OUTPUTS 18 | ${CMAKE_CURRENT_BINARY_DIR}/${LEMON_INPUT_FILENAME}.h 19 | ${CMAKE_CURRENT_BINARY_DIR}/${LEMON_INPUT_FILENAME}${LEMON_TEMPLATE_EXTENSION}) 20 | 21 | ADD_CUSTOM_COMMAND( 22 | OUTPUT ${LEMON_${Name}_OUTPUTS} 23 | COMMAND lemon ARGS ${Input} -P${CMAKE_CURRENT_BINARY_DIR}/ -T${LEMON_TEMPLATE_PATH} 24 | DEPENDS ${Input} ${LEMON_TEMPLATE_PATH} 25 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) 26 | ENDMACRO() 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | LEMON 2 | ===== 3 | 4 | What is it? 5 | ----------- 6 | 7 | From [original documentation](http://www.hwaci.com/sw/lemon/lemon.html "Documentation"): 8 | 9 | Lemon is an LALR(1) parser generator for C or C++. It does the same job as bison and yacc. 10 | But Lemon is not another bison or yacc clone. It uses a different grammar syntax which is designed to reduce the number of coding errors. 11 | Lemon also uses a more sophisticated parsing engine that is faster than yacc and bison and which is both reentrant and thread-safe. 12 | Furthermore, Lemon implements features that can be used to eliminate resource leaks, 13 | making is suitable for use in long-running programs such as graphical user interfaces or embedded controllers. 14 | 15 | What is different compared to original (SQLite) version? 16 | -------------------------------------------------------- 17 | 18 | * Added option `-H` to specify a header file extension. 19 | * Added option `-P` to specify a file-name prefix. 20 | * Generated parser has same extension as template file. 21 | -------------------------------------------------------------------------------- /lemon.c: -------------------------------------------------------------------------------- 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 | #ifdef _MSC_VER 10 | # define _CRT_SECURE_NO_WARNINGS 11 | #endif 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | #ifndef __WIN32__ 21 | # if defined(_WIN32) || defined(WIN32) 22 | # define __WIN32__ 23 | # endif 24 | #endif 25 | 26 | #ifdef __WIN32__ 27 | #ifdef __cplusplus 28 | extern "C" { 29 | #endif 30 | extern int access(const char *path, int mode); 31 | #ifdef __cplusplus 32 | } 33 | #endif 34 | #else 35 | #include 36 | #endif 37 | 38 | /* #define PRIVATE static */ 39 | #define PRIVATE 40 | 41 | #ifdef TEST 42 | #define MAXRHS 5 /* Set low to exercise exception code */ 43 | #else 44 | #define MAXRHS 1000 45 | #endif 46 | 47 | static int showPrecedenceConflict = 0; 48 | static char *msort(char*,char**,int(*)(const char*,const char*)); 49 | 50 | /* 51 | ** Compilers are getting increasingly pedantic about type conversions 52 | ** as C evolves ever closer to Ada.... To work around the latest problems 53 | ** we have to define the following variant of strlen(). 54 | */ 55 | #define lemonStrlen(X) ((int)strlen(X)) 56 | 57 | /* 58 | ** Compilers are starting to complain about the use of sprintf() and strcpy(), 59 | ** saying they are unsafe. So we define our own versions of those routines too. 60 | ** 61 | ** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and 62 | ** lemon_addtext(). The first two are replacements for sprintf() and vsprintf(). 63 | ** The third is a helper routine for vsnprintf() that adds texts to the end of a 64 | ** buffer, making sure the buffer is always zero-terminated. 65 | ** 66 | ** The string formatter is a minimal subset of stdlib sprintf() supporting only 67 | ** a few simply conversions: 68 | ** 69 | ** %d 70 | ** %s 71 | ** %.*s 72 | ** 73 | */ 74 | static void lemon_addtext( 75 | char *zBuf, /* The buffer to which text is added */ 76 | int *pnUsed, /* Slots of the buffer used so far */ 77 | const char *zIn, /* Text to add */ 78 | int nIn, /* Bytes of text to add. -1 to use strlen() */ 79 | int iWidth /* Field width. Negative to left justify */ 80 | ){ 81 | if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){} 82 | while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; } 83 | if( nIn==0 ) return; 84 | memcpy(&zBuf[*pnUsed], zIn, nIn); 85 | *pnUsed += nIn; 86 | while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; } 87 | zBuf[*pnUsed] = 0; 88 | } 89 | static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){ 90 | int i, j, k, c; 91 | int nUsed = 0; 92 | const char *z; 93 | char zTemp[50]; 94 | str[0] = 0; 95 | for(i=j=0; (c = zFormat[i])!=0; i++){ 96 | if( c=='%' ){ 97 | int iWidth = 0; 98 | lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0); 99 | c = zFormat[++i]; 100 | if( isdigit(c) || (c=='-' && isdigit(zFormat[i+1])) ){ 101 | if( c=='-' ) i++; 102 | while( isdigit(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0'; 103 | if( c=='-' ) iWidth = -iWidth; 104 | c = zFormat[i]; 105 | } 106 | if( c=='d' ){ 107 | int v = va_arg(ap, int); 108 | if( v<0 ){ 109 | lemon_addtext(str, &nUsed, "-", 1, iWidth); 110 | v = -v; 111 | }else if( v==0 ){ 112 | lemon_addtext(str, &nUsed, "0", 1, iWidth); 113 | } 114 | k = 0; 115 | while( v>0 ){ 116 | k++; 117 | zTemp[sizeof(zTemp)-k] = (v%10) + '0'; 118 | v /= 10; 119 | } 120 | lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth); 121 | }else if( c=='s' ){ 122 | z = va_arg(ap, const char*); 123 | lemon_addtext(str, &nUsed, z, -1, iWidth); 124 | }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){ 125 | i += 2; 126 | k = va_arg(ap, int); 127 | z = va_arg(ap, const char*); 128 | lemon_addtext(str, &nUsed, z, k, iWidth); 129 | }else if( c=='%' ){ 130 | lemon_addtext(str, &nUsed, "%", 1, 0); 131 | }else{ 132 | fprintf(stderr, "illegal format\n"); 133 | exit(1); 134 | } 135 | j = i+1; 136 | } 137 | } 138 | lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0); 139 | return nUsed; 140 | } 141 | static int lemon_sprintf(char *str, const char *format, ...){ 142 | va_list ap; 143 | int rc; 144 | va_start(ap, format); 145 | rc = lemon_vsprintf(str, format, ap); 146 | va_end(ap); 147 | return rc; 148 | } 149 | static void lemon_strcpy(char *dest, const char *src){ 150 | while( (*(dest++) = *(src++))!=0 ){} 151 | } 152 | static void lemon_strcat(char *dest, const char *src){ 153 | while( *dest ) dest++; 154 | lemon_strcpy(dest, src); 155 | } 156 | 157 | 158 | /* a few forward declarations... */ 159 | struct rule; 160 | struct lemon; 161 | struct action; 162 | 163 | static struct action *Action_new(void); 164 | static struct action *Action_sort(struct action *); 165 | 166 | /********** From the file "build.h" ************************************/ 167 | void FindRulePrecedences(); 168 | void FindFirstSets(); 169 | void FindStates(); 170 | void FindLinks(); 171 | void FindFollowSets(); 172 | void FindActions(); 173 | 174 | /********* From the file "configlist.h" *********************************/ 175 | void Configlist_init(void); 176 | struct config *Configlist_add(struct rule *, int); 177 | struct config *Configlist_addbasis(struct rule *, int); 178 | void Configlist_closure(struct lemon *); 179 | void Configlist_sort(void); 180 | void Configlist_sortbasis(void); 181 | struct config *Configlist_return(void); 182 | struct config *Configlist_basis(void); 183 | void Configlist_eat(struct config *); 184 | void Configlist_reset(void); 185 | 186 | /********* From the file "error.h" ***************************************/ 187 | void ErrorMsg(const char *, int,const char *, ...); 188 | 189 | /****** From the file "option.h" ******************************************/ 190 | enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, 191 | OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR}; 192 | struct s_options { 193 | enum option_type type; 194 | const char *label; 195 | char *arg; 196 | const char *message; 197 | }; 198 | int OptInit(char**,struct s_options*,FILE*); 199 | int OptNArgs(void); 200 | char *OptArg(int); 201 | void OptErr(int); 202 | void OptPrint(void); 203 | 204 | /******** From the file "parse.h" *****************************************/ 205 | void Parse(struct lemon *lemp); 206 | 207 | /********* From the file "plink.h" ***************************************/ 208 | struct plink *Plink_new(void); 209 | void Plink_add(struct plink **, struct config *); 210 | void Plink_copy(struct plink **, struct plink *); 211 | void Plink_delete(struct plink *); 212 | 213 | /********** From the file "report.h" *************************************/ 214 | void Reprint(struct lemon *); 215 | void ReportOutput(struct lemon *); 216 | void ReportTable(struct lemon *, int); 217 | void ReportHeader(struct lemon *); 218 | void CompressTables(struct lemon *); 219 | void ResortStates(struct lemon *); 220 | 221 | /********** From the file "set.h" ****************************************/ 222 | void SetSize(int); /* All sets will be of size N */ 223 | char *SetNew(void); /* A new set for element 0..N */ 224 | void SetFree(char*); /* Deallocate a set */ 225 | int SetAdd(char*,int); /* Add element to a set */ 226 | int SetUnion(char *,char *); /* A <- A U B, thru element N */ 227 | #define SetFind(X,Y) (X[Y]) /* True if Y is in set X */ 228 | 229 | /********** From the file "struct.h" *************************************/ 230 | /* 231 | ** Principal data structures for the LEMON parser generator. 232 | */ 233 | 234 | typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean; 235 | 236 | /* Symbols (terminals and nonterminals) of the grammar are stored 237 | ** in the following: */ 238 | enum symbol_type { 239 | TERMINAL, 240 | NONTERMINAL, 241 | MULTITERMINAL 242 | }; 243 | enum e_assoc { 244 | LEFT, 245 | RIGHT, 246 | NONE, 247 | UNK 248 | }; 249 | struct symbol { 250 | const char *name; /* Name of the symbol */ 251 | int index; /* Index number for this symbol */ 252 | enum symbol_type type; /* Symbols are all either TERMINALS or NTs */ 253 | struct rule *rule; /* Linked list of rules of this (if an NT) */ 254 | struct symbol *fallback; /* fallback token in case this token doesn't parse */ 255 | int prec; /* Precedence if defined (-1 otherwise) */ 256 | enum e_assoc assoc; /* Associativity if precedence is defined */ 257 | char *firstset; /* First-set for all rules of this symbol */ 258 | Boolean lambda; /* True if NT and can generate an empty string */ 259 | int useCnt; /* Number of times used */ 260 | char *destructor; /* Code which executes whenever this symbol is 261 | ** popped from the stack during error processing */ 262 | int destLineno; /* Line number for start of destructor */ 263 | char *datatype; /* The data type of information held by this 264 | ** object. Only used if type==NONTERMINAL */ 265 | int dtnum; /* The data type number. In the parser, the value 266 | ** stack is a union. The .yy%d element of this 267 | ** union is the correct data type for this object */ 268 | /* The following fields are used by MULTITERMINALs only */ 269 | int nsubsym; /* Number of constituent symbols in the MULTI */ 270 | struct symbol **subsym; /* Array of constituent symbols */ 271 | }; 272 | 273 | /* Each production rule in the grammar is stored in the following 274 | ** structure. */ 275 | struct rule { 276 | struct symbol *lhs; /* Left-hand side of the rule */ 277 | const char *lhsalias; /* Alias for the LHS (NULL if none) */ 278 | int lhsStart; /* True if left-hand side is the start symbol */ 279 | int ruleline; /* Line number for the rule */ 280 | int nrhs; /* Number of RHS symbols */ 281 | struct symbol **rhs; /* The RHS symbols */ 282 | const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ 283 | int line; /* Line number at which code begins */ 284 | const char *code; /* The code executed when this rule is reduced */ 285 | struct symbol *precsym; /* Precedence symbol for this rule */ 286 | int index; /* An index number for this rule */ 287 | Boolean canReduce; /* True if this rule is ever reduced */ 288 | struct rule *nextlhs; /* Next rule with the same LHS */ 289 | struct rule *next; /* Next rule in the global list */ 290 | }; 291 | 292 | /* A configuration is a production rule of the grammar together with 293 | ** a mark (dot) showing how much of that rule has been processed so far. 294 | ** Configurations also contain a follow-set which is a list of terminal 295 | ** symbols which are allowed to immediately follow the end of the rule. 296 | ** Every configuration is recorded as an instance of the following: */ 297 | enum cfgstatus { 298 | COMPLETE, 299 | INCOMPLETE 300 | }; 301 | struct config { 302 | struct rule *rp; /* The rule upon which the configuration is based */ 303 | int dot; /* The parse point */ 304 | char *fws; /* Follow-set for this configuration only */ 305 | struct plink *fplp; /* Follow-set forward propagation links */ 306 | struct plink *bplp; /* Follow-set backwards propagation links */ 307 | struct state *stp; /* Pointer to state which contains this */ 308 | enum cfgstatus status; /* used during followset and shift computations */ 309 | struct config *next; /* Next configuration in the state */ 310 | struct config *bp; /* The next basis configuration */ 311 | }; 312 | 313 | enum e_action { 314 | SHIFT, 315 | ACCEPT, 316 | REDUCE, 317 | ERROR, 318 | SSCONFLICT, /* A shift/shift conflict */ 319 | SRCONFLICT, /* Was a reduce, but part of a conflict */ 320 | RRCONFLICT, /* Was a reduce, but part of a conflict */ 321 | SH_RESOLVED, /* Was a shift. Precedence resolved conflict */ 322 | RD_RESOLVED, /* Was reduce. Precedence resolved conflict */ 323 | NOT_USED /* Deleted by compression */ 324 | }; 325 | 326 | /* Every shift or reduce operation is stored as one of the following */ 327 | struct action { 328 | struct symbol *sp; /* The look-ahead symbol */ 329 | enum e_action type; 330 | union { 331 | struct state *stp; /* The new state, if a shift */ 332 | struct rule *rp; /* The rule, if a reduce */ 333 | } x; 334 | struct action *next; /* Next action for this state */ 335 | struct action *collide; /* Next action with the same hash */ 336 | }; 337 | 338 | /* Each state of the generated parser's finite state machine 339 | ** is encoded as an instance of the following structure. */ 340 | struct state { 341 | struct config *bp; /* The basis configurations for this state */ 342 | struct config *cfp; /* All configurations in this set */ 343 | int statenum; /* Sequential number for this state */ 344 | struct action *ap; /* Array of actions for this state */ 345 | int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */ 346 | int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */ 347 | int iDflt; /* Default action */ 348 | }; 349 | #define NO_OFFSET (-2147483647) 350 | 351 | /* A followset propagation link indicates that the contents of one 352 | ** configuration followset should be propagated to another whenever 353 | ** the first changes. */ 354 | struct plink { 355 | struct config *cfp; /* The configuration to which linked */ 356 | struct plink *next; /* The next propagate link */ 357 | }; 358 | 359 | /* The state vector for the entire parser generator is recorded as 360 | ** follows. (LEMON uses no global variables and makes little use of 361 | ** static variables. Fields in the following structure can be thought 362 | ** of as begin global variables in the program.) */ 363 | struct lemon { 364 | struct state **sorted; /* Table of states sorted by state number */ 365 | struct rule *rule; /* List of all rules */ 366 | int nstate; /* Number of states */ 367 | int nrule; /* Number of rules */ 368 | int nsymbol; /* Number of terminal and nonterminal symbols */ 369 | int nterminal; /* Number of terminal symbols */ 370 | struct symbol **symbols; /* Sorted array of pointers to symbols */ 371 | int errorcnt; /* Number of errors */ 372 | struct symbol *errsym; /* The error symbol */ 373 | struct symbol *wildcard; /* Token that matches anything */ 374 | char *name; /* Name of the generated parser */ 375 | char *arg; /* Declaration of the 3th argument to parser */ 376 | char *tokentype; /* Type of terminal symbols in the parser stack */ 377 | char *vartype; /* The default type of non-terminal symbols */ 378 | char *start; /* Name of the start symbol for the grammar */ 379 | char *stacksize; /* Size of the parser stack */ 380 | char *include; /* Code to put at the start of the C file */ 381 | char *error; /* Code to execute when an error is seen */ 382 | char *overflow; /* Code to execute on a stack overflow */ 383 | char *failure; /* Code to execute on parser failure */ 384 | char *accept; /* Code to execute when the parser excepts */ 385 | char *extracode; /* Code appended to the generated file */ 386 | char *tokendest; /* Code to execute to destroy token data */ 387 | char *vardest; /* Code for the default non-terminal destructor */ 388 | char *filename; /* Name of the input file */ 389 | char *outname; /* Name of the current output file */ 390 | char *tokenprefix; /* A prefix added to token names in the .h file */ 391 | int nconflict; /* Number of parsing conflicts */ 392 | int tablesize; /* Size of the parse tables */ 393 | int basisflag; /* Print only basis configurations */ 394 | int has_fallback; /* True if any %fallback is seen in the grammar */ 395 | int nolinenosflag; /* True if #line statements should not be printed */ 396 | char *argv0; /* Name of the program */ 397 | }; 398 | 399 | #define MemoryCheck(X) if((X)==0){ \ 400 | extern void memory_error(); \ 401 | memory_error(); \ 402 | } 403 | 404 | /**************** From the file "table.h" *********************************/ 405 | /* 406 | ** All code in this file has been automatically generated 407 | ** from a specification in the file 408 | ** "table.q" 409 | ** by the associative array code building program "aagen". 410 | ** Do not edit this file! Instead, edit the specification 411 | ** file, then rerun aagen. 412 | */ 413 | /* 414 | ** Code for processing tables in the LEMON parser generator. 415 | */ 416 | /* Routines for handling a strings */ 417 | 418 | const char *Strsafe(const char *); 419 | 420 | void Strsafe_init(void); 421 | int Strsafe_insert(const char *); 422 | const char *Strsafe_find(const char *); 423 | 424 | /* Routines for handling symbols of the grammar */ 425 | 426 | struct symbol *Symbol_new(const char *); 427 | int Symbolcmpp(const void *, const void *); 428 | void Symbol_init(void); 429 | int Symbol_insert(struct symbol *, const char *); 430 | struct symbol *Symbol_find(const char *); 431 | struct symbol *Symbol_Nth(int); 432 | int Symbol_count(void); 433 | struct symbol **Symbol_arrayof(void); 434 | 435 | /* Routines to manage the state table */ 436 | 437 | int Configcmp(const char *, const char *); 438 | struct state *State_new(void); 439 | void State_init(void); 440 | int State_insert(struct state *, struct config *); 441 | struct state *State_find(struct config *); 442 | struct state **State_arrayof(/* */); 443 | 444 | /* Routines used for efficiency in Configlist_add */ 445 | 446 | void Configtable_init(void); 447 | int Configtable_insert(struct config *); 448 | struct config *Configtable_find(struct config *); 449 | void Configtable_clear(int(*)(struct config *)); 450 | 451 | /****************** From the file "action.c" *******************************/ 452 | /* 453 | ** Routines processing parser actions in the LEMON parser generator. 454 | */ 455 | 456 | /* Allocate a new parser action */ 457 | static struct action *Action_new(void){ 458 | static struct action *freelist = 0; 459 | struct action *newaction; 460 | 461 | if( freelist==0 ){ 462 | int i; 463 | int amt = 100; 464 | freelist = (struct action *)calloc(amt, sizeof(struct action)); 465 | if( freelist==0 ){ 466 | fprintf(stderr,"Unable to allocate memory for a new parser action."); 467 | exit(1); 468 | } 469 | for(i=0; inext; 474 | return newaction; 475 | } 476 | 477 | /* Compare two actions for sorting purposes. Return negative, zero, or 478 | ** positive if the first action is less than, equal to, or greater than 479 | ** the first 480 | */ 481 | static int actioncmp( 482 | struct action *ap1, 483 | struct action *ap2 484 | ){ 485 | int rc; 486 | rc = ap1->sp->index - ap2->sp->index; 487 | if( rc==0 ){ 488 | rc = (int)ap1->type - (int)ap2->type; 489 | } 490 | if( rc==0 && ap1->type==REDUCE ){ 491 | rc = ap1->x.rp->index - ap2->x.rp->index; 492 | } 493 | if( rc==0 ){ 494 | rc = (int) (ap2 - ap1); 495 | } 496 | return rc; 497 | } 498 | 499 | /* Sort parser actions */ 500 | static struct action *Action_sort( 501 | struct action *ap 502 | ){ 503 | ap = (struct action *)msort((char *)ap,(char **)&ap->next, 504 | (int(*)(const char*,const char*))actioncmp); 505 | return ap; 506 | } 507 | 508 | void Action_add( 509 | struct action **app, 510 | enum e_action type, 511 | struct symbol *sp, 512 | char *arg 513 | ){ 514 | struct action *newaction; 515 | newaction = Action_new(); 516 | newaction->next = *app; 517 | *app = newaction; 518 | newaction->type = type; 519 | newaction->sp = sp; 520 | if( type==SHIFT ){ 521 | newaction->x.stp = (struct state *)arg; 522 | }else{ 523 | newaction->x.rp = (struct rule *)arg; 524 | } 525 | } 526 | /********************** New code to implement the "acttab" module ***********/ 527 | /* 528 | ** This module implements routines use to construct the yy_action[] table. 529 | */ 530 | 531 | /* 532 | ** The state of the yy_action table under construction is an instance of 533 | ** the following structure. 534 | ** 535 | ** The yy_action table maps the pair (state_number, lookahead) into an 536 | ** action_number. The table is an array of integers pairs. The state_number 537 | ** determines an initial offset into the yy_action array. The lookahead 538 | ** value is then added to this initial offset to get an index X into the 539 | ** yy_action array. If the aAction[X].lookahead equals the value of the 540 | ** of the lookahead input, then the value of the action_number output is 541 | ** aAction[X].action. If the lookaheads do not match then the 542 | ** default action for the state_number is returned. 543 | ** 544 | ** All actions associated with a single state_number are first entered 545 | ** into aLookahead[] using multiple calls to acttab_action(). Then the 546 | ** actions for that single state_number are placed into the aAction[] 547 | ** array with a single call to acttab_insert(). The acttab_insert() call 548 | ** also resets the aLookahead[] array in preparation for the next 549 | ** state number. 550 | */ 551 | struct lookahead_action { 552 | int lookahead; /* Value of the lookahead token */ 553 | int action; /* Action to take on the given lookahead */ 554 | }; 555 | typedef struct acttab acttab; 556 | struct acttab { 557 | int nAction; /* Number of used slots in aAction[] */ 558 | int nActionAlloc; /* Slots allocated for aAction[] */ 559 | struct lookahead_action 560 | *aAction, /* The yy_action[] table under construction */ 561 | *aLookahead; /* A single new transaction set */ 562 | int mnLookahead; /* Minimum aLookahead[].lookahead */ 563 | int mnAction; /* Action associated with mnLookahead */ 564 | int mxLookahead; /* Maximum aLookahead[].lookahead */ 565 | int nLookahead; /* Used slots in aLookahead[] */ 566 | int nLookaheadAlloc; /* Slots allocated in aLookahead[] */ 567 | }; 568 | 569 | /* Return the number of entries in the yy_action table */ 570 | #define acttab_size(X) ((X)->nAction) 571 | 572 | /* The value for the N-th entry in yy_action */ 573 | #define acttab_yyaction(X,N) ((X)->aAction[N].action) 574 | 575 | /* The value for the N-th entry in yy_lookahead */ 576 | #define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead) 577 | 578 | /* Free all memory associated with the given acttab */ 579 | void acttab_free(acttab *p){ 580 | free( p->aAction ); 581 | free( p->aLookahead ); 582 | free( p ); 583 | } 584 | 585 | /* Allocate a new acttab structure */ 586 | acttab *acttab_alloc(void){ 587 | acttab *p = (acttab *) calloc( 1, sizeof(*p) ); 588 | if( p==0 ){ 589 | fprintf(stderr,"Unable to allocate memory for a new acttab."); 590 | exit(1); 591 | } 592 | memset(p, 0, sizeof(*p)); 593 | return p; 594 | } 595 | 596 | /* Add a new action to the current transaction set. 597 | ** 598 | ** This routine is called once for each lookahead for a particular 599 | ** state. 600 | */ 601 | void acttab_action(acttab *p, int lookahead, int action){ 602 | if( p->nLookahead>=p->nLookaheadAlloc ){ 603 | p->nLookaheadAlloc += 25; 604 | p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead, 605 | sizeof(p->aLookahead[0])*p->nLookaheadAlloc ); 606 | if( p->aLookahead==0 ){ 607 | fprintf(stderr,"malloc failed\n"); 608 | exit(1); 609 | } 610 | } 611 | if( p->nLookahead==0 ){ 612 | p->mxLookahead = lookahead; 613 | p->mnLookahead = lookahead; 614 | p->mnAction = action; 615 | }else{ 616 | if( p->mxLookaheadmxLookahead = lookahead; 617 | if( p->mnLookahead>lookahead ){ 618 | p->mnLookahead = lookahead; 619 | p->mnAction = action; 620 | } 621 | } 622 | p->aLookahead[p->nLookahead].lookahead = lookahead; 623 | p->aLookahead[p->nLookahead].action = action; 624 | p->nLookahead++; 625 | } 626 | 627 | /* 628 | ** Add the transaction set built up with prior calls to acttab_action() 629 | ** into the current action table. Then reset the transaction set back 630 | ** to an empty set in preparation for a new round of acttab_action() calls. 631 | ** 632 | ** Return the offset into the action table of the new transaction. 633 | */ 634 | int acttab_insert(acttab *p){ 635 | int i, j, k, n; 636 | assert( p->nLookahead>0 ); 637 | 638 | /* Make sure we have enough space to hold the expanded action table 639 | ** in the worst case. The worst case occurs if the transaction set 640 | ** must be appended to the current action table 641 | */ 642 | n = p->mxLookahead + 1; 643 | if( p->nAction + n >= p->nActionAlloc ){ 644 | int oldAlloc = p->nActionAlloc; 645 | p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20; 646 | p->aAction = (struct lookahead_action *) realloc( p->aAction, 647 | sizeof(p->aAction[0])*p->nActionAlloc); 648 | if( p->aAction==0 ){ 649 | fprintf(stderr,"malloc failed\n"); 650 | exit(1); 651 | } 652 | for(i=oldAlloc; inActionAlloc; i++){ 653 | p->aAction[i].lookahead = -1; 654 | p->aAction[i].action = -1; 655 | } 656 | } 657 | 658 | /* Scan the existing action table looking for an offset that is a 659 | ** duplicate of the current transaction set. Fall out of the loop 660 | ** if and when the duplicate is found. 661 | ** 662 | ** i is the index in p->aAction[] where p->mnLookahead is inserted. 663 | */ 664 | for(i=p->nAction-1; i>=0; i--){ 665 | if( p->aAction[i].lookahead==p->mnLookahead ){ 666 | /* All lookaheads and actions in the aLookahead[] transaction 667 | ** must match against the candidate aAction[i] entry. */ 668 | if( p->aAction[i].action!=p->mnAction ) continue; 669 | for(j=0; jnLookahead; j++){ 670 | k = p->aLookahead[j].lookahead - p->mnLookahead + i; 671 | if( k<0 || k>=p->nAction ) break; 672 | if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break; 673 | if( p->aLookahead[j].action!=p->aAction[k].action ) break; 674 | } 675 | if( jnLookahead ) continue; 676 | 677 | /* No possible lookahead value that is not in the aLookahead[] 678 | ** transaction is allowed to match aAction[i] */ 679 | n = 0; 680 | for(j=0; jnAction; j++){ 681 | if( p->aAction[j].lookahead<0 ) continue; 682 | if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++; 683 | } 684 | if( n==p->nLookahead ){ 685 | break; /* An exact match is found at offset i */ 686 | } 687 | } 688 | } 689 | 690 | /* If no existing offsets exactly match the current transaction, find an 691 | ** an empty offset in the aAction[] table in which we can add the 692 | ** aLookahead[] transaction. 693 | */ 694 | if( i<0 ){ 695 | /* Look for holes in the aAction[] table that fit the current 696 | ** aLookahead[] transaction. Leave i set to the offset of the hole. 697 | ** If no holes are found, i is left at p->nAction, which means the 698 | ** transaction will be appended. */ 699 | for(i=0; inActionAlloc - p->mxLookahead; i++){ 700 | if( p->aAction[i].lookahead<0 ){ 701 | for(j=0; jnLookahead; j++){ 702 | k = p->aLookahead[j].lookahead - p->mnLookahead + i; 703 | if( k<0 ) break; 704 | if( p->aAction[k].lookahead>=0 ) break; 705 | } 706 | if( jnLookahead ) continue; 707 | for(j=0; jnAction; j++){ 708 | if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break; 709 | } 710 | if( j==p->nAction ){ 711 | break; /* Fits in empty slots */ 712 | } 713 | } 714 | } 715 | } 716 | /* Insert transaction set at index i. */ 717 | for(j=0; jnLookahead; j++){ 718 | k = p->aLookahead[j].lookahead - p->mnLookahead + i; 719 | p->aAction[k] = p->aLookahead[j]; 720 | if( k>=p->nAction ) p->nAction = k+1; 721 | } 722 | p->nLookahead = 0; 723 | 724 | /* Return the offset that is added to the lookahead in order to get the 725 | ** index into yy_action of the action */ 726 | return i - p->mnLookahead; 727 | } 728 | 729 | /********************** From the file "build.c" *****************************/ 730 | /* 731 | ** Routines to construction the finite state machine for the LEMON 732 | ** parser generator. 733 | */ 734 | 735 | /* Find a precedence symbol of every rule in the grammar. 736 | ** 737 | ** Those rules which have a precedence symbol coded in the input 738 | ** grammar using the "[symbol]" construct will already have the 739 | ** rp->precsym field filled. Other rules take as their precedence 740 | ** symbol the first RHS symbol with a defined precedence. If there 741 | ** are not RHS symbols with a defined precedence, the precedence 742 | ** symbol field is left blank. 743 | */ 744 | void FindRulePrecedences(struct lemon *xp) 745 | { 746 | struct rule *rp; 747 | for(rp=xp->rule; rp; rp=rp->next){ 748 | if( rp->precsym==0 ){ 749 | int i, j; 750 | for(i=0; inrhs && rp->precsym==0; i++){ 751 | struct symbol *sp = rp->rhs[i]; 752 | if( sp->type==MULTITERMINAL ){ 753 | for(j=0; jnsubsym; j++){ 754 | if( sp->subsym[j]->prec>=0 ){ 755 | rp->precsym = sp->subsym[j]; 756 | break; 757 | } 758 | } 759 | }else if( sp->prec>=0 ){ 760 | rp->precsym = rp->rhs[i]; 761 | } 762 | } 763 | } 764 | } 765 | return; 766 | } 767 | 768 | /* Find all nonterminals which will generate the empty string. 769 | ** Then go back and compute the first sets of every nonterminal. 770 | ** The first set is the set of all terminal symbols which can begin 771 | ** a string generated by that nonterminal. 772 | */ 773 | void FindFirstSets(struct lemon *lemp) 774 | { 775 | int i, j; 776 | struct rule *rp; 777 | int progress; 778 | 779 | for(i=0; insymbol; i++){ 780 | lemp->symbols[i]->lambda = LEMON_FALSE; 781 | } 782 | for(i=lemp->nterminal; insymbol; i++){ 783 | lemp->symbols[i]->firstset = SetNew(); 784 | } 785 | 786 | /* First compute all lambdas */ 787 | do{ 788 | progress = 0; 789 | for(rp=lemp->rule; rp; rp=rp->next){ 790 | if( rp->lhs->lambda ) continue; 791 | for(i=0; inrhs; i++){ 792 | struct symbol *sp = rp->rhs[i]; 793 | assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE ); 794 | if( sp->lambda==LEMON_FALSE ) break; 795 | } 796 | if( i==rp->nrhs ){ 797 | rp->lhs->lambda = LEMON_TRUE; 798 | progress = 1; 799 | } 800 | } 801 | }while( progress ); 802 | 803 | /* Now compute all first sets */ 804 | do{ 805 | struct symbol *s1, *s2; 806 | progress = 0; 807 | for(rp=lemp->rule; rp; rp=rp->next){ 808 | s1 = rp->lhs; 809 | for(i=0; inrhs; i++){ 810 | s2 = rp->rhs[i]; 811 | if( s2->type==TERMINAL ){ 812 | progress += SetAdd(s1->firstset,s2->index); 813 | break; 814 | }else if( s2->type==MULTITERMINAL ){ 815 | for(j=0; jnsubsym; j++){ 816 | progress += SetAdd(s1->firstset,s2->subsym[j]->index); 817 | } 818 | break; 819 | }else if( s1==s2 ){ 820 | if( s1->lambda==LEMON_FALSE ) break; 821 | }else{ 822 | progress += SetUnion(s1->firstset,s2->firstset); 823 | if( s2->lambda==LEMON_FALSE ) break; 824 | } 825 | } 826 | } 827 | }while( progress ); 828 | return; 829 | } 830 | 831 | /* Compute all LR(0) states for the grammar. Links 832 | ** are added to between some states so that the LR(1) follow sets 833 | ** can be computed later. 834 | */ 835 | PRIVATE struct state *getstate(struct lemon *); /* forward reference */ 836 | void FindStates(struct lemon *lemp) 837 | { 838 | struct symbol *sp; 839 | struct rule *rp; 840 | 841 | Configlist_init(); 842 | 843 | /* Find the start symbol */ 844 | if( lemp->start ){ 845 | sp = Symbol_find(lemp->start); 846 | if( sp==0 ){ 847 | ErrorMsg(lemp->filename,0, 848 | "The specified start symbol \"%s\" is not \ 849 | in a nonterminal of the grammar. \"%s\" will be used as the start \ 850 | symbol instead.",lemp->start,lemp->rule->lhs->name); 851 | lemp->errorcnt++; 852 | sp = lemp->rule->lhs; 853 | } 854 | }else{ 855 | sp = lemp->rule->lhs; 856 | } 857 | 858 | /* Make sure the start symbol doesn't occur on the right-hand side of 859 | ** any rule. Report an error if it does. (YACC would generate a new 860 | ** start symbol in this case.) */ 861 | for(rp=lemp->rule; rp; rp=rp->next){ 862 | int i; 863 | for(i=0; inrhs; i++){ 864 | if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */ 865 | ErrorMsg(lemp->filename,0, 866 | "The start symbol \"%s\" occurs on the \ 867 | right-hand side of a rule. This will result in a parser which \ 868 | does not work properly.",sp->name); 869 | lemp->errorcnt++; 870 | } 871 | } 872 | } 873 | 874 | /* The basis configuration set for the first state 875 | ** is all rules which have the start symbol as their 876 | ** left-hand side */ 877 | for(rp=sp->rule; rp; rp=rp->nextlhs){ 878 | struct config *newcfp; 879 | rp->lhsStart = 1; 880 | newcfp = Configlist_addbasis(rp,0); 881 | SetAdd(newcfp->fws,0); 882 | } 883 | 884 | /* Compute the first state. All other states will be 885 | ** computed automatically during the computation of the first one. 886 | ** The returned pointer to the first state is not used. */ 887 | (void)getstate(lemp); 888 | return; 889 | } 890 | 891 | /* Return a pointer to a state which is described by the configuration 892 | ** list which has been built from calls to Configlist_add. 893 | */ 894 | PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */ 895 | PRIVATE struct state *getstate(struct lemon *lemp) 896 | { 897 | struct config *cfp, *bp; 898 | struct state *stp; 899 | 900 | /* Extract the sorted basis of the new state. The basis was constructed 901 | ** by prior calls to "Configlist_addbasis()". */ 902 | Configlist_sortbasis(); 903 | bp = Configlist_basis(); 904 | 905 | /* Get a state with the same basis */ 906 | stp = State_find(bp); 907 | if( stp ){ 908 | /* A state with the same basis already exists! Copy all the follow-set 909 | ** propagation links from the state under construction into the 910 | ** preexisting state, then return a pointer to the preexisting state */ 911 | struct config *x, *y; 912 | for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){ 913 | Plink_copy(&y->bplp,x->bplp); 914 | Plink_delete(x->fplp); 915 | x->fplp = x->bplp = 0; 916 | } 917 | cfp = Configlist_return(); 918 | Configlist_eat(cfp); 919 | }else{ 920 | /* This really is a new state. Construct all the details */ 921 | Configlist_closure(lemp); /* Compute the configuration closure */ 922 | Configlist_sort(); /* Sort the configuration closure */ 923 | cfp = Configlist_return(); /* Get a pointer to the config list */ 924 | stp = State_new(); /* A new state structure */ 925 | MemoryCheck(stp); 926 | stp->bp = bp; /* Remember the configuration basis */ 927 | stp->cfp = cfp; /* Remember the configuration closure */ 928 | stp->statenum = lemp->nstate++; /* Every state gets a sequence number */ 929 | stp->ap = 0; /* No actions, yet. */ 930 | State_insert(stp,stp->bp); /* Add to the state table */ 931 | buildshifts(lemp,stp); /* Recursively compute successor states */ 932 | } 933 | return stp; 934 | } 935 | 936 | /* 937 | ** Return true if two symbols are the same. 938 | */ 939 | int same_symbol(struct symbol *a, struct symbol *b) 940 | { 941 | int i; 942 | if( a==b ) return 1; 943 | if( a->type!=MULTITERMINAL ) return 0; 944 | if( b->type!=MULTITERMINAL ) return 0; 945 | if( a->nsubsym!=b->nsubsym ) return 0; 946 | for(i=0; insubsym; i++){ 947 | if( a->subsym[i]!=b->subsym[i] ) return 0; 948 | } 949 | return 1; 950 | } 951 | 952 | /* Construct all successor states to the given state. A "successor" 953 | ** state is any state which can be reached by a shift action. 954 | */ 955 | PRIVATE void buildshifts(struct lemon *lemp, struct state *stp) 956 | { 957 | struct config *cfp; /* For looping thru the config closure of "stp" */ 958 | struct config *bcfp; /* For the inner loop on config closure of "stp" */ 959 | struct config *newcfg; /* */ 960 | struct symbol *sp; /* Symbol following the dot in configuration "cfp" */ 961 | struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */ 962 | struct state *newstp; /* A pointer to a successor state */ 963 | 964 | /* Each configuration becomes complete after it contibutes to a successor 965 | ** state. Initially, all configurations are incomplete */ 966 | for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE; 967 | 968 | /* Loop through all configurations of the state "stp" */ 969 | for(cfp=stp->cfp; cfp; cfp=cfp->next){ 970 | if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */ 971 | if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */ 972 | Configlist_reset(); /* Reset the new config set */ 973 | sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */ 974 | 975 | /* For every configuration in the state "stp" which has the symbol "sp" 976 | ** following its dot, add the same configuration to the basis set under 977 | ** construction but with the dot shifted one symbol to the right. */ 978 | for(bcfp=cfp; bcfp; bcfp=bcfp->next){ 979 | if( bcfp->status==COMPLETE ) continue; /* Already used */ 980 | if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */ 981 | bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */ 982 | if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */ 983 | bcfp->status = COMPLETE; /* Mark this config as used */ 984 | newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1); 985 | Plink_add(&newcfg->bplp,bcfp); 986 | } 987 | 988 | /* Get a pointer to the state described by the basis configuration set 989 | ** constructed in the preceding loop */ 990 | newstp = getstate(lemp); 991 | 992 | /* The state "newstp" is reached from the state "stp" by a shift action 993 | ** on the symbol "sp" */ 994 | if( sp->type==MULTITERMINAL ){ 995 | int i; 996 | for(i=0; insubsym; i++){ 997 | Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp); 998 | } 999 | }else{ 1000 | Action_add(&stp->ap,SHIFT,sp,(char *)newstp); 1001 | } 1002 | } 1003 | } 1004 | 1005 | /* 1006 | ** Construct the propagation links 1007 | */ 1008 | void FindLinks(struct lemon *lemp) 1009 | { 1010 | int i; 1011 | struct config *cfp, *other; 1012 | struct state *stp; 1013 | struct plink *plp; 1014 | 1015 | /* Housekeeping detail: 1016 | ** Add to every propagate link a pointer back to the state to 1017 | ** which the link is attached. */ 1018 | for(i=0; instate; i++){ 1019 | stp = lemp->sorted[i]; 1020 | for(cfp=stp->cfp; cfp; cfp=cfp->next){ 1021 | cfp->stp = stp; 1022 | } 1023 | } 1024 | 1025 | /* Convert all backlinks into forward links. Only the forward 1026 | ** links are used in the follow-set computation. */ 1027 | for(i=0; instate; i++){ 1028 | stp = lemp->sorted[i]; 1029 | for(cfp=stp->cfp; cfp; cfp=cfp->next){ 1030 | for(plp=cfp->bplp; plp; plp=plp->next){ 1031 | other = plp->cfp; 1032 | Plink_add(&other->fplp,cfp); 1033 | } 1034 | } 1035 | } 1036 | } 1037 | 1038 | /* Compute all followsets. 1039 | ** 1040 | ** A followset is the set of all symbols which can come immediately 1041 | ** after a configuration. 1042 | */ 1043 | void FindFollowSets(struct lemon *lemp) 1044 | { 1045 | int i; 1046 | struct config *cfp; 1047 | struct plink *plp; 1048 | int progress; 1049 | int change; 1050 | 1051 | for(i=0; instate; i++){ 1052 | for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ 1053 | cfp->status = INCOMPLETE; 1054 | } 1055 | } 1056 | 1057 | do{ 1058 | progress = 0; 1059 | for(i=0; instate; i++){ 1060 | for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){ 1061 | if( cfp->status==COMPLETE ) continue; 1062 | for(plp=cfp->fplp; plp; plp=plp->next){ 1063 | change = SetUnion(plp->cfp->fws,cfp->fws); 1064 | if( change ){ 1065 | plp->cfp->status = INCOMPLETE; 1066 | progress = 1; 1067 | } 1068 | } 1069 | cfp->status = COMPLETE; 1070 | } 1071 | } 1072 | }while( progress ); 1073 | } 1074 | 1075 | static int resolve_conflict(struct action *,struct action *); 1076 | 1077 | /* Compute the reduce actions, and resolve conflicts. 1078 | */ 1079 | void FindActions(struct lemon *lemp) 1080 | { 1081 | int i,j; 1082 | struct config *cfp; 1083 | struct state *stp; 1084 | struct symbol *sp; 1085 | struct rule *rp; 1086 | 1087 | /* Add all of the reduce actions 1088 | ** A reduce action is added for each element of the followset of 1089 | ** a configuration which has its dot at the extreme right. 1090 | */ 1091 | for(i=0; instate; i++){ /* Loop over all states */ 1092 | stp = lemp->sorted[i]; 1093 | for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */ 1094 | if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */ 1095 | for(j=0; jnterminal; j++){ 1096 | if( SetFind(cfp->fws,j) ){ 1097 | /* Add a reduce action to the state "stp" which will reduce by the 1098 | ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */ 1099 | Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp); 1100 | } 1101 | } 1102 | } 1103 | } 1104 | } 1105 | 1106 | /* Add the accepting token */ 1107 | if( lemp->start ){ 1108 | sp = Symbol_find(lemp->start); 1109 | if( sp==0 ) sp = lemp->rule->lhs; 1110 | }else{ 1111 | sp = lemp->rule->lhs; 1112 | } 1113 | /* Add to the first state (which is always the starting state of the 1114 | ** finite state machine) an action to ACCEPT if the lookahead is the 1115 | ** start nonterminal. */ 1116 | Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0); 1117 | 1118 | /* Resolve conflicts */ 1119 | for(i=0; instate; i++){ 1120 | struct action *ap, *nap; 1121 | struct state *stp; 1122 | stp = lemp->sorted[i]; 1123 | /* assert( stp->ap ); */ 1124 | stp->ap = Action_sort(stp->ap); 1125 | for(ap=stp->ap; ap && ap->next; ap=ap->next){ 1126 | for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){ 1127 | /* The two actions "ap" and "nap" have the same lookahead. 1128 | ** Figure out which one should be used */ 1129 | lemp->nconflict += resolve_conflict(ap,nap); 1130 | } 1131 | } 1132 | } 1133 | 1134 | /* Report an error for each rule that can never be reduced. */ 1135 | for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE; 1136 | for(i=0; instate; i++){ 1137 | struct action *ap; 1138 | for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){ 1139 | if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE; 1140 | } 1141 | } 1142 | for(rp=lemp->rule; rp; rp=rp->next){ 1143 | if( rp->canReduce ) continue; 1144 | ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n"); 1145 | lemp->errorcnt++; 1146 | } 1147 | } 1148 | 1149 | /* Resolve a conflict between the two given actions. If the 1150 | ** conflict can't be resolved, return non-zero. 1151 | ** 1152 | ** NO LONGER TRUE: 1153 | ** To resolve a conflict, first look to see if either action 1154 | ** is on an error rule. In that case, take the action which 1155 | ** is not associated with the error rule. If neither or both 1156 | ** actions are associated with an error rule, then try to 1157 | ** use precedence to resolve the conflict. 1158 | ** 1159 | ** If either action is a SHIFT, then it must be apx. This 1160 | ** function won't work if apx->type==REDUCE and apy->type==SHIFT. 1161 | */ 1162 | static int resolve_conflict( 1163 | struct action *apx, 1164 | struct action *apy 1165 | ){ 1166 | struct symbol *spx, *spy; 1167 | int errcnt = 0; 1168 | assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ 1169 | if( apx->type==SHIFT && apy->type==SHIFT ){ 1170 | apy->type = SSCONFLICT; 1171 | errcnt++; 1172 | } 1173 | if( apx->type==SHIFT && apy->type==REDUCE ){ 1174 | spx = apx->sp; 1175 | spy = apy->x.rp->precsym; 1176 | if( spy==0 || spx->prec<0 || spy->prec<0 ){ 1177 | /* Not enough precedence information. */ 1178 | apy->type = SRCONFLICT; 1179 | errcnt++; 1180 | }else if( spx->prec>spy->prec ){ /* higher precedence wins */ 1181 | apy->type = RD_RESOLVED; 1182 | }else if( spx->precprec ){ 1183 | apx->type = SH_RESOLVED; 1184 | }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */ 1185 | apy->type = RD_RESOLVED; /* associativity */ 1186 | }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */ 1187 | apx->type = SH_RESOLVED; 1188 | }else{ 1189 | assert( spx->prec==spy->prec && spx->assoc==NONE ); 1190 | apx->type = ERROR; 1191 | } 1192 | }else if( apx->type==REDUCE && apy->type==REDUCE ){ 1193 | spx = apx->x.rp->precsym; 1194 | spy = apy->x.rp->precsym; 1195 | if( spx==0 || spy==0 || spx->prec<0 || 1196 | spy->prec<0 || spx->prec==spy->prec ){ 1197 | apy->type = RRCONFLICT; 1198 | errcnt++; 1199 | }else if( spx->prec>spy->prec ){ 1200 | apy->type = RD_RESOLVED; 1201 | }else if( spx->precprec ){ 1202 | apx->type = RD_RESOLVED; 1203 | } 1204 | }else{ 1205 | assert( 1206 | apx->type==SH_RESOLVED || 1207 | apx->type==RD_RESOLVED || 1208 | apx->type==SSCONFLICT || 1209 | apx->type==SRCONFLICT || 1210 | apx->type==RRCONFLICT || 1211 | apy->type==SH_RESOLVED || 1212 | apy->type==RD_RESOLVED || 1213 | apy->type==SSCONFLICT || 1214 | apy->type==SRCONFLICT || 1215 | apy->type==RRCONFLICT 1216 | ); 1217 | /* The REDUCE/SHIFT case cannot happen because SHIFTs come before 1218 | ** REDUCEs on the list. If we reach this point it must be because 1219 | ** the parser conflict had already been resolved. */ 1220 | } 1221 | return errcnt; 1222 | } 1223 | /********************* From the file "configlist.c" *************************/ 1224 | /* 1225 | ** Routines to processing a configuration list and building a state 1226 | ** in the LEMON parser generator. 1227 | */ 1228 | 1229 | static struct config *freelist = 0; /* List of free configurations */ 1230 | static struct config *current = 0; /* Top of list of configurations */ 1231 | static struct config **currentend = 0; /* Last on list of configs */ 1232 | static struct config *basis = 0; /* Top of list of basis configs */ 1233 | static struct config **basisend = 0; /* End of list of basis configs */ 1234 | 1235 | /* Return a pointer to a new configuration */ 1236 | PRIVATE struct config *newconfig(){ 1237 | struct config *newcfg; 1238 | if( freelist==0 ){ 1239 | int i; 1240 | int amt = 3; 1241 | freelist = (struct config *)calloc( amt, sizeof(struct config) ); 1242 | if( freelist==0 ){ 1243 | fprintf(stderr,"Unable to allocate memory for a new configuration."); 1244 | exit(1); 1245 | } 1246 | for(i=0; inext; 1251 | return newcfg; 1252 | } 1253 | 1254 | /* The configuration "old" is no longer used */ 1255 | PRIVATE void deleteconfig(struct config *old) 1256 | { 1257 | old->next = freelist; 1258 | freelist = old; 1259 | } 1260 | 1261 | /* Initialized the configuration list builder */ 1262 | void Configlist_init(){ 1263 | current = 0; 1264 | currentend = ¤t; 1265 | basis = 0; 1266 | basisend = &basis; 1267 | Configtable_init(); 1268 | return; 1269 | } 1270 | 1271 | /* Initialized the configuration list builder */ 1272 | void Configlist_reset(){ 1273 | current = 0; 1274 | currentend = ¤t; 1275 | basis = 0; 1276 | basisend = &basis; 1277 | Configtable_clear(0); 1278 | return; 1279 | } 1280 | 1281 | /* Add another configuration to the configuration list */ 1282 | struct config *Configlist_add( 1283 | struct rule *rp, /* The rule */ 1284 | int dot /* Index into the RHS of the rule where the dot goes */ 1285 | ){ 1286 | struct config *cfp, model; 1287 | 1288 | assert( currentend!=0 ); 1289 | model.rp = rp; 1290 | model.dot = dot; 1291 | cfp = Configtable_find(&model); 1292 | if( cfp==0 ){ 1293 | cfp = newconfig(); 1294 | cfp->rp = rp; 1295 | cfp->dot = dot; 1296 | cfp->fws = SetNew(); 1297 | cfp->stp = 0; 1298 | cfp->fplp = cfp->bplp = 0; 1299 | cfp->next = 0; 1300 | cfp->bp = 0; 1301 | *currentend = cfp; 1302 | currentend = &cfp->next; 1303 | Configtable_insert(cfp); 1304 | } 1305 | return cfp; 1306 | } 1307 | 1308 | /* Add a basis configuration to the configuration list */ 1309 | struct config *Configlist_addbasis(struct rule *rp, int dot) 1310 | { 1311 | struct config *cfp, model; 1312 | 1313 | assert( basisend!=0 ); 1314 | assert( currentend!=0 ); 1315 | model.rp = rp; 1316 | model.dot = dot; 1317 | cfp = Configtable_find(&model); 1318 | if( cfp==0 ){ 1319 | cfp = newconfig(); 1320 | cfp->rp = rp; 1321 | cfp->dot = dot; 1322 | cfp->fws = SetNew(); 1323 | cfp->stp = 0; 1324 | cfp->fplp = cfp->bplp = 0; 1325 | cfp->next = 0; 1326 | cfp->bp = 0; 1327 | *currentend = cfp; 1328 | currentend = &cfp->next; 1329 | *basisend = cfp; 1330 | basisend = &cfp->bp; 1331 | Configtable_insert(cfp); 1332 | } 1333 | return cfp; 1334 | } 1335 | 1336 | /* Compute the closure of the configuration list */ 1337 | void Configlist_closure(struct lemon *lemp) 1338 | { 1339 | struct config *cfp, *newcfp; 1340 | struct rule *rp, *newrp; 1341 | struct symbol *sp, *xsp; 1342 | int i, dot; 1343 | 1344 | assert( currentend!=0 ); 1345 | for(cfp=current; cfp; cfp=cfp->next){ 1346 | rp = cfp->rp; 1347 | dot = cfp->dot; 1348 | if( dot>=rp->nrhs ) continue; 1349 | sp = rp->rhs[dot]; 1350 | if( sp->type==NONTERMINAL ){ 1351 | if( sp->rule==0 && sp!=lemp->errsym ){ 1352 | ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.", 1353 | sp->name); 1354 | lemp->errorcnt++; 1355 | } 1356 | for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){ 1357 | newcfp = Configlist_add(newrp,0); 1358 | for(i=dot+1; inrhs; i++){ 1359 | xsp = rp->rhs[i]; 1360 | if( xsp->type==TERMINAL ){ 1361 | SetAdd(newcfp->fws,xsp->index); 1362 | break; 1363 | }else if( xsp->type==MULTITERMINAL ){ 1364 | int k; 1365 | for(k=0; knsubsym; k++){ 1366 | SetAdd(newcfp->fws, xsp->subsym[k]->index); 1367 | } 1368 | break; 1369 | }else{ 1370 | SetUnion(newcfp->fws,xsp->firstset); 1371 | if( xsp->lambda==LEMON_FALSE ) break; 1372 | } 1373 | } 1374 | if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp); 1375 | } 1376 | } 1377 | } 1378 | return; 1379 | } 1380 | 1381 | /* Sort the configuration list */ 1382 | void Configlist_sort(){ 1383 | current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp); 1384 | currentend = 0; 1385 | return; 1386 | } 1387 | 1388 | /* Sort the basis configuration list */ 1389 | void Configlist_sortbasis(){ 1390 | basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp); 1391 | basisend = 0; 1392 | return; 1393 | } 1394 | 1395 | /* Return a pointer to the head of the configuration list and 1396 | ** reset the list */ 1397 | struct config *Configlist_return(){ 1398 | struct config *old; 1399 | old = current; 1400 | current = 0; 1401 | currentend = 0; 1402 | return old; 1403 | } 1404 | 1405 | /* Return a pointer to the head of the configuration list and 1406 | ** reset the list */ 1407 | struct config *Configlist_basis(){ 1408 | struct config *old; 1409 | old = basis; 1410 | basis = 0; 1411 | basisend = 0; 1412 | return old; 1413 | } 1414 | 1415 | /* Free all elements of the given configuration list */ 1416 | void Configlist_eat(struct config *cfp) 1417 | { 1418 | struct config *nextcfp; 1419 | for(; cfp; cfp=nextcfp){ 1420 | nextcfp = cfp->next; 1421 | assert( cfp->fplp==0 ); 1422 | assert( cfp->bplp==0 ); 1423 | if( cfp->fws ) SetFree(cfp->fws); 1424 | deleteconfig(cfp); 1425 | } 1426 | return; 1427 | } 1428 | /***************** From the file "error.c" *********************************/ 1429 | /* 1430 | ** Code for printing error message. 1431 | */ 1432 | 1433 | void ErrorMsg(const char *filename, int lineno, const char *format, ...){ 1434 | va_list ap; 1435 | fprintf(stderr, "%s:%d: ", filename, lineno); 1436 | va_start(ap, format); 1437 | vfprintf(stderr,format,ap); 1438 | va_end(ap); 1439 | fprintf(stderr, "\n"); 1440 | } 1441 | /**************** From the file "main.c" ************************************/ 1442 | /* 1443 | ** Main program file for the LEMON parser generator. 1444 | */ 1445 | 1446 | /* Report an out-of-memory condition and abort. This function 1447 | ** is used mostly by the "MemoryCheck" macro in struct.h 1448 | */ 1449 | void memory_error(){ 1450 | fprintf(stderr,"Out of memory. Aborting...\n"); 1451 | exit(1); 1452 | } 1453 | 1454 | static int nDefine = 0; /* Number of -D options on the command line */ 1455 | static char **azDefine = 0; /* Name of the -D macros */ 1456 | 1457 | /* This routine is called with the argument to each -D command-line option. 1458 | ** Add the macro defined to the azDefine array. 1459 | */ 1460 | static void handle_D_option(char *z){ 1461 | char **paz; 1462 | nDefine++; 1463 | azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine); 1464 | if( azDefine==0 ){ 1465 | fprintf(stderr,"out of memory\n"); 1466 | exit(1); 1467 | } 1468 | paz = &azDefine[nDefine-1]; 1469 | *paz = (char *) malloc( lemonStrlen(z)+1 ); 1470 | if( *paz==0 ){ 1471 | fprintf(stderr,"out of memory\n"); 1472 | exit(1); 1473 | } 1474 | lemon_strcpy(*paz, z); 1475 | for(z=*paz; *z && *z!='='; z++){} 1476 | *z = 0; 1477 | } 1478 | 1479 | static void handle_option(char *z, char **out){ 1480 | *out = (char *) malloc( lemonStrlen(z)+1 ); 1481 | if( *out==0 ){ 1482 | memory_error(); 1483 | } 1484 | lemon_strcpy(*out, z); 1485 | } 1486 | 1487 | static char *header_extension = ".h"; 1488 | static void handle_H_option(char *z){ 1489 | handle_option(z, &header_extension); 1490 | } 1491 | 1492 | static char *filename_prefix = ""; 1493 | static void handle_P_option(char *z){ 1494 | handle_option(z, &filename_prefix); 1495 | } 1496 | 1497 | static char *user_templatename = NULL; 1498 | static void handle_T_option(char *z){ 1499 | handle_option(z, &user_templatename); 1500 | } 1501 | 1502 | /* The main program. Parse the command line and do it... */ 1503 | int main(int argc, char **argv) 1504 | { 1505 | static int version = 0; 1506 | static int rpflag = 0; 1507 | static int basisflag = 0; 1508 | static int compress = 0; 1509 | static int quiet = 0; 1510 | static int statistics = 0; 1511 | static int mhflag = 0; 1512 | static int nolinenosflag = 0; 1513 | static int noResort = 0; 1514 | static struct s_options options[] = { 1515 | {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."}, 1516 | {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."}, 1517 | {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."}, 1518 | {OPT_FSTR, "H", (char*)handle_H_option, "Specify a header extension."}, 1519 | {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."}, 1520 | {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, 1521 | {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."}, 1522 | {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."}, 1523 | {OPT_FSTR, "P", (char*)handle_P_option, "Specify a filename prefix."}, 1524 | {OPT_FLAG, "p", (char*)&showPrecedenceConflict, 1525 | "Show conflicts resolved by precedence rules"}, 1526 | {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, 1527 | {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"}, 1528 | {OPT_FLAG, "s", (char*)&statistics, 1529 | "Print parser stats to standard output."}, 1530 | {OPT_FLAG, "x", (char*)&version, "Print the version number."}, 1531 | {OPT_FLAG,0,0,0} 1532 | }; 1533 | int i; 1534 | int exitcode; 1535 | struct lemon lem; 1536 | 1537 | OptInit(argv,options,stderr); 1538 | if( version ){ 1539 | printf("Lemon version 1.0\n"); 1540 | exit(0); 1541 | } 1542 | if( OptNArgs()!=1 ){ 1543 | fprintf(stderr,"Exactly one filename argument is required.\n"); 1544 | exit(1); 1545 | } 1546 | memset(&lem, 0, sizeof(lem)); 1547 | lem.errorcnt = 0; 1548 | 1549 | /* Initialize the machine */ 1550 | Strsafe_init(); 1551 | Symbol_init(); 1552 | State_init(); 1553 | lem.argv0 = argv[0]; 1554 | lem.filename = OptArg(0); 1555 | lem.basisflag = basisflag; 1556 | lem.nolinenosflag = nolinenosflag; 1557 | Symbol_new("$"); 1558 | lem.errsym = Symbol_new("error"); 1559 | lem.errsym->useCnt = 0; 1560 | 1561 | /* Parse the input file */ 1562 | Parse(&lem); 1563 | if( lem.errorcnt ) exit(lem.errorcnt); 1564 | if( lem.nrule==0 ){ 1565 | fprintf(stderr,"Empty grammar.\n"); 1566 | exit(1); 1567 | } 1568 | 1569 | /* Count and index the symbols of the grammar */ 1570 | Symbol_new("{default}"); 1571 | lem.nsymbol = Symbol_count(); 1572 | lem.symbols = Symbol_arrayof(); 1573 | for(i=0; iindex = i; 1574 | qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp); 1575 | for(i=0; iindex = i; 1576 | while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; } 1577 | assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 ); 1578 | lem.nsymbol = i - 1; 1579 | for(i=1; isupper(lem.symbols[i]->name[0]); i++); 1580 | lem.nterminal = i; 1581 | 1582 | /* Generate a reprint of the grammar, if requested on the command line */ 1583 | if( rpflag ){ 1584 | Reprint(&lem); 1585 | }else{ 1586 | /* Initialize the size for all follow and first sets */ 1587 | SetSize(lem.nterminal+1); 1588 | 1589 | /* Find the precedence for every production rule (that has one) */ 1590 | FindRulePrecedences(&lem); 1591 | 1592 | /* Compute the lambda-nonterminals and the first-sets for every 1593 | ** nonterminal */ 1594 | FindFirstSets(&lem); 1595 | 1596 | /* Compute all LR(0) states. Also record follow-set propagation 1597 | ** links so that the follow-set can be computed later */ 1598 | lem.nstate = 0; 1599 | FindStates(&lem); 1600 | lem.sorted = State_arrayof(); 1601 | 1602 | /* Tie up loose ends on the propagation links */ 1603 | FindLinks(&lem); 1604 | 1605 | /* Compute the follow set of every reducible configuration */ 1606 | FindFollowSets(&lem); 1607 | 1608 | /* Compute the action tables */ 1609 | FindActions(&lem); 1610 | 1611 | /* Compress the action tables */ 1612 | if( compress==0 ) CompressTables(&lem); 1613 | 1614 | /* Reorder and renumber the states so that states with fewer choices 1615 | ** occur at the end. This is an optimization that helps make the 1616 | ** generated parser tables smaller. */ 1617 | if( noResort==0 ) ResortStates(&lem); 1618 | 1619 | /* Generate a report of the parser generated. (the "y.output" file) */ 1620 | if( !quiet ) ReportOutput(&lem); 1621 | 1622 | /* Generate the source code for the parser */ 1623 | ReportTable(&lem, mhflag); 1624 | 1625 | /* Produce a header file for use by the scanner. (This step is 1626 | ** omitted if the "-m" option is used because makeheaders will 1627 | ** generate the file for us.) */ 1628 | if( !mhflag ) ReportHeader(&lem); 1629 | } 1630 | if( statistics ){ 1631 | printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n", 1632 | lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule); 1633 | printf(" %d states, %d parser table entries, %d conflicts\n", 1634 | lem.nstate, lem.tablesize, lem.nconflict); 1635 | } 1636 | if( lem.nconflict > 0 ){ 1637 | fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); 1638 | } 1639 | 1640 | /* return 0 on success, 1 on failure. */ 1641 | exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0; 1642 | exit(exitcode); 1643 | return (exitcode); 1644 | } 1645 | /******************** From the file "msort.c" *******************************/ 1646 | /* 1647 | ** A generic merge-sort program. 1648 | ** 1649 | ** USAGE: 1650 | ** Let "ptr" be a pointer to some structure which is at the head of 1651 | ** a null-terminated list. Then to sort the list call: 1652 | ** 1653 | ** ptr = msort(ptr,&(ptr->next),cmpfnc); 1654 | ** 1655 | ** In the above, "cmpfnc" is a pointer to a function which compares 1656 | ** two instances of the structure and returns an integer, as in 1657 | ** strcmp. The second argument is a pointer to the pointer to the 1658 | ** second element of the linked list. This address is used to compute 1659 | ** the offset to the "next" field within the structure. The offset to 1660 | ** the "next" field must be constant for all structures in the list. 1661 | ** 1662 | ** The function returns a new pointer which is the head of the list 1663 | ** after sorting. 1664 | ** 1665 | ** ALGORITHM: 1666 | ** Merge-sort. 1667 | */ 1668 | 1669 | /* 1670 | ** Return a pointer to the next structure in the linked list. 1671 | */ 1672 | #define NEXT(A) (*(char**)(((char*)A)+offset)) 1673 | 1674 | /* 1675 | ** Inputs: 1676 | ** a: A sorted, null-terminated linked list. (May be null). 1677 | ** b: A sorted, null-terminated linked list. (May be null). 1678 | ** cmp: A pointer to the comparison function. 1679 | ** offset: Offset in the structure to the "next" field. 1680 | ** 1681 | ** Return Value: 1682 | ** A pointer to the head of a sorted list containing the elements 1683 | ** of both a and b. 1684 | ** 1685 | ** Side effects: 1686 | ** The "next" pointers for elements in the lists a and b are 1687 | ** changed. 1688 | */ 1689 | static char *merge( 1690 | char *a, 1691 | char *b, 1692 | int (*cmp)(const char*,const char*), 1693 | int offset 1694 | ){ 1695 | char *ptr, *head; 1696 | 1697 | if( a==0 ){ 1698 | head = b; 1699 | }else if( b==0 ){ 1700 | head = a; 1701 | }else{ 1702 | if( (*cmp)(a,b)<=0 ){ 1703 | ptr = a; 1704 | a = NEXT(a); 1705 | }else{ 1706 | ptr = b; 1707 | b = NEXT(b); 1708 | } 1709 | head = ptr; 1710 | while( a && b ){ 1711 | if( (*cmp)(a,b)<=0 ){ 1712 | NEXT(ptr) = a; 1713 | ptr = a; 1714 | a = NEXT(a); 1715 | }else{ 1716 | NEXT(ptr) = b; 1717 | ptr = b; 1718 | b = NEXT(b); 1719 | } 1720 | } 1721 | if( a ) NEXT(ptr) = a; 1722 | else NEXT(ptr) = b; 1723 | } 1724 | return head; 1725 | } 1726 | 1727 | /* 1728 | ** Inputs: 1729 | ** list: Pointer to a singly-linked list of structures. 1730 | ** next: Pointer to pointer to the second element of the list. 1731 | ** cmp: A comparison function. 1732 | ** 1733 | ** Return Value: 1734 | ** A pointer to the head of a sorted list containing the elements 1735 | ** orginally in list. 1736 | ** 1737 | ** Side effects: 1738 | ** The "next" pointers for elements in list are changed. 1739 | */ 1740 | #define LISTSIZE 30 1741 | static char *msort( 1742 | char *list, 1743 | char **next, 1744 | int (*cmp)(const char*,const char*) 1745 | ){ 1746 | unsigned long offset; 1747 | char *ep; 1748 | char *set[LISTSIZE]; 1749 | int i; 1750 | offset = (unsigned long)next - (unsigned long)list; 1751 | for(i=0; istate = WAITING_FOR_DECL_KEYWORD; 2114 | }else if( islower(x[0]) ){ 2115 | psp->lhs = Symbol_new(x); 2116 | psp->nrhs = 0; 2117 | psp->lhsalias = 0; 2118 | psp->state = WAITING_FOR_ARROW; 2119 | }else if( x[0]=='{' ){ 2120 | if( psp->prevrule==0 ){ 2121 | ErrorMsg(psp->filename,psp->tokenlineno, 2122 | "There is no prior rule upon which to attach the code \ 2123 | fragment which begins on this line."); 2124 | psp->errorcnt++; 2125 | }else if( psp->prevrule->code!=0 ){ 2126 | ErrorMsg(psp->filename,psp->tokenlineno, 2127 | "Code fragment beginning on this line is not the first \ 2128 | to follow the previous rule."); 2129 | psp->errorcnt++; 2130 | }else{ 2131 | psp->prevrule->line = psp->tokenlineno; 2132 | psp->prevrule->code = &x[1]; 2133 | } 2134 | }else if( x[0]=='[' ){ 2135 | psp->state = PRECEDENCE_MARK_1; 2136 | }else{ 2137 | ErrorMsg(psp->filename,psp->tokenlineno, 2138 | "Token \"%s\" should be either \"%%\" or a nonterminal name.", 2139 | x); 2140 | psp->errorcnt++; 2141 | } 2142 | break; 2143 | case PRECEDENCE_MARK_1: 2144 | if( !isupper(x[0]) ){ 2145 | ErrorMsg(psp->filename,psp->tokenlineno, 2146 | "The precedence symbol must be a terminal."); 2147 | psp->errorcnt++; 2148 | }else if( psp->prevrule==0 ){ 2149 | ErrorMsg(psp->filename,psp->tokenlineno, 2150 | "There is no prior rule to assign precedence \"[%s]\".",x); 2151 | psp->errorcnt++; 2152 | }else if( psp->prevrule->precsym!=0 ){ 2153 | ErrorMsg(psp->filename,psp->tokenlineno, 2154 | "Precedence mark on this line is not the first \ 2155 | to follow the previous rule."); 2156 | psp->errorcnt++; 2157 | }else{ 2158 | psp->prevrule->precsym = Symbol_new(x); 2159 | } 2160 | psp->state = PRECEDENCE_MARK_2; 2161 | break; 2162 | case PRECEDENCE_MARK_2: 2163 | if( x[0]!=']' ){ 2164 | ErrorMsg(psp->filename,psp->tokenlineno, 2165 | "Missing \"]\" on precedence mark."); 2166 | psp->errorcnt++; 2167 | } 2168 | psp->state = WAITING_FOR_DECL_OR_RULE; 2169 | break; 2170 | case WAITING_FOR_ARROW: 2171 | if( x[0]==':' && x[1]==':' && x[2]=='=' ){ 2172 | psp->state = IN_RHS; 2173 | }else if( x[0]=='(' ){ 2174 | psp->state = LHS_ALIAS_1; 2175 | }else{ 2176 | ErrorMsg(psp->filename,psp->tokenlineno, 2177 | "Expected to see a \":\" following the LHS symbol \"%s\".", 2178 | psp->lhs->name); 2179 | psp->errorcnt++; 2180 | psp->state = RESYNC_AFTER_RULE_ERROR; 2181 | } 2182 | break; 2183 | case LHS_ALIAS_1: 2184 | if( isalpha(x[0]) ){ 2185 | psp->lhsalias = x; 2186 | psp->state = LHS_ALIAS_2; 2187 | }else{ 2188 | ErrorMsg(psp->filename,psp->tokenlineno, 2189 | "\"%s\" is not a valid alias for the LHS \"%s\"\n", 2190 | x,psp->lhs->name); 2191 | psp->errorcnt++; 2192 | psp->state = RESYNC_AFTER_RULE_ERROR; 2193 | } 2194 | break; 2195 | case LHS_ALIAS_2: 2196 | if( x[0]==')' ){ 2197 | psp->state = LHS_ALIAS_3; 2198 | }else{ 2199 | ErrorMsg(psp->filename,psp->tokenlineno, 2200 | "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); 2201 | psp->errorcnt++; 2202 | psp->state = RESYNC_AFTER_RULE_ERROR; 2203 | } 2204 | break; 2205 | case LHS_ALIAS_3: 2206 | if( x[0]==':' && x[1]==':' && x[2]=='=' ){ 2207 | psp->state = IN_RHS; 2208 | }else{ 2209 | ErrorMsg(psp->filename,psp->tokenlineno, 2210 | "Missing \"->\" following: \"%s(%s)\".", 2211 | psp->lhs->name,psp->lhsalias); 2212 | psp->errorcnt++; 2213 | psp->state = RESYNC_AFTER_RULE_ERROR; 2214 | } 2215 | break; 2216 | case IN_RHS: 2217 | if( x[0]=='.' ){ 2218 | struct rule *rp; 2219 | rp = (struct rule *)calloc( sizeof(struct rule) + 2220 | sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1); 2221 | if( rp==0 ){ 2222 | ErrorMsg(psp->filename,psp->tokenlineno, 2223 | "Can't allocate enough memory for this rule."); 2224 | psp->errorcnt++; 2225 | psp->prevrule = 0; 2226 | }else{ 2227 | int i; 2228 | rp->ruleline = psp->tokenlineno; 2229 | rp->rhs = (struct symbol**)&rp[1]; 2230 | rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]); 2231 | for(i=0; inrhs; i++){ 2232 | rp->rhs[i] = psp->rhs[i]; 2233 | rp->rhsalias[i] = psp->alias[i]; 2234 | } 2235 | rp->lhs = psp->lhs; 2236 | rp->lhsalias = psp->lhsalias; 2237 | rp->nrhs = psp->nrhs; 2238 | rp->code = 0; 2239 | rp->precsym = 0; 2240 | rp->index = psp->gp->nrule++; 2241 | rp->nextlhs = rp->lhs->rule; 2242 | rp->lhs->rule = rp; 2243 | rp->next = 0; 2244 | if( psp->firstrule==0 ){ 2245 | psp->firstrule = psp->lastrule = rp; 2246 | }else{ 2247 | psp->lastrule->next = rp; 2248 | psp->lastrule = rp; 2249 | } 2250 | psp->prevrule = rp; 2251 | } 2252 | psp->state = WAITING_FOR_DECL_OR_RULE; 2253 | }else if( isalpha(x[0]) ){ 2254 | if( psp->nrhs>=MAXRHS ){ 2255 | ErrorMsg(psp->filename,psp->tokenlineno, 2256 | "Too many symbols on RHS of rule beginning at \"%s\".", 2257 | x); 2258 | psp->errorcnt++; 2259 | psp->state = RESYNC_AFTER_RULE_ERROR; 2260 | }else{ 2261 | psp->rhs[psp->nrhs] = Symbol_new(x); 2262 | psp->alias[psp->nrhs] = 0; 2263 | psp->nrhs++; 2264 | } 2265 | }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){ 2266 | struct symbol *msp = psp->rhs[psp->nrhs-1]; 2267 | if( msp->type!=MULTITERMINAL ){ 2268 | struct symbol *origsp = msp; 2269 | msp = (struct symbol *) calloc(1,sizeof(*msp)); 2270 | memset(msp, 0, sizeof(*msp)); 2271 | msp->type = MULTITERMINAL; 2272 | msp->nsubsym = 1; 2273 | msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*)); 2274 | msp->subsym[0] = origsp; 2275 | msp->name = origsp->name; 2276 | psp->rhs[psp->nrhs-1] = msp; 2277 | } 2278 | msp->nsubsym++; 2279 | msp->subsym = (struct symbol **) realloc(msp->subsym, 2280 | sizeof(struct symbol*)*msp->nsubsym); 2281 | msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]); 2282 | if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){ 2283 | ErrorMsg(psp->filename,psp->tokenlineno, 2284 | "Cannot form a compound containing a non-terminal"); 2285 | psp->errorcnt++; 2286 | } 2287 | }else if( x[0]=='(' && psp->nrhs>0 ){ 2288 | psp->state = RHS_ALIAS_1; 2289 | }else{ 2290 | ErrorMsg(psp->filename,psp->tokenlineno, 2291 | "Illegal character on RHS of rule: \"%s\".",x); 2292 | psp->errorcnt++; 2293 | psp->state = RESYNC_AFTER_RULE_ERROR; 2294 | } 2295 | break; 2296 | case RHS_ALIAS_1: 2297 | if( isalpha(x[0]) ){ 2298 | psp->alias[psp->nrhs-1] = x; 2299 | psp->state = RHS_ALIAS_2; 2300 | }else{ 2301 | ErrorMsg(psp->filename,psp->tokenlineno, 2302 | "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n", 2303 | x,psp->rhs[psp->nrhs-1]->name); 2304 | psp->errorcnt++; 2305 | psp->state = RESYNC_AFTER_RULE_ERROR; 2306 | } 2307 | break; 2308 | case RHS_ALIAS_2: 2309 | if( x[0]==')' ){ 2310 | psp->state = IN_RHS; 2311 | }else{ 2312 | ErrorMsg(psp->filename,psp->tokenlineno, 2313 | "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias); 2314 | psp->errorcnt++; 2315 | psp->state = RESYNC_AFTER_RULE_ERROR; 2316 | } 2317 | break; 2318 | case WAITING_FOR_DECL_KEYWORD: 2319 | if( isalpha(x[0]) ){ 2320 | psp->declkeyword = x; 2321 | psp->declargslot = 0; 2322 | psp->decllinenoslot = 0; 2323 | psp->insertLineMacro = 1; 2324 | psp->state = WAITING_FOR_DECL_ARG; 2325 | if( strcmp(x,"name")==0 ){ 2326 | psp->declargslot = &(psp->gp->name); 2327 | psp->insertLineMacro = 0; 2328 | }else if( strcmp(x,"include")==0 ){ 2329 | psp->declargslot = &(psp->gp->include); 2330 | }else if( strcmp(x,"code")==0 ){ 2331 | psp->declargslot = &(psp->gp->extracode); 2332 | }else if( strcmp(x,"token_destructor")==0 ){ 2333 | psp->declargslot = &psp->gp->tokendest; 2334 | }else if( strcmp(x,"default_destructor")==0 ){ 2335 | psp->declargslot = &psp->gp->vardest; 2336 | }else if( strcmp(x,"token_prefix")==0 ){ 2337 | psp->declargslot = &psp->gp->tokenprefix; 2338 | psp->insertLineMacro = 0; 2339 | }else if( strcmp(x,"syntax_error")==0 ){ 2340 | psp->declargslot = &(psp->gp->error); 2341 | }else if( strcmp(x,"parse_accept")==0 ){ 2342 | psp->declargslot = &(psp->gp->accept); 2343 | }else if( strcmp(x,"parse_failure")==0 ){ 2344 | psp->declargslot = &(psp->gp->failure); 2345 | }else if( strcmp(x,"stack_overflow")==0 ){ 2346 | psp->declargslot = &(psp->gp->overflow); 2347 | }else if( strcmp(x,"extra_argument")==0 ){ 2348 | psp->declargslot = &(psp->gp->arg); 2349 | psp->insertLineMacro = 0; 2350 | }else if( strcmp(x,"token_type")==0 ){ 2351 | psp->declargslot = &(psp->gp->tokentype); 2352 | psp->insertLineMacro = 0; 2353 | }else if( strcmp(x,"default_type")==0 ){ 2354 | psp->declargslot = &(psp->gp->vartype); 2355 | psp->insertLineMacro = 0; 2356 | }else if( strcmp(x,"stack_size")==0 ){ 2357 | psp->declargslot = &(psp->gp->stacksize); 2358 | psp->insertLineMacro = 0; 2359 | }else if( strcmp(x,"start_symbol")==0 ){ 2360 | psp->declargslot = &(psp->gp->start); 2361 | psp->insertLineMacro = 0; 2362 | }else if( strcmp(x,"left")==0 ){ 2363 | psp->preccounter++; 2364 | psp->declassoc = LEFT; 2365 | psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; 2366 | }else if( strcmp(x,"right")==0 ){ 2367 | psp->preccounter++; 2368 | psp->declassoc = RIGHT; 2369 | psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; 2370 | }else if( strcmp(x,"nonassoc")==0 ){ 2371 | psp->preccounter++; 2372 | psp->declassoc = NONE; 2373 | psp->state = WAITING_FOR_PRECEDENCE_SYMBOL; 2374 | }else if( strcmp(x,"destructor")==0 ){ 2375 | psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL; 2376 | }else if( strcmp(x,"type")==0 ){ 2377 | psp->state = WAITING_FOR_DATATYPE_SYMBOL; 2378 | }else if( strcmp(x,"fallback")==0 ){ 2379 | psp->fallback = 0; 2380 | psp->state = WAITING_FOR_FALLBACK_ID; 2381 | }else if( strcmp(x,"wildcard")==0 ){ 2382 | psp->state = WAITING_FOR_WILDCARD_ID; 2383 | }else if( strcmp(x,"token_class")==0 ){ 2384 | psp->state = WAITING_FOR_CLASS_ID; 2385 | }else{ 2386 | ErrorMsg(psp->filename,psp->tokenlineno, 2387 | "Unknown declaration keyword: \"%%%s\".",x); 2388 | psp->errorcnt++; 2389 | psp->state = RESYNC_AFTER_DECL_ERROR; 2390 | } 2391 | }else{ 2392 | ErrorMsg(psp->filename,psp->tokenlineno, 2393 | "Illegal declaration keyword: \"%s\".",x); 2394 | psp->errorcnt++; 2395 | psp->state = RESYNC_AFTER_DECL_ERROR; 2396 | } 2397 | break; 2398 | case WAITING_FOR_DESTRUCTOR_SYMBOL: 2399 | if( !isalpha(x[0]) ){ 2400 | ErrorMsg(psp->filename,psp->tokenlineno, 2401 | "Symbol name missing after %%destructor keyword"); 2402 | psp->errorcnt++; 2403 | psp->state = RESYNC_AFTER_DECL_ERROR; 2404 | }else{ 2405 | struct symbol *sp = Symbol_new(x); 2406 | psp->declargslot = &sp->destructor; 2407 | psp->decllinenoslot = &sp->destLineno; 2408 | psp->insertLineMacro = 1; 2409 | psp->state = WAITING_FOR_DECL_ARG; 2410 | } 2411 | break; 2412 | case WAITING_FOR_DATATYPE_SYMBOL: 2413 | if( !isalpha(x[0]) ){ 2414 | ErrorMsg(psp->filename,psp->tokenlineno, 2415 | "Symbol name missing after %%type keyword"); 2416 | psp->errorcnt++; 2417 | psp->state = RESYNC_AFTER_DECL_ERROR; 2418 | }else{ 2419 | struct symbol *sp = Symbol_find(x); 2420 | if((sp) && (sp->datatype)){ 2421 | ErrorMsg(psp->filename,psp->tokenlineno, 2422 | "Symbol %%type \"%s\" already defined", x); 2423 | psp->errorcnt++; 2424 | psp->state = RESYNC_AFTER_DECL_ERROR; 2425 | }else{ 2426 | if (!sp){ 2427 | sp = Symbol_new(x); 2428 | } 2429 | psp->declargslot = &sp->datatype; 2430 | psp->insertLineMacro = 0; 2431 | psp->state = WAITING_FOR_DECL_ARG; 2432 | } 2433 | } 2434 | break; 2435 | case WAITING_FOR_PRECEDENCE_SYMBOL: 2436 | if( x[0]=='.' ){ 2437 | psp->state = WAITING_FOR_DECL_OR_RULE; 2438 | }else if( isupper(x[0]) ){ 2439 | struct symbol *sp; 2440 | sp = Symbol_new(x); 2441 | if( sp->prec>=0 ){ 2442 | ErrorMsg(psp->filename,psp->tokenlineno, 2443 | "Symbol \"%s\" has already be given a precedence.",x); 2444 | psp->errorcnt++; 2445 | }else{ 2446 | sp->prec = psp->preccounter; 2447 | sp->assoc = psp->declassoc; 2448 | } 2449 | }else{ 2450 | ErrorMsg(psp->filename,psp->tokenlineno, 2451 | "Can't assign a precedence to \"%s\".",x); 2452 | psp->errorcnt++; 2453 | } 2454 | break; 2455 | case WAITING_FOR_DECL_ARG: 2456 | if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){ 2457 | const char *zOld, *zNew; 2458 | char *zBuf, *z; 2459 | int nOld, n, nLine, nNew, nBack; 2460 | int addLineMacro; 2461 | char zLine[50]; 2462 | zNew = x; 2463 | if( zNew[0]=='"' || zNew[0]=='{' ) zNew++; 2464 | nNew = lemonStrlen(zNew); 2465 | if( *psp->declargslot ){ 2466 | zOld = *psp->declargslot; 2467 | }else{ 2468 | zOld = ""; 2469 | } 2470 | nOld = lemonStrlen(zOld); 2471 | n = nOld + nNew + 20; 2472 | addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro && 2473 | (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0); 2474 | if( addLineMacro ){ 2475 | for(z=psp->filename, nBack=0; *z; z++){ 2476 | if( *z=='\\' ) nBack++; 2477 | } 2478 | lemon_sprintf(zLine, "#line %d ", psp->tokenlineno); 2479 | nLine = lemonStrlen(zLine); 2480 | n += nLine + lemonStrlen(psp->filename) + nBack; 2481 | } 2482 | *psp->declargslot = (char *) realloc(*psp->declargslot, n); 2483 | zBuf = *psp->declargslot + nOld; 2484 | if( addLineMacro ){ 2485 | if( nOld && zBuf[-1]!='\n' ){ 2486 | *(zBuf++) = '\n'; 2487 | } 2488 | memcpy(zBuf, zLine, nLine); 2489 | zBuf += nLine; 2490 | *(zBuf++) = '"'; 2491 | for(z=psp->filename; *z; z++){ 2492 | if( *z=='\\' ){ 2493 | *(zBuf++) = '\\'; 2494 | } 2495 | *(zBuf++) = *z; 2496 | } 2497 | *(zBuf++) = '"'; 2498 | *(zBuf++) = '\n'; 2499 | } 2500 | if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){ 2501 | psp->decllinenoslot[0] = psp->tokenlineno; 2502 | } 2503 | memcpy(zBuf, zNew, nNew); 2504 | zBuf += nNew; 2505 | *zBuf = 0; 2506 | psp->state = WAITING_FOR_DECL_OR_RULE; 2507 | }else{ 2508 | ErrorMsg(psp->filename,psp->tokenlineno, 2509 | "Illegal argument to %%%s: %s",psp->declkeyword,x); 2510 | psp->errorcnt++; 2511 | psp->state = RESYNC_AFTER_DECL_ERROR; 2512 | } 2513 | break; 2514 | case WAITING_FOR_FALLBACK_ID: 2515 | if( x[0]=='.' ){ 2516 | psp->state = WAITING_FOR_DECL_OR_RULE; 2517 | }else if( !isupper(x[0]) ){ 2518 | ErrorMsg(psp->filename, psp->tokenlineno, 2519 | "%%fallback argument \"%s\" should be a token", x); 2520 | psp->errorcnt++; 2521 | }else{ 2522 | struct symbol *sp = Symbol_new(x); 2523 | if( psp->fallback==0 ){ 2524 | psp->fallback = sp; 2525 | }else if( sp->fallback ){ 2526 | ErrorMsg(psp->filename, psp->tokenlineno, 2527 | "More than one fallback assigned to token %s", x); 2528 | psp->errorcnt++; 2529 | }else{ 2530 | sp->fallback = psp->fallback; 2531 | psp->gp->has_fallback = 1; 2532 | } 2533 | } 2534 | break; 2535 | case WAITING_FOR_WILDCARD_ID: 2536 | if( x[0]=='.' ){ 2537 | psp->state = WAITING_FOR_DECL_OR_RULE; 2538 | }else if( !isupper(x[0]) ){ 2539 | ErrorMsg(psp->filename, psp->tokenlineno, 2540 | "%%wildcard argument \"%s\" should be a token", x); 2541 | psp->errorcnt++; 2542 | }else{ 2543 | struct symbol *sp = Symbol_new(x); 2544 | if( psp->gp->wildcard==0 ){ 2545 | psp->gp->wildcard = sp; 2546 | }else{ 2547 | ErrorMsg(psp->filename, psp->tokenlineno, 2548 | "Extra wildcard to token: %s", x); 2549 | psp->errorcnt++; 2550 | } 2551 | } 2552 | break; 2553 | case WAITING_FOR_CLASS_ID: 2554 | if( !islower(x[0]) ){ 2555 | ErrorMsg(psp->filename, psp->tokenlineno, 2556 | "%%token_class must be followed by an identifier: ", x); 2557 | psp->errorcnt++; 2558 | psp->state = RESYNC_AFTER_DECL_ERROR; 2559 | }else if( Symbol_find(x) ){ 2560 | ErrorMsg(psp->filename, psp->tokenlineno, 2561 | "Symbol \"%s\" already used", x); 2562 | psp->errorcnt++; 2563 | psp->state = RESYNC_AFTER_DECL_ERROR; 2564 | }else{ 2565 | psp->tkclass = Symbol_new(x); 2566 | psp->tkclass->type = MULTITERMINAL; 2567 | psp->state = WAITING_FOR_CLASS_TOKEN; 2568 | } 2569 | break; 2570 | case WAITING_FOR_CLASS_TOKEN: 2571 | if( x[0]=='.' ){ 2572 | psp->state = WAITING_FOR_DECL_OR_RULE; 2573 | }else if( isupper(x[0]) || ((x[0]=='|' || x[0]=='/') && isupper(x[1])) ){ 2574 | struct symbol *msp = psp->tkclass; 2575 | msp->nsubsym++; 2576 | msp->subsym = (struct symbol **) realloc(msp->subsym, 2577 | sizeof(struct symbol*)*msp->nsubsym); 2578 | if( !isupper(x[0]) ) x++; 2579 | msp->subsym[msp->nsubsym-1] = Symbol_new(x); 2580 | }else{ 2581 | ErrorMsg(psp->filename, psp->tokenlineno, 2582 | "%%token_class argument \"%s\" should be a token", x); 2583 | psp->errorcnt++; 2584 | psp->state = RESYNC_AFTER_DECL_ERROR; 2585 | } 2586 | break; 2587 | case RESYNC_AFTER_RULE_ERROR: 2588 | /* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; 2589 | ** break; */ 2590 | case RESYNC_AFTER_DECL_ERROR: 2591 | if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE; 2592 | if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD; 2593 | break; 2594 | } 2595 | } 2596 | 2597 | /* Run the preprocessor over the input file text. The global variables 2598 | ** azDefine[0] through azDefine[nDefine-1] contains the names of all defined 2599 | ** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and 2600 | ** comments them out. Text in between is also commented out as appropriate. 2601 | */ 2602 | static void preprocess_input(char *z){ 2603 | int i, j, k, n; 2604 | int exclude = 0; 2605 | int start = 0; 2606 | int lineno = 1; 2607 | int start_lineno = 1; 2608 | for(i=0; z[i]; i++){ 2609 | if( z[i]=='\n' ) lineno++; 2610 | if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue; 2611 | if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){ 2612 | if( exclude ){ 2613 | exclude--; 2614 | if( exclude==0 ){ 2615 | for(j=start; jfilename; 2667 | ps.errorcnt = 0; 2668 | ps.state = INITIALIZE; 2669 | 2670 | /* Begin by reading the input file */ 2671 | fp = fopen(ps.filename,"rb"); 2672 | if( fp==0 ){ 2673 | ErrorMsg(ps.filename,0,"Can't open this file for reading."); 2674 | gp->errorcnt++; 2675 | return; 2676 | } 2677 | fseek(fp,0,2); 2678 | filesize = ftell(fp); 2679 | rewind(fp); 2680 | filebuf = (char *)malloc( filesize+1 ); 2681 | if( filesize>100000000 || filebuf==0 ){ 2682 | ErrorMsg(ps.filename,0,"Input file too large."); 2683 | gp->errorcnt++; 2684 | fclose(fp); 2685 | return; 2686 | } 2687 | if( fread(filebuf,1,filesize,fp)!=filesize ){ 2688 | ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.", 2689 | filesize); 2690 | free(filebuf); 2691 | gp->errorcnt++; 2692 | fclose(fp); 2693 | return; 2694 | } 2695 | fclose(fp); 2696 | filebuf[filesize] = 0; 2697 | 2698 | /* Make an initial pass through the file to handle %ifdef and %ifndef */ 2699 | preprocess_input(filebuf); 2700 | 2701 | /* Now scan the text of the input file */ 2702 | lineno = 1; 2703 | for(cp=filebuf; (c= *cp)!=0; ){ 2704 | if( c=='\n' ) lineno++; /* Keep track of the line number */ 2705 | if( isspace(c) ){ cp++; continue; } /* Skip all white space */ 2706 | if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */ 2707 | cp+=2; 2708 | while( (c= *cp)!=0 && c!='\n' ) cp++; 2709 | continue; 2710 | } 2711 | if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */ 2712 | cp+=2; 2713 | while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){ 2714 | if( c=='\n' ) lineno++; 2715 | cp++; 2716 | } 2717 | if( c ) cp++; 2718 | continue; 2719 | } 2720 | ps.tokenstart = cp; /* Mark the beginning of the token */ 2721 | ps.tokenlineno = lineno; /* Linenumber on which token begins */ 2722 | if( c=='\"' ){ /* String literals */ 2723 | cp++; 2724 | while( (c= *cp)!=0 && c!='\"' ){ 2725 | if( c=='\n' ) lineno++; 2726 | cp++; 2727 | } 2728 | if( c==0 ){ 2729 | ErrorMsg(ps.filename,startline, 2730 | "String starting on this line is not terminated before the end of the file."); 2731 | ps.errorcnt++; 2732 | nextcp = cp; 2733 | }else{ 2734 | nextcp = cp+1; 2735 | } 2736 | }else if( c=='{' ){ /* A block of C code */ 2737 | int level; 2738 | cp++; 2739 | for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){ 2740 | if( c=='\n' ) lineno++; 2741 | else if( c=='{' ) level++; 2742 | else if( c=='}' ) level--; 2743 | else if( c=='/' && cp[1]=='*' ){ /* Skip comments */ 2744 | int prevc; 2745 | cp = &cp[2]; 2746 | prevc = 0; 2747 | while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){ 2748 | if( c=='\n' ) lineno++; 2749 | prevc = c; 2750 | cp++; 2751 | } 2752 | }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */ 2753 | cp = &cp[2]; 2754 | while( (c= *cp)!=0 && c!='\n' ) cp++; 2755 | if( c ) lineno++; 2756 | }else if( c=='\'' || c=='\"' ){ /* String a character literals */ 2757 | int startchar, prevc; 2758 | startchar = c; 2759 | prevc = 0; 2760 | for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){ 2761 | if( c=='\n' ) lineno++; 2762 | if( prevc=='\\' ) prevc = 0; 2763 | else prevc = c; 2764 | } 2765 | } 2766 | } 2767 | if( c==0 ){ 2768 | ErrorMsg(ps.filename,ps.tokenlineno, 2769 | "C code starting on this line is not terminated before the end of the file."); 2770 | ps.errorcnt++; 2771 | nextcp = cp; 2772 | }else{ 2773 | nextcp = cp+1; 2774 | } 2775 | }else if( isalnum(c) ){ /* Identifiers */ 2776 | while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++; 2777 | nextcp = cp; 2778 | }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */ 2779 | cp += 3; 2780 | nextcp = cp; 2781 | }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){ 2782 | cp += 2; 2783 | while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++; 2784 | nextcp = cp; 2785 | }else{ /* All other (one character) operators */ 2786 | cp++; 2787 | nextcp = cp; 2788 | } 2789 | c = *cp; 2790 | *cp = 0; /* Null terminate the token */ 2791 | parseonetoken(&ps); /* Parse the token */ 2792 | *cp = c; /* Restore the buffer */ 2793 | cp = nextcp; 2794 | } 2795 | free(filebuf); /* Release the buffer after parsing */ 2796 | gp->rule = ps.firstrule; 2797 | gp->errorcnt = ps.errorcnt; 2798 | } 2799 | /*************************** From the file "plink.c" *********************/ 2800 | /* 2801 | ** Routines processing configuration follow-set propagation links 2802 | ** in the LEMON parser generator. 2803 | */ 2804 | static struct plink *plink_freelist = 0; 2805 | 2806 | /* Allocate a new plink */ 2807 | struct plink *Plink_new(){ 2808 | struct plink *newlink; 2809 | 2810 | if( plink_freelist==0 ){ 2811 | int i; 2812 | int amt = 100; 2813 | plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) ); 2814 | if( plink_freelist==0 ){ 2815 | fprintf(stderr, 2816 | "Unable to allocate memory for a new follow-set propagation link.\n"); 2817 | exit(1); 2818 | } 2819 | for(i=0; inext; 2824 | return newlink; 2825 | } 2826 | 2827 | /* Add a plink to a plink list */ 2828 | void Plink_add(struct plink **plpp, struct config *cfp) 2829 | { 2830 | struct plink *newlink; 2831 | newlink = Plink_new(); 2832 | newlink->next = *plpp; 2833 | *plpp = newlink; 2834 | newlink->cfp = cfp; 2835 | } 2836 | 2837 | /* Transfer every plink on the list "from" to the list "to" */ 2838 | void Plink_copy(struct plink **to, struct plink *from) 2839 | { 2840 | struct plink *nextpl; 2841 | while( from ){ 2842 | nextpl = from->next; 2843 | from->next = *to; 2844 | *to = from; 2845 | from = nextpl; 2846 | } 2847 | } 2848 | 2849 | /* Delete every plink on the list */ 2850 | void Plink_delete(struct plink *plp) 2851 | { 2852 | struct plink *nextpl; 2853 | 2854 | while( plp ){ 2855 | nextpl = plp->next; 2856 | plp->next = plink_freelist; 2857 | plink_freelist = plp; 2858 | plp = nextpl; 2859 | } 2860 | } 2861 | /*********************** From the file "report.c" **************************/ 2862 | /* 2863 | ** Procedures for generating reports and tables in the LEMON parser generator. 2864 | */ 2865 | 2866 | /* Generate a filename with the given suffix. Space to hold the 2867 | ** name comes from malloc() and must be freed by the calling 2868 | ** function. 2869 | */ 2870 | PRIVATE char *file_makename(struct lemon *lemp, const char *suffix) 2871 | { 2872 | char *name; 2873 | char *cp; 2874 | int filename_prefix_length; 2875 | char *filename; 2876 | char *filename1; 2877 | char *filename2; 2878 | 2879 | filename_prefix_length = lemonStrlen(filename_prefix); 2880 | 2881 | name = (char*)malloc( filename_prefix_length + lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 ); 2882 | if( name==0 ){ 2883 | fprintf(stderr,"Can't allocate space for a filename.\n"); 2884 | exit(1); 2885 | } 2886 | 2887 | if( filename_prefix_length>0 ){ 2888 | filename1 = strrchr(lemp->filename, '\\'); 2889 | filename2 = strrchr(lemp->filename, '/'); 2890 | 2891 | filename = filename1 > filename2 ? filename1 : filename2; 2892 | 2893 | if( filename==0 ){ 2894 | lemon_strcpy(name,filename_prefix); 2895 | lemon_strcat(name,lemp->filename); 2896 | } 2897 | else{ 2898 | ++filename; 2899 | strncpy(name,lemp->filename,filename - lemp->filename); 2900 | strncpy(name + (filename - lemp->filename),filename_prefix,filename_prefix_length + 1); 2901 | lemon_strcat(name,filename); 2902 | } 2903 | } 2904 | else{ 2905 | strcpy(name,lemp->filename); 2906 | } 2907 | 2908 | cp = strrchr(name,'.'); 2909 | if( cp ) *cp = 0; 2910 | lemon_strcat(name,suffix); 2911 | return name; 2912 | } 2913 | 2914 | /* Open a file with a name based on the name of the input file, 2915 | ** but with a different (specified) suffix, and return a pointer 2916 | ** to the stream */ 2917 | PRIVATE FILE *file_open( 2918 | struct lemon *lemp, 2919 | const char *suffix, 2920 | const char *mode 2921 | ){ 2922 | FILE *fp; 2923 | 2924 | if( lemp->outname ) free(lemp->outname); 2925 | lemp->outname = file_makename(lemp, suffix); 2926 | fp = fopen(lemp->outname,mode); 2927 | if( fp==0 && *mode=='w' ){ 2928 | fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname); 2929 | lemp->errorcnt++; 2930 | return 0; 2931 | } 2932 | return fp; 2933 | } 2934 | 2935 | /* Duplicate the input file without comments and without actions 2936 | ** on rules */ 2937 | void Reprint(struct lemon *lemp) 2938 | { 2939 | struct rule *rp; 2940 | struct symbol *sp; 2941 | int i, j, maxlen, len, ncolumns, skip; 2942 | printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename); 2943 | maxlen = 10; 2944 | for(i=0; insymbol; i++){ 2945 | sp = lemp->symbols[i]; 2946 | len = lemonStrlen(sp->name); 2947 | if( len>maxlen ) maxlen = len; 2948 | } 2949 | ncolumns = 76/(maxlen+5); 2950 | if( ncolumns<1 ) ncolumns = 1; 2951 | skip = (lemp->nsymbol + ncolumns - 1)/ncolumns; 2952 | for(i=0; insymbol; j+=skip){ 2955 | sp = lemp->symbols[j]; 2956 | assert( sp->index==j ); 2957 | printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name); 2958 | } 2959 | printf("\n"); 2960 | } 2961 | for(rp=lemp->rule; rp; rp=rp->next){ 2962 | printf("%s",rp->lhs->name); 2963 | /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */ 2964 | printf(" ::="); 2965 | for(i=0; inrhs; i++){ 2966 | sp = rp->rhs[i]; 2967 | if( sp->type==MULTITERMINAL ){ 2968 | printf(" %s", sp->subsym[0]->name); 2969 | for(j=1; jnsubsym; j++){ 2970 | printf("|%s", sp->subsym[j]->name); 2971 | } 2972 | }else{ 2973 | printf(" %s", sp->name); 2974 | } 2975 | /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */ 2976 | } 2977 | printf("."); 2978 | if( rp->precsym ) printf(" [%s]",rp->precsym->name); 2979 | /* if( rp->code ) printf("\n %s",rp->code); */ 2980 | printf("\n"); 2981 | } 2982 | } 2983 | 2984 | void ConfigPrint(FILE *fp, struct config *cfp) 2985 | { 2986 | struct rule *rp; 2987 | struct symbol *sp; 2988 | int i, j; 2989 | rp = cfp->rp; 2990 | fprintf(fp,"%s ::=",rp->lhs->name); 2991 | for(i=0; i<=rp->nrhs; i++){ 2992 | if( i==cfp->dot ) fprintf(fp," *"); 2993 | if( i==rp->nrhs ) break; 2994 | sp = rp->rhs[i]; 2995 | if( sp->type==MULTITERMINAL ){ 2996 | fprintf(fp," %s", sp->subsym[0]->name); 2997 | for(j=1; jnsubsym; j++){ 2998 | fprintf(fp,"|%s",sp->subsym[j]->name); 2999 | } 3000 | }else{ 3001 | fprintf(fp," %s", sp->name); 3002 | } 3003 | } 3004 | } 3005 | 3006 | /* #define TEST */ 3007 | #if 0 3008 | /* Print a set */ 3009 | PRIVATE void SetPrint(out,set,lemp) 3010 | FILE *out; 3011 | char *set; 3012 | struct lemon *lemp; 3013 | { 3014 | int i; 3015 | char *spacer; 3016 | spacer = ""; 3017 | fprintf(out,"%12s[",""); 3018 | for(i=0; interminal; i++){ 3019 | if( SetFind(set,i) ){ 3020 | fprintf(out,"%s%s",spacer,lemp->symbols[i]->name); 3021 | spacer = " "; 3022 | } 3023 | } 3024 | fprintf(out,"]\n"); 3025 | } 3026 | 3027 | /* Print a plink chain */ 3028 | PRIVATE void PlinkPrint(out,plp,tag) 3029 | FILE *out; 3030 | struct plink *plp; 3031 | char *tag; 3032 | { 3033 | while( plp ){ 3034 | fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum); 3035 | ConfigPrint(out,plp->cfp); 3036 | fprintf(out,"\n"); 3037 | plp = plp->next; 3038 | } 3039 | } 3040 | #endif 3041 | 3042 | /* Print an action to the given file descriptor. Return FALSE if 3043 | ** nothing was actually printed. 3044 | */ 3045 | int PrintAction(struct action *ap, FILE *fp, int indent){ 3046 | int result = 1; 3047 | switch( ap->type ){ 3048 | case SHIFT: 3049 | fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum); 3050 | break; 3051 | case REDUCE: 3052 | fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index); 3053 | break; 3054 | case ACCEPT: 3055 | fprintf(fp,"%*s accept",indent,ap->sp->name); 3056 | break; 3057 | case ERROR: 3058 | fprintf(fp,"%*s error",indent,ap->sp->name); 3059 | break; 3060 | case SRCONFLICT: 3061 | case RRCONFLICT: 3062 | fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", 3063 | indent,ap->sp->name,ap->x.rp->index); 3064 | break; 3065 | case SSCONFLICT: 3066 | fprintf(fp,"%*s shift %-3d ** Parsing conflict **", 3067 | indent,ap->sp->name,ap->x.stp->statenum); 3068 | break; 3069 | case SH_RESOLVED: 3070 | if( showPrecedenceConflict ){ 3071 | fprintf(fp,"%*s shift %-3d -- dropped by precedence", 3072 | indent,ap->sp->name,ap->x.stp->statenum); 3073 | }else{ 3074 | result = 0; 3075 | } 3076 | break; 3077 | case RD_RESOLVED: 3078 | if( showPrecedenceConflict ){ 3079 | fprintf(fp,"%*s reduce %-3d -- dropped by precedence", 3080 | indent,ap->sp->name,ap->x.rp->index); 3081 | }else{ 3082 | result = 0; 3083 | } 3084 | break; 3085 | case NOT_USED: 3086 | result = 0; 3087 | break; 3088 | } 3089 | return result; 3090 | } 3091 | 3092 | /* Generate the "y.output" log file */ 3093 | void ReportOutput(struct lemon *lemp) 3094 | { 3095 | int i; 3096 | struct state *stp; 3097 | struct config *cfp; 3098 | struct action *ap; 3099 | FILE *fp; 3100 | 3101 | fp = file_open(lemp,".out","wb"); 3102 | if( fp==0 ) return; 3103 | for(i=0; instate; i++){ 3104 | stp = lemp->sorted[i]; 3105 | fprintf(fp,"State %d:\n",stp->statenum); 3106 | if( lemp->basisflag ) cfp=stp->bp; 3107 | else cfp=stp->cfp; 3108 | while( cfp ){ 3109 | char buf[20]; 3110 | if( cfp->dot==cfp->rp->nrhs ){ 3111 | lemon_sprintf(buf,"(%d)",cfp->rp->index); 3112 | fprintf(fp," %5s ",buf); 3113 | }else{ 3114 | fprintf(fp," "); 3115 | } 3116 | ConfigPrint(fp,cfp); 3117 | fprintf(fp,"\n"); 3118 | #if 0 3119 | SetPrint(fp,cfp->fws,lemp); 3120 | PlinkPrint(fp,cfp->fplp,"To "); 3121 | PlinkPrint(fp,cfp->bplp,"From"); 3122 | #endif 3123 | if( lemp->basisflag ) cfp=cfp->bp; 3124 | else cfp=cfp->next; 3125 | } 3126 | fprintf(fp,"\n"); 3127 | for(ap=stp->ap; ap; ap=ap->next){ 3128 | if( PrintAction(ap,fp,30) ) fprintf(fp,"\n"); 3129 | } 3130 | fprintf(fp,"\n"); 3131 | } 3132 | fprintf(fp, "----------------------------------------------------\n"); 3133 | fprintf(fp, "Symbols:\n"); 3134 | for(i=0; insymbol; i++){ 3135 | int j; 3136 | struct symbol *sp; 3137 | 3138 | sp = lemp->symbols[i]; 3139 | fprintf(fp, " %3d: %s", i, sp->name); 3140 | if( sp->type==NONTERMINAL ){ 3141 | fprintf(fp, ":"); 3142 | if( sp->lambda ){ 3143 | fprintf(fp, " "); 3144 | } 3145 | for(j=0; jnterminal; j++){ 3146 | if( sp->firstset && SetFind(sp->firstset, j) ){ 3147 | fprintf(fp, " %s", lemp->symbols[j]->name); 3148 | } 3149 | } 3150 | } 3151 | fprintf(fp, "\n"); 3152 | } 3153 | fclose(fp); 3154 | return; 3155 | } 3156 | 3157 | /* Search for the file "name" which is in the same directory as 3158 | ** the exacutable */ 3159 | PRIVATE char *pathsearch(char *argv0, char *name, int modemask) 3160 | { 3161 | const char *pathlist; 3162 | char *pathbufptr; 3163 | char *pathbuf; 3164 | char *path,*cp; 3165 | char c; 3166 | 3167 | #ifdef __WIN32__ 3168 | cp = strrchr(argv0,'\\'); 3169 | #else 3170 | cp = strrchr(argv0,'/'); 3171 | #endif 3172 | if( cp ){ 3173 | c = *cp; 3174 | *cp = 0; 3175 | path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 ); 3176 | if( path ) lemon_sprintf(path,"%s/%s",argv0,name); 3177 | *cp = c; 3178 | }else{ 3179 | pathlist = getenv("PATH"); 3180 | if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; 3181 | pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 ); 3182 | path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 ); 3183 | if( (pathbuf != 0) && (path!=0) ){ 3184 | pathbufptr = pathbuf; 3185 | lemon_strcpy(pathbuf, pathlist); 3186 | while( *pathbuf ){ 3187 | cp = strchr(pathbuf,':'); 3188 | if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)]; 3189 | c = *cp; 3190 | *cp = 0; 3191 | lemon_sprintf(path,"%s/%s",pathbuf,name); 3192 | *cp = c; 3193 | if( c==0 ) pathbuf[0] = 0; 3194 | else pathbuf = &cp[1]; 3195 | if( access(path,modemask)==0 ) break; 3196 | } 3197 | free(pathbufptr); 3198 | } 3199 | } 3200 | return path; 3201 | } 3202 | 3203 | /* Given an action, compute the integer value for that action 3204 | ** which is to be put in the action table of the generated machine. 3205 | ** Return negative if no action should be generated. 3206 | */ 3207 | PRIVATE int compute_action(struct lemon *lemp, struct action *ap) 3208 | { 3209 | int act; 3210 | switch( ap->type ){ 3211 | case SHIFT: act = ap->x.stp->statenum; break; 3212 | case REDUCE: act = ap->x.rp->index + lemp->nstate; break; 3213 | case ERROR: act = lemp->nstate + lemp->nrule; break; 3214 | case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break; 3215 | default: act = -1; break; 3216 | } 3217 | return act; 3218 | } 3219 | 3220 | #define LINESIZE 1000 3221 | /* The next cluster of routines are for reading the template file 3222 | ** and writing the results to the generated parser */ 3223 | /* The first function transfers data from "in" to "out" until 3224 | ** a line is seen which begins with "%%". The line number is 3225 | ** tracked. 3226 | ** 3227 | ** if name!=0, then any word that begin with "Parse" is changed to 3228 | ** begin with *name instead. 3229 | */ 3230 | PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno) 3231 | { 3232 | int i, iStart; 3233 | char line[LINESIZE]; 3234 | while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){ 3235 | (*lineno)++; 3236 | iStart = 0; 3237 | if( name ){ 3238 | for(i=0; line[i]; i++){ 3239 | if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0 3240 | && (i==0 || !isalpha(line[i-1])) 3241 | ){ 3242 | if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]); 3243 | fprintf(out,"%s",name); 3244 | i += 4; 3245 | iStart = i+1; 3246 | } 3247 | } 3248 | } 3249 | fprintf(out,"%s",&line[iStart]); 3250 | } 3251 | } 3252 | 3253 | /* The next function finds the template file and opens it, returning 3254 | ** a pointer to the opened file. */ 3255 | PRIVATE FILE *tplt_open(struct lemon *lemp, const char **extension) 3256 | { 3257 | static char templatename[] = "lempar.c"; 3258 | char buf[1000]; 3259 | FILE *in; 3260 | char *tpltname; 3261 | char *cp; 3262 | 3263 | /* first, see if user specified a template filename on the command line. */ 3264 | if (user_templatename != 0) { 3265 | if( access(user_templatename,004)==-1 ){ 3266 | fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", 3267 | user_templatename); 3268 | lemp->errorcnt++; 3269 | return 0; 3270 | } 3271 | in = fopen(user_templatename,"rb"); 3272 | if( in==0 ){ 3273 | fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename); 3274 | lemp->errorcnt++; 3275 | return 0; 3276 | } 3277 | *extension = strrchr(user_templatename,'.'); 3278 | return in; 3279 | } 3280 | 3281 | cp = strrchr(lemp->filename,'.'); 3282 | if( cp ){ 3283 | lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename); 3284 | }else{ 3285 | lemon_sprintf(buf,"%s.lt",lemp->filename); 3286 | } 3287 | if( access(buf,004)==0 ){ 3288 | tpltname = buf; 3289 | }else if( access(templatename,004)==0 ){ 3290 | tpltname = templatename; 3291 | }else{ 3292 | tpltname = pathsearch(lemp->argv0,templatename,0); 3293 | } 3294 | if( tpltname==0 ){ 3295 | fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", 3296 | templatename); 3297 | lemp->errorcnt++; 3298 | return 0; 3299 | } 3300 | in = fopen(tpltname,"rb"); 3301 | if( in==0 ){ 3302 | fprintf(stderr,"Can't open the template file \"%s\".\n",templatename); 3303 | lemp->errorcnt++; 3304 | return 0; 3305 | } 3306 | *extension = strrchr(tpltname,'.'); 3307 | return in; 3308 | } 3309 | 3310 | /* Print a #line directive line to the output file. */ 3311 | PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename) 3312 | { 3313 | fprintf(out,"#line %d \"",lineno); 3314 | while( *filename ){ 3315 | if( *filename == '\\' ) putc('\\',out); 3316 | putc(*filename,out); 3317 | filename++; 3318 | } 3319 | fprintf(out,"\"\n"); 3320 | } 3321 | 3322 | /* Print a string to the file and keep the linenumber up to date */ 3323 | PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno) 3324 | { 3325 | if( str==0 ) return; 3326 | while( *str ){ 3327 | putc(*str,out); 3328 | if( *str=='\n' ) (*lineno)++; 3329 | str++; 3330 | } 3331 | if( str[-1]!='\n' ){ 3332 | putc('\n',out); 3333 | (*lineno)++; 3334 | } 3335 | if (!lemp->nolinenosflag) { 3336 | (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); 3337 | } 3338 | return; 3339 | } 3340 | 3341 | /* 3342 | ** The following routine emits code for the destructor for the 3343 | ** symbol sp 3344 | */ 3345 | void emit_destructor_code( 3346 | FILE *out, 3347 | struct symbol *sp, 3348 | struct lemon *lemp, 3349 | int *lineno 3350 | ){ 3351 | char *cp = 0; 3352 | 3353 | if( sp->type==TERMINAL ){ 3354 | cp = lemp->tokendest; 3355 | if( cp==0 ) return; 3356 | fprintf(out,"{\n"); (*lineno)++; 3357 | }else if( sp->destructor ){ 3358 | cp = sp->destructor; 3359 | fprintf(out,"{\n"); (*lineno)++; 3360 | if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); } 3361 | }else if( lemp->vardest ){ 3362 | cp = lemp->vardest; 3363 | if( cp==0 ) return; 3364 | fprintf(out,"{\n"); (*lineno)++; 3365 | }else{ 3366 | assert( 0 ); /* Cannot happen */ 3367 | } 3368 | for(; *cp; cp++){ 3369 | if( *cp=='$' && cp[1]=='$' ){ 3370 | fprintf(out,"(yypminor->yy%d)",sp->dtnum); 3371 | cp++; 3372 | continue; 3373 | } 3374 | if( *cp=='\n' ) (*lineno)++; 3375 | fputc(*cp,out); 3376 | } 3377 | fprintf(out,"\n"); (*lineno)++; 3378 | if (!lemp->nolinenosflag) { 3379 | (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); 3380 | } 3381 | fprintf(out,"}\n"); (*lineno)++; 3382 | return; 3383 | } 3384 | 3385 | /* 3386 | ** Return TRUE (non-zero) if the given symbol has a destructor. 3387 | */ 3388 | int has_destructor(struct symbol *sp, struct lemon *lemp) 3389 | { 3390 | int ret; 3391 | if( sp->type==TERMINAL ){ 3392 | ret = lemp->tokendest!=0; 3393 | }else{ 3394 | ret = lemp->vardest!=0 || sp->destructor!=0; 3395 | } 3396 | return ret; 3397 | } 3398 | 3399 | /* 3400 | ** Append text to a dynamically allocated string. If zText is 0 then 3401 | ** reset the string to be empty again. Always return the complete text 3402 | ** of the string (which is overwritten with each call). 3403 | ** 3404 | ** n bytes of zText are stored. If n==0 then all of zText up to the first 3405 | ** \000 terminator is stored. zText can contain up to two instances of 3406 | ** %d. The values of p1 and p2 are written into the first and second 3407 | ** %d. 3408 | ** 3409 | ** If n==-1, then the previous character is overwritten. 3410 | */ 3411 | PRIVATE char *append_str(const char *zText, int n, int p1, int p2){ 3412 | static char empty[1] = { 0 }; 3413 | static char *z = 0; 3414 | static int alloced = 0; 3415 | static int used = 0; 3416 | int c; 3417 | char zInt[40]; 3418 | if( zText==0 ){ 3419 | used = 0; 3420 | return z; 3421 | } 3422 | if( n<=0 ){ 3423 | if( n<0 ){ 3424 | used += n; 3425 | assert( used>=0 ); 3426 | } 3427 | n = lemonStrlen(zText); 3428 | } 3429 | if( (int) (n+sizeof(zInt)*2+used) >= alloced ){ 3430 | alloced = n + sizeof(zInt)*2 + used + 200; 3431 | z = (char *) realloc(z, alloced); 3432 | } 3433 | if( z==0 ) return empty; 3434 | while( n-- > 0 ){ 3435 | c = *(zText++); 3436 | if( c=='%' && n>0 && zText[0]=='d' ){ 3437 | lemon_sprintf(zInt, "%d", p1); 3438 | p1 = p2; 3439 | lemon_strcpy(&z[used], zInt); 3440 | used += lemonStrlen(&z[used]); 3441 | zText++; 3442 | n--; 3443 | }else{ 3444 | z[used++] = c; 3445 | } 3446 | } 3447 | z[used] = 0; 3448 | return z; 3449 | } 3450 | 3451 | /* 3452 | ** zCode is a string that is the action associated with a rule. Expand 3453 | ** the symbols in this string so that the refer to elements of the parser 3454 | ** stack. 3455 | */ 3456 | PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){ 3457 | char *cp, *xp; 3458 | int i; 3459 | char lhsused = 0; /* True if the LHS element has been used */ 3460 | char used[MAXRHS]; /* True for each RHS element which is used */ 3461 | 3462 | for(i=0; inrhs; i++) used[i] = 0; 3463 | lhsused = 0; 3464 | 3465 | if( rp->code==0 ){ 3466 | static char newlinestr[2] = { '\n', '\0' }; 3467 | rp->code = newlinestr; 3468 | rp->line = rp->ruleline; 3469 | } 3470 | 3471 | append_str(0,0,0,0); 3472 | 3473 | /* This const cast is wrong but harmless, if we're careful. */ 3474 | for(cp=(char *)rp->code; *cp; cp++){ 3475 | if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){ 3476 | char saved; 3477 | for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++); 3478 | saved = *xp; 3479 | *xp = 0; 3480 | if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){ 3481 | append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0); 3482 | cp = xp; 3483 | lhsused = 1; 3484 | }else{ 3485 | for(i=0; inrhs; i++){ 3486 | if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){ 3487 | if( cp!=rp->code && cp[-1]=='@' ){ 3488 | /* If the argument is of the form @X then substituted 3489 | ** the token number of X, not the value of X */ 3490 | append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0); 3491 | }else{ 3492 | struct symbol *sp = rp->rhs[i]; 3493 | int dtnum; 3494 | if( sp->type==MULTITERMINAL ){ 3495 | dtnum = sp->subsym[0]->dtnum; 3496 | }else{ 3497 | dtnum = sp->dtnum; 3498 | } 3499 | append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum); 3500 | } 3501 | cp = xp; 3502 | used[i] = 1; 3503 | break; 3504 | } 3505 | } 3506 | } 3507 | *xp = saved; 3508 | } 3509 | append_str(cp, 1, 0, 0); 3510 | } /* End loop */ 3511 | 3512 | /* Check to make sure the LHS has been used */ 3513 | if( rp->lhsalias && !lhsused ){ 3514 | ErrorMsg(lemp->filename,rp->ruleline, 3515 | "Label \"%s\" for \"%s(%s)\" is never used.", 3516 | rp->lhsalias,rp->lhs->name,rp->lhsalias); 3517 | lemp->errorcnt++; 3518 | } 3519 | 3520 | /* Generate destructor code for RHS symbols which are not used in the 3521 | ** reduce code */ 3522 | for(i=0; inrhs; i++){ 3523 | if( rp->rhsalias[i] && !used[i] ){ 3524 | ErrorMsg(lemp->filename,rp->ruleline, 3525 | "Label %s for \"%s(%s)\" is never used.", 3526 | rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]); 3527 | lemp->errorcnt++; 3528 | }else if( rp->rhsalias[i]==0 ){ 3529 | if( has_destructor(rp->rhs[i],lemp) ){ 3530 | append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0, 3531 | rp->rhs[i]->index,i-rp->nrhs+1); 3532 | }else{ 3533 | /* No destructor defined for this term */ 3534 | } 3535 | } 3536 | } 3537 | if( rp->code ){ 3538 | cp = append_str(0,0,0,0); 3539 | rp->code = Strsafe(cp?cp:""); 3540 | } 3541 | } 3542 | 3543 | /* 3544 | ** Generate code which executes when the rule "rp" is reduced. Write 3545 | ** the code to "out". Make sure lineno stays up-to-date. 3546 | */ 3547 | PRIVATE void emit_code( 3548 | FILE *out, 3549 | struct rule *rp, 3550 | struct lemon *lemp, 3551 | int *lineno 3552 | ){ 3553 | const char *cp; 3554 | 3555 | /* Generate code to do the reduce action */ 3556 | if( rp->code ){ 3557 | if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); } 3558 | fprintf(out,"{%s",rp->code); 3559 | for(cp=rp->code; *cp; cp++){ 3560 | if( *cp=='\n' ) (*lineno)++; 3561 | } /* End loop */ 3562 | fprintf(out,"}\n"); (*lineno)++; 3563 | if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); } 3564 | } /* End if( rp->code ) */ 3565 | 3566 | return; 3567 | } 3568 | 3569 | /* 3570 | ** Print the definition of the union used for the parser's data stack. 3571 | ** This union contains fields for every possible data type for tokens 3572 | ** and nonterminals. In the process of computing and printing this 3573 | ** union, also set the ".dtnum" field of every terminal and nonterminal 3574 | ** symbol. 3575 | */ 3576 | void print_stack_union( 3577 | FILE *out, /* The output stream */ 3578 | struct lemon *lemp, /* The main info structure for this parser */ 3579 | int *plineno, /* Pointer to the line number */ 3580 | int mhflag /* True if generating makeheaders output */ 3581 | ){ 3582 | int lineno = *plineno; /* The line number of the output */ 3583 | char **types; /* A hash table of datatypes */ 3584 | int arraysize; /* Size of the "types" array */ 3585 | int maxdtlength; /* Maximum length of any ".datatype" field. */ 3586 | char *stddt; /* Standardized name for a datatype */ 3587 | int i,j; /* Loop counters */ 3588 | unsigned hash; /* For hashing the name of a type */ 3589 | const char *name; /* Name of the parser */ 3590 | 3591 | /* Allocate and initialize types[] and allocate stddt[] */ 3592 | arraysize = lemp->nsymbol * 2; 3593 | types = (char**)calloc( arraysize, sizeof(char*) ); 3594 | if( types==0 ){ 3595 | fprintf(stderr,"Out of memory.\n"); 3596 | exit(1); 3597 | } 3598 | for(i=0; ivartype ){ 3601 | maxdtlength = lemonStrlen(lemp->vartype); 3602 | } 3603 | for(i=0; insymbol; i++){ 3604 | int len; 3605 | struct symbol *sp = lemp->symbols[i]; 3606 | if( sp->datatype==0 ) continue; 3607 | len = lemonStrlen(sp->datatype); 3608 | if( len>maxdtlength ) maxdtlength = len; 3609 | } 3610 | stddt = (char*)malloc( maxdtlength*2 + 1 ); 3611 | if( stddt==0 ){ 3612 | fprintf(stderr,"Out of memory.\n"); 3613 | exit(1); 3614 | } 3615 | 3616 | /* Build a hash table of datatypes. The ".dtnum" field of each symbol 3617 | ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is 3618 | ** used for terminal symbols. If there is no %default_type defined then 3619 | ** 0 is also used as the .dtnum value for nonterminals which do not specify 3620 | ** a datatype using the %type directive. 3621 | */ 3622 | for(i=0; insymbol; i++){ 3623 | struct symbol *sp = lemp->symbols[i]; 3624 | char *cp; 3625 | if( sp==lemp->errsym ){ 3626 | sp->dtnum = arraysize+1; 3627 | continue; 3628 | } 3629 | if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){ 3630 | sp->dtnum = 0; 3631 | continue; 3632 | } 3633 | cp = sp->datatype; 3634 | if( cp==0 ) cp = lemp->vartype; 3635 | j = 0; 3636 | while( isspace(*cp) ) cp++; 3637 | while( *cp ) stddt[j++] = *cp++; 3638 | while( j>0 && isspace(stddt[j-1]) ) j--; 3639 | stddt[j] = 0; 3640 | if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){ 3641 | sp->dtnum = 0; 3642 | continue; 3643 | } 3644 | hash = 0; 3645 | for(j=0; stddt[j]; j++){ 3646 | hash = hash*53 + stddt[j]; 3647 | } 3648 | hash = (hash & 0x7fffffff)%arraysize; 3649 | while( types[hash] ){ 3650 | if( strcmp(types[hash],stddt)==0 ){ 3651 | sp->dtnum = hash + 1; 3652 | break; 3653 | } 3654 | hash++; 3655 | if( hash>=(unsigned)arraysize ) hash = 0; 3656 | } 3657 | if( types[hash]==0 ){ 3658 | sp->dtnum = hash + 1; 3659 | types[hash] = (char*)malloc( lemonStrlen(stddt)+1 ); 3660 | if( types[hash]==0 ){ 3661 | fprintf(stderr,"Out of memory.\n"); 3662 | exit(1); 3663 | } 3664 | lemon_strcpy(types[hash],stddt); 3665 | } 3666 | } 3667 | 3668 | /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */ 3669 | name = lemp->name ? lemp->name : "Parse"; 3670 | lineno = *plineno; 3671 | if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; } 3672 | fprintf(out,"#define %sTOKENTYPE %s\n",name, 3673 | lemp->tokentype?lemp->tokentype:"void*"); lineno++; 3674 | if( mhflag ){ fprintf(out,"#endif\n"); lineno++; } 3675 | fprintf(out,"typedef union {\n"); lineno++; 3676 | fprintf(out," int yyinit;\n"); lineno++; 3677 | fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; 3678 | for(i=0; ierrsym->useCnt ){ 3684 | fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++; 3685 | } 3686 | free(stddt); 3687 | free(types); 3688 | fprintf(out,"} YYMINORTYPE;\n"); lineno++; 3689 | *plineno = lineno; 3690 | } 3691 | 3692 | /* 3693 | ** Return the name of a C datatype able to represent values between 3694 | ** lwr and upr, inclusive. 3695 | */ 3696 | static const char *minimum_size_type(int lwr, int upr){ 3697 | if( lwr>=0 ){ 3698 | if( upr<=255 ){ 3699 | return "unsigned char"; 3700 | }else if( upr<65535 ){ 3701 | return "unsigned short int"; 3702 | }else{ 3703 | return "unsigned int"; 3704 | } 3705 | }else if( lwr>=-127 && upr<=127 ){ 3706 | return "signed char"; 3707 | }else if( lwr>=-32767 && upr<32767 ){ 3708 | return "short"; 3709 | }else{ 3710 | return "int"; 3711 | } 3712 | } 3713 | 3714 | /* 3715 | ** Each state contains a set of token transaction and a set of 3716 | ** nonterminal transactions. Each of these sets makes an instance 3717 | ** of the following structure. An array of these structures is used 3718 | ** to order the creation of entries in the yy_action[] table. 3719 | */ 3720 | struct axset { 3721 | struct state *stp; /* A pointer to a state */ 3722 | int isTkn; /* True to use tokens. False for non-terminals */ 3723 | int nAction; /* Number of actions */ 3724 | int iOrder; /* Original order of action sets */ 3725 | }; 3726 | 3727 | /* 3728 | ** Compare to axset structures for sorting purposes 3729 | */ 3730 | static int axset_compare(const void *a, const void *b){ 3731 | struct axset *p1 = (struct axset*)a; 3732 | struct axset *p2 = (struct axset*)b; 3733 | int c; 3734 | c = p2->nAction - p1->nAction; 3735 | if( c==0 ){ 3736 | c = p2->iOrder - p1->iOrder; 3737 | } 3738 | assert( c!=0 || p1==p2 ); 3739 | return c; 3740 | } 3741 | 3742 | /* 3743 | ** Write text on "out" that describes the rule "rp". 3744 | */ 3745 | static void writeRuleText(FILE *out, struct rule *rp){ 3746 | int j; 3747 | fprintf(out,"%s ::=", rp->lhs->name); 3748 | for(j=0; jnrhs; j++){ 3749 | struct symbol *sp = rp->rhs[j]; 3750 | if( sp->type!=MULTITERMINAL ){ 3751 | fprintf(out," %s", sp->name); 3752 | }else{ 3753 | int k; 3754 | fprintf(out," %s", sp->subsym[0]->name); 3755 | for(k=1; knsubsym; k++){ 3756 | fprintf(out,"|%s",sp->subsym[k]->name); 3757 | } 3758 | } 3759 | } 3760 | } 3761 | 3762 | 3763 | /* Generate C source code for the parser */ 3764 | void ReportTable( 3765 | struct lemon *lemp, 3766 | int mhflag /* Output in makeheaders format if true */ 3767 | ){ 3768 | FILE *out, *in; 3769 | char line[LINESIZE]; 3770 | int lineno; 3771 | struct state *stp; 3772 | struct action *ap; 3773 | struct rule *rp; 3774 | struct acttab *pActtab; 3775 | int i, j, n; 3776 | const char *name; 3777 | int mnTknOfst, mxTknOfst; 3778 | int mnNtOfst, mxNtOfst; 3779 | struct axset *ax; 3780 | const char *extension; 3781 | 3782 | in = tplt_open(lemp, &extension); 3783 | if( in==0 ) return; 3784 | if( extension==0 ) extension = ""; 3785 | out = file_open(lemp,extension,"wb"); 3786 | if( out==0 ){ 3787 | fclose(in); 3788 | return; 3789 | } 3790 | lineno = 1; 3791 | tplt_xfer(lemp->name,in,out,&lineno); 3792 | 3793 | /* Generate the include code, if any */ 3794 | tplt_print(out,lemp,lemp->include,&lineno); 3795 | if( mhflag ){ 3796 | char *name = file_makename(lemp, header_extension); 3797 | fprintf(out,"#include \"%s\"\n", name); lineno++; 3798 | free(name); 3799 | } 3800 | tplt_xfer(lemp->name,in,out,&lineno); 3801 | 3802 | /* Generate #defines for all tokens */ 3803 | if( mhflag ){ 3804 | const char *prefix; 3805 | fprintf(out,"#if INTERFACE\n"); lineno++; 3806 | if( lemp->tokenprefix ) prefix = lemp->tokenprefix; 3807 | else prefix = ""; 3808 | for(i=1; interminal; i++){ 3809 | fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i); 3810 | lineno++; 3811 | } 3812 | fprintf(out,"#endif\n"); lineno++; 3813 | } 3814 | tplt_xfer(lemp->name,in,out,&lineno); 3815 | 3816 | /* Generate the defines */ 3817 | fprintf(out,"#define YYCODETYPE %s\n", 3818 | minimum_size_type(0, lemp->nsymbol+1)); lineno++; 3819 | fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++; 3820 | fprintf(out,"#define YYACTIONTYPE %s\n", 3821 | minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++; 3822 | if( lemp->wildcard ){ 3823 | fprintf(out,"#define YYWILDCARD %d\n", 3824 | lemp->wildcard->index); lineno++; 3825 | } 3826 | print_stack_union(out,lemp,&lineno,mhflag); 3827 | fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++; 3828 | if( lemp->stacksize ){ 3829 | fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; 3830 | }else{ 3831 | fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; 3832 | } 3833 | fprintf(out, "#endif\n"); lineno++; 3834 | if( mhflag ){ 3835 | fprintf(out,"#if INTERFACE\n"); lineno++; 3836 | } 3837 | name = lemp->name ? lemp->name : "Parse"; 3838 | if( lemp->arg && lemp->arg[0] ){ 3839 | int i; 3840 | i = lemonStrlen(lemp->arg); 3841 | while( i>=1 && isspace(lemp->arg[i-1]) ) i--; 3842 | while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--; 3843 | fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++; 3844 | fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++; 3845 | fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n", 3846 | name,lemp->arg,&lemp->arg[i]); lineno++; 3847 | fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n", 3848 | name,&lemp->arg[i],&lemp->arg[i]); lineno++; 3849 | }else{ 3850 | fprintf(out,"#define %sARG_SDECL\n",name); lineno++; 3851 | fprintf(out,"#define %sARG_PDECL\n",name); lineno++; 3852 | fprintf(out,"#define %sARG_FETCH\n",name); lineno++; 3853 | fprintf(out,"#define %sARG_STORE\n",name); lineno++; 3854 | } 3855 | if( mhflag ){ 3856 | fprintf(out,"#endif\n"); lineno++; 3857 | } 3858 | fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++; 3859 | fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++; 3860 | if( lemp->errsym->useCnt ){ 3861 | fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++; 3862 | fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++; 3863 | } 3864 | if( lemp->has_fallback ){ 3865 | fprintf(out,"#define YYFALLBACK 1\n"); lineno++; 3866 | } 3867 | tplt_xfer(lemp->name,in,out,&lineno); 3868 | 3869 | /* Generate the action table and its associates: 3870 | ** 3871 | ** yy_action[] A single table containing all actions. 3872 | ** yy_lookahead[] A table containing the lookahead for each entry in 3873 | ** yy_action. Used to detect hash collisions. 3874 | ** yy_shift_ofst[] For each state, the offset into yy_action for 3875 | ** shifting terminals. 3876 | ** yy_reduce_ofst[] For each state, the offset into yy_action for 3877 | ** shifting non-terminals after a reduce. 3878 | ** yy_default[] Default action for each state. 3879 | */ 3880 | 3881 | /* Compute the actions on all states and count them up */ 3882 | ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0])); 3883 | if( ax==0 ){ 3884 | fprintf(stderr,"malloc failed\n"); 3885 | exit(1); 3886 | } 3887 | for(i=0; instate; i++){ 3888 | stp = lemp->sorted[i]; 3889 | ax[i*2].stp = stp; 3890 | ax[i*2].isTkn = 1; 3891 | ax[i*2].nAction = stp->nTknAct; 3892 | ax[i*2+1].stp = stp; 3893 | ax[i*2+1].isTkn = 0; 3894 | ax[i*2+1].nAction = stp->nNtAct; 3895 | } 3896 | mxTknOfst = mnTknOfst = 0; 3897 | mxNtOfst = mnNtOfst = 0; 3898 | 3899 | /* Compute the action table. In order to try to keep the size of the 3900 | ** action table to a minimum, the heuristic of placing the largest action 3901 | ** sets first is used. 3902 | */ 3903 | for(i=0; instate*2; i++) ax[i].iOrder = i; 3904 | qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare); 3905 | pActtab = acttab_alloc(); 3906 | for(i=0; instate*2 && ax[i].nAction>0; i++){ 3907 | stp = ax[i].stp; 3908 | if( ax[i].isTkn ){ 3909 | for(ap=stp->ap; ap; ap=ap->next){ 3910 | int action; 3911 | if( ap->sp->index>=lemp->nterminal ) continue; 3912 | action = compute_action(lemp, ap); 3913 | if( action<0 ) continue; 3914 | acttab_action(pActtab, ap->sp->index, action); 3915 | } 3916 | stp->iTknOfst = acttab_insert(pActtab); 3917 | if( stp->iTknOfstiTknOfst; 3918 | if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst; 3919 | }else{ 3920 | for(ap=stp->ap; ap; ap=ap->next){ 3921 | int action; 3922 | if( ap->sp->indexnterminal ) continue; 3923 | if( ap->sp->index==lemp->nsymbol ) continue; 3924 | action = compute_action(lemp, ap); 3925 | if( action<0 ) continue; 3926 | acttab_action(pActtab, ap->sp->index, action); 3927 | } 3928 | stp->iNtOfst = acttab_insert(pActtab); 3929 | if( stp->iNtOfstiNtOfst; 3930 | if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst; 3931 | } 3932 | } 3933 | free(ax); 3934 | 3935 | /* Output the yy_action table */ 3936 | n = acttab_size(pActtab); 3937 | fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++; 3938 | fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++; 3939 | for(i=j=0; instate + lemp->nrule + 2; 3942 | if( j==0 ) fprintf(out," /* %5d */ ", i); 3943 | fprintf(out, " %4d,", action); 3944 | if( j==9 || i==n-1 ){ 3945 | fprintf(out, "\n"); lineno++; 3946 | j = 0; 3947 | }else{ 3948 | j++; 3949 | } 3950 | } 3951 | fprintf(out, "};\n"); lineno++; 3952 | 3953 | /* Output the yy_lookahead table */ 3954 | fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++; 3955 | for(i=j=0; insymbol; 3958 | if( j==0 ) fprintf(out," /* %5d */ ", i); 3959 | fprintf(out, " %4d,", la); 3960 | if( j==9 || i==n-1 ){ 3961 | fprintf(out, "\n"); lineno++; 3962 | j = 0; 3963 | }else{ 3964 | j++; 3965 | } 3966 | } 3967 | fprintf(out, "};\n"); lineno++; 3968 | 3969 | /* Output the yy_shift_ofst[] table */ 3970 | fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++; 3971 | n = lemp->nstate; 3972 | while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--; 3973 | fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++; 3974 | fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++; 3975 | fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++; 3976 | fprintf(out, "static const %s yy_shift_ofst[] = {\n", 3977 | minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; 3978 | for(i=j=0; isorted[i]; 3981 | ofst = stp->iTknOfst; 3982 | if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1; 3983 | if( j==0 ) fprintf(out," /* %5d */ ", i); 3984 | fprintf(out, " %4d,", ofst); 3985 | if( j==9 || i==n-1 ){ 3986 | fprintf(out, "\n"); lineno++; 3987 | j = 0; 3988 | }else{ 3989 | j++; 3990 | } 3991 | } 3992 | fprintf(out, "};\n"); lineno++; 3993 | 3994 | /* Output the yy_reduce_ofst[] table */ 3995 | fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++; 3996 | n = lemp->nstate; 3997 | while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--; 3998 | fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++; 3999 | fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++; 4000 | fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++; 4001 | fprintf(out, "static const %s yy_reduce_ofst[] = {\n", 4002 | minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; 4003 | for(i=j=0; isorted[i]; 4006 | ofst = stp->iNtOfst; 4007 | if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1; 4008 | if( j==0 ) fprintf(out," /* %5d */ ", i); 4009 | fprintf(out, " %4d,", ofst); 4010 | if( j==9 || i==n-1 ){ 4011 | fprintf(out, "\n"); lineno++; 4012 | j = 0; 4013 | }else{ 4014 | j++; 4015 | } 4016 | } 4017 | fprintf(out, "};\n"); lineno++; 4018 | 4019 | /* Output the default action table */ 4020 | fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++; 4021 | n = lemp->nstate; 4022 | for(i=j=0; isorted[i]; 4024 | if( j==0 ) fprintf(out," /* %5d */ ", i); 4025 | fprintf(out, " %4d,", stp->iDflt); 4026 | if( j==9 || i==n-1 ){ 4027 | fprintf(out, "\n"); lineno++; 4028 | j = 0; 4029 | }else{ 4030 | j++; 4031 | } 4032 | } 4033 | fprintf(out, "};\n"); lineno++; 4034 | tplt_xfer(lemp->name,in,out,&lineno); 4035 | 4036 | /* Generate the table of fallback tokens. 4037 | */ 4038 | if( lemp->has_fallback ){ 4039 | int mx = lemp->nterminal - 1; 4040 | while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } 4041 | for(i=0; i<=mx; i++){ 4042 | struct symbol *p = lemp->symbols[i]; 4043 | if( p->fallback==0 ){ 4044 | fprintf(out, " 0, /* %10s => nothing */\n", p->name); 4045 | }else{ 4046 | fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index, 4047 | p->name, p->fallback->name); 4048 | } 4049 | lineno++; 4050 | } 4051 | } 4052 | tplt_xfer(lemp->name, in, out, &lineno); 4053 | 4054 | /* Generate a table containing the symbolic name of every symbol 4055 | */ 4056 | for(i=0; insymbol; i++){ 4057 | lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name); 4058 | fprintf(out," %-15s",line); 4059 | if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; } 4060 | } 4061 | if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; } 4062 | tplt_xfer(lemp->name,in,out,&lineno); 4063 | 4064 | /* Generate a table containing a text string that describes every 4065 | ** rule in the rule set of the grammar. This information is used 4066 | ** when tracing REDUCE actions. 4067 | */ 4068 | for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){ 4069 | assert( rp->index==i ); 4070 | fprintf(out," /* %3d */ \"", i); 4071 | writeRuleText(out, rp); 4072 | fprintf(out,"\",\n"); lineno++; 4073 | } 4074 | tplt_xfer(lemp->name,in,out,&lineno); 4075 | 4076 | /* Generate code which executes every time a symbol is popped from 4077 | ** the stack while processing errors or while destroying the parser. 4078 | ** (In other words, generate the %destructor actions) 4079 | */ 4080 | if( lemp->tokendest ){ 4081 | int once = 1; 4082 | for(i=0; insymbol; i++){ 4083 | struct symbol *sp = lemp->symbols[i]; 4084 | if( sp==0 || sp->type!=TERMINAL ) continue; 4085 | if( once ){ 4086 | fprintf(out, " /* TERMINAL Destructor */\n"); lineno++; 4087 | once = 0; 4088 | } 4089 | fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; 4090 | } 4091 | for(i=0; insymbol && lemp->symbols[i]->type!=TERMINAL; i++); 4092 | if( insymbol ){ 4093 | emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); 4094 | fprintf(out," break;\n"); lineno++; 4095 | } 4096 | } 4097 | if( lemp->vardest ){ 4098 | struct symbol *dflt_sp = 0; 4099 | int once = 1; 4100 | for(i=0; insymbol; i++){ 4101 | struct symbol *sp = lemp->symbols[i]; 4102 | if( sp==0 || sp->type==TERMINAL || 4103 | sp->index<=0 || sp->destructor!=0 ) continue; 4104 | if( once ){ 4105 | fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++; 4106 | once = 0; 4107 | } 4108 | fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; 4109 | dflt_sp = sp; 4110 | } 4111 | if( dflt_sp!=0 ){ 4112 | emit_destructor_code(out,dflt_sp,lemp,&lineno); 4113 | } 4114 | fprintf(out," break;\n"); lineno++; 4115 | } 4116 | for(i=0; insymbol; i++){ 4117 | struct symbol *sp = lemp->symbols[i]; 4118 | if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue; 4119 | fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; 4120 | 4121 | /* Combine duplicate destructors into a single case */ 4122 | for(j=i+1; jnsymbol; j++){ 4123 | struct symbol *sp2 = lemp->symbols[j]; 4124 | if( sp2 && sp2->type!=TERMINAL && sp2->destructor 4125 | && sp2->dtnum==sp->dtnum 4126 | && strcmp(sp->destructor,sp2->destructor)==0 ){ 4127 | fprintf(out," case %d: /* %s */\n", 4128 | sp2->index, sp2->name); lineno++; 4129 | sp2->destructor = 0; 4130 | } 4131 | } 4132 | 4133 | emit_destructor_code(out,lemp->symbols[i],lemp,&lineno); 4134 | fprintf(out," break;\n"); lineno++; 4135 | } 4136 | tplt_xfer(lemp->name,in,out,&lineno); 4137 | 4138 | /* Generate code which executes whenever the parser stack overflows */ 4139 | tplt_print(out,lemp,lemp->overflow,&lineno); 4140 | tplt_xfer(lemp->name,in,out,&lineno); 4141 | 4142 | /* Generate the table of rule information 4143 | ** 4144 | ** Note: This code depends on the fact that rules are number 4145 | ** sequentually beginning with 0. 4146 | */ 4147 | for(rp=lemp->rule; rp; rp=rp->next){ 4148 | fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++; 4149 | } 4150 | tplt_xfer(lemp->name,in,out,&lineno); 4151 | 4152 | /* Generate code which execution during each REDUCE action */ 4153 | for(rp=lemp->rule; rp; rp=rp->next){ 4154 | translate_code(lemp, rp); 4155 | } 4156 | /* First output rules other than the default: rule */ 4157 | for(rp=lemp->rule; rp; rp=rp->next){ 4158 | struct rule *rp2; /* Other rules with the same action */ 4159 | if( rp->code==0 ) continue; 4160 | if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */ 4161 | fprintf(out," case %d: /* ", rp->index); 4162 | writeRuleText(out, rp); 4163 | fprintf(out, " */\n"); lineno++; 4164 | for(rp2=rp->next; rp2; rp2=rp2->next){ 4165 | if( rp2->code==rp->code ){ 4166 | fprintf(out," case %d: /* ", rp2->index); 4167 | writeRuleText(out, rp2); 4168 | fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++; 4169 | rp2->code = 0; 4170 | } 4171 | } 4172 | emit_code(out,rp,lemp,&lineno); 4173 | fprintf(out," break;\n"); lineno++; 4174 | rp->code = 0; 4175 | } 4176 | /* Finally, output the default: rule. We choose as the default: all 4177 | ** empty actions. */ 4178 | fprintf(out," default:\n"); lineno++; 4179 | for(rp=lemp->rule; rp; rp=rp->next){ 4180 | if( rp->code==0 ) continue; 4181 | assert( rp->code[0]=='\n' && rp->code[1]==0 ); 4182 | fprintf(out," /* (%d) ", rp->index); 4183 | writeRuleText(out, rp); 4184 | fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++; 4185 | } 4186 | fprintf(out," break;\n"); lineno++; 4187 | tplt_xfer(lemp->name,in,out,&lineno); 4188 | 4189 | /* Generate code which executes if a parse fails */ 4190 | tplt_print(out,lemp,lemp->failure,&lineno); 4191 | tplt_xfer(lemp->name,in,out,&lineno); 4192 | 4193 | /* Generate code which executes when a syntax error occurs */ 4194 | tplt_print(out,lemp,lemp->error,&lineno); 4195 | tplt_xfer(lemp->name,in,out,&lineno); 4196 | 4197 | /* Generate code which executes when the parser accepts its input */ 4198 | tplt_print(out,lemp,lemp->accept,&lineno); 4199 | tplt_xfer(lemp->name,in,out,&lineno); 4200 | 4201 | /* Append any addition code the user desires */ 4202 | tplt_print(out,lemp,lemp->extracode,&lineno); 4203 | 4204 | fclose(in); 4205 | fclose(out); 4206 | return; 4207 | } 4208 | 4209 | /* Generate a header file for the parser */ 4210 | void ReportHeader(struct lemon *lemp) 4211 | { 4212 | FILE *out, *in; 4213 | const char *prefix; 4214 | char line[LINESIZE]; 4215 | char pattern[LINESIZE]; 4216 | int i; 4217 | 4218 | if( lemp->tokenprefix ) prefix = lemp->tokenprefix; 4219 | else prefix = ""; 4220 | in = file_open(lemp,header_extension,"rb"); 4221 | if( in ){ 4222 | int nextChar; 4223 | for(i=1; interminal && fgets(line,LINESIZE,in); i++){ 4224 | lemon_sprintf(pattern,"#define %s%-30s %3d\n", 4225 | prefix,lemp->symbols[i]->name,i); 4226 | if( strcmp(line,pattern) ) break; 4227 | } 4228 | nextChar = fgetc(in); 4229 | fclose(in); 4230 | if( i==lemp->nterminal && nextChar==EOF ){ 4231 | /* No change in the file. Don't rewrite it. */ 4232 | return; 4233 | } 4234 | } 4235 | out = file_open(lemp,header_extension,"wb"); 4236 | if( out ){ 4237 | for(i=1; interminal; i++){ 4238 | fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i); 4239 | } 4240 | fclose(out); 4241 | } 4242 | return; 4243 | } 4244 | 4245 | /* Reduce the size of the action tables, if possible, by making use 4246 | ** of defaults. 4247 | ** 4248 | ** In this version, we take the most frequent REDUCE action and make 4249 | ** it the default. Except, there is no default if the wildcard token 4250 | ** is a possible look-ahead. 4251 | */ 4252 | void CompressTables(struct lemon *lemp) 4253 | { 4254 | struct state *stp; 4255 | struct action *ap, *ap2; 4256 | struct rule *rp, *rp2, *rbest; 4257 | int nbest, n; 4258 | int i; 4259 | int usesWildcard; 4260 | 4261 | for(i=0; instate; i++){ 4262 | stp = lemp->sorted[i]; 4263 | nbest = 0; 4264 | rbest = 0; 4265 | usesWildcard = 0; 4266 | 4267 | for(ap=stp->ap; ap; ap=ap->next){ 4268 | if( ap->type==SHIFT && ap->sp==lemp->wildcard ){ 4269 | usesWildcard = 1; 4270 | } 4271 | if( ap->type!=REDUCE ) continue; 4272 | rp = ap->x.rp; 4273 | if( rp->lhsStart ) continue; 4274 | if( rp==rbest ) continue; 4275 | n = 1; 4276 | for(ap2=ap->next; ap2; ap2=ap2->next){ 4277 | if( ap2->type!=REDUCE ) continue; 4278 | rp2 = ap2->x.rp; 4279 | if( rp2==rbest ) continue; 4280 | if( rp2==rp ) n++; 4281 | } 4282 | if( n>nbest ){ 4283 | nbest = n; 4284 | rbest = rp; 4285 | } 4286 | } 4287 | 4288 | /* Do not make a default if the number of rules to default 4289 | ** is not at least 1 or if the wildcard token is a possible 4290 | ** lookahead. 4291 | */ 4292 | if( nbest<1 || usesWildcard ) continue; 4293 | 4294 | 4295 | /* Combine matching REDUCE actions into a single default */ 4296 | for(ap=stp->ap; ap; ap=ap->next){ 4297 | if( ap->type==REDUCE && ap->x.rp==rbest ) break; 4298 | } 4299 | assert( ap ); 4300 | ap->sp = Symbol_new("{default}"); 4301 | for(ap=ap->next; ap; ap=ap->next){ 4302 | if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED; 4303 | } 4304 | stp->ap = Action_sort(stp->ap); 4305 | } 4306 | } 4307 | 4308 | 4309 | /* 4310 | ** Compare two states for sorting purposes. The smaller state is the 4311 | ** one with the most non-terminal actions. If they have the same number 4312 | ** of non-terminal actions, then the smaller is the one with the most 4313 | ** token actions. 4314 | */ 4315 | static int stateResortCompare(const void *a, const void *b){ 4316 | const struct state *pA = *(const struct state**)a; 4317 | const struct state *pB = *(const struct state**)b; 4318 | int n; 4319 | 4320 | n = pB->nNtAct - pA->nNtAct; 4321 | if( n==0 ){ 4322 | n = pB->nTknAct - pA->nTknAct; 4323 | if( n==0 ){ 4324 | n = pB->statenum - pA->statenum; 4325 | } 4326 | } 4327 | assert( n!=0 ); 4328 | return n; 4329 | } 4330 | 4331 | 4332 | /* 4333 | ** Renumber and resort states so that states with fewer choices 4334 | ** occur at the end. Except, keep state 0 as the first state. 4335 | */ 4336 | void ResortStates(struct lemon *lemp) 4337 | { 4338 | int i; 4339 | struct state *stp; 4340 | struct action *ap; 4341 | 4342 | for(i=0; instate; i++){ 4343 | stp = lemp->sorted[i]; 4344 | stp->nTknAct = stp->nNtAct = 0; 4345 | stp->iDflt = lemp->nstate + lemp->nrule; 4346 | stp->iTknOfst = NO_OFFSET; 4347 | stp->iNtOfst = NO_OFFSET; 4348 | for(ap=stp->ap; ap; ap=ap->next){ 4349 | if( compute_action(lemp,ap)>=0 ){ 4350 | if( ap->sp->indexnterminal ){ 4351 | stp->nTknAct++; 4352 | }else if( ap->sp->indexnsymbol ){ 4353 | stp->nNtAct++; 4354 | }else{ 4355 | stp->iDflt = compute_action(lemp, ap); 4356 | } 4357 | } 4358 | } 4359 | } 4360 | qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]), 4361 | stateResortCompare); 4362 | for(i=0; instate; i++){ 4363 | lemp->sorted[i]->statenum = i; 4364 | } 4365 | } 4366 | 4367 | 4368 | /***************** From the file "set.c" ************************************/ 4369 | /* 4370 | ** Set manipulation routines for the LEMON parser generator. 4371 | */ 4372 | 4373 | static int size = 0; 4374 | 4375 | /* Set the set size */ 4376 | void SetSize(int n) 4377 | { 4378 | size = n+1; 4379 | } 4380 | 4381 | /* Allocate a new set */ 4382 | char *SetNew(){ 4383 | char *s; 4384 | s = (char*)calloc( size, 1); 4385 | if( s==0 ){ 4386 | extern void memory_error(); 4387 | memory_error(); 4388 | } 4389 | return s; 4390 | } 4391 | 4392 | /* Deallocate a set */ 4393 | void SetFree(char *s) 4394 | { 4395 | free(s); 4396 | } 4397 | 4398 | /* Add a new element to the set. Return TRUE if the element was added 4399 | ** and FALSE if it was already there. */ 4400 | int SetAdd(char *s, int e) 4401 | { 4402 | int rv; 4403 | assert( e>=0 && esize = 1024; 4493 | x1a->count = 0; 4494 | x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*)); 4495 | if( x1a->tbl==0 ){ 4496 | free(x1a); 4497 | x1a = 0; 4498 | }else{ 4499 | int i; 4500 | x1a->ht = (x1node**)&(x1a->tbl[1024]); 4501 | for(i=0; i<1024; i++) x1a->ht[i] = 0; 4502 | } 4503 | } 4504 | } 4505 | /* Insert a new record into the array. Return TRUE if successful. 4506 | ** Prior data with the same key is NOT overwritten */ 4507 | int Strsafe_insert(const char *data) 4508 | { 4509 | x1node *np; 4510 | unsigned h; 4511 | unsigned ph; 4512 | 4513 | if( x1a==0 ) return 0; 4514 | ph = strhash(data); 4515 | h = ph & (x1a->size-1); 4516 | np = x1a->ht[h]; 4517 | while( np ){ 4518 | if( strcmp(np->data,data)==0 ){ 4519 | /* An existing entry with the same key is found. */ 4520 | /* Fail because overwrite is not allows. */ 4521 | return 0; 4522 | } 4523 | np = np->next; 4524 | } 4525 | if( x1a->count>=x1a->size ){ 4526 | /* Need to make the hash table bigger */ 4527 | int i,size; 4528 | struct s_x1 array; 4529 | array.size = size = x1a->size*2; 4530 | array.count = x1a->count; 4531 | array.tbl = (x1node*)calloc(size, sizeof(x1node) + sizeof(x1node*)); 4532 | if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 4533 | array.ht = (x1node**)&(array.tbl[size]); 4534 | for(i=0; icount; i++){ 4536 | x1node *oldnp, *newnp; 4537 | oldnp = &(x1a->tbl[i]); 4538 | h = strhash(oldnp->data) & (size-1); 4539 | newnp = &(array.tbl[i]); 4540 | if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 4541 | newnp->next = array.ht[h]; 4542 | newnp->data = oldnp->data; 4543 | newnp->from = &(array.ht[h]); 4544 | array.ht[h] = newnp; 4545 | } 4546 | free(x1a->tbl); 4547 | *x1a = array; 4548 | } 4549 | /* Insert the new data */ 4550 | h = ph & (x1a->size-1); 4551 | np = &(x1a->tbl[x1a->count++]); 4552 | np->data = data; 4553 | if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next); 4554 | np->next = x1a->ht[h]; 4555 | x1a->ht[h] = np; 4556 | np->from = &(x1a->ht[h]); 4557 | return 1; 4558 | } 4559 | 4560 | /* Return a pointer to data assigned to the given key. Return NULL 4561 | ** if no such key. */ 4562 | const char *Strsafe_find(const char *key) 4563 | { 4564 | unsigned h; 4565 | x1node *np; 4566 | 4567 | if( x1a==0 ) return 0; 4568 | h = strhash(key) & (x1a->size-1); 4569 | np = x1a->ht[h]; 4570 | while( np ){ 4571 | if( strcmp(np->data,key)==0 ) break; 4572 | np = np->next; 4573 | } 4574 | return np ? np->data : 0; 4575 | } 4576 | 4577 | /* Return a pointer to the (terminal or nonterminal) symbol "x". 4578 | ** Create a new symbol if this is the first time "x" has been seen. 4579 | */ 4580 | struct symbol *Symbol_new(const char *x) 4581 | { 4582 | struct symbol *sp; 4583 | 4584 | sp = Symbol_find(x); 4585 | if( sp==0 ){ 4586 | sp = (struct symbol *)calloc(1, sizeof(struct symbol) ); 4587 | MemoryCheck(sp); 4588 | sp->name = Strsafe(x); 4589 | sp->type = isupper(*x) ? TERMINAL : NONTERMINAL; 4590 | sp->rule = 0; 4591 | sp->fallback = 0; 4592 | sp->prec = -1; 4593 | sp->assoc = UNK; 4594 | sp->firstset = 0; 4595 | sp->lambda = LEMON_FALSE; 4596 | sp->destructor = 0; 4597 | sp->destLineno = 0; 4598 | sp->datatype = 0; 4599 | sp->useCnt = 0; 4600 | Symbol_insert(sp,sp->name); 4601 | } 4602 | sp->useCnt++; 4603 | return sp; 4604 | } 4605 | 4606 | /* Compare two symbols for sorting purposes. Return negative, 4607 | ** zero, or positive if a is less then, equal to, or greater 4608 | ** than b. 4609 | ** 4610 | ** Symbols that begin with upper case letters (terminals or tokens) 4611 | ** must sort before symbols that begin with lower case letters 4612 | ** (non-terminals). And MULTITERMINAL symbols (created using the 4613 | ** %token_class directive) must sort at the very end. Other than 4614 | ** that, the order does not matter. 4615 | ** 4616 | ** We find experimentally that leaving the symbols in their original 4617 | ** order (the order they appeared in the grammar file) gives the 4618 | ** smallest parser tables in SQLite. 4619 | */ 4620 | int Symbolcmpp(const void *_a, const void *_b) 4621 | { 4622 | const struct symbol *a = *(const struct symbol **) _a; 4623 | const struct symbol *b = *(const struct symbol **) _b; 4624 | int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1; 4625 | int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1; 4626 | return i1==i2 ? a->index - b->index : i1 - i2; 4627 | } 4628 | 4629 | /* There is one instance of the following structure for each 4630 | ** associative array of type "x2". 4631 | */ 4632 | struct s_x2 { 4633 | int size; /* The number of available slots. */ 4634 | /* Must be a power of 2 greater than or */ 4635 | /* equal to 1 */ 4636 | int count; /* Number of currently slots filled */ 4637 | struct s_x2node *tbl; /* The data stored here */ 4638 | struct s_x2node **ht; /* Hash table for lookups */ 4639 | }; 4640 | 4641 | /* There is one instance of this structure for every data element 4642 | ** in an associative array of type "x2". 4643 | */ 4644 | typedef struct s_x2node { 4645 | struct symbol *data; /* The data */ 4646 | const char *key; /* The key */ 4647 | struct s_x2node *next; /* Next entry with the same hash */ 4648 | struct s_x2node **from; /* Previous link */ 4649 | } x2node; 4650 | 4651 | /* There is only one instance of the array, which is the following */ 4652 | static struct s_x2 *x2a; 4653 | 4654 | /* Allocate a new associative array */ 4655 | void Symbol_init(){ 4656 | if( x2a ) return; 4657 | x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); 4658 | if( x2a ){ 4659 | x2a->size = 128; 4660 | x2a->count = 0; 4661 | x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*)); 4662 | if( x2a->tbl==0 ){ 4663 | free(x2a); 4664 | x2a = 0; 4665 | }else{ 4666 | int i; 4667 | x2a->ht = (x2node**)&(x2a->tbl[128]); 4668 | for(i=0; i<128; i++) x2a->ht[i] = 0; 4669 | } 4670 | } 4671 | } 4672 | /* Insert a new record into the array. Return TRUE if successful. 4673 | ** Prior data with the same key is NOT overwritten */ 4674 | int Symbol_insert(struct symbol *data, const char *key) 4675 | { 4676 | x2node *np; 4677 | unsigned h; 4678 | unsigned ph; 4679 | 4680 | if( x2a==0 ) return 0; 4681 | ph = strhash(key); 4682 | h = ph & (x2a->size-1); 4683 | np = x2a->ht[h]; 4684 | while( np ){ 4685 | if( strcmp(np->key,key)==0 ){ 4686 | /* An existing entry with the same key is found. */ 4687 | /* Fail because overwrite is not allows. */ 4688 | return 0; 4689 | } 4690 | np = np->next; 4691 | } 4692 | if( x2a->count>=x2a->size ){ 4693 | /* Need to make the hash table bigger */ 4694 | int i,size; 4695 | struct s_x2 array; 4696 | array.size = size = x2a->size*2; 4697 | array.count = x2a->count; 4698 | array.tbl = (x2node*)calloc(size, sizeof(x2node) + sizeof(x2node*)); 4699 | if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 4700 | array.ht = (x2node**)&(array.tbl[size]); 4701 | for(i=0; icount; i++){ 4703 | x2node *oldnp, *newnp; 4704 | oldnp = &(x2a->tbl[i]); 4705 | h = strhash(oldnp->key) & (size-1); 4706 | newnp = &(array.tbl[i]); 4707 | if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 4708 | newnp->next = array.ht[h]; 4709 | newnp->key = oldnp->key; 4710 | newnp->data = oldnp->data; 4711 | newnp->from = &(array.ht[h]); 4712 | array.ht[h] = newnp; 4713 | } 4714 | free(x2a->tbl); 4715 | *x2a = array; 4716 | } 4717 | /* Insert the new data */ 4718 | h = ph & (x2a->size-1); 4719 | np = &(x2a->tbl[x2a->count++]); 4720 | np->key = key; 4721 | np->data = data; 4722 | if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next); 4723 | np->next = x2a->ht[h]; 4724 | x2a->ht[h] = np; 4725 | np->from = &(x2a->ht[h]); 4726 | return 1; 4727 | } 4728 | 4729 | /* Return a pointer to data assigned to the given key. Return NULL 4730 | ** if no such key. */ 4731 | struct symbol *Symbol_find(const char *key) 4732 | { 4733 | unsigned h; 4734 | x2node *np; 4735 | 4736 | if( x2a==0 ) return 0; 4737 | h = strhash(key) & (x2a->size-1); 4738 | np = x2a->ht[h]; 4739 | while( np ){ 4740 | if( strcmp(np->key,key)==0 ) break; 4741 | np = np->next; 4742 | } 4743 | return np ? np->data : 0; 4744 | } 4745 | 4746 | /* Return the n-th data. Return NULL if n is out of range. */ 4747 | struct symbol *Symbol_Nth(int n) 4748 | { 4749 | struct symbol *data; 4750 | if( x2a && n>0 && n<=x2a->count ){ 4751 | data = x2a->tbl[n-1].data; 4752 | }else{ 4753 | data = 0; 4754 | } 4755 | return data; 4756 | } 4757 | 4758 | /* Return the size of the array */ 4759 | int Symbol_count() 4760 | { 4761 | return x2a ? x2a->count : 0; 4762 | } 4763 | 4764 | /* Return an array of pointers to all data in the table. 4765 | ** The array is obtained from malloc. Return NULL if memory allocation 4766 | ** problems, or if the array is empty. */ 4767 | struct symbol **Symbol_arrayof() 4768 | { 4769 | struct symbol **array; 4770 | int i,size; 4771 | if( x2a==0 ) return 0; 4772 | size = x2a->count; 4773 | array = (struct symbol **)calloc(size, sizeof(struct symbol *)); 4774 | if( array ){ 4775 | for(i=0; itbl[i].data; 4776 | } 4777 | return array; 4778 | } 4779 | 4780 | /* Compare two configurations */ 4781 | int Configcmp(const char *_a,const char *_b) 4782 | { 4783 | const struct config *a = (struct config *) _a; 4784 | const struct config *b = (struct config *) _b; 4785 | int x; 4786 | x = a->rp->index - b->rp->index; 4787 | if( x==0 ) x = a->dot - b->dot; 4788 | return x; 4789 | } 4790 | 4791 | /* Compare two states */ 4792 | PRIVATE int statecmp(struct config *a, struct config *b) 4793 | { 4794 | int rc; 4795 | for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){ 4796 | rc = a->rp->index - b->rp->index; 4797 | if( rc==0 ) rc = a->dot - b->dot; 4798 | } 4799 | if( rc==0 ){ 4800 | if( a ) rc = 1; 4801 | if( b ) rc = -1; 4802 | } 4803 | return rc; 4804 | } 4805 | 4806 | /* Hash a state */ 4807 | PRIVATE unsigned statehash(struct config *a) 4808 | { 4809 | unsigned h=0; 4810 | while( a ){ 4811 | h = h*571 + a->rp->index*37 + a->dot; 4812 | a = a->bp; 4813 | } 4814 | return h; 4815 | } 4816 | 4817 | /* Allocate a new state structure */ 4818 | struct state *State_new() 4819 | { 4820 | struct state *newstate; 4821 | newstate = (struct state *)calloc(1, sizeof(struct state) ); 4822 | MemoryCheck(newstate); 4823 | return newstate; 4824 | } 4825 | 4826 | /* There is one instance of the following structure for each 4827 | ** associative array of type "x3". 4828 | */ 4829 | struct s_x3 { 4830 | int size; /* The number of available slots. */ 4831 | /* Must be a power of 2 greater than or */ 4832 | /* equal to 1 */ 4833 | int count; /* Number of currently slots filled */ 4834 | struct s_x3node *tbl; /* The data stored here */ 4835 | struct s_x3node **ht; /* Hash table for lookups */ 4836 | }; 4837 | 4838 | /* There is one instance of this structure for every data element 4839 | ** in an associative array of type "x3". 4840 | */ 4841 | typedef struct s_x3node { 4842 | struct state *data; /* The data */ 4843 | struct config *key; /* The key */ 4844 | struct s_x3node *next; /* Next entry with the same hash */ 4845 | struct s_x3node **from; /* Previous link */ 4846 | } x3node; 4847 | 4848 | /* There is only one instance of the array, which is the following */ 4849 | static struct s_x3 *x3a; 4850 | 4851 | /* Allocate a new associative array */ 4852 | void State_init(){ 4853 | if( x3a ) return; 4854 | x3a = (struct s_x3*)malloc( sizeof(struct s_x3) ); 4855 | if( x3a ){ 4856 | x3a->size = 128; 4857 | x3a->count = 0; 4858 | x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*)); 4859 | if( x3a->tbl==0 ){ 4860 | free(x3a); 4861 | x3a = 0; 4862 | }else{ 4863 | int i; 4864 | x3a->ht = (x3node**)&(x3a->tbl[128]); 4865 | for(i=0; i<128; i++) x3a->ht[i] = 0; 4866 | } 4867 | } 4868 | } 4869 | /* Insert a new record into the array. Return TRUE if successful. 4870 | ** Prior data with the same key is NOT overwritten */ 4871 | int State_insert(struct state *data, struct config *key) 4872 | { 4873 | x3node *np; 4874 | unsigned h; 4875 | unsigned ph; 4876 | 4877 | if( x3a==0 ) return 0; 4878 | ph = statehash(key); 4879 | h = ph & (x3a->size-1); 4880 | np = x3a->ht[h]; 4881 | while( np ){ 4882 | if( statecmp(np->key,key)==0 ){ 4883 | /* An existing entry with the same key is found. */ 4884 | /* Fail because overwrite is not allows. */ 4885 | return 0; 4886 | } 4887 | np = np->next; 4888 | } 4889 | if( x3a->count>=x3a->size ){ 4890 | /* Need to make the hash table bigger */ 4891 | int i,size; 4892 | struct s_x3 array; 4893 | array.size = size = x3a->size*2; 4894 | array.count = x3a->count; 4895 | array.tbl = (x3node*)calloc(size, sizeof(x3node) + sizeof(x3node*)); 4896 | if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 4897 | array.ht = (x3node**)&(array.tbl[size]); 4898 | for(i=0; icount; i++){ 4900 | x3node *oldnp, *newnp; 4901 | oldnp = &(x3a->tbl[i]); 4902 | h = statehash(oldnp->key) & (size-1); 4903 | newnp = &(array.tbl[i]); 4904 | if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 4905 | newnp->next = array.ht[h]; 4906 | newnp->key = oldnp->key; 4907 | newnp->data = oldnp->data; 4908 | newnp->from = &(array.ht[h]); 4909 | array.ht[h] = newnp; 4910 | } 4911 | free(x3a->tbl); 4912 | *x3a = array; 4913 | } 4914 | /* Insert the new data */ 4915 | h = ph & (x3a->size-1); 4916 | np = &(x3a->tbl[x3a->count++]); 4917 | np->key = key; 4918 | np->data = data; 4919 | if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next); 4920 | np->next = x3a->ht[h]; 4921 | x3a->ht[h] = np; 4922 | np->from = &(x3a->ht[h]); 4923 | return 1; 4924 | } 4925 | 4926 | /* Return a pointer to data assigned to the given key. Return NULL 4927 | ** if no such key. */ 4928 | struct state *State_find(struct config *key) 4929 | { 4930 | unsigned h; 4931 | x3node *np; 4932 | 4933 | if( x3a==0 ) return 0; 4934 | h = statehash(key) & (x3a->size-1); 4935 | np = x3a->ht[h]; 4936 | while( np ){ 4937 | if( statecmp(np->key,key)==0 ) break; 4938 | np = np->next; 4939 | } 4940 | return np ? np->data : 0; 4941 | } 4942 | 4943 | /* Return an array of pointers to all data in the table. 4944 | ** The array is obtained from malloc. Return NULL if memory allocation 4945 | ** problems, or if the array is empty. */ 4946 | struct state **State_arrayof() 4947 | { 4948 | struct state **array; 4949 | int i,size; 4950 | if( x3a==0 ) return 0; 4951 | size = x3a->count; 4952 | array = (struct state **)calloc(size, sizeof(struct state *)); 4953 | if( array ){ 4954 | for(i=0; itbl[i].data; 4955 | } 4956 | return array; 4957 | } 4958 | 4959 | /* Hash a configuration */ 4960 | PRIVATE unsigned confighash(struct config *a) 4961 | { 4962 | unsigned h=0; 4963 | h = h*571 + a->rp->index*37 + a->dot; 4964 | return h; 4965 | } 4966 | 4967 | /* There is one instance of the following structure for each 4968 | ** associative array of type "x4". 4969 | */ 4970 | struct s_x4 { 4971 | int size; /* The number of available slots. */ 4972 | /* Must be a power of 2 greater than or */ 4973 | /* equal to 1 */ 4974 | int count; /* Number of currently slots filled */ 4975 | struct s_x4node *tbl; /* The data stored here */ 4976 | struct s_x4node **ht; /* Hash table for lookups */ 4977 | }; 4978 | 4979 | /* There is one instance of this structure for every data element 4980 | ** in an associative array of type "x4". 4981 | */ 4982 | typedef struct s_x4node { 4983 | struct config *data; /* The data */ 4984 | struct s_x4node *next; /* Next entry with the same hash */ 4985 | struct s_x4node **from; /* Previous link */ 4986 | } x4node; 4987 | 4988 | /* There is only one instance of the array, which is the following */ 4989 | static struct s_x4 *x4a; 4990 | 4991 | /* Allocate a new associative array */ 4992 | void Configtable_init(){ 4993 | if( x4a ) return; 4994 | x4a = (struct s_x4*)malloc( sizeof(struct s_x4) ); 4995 | if( x4a ){ 4996 | x4a->size = 64; 4997 | x4a->count = 0; 4998 | x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*)); 4999 | if( x4a->tbl==0 ){ 5000 | free(x4a); 5001 | x4a = 0; 5002 | }else{ 5003 | int i; 5004 | x4a->ht = (x4node**)&(x4a->tbl[64]); 5005 | for(i=0; i<64; i++) x4a->ht[i] = 0; 5006 | } 5007 | } 5008 | } 5009 | /* Insert a new record into the array. Return TRUE if successful. 5010 | ** Prior data with the same key is NOT overwritten */ 5011 | int Configtable_insert(struct config *data) 5012 | { 5013 | x4node *np; 5014 | unsigned h; 5015 | unsigned ph; 5016 | 5017 | if( x4a==0 ) return 0; 5018 | ph = confighash(data); 5019 | h = ph & (x4a->size-1); 5020 | np = x4a->ht[h]; 5021 | while( np ){ 5022 | if( Configcmp((const char *) np->data,(const char *) data)==0 ){ 5023 | /* An existing entry with the same key is found. */ 5024 | /* Fail because overwrite is not allows. */ 5025 | return 0; 5026 | } 5027 | np = np->next; 5028 | } 5029 | if( x4a->count>=x4a->size ){ 5030 | /* Need to make the hash table bigger */ 5031 | int i,size; 5032 | struct s_x4 array; 5033 | array.size = size = x4a->size*2; 5034 | array.count = x4a->count; 5035 | array.tbl = (x4node*)calloc(size, sizeof(x4node) + sizeof(x4node*)); 5036 | if( array.tbl==0 ) return 0; /* Fail due to malloc failure */ 5037 | array.ht = (x4node**)&(array.tbl[size]); 5038 | for(i=0; icount; i++){ 5040 | x4node *oldnp, *newnp; 5041 | oldnp = &(x4a->tbl[i]); 5042 | h = confighash(oldnp->data) & (size-1); 5043 | newnp = &(array.tbl[i]); 5044 | if( array.ht[h] ) array.ht[h]->from = &(newnp->next); 5045 | newnp->next = array.ht[h]; 5046 | newnp->data = oldnp->data; 5047 | newnp->from = &(array.ht[h]); 5048 | array.ht[h] = newnp; 5049 | } 5050 | free(x4a->tbl); 5051 | *x4a = array; 5052 | } 5053 | /* Insert the new data */ 5054 | h = ph & (x4a->size-1); 5055 | np = &(x4a->tbl[x4a->count++]); 5056 | np->data = data; 5057 | if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next); 5058 | np->next = x4a->ht[h]; 5059 | x4a->ht[h] = np; 5060 | np->from = &(x4a->ht[h]); 5061 | return 1; 5062 | } 5063 | 5064 | /* Return a pointer to data assigned to the given key. Return NULL 5065 | ** if no such key. */ 5066 | struct config *Configtable_find(struct config *key) 5067 | { 5068 | int h; 5069 | x4node *np; 5070 | 5071 | if( x4a==0 ) return 0; 5072 | h = confighash(key) & (x4a->size-1); 5073 | np = x4a->ht[h]; 5074 | while( np ){ 5075 | if( Configcmp((const char *) np->data,(const char *) key)==0 ) break; 5076 | np = np->next; 5077 | } 5078 | return np ? np->data : 0; 5079 | } 5080 | 5081 | /* Remove all data from the table. Pass each data to the function "f" 5082 | ** as it is removed. ("f" may be null to avoid this step.) */ 5083 | void Configtable_clear(int(*f)(struct config *)) 5084 | { 5085 | int i; 5086 | if( x4a==0 || x4a->count==0 ) return; 5087 | if( f ) for(i=0; icount; i++) (*f)(x4a->tbl[i].data); 5088 | for(i=0; isize; i++) x4a->ht[i] = 0; 5089 | x4a->count = 0; 5090 | return; 5091 | } 5092 | -------------------------------------------------------------------------------- /lempar.c: -------------------------------------------------------------------------------- 1 | /* Driver template for the LEMON parser generator. 2 | ** The author disclaims copyright to this source code. 3 | */ 4 | /* First off, code is included that follows the "include" declaration 5 | ** in the input grammar file. */ 6 | #include 7 | #include 8 | %% 9 | /* Next is all token values, in a form suitable for use by makeheaders. 10 | ** This section will be null unless lemon is run with the -m switch. 11 | */ 12 | /* 13 | ** These constants (all generated automatically by the parser generator) 14 | ** specify the various kinds of tokens (terminals) that the parser 15 | ** understands. 16 | ** 17 | ** Each symbol here is a terminal symbol in the grammar. 18 | */ 19 | %% 20 | /* Make sure the INTERFACE macro is defined. 21 | */ 22 | #ifndef INTERFACE 23 | # define INTERFACE 1 24 | #endif 25 | /* The next thing included is series of defines which control 26 | ** various aspects of the generated parser. 27 | ** YYCODETYPE is the data type used for storing terminal 28 | ** and nonterminal numbers. "unsigned char" is 29 | ** used if there are fewer than 250 terminals 30 | ** and nonterminals. "int" is used otherwise. 31 | ** YYNOCODE is a number of type YYCODETYPE which corresponds 32 | ** to no legal terminal or nonterminal number. This 33 | ** number is used to fill in empty slots of the hash 34 | ** table. 35 | ** YYFALLBACK If defined, this indicates that one or more tokens 36 | ** have fall-back values which should be used if the 37 | ** original value of the token will not parse. 38 | ** YYACTIONTYPE is the data type used for storing terminal 39 | ** and nonterminal numbers. "unsigned char" is 40 | ** used if there are fewer than 250 rules and 41 | ** states combined. "int" is used otherwise. 42 | ** ParseTOKENTYPE is the data type used for minor tokens given 43 | ** directly to the parser from the tokenizer. 44 | ** YYMINORTYPE is the data type used for all minor tokens. 45 | ** This is typically a union of many types, one of 46 | ** which is ParseTOKENTYPE. The entry in the union 47 | ** for base tokens is called "yy0". 48 | ** YYSTACKDEPTH is the maximum depth of the parser's stack. If 49 | ** zero the stack is dynamically sized using realloc() 50 | ** ParseARG_SDECL A static variable declaration for the %extra_argument 51 | ** ParseARG_PDECL A parameter declaration for the %extra_argument 52 | ** ParseARG_STORE Code to store %extra_argument into yypParser 53 | ** ParseARG_FETCH Code to extract %extra_argument from yypParser 54 | ** YYNSTATE the combined number of states. 55 | ** YYNRULE the number of rules in the grammar 56 | ** YYERRORSYMBOL is the code number of the error symbol. If not 57 | ** defined, then do no error processing. 58 | */ 59 | %% 60 | #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) 61 | #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) 62 | #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) 63 | 64 | /* The yyzerominor constant is used to initialize instances of 65 | ** YYMINORTYPE objects to zero. */ 66 | static const YYMINORTYPE yyzerominor = { 0 }; 67 | 68 | /* Define the yytestcase() macro to be a no-op if is not already defined 69 | ** otherwise. 70 | ** 71 | ** Applications can choose to define yytestcase() in the %include section 72 | ** to a macro that can assist in verifying code coverage. For production 73 | ** code the yytestcase() macro should be turned off. But it is useful 74 | ** for testing. 75 | */ 76 | #ifndef yytestcase 77 | # define yytestcase(X) 78 | #endif 79 | 80 | 81 | /* Next are the tables used to determine what action to take based on the 82 | ** current state and lookahead token. These tables are used to implement 83 | ** functions that take a state number and lookahead value and return an 84 | ** action integer. 85 | ** 86 | ** Suppose the action integer is N. Then the action is determined as 87 | ** follows 88 | ** 89 | ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead 90 | ** token onto the stack and goto state N. 91 | ** 92 | ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. 93 | ** 94 | ** N == YYNSTATE+YYNRULE A syntax error has occurred. 95 | ** 96 | ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. 97 | ** 98 | ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused 99 | ** slots in the yy_action[] table. 100 | ** 101 | ** The action table is constructed as a single large table named yy_action[]. 102 | ** Given state S and lookahead X, the action is computed as 103 | ** 104 | ** yy_action[ yy_shift_ofst[S] + X ] 105 | ** 106 | ** If the index value yy_shift_ofst[S]+X is out of range or if the value 107 | ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] 108 | ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table 109 | ** and that yy_default[S] should be used instead. 110 | ** 111 | ** The formula above is for computing the action when the lookahead is 112 | ** a terminal symbol. If the lookahead is a non-terminal (as occurs after 113 | ** a reduce action) then the yy_reduce_ofst[] array is used in place of 114 | ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of 115 | ** YY_SHIFT_USE_DFLT. 116 | ** 117 | ** The following are the tables generated in this section: 118 | ** 119 | ** yy_action[] A single table containing all actions. 120 | ** yy_lookahead[] A table containing the lookahead for each entry in 121 | ** yy_action. Used to detect hash collisions. 122 | ** yy_shift_ofst[] For each state, the offset into yy_action for 123 | ** shifting terminals. 124 | ** yy_reduce_ofst[] For each state, the offset into yy_action for 125 | ** shifting non-terminals after a reduce. 126 | ** yy_default[] Default action for each state. 127 | */ 128 | %% 129 | 130 | /* The next table maps tokens into fallback tokens. If a construct 131 | ** like the following: 132 | ** 133 | ** %fallback ID X Y Z. 134 | ** 135 | ** appears in the grammar, then ID becomes a fallback token for X, Y, 136 | ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser 137 | ** but it does not parse, the type of the token is changed to ID and 138 | ** the parse is retried before an error is thrown. 139 | */ 140 | #ifdef YYFALLBACK 141 | static const YYCODETYPE yyFallback[] = { 142 | %% 143 | }; 144 | #endif /* YYFALLBACK */ 145 | 146 | /* The following structure represents a single element of the 147 | ** parser's stack. Information stored includes: 148 | ** 149 | ** + The state number for the parser at this level of the stack. 150 | ** 151 | ** + The value of the token stored at this level of the stack. 152 | ** (In other words, the "major" token.) 153 | ** 154 | ** + The semantic value stored at this level of the stack. This is 155 | ** the information used by the action routines in the grammar. 156 | ** It is sometimes called the "minor" token. 157 | */ 158 | struct yyStackEntry { 159 | YYACTIONTYPE stateno; /* The state-number */ 160 | YYCODETYPE major; /* The major token value. This is the code 161 | ** number for the token at this stack level */ 162 | YYMINORTYPE minor; /* The user-supplied minor token value. This 163 | ** is the value of the token */ 164 | }; 165 | typedef struct yyStackEntry yyStackEntry; 166 | 167 | /* The state of the parser is completely contained in an instance of 168 | ** the following structure */ 169 | struct yyParser { 170 | int yyidx; /* Index of top element in stack */ 171 | #ifdef YYTRACKMAXSTACKDEPTH 172 | int yyidxMax; /* Maximum value of yyidx */ 173 | #endif 174 | int yyerrcnt; /* Shifts left before out of the error */ 175 | ParseARG_SDECL /* A place to hold %extra_argument */ 176 | #if YYSTACKDEPTH<=0 177 | int yystksz; /* Current side of the stack */ 178 | yyStackEntry *yystack; /* The parser's stack */ 179 | #else 180 | yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ 181 | #endif 182 | }; 183 | typedef struct yyParser yyParser; 184 | 185 | #ifndef NDEBUG 186 | #include 187 | static FILE *yyTraceFILE = 0; 188 | static char *yyTracePrompt = 0; 189 | #endif /* NDEBUG */ 190 | 191 | #ifndef NDEBUG 192 | /* 193 | ** Turn parser tracing on by giving a stream to which to write the trace 194 | ** and a prompt to preface each trace message. Tracing is turned off 195 | ** by making either argument NULL 196 | ** 197 | ** Inputs: 198 | **
    199 | **
  • A FILE* to which trace output should be written. 200 | ** If NULL, then tracing is turned off. 201 | **
  • A prefix string written at the beginning of every 202 | ** line of trace output. If NULL, then tracing is 203 | ** turned off. 204 | **
205 | ** 206 | ** Outputs: 207 | ** None. 208 | */ 209 | void ParseTrace(FILE *TraceFILE, char *zTracePrompt){ 210 | yyTraceFILE = TraceFILE; 211 | yyTracePrompt = zTracePrompt; 212 | if( yyTraceFILE==0 ) yyTracePrompt = 0; 213 | else if( yyTracePrompt==0 ) yyTraceFILE = 0; 214 | } 215 | #endif /* NDEBUG */ 216 | 217 | #ifndef NDEBUG 218 | /* For tracing shifts, the names of all terminals and nonterminals 219 | ** are required. The following table supplies these names */ 220 | static const char *const yyTokenName[] = { 221 | %% 222 | }; 223 | #endif /* NDEBUG */ 224 | 225 | #ifndef NDEBUG 226 | /* For tracing reduce actions, the names of all rules are required. 227 | */ 228 | static const char *const yyRuleName[] = { 229 | %% 230 | }; 231 | #endif /* NDEBUG */ 232 | 233 | 234 | #if YYSTACKDEPTH<=0 235 | /* 236 | ** Try to increase the size of the parser stack. 237 | */ 238 | static void yyGrowStack(yyParser *p){ 239 | int newSize; 240 | yyStackEntry *pNew; 241 | 242 | newSize = p->yystksz*2 + 100; 243 | pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); 244 | if( pNew ){ 245 | p->yystack = pNew; 246 | p->yystksz = newSize; 247 | #ifndef NDEBUG 248 | if( yyTraceFILE ){ 249 | fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", 250 | yyTracePrompt, p->yystksz); 251 | } 252 | #endif 253 | } 254 | } 255 | #endif 256 | 257 | /* 258 | ** This function allocates a new parser. 259 | ** The only argument is a pointer to a function which works like 260 | ** malloc. 261 | ** 262 | ** Inputs: 263 | ** A pointer to the function used to allocate memory. 264 | ** 265 | ** Outputs: 266 | ** A pointer to a parser. This pointer is used in subsequent calls 267 | ** to Parse and ParseFree. 268 | */ 269 | void *ParseAlloc(void *(*mallocProc)(size_t)){ 270 | yyParser *pParser; 271 | pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); 272 | if( pParser ){ 273 | pParser->yyidx = -1; 274 | #ifdef YYTRACKMAXSTACKDEPTH 275 | pParser->yyidxMax = 0; 276 | #endif 277 | #if YYSTACKDEPTH<=0 278 | pParser->yystack = NULL; 279 | pParser->yystksz = 0; 280 | yyGrowStack(pParser); 281 | #endif 282 | } 283 | return pParser; 284 | } 285 | 286 | /* The following function deletes the value associated with a 287 | ** symbol. The symbol can be either a terminal or nonterminal. 288 | ** "yymajor" is the symbol code, and "yypminor" is a pointer to 289 | ** the value. 290 | */ 291 | static void yy_destructor( 292 | yyParser *yypParser, /* The parser */ 293 | YYCODETYPE yymajor, /* Type code for object to destroy */ 294 | YYMINORTYPE *yypminor /* The object to be destroyed */ 295 | ){ 296 | ParseARG_FETCH; 297 | switch( yymajor ){ 298 | /* Here is inserted the actions which take place when a 299 | ** terminal or non-terminal is destroyed. This can happen 300 | ** when the symbol is popped from the stack during a 301 | ** reduce or during error processing or when a parser is 302 | ** being destroyed before it is finished parsing. 303 | ** 304 | ** Note: during a reduce, the only symbols destroyed are those 305 | ** which appear on the RHS of the rule, but which are not used 306 | ** inside the C code. 307 | */ 308 | %% 309 | default: break; /* If no destructor action specified: do nothing */ 310 | } 311 | } 312 | 313 | /* 314 | ** Pop the parser's stack once. 315 | ** 316 | ** If there is a destructor routine associated with the token which 317 | ** is popped from the stack, then call it. 318 | ** 319 | ** Return the major token number for the symbol popped. 320 | */ 321 | static int yy_pop_parser_stack(yyParser *pParser){ 322 | YYCODETYPE yymajor; 323 | yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; 324 | 325 | if( pParser->yyidx<0 ) return 0; 326 | #ifndef NDEBUG 327 | if( yyTraceFILE && pParser->yyidx>=0 ){ 328 | fprintf(yyTraceFILE,"%sPopping %s\n", 329 | yyTracePrompt, 330 | yyTokenName[yytos->major]); 331 | } 332 | #endif 333 | yymajor = yytos->major; 334 | yy_destructor(pParser, yymajor, &yytos->minor); 335 | pParser->yyidx--; 336 | return yymajor; 337 | } 338 | 339 | /* 340 | ** Deallocate and destroy a parser. Destructors are all called for 341 | ** all stack elements before shutting the parser down. 342 | ** 343 | ** Inputs: 344 | **
    345 | **
  • A pointer to the parser. This should be a pointer 346 | ** obtained from ParseAlloc. 347 | **
  • A pointer to a function used to reclaim memory obtained 348 | ** from malloc. 349 | **
350 | */ 351 | void ParseFree( 352 | void *p, /* The parser to be deleted */ 353 | void (*freeProc)(void*) /* Function used to reclaim memory */ 354 | ){ 355 | yyParser *pParser = (yyParser*)p; 356 | if( pParser==0 ) return; 357 | while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); 358 | #if YYSTACKDEPTH<=0 359 | free(pParser->yystack); 360 | #endif 361 | (*freeProc)((void*)pParser); 362 | } 363 | 364 | /* 365 | ** Return the peak depth of the stack for a parser. 366 | */ 367 | #ifdef YYTRACKMAXSTACKDEPTH 368 | int ParseStackPeak(void *p){ 369 | yyParser *pParser = (yyParser*)p; 370 | return pParser->yyidxMax; 371 | } 372 | #endif 373 | 374 | /* 375 | ** Find the appropriate action for a parser given the terminal 376 | ** look-ahead token iLookAhead. 377 | ** 378 | ** If the look-ahead token is YYNOCODE, then check to see if the action is 379 | ** independent of the look-ahead. If it is, return the action, otherwise 380 | ** return YY_NO_ACTION. 381 | */ 382 | static int yy_find_shift_action( 383 | yyParser *pParser, /* The parser */ 384 | YYCODETYPE iLookAhead /* The look-ahead token */ 385 | ){ 386 | int i; 387 | int stateno = pParser->yystack[pParser->yyidx].stateno; 388 | 389 | if( stateno>YY_SHIFT_COUNT 390 | || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ 391 | return yy_default[stateno]; 392 | } 393 | assert( iLookAhead!=YYNOCODE ); 394 | i += iLookAhead; 395 | if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ 396 | if( iLookAhead>0 ){ 397 | #ifdef YYFALLBACK 398 | YYCODETYPE iFallback; /* Fallback token */ 399 | if( iLookAhead %s\n", 404 | yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); 405 | } 406 | #endif 407 | return yy_find_shift_action(pParser, iFallback); 408 | } 409 | #endif 410 | #ifdef YYWILDCARD 411 | { 412 | int j = i - iLookAhead + YYWILDCARD; 413 | if( 414 | #if YY_SHIFT_MIN+YYWILDCARD<0 415 | j>=0 && 416 | #endif 417 | #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT 418 | j %s\n", 425 | yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); 426 | } 427 | #endif /* NDEBUG */ 428 | return yy_action[j]; 429 | } 430 | } 431 | #endif /* YYWILDCARD */ 432 | } 433 | return yy_default[stateno]; 434 | }else{ 435 | return yy_action[i]; 436 | } 437 | } 438 | 439 | /* 440 | ** Find the appropriate action for a parser given the non-terminal 441 | ** look-ahead token iLookAhead. 442 | ** 443 | ** If the look-ahead token is YYNOCODE, then check to see if the action is 444 | ** independent of the look-ahead. If it is, return the action, otherwise 445 | ** return YY_NO_ACTION. 446 | */ 447 | static int yy_find_reduce_action( 448 | int stateno, /* Current state number */ 449 | YYCODETYPE iLookAhead /* The look-ahead token */ 450 | ){ 451 | int i; 452 | #ifdef YYERRORSYMBOL 453 | if( stateno>YY_REDUCE_COUNT ){ 454 | return yy_default[stateno]; 455 | } 456 | #else 457 | assert( stateno<=YY_REDUCE_COUNT ); 458 | #endif 459 | i = yy_reduce_ofst[stateno]; 460 | assert( i!=YY_REDUCE_USE_DFLT ); 461 | assert( iLookAhead!=YYNOCODE ); 462 | i += iLookAhead; 463 | #ifdef YYERRORSYMBOL 464 | if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ 465 | return yy_default[stateno]; 466 | } 467 | #else 468 | assert( i>=0 && iyyidx--; 480 | #ifndef NDEBUG 481 | if( yyTraceFILE ){ 482 | fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); 483 | } 484 | #endif 485 | while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); 486 | /* Here code is inserted which will execute if the parser 487 | ** stack every overflows */ 488 | %% 489 | ParseARG_STORE; /* Suppress warning about unused %extra_argument var */ 490 | } 491 | 492 | /* 493 | ** Perform a shift action. 494 | */ 495 | static void yy_shift( 496 | yyParser *yypParser, /* The parser to be shifted */ 497 | int yyNewState, /* The new state to shift in */ 498 | int yyMajor, /* The major token to shift in */ 499 | YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */ 500 | ){ 501 | yyStackEntry *yytos; 502 | yypParser->yyidx++; 503 | #ifdef YYTRACKMAXSTACKDEPTH 504 | if( yypParser->yyidx>yypParser->yyidxMax ){ 505 | yypParser->yyidxMax = yypParser->yyidx; 506 | } 507 | #endif 508 | #if YYSTACKDEPTH>0 509 | if( yypParser->yyidx>=YYSTACKDEPTH ){ 510 | yyStackOverflow(yypParser, yypMinor); 511 | return; 512 | } 513 | #else 514 | if( yypParser->yyidx>=yypParser->yystksz ){ 515 | yyGrowStack(yypParser); 516 | if( yypParser->yyidx>=yypParser->yystksz ){ 517 | yyStackOverflow(yypParser, yypMinor); 518 | return; 519 | } 520 | } 521 | #endif 522 | yytos = &yypParser->yystack[yypParser->yyidx]; 523 | yytos->stateno = (YYACTIONTYPE)yyNewState; 524 | yytos->major = (YYCODETYPE)yyMajor; 525 | yytos->minor = *yypMinor; 526 | #ifndef NDEBUG 527 | if( yyTraceFILE && yypParser->yyidx>0 ){ 528 | int i; 529 | fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); 530 | fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); 531 | for(i=1; i<=yypParser->yyidx; i++) 532 | fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); 533 | fprintf(yyTraceFILE,"\n"); 534 | } 535 | #endif 536 | } 537 | 538 | /* The following table contains information about every rule that 539 | ** is used during the reduce. 540 | */ 541 | static const struct { 542 | YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ 543 | unsigned char nrhs; /* Number of right-hand side symbols in the rule */ 544 | } yyRuleInfo[] = { 545 | %% 546 | }; 547 | 548 | static void yy_accept(yyParser*); /* Forward Declaration */ 549 | 550 | /* 551 | ** Perform a reduce action and the shift that must immediately 552 | ** follow the reduce. 553 | */ 554 | static void yy_reduce( 555 | yyParser *yypParser, /* The parser */ 556 | int yyruleno /* Number of the rule by which to reduce */ 557 | ){ 558 | int yygoto; /* The next state */ 559 | int yyact; /* The next action */ 560 | YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ 561 | yyStackEntry *yymsp; /* The top of the parser's stack */ 562 | int yysize; /* Amount to pop the stack */ 563 | ParseARG_FETCH; 564 | yymsp = &yypParser->yystack[yypParser->yyidx]; 565 | #ifndef NDEBUG 566 | if( yyTraceFILE && yyruleno>=0 567 | && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ 568 | fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, 569 | yyRuleName[yyruleno]); 570 | } 571 | #endif /* NDEBUG */ 572 | 573 | /* Silence complaints from purify about yygotominor being uninitialized 574 | ** in some cases when it is copied into the stack after the following 575 | ** switch. yygotominor is uninitialized when a rule reduces that does 576 | ** not set the value of its left-hand side nonterminal. Leaving the 577 | ** value of the nonterminal uninitialized is utterly harmless as long 578 | ** as the value is never used. So really the only thing this code 579 | ** accomplishes is to quieten purify. 580 | ** 581 | ** 2007-01-16: The wireshark project (www.wireshark.org) reports that 582 | ** without this code, their parser segfaults. I'm not sure what there 583 | ** parser is doing to make this happen. This is the second bug report 584 | ** from wireshark this week. Clearly they are stressing Lemon in ways 585 | ** that it has not been previously stressed... (SQLite ticket #2172) 586 | */ 587 | /*memset(&yygotominor, 0, sizeof(yygotominor));*/ 588 | yygotominor = yyzerominor; 589 | 590 | 591 | switch( yyruleno ){ 592 | /* Beginning here are the reduction cases. A typical example 593 | ** follows: 594 | ** case 0: 595 | ** #line 596 | ** { ... } // User supplied code 597 | ** #line 598 | ** break; 599 | */ 600 | %% 601 | }; 602 | yygoto = yyRuleInfo[yyruleno].lhs; 603 | yysize = yyRuleInfo[yyruleno].nrhs; 604 | yypParser->yyidx -= yysize; 605 | yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); 606 | if( yyact < YYNSTATE ){ 607 | #ifdef NDEBUG 608 | /* If we are not debugging and the reduce action popped at least 609 | ** one element off the stack, then we can push the new element back 610 | ** onto the stack here, and skip the stack overflow test in yy_shift(). 611 | ** That gives a significant speed improvement. */ 612 | if( yysize ){ 613 | yypParser->yyidx++; 614 | yymsp -= yysize-1; 615 | yymsp->stateno = (YYACTIONTYPE)yyact; 616 | yymsp->major = (YYCODETYPE)yygoto; 617 | yymsp->minor = yygotominor; 618 | }else 619 | #endif 620 | { 621 | yy_shift(yypParser,yyact,yygoto,&yygotominor); 622 | } 623 | }else{ 624 | assert( yyact == YYNSTATE + YYNRULE + 1 ); 625 | yy_accept(yypParser); 626 | } 627 | } 628 | 629 | /* 630 | ** The following code executes when the parse fails 631 | */ 632 | #ifndef YYNOERRORRECOVERY 633 | static void yy_parse_failed( 634 | yyParser *yypParser /* The parser */ 635 | ){ 636 | ParseARG_FETCH; 637 | #ifndef NDEBUG 638 | if( yyTraceFILE ){ 639 | fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); 640 | } 641 | #endif 642 | while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); 643 | /* Here code is inserted which will be executed whenever the 644 | ** parser fails */ 645 | %% 646 | ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ 647 | } 648 | #endif /* YYNOERRORRECOVERY */ 649 | 650 | /* 651 | ** The following code executes when a syntax error first occurs. 652 | */ 653 | static void yy_syntax_error( 654 | yyParser *yypParser, /* The parser */ 655 | int yymajor, /* The major type of the error token */ 656 | YYMINORTYPE yyminor /* The minor type of the error token */ 657 | ){ 658 | ParseARG_FETCH; 659 | #define TOKEN (yyminor.yy0) 660 | %% 661 | ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ 662 | } 663 | 664 | /* 665 | ** The following is executed when the parser accepts 666 | */ 667 | static void yy_accept( 668 | yyParser *yypParser /* The parser */ 669 | ){ 670 | ParseARG_FETCH; 671 | #ifndef NDEBUG 672 | if( yyTraceFILE ){ 673 | fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); 674 | } 675 | #endif 676 | while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); 677 | /* Here code is inserted which will be executed whenever the 678 | ** parser accepts */ 679 | %% 680 | ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ 681 | } 682 | 683 | /* The main parser program. 684 | ** The first argument is a pointer to a structure obtained from 685 | ** "ParseAlloc" which describes the current state of the parser. 686 | ** The second argument is the major token number. The third is 687 | ** the minor token. The fourth optional argument is whatever the 688 | ** user wants (and specified in the grammar) and is available for 689 | ** use by the action routines. 690 | ** 691 | ** Inputs: 692 | **
    693 | **
  • A pointer to the parser (an opaque structure.) 694 | **
  • The major token number. 695 | **
  • The minor token number. 696 | **
  • An option argument of a grammar-specified type. 697 | **
698 | ** 699 | ** Outputs: 700 | ** None. 701 | */ 702 | void Parse( 703 | void *yyp, /* The parser */ 704 | int yymajor, /* The major token code number */ 705 | ParseTOKENTYPE yyminor /* The value for the token */ 706 | ParseARG_PDECL /* Optional %extra_argument parameter */ 707 | ){ 708 | YYMINORTYPE yyminorunion; 709 | int yyact; /* The parser action. */ 710 | int yyendofinput; /* True if we are at the end of input */ 711 | #ifdef YYERRORSYMBOL 712 | int yyerrorhit = 0; /* True if yymajor has invoked an error */ 713 | #endif 714 | yyParser *yypParser; /* The parser */ 715 | 716 | /* (re)initialize the parser, if necessary */ 717 | yypParser = (yyParser*)yyp; 718 | if( yypParser->yyidx<0 ){ 719 | #if YYSTACKDEPTH<=0 720 | if( yypParser->yystksz <=0 ){ 721 | /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ 722 | yyminorunion = yyzerominor; 723 | yyStackOverflow(yypParser, &yyminorunion); 724 | return; 725 | } 726 | #endif 727 | yypParser->yyidx = 0; 728 | yypParser->yyerrcnt = -1; 729 | yypParser->yystack[0].stateno = 0; 730 | yypParser->yystack[0].major = 0; 731 | } 732 | yyminorunion.yy0 = yyminor; 733 | yyendofinput = (yymajor==0); 734 | ParseARG_STORE; 735 | 736 | #ifndef NDEBUG 737 | if( yyTraceFILE ){ 738 | fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); 739 | } 740 | #endif 741 | 742 | do{ 743 | yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); 744 | if( yyactyyerrcnt--; 748 | yymajor = YYNOCODE; 749 | }else if( yyact < YYNSTATE + YYNRULE ){ 750 | yy_reduce(yypParser,yyact-YYNSTATE); 751 | }else{ 752 | assert( yyact == YY_ERROR_ACTION ); 753 | #ifdef YYERRORSYMBOL 754 | int yymx; 755 | #endif 756 | #ifndef NDEBUG 757 | if( yyTraceFILE ){ 758 | fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); 759 | } 760 | #endif 761 | #ifdef YYERRORSYMBOL 762 | /* A syntax error has occurred. 763 | ** The response to an error depends upon whether or not the 764 | ** grammar defines an error token "ERROR". 765 | ** 766 | ** This is what we do if the grammar does define ERROR: 767 | ** 768 | ** * Call the %syntax_error function. 769 | ** 770 | ** * Begin popping the stack until we enter a state where 771 | ** it is legal to shift the error symbol, then shift 772 | ** the error symbol. 773 | ** 774 | ** * Set the error count to three. 775 | ** 776 | ** * Begin accepting and shifting new tokens. No new error 777 | ** processing will occur until three tokens have been 778 | ** shifted successfully. 779 | ** 780 | */ 781 | if( yypParser->yyerrcnt<0 ){ 782 | yy_syntax_error(yypParser,yymajor,yyminorunion); 783 | } 784 | yymx = yypParser->yystack[yypParser->yyidx].major; 785 | if( yymx==YYERRORSYMBOL || yyerrorhit ){ 786 | #ifndef NDEBUG 787 | if( yyTraceFILE ){ 788 | fprintf(yyTraceFILE,"%sDiscard input token %s\n", 789 | yyTracePrompt,yyTokenName[yymajor]); 790 | } 791 | #endif 792 | yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion); 793 | yymajor = YYNOCODE; 794 | }else{ 795 | while( 796 | yypParser->yyidx >= 0 && 797 | yymx != YYERRORSYMBOL && 798 | (yyact = yy_find_reduce_action( 799 | yypParser->yystack[yypParser->yyidx].stateno, 800 | YYERRORSYMBOL)) >= YYNSTATE 801 | ){ 802 | yy_pop_parser_stack(yypParser); 803 | } 804 | if( yypParser->yyidx < 0 || yymajor==0 ){ 805 | yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); 806 | yy_parse_failed(yypParser); 807 | yymajor = YYNOCODE; 808 | }else if( yymx!=YYERRORSYMBOL ){ 809 | YYMINORTYPE u2; 810 | u2.YYERRSYMDT = 0; 811 | yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); 812 | } 813 | } 814 | yypParser->yyerrcnt = 3; 815 | yyerrorhit = 1; 816 | #elif defined(YYNOERRORRECOVERY) 817 | /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to 818 | ** do any kind of error recovery. Instead, simply invoke the syntax 819 | ** error routine and continue going as if nothing had happened. 820 | ** 821 | ** Applications can set this macro (for example inside %include) if 822 | ** they intend to abandon the parse upon the first syntax error seen. 823 | */ 824 | yy_syntax_error(yypParser,yymajor,yyminorunion); 825 | yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); 826 | yymajor = YYNOCODE; 827 | 828 | #else /* YYERRORSYMBOL is not defined */ 829 | /* This is what we do if the grammar does not define ERROR: 830 | ** 831 | ** * Report an error message, and throw away the input token. 832 | ** 833 | ** * If the input token is $, then fail the parse. 834 | ** 835 | ** As before, subsequent error messages are suppressed until 836 | ** three input tokens have been successfully shifted. 837 | */ 838 | if( yypParser->yyerrcnt<=0 ){ 839 | yy_syntax_error(yypParser,yymajor,yyminorunion); 840 | } 841 | yypParser->yyerrcnt = 3; 842 | yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); 843 | if( yyendofinput ){ 844 | yy_parse_failed(yypParser); 845 | } 846 | yymajor = YYNOCODE; 847 | #endif 848 | } 849 | }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); 850 | return; 851 | } 852 | --------------------------------------------------------------------------------