blob: f27fe4d24a7bfb0a60e77cc4f640fdf942d74396 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
drhf9a2e7b2003-04-15 01:49:48 +000010#include <stdarg.h>
drh75897232000-05-29 14:26:00 +000011#include <string.h>
12#include <ctype.h>
drh8b582012003-10-21 13:16:03 +000013#include <stdlib.h>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drh75897232000-05-29 14:26:00 +000016#ifndef __WIN32__
17# if defined(_WIN32) || defined(WIN32)
drhf2f105d2012-08-20 15:53:54 +000018# define __WIN32__
drh75897232000-05-29 14:26:00 +000019# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
drhdf609712010-11-23 20:55:27 +000023#ifdef __cplusplus
24extern "C" {
25#endif
26extern int access(const char *path, int mode);
27#ifdef __cplusplus
28}
29#endif
rse8f304482007-07-30 18:31:53 +000030#else
31#include <unistd.h>
32#endif
33
drh75897232000-05-29 14:26:00 +000034/* #define PRIVATE static */
35#define PRIVATE
36
37#ifdef TEST
38#define MAXRHS 5 /* Set low to exercise exception code */
39#else
40#define MAXRHS 1000
41#endif
42
drhf5c4e0f2010-07-18 11:35:53 +000043static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000044static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000045
drh87cf1372008-08-13 20:09:06 +000046/*
47** Compilers are getting increasingly pedantic about type conversions
48** as C evolves ever closer to Ada.... To work around the latest problems
49** we have to define the following variant of strlen().
50*/
51#define lemonStrlen(X) ((int)strlen(X))
52
drh898799f2014-01-10 23:21:00 +000053/*
54** Compilers are starting to complain about the use of sprintf() and strcpy(),
55** saying they are unsafe. So we define our own versions of those routines too.
56**
57** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
drh25473362015-09-04 18:03:45 +000058** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
drh898799f2014-01-10 23:21:00 +000059** The third is a helper routine for vsnprintf() that adds texts to the end of a
60** buffer, making sure the buffer is always zero-terminated.
61**
62** The string formatter is a minimal subset of stdlib sprintf() supporting only
63** a few simply conversions:
64**
65** %d
66** %s
67** %.*s
68**
69*/
70static void lemon_addtext(
71 char *zBuf, /* The buffer to which text is added */
72 int *pnUsed, /* Slots of the buffer used so far */
73 const char *zIn, /* Text to add */
drh61f92cd2014-01-11 03:06:18 +000074 int nIn, /* Bytes of text to add. -1 to use strlen() */
75 int iWidth /* Field width. Negative to left justify */
drh898799f2014-01-10 23:21:00 +000076){
77 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
drhecaa9d32014-01-11 03:27:37 +000078 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
drh898799f2014-01-10 23:21:00 +000079 if( nIn==0 ) return;
80 memcpy(&zBuf[*pnUsed], zIn, nIn);
81 *pnUsed += nIn;
drhecaa9d32014-01-11 03:27:37 +000082 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
drh898799f2014-01-10 23:21:00 +000083 zBuf[*pnUsed] = 0;
84}
85static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
mistachkin7a429652014-01-14 10:17:21 +000086 int i, j, k, c;
drh898799f2014-01-10 23:21:00 +000087 int nUsed = 0;
88 const char *z;
89 char zTemp[50];
90 str[0] = 0;
91 for(i=j=0; (c = zFormat[i])!=0; i++){
92 if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +000093 int iWidth = 0;
94 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +000095 c = zFormat[++i];
drh61f92cd2014-01-11 03:06:18 +000096 if( isdigit(c) || (c=='-' && isdigit(zFormat[i+1])) ){
97 if( c=='-' ) i++;
98 while( isdigit(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
99 if( c=='-' ) iWidth = -iWidth;
100 c = zFormat[i];
101 }
drh898799f2014-01-10 23:21:00 +0000102 if( c=='d' ){
103 int v = va_arg(ap, int);
104 if( v<0 ){
drh61f92cd2014-01-11 03:06:18 +0000105 lemon_addtext(str, &nUsed, "-", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000106 v = -v;
107 }else if( v==0 ){
drh61f92cd2014-01-11 03:06:18 +0000108 lemon_addtext(str, &nUsed, "0", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000109 }
110 k = 0;
111 while( v>0 ){
112 k++;
113 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
114 v /= 10;
115 }
drh61f92cd2014-01-11 03:06:18 +0000116 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
drh898799f2014-01-10 23:21:00 +0000117 }else if( c=='s' ){
118 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000119 lemon_addtext(str, &nUsed, z, -1, iWidth);
drh898799f2014-01-10 23:21:00 +0000120 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
121 i += 2;
122 k = va_arg(ap, int);
123 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000124 lemon_addtext(str, &nUsed, z, k, iWidth);
drh898799f2014-01-10 23:21:00 +0000125 }else if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000126 lemon_addtext(str, &nUsed, "%", 1, 0);
drh898799f2014-01-10 23:21:00 +0000127 }else{
128 fprintf(stderr, "illegal format\n");
129 exit(1);
130 }
131 j = i+1;
132 }
133 }
drh61f92cd2014-01-11 03:06:18 +0000134 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000135 return nUsed;
136}
137static int lemon_sprintf(char *str, const char *format, ...){
138 va_list ap;
139 int rc;
140 va_start(ap, format);
141 rc = lemon_vsprintf(str, format, ap);
142 va_end(ap);
143 return rc;
144}
145static void lemon_strcpy(char *dest, const char *src){
146 while( (*(dest++) = *(src++))!=0 ){}
147}
148static void lemon_strcat(char *dest, const char *src){
149 while( *dest ) dest++;
150 lemon_strcpy(dest, src);
151}
152
153
icculus9e44cf12010-02-14 17:14:22 +0000154/* a few forward declarations... */
155struct rule;
156struct lemon;
157struct action;
158
drhe9278182007-07-18 18:16:29 +0000159static struct action *Action_new(void);
160static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +0000161
162/********** From the file "build.h" ************************************/
163void FindRulePrecedences();
164void FindFirstSets();
165void FindStates();
166void FindLinks();
167void FindFollowSets();
168void FindActions();
169
170/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +0000171void Configlist_init(void);
172struct config *Configlist_add(struct rule *, int);
173struct config *Configlist_addbasis(struct rule *, int);
174void Configlist_closure(struct lemon *);
175void Configlist_sort(void);
176void Configlist_sortbasis(void);
177struct config *Configlist_return(void);
178struct config *Configlist_basis(void);
179void Configlist_eat(struct config *);
180void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +0000181
182/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +0000183void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +0000184
185/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +0000186enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
187 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +0000188struct s_options {
icculus9e44cf12010-02-14 17:14:22 +0000189 enum option_type type;
190 const char *label;
drh75897232000-05-29 14:26:00 +0000191 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000192 const char *message;
drh75897232000-05-29 14:26:00 +0000193};
icculus9e44cf12010-02-14 17:14:22 +0000194int OptInit(char**,struct s_options*,FILE*);
195int OptNArgs(void);
196char *OptArg(int);
197void OptErr(int);
198void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000199
200/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000201void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000202
203/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000204struct plink *Plink_new(void);
205void Plink_add(struct plink **, struct config *);
206void Plink_copy(struct plink **, struct plink *);
207void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000208
209/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000210void Reprint(struct lemon *);
211void ReportOutput(struct lemon *);
212void ReportTable(struct lemon *, int);
213void ReportHeader(struct lemon *);
214void CompressTables(struct lemon *);
215void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000216
217/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000218void SetSize(int); /* All sets will be of size N */
219char *SetNew(void); /* A new set for element 0..N */
220void SetFree(char*); /* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +0000221int SetAdd(char*,int); /* Add element to a set */
222int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000223#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
224
225/********** From the file "struct.h" *************************************/
226/*
227** Principal data structures for the LEMON parser generator.
228*/
229
drhaa9f1122007-08-23 02:50:56 +0000230typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000231
232/* Symbols (terminals and nonterminals) of the grammar are stored
233** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000234enum symbol_type {
235 TERMINAL,
236 NONTERMINAL,
237 MULTITERMINAL
238};
239enum e_assoc {
drh75897232000-05-29 14:26:00 +0000240 LEFT,
241 RIGHT,
242 NONE,
243 UNK
icculus9e44cf12010-02-14 17:14:22 +0000244};
245struct symbol {
246 const char *name; /* Name of the symbol */
247 int index; /* Index number for this symbol */
248 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
249 struct rule *rule; /* Linked list of rules of this (if an NT) */
250 struct symbol *fallback; /* fallback token in case this token doesn't parse */
251 int prec; /* Precedence if defined (-1 otherwise) */
252 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000253 char *firstset; /* First-set for all rules of this symbol */
254 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000255 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000256 char *destructor; /* Code which executes whenever this symbol is
257 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000258 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000259 char *datatype; /* The data type of information held by this
260 ** object. Only used if type==NONTERMINAL */
261 int dtnum; /* The data type number. In the parser, the value
262 ** stack is a union. The .yy%d element of this
263 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000264 /* The following fields are used by MULTITERMINALs only */
265 int nsubsym; /* Number of constituent symbols in the MULTI */
266 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000267};
268
269/* Each production rule in the grammar is stored in the following
270** structure. */
271struct rule {
272 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000273 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000274 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000275 int ruleline; /* Line number for the rule */
276 int nrhs; /* Number of RHS symbols */
277 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000278 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000279 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000280 const char *code; /* The code executed when this rule is reduced */
drh75897232000-05-29 14:26:00 +0000281 struct symbol *precsym; /* Precedence symbol for this rule */
282 int index; /* An index number for this rule */
283 Boolean canReduce; /* True if this rule is ever reduced */
284 struct rule *nextlhs; /* Next rule with the same LHS */
285 struct rule *next; /* Next rule in the global list */
286};
287
288/* A configuration is a production rule of the grammar together with
289** a mark (dot) showing how much of that rule has been processed so far.
290** Configurations also contain a follow-set which is a list of terminal
291** symbols which are allowed to immediately follow the end of the rule.
292** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000293enum cfgstatus {
294 COMPLETE,
295 INCOMPLETE
296};
drh75897232000-05-29 14:26:00 +0000297struct config {
298 struct rule *rp; /* The rule upon which the configuration is based */
299 int dot; /* The parse point */
300 char *fws; /* Follow-set for this configuration only */
301 struct plink *fplp; /* Follow-set forward propagation links */
302 struct plink *bplp; /* Follow-set backwards propagation links */
303 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000304 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000305 struct config *next; /* Next configuration in the state */
306 struct config *bp; /* The next basis configuration */
307};
308
icculus9e44cf12010-02-14 17:14:22 +0000309enum e_action {
310 SHIFT,
311 ACCEPT,
312 REDUCE,
313 ERROR,
314 SSCONFLICT, /* A shift/shift conflict */
315 SRCONFLICT, /* Was a reduce, but part of a conflict */
316 RRCONFLICT, /* Was a reduce, but part of a conflict */
317 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
318 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
319 NOT_USED /* Deleted by compression */
320};
321
drh75897232000-05-29 14:26:00 +0000322/* Every shift or reduce operation is stored as one of the following */
323struct action {
324 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000325 enum e_action type;
drh75897232000-05-29 14:26:00 +0000326 union {
327 struct state *stp; /* The new state, if a shift */
328 struct rule *rp; /* The rule, if a reduce */
329 } x;
330 struct action *next; /* Next action for this state */
331 struct action *collide; /* Next action with the same hash */
332};
333
334/* Each state of the generated parser's finite state machine
335** is encoded as an instance of the following structure. */
336struct state {
337 struct config *bp; /* The basis configurations for this state */
338 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000339 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000340 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000341 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
342 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
343 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000344};
drh8b582012003-10-21 13:16:03 +0000345#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000346
347/* A followset propagation link indicates that the contents of one
348** configuration followset should be propagated to another whenever
349** the first changes. */
350struct plink {
351 struct config *cfp; /* The configuration to which linked */
352 struct plink *next; /* The next propagate link */
353};
354
355/* The state vector for the entire parser generator is recorded as
356** follows. (LEMON uses no global variables and makes little use of
357** static variables. Fields in the following structure can be thought
358** of as begin global variables in the program.) */
359struct lemon {
360 struct state **sorted; /* Table of states sorted by state number */
361 struct rule *rule; /* List of all rules */
362 int nstate; /* Number of states */
363 int nrule; /* Number of rules */
364 int nsymbol; /* Number of terminal and nonterminal symbols */
365 int nterminal; /* Number of terminal symbols */
366 struct symbol **symbols; /* Sorted array of pointers to symbols */
367 int errorcnt; /* Number of errors */
368 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000369 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000370 char *name; /* Name of the generated parser */
371 char *arg; /* Declaration of the 3th argument to parser */
372 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000373 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000374 char *start; /* Name of the start symbol for the grammar */
375 char *stacksize; /* Size of the parser stack */
376 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000377 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000378 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000379 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000380 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000381 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000382 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000383 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000384 char *filename; /* Name of the input file */
385 char *outname; /* Name of the current output file */
386 char *tokenprefix; /* A prefix added to token names in the .h file */
387 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000388 int nactiontab; /* Number of entries in the yy_action[] table */
389 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000390 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000391 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000392 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000393 char *argv0; /* Name of the program */
394};
395
396#define MemoryCheck(X) if((X)==0){ \
397 extern void memory_error(); \
398 memory_error(); \
399}
400
401/**************** From the file "table.h" *********************************/
402/*
403** All code in this file has been automatically generated
404** from a specification in the file
405** "table.q"
406** by the associative array code building program "aagen".
407** Do not edit this file! Instead, edit the specification
408** file, then rerun aagen.
409*/
410/*
411** Code for processing tables in the LEMON parser generator.
412*/
drh75897232000-05-29 14:26:00 +0000413/* Routines for handling a strings */
414
icculus9e44cf12010-02-14 17:14:22 +0000415const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000416
icculus9e44cf12010-02-14 17:14:22 +0000417void Strsafe_init(void);
418int Strsafe_insert(const char *);
419const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000420
421/* Routines for handling symbols of the grammar */
422
icculus9e44cf12010-02-14 17:14:22 +0000423struct symbol *Symbol_new(const char *);
424int Symbolcmpp(const void *, const void *);
425void Symbol_init(void);
426int Symbol_insert(struct symbol *, const char *);
427struct symbol *Symbol_find(const char *);
428struct symbol *Symbol_Nth(int);
429int Symbol_count(void);
430struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000431
432/* Routines to manage the state table */
433
icculus9e44cf12010-02-14 17:14:22 +0000434int Configcmp(const char *, const char *);
435struct state *State_new(void);
436void State_init(void);
437int State_insert(struct state *, struct config *);
438struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000439struct state **State_arrayof(/* */);
440
441/* Routines used for efficiency in Configlist_add */
442
icculus9e44cf12010-02-14 17:14:22 +0000443void Configtable_init(void);
444int Configtable_insert(struct config *);
445struct config *Configtable_find(struct config *);
446void Configtable_clear(int(*)(struct config *));
447
drh75897232000-05-29 14:26:00 +0000448/****************** From the file "action.c" *******************************/
449/*
450** Routines processing parser actions in the LEMON parser generator.
451*/
452
453/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000454static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000455 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000456 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000457
458 if( freelist==0 ){
459 int i;
460 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000461 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000462 if( freelist==0 ){
463 fprintf(stderr,"Unable to allocate memory for a new parser action.");
464 exit(1);
465 }
466 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
467 freelist[amt-1].next = 0;
468 }
icculus9e44cf12010-02-14 17:14:22 +0000469 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000470 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000471 return newaction;
drh75897232000-05-29 14:26:00 +0000472}
473
drhe9278182007-07-18 18:16:29 +0000474/* Compare two actions for sorting purposes. Return negative, zero, or
475** positive if the first action is less than, equal to, or greater than
476** the first
477*/
478static int actioncmp(
479 struct action *ap1,
480 struct action *ap2
481){
drh75897232000-05-29 14:26:00 +0000482 int rc;
483 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000484 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000485 rc = (int)ap1->type - (int)ap2->type;
486 }
487 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000488 rc = ap1->x.rp->index - ap2->x.rp->index;
489 }
drhe594bc32009-11-03 13:02:25 +0000490 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000491 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000492 }
drh75897232000-05-29 14:26:00 +0000493 return rc;
494}
495
496/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000497static struct action *Action_sort(
498 struct action *ap
499){
500 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
501 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000502 return ap;
503}
504
icculus9e44cf12010-02-14 17:14:22 +0000505void Action_add(
506 struct action **app,
507 enum e_action type,
508 struct symbol *sp,
509 char *arg
510){
511 struct action *newaction;
512 newaction = Action_new();
513 newaction->next = *app;
514 *app = newaction;
515 newaction->type = type;
516 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000517 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000518 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000519 }else{
icculus9e44cf12010-02-14 17:14:22 +0000520 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000521 }
522}
drh8b582012003-10-21 13:16:03 +0000523/********************** New code to implement the "acttab" module ***********/
524/*
525** This module implements routines use to construct the yy_action[] table.
526*/
527
528/*
529** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000530** the following structure.
531**
532** The yy_action table maps the pair (state_number, lookahead) into an
533** action_number. The table is an array of integers pairs. The state_number
534** determines an initial offset into the yy_action array. The lookahead
535** value is then added to this initial offset to get an index X into the
536** yy_action array. If the aAction[X].lookahead equals the value of the
537** of the lookahead input, then the value of the action_number output is
538** aAction[X].action. If the lookaheads do not match then the
539** default action for the state_number is returned.
540**
541** All actions associated with a single state_number are first entered
542** into aLookahead[] using multiple calls to acttab_action(). Then the
543** actions for that single state_number are placed into the aAction[]
544** array with a single call to acttab_insert(). The acttab_insert() call
545** also resets the aLookahead[] array in preparation for the next
546** state number.
drh8b582012003-10-21 13:16:03 +0000547*/
icculus9e44cf12010-02-14 17:14:22 +0000548struct lookahead_action {
549 int lookahead; /* Value of the lookahead token */
550 int action; /* Action to take on the given lookahead */
551};
drh8b582012003-10-21 13:16:03 +0000552typedef struct acttab acttab;
553struct acttab {
554 int nAction; /* Number of used slots in aAction[] */
555 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000556 struct lookahead_action
557 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000558 *aLookahead; /* A single new transaction set */
559 int mnLookahead; /* Minimum aLookahead[].lookahead */
560 int mnAction; /* Action associated with mnLookahead */
561 int mxLookahead; /* Maximum aLookahead[].lookahead */
562 int nLookahead; /* Used slots in aLookahead[] */
563 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
564};
565
566/* Return the number of entries in the yy_action table */
567#define acttab_size(X) ((X)->nAction)
568
569/* The value for the N-th entry in yy_action */
570#define acttab_yyaction(X,N) ((X)->aAction[N].action)
571
572/* The value for the N-th entry in yy_lookahead */
573#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
574
575/* Free all memory associated with the given acttab */
576void acttab_free(acttab *p){
577 free( p->aAction );
578 free( p->aLookahead );
579 free( p );
580}
581
582/* Allocate a new acttab structure */
583acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000584 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000585 if( p==0 ){
586 fprintf(stderr,"Unable to allocate memory for a new acttab.");
587 exit(1);
588 }
589 memset(p, 0, sizeof(*p));
590 return p;
591}
592
drh8dc3e8f2010-01-07 03:53:03 +0000593/* Add a new action to the current transaction set.
594**
595** This routine is called once for each lookahead for a particular
596** state.
drh8b582012003-10-21 13:16:03 +0000597*/
598void acttab_action(acttab *p, int lookahead, int action){
599 if( p->nLookahead>=p->nLookaheadAlloc ){
600 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000601 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000602 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
603 if( p->aLookahead==0 ){
604 fprintf(stderr,"malloc failed\n");
605 exit(1);
606 }
607 }
608 if( p->nLookahead==0 ){
609 p->mxLookahead = lookahead;
610 p->mnLookahead = lookahead;
611 p->mnAction = action;
612 }else{
613 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
614 if( p->mnLookahead>lookahead ){
615 p->mnLookahead = lookahead;
616 p->mnAction = action;
617 }
618 }
619 p->aLookahead[p->nLookahead].lookahead = lookahead;
620 p->aLookahead[p->nLookahead].action = action;
621 p->nLookahead++;
622}
623
624/*
625** Add the transaction set built up with prior calls to acttab_action()
626** into the current action table. Then reset the transaction set back
627** to an empty set in preparation for a new round of acttab_action() calls.
628**
629** Return the offset into the action table of the new transaction.
630*/
631int acttab_insert(acttab *p){
632 int i, j, k, n;
633 assert( p->nLookahead>0 );
634
635 /* Make sure we have enough space to hold the expanded action table
636 ** in the worst case. The worst case occurs if the transaction set
637 ** must be appended to the current action table
638 */
drh784d86f2004-02-19 18:41:53 +0000639 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000640 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000641 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000642 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000643 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000644 sizeof(p->aAction[0])*p->nActionAlloc);
645 if( p->aAction==0 ){
646 fprintf(stderr,"malloc failed\n");
647 exit(1);
648 }
drhfdbf9282003-10-21 16:34:41 +0000649 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000650 p->aAction[i].lookahead = -1;
651 p->aAction[i].action = -1;
652 }
653 }
654
drh8dc3e8f2010-01-07 03:53:03 +0000655 /* Scan the existing action table looking for an offset that is a
656 ** duplicate of the current transaction set. Fall out of the loop
657 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000658 **
659 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
660 */
drh8dc3e8f2010-01-07 03:53:03 +0000661 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000662 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000663 /* All lookaheads and actions in the aLookahead[] transaction
664 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000665 if( p->aAction[i].action!=p->mnAction ) continue;
666 for(j=0; j<p->nLookahead; j++){
667 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
668 if( k<0 || k>=p->nAction ) break;
669 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
670 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
671 }
672 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000673
674 /* No possible lookahead value that is not in the aLookahead[]
675 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000676 n = 0;
677 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000678 if( p->aAction[j].lookahead<0 ) continue;
679 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000680 }
drhfdbf9282003-10-21 16:34:41 +0000681 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000682 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000683 }
drh8b582012003-10-21 13:16:03 +0000684 }
685 }
drh8dc3e8f2010-01-07 03:53:03 +0000686
687 /* If no existing offsets exactly match the current transaction, find an
688 ** an empty offset in the aAction[] table in which we can add the
689 ** aLookahead[] transaction.
690 */
drhf16371d2009-11-03 19:18:31 +0000691 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000692 /* Look for holes in the aAction[] table that fit the current
693 ** aLookahead[] transaction. Leave i set to the offset of the hole.
694 ** If no holes are found, i is left at p->nAction, which means the
695 ** transaction will be appended. */
696 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000697 if( p->aAction[i].lookahead<0 ){
698 for(j=0; j<p->nLookahead; j++){
699 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
700 if( k<0 ) break;
701 if( p->aAction[k].lookahead>=0 ) break;
702 }
703 if( j<p->nLookahead ) continue;
704 for(j=0; j<p->nAction; j++){
705 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
706 }
707 if( j==p->nAction ){
708 break; /* Fits in empty slots */
709 }
710 }
711 }
712 }
drh8b582012003-10-21 13:16:03 +0000713 /* Insert transaction set at index i. */
714 for(j=0; j<p->nLookahead; j++){
715 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
716 p->aAction[k] = p->aLookahead[j];
717 if( k>=p->nAction ) p->nAction = k+1;
718 }
719 p->nLookahead = 0;
720
721 /* Return the offset that is added to the lookahead in order to get the
722 ** index into yy_action of the action */
723 return i - p->mnLookahead;
724}
725
drh75897232000-05-29 14:26:00 +0000726/********************** From the file "build.c" *****************************/
727/*
728** Routines to construction the finite state machine for the LEMON
729** parser generator.
730*/
731
732/* Find a precedence symbol of every rule in the grammar.
733**
734** Those rules which have a precedence symbol coded in the input
735** grammar using the "[symbol]" construct will already have the
736** rp->precsym field filled. Other rules take as their precedence
737** symbol the first RHS symbol with a defined precedence. If there
738** are not RHS symbols with a defined precedence, the precedence
739** symbol field is left blank.
740*/
icculus9e44cf12010-02-14 17:14:22 +0000741void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000742{
743 struct rule *rp;
744 for(rp=xp->rule; rp; rp=rp->next){
745 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000746 int i, j;
747 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
748 struct symbol *sp = rp->rhs[i];
749 if( sp->type==MULTITERMINAL ){
750 for(j=0; j<sp->nsubsym; j++){
751 if( sp->subsym[j]->prec>=0 ){
752 rp->precsym = sp->subsym[j];
753 break;
754 }
755 }
756 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000757 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000758 }
drh75897232000-05-29 14:26:00 +0000759 }
760 }
761 }
762 return;
763}
764
765/* Find all nonterminals which will generate the empty string.
766** Then go back and compute the first sets of every nonterminal.
767** The first set is the set of all terminal symbols which can begin
768** a string generated by that nonterminal.
769*/
icculus9e44cf12010-02-14 17:14:22 +0000770void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000771{
drhfd405312005-11-06 04:06:59 +0000772 int i, j;
drh75897232000-05-29 14:26:00 +0000773 struct rule *rp;
774 int progress;
775
776 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000777 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000778 }
779 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
780 lemp->symbols[i]->firstset = SetNew();
781 }
782
783 /* First compute all lambdas */
784 do{
785 progress = 0;
786 for(rp=lemp->rule; rp; rp=rp->next){
787 if( rp->lhs->lambda ) continue;
788 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000789 struct symbol *sp = rp->rhs[i];
790 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
791 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000792 }
793 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000794 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000795 progress = 1;
796 }
797 }
798 }while( progress );
799
800 /* Now compute all first sets */
801 do{
802 struct symbol *s1, *s2;
803 progress = 0;
804 for(rp=lemp->rule; rp; rp=rp->next){
805 s1 = rp->lhs;
806 for(i=0; i<rp->nrhs; i++){
807 s2 = rp->rhs[i];
808 if( s2->type==TERMINAL ){
809 progress += SetAdd(s1->firstset,s2->index);
810 break;
drhfd405312005-11-06 04:06:59 +0000811 }else if( s2->type==MULTITERMINAL ){
812 for(j=0; j<s2->nsubsym; j++){
813 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
814 }
815 break;
drhf2f105d2012-08-20 15:53:54 +0000816 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000817 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000818 }else{
drh75897232000-05-29 14:26:00 +0000819 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000820 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000821 }
drh75897232000-05-29 14:26:00 +0000822 }
823 }
824 }while( progress );
825 return;
826}
827
828/* Compute all LR(0) states for the grammar. Links
829** are added to between some states so that the LR(1) follow sets
830** can be computed later.
831*/
icculus9e44cf12010-02-14 17:14:22 +0000832PRIVATE struct state *getstate(struct lemon *); /* forward reference */
833void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000834{
835 struct symbol *sp;
836 struct rule *rp;
837
838 Configlist_init();
839
840 /* Find the start symbol */
841 if( lemp->start ){
842 sp = Symbol_find(lemp->start);
843 if( sp==0 ){
844 ErrorMsg(lemp->filename,0,
845"The specified start symbol \"%s\" is not \
846in a nonterminal of the grammar. \"%s\" will be used as the start \
847symbol instead.",lemp->start,lemp->rule->lhs->name);
848 lemp->errorcnt++;
849 sp = lemp->rule->lhs;
850 }
851 }else{
852 sp = lemp->rule->lhs;
853 }
854
855 /* Make sure the start symbol doesn't occur on the right-hand side of
856 ** any rule. Report an error if it does. (YACC would generate a new
857 ** start symbol in this case.) */
858 for(rp=lemp->rule; rp; rp=rp->next){
859 int i;
860 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000861 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000862 ErrorMsg(lemp->filename,0,
863"The start symbol \"%s\" occurs on the \
864right-hand side of a rule. This will result in a parser which \
865does not work properly.",sp->name);
866 lemp->errorcnt++;
867 }
868 }
869 }
870
871 /* The basis configuration set for the first state
872 ** is all rules which have the start symbol as their
873 ** left-hand side */
874 for(rp=sp->rule; rp; rp=rp->nextlhs){
875 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000876 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000877 newcfp = Configlist_addbasis(rp,0);
878 SetAdd(newcfp->fws,0);
879 }
880
881 /* Compute the first state. All other states will be
882 ** computed automatically during the computation of the first one.
883 ** The returned pointer to the first state is not used. */
884 (void)getstate(lemp);
885 return;
886}
887
888/* Return a pointer to a state which is described by the configuration
889** list which has been built from calls to Configlist_add.
890*/
icculus9e44cf12010-02-14 17:14:22 +0000891PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
892PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000893{
894 struct config *cfp, *bp;
895 struct state *stp;
896
897 /* Extract the sorted basis of the new state. The basis was constructed
898 ** by prior calls to "Configlist_addbasis()". */
899 Configlist_sortbasis();
900 bp = Configlist_basis();
901
902 /* Get a state with the same basis */
903 stp = State_find(bp);
904 if( stp ){
905 /* A state with the same basis already exists! Copy all the follow-set
906 ** propagation links from the state under construction into the
907 ** preexisting state, then return a pointer to the preexisting state */
908 struct config *x, *y;
909 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
910 Plink_copy(&y->bplp,x->bplp);
911 Plink_delete(x->fplp);
912 x->fplp = x->bplp = 0;
913 }
914 cfp = Configlist_return();
915 Configlist_eat(cfp);
916 }else{
917 /* This really is a new state. Construct all the details */
918 Configlist_closure(lemp); /* Compute the configuration closure */
919 Configlist_sort(); /* Sort the configuration closure */
920 cfp = Configlist_return(); /* Get a pointer to the config list */
921 stp = State_new(); /* A new state structure */
922 MemoryCheck(stp);
923 stp->bp = bp; /* Remember the configuration basis */
924 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000925 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000926 stp->ap = 0; /* No actions, yet. */
927 State_insert(stp,stp->bp); /* Add to the state table */
928 buildshifts(lemp,stp); /* Recursively compute successor states */
929 }
930 return stp;
931}
932
drhfd405312005-11-06 04:06:59 +0000933/*
934** Return true if two symbols are the same.
935*/
icculus9e44cf12010-02-14 17:14:22 +0000936int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000937{
938 int i;
939 if( a==b ) return 1;
940 if( a->type!=MULTITERMINAL ) return 0;
941 if( b->type!=MULTITERMINAL ) return 0;
942 if( a->nsubsym!=b->nsubsym ) return 0;
943 for(i=0; i<a->nsubsym; i++){
944 if( a->subsym[i]!=b->subsym[i] ) return 0;
945 }
946 return 1;
947}
948
drh75897232000-05-29 14:26:00 +0000949/* Construct all successor states to the given state. A "successor"
950** state is any state which can be reached by a shift action.
951*/
icculus9e44cf12010-02-14 17:14:22 +0000952PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000953{
954 struct config *cfp; /* For looping thru the config closure of "stp" */
955 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000956 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000957 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
958 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
959 struct state *newstp; /* A pointer to a successor state */
960
961 /* Each configuration becomes complete after it contibutes to a successor
962 ** state. Initially, all configurations are incomplete */
963 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
964
965 /* Loop through all configurations of the state "stp" */
966 for(cfp=stp->cfp; cfp; cfp=cfp->next){
967 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
968 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
969 Configlist_reset(); /* Reset the new config set */
970 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
971
972 /* For every configuration in the state "stp" which has the symbol "sp"
973 ** following its dot, add the same configuration to the basis set under
974 ** construction but with the dot shifted one symbol to the right. */
975 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
976 if( bcfp->status==COMPLETE ) continue; /* Already used */
977 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
978 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000979 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000980 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000981 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
982 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000983 }
984
985 /* Get a pointer to the state described by the basis configuration set
986 ** constructed in the preceding loop */
987 newstp = getstate(lemp);
988
989 /* The state "newstp" is reached from the state "stp" by a shift action
990 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000991 if( sp->type==MULTITERMINAL ){
992 int i;
993 for(i=0; i<sp->nsubsym; i++){
994 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
995 }
996 }else{
997 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
998 }
drh75897232000-05-29 14:26:00 +0000999 }
1000}
1001
1002/*
1003** Construct the propagation links
1004*/
icculus9e44cf12010-02-14 17:14:22 +00001005void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001006{
1007 int i;
1008 struct config *cfp, *other;
1009 struct state *stp;
1010 struct plink *plp;
1011
1012 /* Housekeeping detail:
1013 ** Add to every propagate link a pointer back to the state to
1014 ** which the link is attached. */
1015 for(i=0; i<lemp->nstate; i++){
1016 stp = lemp->sorted[i];
1017 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1018 cfp->stp = stp;
1019 }
1020 }
1021
1022 /* Convert all backlinks into forward links. Only the forward
1023 ** links are used in the follow-set computation. */
1024 for(i=0; i<lemp->nstate; i++){
1025 stp = lemp->sorted[i];
1026 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1027 for(plp=cfp->bplp; plp; plp=plp->next){
1028 other = plp->cfp;
1029 Plink_add(&other->fplp,cfp);
1030 }
1031 }
1032 }
1033}
1034
1035/* Compute all followsets.
1036**
1037** A followset is the set of all symbols which can come immediately
1038** after a configuration.
1039*/
icculus9e44cf12010-02-14 17:14:22 +00001040void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001041{
1042 int i;
1043 struct config *cfp;
1044 struct plink *plp;
1045 int progress;
1046 int change;
1047
1048 for(i=0; i<lemp->nstate; i++){
1049 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1050 cfp->status = INCOMPLETE;
1051 }
1052 }
1053
1054 do{
1055 progress = 0;
1056 for(i=0; i<lemp->nstate; i++){
1057 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1058 if( cfp->status==COMPLETE ) continue;
1059 for(plp=cfp->fplp; plp; plp=plp->next){
1060 change = SetUnion(plp->cfp->fws,cfp->fws);
1061 if( change ){
1062 plp->cfp->status = INCOMPLETE;
1063 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001064 }
1065 }
drh75897232000-05-29 14:26:00 +00001066 cfp->status = COMPLETE;
1067 }
1068 }
1069 }while( progress );
1070}
1071
drh3cb2f6e2012-01-09 14:19:05 +00001072static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001073
1074/* Compute the reduce actions, and resolve conflicts.
1075*/
icculus9e44cf12010-02-14 17:14:22 +00001076void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001077{
1078 int i,j;
1079 struct config *cfp;
1080 struct state *stp;
1081 struct symbol *sp;
1082 struct rule *rp;
1083
1084 /* Add all of the reduce actions
1085 ** A reduce action is added for each element of the followset of
1086 ** a configuration which has its dot at the extreme right.
1087 */
1088 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1089 stp = lemp->sorted[i];
1090 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1091 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1092 for(j=0; j<lemp->nterminal; j++){
1093 if( SetFind(cfp->fws,j) ){
1094 /* Add a reduce action to the state "stp" which will reduce by the
1095 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001096 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001097 }
drhf2f105d2012-08-20 15:53:54 +00001098 }
drh75897232000-05-29 14:26:00 +00001099 }
1100 }
1101 }
1102
1103 /* Add the accepting token */
1104 if( lemp->start ){
1105 sp = Symbol_find(lemp->start);
1106 if( sp==0 ) sp = lemp->rule->lhs;
1107 }else{
1108 sp = lemp->rule->lhs;
1109 }
1110 /* Add to the first state (which is always the starting state of the
1111 ** finite state machine) an action to ACCEPT if the lookahead is the
1112 ** start nonterminal. */
1113 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1114
1115 /* Resolve conflicts */
1116 for(i=0; i<lemp->nstate; i++){
1117 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001118 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001119 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001120 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001121 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001122 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1123 /* The two actions "ap" and "nap" have the same lookahead.
1124 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001125 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001126 }
1127 }
1128 }
1129
1130 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001131 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001132 for(i=0; i<lemp->nstate; i++){
1133 struct action *ap;
1134 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001135 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001136 }
1137 }
1138 for(rp=lemp->rule; rp; rp=rp->next){
1139 if( rp->canReduce ) continue;
1140 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1141 lemp->errorcnt++;
1142 }
1143}
1144
1145/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001146** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001147**
1148** NO LONGER TRUE:
1149** To resolve a conflict, first look to see if either action
1150** is on an error rule. In that case, take the action which
1151** is not associated with the error rule. If neither or both
1152** actions are associated with an error rule, then try to
1153** use precedence to resolve the conflict.
1154**
1155** If either action is a SHIFT, then it must be apx. This
1156** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1157*/
icculus9e44cf12010-02-14 17:14:22 +00001158static int resolve_conflict(
1159 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001160 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001161){
drh75897232000-05-29 14:26:00 +00001162 struct symbol *spx, *spy;
1163 int errcnt = 0;
1164 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001165 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001166 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001167 errcnt++;
1168 }
drh75897232000-05-29 14:26:00 +00001169 if( apx->type==SHIFT && apy->type==REDUCE ){
1170 spx = apx->sp;
1171 spy = apy->x.rp->precsym;
1172 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1173 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001174 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001175 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001176 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001177 apy->type = RD_RESOLVED;
1178 }else if( spx->prec<spy->prec ){
1179 apx->type = SH_RESOLVED;
1180 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1181 apy->type = RD_RESOLVED; /* associativity */
1182 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1183 apx->type = SH_RESOLVED;
1184 }else{
1185 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001186 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001187 }
1188 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1189 spx = apx->x.rp->precsym;
1190 spy = apy->x.rp->precsym;
1191 if( spx==0 || spy==0 || spx->prec<0 ||
1192 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001193 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001194 errcnt++;
1195 }else if( spx->prec>spy->prec ){
1196 apy->type = RD_RESOLVED;
1197 }else if( spx->prec<spy->prec ){
1198 apx->type = RD_RESOLVED;
1199 }
1200 }else{
drhb59499c2002-02-23 18:45:13 +00001201 assert(
1202 apx->type==SH_RESOLVED ||
1203 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001204 apx->type==SSCONFLICT ||
1205 apx->type==SRCONFLICT ||
1206 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001207 apy->type==SH_RESOLVED ||
1208 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001209 apy->type==SSCONFLICT ||
1210 apy->type==SRCONFLICT ||
1211 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001212 );
1213 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1214 ** REDUCEs on the list. If we reach this point it must be because
1215 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001216 }
1217 return errcnt;
1218}
1219/********************* From the file "configlist.c" *************************/
1220/*
1221** Routines to processing a configuration list and building a state
1222** in the LEMON parser generator.
1223*/
1224
1225static struct config *freelist = 0; /* List of free configurations */
1226static struct config *current = 0; /* Top of list of configurations */
1227static struct config **currentend = 0; /* Last on list of configs */
1228static struct config *basis = 0; /* Top of list of basis configs */
1229static struct config **basisend = 0; /* End of list of basis configs */
1230
1231/* Return a pointer to a new configuration */
1232PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001233 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001234 if( freelist==0 ){
1235 int i;
1236 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001237 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001238 if( freelist==0 ){
1239 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1240 exit(1);
1241 }
1242 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1243 freelist[amt-1].next = 0;
1244 }
icculus9e44cf12010-02-14 17:14:22 +00001245 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001246 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001247 return newcfg;
drh75897232000-05-29 14:26:00 +00001248}
1249
1250/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001251PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001252{
1253 old->next = freelist;
1254 freelist = old;
1255}
1256
1257/* Initialized the configuration list builder */
1258void Configlist_init(){
1259 current = 0;
1260 currentend = &current;
1261 basis = 0;
1262 basisend = &basis;
1263 Configtable_init();
1264 return;
1265}
1266
1267/* Initialized the configuration list builder */
1268void Configlist_reset(){
1269 current = 0;
1270 currentend = &current;
1271 basis = 0;
1272 basisend = &basis;
1273 Configtable_clear(0);
1274 return;
1275}
1276
1277/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001278struct config *Configlist_add(
1279 struct rule *rp, /* The rule */
1280 int dot /* Index into the RHS of the rule where the dot goes */
1281){
drh75897232000-05-29 14:26:00 +00001282 struct config *cfp, model;
1283
1284 assert( currentend!=0 );
1285 model.rp = rp;
1286 model.dot = dot;
1287 cfp = Configtable_find(&model);
1288 if( cfp==0 ){
1289 cfp = newconfig();
1290 cfp->rp = rp;
1291 cfp->dot = dot;
1292 cfp->fws = SetNew();
1293 cfp->stp = 0;
1294 cfp->fplp = cfp->bplp = 0;
1295 cfp->next = 0;
1296 cfp->bp = 0;
1297 *currentend = cfp;
1298 currentend = &cfp->next;
1299 Configtable_insert(cfp);
1300 }
1301 return cfp;
1302}
1303
1304/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001305struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001306{
1307 struct config *cfp, model;
1308
1309 assert( basisend!=0 );
1310 assert( currentend!=0 );
1311 model.rp = rp;
1312 model.dot = dot;
1313 cfp = Configtable_find(&model);
1314 if( cfp==0 ){
1315 cfp = newconfig();
1316 cfp->rp = rp;
1317 cfp->dot = dot;
1318 cfp->fws = SetNew();
1319 cfp->stp = 0;
1320 cfp->fplp = cfp->bplp = 0;
1321 cfp->next = 0;
1322 cfp->bp = 0;
1323 *currentend = cfp;
1324 currentend = &cfp->next;
1325 *basisend = cfp;
1326 basisend = &cfp->bp;
1327 Configtable_insert(cfp);
1328 }
1329 return cfp;
1330}
1331
1332/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001333void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001334{
1335 struct config *cfp, *newcfp;
1336 struct rule *rp, *newrp;
1337 struct symbol *sp, *xsp;
1338 int i, dot;
1339
1340 assert( currentend!=0 );
1341 for(cfp=current; cfp; cfp=cfp->next){
1342 rp = cfp->rp;
1343 dot = cfp->dot;
1344 if( dot>=rp->nrhs ) continue;
1345 sp = rp->rhs[dot];
1346 if( sp->type==NONTERMINAL ){
1347 if( sp->rule==0 && sp!=lemp->errsym ){
1348 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1349 sp->name);
1350 lemp->errorcnt++;
1351 }
1352 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1353 newcfp = Configlist_add(newrp,0);
1354 for(i=dot+1; i<rp->nrhs; i++){
1355 xsp = rp->rhs[i];
1356 if( xsp->type==TERMINAL ){
1357 SetAdd(newcfp->fws,xsp->index);
1358 break;
drhfd405312005-11-06 04:06:59 +00001359 }else if( xsp->type==MULTITERMINAL ){
1360 int k;
1361 for(k=0; k<xsp->nsubsym; k++){
1362 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1363 }
1364 break;
drhf2f105d2012-08-20 15:53:54 +00001365 }else{
drh75897232000-05-29 14:26:00 +00001366 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001367 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001368 }
1369 }
drh75897232000-05-29 14:26:00 +00001370 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1371 }
1372 }
1373 }
1374 return;
1375}
1376
1377/* Sort the configuration list */
1378void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001379 current = (struct config*)msort((char*)current,(char**)&(current->next),
1380 Configcmp);
drh75897232000-05-29 14:26:00 +00001381 currentend = 0;
1382 return;
1383}
1384
1385/* Sort the basis configuration list */
1386void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001387 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1388 Configcmp);
drh75897232000-05-29 14:26:00 +00001389 basisend = 0;
1390 return;
1391}
1392
1393/* Return a pointer to the head of the configuration list and
1394** reset the list */
1395struct config *Configlist_return(){
1396 struct config *old;
1397 old = current;
1398 current = 0;
1399 currentend = 0;
1400 return old;
1401}
1402
1403/* Return a pointer to the head of the configuration list and
1404** reset the list */
1405struct config *Configlist_basis(){
1406 struct config *old;
1407 old = basis;
1408 basis = 0;
1409 basisend = 0;
1410 return old;
1411}
1412
1413/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001414void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001415{
1416 struct config *nextcfp;
1417 for(; cfp; cfp=nextcfp){
1418 nextcfp = cfp->next;
1419 assert( cfp->fplp==0 );
1420 assert( cfp->bplp==0 );
1421 if( cfp->fws ) SetFree(cfp->fws);
1422 deleteconfig(cfp);
1423 }
1424 return;
1425}
1426/***************** From the file "error.c" *********************************/
1427/*
1428** Code for printing error message.
1429*/
1430
drhf9a2e7b2003-04-15 01:49:48 +00001431void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001432 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001433 fprintf(stderr, "%s:%d: ", filename, lineno);
1434 va_start(ap, format);
1435 vfprintf(stderr,format,ap);
1436 va_end(ap);
1437 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001438}
1439/**************** From the file "main.c" ************************************/
1440/*
1441** Main program file for the LEMON parser generator.
1442*/
1443
1444/* Report an out-of-memory condition and abort. This function
1445** is used mostly by the "MemoryCheck" macro in struct.h
1446*/
1447void memory_error(){
1448 fprintf(stderr,"Out of memory. Aborting...\n");
1449 exit(1);
1450}
1451
drh6d08b4d2004-07-20 12:45:22 +00001452static int nDefine = 0; /* Number of -D options on the command line */
1453static char **azDefine = 0; /* Name of the -D macros */
1454
1455/* This routine is called with the argument to each -D command-line option.
1456** Add the macro defined to the azDefine array.
1457*/
1458static void handle_D_option(char *z){
1459 char **paz;
1460 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001461 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001462 if( azDefine==0 ){
1463 fprintf(stderr,"out of memory\n");
1464 exit(1);
1465 }
1466 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001467 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001468 if( *paz==0 ){
1469 fprintf(stderr,"out of memory\n");
1470 exit(1);
1471 }
drh898799f2014-01-10 23:21:00 +00001472 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001473 for(z=*paz; *z && *z!='='; z++){}
1474 *z = 0;
1475}
1476
icculus3e143bd2010-02-14 00:48:49 +00001477static char *user_templatename = NULL;
1478static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001479 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001480 if( user_templatename==0 ){
1481 memory_error();
1482 }
drh898799f2014-01-10 23:21:00 +00001483 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001484}
drh75897232000-05-29 14:26:00 +00001485
drhc75e0162015-09-07 02:23:02 +00001486/* forward reference */
1487static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1488
1489/* Print a single line of the "Parser Stats" output
1490*/
1491static void stats_line(const char *zLabel, int iValue){
1492 int nLabel = lemonStrlen(zLabel);
1493 printf(" %s%.*s %5d\n", zLabel,
1494 35-nLabel, "................................",
1495 iValue);
1496}
1497
drh75897232000-05-29 14:26:00 +00001498/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001499int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001500{
1501 static int version = 0;
1502 static int rpflag = 0;
1503 static int basisflag = 0;
1504 static int compress = 0;
1505 static int quiet = 0;
1506 static int statistics = 0;
1507 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001508 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001509 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001510 static struct s_options options[] = {
1511 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1512 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001513 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001514 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001515 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001516 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001517 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1518 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001519 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001520 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1521 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001522 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001523 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001524 {OPT_FLAG, "s", (char*)&statistics,
1525 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001526 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001527 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1528 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001529 {OPT_FLAG,0,0,0}
1530 };
1531 int i;
icculus42585cf2010-02-14 05:19:56 +00001532 int exitcode;
drh75897232000-05-29 14:26:00 +00001533 struct lemon lem;
1534
drhb0c86772000-06-02 23:21:26 +00001535 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001536 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001537 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001538 exit(0);
1539 }
drhb0c86772000-06-02 23:21:26 +00001540 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001541 fprintf(stderr,"Exactly one filename argument is required.\n");
1542 exit(1);
1543 }
drh954f6b42006-06-13 13:27:46 +00001544 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001545 lem.errorcnt = 0;
1546
1547 /* Initialize the machine */
1548 Strsafe_init();
1549 Symbol_init();
1550 State_init();
1551 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001552 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001553 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001554 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001555 Symbol_new("$");
1556 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001557 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001558
1559 /* Parse the input file */
1560 Parse(&lem);
1561 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001562 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001563 fprintf(stderr,"Empty grammar.\n");
1564 exit(1);
1565 }
1566
1567 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001568 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001569 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001570 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001571 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1572 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1573 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1574 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1575 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1576 lem.nsymbol = i - 1;
drh75897232000-05-29 14:26:00 +00001577 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1578 lem.nterminal = i;
1579
1580 /* Generate a reprint of the grammar, if requested on the command line */
1581 if( rpflag ){
1582 Reprint(&lem);
1583 }else{
1584 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001585 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001586
1587 /* Find the precedence for every production rule (that has one) */
1588 FindRulePrecedences(&lem);
1589
1590 /* Compute the lambda-nonterminals and the first-sets for every
1591 ** nonterminal */
1592 FindFirstSets(&lem);
1593
1594 /* Compute all LR(0) states. Also record follow-set propagation
1595 ** links so that the follow-set can be computed later */
1596 lem.nstate = 0;
1597 FindStates(&lem);
1598 lem.sorted = State_arrayof();
1599
1600 /* Tie up loose ends on the propagation links */
1601 FindLinks(&lem);
1602
1603 /* Compute the follow set of every reducible configuration */
1604 FindFollowSets(&lem);
1605
1606 /* Compute the action tables */
1607 FindActions(&lem);
1608
1609 /* Compress the action tables */
1610 if( compress==0 ) CompressTables(&lem);
1611
drhada354d2005-11-05 15:03:59 +00001612 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001613 ** occur at the end. This is an optimization that helps make the
1614 ** generated parser tables smaller. */
1615 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001616
drh75897232000-05-29 14:26:00 +00001617 /* Generate a report of the parser generated. (the "y.output" file) */
1618 if( !quiet ) ReportOutput(&lem);
1619
1620 /* Generate the source code for the parser */
1621 ReportTable(&lem, mhflag);
1622
1623 /* Produce a header file for use by the scanner. (This step is
1624 ** omitted if the "-m" option is used because makeheaders will
1625 ** generate the file for us.) */
1626 if( !mhflag ) ReportHeader(&lem);
1627 }
1628 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001629 printf("Parser statistics:\n");
1630 stats_line("terminal symbols", lem.nterminal);
1631 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1632 stats_line("total symbols", lem.nsymbol);
1633 stats_line("rules", lem.nrule);
1634 stats_line("states", lem.nstate);
1635 stats_line("conflicts", lem.nconflict);
1636 stats_line("action table entries", lem.nactiontab);
1637 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001638 }
icculus8e158022010-02-16 16:09:03 +00001639 if( lem.nconflict > 0 ){
1640 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001641 }
1642
1643 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001644 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001645 exit(exitcode);
1646 return (exitcode);
drh75897232000-05-29 14:26:00 +00001647}
1648/******************** From the file "msort.c" *******************************/
1649/*
1650** A generic merge-sort program.
1651**
1652** USAGE:
1653** Let "ptr" be a pointer to some structure which is at the head of
1654** a null-terminated list. Then to sort the list call:
1655**
1656** ptr = msort(ptr,&(ptr->next),cmpfnc);
1657**
1658** In the above, "cmpfnc" is a pointer to a function which compares
1659** two instances of the structure and returns an integer, as in
1660** strcmp. The second argument is a pointer to the pointer to the
1661** second element of the linked list. This address is used to compute
1662** the offset to the "next" field within the structure. The offset to
1663** the "next" field must be constant for all structures in the list.
1664**
1665** The function returns a new pointer which is the head of the list
1666** after sorting.
1667**
1668** ALGORITHM:
1669** Merge-sort.
1670*/
1671
1672/*
1673** Return a pointer to the next structure in the linked list.
1674*/
drhd25d6922012-04-18 09:59:56 +00001675#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001676
1677/*
1678** Inputs:
1679** a: A sorted, null-terminated linked list. (May be null).
1680** b: A sorted, null-terminated linked list. (May be null).
1681** cmp: A pointer to the comparison function.
1682** offset: Offset in the structure to the "next" field.
1683**
1684** Return Value:
1685** A pointer to the head of a sorted list containing the elements
1686** of both a and b.
1687**
1688** Side effects:
1689** The "next" pointers for elements in the lists a and b are
1690** changed.
1691*/
drhe9278182007-07-18 18:16:29 +00001692static char *merge(
1693 char *a,
1694 char *b,
1695 int (*cmp)(const char*,const char*),
1696 int offset
1697){
drh75897232000-05-29 14:26:00 +00001698 char *ptr, *head;
1699
1700 if( a==0 ){
1701 head = b;
1702 }else if( b==0 ){
1703 head = a;
1704 }else{
drhe594bc32009-11-03 13:02:25 +00001705 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001706 ptr = a;
1707 a = NEXT(a);
1708 }else{
1709 ptr = b;
1710 b = NEXT(b);
1711 }
1712 head = ptr;
1713 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001714 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001715 NEXT(ptr) = a;
1716 ptr = a;
1717 a = NEXT(a);
1718 }else{
1719 NEXT(ptr) = b;
1720 ptr = b;
1721 b = NEXT(b);
1722 }
1723 }
1724 if( a ) NEXT(ptr) = a;
1725 else NEXT(ptr) = b;
1726 }
1727 return head;
1728}
1729
1730/*
1731** Inputs:
1732** list: Pointer to a singly-linked list of structures.
1733** next: Pointer to pointer to the second element of the list.
1734** cmp: A comparison function.
1735**
1736** Return Value:
1737** A pointer to the head of a sorted list containing the elements
1738** orginally in list.
1739**
1740** Side effects:
1741** The "next" pointers for elements in list are changed.
1742*/
1743#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001744static char *msort(
1745 char *list,
1746 char **next,
1747 int (*cmp)(const char*,const char*)
1748){
drhba99af52001-10-25 20:37:16 +00001749 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001750 char *ep;
1751 char *set[LISTSIZE];
1752 int i;
drh1cc0d112015-03-31 15:15:48 +00001753 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001754 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1755 while( list ){
1756 ep = list;
1757 list = NEXT(list);
1758 NEXT(ep) = 0;
1759 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1760 ep = merge(ep,set[i],cmp,offset);
1761 set[i] = 0;
1762 }
1763 set[i] = ep;
1764 }
1765 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001766 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001767 return ep;
1768}
1769/************************ From the file "option.c" **************************/
1770static char **argv;
1771static struct s_options *op;
1772static FILE *errstream;
1773
1774#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1775
1776/*
1777** Print the command line with a carrot pointing to the k-th character
1778** of the n-th field.
1779*/
icculus9e44cf12010-02-14 17:14:22 +00001780static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001781{
1782 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001783 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001784 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001785 for(i=1; i<n && argv[i]; i++){
1786 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001787 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001788 }
1789 spcnt += k;
1790 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1791 if( spcnt<20 ){
1792 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1793 }else{
1794 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1795 }
1796}
1797
1798/*
1799** Return the index of the N-th non-switch argument. Return -1
1800** if N is out of range.
1801*/
icculus9e44cf12010-02-14 17:14:22 +00001802static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001803{
1804 int i;
1805 int dashdash = 0;
1806 if( argv!=0 && *argv!=0 ){
1807 for(i=1; argv[i]; i++){
1808 if( dashdash || !ISOPT(argv[i]) ){
1809 if( n==0 ) return i;
1810 n--;
1811 }
1812 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1813 }
1814 }
1815 return -1;
1816}
1817
1818static char emsg[] = "Command line syntax error: ";
1819
1820/*
1821** Process a flag command line argument.
1822*/
icculus9e44cf12010-02-14 17:14:22 +00001823static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001824{
1825 int v;
1826 int errcnt = 0;
1827 int j;
1828 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001829 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001830 }
1831 v = argv[i][0]=='-' ? 1 : 0;
1832 if( op[j].label==0 ){
1833 if( err ){
1834 fprintf(err,"%sundefined option.\n",emsg);
1835 errline(i,1,err);
1836 }
1837 errcnt++;
drh0325d392015-01-01 19:11:22 +00001838 }else if( op[j].arg==0 ){
1839 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001840 }else if( op[j].type==OPT_FLAG ){
1841 *((int*)op[j].arg) = v;
1842 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001843 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001844 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001845 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001846 }else{
1847 if( err ){
1848 fprintf(err,"%smissing argument on switch.\n",emsg);
1849 errline(i,1,err);
1850 }
1851 errcnt++;
1852 }
1853 return errcnt;
1854}
1855
1856/*
1857** Process a command line switch which has an argument.
1858*/
icculus9e44cf12010-02-14 17:14:22 +00001859static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001860{
1861 int lv = 0;
1862 double dv = 0.0;
1863 char *sv = 0, *end;
1864 char *cp;
1865 int j;
1866 int errcnt = 0;
1867 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001868 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001869 *cp = 0;
1870 for(j=0; op[j].label; j++){
1871 if( strcmp(argv[i],op[j].label)==0 ) break;
1872 }
1873 *cp = '=';
1874 if( op[j].label==0 ){
1875 if( err ){
1876 fprintf(err,"%sundefined option.\n",emsg);
1877 errline(i,0,err);
1878 }
1879 errcnt++;
1880 }else{
1881 cp++;
1882 switch( op[j].type ){
1883 case OPT_FLAG:
1884 case OPT_FFLAG:
1885 if( err ){
1886 fprintf(err,"%soption requires an argument.\n",emsg);
1887 errline(i,0,err);
1888 }
1889 errcnt++;
1890 break;
1891 case OPT_DBL:
1892 case OPT_FDBL:
1893 dv = strtod(cp,&end);
1894 if( *end ){
1895 if( err ){
drh25473362015-09-04 18:03:45 +00001896 fprintf(err,
1897 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001898 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001899 }
1900 errcnt++;
1901 }
1902 break;
1903 case OPT_INT:
1904 case OPT_FINT:
1905 lv = strtol(cp,&end,0);
1906 if( *end ){
1907 if( err ){
1908 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001909 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001910 }
1911 errcnt++;
1912 }
1913 break;
1914 case OPT_STR:
1915 case OPT_FSTR:
1916 sv = cp;
1917 break;
1918 }
1919 switch( op[j].type ){
1920 case OPT_FLAG:
1921 case OPT_FFLAG:
1922 break;
1923 case OPT_DBL:
1924 *(double*)(op[j].arg) = dv;
1925 break;
1926 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001927 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001928 break;
1929 case OPT_INT:
1930 *(int*)(op[j].arg) = lv;
1931 break;
1932 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001933 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001934 break;
1935 case OPT_STR:
1936 *(char**)(op[j].arg) = sv;
1937 break;
1938 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001939 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001940 break;
1941 }
1942 }
1943 return errcnt;
1944}
1945
icculus9e44cf12010-02-14 17:14:22 +00001946int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001947{
1948 int errcnt = 0;
1949 argv = a;
1950 op = o;
1951 errstream = err;
1952 if( argv && *argv && op ){
1953 int i;
1954 for(i=1; argv[i]; i++){
1955 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1956 errcnt += handleflags(i,err);
1957 }else if( strchr(argv[i],'=') ){
1958 errcnt += handleswitch(i,err);
1959 }
1960 }
1961 }
1962 if( errcnt>0 ){
1963 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001964 OptPrint();
drh75897232000-05-29 14:26:00 +00001965 exit(1);
1966 }
1967 return 0;
1968}
1969
drhb0c86772000-06-02 23:21:26 +00001970int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001971 int cnt = 0;
1972 int dashdash = 0;
1973 int i;
1974 if( argv!=0 && argv[0]!=0 ){
1975 for(i=1; argv[i]; i++){
1976 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1977 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1978 }
1979 }
1980 return cnt;
1981}
1982
icculus9e44cf12010-02-14 17:14:22 +00001983char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001984{
1985 int i;
1986 i = argindex(n);
1987 return i>=0 ? argv[i] : 0;
1988}
1989
icculus9e44cf12010-02-14 17:14:22 +00001990void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001991{
1992 int i;
1993 i = argindex(n);
1994 if( i>=0 ) errline(i,0,errstream);
1995}
1996
drhb0c86772000-06-02 23:21:26 +00001997void OptPrint(){
drh75897232000-05-29 14:26:00 +00001998 int i;
1999 int max, len;
2000 max = 0;
2001 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002002 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002003 switch( op[i].type ){
2004 case OPT_FLAG:
2005 case OPT_FFLAG:
2006 break;
2007 case OPT_INT:
2008 case OPT_FINT:
2009 len += 9; /* length of "<integer>" */
2010 break;
2011 case OPT_DBL:
2012 case OPT_FDBL:
2013 len += 6; /* length of "<real>" */
2014 break;
2015 case OPT_STR:
2016 case OPT_FSTR:
2017 len += 8; /* length of "<string>" */
2018 break;
2019 }
2020 if( len>max ) max = len;
2021 }
2022 for(i=0; op[i].label; i++){
2023 switch( op[i].type ){
2024 case OPT_FLAG:
2025 case OPT_FFLAG:
2026 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2027 break;
2028 case OPT_INT:
2029 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002030 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002031 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002032 break;
2033 case OPT_DBL:
2034 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002035 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002036 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002037 break;
2038 case OPT_STR:
2039 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002040 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002041 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002042 break;
2043 }
2044 }
2045}
2046/*********************** From the file "parse.c" ****************************/
2047/*
2048** Input file parser for the LEMON parser generator.
2049*/
2050
2051/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002052enum e_state {
2053 INITIALIZE,
2054 WAITING_FOR_DECL_OR_RULE,
2055 WAITING_FOR_DECL_KEYWORD,
2056 WAITING_FOR_DECL_ARG,
2057 WAITING_FOR_PRECEDENCE_SYMBOL,
2058 WAITING_FOR_ARROW,
2059 IN_RHS,
2060 LHS_ALIAS_1,
2061 LHS_ALIAS_2,
2062 LHS_ALIAS_3,
2063 RHS_ALIAS_1,
2064 RHS_ALIAS_2,
2065 PRECEDENCE_MARK_1,
2066 PRECEDENCE_MARK_2,
2067 RESYNC_AFTER_RULE_ERROR,
2068 RESYNC_AFTER_DECL_ERROR,
2069 WAITING_FOR_DESTRUCTOR_SYMBOL,
2070 WAITING_FOR_DATATYPE_SYMBOL,
2071 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002072 WAITING_FOR_WILDCARD_ID,
2073 WAITING_FOR_CLASS_ID,
2074 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002075};
drh75897232000-05-29 14:26:00 +00002076struct pstate {
2077 char *filename; /* Name of the input file */
2078 int tokenlineno; /* Linenumber at which current token starts */
2079 int errorcnt; /* Number of errors so far */
2080 char *tokenstart; /* Text of current token */
2081 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002082 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002083 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002084 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002085 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002086 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002087 int nrhs; /* Number of right-hand side symbols seen */
2088 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002089 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002090 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002091 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002092 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002093 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002094 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002095 enum e_assoc declassoc; /* Assign this association to decl arguments */
2096 int preccounter; /* Assign this precedence to decl arguments */
2097 struct rule *firstrule; /* Pointer to first rule in the grammar */
2098 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2099};
2100
2101/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002102static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002103{
icculus9e44cf12010-02-14 17:14:22 +00002104 const char *x;
drh75897232000-05-29 14:26:00 +00002105 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2106#if 0
2107 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2108 x,psp->state);
2109#endif
2110 switch( psp->state ){
2111 case INITIALIZE:
2112 psp->prevrule = 0;
2113 psp->preccounter = 0;
2114 psp->firstrule = psp->lastrule = 0;
2115 psp->gp->nrule = 0;
2116 /* Fall thru to next case */
2117 case WAITING_FOR_DECL_OR_RULE:
2118 if( x[0]=='%' ){
2119 psp->state = WAITING_FOR_DECL_KEYWORD;
2120 }else if( islower(x[0]) ){
2121 psp->lhs = Symbol_new(x);
2122 psp->nrhs = 0;
2123 psp->lhsalias = 0;
2124 psp->state = WAITING_FOR_ARROW;
2125 }else if( x[0]=='{' ){
2126 if( psp->prevrule==0 ){
2127 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002128"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002129fragment which begins on this line.");
2130 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002131 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002132 ErrorMsg(psp->filename,psp->tokenlineno,
2133"Code fragment beginning on this line is not the first \
2134to follow the previous rule.");
2135 psp->errorcnt++;
2136 }else{
2137 psp->prevrule->line = psp->tokenlineno;
2138 psp->prevrule->code = &x[1];
drhf2f105d2012-08-20 15:53:54 +00002139 }
drh75897232000-05-29 14:26:00 +00002140 }else if( x[0]=='[' ){
2141 psp->state = PRECEDENCE_MARK_1;
2142 }else{
2143 ErrorMsg(psp->filename,psp->tokenlineno,
2144 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2145 x);
2146 psp->errorcnt++;
2147 }
2148 break;
2149 case PRECEDENCE_MARK_1:
2150 if( !isupper(x[0]) ){
2151 ErrorMsg(psp->filename,psp->tokenlineno,
2152 "The precedence symbol must be a terminal.");
2153 psp->errorcnt++;
2154 }else if( psp->prevrule==0 ){
2155 ErrorMsg(psp->filename,psp->tokenlineno,
2156 "There is no prior rule to assign precedence \"[%s]\".",x);
2157 psp->errorcnt++;
2158 }else if( psp->prevrule->precsym!=0 ){
2159 ErrorMsg(psp->filename,psp->tokenlineno,
2160"Precedence mark on this line is not the first \
2161to follow the previous rule.");
2162 psp->errorcnt++;
2163 }else{
2164 psp->prevrule->precsym = Symbol_new(x);
2165 }
2166 psp->state = PRECEDENCE_MARK_2;
2167 break;
2168 case PRECEDENCE_MARK_2:
2169 if( x[0]!=']' ){
2170 ErrorMsg(psp->filename,psp->tokenlineno,
2171 "Missing \"]\" on precedence mark.");
2172 psp->errorcnt++;
2173 }
2174 psp->state = WAITING_FOR_DECL_OR_RULE;
2175 break;
2176 case WAITING_FOR_ARROW:
2177 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2178 psp->state = IN_RHS;
2179 }else if( x[0]=='(' ){
2180 psp->state = LHS_ALIAS_1;
2181 }else{
2182 ErrorMsg(psp->filename,psp->tokenlineno,
2183 "Expected to see a \":\" following the LHS symbol \"%s\".",
2184 psp->lhs->name);
2185 psp->errorcnt++;
2186 psp->state = RESYNC_AFTER_RULE_ERROR;
2187 }
2188 break;
2189 case LHS_ALIAS_1:
2190 if( isalpha(x[0]) ){
2191 psp->lhsalias = x;
2192 psp->state = LHS_ALIAS_2;
2193 }else{
2194 ErrorMsg(psp->filename,psp->tokenlineno,
2195 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2196 x,psp->lhs->name);
2197 psp->errorcnt++;
2198 psp->state = RESYNC_AFTER_RULE_ERROR;
2199 }
2200 break;
2201 case LHS_ALIAS_2:
2202 if( x[0]==')' ){
2203 psp->state = LHS_ALIAS_3;
2204 }else{
2205 ErrorMsg(psp->filename,psp->tokenlineno,
2206 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2207 psp->errorcnt++;
2208 psp->state = RESYNC_AFTER_RULE_ERROR;
2209 }
2210 break;
2211 case LHS_ALIAS_3:
2212 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2213 psp->state = IN_RHS;
2214 }else{
2215 ErrorMsg(psp->filename,psp->tokenlineno,
2216 "Missing \"->\" following: \"%s(%s)\".",
2217 psp->lhs->name,psp->lhsalias);
2218 psp->errorcnt++;
2219 psp->state = RESYNC_AFTER_RULE_ERROR;
2220 }
2221 break;
2222 case IN_RHS:
2223 if( x[0]=='.' ){
2224 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002225 rp = (struct rule *)calloc( sizeof(struct rule) +
2226 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002227 if( rp==0 ){
2228 ErrorMsg(psp->filename,psp->tokenlineno,
2229 "Can't allocate enough memory for this rule.");
2230 psp->errorcnt++;
2231 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002232 }else{
drh75897232000-05-29 14:26:00 +00002233 int i;
2234 rp->ruleline = psp->tokenlineno;
2235 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002236 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002237 for(i=0; i<psp->nrhs; i++){
2238 rp->rhs[i] = psp->rhs[i];
2239 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002240 }
drh75897232000-05-29 14:26:00 +00002241 rp->lhs = psp->lhs;
2242 rp->lhsalias = psp->lhsalias;
2243 rp->nrhs = psp->nrhs;
2244 rp->code = 0;
2245 rp->precsym = 0;
2246 rp->index = psp->gp->nrule++;
2247 rp->nextlhs = rp->lhs->rule;
2248 rp->lhs->rule = rp;
2249 rp->next = 0;
2250 if( psp->firstrule==0 ){
2251 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002252 }else{
drh75897232000-05-29 14:26:00 +00002253 psp->lastrule->next = rp;
2254 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002255 }
drh75897232000-05-29 14:26:00 +00002256 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002257 }
drh75897232000-05-29 14:26:00 +00002258 psp->state = WAITING_FOR_DECL_OR_RULE;
2259 }else if( isalpha(x[0]) ){
2260 if( psp->nrhs>=MAXRHS ){
2261 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002262 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002263 x);
2264 psp->errorcnt++;
2265 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002266 }else{
drh75897232000-05-29 14:26:00 +00002267 psp->rhs[psp->nrhs] = Symbol_new(x);
2268 psp->alias[psp->nrhs] = 0;
2269 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002270 }
drhfd405312005-11-06 04:06:59 +00002271 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2272 struct symbol *msp = psp->rhs[psp->nrhs-1];
2273 if( msp->type!=MULTITERMINAL ){
2274 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002275 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002276 memset(msp, 0, sizeof(*msp));
2277 msp->type = MULTITERMINAL;
2278 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002279 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002280 msp->subsym[0] = origsp;
2281 msp->name = origsp->name;
2282 psp->rhs[psp->nrhs-1] = msp;
2283 }
2284 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002285 msp->subsym = (struct symbol **) realloc(msp->subsym,
2286 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002287 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2288 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2289 ErrorMsg(psp->filename,psp->tokenlineno,
2290 "Cannot form a compound containing a non-terminal");
2291 psp->errorcnt++;
2292 }
drh75897232000-05-29 14:26:00 +00002293 }else if( x[0]=='(' && psp->nrhs>0 ){
2294 psp->state = RHS_ALIAS_1;
2295 }else{
2296 ErrorMsg(psp->filename,psp->tokenlineno,
2297 "Illegal character on RHS of rule: \"%s\".",x);
2298 psp->errorcnt++;
2299 psp->state = RESYNC_AFTER_RULE_ERROR;
2300 }
2301 break;
2302 case RHS_ALIAS_1:
2303 if( isalpha(x[0]) ){
2304 psp->alias[psp->nrhs-1] = x;
2305 psp->state = RHS_ALIAS_2;
2306 }else{
2307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2309 x,psp->rhs[psp->nrhs-1]->name);
2310 psp->errorcnt++;
2311 psp->state = RESYNC_AFTER_RULE_ERROR;
2312 }
2313 break;
2314 case RHS_ALIAS_2:
2315 if( x[0]==')' ){
2316 psp->state = IN_RHS;
2317 }else{
2318 ErrorMsg(psp->filename,psp->tokenlineno,
2319 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2320 psp->errorcnt++;
2321 psp->state = RESYNC_AFTER_RULE_ERROR;
2322 }
2323 break;
2324 case WAITING_FOR_DECL_KEYWORD:
2325 if( isalpha(x[0]) ){
2326 psp->declkeyword = x;
2327 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002328 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002329 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002330 psp->state = WAITING_FOR_DECL_ARG;
2331 if( strcmp(x,"name")==0 ){
2332 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002333 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002334 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002335 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002336 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002337 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002338 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002339 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002340 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002341 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002342 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002343 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002344 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002345 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002346 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002347 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002348 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002349 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002350 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002351 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002352 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002353 }else if( strcmp(x,"extra_argument")==0 ){
2354 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002355 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002356 }else if( strcmp(x,"token_type")==0 ){
2357 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002358 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002359 }else if( strcmp(x,"default_type")==0 ){
2360 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002361 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002362 }else if( strcmp(x,"stack_size")==0 ){
2363 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002364 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002365 }else if( strcmp(x,"start_symbol")==0 ){
2366 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002367 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002368 }else if( strcmp(x,"left")==0 ){
2369 psp->preccounter++;
2370 psp->declassoc = LEFT;
2371 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2372 }else if( strcmp(x,"right")==0 ){
2373 psp->preccounter++;
2374 psp->declassoc = RIGHT;
2375 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2376 }else if( strcmp(x,"nonassoc")==0 ){
2377 psp->preccounter++;
2378 psp->declassoc = NONE;
2379 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002380 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002381 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002382 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002383 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002384 }else if( strcmp(x,"fallback")==0 ){
2385 psp->fallback = 0;
2386 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002387 }else if( strcmp(x,"wildcard")==0 ){
2388 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002389 }else if( strcmp(x,"token_class")==0 ){
2390 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002391 }else{
2392 ErrorMsg(psp->filename,psp->tokenlineno,
2393 "Unknown declaration keyword: \"%%%s\".",x);
2394 psp->errorcnt++;
2395 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002396 }
drh75897232000-05-29 14:26:00 +00002397 }else{
2398 ErrorMsg(psp->filename,psp->tokenlineno,
2399 "Illegal declaration keyword: \"%s\".",x);
2400 psp->errorcnt++;
2401 psp->state = RESYNC_AFTER_DECL_ERROR;
2402 }
2403 break;
2404 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2405 if( !isalpha(x[0]) ){
2406 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002407 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002408 psp->errorcnt++;
2409 psp->state = RESYNC_AFTER_DECL_ERROR;
2410 }else{
icculusd286fa62010-03-03 17:06:32 +00002411 struct symbol *sp = Symbol_new(x);
2412 psp->declargslot = &sp->destructor;
2413 psp->decllinenoslot = &sp->destLineno;
2414 psp->insertLineMacro = 1;
2415 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002416 }
2417 break;
2418 case WAITING_FOR_DATATYPE_SYMBOL:
2419 if( !isalpha(x[0]) ){
2420 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002421 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002422 psp->errorcnt++;
2423 psp->state = RESYNC_AFTER_DECL_ERROR;
2424 }else{
icculus866bf1e2010-02-17 20:31:32 +00002425 struct symbol *sp = Symbol_find(x);
2426 if((sp) && (sp->datatype)){
2427 ErrorMsg(psp->filename,psp->tokenlineno,
2428 "Symbol %%type \"%s\" already defined", x);
2429 psp->errorcnt++;
2430 psp->state = RESYNC_AFTER_DECL_ERROR;
2431 }else{
2432 if (!sp){
2433 sp = Symbol_new(x);
2434 }
2435 psp->declargslot = &sp->datatype;
2436 psp->insertLineMacro = 0;
2437 psp->state = WAITING_FOR_DECL_ARG;
2438 }
drh75897232000-05-29 14:26:00 +00002439 }
2440 break;
2441 case WAITING_FOR_PRECEDENCE_SYMBOL:
2442 if( x[0]=='.' ){
2443 psp->state = WAITING_FOR_DECL_OR_RULE;
2444 }else if( isupper(x[0]) ){
2445 struct symbol *sp;
2446 sp = Symbol_new(x);
2447 if( sp->prec>=0 ){
2448 ErrorMsg(psp->filename,psp->tokenlineno,
2449 "Symbol \"%s\" has already be given a precedence.",x);
2450 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002451 }else{
drh75897232000-05-29 14:26:00 +00002452 sp->prec = psp->preccounter;
2453 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002454 }
drh75897232000-05-29 14:26:00 +00002455 }else{
2456 ErrorMsg(psp->filename,psp->tokenlineno,
2457 "Can't assign a precedence to \"%s\".",x);
2458 psp->errorcnt++;
2459 }
2460 break;
2461 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002462 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002463 const char *zOld, *zNew;
2464 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002465 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002466 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002467 char zLine[50];
2468 zNew = x;
2469 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002470 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002471 if( *psp->declargslot ){
2472 zOld = *psp->declargslot;
2473 }else{
2474 zOld = "";
2475 }
drh87cf1372008-08-13 20:09:06 +00002476 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002477 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002478 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002479 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2480 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002481 for(z=psp->filename, nBack=0; *z; z++){
2482 if( *z=='\\' ) nBack++;
2483 }
drh898799f2014-01-10 23:21:00 +00002484 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002485 nLine = lemonStrlen(zLine);
2486 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002487 }
icculus9e44cf12010-02-14 17:14:22 +00002488 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2489 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002490 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002491 if( nOld && zBuf[-1]!='\n' ){
2492 *(zBuf++) = '\n';
2493 }
2494 memcpy(zBuf, zLine, nLine);
2495 zBuf += nLine;
2496 *(zBuf++) = '"';
2497 for(z=psp->filename; *z; z++){
2498 if( *z=='\\' ){
2499 *(zBuf++) = '\\';
2500 }
2501 *(zBuf++) = *z;
2502 }
2503 *(zBuf++) = '"';
2504 *(zBuf++) = '\n';
2505 }
drh4dc8ef52008-07-01 17:13:57 +00002506 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2507 psp->decllinenoslot[0] = psp->tokenlineno;
2508 }
drha5808f32008-04-27 22:19:44 +00002509 memcpy(zBuf, zNew, nNew);
2510 zBuf += nNew;
2511 *zBuf = 0;
2512 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002513 }else{
2514 ErrorMsg(psp->filename,psp->tokenlineno,
2515 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2516 psp->errorcnt++;
2517 psp->state = RESYNC_AFTER_DECL_ERROR;
2518 }
2519 break;
drh0bd1f4e2002-06-06 18:54:39 +00002520 case WAITING_FOR_FALLBACK_ID:
2521 if( x[0]=='.' ){
2522 psp->state = WAITING_FOR_DECL_OR_RULE;
2523 }else if( !isupper(x[0]) ){
2524 ErrorMsg(psp->filename, psp->tokenlineno,
2525 "%%fallback argument \"%s\" should be a token", x);
2526 psp->errorcnt++;
2527 }else{
2528 struct symbol *sp = Symbol_new(x);
2529 if( psp->fallback==0 ){
2530 psp->fallback = sp;
2531 }else if( sp->fallback ){
2532 ErrorMsg(psp->filename, psp->tokenlineno,
2533 "More than one fallback assigned to token %s", x);
2534 psp->errorcnt++;
2535 }else{
2536 sp->fallback = psp->fallback;
2537 psp->gp->has_fallback = 1;
2538 }
2539 }
2540 break;
drhe09daa92006-06-10 13:29:31 +00002541 case WAITING_FOR_WILDCARD_ID:
2542 if( x[0]=='.' ){
2543 psp->state = WAITING_FOR_DECL_OR_RULE;
2544 }else if( !isupper(x[0]) ){
2545 ErrorMsg(psp->filename, psp->tokenlineno,
2546 "%%wildcard argument \"%s\" should be a token", x);
2547 psp->errorcnt++;
2548 }else{
2549 struct symbol *sp = Symbol_new(x);
2550 if( psp->gp->wildcard==0 ){
2551 psp->gp->wildcard = sp;
2552 }else{
2553 ErrorMsg(psp->filename, psp->tokenlineno,
2554 "Extra wildcard to token: %s", x);
2555 psp->errorcnt++;
2556 }
2557 }
2558 break;
drh61f92cd2014-01-11 03:06:18 +00002559 case WAITING_FOR_CLASS_ID:
2560 if( !islower(x[0]) ){
2561 ErrorMsg(psp->filename, psp->tokenlineno,
2562 "%%token_class must be followed by an identifier: ", x);
2563 psp->errorcnt++;
2564 psp->state = RESYNC_AFTER_DECL_ERROR;
2565 }else if( Symbol_find(x) ){
2566 ErrorMsg(psp->filename, psp->tokenlineno,
2567 "Symbol \"%s\" already used", x);
2568 psp->errorcnt++;
2569 psp->state = RESYNC_AFTER_DECL_ERROR;
2570 }else{
2571 psp->tkclass = Symbol_new(x);
2572 psp->tkclass->type = MULTITERMINAL;
2573 psp->state = WAITING_FOR_CLASS_TOKEN;
2574 }
2575 break;
2576 case WAITING_FOR_CLASS_TOKEN:
2577 if( x[0]=='.' ){
2578 psp->state = WAITING_FOR_DECL_OR_RULE;
2579 }else if( isupper(x[0]) || ((x[0]=='|' || x[0]=='/') && isupper(x[1])) ){
2580 struct symbol *msp = psp->tkclass;
2581 msp->nsubsym++;
2582 msp->subsym = (struct symbol **) realloc(msp->subsym,
2583 sizeof(struct symbol*)*msp->nsubsym);
2584 if( !isupper(x[0]) ) x++;
2585 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2586 }else{
2587 ErrorMsg(psp->filename, psp->tokenlineno,
2588 "%%token_class argument \"%s\" should be a token", x);
2589 psp->errorcnt++;
2590 psp->state = RESYNC_AFTER_DECL_ERROR;
2591 }
2592 break;
drh75897232000-05-29 14:26:00 +00002593 case RESYNC_AFTER_RULE_ERROR:
2594/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2595** break; */
2596 case RESYNC_AFTER_DECL_ERROR:
2597 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2598 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2599 break;
2600 }
2601}
2602
drh34ff57b2008-07-14 12:27:51 +00002603/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002604** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2605** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2606** comments them out. Text in between is also commented out as appropriate.
2607*/
danielk1977940fac92005-01-23 22:41:37 +00002608static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002609 int i, j, k, n;
2610 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002611 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002612 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002613 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002614 for(i=0; z[i]; i++){
2615 if( z[i]=='\n' ) lineno++;
2616 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2617 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2618 if( exclude ){
2619 exclude--;
2620 if( exclude==0 ){
2621 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2622 }
2623 }
2624 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2625 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2626 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2627 if( exclude ){
2628 exclude++;
2629 }else{
2630 for(j=i+7; isspace(z[j]); j++){}
2631 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2632 exclude = 1;
2633 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002634 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002635 exclude = 0;
2636 break;
2637 }
2638 }
2639 if( z[i+3]=='n' ) exclude = !exclude;
2640 if( exclude ){
2641 start = i;
2642 start_lineno = lineno;
2643 }
2644 }
2645 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2646 }
2647 }
2648 if( exclude ){
2649 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2650 exit(1);
2651 }
2652}
2653
drh75897232000-05-29 14:26:00 +00002654/* In spite of its name, this function is really a scanner. It read
2655** in the entire input file (all at once) then tokenizes it. Each
2656** token is passed to the function "parseonetoken" which builds all
2657** the appropriate data structures in the global state vector "gp".
2658*/
icculus9e44cf12010-02-14 17:14:22 +00002659void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002660{
2661 struct pstate ps;
2662 FILE *fp;
2663 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002664 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002665 int lineno;
2666 int c;
2667 char *cp, *nextcp;
2668 int startline = 0;
2669
rse38514a92007-09-20 11:34:17 +00002670 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002671 ps.gp = gp;
2672 ps.filename = gp->filename;
2673 ps.errorcnt = 0;
2674 ps.state = INITIALIZE;
2675
2676 /* Begin by reading the input file */
2677 fp = fopen(ps.filename,"rb");
2678 if( fp==0 ){
2679 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2680 gp->errorcnt++;
2681 return;
2682 }
2683 fseek(fp,0,2);
2684 filesize = ftell(fp);
2685 rewind(fp);
2686 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002687 if( filesize>100000000 || filebuf==0 ){
2688 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002689 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002690 fclose(fp);
drh75897232000-05-29 14:26:00 +00002691 return;
2692 }
2693 if( fread(filebuf,1,filesize,fp)!=filesize ){
2694 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2695 filesize);
2696 free(filebuf);
2697 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002698 fclose(fp);
drh75897232000-05-29 14:26:00 +00002699 return;
2700 }
2701 fclose(fp);
2702 filebuf[filesize] = 0;
2703
drh6d08b4d2004-07-20 12:45:22 +00002704 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2705 preprocess_input(filebuf);
2706
drh75897232000-05-29 14:26:00 +00002707 /* Now scan the text of the input file */
2708 lineno = 1;
2709 for(cp=filebuf; (c= *cp)!=0; ){
2710 if( c=='\n' ) lineno++; /* Keep track of the line number */
2711 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2712 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2713 cp+=2;
2714 while( (c= *cp)!=0 && c!='\n' ) cp++;
2715 continue;
2716 }
2717 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2718 cp+=2;
2719 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2720 if( c=='\n' ) lineno++;
2721 cp++;
2722 }
2723 if( c ) cp++;
2724 continue;
2725 }
2726 ps.tokenstart = cp; /* Mark the beginning of the token */
2727 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2728 if( c=='\"' ){ /* String literals */
2729 cp++;
2730 while( (c= *cp)!=0 && c!='\"' ){
2731 if( c=='\n' ) lineno++;
2732 cp++;
2733 }
2734 if( c==0 ){
2735 ErrorMsg(ps.filename,startline,
2736"String starting on this line is not terminated before the end of the file.");
2737 ps.errorcnt++;
2738 nextcp = cp;
2739 }else{
2740 nextcp = cp+1;
2741 }
2742 }else if( c=='{' ){ /* A block of C code */
2743 int level;
2744 cp++;
2745 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2746 if( c=='\n' ) lineno++;
2747 else if( c=='{' ) level++;
2748 else if( c=='}' ) level--;
2749 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2750 int prevc;
2751 cp = &cp[2];
2752 prevc = 0;
2753 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2754 if( c=='\n' ) lineno++;
2755 prevc = c;
2756 cp++;
drhf2f105d2012-08-20 15:53:54 +00002757 }
2758 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002759 cp = &cp[2];
2760 while( (c= *cp)!=0 && c!='\n' ) cp++;
2761 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002762 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002763 int startchar, prevc;
2764 startchar = c;
2765 prevc = 0;
2766 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2767 if( c=='\n' ) lineno++;
2768 if( prevc=='\\' ) prevc = 0;
2769 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002770 }
2771 }
drh75897232000-05-29 14:26:00 +00002772 }
2773 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002774 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002775"C code starting on this line is not terminated before the end of the file.");
2776 ps.errorcnt++;
2777 nextcp = cp;
2778 }else{
2779 nextcp = cp+1;
2780 }
2781 }else if( isalnum(c) ){ /* Identifiers */
2782 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2783 nextcp = cp;
2784 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2785 cp += 3;
2786 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002787 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2788 cp += 2;
2789 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2790 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002791 }else{ /* All other (one character) operators */
2792 cp++;
2793 nextcp = cp;
2794 }
2795 c = *cp;
2796 *cp = 0; /* Null terminate the token */
2797 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002798 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002799 cp = nextcp;
2800 }
2801 free(filebuf); /* Release the buffer after parsing */
2802 gp->rule = ps.firstrule;
2803 gp->errorcnt = ps.errorcnt;
2804}
2805/*************************** From the file "plink.c" *********************/
2806/*
2807** Routines processing configuration follow-set propagation links
2808** in the LEMON parser generator.
2809*/
2810static struct plink *plink_freelist = 0;
2811
2812/* Allocate a new plink */
2813struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002814 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002815
2816 if( plink_freelist==0 ){
2817 int i;
2818 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002819 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002820 if( plink_freelist==0 ){
2821 fprintf(stderr,
2822 "Unable to allocate memory for a new follow-set propagation link.\n");
2823 exit(1);
2824 }
2825 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2826 plink_freelist[amt-1].next = 0;
2827 }
icculus9e44cf12010-02-14 17:14:22 +00002828 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002829 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002830 return newlink;
drh75897232000-05-29 14:26:00 +00002831}
2832
2833/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002834void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002835{
icculus9e44cf12010-02-14 17:14:22 +00002836 struct plink *newlink;
2837 newlink = Plink_new();
2838 newlink->next = *plpp;
2839 *plpp = newlink;
2840 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002841}
2842
2843/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002844void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002845{
2846 struct plink *nextpl;
2847 while( from ){
2848 nextpl = from->next;
2849 from->next = *to;
2850 *to = from;
2851 from = nextpl;
2852 }
2853}
2854
2855/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002856void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002857{
2858 struct plink *nextpl;
2859
2860 while( plp ){
2861 nextpl = plp->next;
2862 plp->next = plink_freelist;
2863 plink_freelist = plp;
2864 plp = nextpl;
2865 }
2866}
2867/*********************** From the file "report.c" **************************/
2868/*
2869** Procedures for generating reports and tables in the LEMON parser generator.
2870*/
2871
2872/* Generate a filename with the given suffix. Space to hold the
2873** name comes from malloc() and must be freed by the calling
2874** function.
2875*/
icculus9e44cf12010-02-14 17:14:22 +00002876PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002877{
2878 char *name;
2879 char *cp;
2880
icculus9e44cf12010-02-14 17:14:22 +00002881 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002882 if( name==0 ){
2883 fprintf(stderr,"Can't allocate space for a filename.\n");
2884 exit(1);
2885 }
drh898799f2014-01-10 23:21:00 +00002886 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002887 cp = strrchr(name,'.');
2888 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002889 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002890 return name;
2891}
2892
2893/* Open a file with a name based on the name of the input file,
2894** but with a different (specified) suffix, and return a pointer
2895** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002896PRIVATE FILE *file_open(
2897 struct lemon *lemp,
2898 const char *suffix,
2899 const char *mode
2900){
drh75897232000-05-29 14:26:00 +00002901 FILE *fp;
2902
2903 if( lemp->outname ) free(lemp->outname);
2904 lemp->outname = file_makename(lemp, suffix);
2905 fp = fopen(lemp->outname,mode);
2906 if( fp==0 && *mode=='w' ){
2907 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2908 lemp->errorcnt++;
2909 return 0;
2910 }
2911 return fp;
2912}
2913
2914/* Duplicate the input file without comments and without actions
2915** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002916void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002917{
2918 struct rule *rp;
2919 struct symbol *sp;
2920 int i, j, maxlen, len, ncolumns, skip;
2921 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2922 maxlen = 10;
2923 for(i=0; i<lemp->nsymbol; i++){
2924 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002925 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002926 if( len>maxlen ) maxlen = len;
2927 }
2928 ncolumns = 76/(maxlen+5);
2929 if( ncolumns<1 ) ncolumns = 1;
2930 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2931 for(i=0; i<skip; i++){
2932 printf("//");
2933 for(j=i; j<lemp->nsymbol; j+=skip){
2934 sp = lemp->symbols[j];
2935 assert( sp->index==j );
2936 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2937 }
2938 printf("\n");
2939 }
2940 for(rp=lemp->rule; rp; rp=rp->next){
2941 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002942 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002943 printf(" ::=");
2944 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002945 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002946 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002947 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002948 for(j=1; j<sp->nsubsym; j++){
2949 printf("|%s", sp->subsym[j]->name);
2950 }
drh61f92cd2014-01-11 03:06:18 +00002951 }else{
2952 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002953 }
2954 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002955 }
2956 printf(".");
2957 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002958 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002959 printf("\n");
2960 }
2961}
2962
icculus9e44cf12010-02-14 17:14:22 +00002963void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002964{
2965 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002966 struct symbol *sp;
2967 int i, j;
drh75897232000-05-29 14:26:00 +00002968 rp = cfp->rp;
2969 fprintf(fp,"%s ::=",rp->lhs->name);
2970 for(i=0; i<=rp->nrhs; i++){
2971 if( i==cfp->dot ) fprintf(fp," *");
2972 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002973 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002974 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002975 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002976 for(j=1; j<sp->nsubsym; j++){
2977 fprintf(fp,"|%s",sp->subsym[j]->name);
2978 }
drh61f92cd2014-01-11 03:06:18 +00002979 }else{
2980 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002981 }
drh75897232000-05-29 14:26:00 +00002982 }
2983}
2984
2985/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002986#if 0
drh75897232000-05-29 14:26:00 +00002987/* Print a set */
2988PRIVATE void SetPrint(out,set,lemp)
2989FILE *out;
2990char *set;
2991struct lemon *lemp;
2992{
2993 int i;
2994 char *spacer;
2995 spacer = "";
2996 fprintf(out,"%12s[","");
2997 for(i=0; i<lemp->nterminal; i++){
2998 if( SetFind(set,i) ){
2999 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3000 spacer = " ";
3001 }
3002 }
3003 fprintf(out,"]\n");
3004}
3005
3006/* Print a plink chain */
3007PRIVATE void PlinkPrint(out,plp,tag)
3008FILE *out;
3009struct plink *plp;
3010char *tag;
3011{
3012 while( plp ){
drhada354d2005-11-05 15:03:59 +00003013 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003014 ConfigPrint(out,plp->cfp);
3015 fprintf(out,"\n");
3016 plp = plp->next;
3017 }
3018}
3019#endif
3020
3021/* Print an action to the given file descriptor. Return FALSE if
3022** nothing was actually printed.
3023*/
3024int PrintAction(struct action *ap, FILE *fp, int indent){
3025 int result = 1;
3026 switch( ap->type ){
3027 case SHIFT:
drhada354d2005-11-05 15:03:59 +00003028 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00003029 break;
3030 case REDUCE:
3031 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
3032 break;
3033 case ACCEPT:
3034 fprintf(fp,"%*s accept",indent,ap->sp->name);
3035 break;
3036 case ERROR:
3037 fprintf(fp,"%*s error",indent,ap->sp->name);
3038 break;
drh9892c5d2007-12-21 00:02:11 +00003039 case SRCONFLICT:
3040 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00003041 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
3042 indent,ap->sp->name,ap->x.rp->index);
3043 break;
drh9892c5d2007-12-21 00:02:11 +00003044 case SSCONFLICT:
drhdd7e9db2010-07-19 01:52:07 +00003045 fprintf(fp,"%*s shift %-3d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003046 indent,ap->sp->name,ap->x.stp->statenum);
3047 break;
drh75897232000-05-29 14:26:00 +00003048 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003049 if( showPrecedenceConflict ){
drhdd7e9db2010-07-19 01:52:07 +00003050 fprintf(fp,"%*s shift %-3d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003051 indent,ap->sp->name,ap->x.stp->statenum);
3052 }else{
3053 result = 0;
3054 }
3055 break;
drh75897232000-05-29 14:26:00 +00003056 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003057 if( showPrecedenceConflict ){
drhdd7e9db2010-07-19 01:52:07 +00003058 fprintf(fp,"%*s reduce %-3d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003059 indent,ap->sp->name,ap->x.rp->index);
3060 }else{
3061 result = 0;
3062 }
3063 break;
drh75897232000-05-29 14:26:00 +00003064 case NOT_USED:
3065 result = 0;
3066 break;
3067 }
3068 return result;
3069}
3070
3071/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00003072void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003073{
3074 int i;
3075 struct state *stp;
3076 struct config *cfp;
3077 struct action *ap;
3078 FILE *fp;
3079
drh2aa6ca42004-09-10 00:14:04 +00003080 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003081 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00003082 for(i=0; i<lemp->nstate; i++){
3083 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003084 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003085 if( lemp->basisflag ) cfp=stp->bp;
3086 else cfp=stp->cfp;
3087 while( cfp ){
3088 char buf[20];
3089 if( cfp->dot==cfp->rp->nrhs ){
drh898799f2014-01-10 23:21:00 +00003090 lemon_sprintf(buf,"(%d)",cfp->rp->index);
drh75897232000-05-29 14:26:00 +00003091 fprintf(fp," %5s ",buf);
3092 }else{
3093 fprintf(fp," ");
3094 }
3095 ConfigPrint(fp,cfp);
3096 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003097#if 0
drh75897232000-05-29 14:26:00 +00003098 SetPrint(fp,cfp->fws,lemp);
3099 PlinkPrint(fp,cfp->fplp,"To ");
3100 PlinkPrint(fp,cfp->bplp,"From");
3101#endif
3102 if( lemp->basisflag ) cfp=cfp->bp;
3103 else cfp=cfp->next;
3104 }
3105 fprintf(fp,"\n");
3106 for(ap=stp->ap; ap; ap=ap->next){
3107 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3108 }
3109 fprintf(fp,"\n");
3110 }
drhe9278182007-07-18 18:16:29 +00003111 fprintf(fp, "----------------------------------------------------\n");
3112 fprintf(fp, "Symbols:\n");
3113 for(i=0; i<lemp->nsymbol; i++){
3114 int j;
3115 struct symbol *sp;
3116
3117 sp = lemp->symbols[i];
3118 fprintf(fp, " %3d: %s", i, sp->name);
3119 if( sp->type==NONTERMINAL ){
3120 fprintf(fp, ":");
3121 if( sp->lambda ){
3122 fprintf(fp, " <lambda>");
3123 }
3124 for(j=0; j<lemp->nterminal; j++){
3125 if( sp->firstset && SetFind(sp->firstset, j) ){
3126 fprintf(fp, " %s", lemp->symbols[j]->name);
3127 }
3128 }
3129 }
3130 fprintf(fp, "\n");
3131 }
drh75897232000-05-29 14:26:00 +00003132 fclose(fp);
3133 return;
3134}
3135
3136/* Search for the file "name" which is in the same directory as
3137** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003138PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003139{
icculus9e44cf12010-02-14 17:14:22 +00003140 const char *pathlist;
3141 char *pathbufptr;
3142 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003143 char *path,*cp;
3144 char c;
drh75897232000-05-29 14:26:00 +00003145
3146#ifdef __WIN32__
3147 cp = strrchr(argv0,'\\');
3148#else
3149 cp = strrchr(argv0,'/');
3150#endif
3151 if( cp ){
3152 c = *cp;
3153 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003154 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003155 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003156 *cp = c;
3157 }else{
drh75897232000-05-29 14:26:00 +00003158 pathlist = getenv("PATH");
3159 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003160 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003161 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003162 if( (pathbuf != 0) && (path!=0) ){
3163 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003164 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003165 while( *pathbuf ){
3166 cp = strchr(pathbuf,':');
3167 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003168 c = *cp;
3169 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003170 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003171 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003172 if( c==0 ) pathbuf[0] = 0;
3173 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003174 if( access(path,modemask)==0 ) break;
3175 }
icculus9e44cf12010-02-14 17:14:22 +00003176 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003177 }
3178 }
3179 return path;
3180}
3181
3182/* Given an action, compute the integer value for that action
3183** which is to be put in the action table of the generated machine.
3184** Return negative if no action should be generated.
3185*/
icculus9e44cf12010-02-14 17:14:22 +00003186PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003187{
3188 int act;
3189 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003190 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003191 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3192 case ERROR: act = lemp->nstate + lemp->nrule; break;
3193 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3194 default: act = -1; break;
3195 }
3196 return act;
3197}
3198
3199#define LINESIZE 1000
3200/* The next cluster of routines are for reading the template file
3201** and writing the results to the generated parser */
3202/* The first function transfers data from "in" to "out" until
3203** a line is seen which begins with "%%". The line number is
3204** tracked.
3205**
3206** if name!=0, then any word that begin with "Parse" is changed to
3207** begin with *name instead.
3208*/
icculus9e44cf12010-02-14 17:14:22 +00003209PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003210{
3211 int i, iStart;
3212 char line[LINESIZE];
3213 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3214 (*lineno)++;
3215 iStart = 0;
3216 if( name ){
3217 for(i=0; line[i]; i++){
3218 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3219 && (i==0 || !isalpha(line[i-1]))
3220 ){
3221 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3222 fprintf(out,"%s",name);
3223 i += 4;
3224 iStart = i+1;
3225 }
3226 }
3227 }
3228 fprintf(out,"%s",&line[iStart]);
3229 }
3230}
3231
3232/* The next function finds the template file and opens it, returning
3233** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003234PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003235{
3236 static char templatename[] = "lempar.c";
3237 char buf[1000];
3238 FILE *in;
3239 char *tpltname;
3240 char *cp;
3241
icculus3e143bd2010-02-14 00:48:49 +00003242 /* first, see if user specified a template filename on the command line. */
3243 if (user_templatename != 0) {
3244 if( access(user_templatename,004)==-1 ){
3245 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3246 user_templatename);
3247 lemp->errorcnt++;
3248 return 0;
3249 }
3250 in = fopen(user_templatename,"rb");
3251 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003252 fprintf(stderr,"Can't open the template file \"%s\".\n",
3253 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003254 lemp->errorcnt++;
3255 return 0;
3256 }
3257 return in;
3258 }
3259
drh75897232000-05-29 14:26:00 +00003260 cp = strrchr(lemp->filename,'.');
3261 if( cp ){
drh898799f2014-01-10 23:21:00 +00003262 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003263 }else{
drh898799f2014-01-10 23:21:00 +00003264 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003265 }
3266 if( access(buf,004)==0 ){
3267 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003268 }else if( access(templatename,004)==0 ){
3269 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003270 }else{
3271 tpltname = pathsearch(lemp->argv0,templatename,0);
3272 }
3273 if( tpltname==0 ){
3274 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3275 templatename);
3276 lemp->errorcnt++;
3277 return 0;
3278 }
drh2aa6ca42004-09-10 00:14:04 +00003279 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003280 if( in==0 ){
3281 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3282 lemp->errorcnt++;
3283 return 0;
3284 }
3285 return in;
3286}
3287
drhaf805ca2004-09-07 11:28:25 +00003288/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003289PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003290{
3291 fprintf(out,"#line %d \"",lineno);
3292 while( *filename ){
3293 if( *filename == '\\' ) putc('\\',out);
3294 putc(*filename,out);
3295 filename++;
3296 }
3297 fprintf(out,"\"\n");
3298}
3299
drh75897232000-05-29 14:26:00 +00003300/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003301PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003302{
3303 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003304 while( *str ){
drh75897232000-05-29 14:26:00 +00003305 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003306 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003307 str++;
3308 }
drh9db55df2004-09-09 14:01:21 +00003309 if( str[-1]!='\n' ){
3310 putc('\n',out);
3311 (*lineno)++;
3312 }
shane58543932008-12-10 20:10:04 +00003313 if (!lemp->nolinenosflag) {
3314 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3315 }
drh75897232000-05-29 14:26:00 +00003316 return;
3317}
3318
3319/*
3320** The following routine emits code for the destructor for the
3321** symbol sp
3322*/
icculus9e44cf12010-02-14 17:14:22 +00003323void emit_destructor_code(
3324 FILE *out,
3325 struct symbol *sp,
3326 struct lemon *lemp,
3327 int *lineno
3328){
drhcc83b6e2004-04-23 23:38:42 +00003329 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003330
drh75897232000-05-29 14:26:00 +00003331 if( sp->type==TERMINAL ){
3332 cp = lemp->tokendest;
3333 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003334 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003335 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003336 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003337 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003338 if( !lemp->nolinenosflag ){
3339 (*lineno)++;
3340 tplt_linedir(out,sp->destLineno,lemp->filename);
3341 }
drh960e8c62001-04-03 16:53:21 +00003342 }else if( lemp->vardest ){
3343 cp = lemp->vardest;
3344 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003345 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003346 }else{
3347 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003348 }
3349 for(; *cp; cp++){
3350 if( *cp=='$' && cp[1]=='$' ){
3351 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3352 cp++;
3353 continue;
3354 }
shane58543932008-12-10 20:10:04 +00003355 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003356 fputc(*cp,out);
3357 }
shane58543932008-12-10 20:10:04 +00003358 fprintf(out,"\n"); (*lineno)++;
3359 if (!lemp->nolinenosflag) {
3360 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3361 }
3362 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003363 return;
3364}
3365
3366/*
drh960e8c62001-04-03 16:53:21 +00003367** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003368*/
icculus9e44cf12010-02-14 17:14:22 +00003369int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003370{
3371 int ret;
3372 if( sp->type==TERMINAL ){
3373 ret = lemp->tokendest!=0;
3374 }else{
drh960e8c62001-04-03 16:53:21 +00003375 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003376 }
3377 return ret;
3378}
3379
drh0bb132b2004-07-20 14:06:51 +00003380/*
3381** Append text to a dynamically allocated string. If zText is 0 then
3382** reset the string to be empty again. Always return the complete text
3383** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003384**
3385** n bytes of zText are stored. If n==0 then all of zText up to the first
3386** \000 terminator is stored. zText can contain up to two instances of
3387** %d. The values of p1 and p2 are written into the first and second
3388** %d.
3389**
3390** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003391*/
icculus9e44cf12010-02-14 17:14:22 +00003392PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3393 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003394 static char *z = 0;
3395 static int alloced = 0;
3396 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003397 int c;
drh0bb132b2004-07-20 14:06:51 +00003398 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003399 if( zText==0 ){
3400 used = 0;
3401 return z;
3402 }
drh7ac25c72004-08-19 15:12:26 +00003403 if( n<=0 ){
3404 if( n<0 ){
3405 used += n;
3406 assert( used>=0 );
3407 }
drh87cf1372008-08-13 20:09:06 +00003408 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003409 }
drhdf609712010-11-23 20:55:27 +00003410 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003411 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003412 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003413 }
icculus9e44cf12010-02-14 17:14:22 +00003414 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003415 while( n-- > 0 ){
3416 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003417 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003418 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003419 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003420 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003421 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003422 zText++;
3423 n--;
3424 }else{
mistachkin2318d332015-01-12 18:02:52 +00003425 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003426 }
3427 }
3428 z[used] = 0;
3429 return z;
3430}
3431
3432/*
3433** zCode is a string that is the action associated with a rule. Expand
3434** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003435** stack.
drh0bb132b2004-07-20 14:06:51 +00003436*/
drhaf805ca2004-09-07 11:28:25 +00003437PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003438 char *cp, *xp;
3439 int i;
3440 char lhsused = 0; /* True if the LHS element has been used */
3441 char used[MAXRHS]; /* True for each RHS element which is used */
3442
3443 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3444 lhsused = 0;
3445
drh19c9e562007-03-29 20:13:53 +00003446 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003447 static char newlinestr[2] = { '\n', '\0' };
3448 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003449 rp->line = rp->ruleline;
3450 }
3451
drh0bb132b2004-07-20 14:06:51 +00003452 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003453
3454 /* This const cast is wrong but harmless, if we're careful. */
3455 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003456 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3457 char saved;
3458 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3459 saved = *xp;
3460 *xp = 0;
3461 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003462 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003463 cp = xp;
3464 lhsused = 1;
3465 }else{
3466 for(i=0; i<rp->nrhs; i++){
3467 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003468 if( cp!=rp->code && cp[-1]=='@' ){
3469 /* If the argument is of the form @X then substituted
3470 ** the token number of X, not the value of X */
3471 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3472 }else{
drhfd405312005-11-06 04:06:59 +00003473 struct symbol *sp = rp->rhs[i];
3474 int dtnum;
3475 if( sp->type==MULTITERMINAL ){
3476 dtnum = sp->subsym[0]->dtnum;
3477 }else{
3478 dtnum = sp->dtnum;
3479 }
3480 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003481 }
drh0bb132b2004-07-20 14:06:51 +00003482 cp = xp;
3483 used[i] = 1;
3484 break;
3485 }
3486 }
3487 }
3488 *xp = saved;
3489 }
3490 append_str(cp, 1, 0, 0);
3491 } /* End loop */
3492
3493 /* Check to make sure the LHS has been used */
3494 if( rp->lhsalias && !lhsused ){
3495 ErrorMsg(lemp->filename,rp->ruleline,
3496 "Label \"%s\" for \"%s(%s)\" is never used.",
3497 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3498 lemp->errorcnt++;
3499 }
3500
3501 /* Generate destructor code for RHS symbols which are not used in the
3502 ** reduce code */
3503 for(i=0; i<rp->nrhs; i++){
3504 if( rp->rhsalias[i] && !used[i] ){
3505 ErrorMsg(lemp->filename,rp->ruleline,
3506 "Label %s for \"%s(%s)\" is never used.",
3507 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3508 lemp->errorcnt++;
3509 }else if( rp->rhsalias[i]==0 ){
3510 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003511 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003512 rp->rhs[i]->index,i-rp->nrhs+1);
3513 }else{
3514 /* No destructor defined for this term */
3515 }
3516 }
3517 }
drh61e339a2007-01-16 03:09:02 +00003518 if( rp->code ){
3519 cp = append_str(0,0,0,0);
3520 rp->code = Strsafe(cp?cp:"");
3521 }
drh0bb132b2004-07-20 14:06:51 +00003522}
3523
drh75897232000-05-29 14:26:00 +00003524/*
3525** Generate code which executes when the rule "rp" is reduced. Write
3526** the code to "out". Make sure lineno stays up-to-date.
3527*/
icculus9e44cf12010-02-14 17:14:22 +00003528PRIVATE void emit_code(
3529 FILE *out,
3530 struct rule *rp,
3531 struct lemon *lemp,
3532 int *lineno
3533){
3534 const char *cp;
drh75897232000-05-29 14:26:00 +00003535
3536 /* Generate code to do the reduce action */
3537 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003538 if( !lemp->nolinenosflag ){
3539 (*lineno)++;
3540 tplt_linedir(out,rp->line,lemp->filename);
3541 }
drhaf805ca2004-09-07 11:28:25 +00003542 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003543 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003544 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003545 } /* End loop */
shane58543932008-12-10 20:10:04 +00003546 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003547 if( !lemp->nolinenosflag ){
3548 (*lineno)++;
3549 tplt_linedir(out,*lineno,lemp->outname);
3550 }
drh75897232000-05-29 14:26:00 +00003551 } /* End if( rp->code ) */
3552
drh75897232000-05-29 14:26:00 +00003553 return;
3554}
3555
3556/*
3557** Print the definition of the union used for the parser's data stack.
3558** This union contains fields for every possible data type for tokens
3559** and nonterminals. In the process of computing and printing this
3560** union, also set the ".dtnum" field of every terminal and nonterminal
3561** symbol.
3562*/
icculus9e44cf12010-02-14 17:14:22 +00003563void print_stack_union(
3564 FILE *out, /* The output stream */
3565 struct lemon *lemp, /* The main info structure for this parser */
3566 int *plineno, /* Pointer to the line number */
3567 int mhflag /* True if generating makeheaders output */
3568){
drh75897232000-05-29 14:26:00 +00003569 int lineno = *plineno; /* The line number of the output */
3570 char **types; /* A hash table of datatypes */
3571 int arraysize; /* Size of the "types" array */
3572 int maxdtlength; /* Maximum length of any ".datatype" field. */
3573 char *stddt; /* Standardized name for a datatype */
3574 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003575 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003576 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003577
3578 /* Allocate and initialize types[] and allocate stddt[] */
3579 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003580 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003581 if( types==0 ){
3582 fprintf(stderr,"Out of memory.\n");
3583 exit(1);
3584 }
drh75897232000-05-29 14:26:00 +00003585 for(i=0; i<arraysize; i++) types[i] = 0;
3586 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003587 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003588 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003589 }
drh75897232000-05-29 14:26:00 +00003590 for(i=0; i<lemp->nsymbol; i++){
3591 int len;
3592 struct symbol *sp = lemp->symbols[i];
3593 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003594 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003595 if( len>maxdtlength ) maxdtlength = len;
3596 }
3597 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003598 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003599 fprintf(stderr,"Out of memory.\n");
3600 exit(1);
3601 }
3602
3603 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3604 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003605 ** used for terminal symbols. If there is no %default_type defined then
3606 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3607 ** a datatype using the %type directive.
3608 */
drh75897232000-05-29 14:26:00 +00003609 for(i=0; i<lemp->nsymbol; i++){
3610 struct symbol *sp = lemp->symbols[i];
3611 char *cp;
3612 if( sp==lemp->errsym ){
3613 sp->dtnum = arraysize+1;
3614 continue;
3615 }
drh960e8c62001-04-03 16:53:21 +00003616 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003617 sp->dtnum = 0;
3618 continue;
3619 }
3620 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003621 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003622 j = 0;
3623 while( isspace(*cp) ) cp++;
3624 while( *cp ) stddt[j++] = *cp++;
3625 while( j>0 && isspace(stddt[j-1]) ) j--;
3626 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003627 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003628 sp->dtnum = 0;
3629 continue;
3630 }
drh75897232000-05-29 14:26:00 +00003631 hash = 0;
3632 for(j=0; stddt[j]; j++){
3633 hash = hash*53 + stddt[j];
3634 }
drh3b2129c2003-05-13 00:34:21 +00003635 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003636 while( types[hash] ){
3637 if( strcmp(types[hash],stddt)==0 ){
3638 sp->dtnum = hash + 1;
3639 break;
3640 }
3641 hash++;
drh2b51f212013-10-11 23:01:02 +00003642 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003643 }
3644 if( types[hash]==0 ){
3645 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003646 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003647 if( types[hash]==0 ){
3648 fprintf(stderr,"Out of memory.\n");
3649 exit(1);
3650 }
drh898799f2014-01-10 23:21:00 +00003651 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003652 }
3653 }
3654
3655 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3656 name = lemp->name ? lemp->name : "Parse";
3657 lineno = *plineno;
3658 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3659 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3660 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3661 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3662 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003663 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003664 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3665 for(i=0; i<arraysize; i++){
3666 if( types[i]==0 ) continue;
3667 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3668 free(types[i]);
3669 }
drhc4dd3fd2008-01-22 01:48:05 +00003670 if( lemp->errsym->useCnt ){
3671 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3672 }
drh75897232000-05-29 14:26:00 +00003673 free(stddt);
3674 free(types);
3675 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3676 *plineno = lineno;
3677}
3678
drhb29b0a52002-02-23 19:39:46 +00003679/*
3680** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003681** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3682** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003683*/
drhc75e0162015-09-07 02:23:02 +00003684static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3685 const char *zType = "int";
3686 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003687 if( lwr>=0 ){
3688 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003689 zType = "unsigned char";
3690 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003691 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003692 zType = "unsigned short int";
3693 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003694 }else{
drhc75e0162015-09-07 02:23:02 +00003695 zType = "unsigned int";
3696 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003697 }
3698 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003699 zType = "signed char";
3700 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003701 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003702 zType = "short";
3703 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003704 }
drhc75e0162015-09-07 02:23:02 +00003705 if( pnByte ) *pnByte = nByte;
3706 return zType;
drhb29b0a52002-02-23 19:39:46 +00003707}
3708
drhfdbf9282003-10-21 16:34:41 +00003709/*
3710** Each state contains a set of token transaction and a set of
3711** nonterminal transactions. Each of these sets makes an instance
3712** of the following structure. An array of these structures is used
3713** to order the creation of entries in the yy_action[] table.
3714*/
3715struct axset {
3716 struct state *stp; /* A pointer to a state */
3717 int isTkn; /* True to use tokens. False for non-terminals */
3718 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003719 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003720};
3721
3722/*
3723** Compare to axset structures for sorting purposes
3724*/
3725static int axset_compare(const void *a, const void *b){
3726 struct axset *p1 = (struct axset*)a;
3727 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003728 int c;
3729 c = p2->nAction - p1->nAction;
3730 if( c==0 ){
3731 c = p2->iOrder - p1->iOrder;
3732 }
3733 assert( c!=0 || p1==p2 );
3734 return c;
drhfdbf9282003-10-21 16:34:41 +00003735}
3736
drhc4dd3fd2008-01-22 01:48:05 +00003737/*
3738** Write text on "out" that describes the rule "rp".
3739*/
3740static void writeRuleText(FILE *out, struct rule *rp){
3741 int j;
3742 fprintf(out,"%s ::=", rp->lhs->name);
3743 for(j=0; j<rp->nrhs; j++){
3744 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003745 if( sp->type!=MULTITERMINAL ){
3746 fprintf(out," %s", sp->name);
3747 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003748 int k;
drh61f92cd2014-01-11 03:06:18 +00003749 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003750 for(k=1; k<sp->nsubsym; k++){
3751 fprintf(out,"|%s",sp->subsym[k]->name);
3752 }
3753 }
3754 }
3755}
3756
3757
drh75897232000-05-29 14:26:00 +00003758/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003759void ReportTable(
3760 struct lemon *lemp,
3761 int mhflag /* Output in makeheaders format if true */
3762){
drh75897232000-05-29 14:26:00 +00003763 FILE *out, *in;
3764 char line[LINESIZE];
3765 int lineno;
3766 struct state *stp;
3767 struct action *ap;
3768 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003769 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003770 int i, j, n, sz;
3771 int szActionType; /* sizeof(YYACTIONTYPE) */
3772 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003773 const char *name;
drh8b582012003-10-21 13:16:03 +00003774 int mnTknOfst, mxTknOfst;
3775 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003776 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003777
3778 in = tplt_open(lemp);
3779 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003780 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003781 if( out==0 ){
3782 fclose(in);
3783 return;
3784 }
3785 lineno = 1;
3786 tplt_xfer(lemp->name,in,out,&lineno);
3787
3788 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003789 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003790 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00003791 char *incName = file_makename(lemp, ".h");
3792 fprintf(out,"#include \"%s\"\n", incName); lineno++;
3793 free(incName);
drh75897232000-05-29 14:26:00 +00003794 }
3795 tplt_xfer(lemp->name,in,out,&lineno);
3796
3797 /* Generate #defines for all tokens */
3798 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003799 const char *prefix;
drh75897232000-05-29 14:26:00 +00003800 fprintf(out,"#if INTERFACE\n"); lineno++;
3801 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3802 else prefix = "";
3803 for(i=1; i<lemp->nterminal; i++){
3804 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3805 lineno++;
3806 }
3807 fprintf(out,"#endif\n"); lineno++;
3808 }
3809 tplt_xfer(lemp->name,in,out,&lineno);
3810
3811 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003812 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00003813 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00003814 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3815 fprintf(out,"#define YYACTIONTYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00003816 minimum_size_type(0, lemp->nstate+lemp->nrule+5, &szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003817 if( lemp->wildcard ){
3818 fprintf(out,"#define YYWILDCARD %d\n",
3819 lemp->wildcard->index); lineno++;
3820 }
drh75897232000-05-29 14:26:00 +00003821 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003822 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003823 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003824 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3825 }else{
3826 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3827 }
drhca44b5a2007-02-22 23:06:58 +00003828 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003829 if( mhflag ){
3830 fprintf(out,"#if INTERFACE\n"); lineno++;
3831 }
3832 name = lemp->name ? lemp->name : "Parse";
3833 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00003834 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003835 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3836 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003837 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3838 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3839 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3840 name,lemp->arg,&lemp->arg[i]); lineno++;
3841 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3842 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003843 }else{
drh1f245e42002-03-11 13:55:50 +00003844 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3845 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3846 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3847 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003848 }
3849 if( mhflag ){
3850 fprintf(out,"#endif\n"); lineno++;
3851 }
3852 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3853 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003854 if( lemp->errsym->useCnt ){
3855 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3856 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3857 }
drh0bd1f4e2002-06-06 18:54:39 +00003858 if( lemp->has_fallback ){
3859 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3860 }
drh75897232000-05-29 14:26:00 +00003861 tplt_xfer(lemp->name,in,out,&lineno);
3862
drh8b582012003-10-21 13:16:03 +00003863 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003864 **
drh8b582012003-10-21 13:16:03 +00003865 ** yy_action[] A single table containing all actions.
3866 ** yy_lookahead[] A table containing the lookahead for each entry in
3867 ** yy_action. Used to detect hash collisions.
3868 ** yy_shift_ofst[] For each state, the offset into yy_action for
3869 ** shifting terminals.
3870 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3871 ** shifting non-terminals after a reduce.
3872 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003873 */
drh75897232000-05-29 14:26:00 +00003874
drh8b582012003-10-21 13:16:03 +00003875 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003876 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003877 if( ax==0 ){
3878 fprintf(stderr,"malloc failed\n");
3879 exit(1);
3880 }
drh75897232000-05-29 14:26:00 +00003881 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003882 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003883 ax[i*2].stp = stp;
3884 ax[i*2].isTkn = 1;
3885 ax[i*2].nAction = stp->nTknAct;
3886 ax[i*2+1].stp = stp;
3887 ax[i*2+1].isTkn = 0;
3888 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003889 }
drh8b582012003-10-21 13:16:03 +00003890 mxTknOfst = mnTknOfst = 0;
3891 mxNtOfst = mnNtOfst = 0;
3892
drhfdbf9282003-10-21 16:34:41 +00003893 /* Compute the action table. In order to try to keep the size of the
3894 ** action table to a minimum, the heuristic of placing the largest action
3895 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003896 */
drhe594bc32009-11-03 13:02:25 +00003897 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003898 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003899 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003900 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3901 stp = ax[i].stp;
3902 if( ax[i].isTkn ){
3903 for(ap=stp->ap; ap; ap=ap->next){
3904 int action;
3905 if( ap->sp->index>=lemp->nterminal ) continue;
3906 action = compute_action(lemp, ap);
3907 if( action<0 ) continue;
3908 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003909 }
drhfdbf9282003-10-21 16:34:41 +00003910 stp->iTknOfst = acttab_insert(pActtab);
3911 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3912 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3913 }else{
3914 for(ap=stp->ap; ap; ap=ap->next){
3915 int action;
3916 if( ap->sp->index<lemp->nterminal ) continue;
3917 if( ap->sp->index==lemp->nsymbol ) continue;
3918 action = compute_action(lemp, ap);
3919 if( action<0 ) continue;
3920 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003921 }
drhfdbf9282003-10-21 16:34:41 +00003922 stp->iNtOfst = acttab_insert(pActtab);
3923 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3924 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003925 }
3926 }
drhfdbf9282003-10-21 16:34:41 +00003927 free(ax);
drh8b582012003-10-21 13:16:03 +00003928
3929 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00003930 lemp->nactiontab = n = acttab_size(pActtab);
3931 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00003932 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3933 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003934 for(i=j=0; i<n; i++){
3935 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003936 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003937 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003938 fprintf(out, " %4d,", action);
3939 if( j==9 || i==n-1 ){
3940 fprintf(out, "\n"); lineno++;
3941 j = 0;
3942 }else{
3943 j++;
3944 }
3945 }
3946 fprintf(out, "};\n"); lineno++;
3947
3948 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00003949 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00003950 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003951 for(i=j=0; i<n; i++){
3952 int la = acttab_yylookahead(pActtab, i);
3953 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003954 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003955 fprintf(out, " %4d,", la);
3956 if( j==9 || i==n-1 ){
3957 fprintf(out, "\n"); lineno++;
3958 j = 0;
3959 }else{
3960 j++;
3961 }
3962 }
3963 fprintf(out, "};\n"); lineno++;
3964
3965 /* Output the yy_shift_ofst[] table */
3966 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003967 n = lemp->nstate;
3968 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003969 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3970 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3971 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003972 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00003973 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
3974 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00003975 for(i=j=0; i<n; i++){
3976 int ofst;
3977 stp = lemp->sorted[i];
3978 ofst = stp->iTknOfst;
3979 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003980 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003981 fprintf(out, " %4d,", ofst);
3982 if( j==9 || i==n-1 ){
3983 fprintf(out, "\n"); lineno++;
3984 j = 0;
3985 }else{
3986 j++;
3987 }
3988 }
3989 fprintf(out, "};\n"); lineno++;
3990
3991 /* Output the yy_reduce_ofst[] table */
3992 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003993 n = lemp->nstate;
3994 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003995 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3996 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3997 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003998 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00003999 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4000 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004001 for(i=j=0; i<n; i++){
4002 int ofst;
4003 stp = lemp->sorted[i];
4004 ofst = stp->iNtOfst;
4005 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004006 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004007 fprintf(out, " %4d,", ofst);
4008 if( j==9 || i==n-1 ){
4009 fprintf(out, "\n"); lineno++;
4010 j = 0;
4011 }else{
4012 j++;
4013 }
4014 }
4015 fprintf(out, "};\n"); lineno++;
4016
4017 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004018 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004019 n = lemp->nstate;
drhc75e0162015-09-07 02:23:02 +00004020 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004021 for(i=j=0; i<n; i++){
4022 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004023 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004024 fprintf(out, " %4d,", stp->iDflt);
4025 if( j==9 || i==n-1 ){
4026 fprintf(out, "\n"); lineno++;
4027 j = 0;
4028 }else{
4029 j++;
4030 }
4031 }
4032 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004033 tplt_xfer(lemp->name,in,out,&lineno);
4034
drh0bd1f4e2002-06-06 18:54:39 +00004035 /* Generate the table of fallback tokens.
4036 */
4037 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004038 int mx = lemp->nterminal - 1;
4039 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004040 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004041 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004042 struct symbol *p = lemp->symbols[i];
4043 if( p->fallback==0 ){
4044 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4045 }else{
4046 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4047 p->name, p->fallback->name);
4048 }
4049 lineno++;
4050 }
4051 }
4052 tplt_xfer(lemp->name, in, out, &lineno);
4053
4054 /* Generate a table containing the symbolic name of every symbol
4055 */
drh75897232000-05-29 14:26:00 +00004056 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004057 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004058 fprintf(out," %-15s",line);
4059 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4060 }
4061 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4062 tplt_xfer(lemp->name,in,out,&lineno);
4063
drh0bd1f4e2002-06-06 18:54:39 +00004064 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004065 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004066 ** when tracing REDUCE actions.
4067 */
4068 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4069 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004070 fprintf(out," /* %3d */ \"", i);
4071 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004072 fprintf(out,"\",\n"); lineno++;
4073 }
4074 tplt_xfer(lemp->name,in,out,&lineno);
4075
drh75897232000-05-29 14:26:00 +00004076 /* Generate code which executes every time a symbol is popped from
4077 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004078 ** (In other words, generate the %destructor actions)
4079 */
drh75897232000-05-29 14:26:00 +00004080 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004081 int once = 1;
drh75897232000-05-29 14:26:00 +00004082 for(i=0; i<lemp->nsymbol; i++){
4083 struct symbol *sp = lemp->symbols[i];
4084 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004085 if( once ){
4086 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4087 once = 0;
4088 }
drhc53eed12009-06-12 17:46:19 +00004089 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004090 }
4091 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4092 if( i<lemp->nsymbol ){
4093 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4094 fprintf(out," break;\n"); lineno++;
4095 }
4096 }
drh8d659732005-01-13 23:54:06 +00004097 if( lemp->vardest ){
4098 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004099 int once = 1;
drh8d659732005-01-13 23:54:06 +00004100 for(i=0; i<lemp->nsymbol; i++){
4101 struct symbol *sp = lemp->symbols[i];
4102 if( sp==0 || sp->type==TERMINAL ||
4103 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004104 if( once ){
4105 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4106 once = 0;
4107 }
drhc53eed12009-06-12 17:46:19 +00004108 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004109 dflt_sp = sp;
4110 }
4111 if( dflt_sp!=0 ){
4112 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004113 }
drh4dc8ef52008-07-01 17:13:57 +00004114 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004115 }
drh75897232000-05-29 14:26:00 +00004116 for(i=0; i<lemp->nsymbol; i++){
4117 struct symbol *sp = lemp->symbols[i];
4118 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004119 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004120
4121 /* Combine duplicate destructors into a single case */
4122 for(j=i+1; j<lemp->nsymbol; j++){
4123 struct symbol *sp2 = lemp->symbols[j];
4124 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4125 && sp2->dtnum==sp->dtnum
4126 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004127 fprintf(out," case %d: /* %s */\n",
4128 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004129 sp2->destructor = 0;
4130 }
4131 }
4132
drh75897232000-05-29 14:26:00 +00004133 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4134 fprintf(out," break;\n"); lineno++;
4135 }
drh75897232000-05-29 14:26:00 +00004136 tplt_xfer(lemp->name,in,out,&lineno);
4137
4138 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004139 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004140 tplt_xfer(lemp->name,in,out,&lineno);
4141
4142 /* Generate the table of rule information
4143 **
4144 ** Note: This code depends on the fact that rules are number
4145 ** sequentually beginning with 0.
4146 */
4147 for(rp=lemp->rule; rp; rp=rp->next){
4148 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4149 }
4150 tplt_xfer(lemp->name,in,out,&lineno);
4151
4152 /* Generate code which execution during each REDUCE action */
4153 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004154 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004155 }
drhc53eed12009-06-12 17:46:19 +00004156 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004157 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004158 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004159 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004160 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004161 fprintf(out," case %d: /* ", rp->index);
4162 writeRuleText(out, rp);
4163 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004164 for(rp2=rp->next; rp2; rp2=rp2->next){
4165 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004166 fprintf(out," case %d: /* ", rp2->index);
4167 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004168 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004169 rp2->code = 0;
4170 }
4171 }
drh75897232000-05-29 14:26:00 +00004172 emit_code(out,rp,lemp,&lineno);
4173 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004174 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004175 }
drhc53eed12009-06-12 17:46:19 +00004176 /* Finally, output the default: rule. We choose as the default: all
4177 ** empty actions. */
4178 fprintf(out," default:\n"); lineno++;
4179 for(rp=lemp->rule; rp; rp=rp->next){
4180 if( rp->code==0 ) continue;
4181 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4182 fprintf(out," /* (%d) ", rp->index);
4183 writeRuleText(out, rp);
4184 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4185 }
4186 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004187 tplt_xfer(lemp->name,in,out,&lineno);
4188
4189 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004190 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004191 tplt_xfer(lemp->name,in,out,&lineno);
4192
4193 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004194 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004195 tplt_xfer(lemp->name,in,out,&lineno);
4196
4197 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004198 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004199 tplt_xfer(lemp->name,in,out,&lineno);
4200
4201 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004202 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004203
4204 fclose(in);
4205 fclose(out);
4206 return;
4207}
4208
4209/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004210void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004211{
4212 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004213 const char *prefix;
drh75897232000-05-29 14:26:00 +00004214 char line[LINESIZE];
4215 char pattern[LINESIZE];
4216 int i;
4217
4218 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4219 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004220 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004221 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004222 int nextChar;
drh75897232000-05-29 14:26:00 +00004223 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004224 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4225 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004226 if( strcmp(line,pattern) ) break;
4227 }
drh8ba0d1c2012-06-16 15:26:31 +00004228 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004229 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004230 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004231 /* No change in the file. Don't rewrite it. */
4232 return;
4233 }
4234 }
drh2aa6ca42004-09-10 00:14:04 +00004235 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004236 if( out ){
4237 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004238 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004239 }
4240 fclose(out);
4241 }
4242 return;
4243}
4244
4245/* Reduce the size of the action tables, if possible, by making use
4246** of defaults.
4247**
drhb59499c2002-02-23 18:45:13 +00004248** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004249** it the default. Except, there is no default if the wildcard token
4250** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004251*/
icculus9e44cf12010-02-14 17:14:22 +00004252void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004253{
4254 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004255 struct action *ap, *ap2;
4256 struct rule *rp, *rp2, *rbest;
4257 int nbest, n;
drh75897232000-05-29 14:26:00 +00004258 int i;
drhe09daa92006-06-10 13:29:31 +00004259 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004260
4261 for(i=0; i<lemp->nstate; i++){
4262 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004263 nbest = 0;
4264 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004265 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004266
drhb59499c2002-02-23 18:45:13 +00004267 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004268 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4269 usesWildcard = 1;
4270 }
drhb59499c2002-02-23 18:45:13 +00004271 if( ap->type!=REDUCE ) continue;
4272 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004273 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004274 if( rp==rbest ) continue;
4275 n = 1;
4276 for(ap2=ap->next; ap2; ap2=ap2->next){
4277 if( ap2->type!=REDUCE ) continue;
4278 rp2 = ap2->x.rp;
4279 if( rp2==rbest ) continue;
4280 if( rp2==rp ) n++;
4281 }
4282 if( n>nbest ){
4283 nbest = n;
4284 rbest = rp;
drh75897232000-05-29 14:26:00 +00004285 }
4286 }
drhb59499c2002-02-23 18:45:13 +00004287
4288 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004289 ** is not at least 1 or if the wildcard token is a possible
4290 ** lookahead.
4291 */
4292 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004293
drhb59499c2002-02-23 18:45:13 +00004294
4295 /* Combine matching REDUCE actions into a single default */
4296 for(ap=stp->ap; ap; ap=ap->next){
4297 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4298 }
drh75897232000-05-29 14:26:00 +00004299 assert( ap );
4300 ap->sp = Symbol_new("{default}");
4301 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004302 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004303 }
4304 stp->ap = Action_sort(stp->ap);
4305 }
4306}
drhb59499c2002-02-23 18:45:13 +00004307
drhada354d2005-11-05 15:03:59 +00004308
4309/*
4310** Compare two states for sorting purposes. The smaller state is the
4311** one with the most non-terminal actions. If they have the same number
4312** of non-terminal actions, then the smaller is the one with the most
4313** token actions.
4314*/
4315static int stateResortCompare(const void *a, const void *b){
4316 const struct state *pA = *(const struct state**)a;
4317 const struct state *pB = *(const struct state**)b;
4318 int n;
4319
4320 n = pB->nNtAct - pA->nNtAct;
4321 if( n==0 ){
4322 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004323 if( n==0 ){
4324 n = pB->statenum - pA->statenum;
4325 }
drhada354d2005-11-05 15:03:59 +00004326 }
drhe594bc32009-11-03 13:02:25 +00004327 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004328 return n;
4329}
4330
4331
4332/*
4333** Renumber and resort states so that states with fewer choices
4334** occur at the end. Except, keep state 0 as the first state.
4335*/
icculus9e44cf12010-02-14 17:14:22 +00004336void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004337{
4338 int i;
4339 struct state *stp;
4340 struct action *ap;
4341
4342 for(i=0; i<lemp->nstate; i++){
4343 stp = lemp->sorted[i];
4344 stp->nTknAct = stp->nNtAct = 0;
4345 stp->iDflt = lemp->nstate + lemp->nrule;
4346 stp->iTknOfst = NO_OFFSET;
4347 stp->iNtOfst = NO_OFFSET;
4348 for(ap=stp->ap; ap; ap=ap->next){
4349 if( compute_action(lemp,ap)>=0 ){
4350 if( ap->sp->index<lemp->nterminal ){
4351 stp->nTknAct++;
4352 }else if( ap->sp->index<lemp->nsymbol ){
4353 stp->nNtAct++;
4354 }else{
4355 stp->iDflt = compute_action(lemp, ap);
4356 }
4357 }
4358 }
4359 }
4360 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4361 stateResortCompare);
4362 for(i=0; i<lemp->nstate; i++){
4363 lemp->sorted[i]->statenum = i;
4364 }
4365}
4366
4367
drh75897232000-05-29 14:26:00 +00004368/***************** From the file "set.c" ************************************/
4369/*
4370** Set manipulation routines for the LEMON parser generator.
4371*/
4372
4373static int size = 0;
4374
4375/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004376void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004377{
4378 size = n+1;
4379}
4380
4381/* Allocate a new set */
4382char *SetNew(){
4383 char *s;
drh9892c5d2007-12-21 00:02:11 +00004384 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004385 if( s==0 ){
4386 extern void memory_error();
4387 memory_error();
4388 }
drh75897232000-05-29 14:26:00 +00004389 return s;
4390}
4391
4392/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004393void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004394{
4395 free(s);
4396}
4397
4398/* Add a new element to the set. Return TRUE if the element was added
4399** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004400int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004401{
4402 int rv;
drh9892c5d2007-12-21 00:02:11 +00004403 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004404 rv = s[e];
4405 s[e] = 1;
4406 return !rv;
4407}
4408
4409/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004410int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004411{
4412 int i, progress;
4413 progress = 0;
4414 for(i=0; i<size; i++){
4415 if( s2[i]==0 ) continue;
4416 if( s1[i]==0 ){
4417 progress = 1;
4418 s1[i] = 1;
4419 }
4420 }
4421 return progress;
4422}
4423/********************** From the file "table.c" ****************************/
4424/*
4425** All code in this file has been automatically generated
4426** from a specification in the file
4427** "table.q"
4428** by the associative array code building program "aagen".
4429** Do not edit this file! Instead, edit the specification
4430** file, then rerun aagen.
4431*/
4432/*
4433** Code for processing tables in the LEMON parser generator.
4434*/
4435
drh01f75f22013-10-02 20:46:30 +00004436PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004437{
drh01f75f22013-10-02 20:46:30 +00004438 unsigned h = 0;
4439 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004440 return h;
4441}
4442
4443/* Works like strdup, sort of. Save a string in malloced memory, but
4444** keep strings in a table so that the same string is not in more
4445** than one place.
4446*/
icculus9e44cf12010-02-14 17:14:22 +00004447const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004448{
icculus9e44cf12010-02-14 17:14:22 +00004449 const char *z;
4450 char *cpy;
drh75897232000-05-29 14:26:00 +00004451
drh916f75f2006-07-17 00:19:39 +00004452 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004453 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004454 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004455 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004456 z = cpy;
drh75897232000-05-29 14:26:00 +00004457 Strsafe_insert(z);
4458 }
4459 MemoryCheck(z);
4460 return z;
4461}
4462
4463/* There is one instance of the following structure for each
4464** associative array of type "x1".
4465*/
4466struct s_x1 {
4467 int size; /* The number of available slots. */
4468 /* Must be a power of 2 greater than or */
4469 /* equal to 1 */
4470 int count; /* Number of currently slots filled */
4471 struct s_x1node *tbl; /* The data stored here */
4472 struct s_x1node **ht; /* Hash table for lookups */
4473};
4474
4475/* There is one instance of this structure for every data element
4476** in an associative array of type "x1".
4477*/
4478typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004479 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004480 struct s_x1node *next; /* Next entry with the same hash */
4481 struct s_x1node **from; /* Previous link */
4482} x1node;
4483
4484/* There is only one instance of the array, which is the following */
4485static struct s_x1 *x1a;
4486
4487/* Allocate a new associative array */
4488void Strsafe_init(){
4489 if( x1a ) return;
4490 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4491 if( x1a ){
4492 x1a->size = 1024;
4493 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004494 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004495 if( x1a->tbl==0 ){
4496 free(x1a);
4497 x1a = 0;
4498 }else{
4499 int i;
4500 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4501 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4502 }
4503 }
4504}
4505/* Insert a new record into the array. Return TRUE if successful.
4506** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004507int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004508{
4509 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004510 unsigned h;
4511 unsigned ph;
drh75897232000-05-29 14:26:00 +00004512
4513 if( x1a==0 ) return 0;
4514 ph = strhash(data);
4515 h = ph & (x1a->size-1);
4516 np = x1a->ht[h];
4517 while( np ){
4518 if( strcmp(np->data,data)==0 ){
4519 /* An existing entry with the same key is found. */
4520 /* Fail because overwrite is not allows. */
4521 return 0;
4522 }
4523 np = np->next;
4524 }
4525 if( x1a->count>=x1a->size ){
4526 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004527 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004528 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004529 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004530 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004531 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004532 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004533 array.ht = (x1node**)&(array.tbl[arrSize]);
4534 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004535 for(i=0; i<x1a->count; i++){
4536 x1node *oldnp, *newnp;
4537 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004538 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004539 newnp = &(array.tbl[i]);
4540 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4541 newnp->next = array.ht[h];
4542 newnp->data = oldnp->data;
4543 newnp->from = &(array.ht[h]);
4544 array.ht[h] = newnp;
4545 }
4546 free(x1a->tbl);
4547 *x1a = array;
4548 }
4549 /* Insert the new data */
4550 h = ph & (x1a->size-1);
4551 np = &(x1a->tbl[x1a->count++]);
4552 np->data = data;
4553 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4554 np->next = x1a->ht[h];
4555 x1a->ht[h] = np;
4556 np->from = &(x1a->ht[h]);
4557 return 1;
4558}
4559
4560/* Return a pointer to data assigned to the given key. Return NULL
4561** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004562const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004563{
drh01f75f22013-10-02 20:46:30 +00004564 unsigned h;
drh75897232000-05-29 14:26:00 +00004565 x1node *np;
4566
4567 if( x1a==0 ) return 0;
4568 h = strhash(key) & (x1a->size-1);
4569 np = x1a->ht[h];
4570 while( np ){
4571 if( strcmp(np->data,key)==0 ) break;
4572 np = np->next;
4573 }
4574 return np ? np->data : 0;
4575}
4576
4577/* Return a pointer to the (terminal or nonterminal) symbol "x".
4578** Create a new symbol if this is the first time "x" has been seen.
4579*/
icculus9e44cf12010-02-14 17:14:22 +00004580struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004581{
4582 struct symbol *sp;
4583
4584 sp = Symbol_find(x);
4585 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004586 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004587 MemoryCheck(sp);
4588 sp->name = Strsafe(x);
4589 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4590 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004591 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004592 sp->prec = -1;
4593 sp->assoc = UNK;
4594 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004595 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004596 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004597 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004598 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004599 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004600 Symbol_insert(sp,sp->name);
4601 }
drhc4dd3fd2008-01-22 01:48:05 +00004602 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004603 return sp;
4604}
4605
drh61f92cd2014-01-11 03:06:18 +00004606/* Compare two symbols for sorting purposes. Return negative,
4607** zero, or positive if a is less then, equal to, or greater
4608** than b.
drh60d31652004-02-22 00:08:04 +00004609**
4610** Symbols that begin with upper case letters (terminals or tokens)
4611** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004612** (non-terminals). And MULTITERMINAL symbols (created using the
4613** %token_class directive) must sort at the very end. Other than
4614** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004615**
4616** We find experimentally that leaving the symbols in their original
4617** order (the order they appeared in the grammar file) gives the
4618** smallest parser tables in SQLite.
4619*/
icculus9e44cf12010-02-14 17:14:22 +00004620int Symbolcmpp(const void *_a, const void *_b)
4621{
drh61f92cd2014-01-11 03:06:18 +00004622 const struct symbol *a = *(const struct symbol **) _a;
4623 const struct symbol *b = *(const struct symbol **) _b;
4624 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4625 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4626 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004627}
4628
4629/* There is one instance of the following structure for each
4630** associative array of type "x2".
4631*/
4632struct s_x2 {
4633 int size; /* The number of available slots. */
4634 /* Must be a power of 2 greater than or */
4635 /* equal to 1 */
4636 int count; /* Number of currently slots filled */
4637 struct s_x2node *tbl; /* The data stored here */
4638 struct s_x2node **ht; /* Hash table for lookups */
4639};
4640
4641/* There is one instance of this structure for every data element
4642** in an associative array of type "x2".
4643*/
4644typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004645 struct symbol *data; /* The data */
4646 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004647 struct s_x2node *next; /* Next entry with the same hash */
4648 struct s_x2node **from; /* Previous link */
4649} x2node;
4650
4651/* There is only one instance of the array, which is the following */
4652static struct s_x2 *x2a;
4653
4654/* Allocate a new associative array */
4655void Symbol_init(){
4656 if( x2a ) return;
4657 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4658 if( x2a ){
4659 x2a->size = 128;
4660 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004661 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004662 if( x2a->tbl==0 ){
4663 free(x2a);
4664 x2a = 0;
4665 }else{
4666 int i;
4667 x2a->ht = (x2node**)&(x2a->tbl[128]);
4668 for(i=0; i<128; i++) x2a->ht[i] = 0;
4669 }
4670 }
4671}
4672/* Insert a new record into the array. Return TRUE if successful.
4673** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004674int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004675{
4676 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004677 unsigned h;
4678 unsigned ph;
drh75897232000-05-29 14:26:00 +00004679
4680 if( x2a==0 ) return 0;
4681 ph = strhash(key);
4682 h = ph & (x2a->size-1);
4683 np = x2a->ht[h];
4684 while( np ){
4685 if( strcmp(np->key,key)==0 ){
4686 /* An existing entry with the same key is found. */
4687 /* Fail because overwrite is not allows. */
4688 return 0;
4689 }
4690 np = np->next;
4691 }
4692 if( x2a->count>=x2a->size ){
4693 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004694 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004695 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004696 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004697 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004698 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004699 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004700 array.ht = (x2node**)&(array.tbl[arrSize]);
4701 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004702 for(i=0; i<x2a->count; i++){
4703 x2node *oldnp, *newnp;
4704 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004705 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004706 newnp = &(array.tbl[i]);
4707 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4708 newnp->next = array.ht[h];
4709 newnp->key = oldnp->key;
4710 newnp->data = oldnp->data;
4711 newnp->from = &(array.ht[h]);
4712 array.ht[h] = newnp;
4713 }
4714 free(x2a->tbl);
4715 *x2a = array;
4716 }
4717 /* Insert the new data */
4718 h = ph & (x2a->size-1);
4719 np = &(x2a->tbl[x2a->count++]);
4720 np->key = key;
4721 np->data = data;
4722 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4723 np->next = x2a->ht[h];
4724 x2a->ht[h] = np;
4725 np->from = &(x2a->ht[h]);
4726 return 1;
4727}
4728
4729/* Return a pointer to data assigned to the given key. Return NULL
4730** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004731struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004732{
drh01f75f22013-10-02 20:46:30 +00004733 unsigned h;
drh75897232000-05-29 14:26:00 +00004734 x2node *np;
4735
4736 if( x2a==0 ) return 0;
4737 h = strhash(key) & (x2a->size-1);
4738 np = x2a->ht[h];
4739 while( np ){
4740 if( strcmp(np->key,key)==0 ) break;
4741 np = np->next;
4742 }
4743 return np ? np->data : 0;
4744}
4745
4746/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004747struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004748{
4749 struct symbol *data;
4750 if( x2a && n>0 && n<=x2a->count ){
4751 data = x2a->tbl[n-1].data;
4752 }else{
4753 data = 0;
4754 }
4755 return data;
4756}
4757
4758/* Return the size of the array */
4759int Symbol_count()
4760{
4761 return x2a ? x2a->count : 0;
4762}
4763
4764/* Return an array of pointers to all data in the table.
4765** The array is obtained from malloc. Return NULL if memory allocation
4766** problems, or if the array is empty. */
4767struct symbol **Symbol_arrayof()
4768{
4769 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00004770 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004771 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004772 arrSize = x2a->count;
4773 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004774 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004775 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004776 }
4777 return array;
4778}
4779
4780/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004781int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004782{
icculus9e44cf12010-02-14 17:14:22 +00004783 const struct config *a = (struct config *) _a;
4784 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004785 int x;
4786 x = a->rp->index - b->rp->index;
4787 if( x==0 ) x = a->dot - b->dot;
4788 return x;
4789}
4790
4791/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004792PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004793{
4794 int rc;
4795 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4796 rc = a->rp->index - b->rp->index;
4797 if( rc==0 ) rc = a->dot - b->dot;
4798 }
4799 if( rc==0 ){
4800 if( a ) rc = 1;
4801 if( b ) rc = -1;
4802 }
4803 return rc;
4804}
4805
4806/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00004807PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004808{
drh01f75f22013-10-02 20:46:30 +00004809 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004810 while( a ){
4811 h = h*571 + a->rp->index*37 + a->dot;
4812 a = a->bp;
4813 }
4814 return h;
4815}
4816
4817/* Allocate a new state structure */
4818struct state *State_new()
4819{
icculus9e44cf12010-02-14 17:14:22 +00004820 struct state *newstate;
4821 newstate = (struct state *)calloc(1, sizeof(struct state) );
4822 MemoryCheck(newstate);
4823 return newstate;
drh75897232000-05-29 14:26:00 +00004824}
4825
4826/* There is one instance of the following structure for each
4827** associative array of type "x3".
4828*/
4829struct s_x3 {
4830 int size; /* The number of available slots. */
4831 /* Must be a power of 2 greater than or */
4832 /* equal to 1 */
4833 int count; /* Number of currently slots filled */
4834 struct s_x3node *tbl; /* The data stored here */
4835 struct s_x3node **ht; /* Hash table for lookups */
4836};
4837
4838/* There is one instance of this structure for every data element
4839** in an associative array of type "x3".
4840*/
4841typedef struct s_x3node {
4842 struct state *data; /* The data */
4843 struct config *key; /* The key */
4844 struct s_x3node *next; /* Next entry with the same hash */
4845 struct s_x3node **from; /* Previous link */
4846} x3node;
4847
4848/* There is only one instance of the array, which is the following */
4849static struct s_x3 *x3a;
4850
4851/* Allocate a new associative array */
4852void State_init(){
4853 if( x3a ) return;
4854 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4855 if( x3a ){
4856 x3a->size = 128;
4857 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004858 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00004859 if( x3a->tbl==0 ){
4860 free(x3a);
4861 x3a = 0;
4862 }else{
4863 int i;
4864 x3a->ht = (x3node**)&(x3a->tbl[128]);
4865 for(i=0; i<128; i++) x3a->ht[i] = 0;
4866 }
4867 }
4868}
4869/* Insert a new record into the array. Return TRUE if successful.
4870** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004871int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004872{
4873 x3node *np;
drh01f75f22013-10-02 20:46:30 +00004874 unsigned h;
4875 unsigned ph;
drh75897232000-05-29 14:26:00 +00004876
4877 if( x3a==0 ) return 0;
4878 ph = statehash(key);
4879 h = ph & (x3a->size-1);
4880 np = x3a->ht[h];
4881 while( np ){
4882 if( statecmp(np->key,key)==0 ){
4883 /* An existing entry with the same key is found. */
4884 /* Fail because overwrite is not allows. */
4885 return 0;
4886 }
4887 np = np->next;
4888 }
4889 if( x3a->count>=x3a->size ){
4890 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004891 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004892 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00004893 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00004894 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00004895 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00004896 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004897 array.ht = (x3node**)&(array.tbl[arrSize]);
4898 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004899 for(i=0; i<x3a->count; i++){
4900 x3node *oldnp, *newnp;
4901 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004902 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004903 newnp = &(array.tbl[i]);
4904 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4905 newnp->next = array.ht[h];
4906 newnp->key = oldnp->key;
4907 newnp->data = oldnp->data;
4908 newnp->from = &(array.ht[h]);
4909 array.ht[h] = newnp;
4910 }
4911 free(x3a->tbl);
4912 *x3a = array;
4913 }
4914 /* Insert the new data */
4915 h = ph & (x3a->size-1);
4916 np = &(x3a->tbl[x3a->count++]);
4917 np->key = key;
4918 np->data = data;
4919 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4920 np->next = x3a->ht[h];
4921 x3a->ht[h] = np;
4922 np->from = &(x3a->ht[h]);
4923 return 1;
4924}
4925
4926/* Return a pointer to data assigned to the given key. Return NULL
4927** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004928struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004929{
drh01f75f22013-10-02 20:46:30 +00004930 unsigned h;
drh75897232000-05-29 14:26:00 +00004931 x3node *np;
4932
4933 if( x3a==0 ) return 0;
4934 h = statehash(key) & (x3a->size-1);
4935 np = x3a->ht[h];
4936 while( np ){
4937 if( statecmp(np->key,key)==0 ) break;
4938 np = np->next;
4939 }
4940 return np ? np->data : 0;
4941}
4942
4943/* Return an array of pointers to all data in the table.
4944** The array is obtained from malloc. Return NULL if memory allocation
4945** problems, or if the array is empty. */
4946struct state **State_arrayof()
4947{
4948 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00004949 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004950 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004951 arrSize = x3a->count;
4952 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00004953 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004954 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004955 }
4956 return array;
4957}
4958
4959/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00004960PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004961{
drh01f75f22013-10-02 20:46:30 +00004962 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004963 h = h*571 + a->rp->index*37 + a->dot;
4964 return h;
4965}
4966
4967/* There is one instance of the following structure for each
4968** associative array of type "x4".
4969*/
4970struct s_x4 {
4971 int size; /* The number of available slots. */
4972 /* Must be a power of 2 greater than or */
4973 /* equal to 1 */
4974 int count; /* Number of currently slots filled */
4975 struct s_x4node *tbl; /* The data stored here */
4976 struct s_x4node **ht; /* Hash table for lookups */
4977};
4978
4979/* There is one instance of this structure for every data element
4980** in an associative array of type "x4".
4981*/
4982typedef struct s_x4node {
4983 struct config *data; /* The data */
4984 struct s_x4node *next; /* Next entry with the same hash */
4985 struct s_x4node **from; /* Previous link */
4986} x4node;
4987
4988/* There is only one instance of the array, which is the following */
4989static struct s_x4 *x4a;
4990
4991/* Allocate a new associative array */
4992void Configtable_init(){
4993 if( x4a ) return;
4994 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4995 if( x4a ){
4996 x4a->size = 64;
4997 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004998 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00004999 if( x4a->tbl==0 ){
5000 free(x4a);
5001 x4a = 0;
5002 }else{
5003 int i;
5004 x4a->ht = (x4node**)&(x4a->tbl[64]);
5005 for(i=0; i<64; i++) x4a->ht[i] = 0;
5006 }
5007 }
5008}
5009/* Insert a new record into the array. Return TRUE if successful.
5010** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005011int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005012{
5013 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005014 unsigned h;
5015 unsigned ph;
drh75897232000-05-29 14:26:00 +00005016
5017 if( x4a==0 ) return 0;
5018 ph = confighash(data);
5019 h = ph & (x4a->size-1);
5020 np = x4a->ht[h];
5021 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005022 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005023 /* An existing entry with the same key is found. */
5024 /* Fail because overwrite is not allows. */
5025 return 0;
5026 }
5027 np = np->next;
5028 }
5029 if( x4a->count>=x4a->size ){
5030 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005031 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005032 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005033 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005034 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005035 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005036 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005037 array.ht = (x4node**)&(array.tbl[arrSize]);
5038 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005039 for(i=0; i<x4a->count; i++){
5040 x4node *oldnp, *newnp;
5041 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005042 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005043 newnp = &(array.tbl[i]);
5044 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5045 newnp->next = array.ht[h];
5046 newnp->data = oldnp->data;
5047 newnp->from = &(array.ht[h]);
5048 array.ht[h] = newnp;
5049 }
5050 free(x4a->tbl);
5051 *x4a = array;
5052 }
5053 /* Insert the new data */
5054 h = ph & (x4a->size-1);
5055 np = &(x4a->tbl[x4a->count++]);
5056 np->data = data;
5057 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5058 np->next = x4a->ht[h];
5059 x4a->ht[h] = np;
5060 np->from = &(x4a->ht[h]);
5061 return 1;
5062}
5063
5064/* Return a pointer to data assigned to the given key. Return NULL
5065** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005066struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005067{
5068 int h;
5069 x4node *np;
5070
5071 if( x4a==0 ) return 0;
5072 h = confighash(key) & (x4a->size-1);
5073 np = x4a->ht[h];
5074 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005075 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005076 np = np->next;
5077 }
5078 return np ? np->data : 0;
5079}
5080
5081/* Remove all data from the table. Pass each data to the function "f"
5082** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005083void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005084{
5085 int i;
5086 if( x4a==0 || x4a->count==0 ) return;
5087 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5088 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5089 x4a->count = 0;
5090 return;
5091}