Debian Codegraph @

misc/lemon.c

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