blob: c6780de9a8ebdb820f4268bb8c3bc0f7c013adf8 [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
drhc56fac72015-10-29 13:48:15 +000016#define ISSPACE(X) isspace((unsigned char)(X))
17#define ISDIGIT(X) isdigit((unsigned char)(X))
18#define ISALNUM(X) isalnum((unsigned char)(X))
19#define ISALPHA(X) isalpha((unsigned char)(X))
20#define ISUPPER(X) isupper((unsigned char)(X))
21#define ISLOWER(X) islower((unsigned char)(X))
22
23
drh75897232000-05-29 14:26:00 +000024#ifndef __WIN32__
25# if defined(_WIN32) || defined(WIN32)
drhf2f105d2012-08-20 15:53:54 +000026# define __WIN32__
drh75897232000-05-29 14:26:00 +000027# endif
28#endif
29
rse8f304482007-07-30 18:31:53 +000030#ifdef __WIN32__
drhdf609712010-11-23 20:55:27 +000031#ifdef __cplusplus
32extern "C" {
33#endif
34extern int access(const char *path, int mode);
35#ifdef __cplusplus
36}
37#endif
rse8f304482007-07-30 18:31:53 +000038#else
39#include <unistd.h>
40#endif
41
drh75897232000-05-29 14:26:00 +000042/* #define PRIVATE static */
43#define PRIVATE
44
45#ifdef TEST
46#define MAXRHS 5 /* Set low to exercise exception code */
47#else
48#define MAXRHS 1000
49#endif
50
mistachkin17df7612019-06-03 15:09:25 +000051extern void memory_error();
drhf5c4e0f2010-07-18 11:35:53 +000052static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000053static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000054
drh87cf1372008-08-13 20:09:06 +000055/*
56** Compilers are getting increasingly pedantic about type conversions
57** as C evolves ever closer to Ada.... To work around the latest problems
58** we have to define the following variant of strlen().
59*/
60#define lemonStrlen(X) ((int)strlen(X))
61
drh898799f2014-01-10 23:21:00 +000062/*
63** Compilers are starting to complain about the use of sprintf() and strcpy(),
64** saying they are unsafe. So we define our own versions of those routines too.
65**
66** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
drh25473362015-09-04 18:03:45 +000067** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
drh898799f2014-01-10 23:21:00 +000068** The third is a helper routine for vsnprintf() that adds texts to the end of a
69** buffer, making sure the buffer is always zero-terminated.
70**
71** The string formatter is a minimal subset of stdlib sprintf() supporting only
72** a few simply conversions:
73**
74** %d
75** %s
76** %.*s
77**
78*/
79static void lemon_addtext(
80 char *zBuf, /* The buffer to which text is added */
81 int *pnUsed, /* Slots of the buffer used so far */
82 const char *zIn, /* Text to add */
drh61f92cd2014-01-11 03:06:18 +000083 int nIn, /* Bytes of text to add. -1 to use strlen() */
84 int iWidth /* Field width. Negative to left justify */
drh898799f2014-01-10 23:21:00 +000085){
86 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
drhecaa9d32014-01-11 03:27:37 +000087 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
drh898799f2014-01-10 23:21:00 +000088 if( nIn==0 ) return;
89 memcpy(&zBuf[*pnUsed], zIn, nIn);
90 *pnUsed += nIn;
drhecaa9d32014-01-11 03:27:37 +000091 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
drh898799f2014-01-10 23:21:00 +000092 zBuf[*pnUsed] = 0;
93}
94static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
mistachkin7a429652014-01-14 10:17:21 +000095 int i, j, k, c;
drh898799f2014-01-10 23:21:00 +000096 int nUsed = 0;
97 const char *z;
98 char zTemp[50];
99 str[0] = 0;
100 for(i=j=0; (c = zFormat[i])!=0; i++){
101 if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000102 int iWidth = 0;
103 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000104 c = zFormat[++i];
drhc56fac72015-10-29 13:48:15 +0000105 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
drh61f92cd2014-01-11 03:06:18 +0000106 if( c=='-' ) i++;
drhc56fac72015-10-29 13:48:15 +0000107 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
drh61f92cd2014-01-11 03:06:18 +0000108 if( c=='-' ) iWidth = -iWidth;
109 c = zFormat[i];
110 }
drh898799f2014-01-10 23:21:00 +0000111 if( c=='d' ){
112 int v = va_arg(ap, int);
113 if( v<0 ){
drh61f92cd2014-01-11 03:06:18 +0000114 lemon_addtext(str, &nUsed, "-", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000115 v = -v;
116 }else if( v==0 ){
drh61f92cd2014-01-11 03:06:18 +0000117 lemon_addtext(str, &nUsed, "0", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000118 }
119 k = 0;
120 while( v>0 ){
121 k++;
122 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
123 v /= 10;
124 }
drh61f92cd2014-01-11 03:06:18 +0000125 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
drh898799f2014-01-10 23:21:00 +0000126 }else if( c=='s' ){
127 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000128 lemon_addtext(str, &nUsed, z, -1, iWidth);
drh898799f2014-01-10 23:21:00 +0000129 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
130 i += 2;
131 k = va_arg(ap, int);
132 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000133 lemon_addtext(str, &nUsed, z, k, iWidth);
drh898799f2014-01-10 23:21:00 +0000134 }else if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000135 lemon_addtext(str, &nUsed, "%", 1, 0);
drh898799f2014-01-10 23:21:00 +0000136 }else{
137 fprintf(stderr, "illegal format\n");
138 exit(1);
139 }
140 j = i+1;
141 }
142 }
drh61f92cd2014-01-11 03:06:18 +0000143 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000144 return nUsed;
145}
146static int lemon_sprintf(char *str, const char *format, ...){
147 va_list ap;
148 int rc;
149 va_start(ap, format);
150 rc = lemon_vsprintf(str, format, ap);
151 va_end(ap);
152 return rc;
153}
154static void lemon_strcpy(char *dest, const char *src){
155 while( (*(dest++) = *(src++))!=0 ){}
156}
157static void lemon_strcat(char *dest, const char *src){
158 while( *dest ) dest++;
159 lemon_strcpy(dest, src);
160}
161
162
icculus9e44cf12010-02-14 17:14:22 +0000163/* a few forward declarations... */
164struct rule;
165struct lemon;
166struct action;
167
drhe9278182007-07-18 18:16:29 +0000168static struct action *Action_new(void);
169static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +0000170
171/********** From the file "build.h" ************************************/
drh14d88552017-04-14 19:44:15 +0000172void FindRulePrecedences(struct lemon*);
173void FindFirstSets(struct lemon*);
174void FindStates(struct lemon*);
175void FindLinks(struct lemon*);
176void FindFollowSets(struct lemon*);
177void FindActions(struct lemon*);
drh75897232000-05-29 14:26:00 +0000178
179/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +0000180void Configlist_init(void);
181struct config *Configlist_add(struct rule *, int);
182struct config *Configlist_addbasis(struct rule *, int);
183void Configlist_closure(struct lemon *);
184void Configlist_sort(void);
185void Configlist_sortbasis(void);
186struct config *Configlist_return(void);
187struct config *Configlist_basis(void);
188void Configlist_eat(struct config *);
189void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +0000190
191/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +0000192void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +0000193
194/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +0000195enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
196 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +0000197struct s_options {
icculus9e44cf12010-02-14 17:14:22 +0000198 enum option_type type;
199 const char *label;
drh75897232000-05-29 14:26:00 +0000200 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000201 const char *message;
drh75897232000-05-29 14:26:00 +0000202};
icculus9e44cf12010-02-14 17:14:22 +0000203int OptInit(char**,struct s_options*,FILE*);
204int OptNArgs(void);
205char *OptArg(int);
206void OptErr(int);
207void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000208
209/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000210void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000211
212/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000213struct plink *Plink_new(void);
214void Plink_add(struct plink **, struct config *);
215void Plink_copy(struct plink **, struct plink *);
216void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000217
218/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000219void Reprint(struct lemon *);
220void ReportOutput(struct lemon *);
drhfe03dac2019-11-26 02:22:39 +0000221void ReportTable(struct lemon *, int, int);
icculus9e44cf12010-02-14 17:14:22 +0000222void ReportHeader(struct lemon *);
223void CompressTables(struct lemon *);
224void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000225
226/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000227void SetSize(int); /* All sets will be of size N */
228char *SetNew(void); /* A new set for element 0..N */
229void SetFree(char*); /* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +0000230int SetAdd(char*,int); /* Add element to a set */
231int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000232#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
233
234/********** From the file "struct.h" *************************************/
235/*
236** Principal data structures for the LEMON parser generator.
237*/
238
drhaa9f1122007-08-23 02:50:56 +0000239typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000240
241/* Symbols (terminals and nonterminals) of the grammar are stored
242** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000243enum symbol_type {
244 TERMINAL,
245 NONTERMINAL,
246 MULTITERMINAL
247};
248enum e_assoc {
drh75897232000-05-29 14:26:00 +0000249 LEFT,
250 RIGHT,
251 NONE,
252 UNK
icculus9e44cf12010-02-14 17:14:22 +0000253};
254struct symbol {
255 const char *name; /* Name of the symbol */
256 int index; /* Index number for this symbol */
257 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
258 struct rule *rule; /* Linked list of rules of this (if an NT) */
259 struct symbol *fallback; /* fallback token in case this token doesn't parse */
260 int prec; /* Precedence if defined (-1 otherwise) */
261 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000262 char *firstset; /* First-set for all rules of this symbol */
263 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000264 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000265 char *destructor; /* Code which executes whenever this symbol is
266 ** popped from the stack during error processing */
drh0f832dd2016-08-16 16:46:40 +0000267 int destLineno; /* Line number for start of destructor. Set to
268 ** -1 for duplicate destructors. */
drh75897232000-05-29 14:26:00 +0000269 char *datatype; /* The data type of information held by this
270 ** object. Only used if type==NONTERMINAL */
271 int dtnum; /* The data type number. In the parser, the value
272 ** stack is a union. The .yy%d element of this
273 ** union is the correct data type for this object */
drh539e7412018-04-21 20:24:19 +0000274 int bContent; /* True if this symbol ever carries content - if
275 ** it is ever more than just syntax */
drhfd405312005-11-06 04:06:59 +0000276 /* The following fields are used by MULTITERMINALs only */
277 int nsubsym; /* Number of constituent symbols in the MULTI */
278 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000279};
280
281/* Each production rule in the grammar is stored in the following
282** structure. */
283struct rule {
284 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000285 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000286 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000287 int ruleline; /* Line number for the rule */
288 int nrhs; /* Number of RHS symbols */
289 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000290 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000291 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000292 const char *code; /* The code executed when this rule is reduced */
drh4dd0d3f2016-02-17 01:18:33 +0000293 const char *codePrefix; /* Setup code before code[] above */
294 const char *codeSuffix; /* Breakdown code after code[] above */
drh75897232000-05-29 14:26:00 +0000295 struct symbol *precsym; /* Precedence symbol for this rule */
296 int index; /* An index number for this rule */
drh4ef07702016-03-16 19:45:54 +0000297 int iRule; /* Rule number as used in the generated tables */
drhe94006e2019-12-10 20:41:48 +0000298 Boolean noCode; /* True if this rule has no associated C code */
299 Boolean codeEmitted; /* True if the code has been emitted already */
drh75897232000-05-29 14:26:00 +0000300 Boolean canReduce; /* True if this rule is ever reduced */
drh756b41e2016-05-24 18:55:08 +0000301 Boolean doesReduce; /* Reduce actions occur after optimization */
drhe94006e2019-12-10 20:41:48 +0000302 Boolean neverReduce; /* Reduce is theoretically possible, but prevented
303 ** by actions or other outside implementation */
drh75897232000-05-29 14:26:00 +0000304 struct rule *nextlhs; /* Next rule with the same LHS */
305 struct rule *next; /* Next rule in the global list */
306};
307
308/* A configuration is a production rule of the grammar together with
309** a mark (dot) showing how much of that rule has been processed so far.
310** Configurations also contain a follow-set which is a list of terminal
311** symbols which are allowed to immediately follow the end of the rule.
312** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000313enum cfgstatus {
314 COMPLETE,
315 INCOMPLETE
316};
drh75897232000-05-29 14:26:00 +0000317struct config {
318 struct rule *rp; /* The rule upon which the configuration is based */
319 int dot; /* The parse point */
320 char *fws; /* Follow-set for this configuration only */
321 struct plink *fplp; /* Follow-set forward propagation links */
322 struct plink *bplp; /* Follow-set backwards propagation links */
323 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000324 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000325 struct config *next; /* Next configuration in the state */
326 struct config *bp; /* The next basis configuration */
327};
328
icculus9e44cf12010-02-14 17:14:22 +0000329enum e_action {
330 SHIFT,
331 ACCEPT,
332 REDUCE,
333 ERROR,
334 SSCONFLICT, /* A shift/shift conflict */
335 SRCONFLICT, /* Was a reduce, but part of a conflict */
336 RRCONFLICT, /* Was a reduce, but part of a conflict */
337 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
338 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000339 NOT_USED, /* Deleted by compression */
340 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000341};
342
drh75897232000-05-29 14:26:00 +0000343/* Every shift or reduce operation is stored as one of the following */
344struct action {
345 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000346 enum e_action type;
drh75897232000-05-29 14:26:00 +0000347 union {
348 struct state *stp; /* The new state, if a shift */
349 struct rule *rp; /* The rule, if a reduce */
350 } x;
drhc173ad82016-05-23 16:15:02 +0000351 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
drh75897232000-05-29 14:26:00 +0000352 struct action *next; /* Next action for this state */
353 struct action *collide; /* Next action with the same hash */
354};
355
356/* Each state of the generated parser's finite state machine
357** is encoded as an instance of the following structure. */
358struct state {
359 struct config *bp; /* The basis configurations for this state */
360 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000361 int statenum; /* Sequential number for this state */
drh711c9812016-05-23 14:24:31 +0000362 struct action *ap; /* List of actions for this state */
drh8b582012003-10-21 13:16:03 +0000363 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
364 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000365 int iDfltReduce; /* Default action is to REDUCE by this rule */
366 struct rule *pDfltReduce;/* The default REDUCE rule. */
367 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000368};
drh8b582012003-10-21 13:16:03 +0000369#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000370
371/* A followset propagation link indicates that the contents of one
372** configuration followset should be propagated to another whenever
373** the first changes. */
374struct plink {
375 struct config *cfp; /* The configuration to which linked */
376 struct plink *next; /* The next propagate link */
377};
378
379/* The state vector for the entire parser generator is recorded as
380** follows. (LEMON uses no global variables and makes little use of
381** static variables. Fields in the following structure can be thought
382** of as begin global variables in the program.) */
383struct lemon {
384 struct state **sorted; /* Table of states sorted by state number */
385 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000386 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000387 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000388 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000389 int nrule; /* Number of rules */
390 int nsymbol; /* Number of terminal and nonterminal symbols */
391 int nterminal; /* Number of terminal symbols */
drh5c8241b2017-12-24 23:38:10 +0000392 int minShiftReduce; /* Minimum shift-reduce action value */
393 int errAction; /* Error action value */
394 int accAction; /* Accept action value */
395 int noAction; /* No-op action value */
396 int minReduce; /* Minimum reduce action */
397 int maxAction; /* Maximum action value of any kind */
drh75897232000-05-29 14:26:00 +0000398 struct symbol **symbols; /* Sorted array of pointers to symbols */
399 int errorcnt; /* Number of errors */
400 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000401 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000402 char *name; /* Name of the generated parser */
403 char *arg; /* Declaration of the 3th argument to parser */
drhfb32c442018-04-21 13:51:42 +0000404 char *ctx; /* Declaration of 2nd argument to constructor */
drh75897232000-05-29 14:26:00 +0000405 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000406 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000407 char *start; /* Name of the start symbol for the grammar */
408 char *stacksize; /* Size of the parser stack */
409 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000410 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000411 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000412 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000413 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000414 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000415 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000416 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000417 char *filename; /* Name of the input file */
418 char *outname; /* Name of the current output file */
419 char *tokenprefix; /* A prefix added to token names in the .h file */
420 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000421 int nactiontab; /* Number of entries in the yy_action[] table */
drh3a9d6c72017-12-25 04:15:38 +0000422 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
drhc75e0162015-09-07 02:23:02 +0000423 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000424 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000425 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000426 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000427 char *argv0; /* Name of the program */
428};
429
430#define MemoryCheck(X) if((X)==0){ \
431 extern void memory_error(); \
432 memory_error(); \
433}
434
435/**************** From the file "table.h" *********************************/
436/*
437** All code in this file has been automatically generated
438** from a specification in the file
439** "table.q"
440** by the associative array code building program "aagen".
441** Do not edit this file! Instead, edit the specification
442** file, then rerun aagen.
443*/
444/*
445** Code for processing tables in the LEMON parser generator.
446*/
drh75897232000-05-29 14:26:00 +0000447/* Routines for handling a strings */
448
icculus9e44cf12010-02-14 17:14:22 +0000449const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000450
icculus9e44cf12010-02-14 17:14:22 +0000451void Strsafe_init(void);
452int Strsafe_insert(const char *);
453const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000454
455/* Routines for handling symbols of the grammar */
456
icculus9e44cf12010-02-14 17:14:22 +0000457struct symbol *Symbol_new(const char *);
458int Symbolcmpp(const void *, const void *);
459void Symbol_init(void);
460int Symbol_insert(struct symbol *, const char *);
461struct symbol *Symbol_find(const char *);
462struct symbol *Symbol_Nth(int);
463int Symbol_count(void);
464struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000465
466/* Routines to manage the state table */
467
icculus9e44cf12010-02-14 17:14:22 +0000468int Configcmp(const char *, const char *);
469struct state *State_new(void);
470void State_init(void);
471int State_insert(struct state *, struct config *);
472struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000473struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000474
475/* Routines used for efficiency in Configlist_add */
476
icculus9e44cf12010-02-14 17:14:22 +0000477void Configtable_init(void);
478int Configtable_insert(struct config *);
479struct config *Configtable_find(struct config *);
480void Configtable_clear(int(*)(struct config *));
481
drh75897232000-05-29 14:26:00 +0000482/****************** From the file "action.c" *******************************/
483/*
484** Routines processing parser actions in the LEMON parser generator.
485*/
486
487/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000488static struct action *Action_new(void){
mistachkind9bc6e82019-05-10 16:16:19 +0000489 static struct action *actionfreelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000490 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000491
mistachkind9bc6e82019-05-10 16:16:19 +0000492 if( actionfreelist==0 ){
drh75897232000-05-29 14:26:00 +0000493 int i;
494 int amt = 100;
mistachkind9bc6e82019-05-10 16:16:19 +0000495 actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
496 if( actionfreelist==0 ){
drh75897232000-05-29 14:26:00 +0000497 fprintf(stderr,"Unable to allocate memory for a new parser action.");
498 exit(1);
499 }
mistachkind9bc6e82019-05-10 16:16:19 +0000500 for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
501 actionfreelist[amt-1].next = 0;
drh75897232000-05-29 14:26:00 +0000502 }
mistachkind9bc6e82019-05-10 16:16:19 +0000503 newaction = actionfreelist;
504 actionfreelist = actionfreelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000505 return newaction;
drh75897232000-05-29 14:26:00 +0000506}
507
drhe9278182007-07-18 18:16:29 +0000508/* Compare two actions for sorting purposes. Return negative, zero, or
509** positive if the first action is less than, equal to, or greater than
510** the first
511*/
512static int actioncmp(
513 struct action *ap1,
514 struct action *ap2
515){
drh75897232000-05-29 14:26:00 +0000516 int rc;
517 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000518 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000519 rc = (int)ap1->type - (int)ap2->type;
520 }
drh3bd48ab2015-09-07 18:23:37 +0000521 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000522 rc = ap1->x.rp->index - ap2->x.rp->index;
523 }
drhe594bc32009-11-03 13:02:25 +0000524 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000525 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000526 }
drh75897232000-05-29 14:26:00 +0000527 return rc;
528}
529
530/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000531static struct action *Action_sort(
532 struct action *ap
533){
534 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
535 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000536 return ap;
537}
538
icculus9e44cf12010-02-14 17:14:22 +0000539void Action_add(
540 struct action **app,
541 enum e_action type,
542 struct symbol *sp,
543 char *arg
544){
545 struct action *newaction;
546 newaction = Action_new();
547 newaction->next = *app;
548 *app = newaction;
549 newaction->type = type;
550 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000551 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000552 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000553 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000554 }else{
icculus9e44cf12010-02-14 17:14:22 +0000555 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000556 }
557}
drh8b582012003-10-21 13:16:03 +0000558/********************** New code to implement the "acttab" module ***********/
559/*
560** This module implements routines use to construct the yy_action[] table.
561*/
562
563/*
564** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000565** the following structure.
566**
567** The yy_action table maps the pair (state_number, lookahead) into an
568** action_number. The table is an array of integers pairs. The state_number
569** determines an initial offset into the yy_action array. The lookahead
570** value is then added to this initial offset to get an index X into the
571** yy_action array. If the aAction[X].lookahead equals the value of the
572** of the lookahead input, then the value of the action_number output is
573** aAction[X].action. If the lookaheads do not match then the
574** default action for the state_number is returned.
575**
576** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000577** into aLookahead[] using multiple calls to acttab_action(). Then the
578** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000579** array with a single call to acttab_insert(). The acttab_insert() call
580** also resets the aLookahead[] array in preparation for the next
581** state number.
drh8b582012003-10-21 13:16:03 +0000582*/
icculus9e44cf12010-02-14 17:14:22 +0000583struct lookahead_action {
584 int lookahead; /* Value of the lookahead token */
585 int action; /* Action to take on the given lookahead */
586};
drh8b582012003-10-21 13:16:03 +0000587typedef struct acttab acttab;
588struct acttab {
589 int nAction; /* Number of used slots in aAction[] */
590 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000591 struct lookahead_action
592 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000593 *aLookahead; /* A single new transaction set */
594 int mnLookahead; /* Minimum aLookahead[].lookahead */
595 int mnAction; /* Action associated with mnLookahead */
596 int mxLookahead; /* Maximum aLookahead[].lookahead */
597 int nLookahead; /* Used slots in aLookahead[] */
598 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
drh3a9d6c72017-12-25 04:15:38 +0000599 int nterminal; /* Number of terminal symbols */
600 int nsymbol; /* total number of symbols */
drh8b582012003-10-21 13:16:03 +0000601};
602
603/* Return the number of entries in the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +0000604#define acttab_lookahead_size(X) ((X)->nAction)
drh8b582012003-10-21 13:16:03 +0000605
606/* The value for the N-th entry in yy_action */
607#define acttab_yyaction(X,N) ((X)->aAction[N].action)
608
609/* The value for the N-th entry in yy_lookahead */
610#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
611
612/* Free all memory associated with the given acttab */
613void acttab_free(acttab *p){
614 free( p->aAction );
615 free( p->aLookahead );
616 free( p );
617}
618
619/* Allocate a new acttab structure */
drh3a9d6c72017-12-25 04:15:38 +0000620acttab *acttab_alloc(int nsymbol, int nterminal){
icculus9e44cf12010-02-14 17:14:22 +0000621 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000622 if( p==0 ){
623 fprintf(stderr,"Unable to allocate memory for a new acttab.");
624 exit(1);
625 }
626 memset(p, 0, sizeof(*p));
drh3a9d6c72017-12-25 04:15:38 +0000627 p->nsymbol = nsymbol;
628 p->nterminal = nterminal;
drh8b582012003-10-21 13:16:03 +0000629 return p;
630}
631
drh06f60d82017-04-14 19:46:12 +0000632/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000633**
634** This routine is called once for each lookahead for a particular
635** state.
drh8b582012003-10-21 13:16:03 +0000636*/
637void acttab_action(acttab *p, int lookahead, int action){
638 if( p->nLookahead>=p->nLookaheadAlloc ){
639 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000640 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000641 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
642 if( p->aLookahead==0 ){
643 fprintf(stderr,"malloc failed\n");
644 exit(1);
645 }
646 }
647 if( p->nLookahead==0 ){
648 p->mxLookahead = lookahead;
649 p->mnLookahead = lookahead;
650 p->mnAction = action;
651 }else{
652 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
653 if( p->mnLookahead>lookahead ){
654 p->mnLookahead = lookahead;
655 p->mnAction = action;
656 }
657 }
658 p->aLookahead[p->nLookahead].lookahead = lookahead;
659 p->aLookahead[p->nLookahead].action = action;
660 p->nLookahead++;
661}
662
663/*
664** Add the transaction set built up with prior calls to acttab_action()
665** into the current action table. Then reset the transaction set back
666** to an empty set in preparation for a new round of acttab_action() calls.
667**
668** Return the offset into the action table of the new transaction.
drh3a9d6c72017-12-25 04:15:38 +0000669**
670** If the makeItSafe parameter is true, then the offset is chosen so that
671** it is impossible to overread the yy_lookaside[] table regardless of
672** the lookaside token. This is done for the terminal symbols, as they
673** come from external inputs and can contain syntax errors. When makeItSafe
674** is false, there is more flexibility in selecting offsets, resulting in
675** a smaller table. For non-terminal symbols, which are never syntax errors,
676** makeItSafe can be false.
drh8b582012003-10-21 13:16:03 +0000677*/
drh3a9d6c72017-12-25 04:15:38 +0000678int acttab_insert(acttab *p, int makeItSafe){
679 int i, j, k, n, end;
drh8b582012003-10-21 13:16:03 +0000680 assert( p->nLookahead>0 );
681
682 /* Make sure we have enough space to hold the expanded action table
683 ** in the worst case. The worst case occurs if the transaction set
684 ** must be appended to the current action table
685 */
drh3a9d6c72017-12-25 04:15:38 +0000686 n = p->nsymbol + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000687 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000688 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000689 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000690 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000691 sizeof(p->aAction[0])*p->nActionAlloc);
692 if( p->aAction==0 ){
693 fprintf(stderr,"malloc failed\n");
694 exit(1);
695 }
drhfdbf9282003-10-21 16:34:41 +0000696 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000697 p->aAction[i].lookahead = -1;
698 p->aAction[i].action = -1;
699 }
700 }
701
drh06f60d82017-04-14 19:46:12 +0000702 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000703 ** duplicate of the current transaction set. Fall out of the loop
704 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000705 **
706 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
707 */
drh3a9d6c72017-12-25 04:15:38 +0000708 end = makeItSafe ? p->mnLookahead : 0;
709 for(i=p->nAction-1; i>=end; i--){
drhf16371d2009-11-03 19:18:31 +0000710 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000711 /* All lookaheads and actions in the aLookahead[] transaction
712 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000713 if( p->aAction[i].action!=p->mnAction ) continue;
714 for(j=0; j<p->nLookahead; j++){
715 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
716 if( k<0 || k>=p->nAction ) break;
717 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
718 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
719 }
720 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000721
722 /* No possible lookahead value that is not in the aLookahead[]
723 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000724 n = 0;
725 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000726 if( p->aAction[j].lookahead<0 ) continue;
727 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000728 }
drhfdbf9282003-10-21 16:34:41 +0000729 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000730 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000731 }
drh8b582012003-10-21 13:16:03 +0000732 }
733 }
drh8dc3e8f2010-01-07 03:53:03 +0000734
735 /* If no existing offsets exactly match the current transaction, find an
736 ** an empty offset in the aAction[] table in which we can add the
737 ** aLookahead[] transaction.
738 */
drh3a9d6c72017-12-25 04:15:38 +0000739 if( i<end ){
drh8dc3e8f2010-01-07 03:53:03 +0000740 /* Look for holes in the aAction[] table that fit the current
741 ** aLookahead[] transaction. Leave i set to the offset of the hole.
742 ** If no holes are found, i is left at p->nAction, which means the
743 ** transaction will be appended. */
drh3a9d6c72017-12-25 04:15:38 +0000744 i = makeItSafe ? p->mnLookahead : 0;
745 for(; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000746 if( p->aAction[i].lookahead<0 ){
747 for(j=0; j<p->nLookahead; j++){
748 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
749 if( k<0 ) break;
750 if( p->aAction[k].lookahead>=0 ) break;
751 }
752 if( j<p->nLookahead ) continue;
753 for(j=0; j<p->nAction; j++){
754 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
755 }
756 if( j==p->nAction ){
757 break; /* Fits in empty slots */
758 }
759 }
760 }
761 }
drh8b582012003-10-21 13:16:03 +0000762 /* Insert transaction set at index i. */
drh3a9d6c72017-12-25 04:15:38 +0000763#if 0
764 printf("Acttab:");
765 for(j=0; j<p->nLookahead; j++){
766 printf(" %d", p->aLookahead[j].lookahead);
767 }
768 printf(" inserted at %d\n", i);
769#endif
drh8b582012003-10-21 13:16:03 +0000770 for(j=0; j<p->nLookahead; j++){
771 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
772 p->aAction[k] = p->aLookahead[j];
773 if( k>=p->nAction ) p->nAction = k+1;
774 }
drh4396c612017-12-27 15:21:16 +0000775 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
drh8b582012003-10-21 13:16:03 +0000776 p->nLookahead = 0;
777
778 /* Return the offset that is added to the lookahead in order to get the
779 ** index into yy_action of the action */
780 return i - p->mnLookahead;
781}
782
drh3a9d6c72017-12-25 04:15:38 +0000783/*
784** Return the size of the action table without the trailing syntax error
785** entries.
786*/
787int acttab_action_size(acttab *p){
788 int n = p->nAction;
789 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
790 return n;
791}
792
drh75897232000-05-29 14:26:00 +0000793/********************** From the file "build.c" *****************************/
794/*
795** Routines to construction the finite state machine for the LEMON
796** parser generator.
797*/
798
799/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000800**
drh75897232000-05-29 14:26:00 +0000801** Those rules which have a precedence symbol coded in the input
802** grammar using the "[symbol]" construct will already have the
803** rp->precsym field filled. Other rules take as their precedence
804** symbol the first RHS symbol with a defined precedence. If there
805** are not RHS symbols with a defined precedence, the precedence
806** symbol field is left blank.
807*/
icculus9e44cf12010-02-14 17:14:22 +0000808void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000809{
810 struct rule *rp;
811 for(rp=xp->rule; rp; rp=rp->next){
812 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000813 int i, j;
814 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
815 struct symbol *sp = rp->rhs[i];
816 if( sp->type==MULTITERMINAL ){
817 for(j=0; j<sp->nsubsym; j++){
818 if( sp->subsym[j]->prec>=0 ){
819 rp->precsym = sp->subsym[j];
820 break;
821 }
822 }
823 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000824 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000825 }
drh75897232000-05-29 14:26:00 +0000826 }
827 }
828 }
829 return;
830}
831
832/* Find all nonterminals which will generate the empty string.
833** Then go back and compute the first sets of every nonterminal.
834** The first set is the set of all terminal symbols which can begin
835** a string generated by that nonterminal.
836*/
icculus9e44cf12010-02-14 17:14:22 +0000837void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000838{
drhfd405312005-11-06 04:06:59 +0000839 int i, j;
drh75897232000-05-29 14:26:00 +0000840 struct rule *rp;
841 int progress;
842
843 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000844 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000845 }
846 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
847 lemp->symbols[i]->firstset = SetNew();
848 }
849
850 /* First compute all lambdas */
851 do{
852 progress = 0;
853 for(rp=lemp->rule; rp; rp=rp->next){
854 if( rp->lhs->lambda ) continue;
855 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000856 struct symbol *sp = rp->rhs[i];
857 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
858 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000859 }
860 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000861 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000862 progress = 1;
863 }
864 }
865 }while( progress );
866
867 /* Now compute all first sets */
868 do{
869 struct symbol *s1, *s2;
870 progress = 0;
871 for(rp=lemp->rule; rp; rp=rp->next){
872 s1 = rp->lhs;
873 for(i=0; i<rp->nrhs; i++){
874 s2 = rp->rhs[i];
875 if( s2->type==TERMINAL ){
876 progress += SetAdd(s1->firstset,s2->index);
877 break;
drhfd405312005-11-06 04:06:59 +0000878 }else if( s2->type==MULTITERMINAL ){
879 for(j=0; j<s2->nsubsym; j++){
880 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
881 }
882 break;
drhf2f105d2012-08-20 15:53:54 +0000883 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000884 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000885 }else{
drh75897232000-05-29 14:26:00 +0000886 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000887 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000888 }
drh75897232000-05-29 14:26:00 +0000889 }
890 }
891 }while( progress );
892 return;
893}
894
895/* Compute all LR(0) states for the grammar. Links
896** are added to between some states so that the LR(1) follow sets
897** can be computed later.
898*/
icculus9e44cf12010-02-14 17:14:22 +0000899PRIVATE struct state *getstate(struct lemon *); /* forward reference */
900void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000901{
902 struct symbol *sp;
903 struct rule *rp;
904
905 Configlist_init();
906
907 /* Find the start symbol */
908 if( lemp->start ){
909 sp = Symbol_find(lemp->start);
910 if( sp==0 ){
911 ErrorMsg(lemp->filename,0,
912"The specified start symbol \"%s\" is not \
913in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000914symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000915 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000916 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000917 }
918 }else{
drh4ef07702016-03-16 19:45:54 +0000919 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000920 }
921
922 /* Make sure the start symbol doesn't occur on the right-hand side of
923 ** any rule. Report an error if it does. (YACC would generate a new
924 ** start symbol in this case.) */
925 for(rp=lemp->rule; rp; rp=rp->next){
926 int i;
927 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000928 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000929 ErrorMsg(lemp->filename,0,
930"The start symbol \"%s\" occurs on the \
931right-hand side of a rule. This will result in a parser which \
932does not work properly.",sp->name);
933 lemp->errorcnt++;
934 }
935 }
936 }
937
938 /* The basis configuration set for the first state
939 ** is all rules which have the start symbol as their
940 ** left-hand side */
941 for(rp=sp->rule; rp; rp=rp->nextlhs){
942 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000943 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000944 newcfp = Configlist_addbasis(rp,0);
945 SetAdd(newcfp->fws,0);
946 }
947
948 /* Compute the first state. All other states will be
949 ** computed automatically during the computation of the first one.
950 ** The returned pointer to the first state is not used. */
951 (void)getstate(lemp);
952 return;
953}
954
955/* Return a pointer to a state which is described by the configuration
956** list which has been built from calls to Configlist_add.
957*/
icculus9e44cf12010-02-14 17:14:22 +0000958PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
959PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000960{
961 struct config *cfp, *bp;
962 struct state *stp;
963
964 /* Extract the sorted basis of the new state. The basis was constructed
965 ** by prior calls to "Configlist_addbasis()". */
966 Configlist_sortbasis();
967 bp = Configlist_basis();
968
969 /* Get a state with the same basis */
970 stp = State_find(bp);
971 if( stp ){
972 /* A state with the same basis already exists! Copy all the follow-set
973 ** propagation links from the state under construction into the
974 ** preexisting state, then return a pointer to the preexisting state */
975 struct config *x, *y;
976 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
977 Plink_copy(&y->bplp,x->bplp);
978 Plink_delete(x->fplp);
979 x->fplp = x->bplp = 0;
980 }
981 cfp = Configlist_return();
982 Configlist_eat(cfp);
983 }else{
984 /* This really is a new state. Construct all the details */
985 Configlist_closure(lemp); /* Compute the configuration closure */
986 Configlist_sort(); /* Sort the configuration closure */
987 cfp = Configlist_return(); /* Get a pointer to the config list */
988 stp = State_new(); /* A new state structure */
989 MemoryCheck(stp);
990 stp->bp = bp; /* Remember the configuration basis */
991 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000992 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000993 stp->ap = 0; /* No actions, yet. */
994 State_insert(stp,stp->bp); /* Add to the state table */
995 buildshifts(lemp,stp); /* Recursively compute successor states */
996 }
997 return stp;
998}
999
drhfd405312005-11-06 04:06:59 +00001000/*
1001** Return true if two symbols are the same.
1002*/
icculus9e44cf12010-02-14 17:14:22 +00001003int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +00001004{
1005 int i;
1006 if( a==b ) return 1;
1007 if( a->type!=MULTITERMINAL ) return 0;
1008 if( b->type!=MULTITERMINAL ) return 0;
1009 if( a->nsubsym!=b->nsubsym ) return 0;
1010 for(i=0; i<a->nsubsym; i++){
1011 if( a->subsym[i]!=b->subsym[i] ) return 0;
1012 }
1013 return 1;
1014}
1015
drh75897232000-05-29 14:26:00 +00001016/* Construct all successor states to the given state. A "successor"
1017** state is any state which can be reached by a shift action.
1018*/
icculus9e44cf12010-02-14 17:14:22 +00001019PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +00001020{
1021 struct config *cfp; /* For looping thru the config closure of "stp" */
1022 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +00001023 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +00001024 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1025 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1026 struct state *newstp; /* A pointer to a successor state */
1027
1028 /* Each configuration becomes complete after it contibutes to a successor
1029 ** state. Initially, all configurations are incomplete */
1030 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1031
1032 /* Loop through all configurations of the state "stp" */
1033 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1034 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1035 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1036 Configlist_reset(); /* Reset the new config set */
1037 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1038
1039 /* For every configuration in the state "stp" which has the symbol "sp"
1040 ** following its dot, add the same configuration to the basis set under
1041 ** construction but with the dot shifted one symbol to the right. */
1042 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1043 if( bcfp->status==COMPLETE ) continue; /* Already used */
1044 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1045 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001046 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001047 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001048 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1049 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001050 }
1051
1052 /* Get a pointer to the state described by the basis configuration set
1053 ** constructed in the preceding loop */
1054 newstp = getstate(lemp);
1055
1056 /* The state "newstp" is reached from the state "stp" by a shift action
1057 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001058 if( sp->type==MULTITERMINAL ){
1059 int i;
1060 for(i=0; i<sp->nsubsym; i++){
1061 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1062 }
1063 }else{
1064 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1065 }
drh75897232000-05-29 14:26:00 +00001066 }
1067}
1068
1069/*
1070** Construct the propagation links
1071*/
icculus9e44cf12010-02-14 17:14:22 +00001072void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001073{
1074 int i;
1075 struct config *cfp, *other;
1076 struct state *stp;
1077 struct plink *plp;
1078
1079 /* Housekeeping detail:
1080 ** Add to every propagate link a pointer back to the state to
1081 ** which the link is attached. */
1082 for(i=0; i<lemp->nstate; i++){
1083 stp = lemp->sorted[i];
1084 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1085 cfp->stp = stp;
1086 }
1087 }
1088
1089 /* Convert all backlinks into forward links. Only the forward
1090 ** links are used in the follow-set computation. */
1091 for(i=0; i<lemp->nstate; i++){
1092 stp = lemp->sorted[i];
1093 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1094 for(plp=cfp->bplp; plp; plp=plp->next){
1095 other = plp->cfp;
1096 Plink_add(&other->fplp,cfp);
1097 }
1098 }
1099 }
1100}
1101
1102/* Compute all followsets.
1103**
1104** A followset is the set of all symbols which can come immediately
1105** after a configuration.
1106*/
icculus9e44cf12010-02-14 17:14:22 +00001107void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001108{
1109 int i;
1110 struct config *cfp;
1111 struct plink *plp;
1112 int progress;
1113 int change;
1114
1115 for(i=0; i<lemp->nstate; i++){
1116 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1117 cfp->status = INCOMPLETE;
1118 }
1119 }
drh06f60d82017-04-14 19:46:12 +00001120
drh75897232000-05-29 14:26:00 +00001121 do{
1122 progress = 0;
1123 for(i=0; i<lemp->nstate; i++){
1124 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1125 if( cfp->status==COMPLETE ) continue;
1126 for(plp=cfp->fplp; plp; plp=plp->next){
1127 change = SetUnion(plp->cfp->fws,cfp->fws);
1128 if( change ){
1129 plp->cfp->status = INCOMPLETE;
1130 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001131 }
1132 }
drh75897232000-05-29 14:26:00 +00001133 cfp->status = COMPLETE;
1134 }
1135 }
1136 }while( progress );
1137}
1138
drh3cb2f6e2012-01-09 14:19:05 +00001139static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001140
1141/* Compute the reduce actions, and resolve conflicts.
1142*/
icculus9e44cf12010-02-14 17:14:22 +00001143void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001144{
1145 int i,j;
1146 struct config *cfp;
1147 struct state *stp;
1148 struct symbol *sp;
1149 struct rule *rp;
1150
drh06f60d82017-04-14 19:46:12 +00001151 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001152 ** A reduce action is added for each element of the followset of
1153 ** a configuration which has its dot at the extreme right.
1154 */
1155 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1156 stp = lemp->sorted[i];
1157 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1158 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1159 for(j=0; j<lemp->nterminal; j++){
1160 if( SetFind(cfp->fws,j) ){
1161 /* Add a reduce action to the state "stp" which will reduce by the
1162 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001163 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001164 }
drhf2f105d2012-08-20 15:53:54 +00001165 }
drh75897232000-05-29 14:26:00 +00001166 }
1167 }
1168 }
1169
1170 /* Add the accepting token */
1171 if( lemp->start ){
1172 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001173 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001174 }else{
drh4ef07702016-03-16 19:45:54 +00001175 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001176 }
1177 /* Add to the first state (which is always the starting state of the
1178 ** finite state machine) an action to ACCEPT if the lookahead is the
1179 ** start nonterminal. */
1180 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1181
1182 /* Resolve conflicts */
1183 for(i=0; i<lemp->nstate; i++){
1184 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001185 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001186 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001187 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001188 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001189 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1190 /* The two actions "ap" and "nap" have the same lookahead.
1191 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001192 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001193 }
1194 }
1195 }
1196
1197 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001198 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001199 for(i=0; i<lemp->nstate; i++){
1200 struct action *ap;
1201 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001202 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001203 }
1204 }
1205 for(rp=lemp->rule; rp; rp=rp->next){
1206 if( rp->canReduce ) continue;
1207 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1208 lemp->errorcnt++;
1209 }
1210}
1211
1212/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001213** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001214**
1215** NO LONGER TRUE:
1216** To resolve a conflict, first look to see if either action
1217** is on an error rule. In that case, take the action which
1218** is not associated with the error rule. If neither or both
1219** actions are associated with an error rule, then try to
1220** use precedence to resolve the conflict.
1221**
1222** If either action is a SHIFT, then it must be apx. This
1223** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1224*/
icculus9e44cf12010-02-14 17:14:22 +00001225static int resolve_conflict(
1226 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001227 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001228){
drh75897232000-05-29 14:26:00 +00001229 struct symbol *spx, *spy;
1230 int errcnt = 0;
1231 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001232 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001233 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001234 errcnt++;
1235 }
drh75897232000-05-29 14:26:00 +00001236 if( apx->type==SHIFT && apy->type==REDUCE ){
1237 spx = apx->sp;
1238 spy = apy->x.rp->precsym;
1239 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1240 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001241 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001242 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001243 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001244 apy->type = RD_RESOLVED;
1245 }else if( spx->prec<spy->prec ){
1246 apx->type = SH_RESOLVED;
1247 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1248 apy->type = RD_RESOLVED; /* associativity */
1249 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1250 apx->type = SH_RESOLVED;
1251 }else{
1252 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001253 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001254 }
1255 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1256 spx = apx->x.rp->precsym;
1257 spy = apy->x.rp->precsym;
1258 if( spx==0 || spy==0 || spx->prec<0 ||
1259 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001260 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001261 errcnt++;
1262 }else if( spx->prec>spy->prec ){
1263 apy->type = RD_RESOLVED;
1264 }else if( spx->prec<spy->prec ){
1265 apx->type = RD_RESOLVED;
1266 }
1267 }else{
drh06f60d82017-04-14 19:46:12 +00001268 assert(
drhb59499c2002-02-23 18:45:13 +00001269 apx->type==SH_RESOLVED ||
1270 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001271 apx->type==SSCONFLICT ||
1272 apx->type==SRCONFLICT ||
1273 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001274 apy->type==SH_RESOLVED ||
1275 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001276 apy->type==SSCONFLICT ||
1277 apy->type==SRCONFLICT ||
1278 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001279 );
1280 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1281 ** REDUCEs on the list. If we reach this point it must be because
1282 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001283 }
1284 return errcnt;
1285}
1286/********************* From the file "configlist.c" *************************/
1287/*
1288** Routines to processing a configuration list and building a state
1289** in the LEMON parser generator.
1290*/
1291
1292static struct config *freelist = 0; /* List of free configurations */
1293static struct config *current = 0; /* Top of list of configurations */
1294static struct config **currentend = 0; /* Last on list of configs */
1295static struct config *basis = 0; /* Top of list of basis configs */
1296static struct config **basisend = 0; /* End of list of basis configs */
1297
1298/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001299PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001300 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001301 if( freelist==0 ){
1302 int i;
1303 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001304 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001305 if( freelist==0 ){
1306 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1307 exit(1);
1308 }
1309 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1310 freelist[amt-1].next = 0;
1311 }
icculus9e44cf12010-02-14 17:14:22 +00001312 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001313 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001314 return newcfg;
drh75897232000-05-29 14:26:00 +00001315}
1316
1317/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001318PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001319{
1320 old->next = freelist;
1321 freelist = old;
1322}
1323
1324/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001325void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001326 current = 0;
1327 currentend = &current;
1328 basis = 0;
1329 basisend = &basis;
1330 Configtable_init();
1331 return;
1332}
1333
1334/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001335void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001336 current = 0;
1337 currentend = &current;
1338 basis = 0;
1339 basisend = &basis;
1340 Configtable_clear(0);
1341 return;
1342}
1343
1344/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001345struct config *Configlist_add(
1346 struct rule *rp, /* The rule */
1347 int dot /* Index into the RHS of the rule where the dot goes */
1348){
drh75897232000-05-29 14:26:00 +00001349 struct config *cfp, model;
1350
1351 assert( currentend!=0 );
1352 model.rp = rp;
1353 model.dot = dot;
1354 cfp = Configtable_find(&model);
1355 if( cfp==0 ){
1356 cfp = newconfig();
1357 cfp->rp = rp;
1358 cfp->dot = dot;
1359 cfp->fws = SetNew();
1360 cfp->stp = 0;
1361 cfp->fplp = cfp->bplp = 0;
1362 cfp->next = 0;
1363 cfp->bp = 0;
1364 *currentend = cfp;
1365 currentend = &cfp->next;
1366 Configtable_insert(cfp);
1367 }
1368 return cfp;
1369}
1370
1371/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001372struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001373{
1374 struct config *cfp, model;
1375
1376 assert( basisend!=0 );
1377 assert( currentend!=0 );
1378 model.rp = rp;
1379 model.dot = dot;
1380 cfp = Configtable_find(&model);
1381 if( cfp==0 ){
1382 cfp = newconfig();
1383 cfp->rp = rp;
1384 cfp->dot = dot;
1385 cfp->fws = SetNew();
1386 cfp->stp = 0;
1387 cfp->fplp = cfp->bplp = 0;
1388 cfp->next = 0;
1389 cfp->bp = 0;
1390 *currentend = cfp;
1391 currentend = &cfp->next;
1392 *basisend = cfp;
1393 basisend = &cfp->bp;
1394 Configtable_insert(cfp);
1395 }
1396 return cfp;
1397}
1398
1399/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001400void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001401{
1402 struct config *cfp, *newcfp;
1403 struct rule *rp, *newrp;
1404 struct symbol *sp, *xsp;
1405 int i, dot;
1406
1407 assert( currentend!=0 );
1408 for(cfp=current; cfp; cfp=cfp->next){
1409 rp = cfp->rp;
1410 dot = cfp->dot;
1411 if( dot>=rp->nrhs ) continue;
1412 sp = rp->rhs[dot];
1413 if( sp->type==NONTERMINAL ){
1414 if( sp->rule==0 && sp!=lemp->errsym ){
1415 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1416 sp->name);
1417 lemp->errorcnt++;
1418 }
1419 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1420 newcfp = Configlist_add(newrp,0);
1421 for(i=dot+1; i<rp->nrhs; i++){
1422 xsp = rp->rhs[i];
1423 if( xsp->type==TERMINAL ){
1424 SetAdd(newcfp->fws,xsp->index);
1425 break;
drhfd405312005-11-06 04:06:59 +00001426 }else if( xsp->type==MULTITERMINAL ){
1427 int k;
1428 for(k=0; k<xsp->nsubsym; k++){
1429 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1430 }
1431 break;
drhf2f105d2012-08-20 15:53:54 +00001432 }else{
drh75897232000-05-29 14:26:00 +00001433 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001434 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001435 }
1436 }
drh75897232000-05-29 14:26:00 +00001437 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1438 }
1439 }
1440 }
1441 return;
1442}
1443
1444/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001445void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001446 current = (struct config*)msort((char*)current,(char**)&(current->next),
1447 Configcmp);
drh75897232000-05-29 14:26:00 +00001448 currentend = 0;
1449 return;
1450}
1451
1452/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001453void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001454 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1455 Configcmp);
drh75897232000-05-29 14:26:00 +00001456 basisend = 0;
1457 return;
1458}
1459
1460/* Return a pointer to the head of the configuration list and
1461** reset the list */
drh14d88552017-04-14 19:44:15 +00001462struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001463 struct config *old;
1464 old = current;
1465 current = 0;
1466 currentend = 0;
1467 return old;
1468}
1469
1470/* Return a pointer to the head of the configuration list and
1471** reset the list */
drh14d88552017-04-14 19:44:15 +00001472struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001473 struct config *old;
1474 old = basis;
1475 basis = 0;
1476 basisend = 0;
1477 return old;
1478}
1479
1480/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001481void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001482{
1483 struct config *nextcfp;
1484 for(; cfp; cfp=nextcfp){
1485 nextcfp = cfp->next;
1486 assert( cfp->fplp==0 );
1487 assert( cfp->bplp==0 );
1488 if( cfp->fws ) SetFree(cfp->fws);
1489 deleteconfig(cfp);
1490 }
1491 return;
1492}
1493/***************** From the file "error.c" *********************************/
1494/*
1495** Code for printing error message.
1496*/
1497
drhf9a2e7b2003-04-15 01:49:48 +00001498void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001499 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001500 fprintf(stderr, "%s:%d: ", filename, lineno);
1501 va_start(ap, format);
1502 vfprintf(stderr,format,ap);
1503 va_end(ap);
1504 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001505}
1506/**************** From the file "main.c" ************************************/
1507/*
1508** Main program file for the LEMON parser generator.
1509*/
1510
1511/* Report an out-of-memory condition and abort. This function
1512** is used mostly by the "MemoryCheck" macro in struct.h
1513*/
drh14d88552017-04-14 19:44:15 +00001514void memory_error(void){
drh75897232000-05-29 14:26:00 +00001515 fprintf(stderr,"Out of memory. Aborting...\n");
1516 exit(1);
1517}
1518
drh6d08b4d2004-07-20 12:45:22 +00001519static int nDefine = 0; /* Number of -D options on the command line */
1520static char **azDefine = 0; /* Name of the -D macros */
1521
1522/* This routine is called with the argument to each -D command-line option.
1523** Add the macro defined to the azDefine array.
1524*/
1525static void handle_D_option(char *z){
1526 char **paz;
1527 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001528 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001529 if( azDefine==0 ){
1530 fprintf(stderr,"out of memory\n");
1531 exit(1);
1532 }
1533 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001534 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001535 if( *paz==0 ){
1536 fprintf(stderr,"out of memory\n");
1537 exit(1);
1538 }
drh898799f2014-01-10 23:21:00 +00001539 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001540 for(z=*paz; *z && *z!='='; z++){}
1541 *z = 0;
1542}
1543
drh9f88e6d2018-04-20 20:47:49 +00001544/* Rember the name of the output directory
1545*/
1546static char *outputDir = NULL;
1547static void handle_d_option(char *z){
1548 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1549 if( outputDir==0 ){
1550 fprintf(stderr,"out of memory\n");
1551 exit(1);
1552 }
1553 lemon_strcpy(outputDir, z);
1554}
1555
icculus3e143bd2010-02-14 00:48:49 +00001556static char *user_templatename = NULL;
1557static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001558 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001559 if( user_templatename==0 ){
1560 memory_error();
1561 }
drh898799f2014-01-10 23:21:00 +00001562 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001563}
drh75897232000-05-29 14:26:00 +00001564
drh711c9812016-05-23 14:24:31 +00001565/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001566static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1567 struct rule *pFirst = 0;
1568 struct rule **ppPrev = &pFirst;
1569 while( pA && pB ){
1570 if( pA->iRule<pB->iRule ){
1571 *ppPrev = pA;
1572 ppPrev = &pA->next;
1573 pA = pA->next;
1574 }else{
1575 *ppPrev = pB;
1576 ppPrev = &pB->next;
1577 pB = pB->next;
1578 }
1579 }
1580 if( pA ){
1581 *ppPrev = pA;
1582 }else{
1583 *ppPrev = pB;
1584 }
1585 return pFirst;
1586}
1587
1588/*
1589** Sort a list of rules in order of increasing iRule value
1590*/
1591static struct rule *Rule_sort(struct rule *rp){
1592 int i;
1593 struct rule *pNext;
1594 struct rule *x[32];
1595 memset(x, 0, sizeof(x));
1596 while( rp ){
1597 pNext = rp->next;
1598 rp->next = 0;
1599 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1600 rp = Rule_merge(x[i], rp);
1601 x[i] = 0;
1602 }
1603 x[i] = rp;
1604 rp = pNext;
1605 }
1606 rp = 0;
1607 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1608 rp = Rule_merge(x[i], rp);
1609 }
1610 return rp;
1611}
1612
drhc75e0162015-09-07 02:23:02 +00001613/* forward reference */
1614static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1615
1616/* Print a single line of the "Parser Stats" output
1617*/
1618static void stats_line(const char *zLabel, int iValue){
1619 int nLabel = lemonStrlen(zLabel);
1620 printf(" %s%.*s %5d\n", zLabel,
1621 35-nLabel, "................................",
1622 iValue);
1623}
1624
drh75897232000-05-29 14:26:00 +00001625/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001626int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001627{
1628 static int version = 0;
1629 static int rpflag = 0;
1630 static int basisflag = 0;
1631 static int compress = 0;
1632 static int quiet = 0;
1633 static int statistics = 0;
1634 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001635 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001636 static int noResort = 0;
drhfe03dac2019-11-26 02:22:39 +00001637 static int sqlFlag = 0;
drh9f88e6d2018-04-20 20:47:49 +00001638
drh75897232000-05-29 14:26:00 +00001639 static struct s_options options[] = {
1640 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1641 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh9f88e6d2018-04-20 20:47:49 +00001642 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
drh6d08b4d2004-07-20 12:45:22 +00001643 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001644 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001645 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001646 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001647 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1648 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001649 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001650 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1651 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001652 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001653 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001654 {OPT_FLAG, "s", (char*)&statistics,
1655 "Print parser stats to standard output."},
drhfe03dac2019-11-26 02:22:39 +00001656 {OPT_FLAG, "S", (char*)&sqlFlag,
1657 "Generate the *.sql file describing the parser tables."},
drh75897232000-05-29 14:26:00 +00001658 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001659 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1660 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001661 {OPT_FLAG,0,0,0}
1662 };
1663 int i;
icculus42585cf2010-02-14 05:19:56 +00001664 int exitcode;
drh75897232000-05-29 14:26:00 +00001665 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001666 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001667
drhb0c86772000-06-02 23:21:26 +00001668 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001669 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001670 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001671 exit(0);
drh75897232000-05-29 14:26:00 +00001672 }
drhb0c86772000-06-02 23:21:26 +00001673 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001674 fprintf(stderr,"Exactly one filename argument is required.\n");
1675 exit(1);
1676 }
drh954f6b42006-06-13 13:27:46 +00001677 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001678 lem.errorcnt = 0;
1679
1680 /* Initialize the machine */
1681 Strsafe_init();
1682 Symbol_init();
1683 State_init();
1684 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001685 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001686 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001687 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001688 Symbol_new("$");
drh75897232000-05-29 14:26:00 +00001689
1690 /* Parse the input file */
1691 Parse(&lem);
1692 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001693 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001694 fprintf(stderr,"Empty grammar.\n");
1695 exit(1);
1696 }
drhed0c15b2018-04-16 14:31:34 +00001697 lem.errsym = Symbol_find("error");
drh75897232000-05-29 14:26:00 +00001698
1699 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001700 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001701 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001702 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001703 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1704 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1705 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1706 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1707 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1708 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001709 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001710 lem.nterminal = i;
1711
drh711c9812016-05-23 14:24:31 +00001712 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1713 ** reduce action C-code associated with them last, so that the switch()
1714 ** statement that selects reduction actions will have a smaller jump table.
1715 */
drh4ef07702016-03-16 19:45:54 +00001716 for(i=0, rp=lem.rule; rp; rp=rp->next){
1717 rp->iRule = rp->code ? i++ : -1;
1718 }
1719 for(rp=lem.rule; rp; rp=rp->next){
1720 if( rp->iRule<0 ) rp->iRule = i++;
1721 }
1722 lem.startRule = lem.rule;
1723 lem.rule = Rule_sort(lem.rule);
1724
drh75897232000-05-29 14:26:00 +00001725 /* Generate a reprint of the grammar, if requested on the command line */
1726 if( rpflag ){
1727 Reprint(&lem);
1728 }else{
1729 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001730 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001731
1732 /* Find the precedence for every production rule (that has one) */
1733 FindRulePrecedences(&lem);
1734
1735 /* Compute the lambda-nonterminals and the first-sets for every
1736 ** nonterminal */
1737 FindFirstSets(&lem);
1738
1739 /* Compute all LR(0) states. Also record follow-set propagation
1740 ** links so that the follow-set can be computed later */
1741 lem.nstate = 0;
1742 FindStates(&lem);
1743 lem.sorted = State_arrayof();
1744
1745 /* Tie up loose ends on the propagation links */
1746 FindLinks(&lem);
1747
1748 /* Compute the follow set of every reducible configuration */
1749 FindFollowSets(&lem);
1750
1751 /* Compute the action tables */
1752 FindActions(&lem);
1753
1754 /* Compress the action tables */
1755 if( compress==0 ) CompressTables(&lem);
1756
drhada354d2005-11-05 15:03:59 +00001757 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001758 ** occur at the end. This is an optimization that helps make the
1759 ** generated parser tables smaller. */
1760 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001761
drh75897232000-05-29 14:26:00 +00001762 /* Generate a report of the parser generated. (the "y.output" file) */
1763 if( !quiet ) ReportOutput(&lem);
1764
1765 /* Generate the source code for the parser */
drhfe03dac2019-11-26 02:22:39 +00001766 ReportTable(&lem, mhflag, sqlFlag);
drh75897232000-05-29 14:26:00 +00001767
1768 /* Produce a header file for use by the scanner. (This step is
1769 ** omitted if the "-m" option is used because makeheaders will
1770 ** generate the file for us.) */
1771 if( !mhflag ) ReportHeader(&lem);
1772 }
1773 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001774 printf("Parser statistics:\n");
1775 stats_line("terminal symbols", lem.nterminal);
1776 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1777 stats_line("total symbols", lem.nsymbol);
1778 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001779 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001780 stats_line("conflicts", lem.nconflict);
1781 stats_line("action table entries", lem.nactiontab);
drh3a9d6c72017-12-25 04:15:38 +00001782 stats_line("lookahead table entries", lem.nlookaheadtab);
drhc75e0162015-09-07 02:23:02 +00001783 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001784 }
icculus8e158022010-02-16 16:09:03 +00001785 if( lem.nconflict > 0 ){
1786 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001787 }
1788
1789 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001790 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001791 exit(exitcode);
1792 return (exitcode);
drh75897232000-05-29 14:26:00 +00001793}
1794/******************** From the file "msort.c" *******************************/
1795/*
1796** A generic merge-sort program.
1797**
1798** USAGE:
1799** Let "ptr" be a pointer to some structure which is at the head of
1800** a null-terminated list. Then to sort the list call:
1801**
1802** ptr = msort(ptr,&(ptr->next),cmpfnc);
1803**
1804** In the above, "cmpfnc" is a pointer to a function which compares
1805** two instances of the structure and returns an integer, as in
1806** strcmp. The second argument is a pointer to the pointer to the
1807** second element of the linked list. This address is used to compute
1808** the offset to the "next" field within the structure. The offset to
1809** the "next" field must be constant for all structures in the list.
1810**
1811** The function returns a new pointer which is the head of the list
1812** after sorting.
1813**
1814** ALGORITHM:
1815** Merge-sort.
1816*/
1817
1818/*
1819** Return a pointer to the next structure in the linked list.
1820*/
drhd25d6922012-04-18 09:59:56 +00001821#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001822
1823/*
1824** Inputs:
1825** a: A sorted, null-terminated linked list. (May be null).
1826** b: A sorted, null-terminated linked list. (May be null).
1827** cmp: A pointer to the comparison function.
1828** offset: Offset in the structure to the "next" field.
1829**
1830** Return Value:
1831** A pointer to the head of a sorted list containing the elements
1832** of both a and b.
1833**
1834** Side effects:
1835** The "next" pointers for elements in the lists a and b are
1836** changed.
1837*/
drhe9278182007-07-18 18:16:29 +00001838static char *merge(
1839 char *a,
1840 char *b,
1841 int (*cmp)(const char*,const char*),
1842 int offset
1843){
drh75897232000-05-29 14:26:00 +00001844 char *ptr, *head;
1845
1846 if( a==0 ){
1847 head = b;
1848 }else if( b==0 ){
1849 head = a;
1850 }else{
drhe594bc32009-11-03 13:02:25 +00001851 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001852 ptr = a;
1853 a = NEXT(a);
1854 }else{
1855 ptr = b;
1856 b = NEXT(b);
1857 }
1858 head = ptr;
1859 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001860 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001861 NEXT(ptr) = a;
1862 ptr = a;
1863 a = NEXT(a);
1864 }else{
1865 NEXT(ptr) = b;
1866 ptr = b;
1867 b = NEXT(b);
1868 }
1869 }
1870 if( a ) NEXT(ptr) = a;
1871 else NEXT(ptr) = b;
1872 }
1873 return head;
1874}
1875
1876/*
1877** Inputs:
1878** list: Pointer to a singly-linked list of structures.
1879** next: Pointer to pointer to the second element of the list.
1880** cmp: A comparison function.
1881**
1882** Return Value:
1883** A pointer to the head of a sorted list containing the elements
1884** orginally in list.
1885**
1886** Side effects:
1887** The "next" pointers for elements in list are changed.
1888*/
1889#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001890static char *msort(
1891 char *list,
1892 char **next,
1893 int (*cmp)(const char*,const char*)
1894){
drhba99af52001-10-25 20:37:16 +00001895 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001896 char *ep;
1897 char *set[LISTSIZE];
1898 int i;
drh1cc0d112015-03-31 15:15:48 +00001899 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001900 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1901 while( list ){
1902 ep = list;
1903 list = NEXT(list);
1904 NEXT(ep) = 0;
1905 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1906 ep = merge(ep,set[i],cmp,offset);
1907 set[i] = 0;
1908 }
1909 set[i] = ep;
1910 }
1911 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001912 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001913 return ep;
1914}
1915/************************ From the file "option.c" **************************/
mistachkind9bc6e82019-05-10 16:16:19 +00001916static char **g_argv;
drh75897232000-05-29 14:26:00 +00001917static struct s_options *op;
1918static FILE *errstream;
1919
1920#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1921
1922/*
1923** Print the command line with a carrot pointing to the k-th character
1924** of the n-th field.
1925*/
icculus9e44cf12010-02-14 17:14:22 +00001926static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001927{
1928 int spcnt, i;
mistachkind9bc6e82019-05-10 16:16:19 +00001929 if( g_argv[0] ) fprintf(err,"%s",g_argv[0]);
1930 spcnt = lemonStrlen(g_argv[0]) + 1;
1931 for(i=1; i<n && g_argv[i]; i++){
1932 fprintf(err," %s",g_argv[i]);
1933 spcnt += lemonStrlen(g_argv[i])+1;
drh75897232000-05-29 14:26:00 +00001934 }
1935 spcnt += k;
mistachkind9bc6e82019-05-10 16:16:19 +00001936 for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
drh75897232000-05-29 14:26:00 +00001937 if( spcnt<20 ){
1938 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1939 }else{
1940 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1941 }
1942}
1943
1944/*
1945** Return the index of the N-th non-switch argument. Return -1
1946** if N is out of range.
1947*/
icculus9e44cf12010-02-14 17:14:22 +00001948static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001949{
1950 int i;
1951 int dashdash = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00001952 if( g_argv!=0 && *g_argv!=0 ){
1953 for(i=1; g_argv[i]; i++){
1954 if( dashdash || !ISOPT(g_argv[i]) ){
drh75897232000-05-29 14:26:00 +00001955 if( n==0 ) return i;
1956 n--;
1957 }
mistachkind9bc6e82019-05-10 16:16:19 +00001958 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
drh75897232000-05-29 14:26:00 +00001959 }
1960 }
1961 return -1;
1962}
1963
1964static char emsg[] = "Command line syntax error: ";
1965
1966/*
1967** Process a flag command line argument.
1968*/
icculus9e44cf12010-02-14 17:14:22 +00001969static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001970{
1971 int v;
1972 int errcnt = 0;
1973 int j;
1974 for(j=0; op[j].label; j++){
mistachkind9bc6e82019-05-10 16:16:19 +00001975 if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001976 }
mistachkind9bc6e82019-05-10 16:16:19 +00001977 v = g_argv[i][0]=='-' ? 1 : 0;
drh75897232000-05-29 14:26:00 +00001978 if( op[j].label==0 ){
1979 if( err ){
1980 fprintf(err,"%sundefined option.\n",emsg);
1981 errline(i,1,err);
1982 }
1983 errcnt++;
drh0325d392015-01-01 19:11:22 +00001984 }else if( op[j].arg==0 ){
1985 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001986 }else if( op[j].type==OPT_FLAG ){
1987 *((int*)op[j].arg) = v;
1988 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001989 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001990 }else if( op[j].type==OPT_FSTR ){
mistachkind9bc6e82019-05-10 16:16:19 +00001991 (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
drh75897232000-05-29 14:26:00 +00001992 }else{
1993 if( err ){
1994 fprintf(err,"%smissing argument on switch.\n",emsg);
1995 errline(i,1,err);
1996 }
1997 errcnt++;
1998 }
1999 return errcnt;
2000}
2001
2002/*
2003** Process a command line switch which has an argument.
2004*/
icculus9e44cf12010-02-14 17:14:22 +00002005static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00002006{
2007 int lv = 0;
2008 double dv = 0.0;
2009 char *sv = 0, *end;
2010 char *cp;
2011 int j;
2012 int errcnt = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00002013 cp = strchr(g_argv[i],'=');
drh43617e92006-03-06 20:55:46 +00002014 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00002015 *cp = 0;
2016 for(j=0; op[j].label; j++){
mistachkind9bc6e82019-05-10 16:16:19 +00002017 if( strcmp(g_argv[i],op[j].label)==0 ) break;
drh75897232000-05-29 14:26:00 +00002018 }
2019 *cp = '=';
2020 if( op[j].label==0 ){
2021 if( err ){
2022 fprintf(err,"%sundefined option.\n",emsg);
2023 errline(i,0,err);
2024 }
2025 errcnt++;
2026 }else{
2027 cp++;
2028 switch( op[j].type ){
2029 case OPT_FLAG:
2030 case OPT_FFLAG:
2031 if( err ){
2032 fprintf(err,"%soption requires an argument.\n",emsg);
2033 errline(i,0,err);
2034 }
2035 errcnt++;
2036 break;
2037 case OPT_DBL:
2038 case OPT_FDBL:
2039 dv = strtod(cp,&end);
2040 if( *end ){
2041 if( err ){
drh25473362015-09-04 18:03:45 +00002042 fprintf(err,
2043 "%sillegal character in floating-point argument.\n",emsg);
mistachkind9bc6e82019-05-10 16:16:19 +00002044 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
drh75897232000-05-29 14:26:00 +00002045 }
2046 errcnt++;
2047 }
2048 break;
2049 case OPT_INT:
2050 case OPT_FINT:
2051 lv = strtol(cp,&end,0);
2052 if( *end ){
2053 if( err ){
2054 fprintf(err,"%sillegal character in integer argument.\n",emsg);
mistachkind9bc6e82019-05-10 16:16:19 +00002055 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
drh75897232000-05-29 14:26:00 +00002056 }
2057 errcnt++;
2058 }
2059 break;
2060 case OPT_STR:
2061 case OPT_FSTR:
2062 sv = cp;
2063 break;
2064 }
2065 switch( op[j].type ){
2066 case OPT_FLAG:
2067 case OPT_FFLAG:
2068 break;
2069 case OPT_DBL:
2070 *(double*)(op[j].arg) = dv;
2071 break;
2072 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002073 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002074 break;
2075 case OPT_INT:
2076 *(int*)(op[j].arg) = lv;
2077 break;
2078 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002079 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002080 break;
2081 case OPT_STR:
2082 *(char**)(op[j].arg) = sv;
2083 break;
2084 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002085 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002086 break;
2087 }
2088 }
2089 return errcnt;
2090}
2091
icculus9e44cf12010-02-14 17:14:22 +00002092int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002093{
2094 int errcnt = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00002095 g_argv = a;
drh75897232000-05-29 14:26:00 +00002096 op = o;
2097 errstream = err;
mistachkind9bc6e82019-05-10 16:16:19 +00002098 if( g_argv && *g_argv && op ){
drh75897232000-05-29 14:26:00 +00002099 int i;
mistachkind9bc6e82019-05-10 16:16:19 +00002100 for(i=1; g_argv[i]; i++){
2101 if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
drh75897232000-05-29 14:26:00 +00002102 errcnt += handleflags(i,err);
mistachkind9bc6e82019-05-10 16:16:19 +00002103 }else if( strchr(g_argv[i],'=') ){
drh75897232000-05-29 14:26:00 +00002104 errcnt += handleswitch(i,err);
2105 }
2106 }
2107 }
2108 if( errcnt>0 ){
2109 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002110 OptPrint();
drh75897232000-05-29 14:26:00 +00002111 exit(1);
2112 }
2113 return 0;
2114}
2115
drh14d88552017-04-14 19:44:15 +00002116int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002117 int cnt = 0;
2118 int dashdash = 0;
2119 int i;
mistachkind9bc6e82019-05-10 16:16:19 +00002120 if( g_argv!=0 && g_argv[0]!=0 ){
2121 for(i=1; g_argv[i]; i++){
2122 if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
2123 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
drh75897232000-05-29 14:26:00 +00002124 }
2125 }
2126 return cnt;
2127}
2128
icculus9e44cf12010-02-14 17:14:22 +00002129char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002130{
2131 int i;
2132 i = argindex(n);
mistachkind9bc6e82019-05-10 16:16:19 +00002133 return i>=0 ? g_argv[i] : 0;
drh75897232000-05-29 14:26:00 +00002134}
2135
icculus9e44cf12010-02-14 17:14:22 +00002136void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002137{
2138 int i;
2139 i = argindex(n);
2140 if( i>=0 ) errline(i,0,errstream);
2141}
2142
drh14d88552017-04-14 19:44:15 +00002143void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002144 int i;
2145 int max, len;
2146 max = 0;
2147 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002148 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002149 switch( op[i].type ){
2150 case OPT_FLAG:
2151 case OPT_FFLAG:
2152 break;
2153 case OPT_INT:
2154 case OPT_FINT:
2155 len += 9; /* length of "<integer>" */
2156 break;
2157 case OPT_DBL:
2158 case OPT_FDBL:
2159 len += 6; /* length of "<real>" */
2160 break;
2161 case OPT_STR:
2162 case OPT_FSTR:
2163 len += 8; /* length of "<string>" */
2164 break;
2165 }
2166 if( len>max ) max = len;
2167 }
2168 for(i=0; op[i].label; i++){
2169 switch( op[i].type ){
2170 case OPT_FLAG:
2171 case OPT_FFLAG:
2172 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2173 break;
2174 case OPT_INT:
2175 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002176 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002177 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002178 break;
2179 case OPT_DBL:
2180 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002181 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002182 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002183 break;
2184 case OPT_STR:
2185 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002186 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002187 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002188 break;
2189 }
2190 }
2191}
2192/*********************** From the file "parse.c" ****************************/
2193/*
2194** Input file parser for the LEMON parser generator.
2195*/
2196
2197/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002198enum e_state {
2199 INITIALIZE,
2200 WAITING_FOR_DECL_OR_RULE,
2201 WAITING_FOR_DECL_KEYWORD,
2202 WAITING_FOR_DECL_ARG,
2203 WAITING_FOR_PRECEDENCE_SYMBOL,
2204 WAITING_FOR_ARROW,
2205 IN_RHS,
2206 LHS_ALIAS_1,
2207 LHS_ALIAS_2,
2208 LHS_ALIAS_3,
2209 RHS_ALIAS_1,
2210 RHS_ALIAS_2,
2211 PRECEDENCE_MARK_1,
2212 PRECEDENCE_MARK_2,
2213 RESYNC_AFTER_RULE_ERROR,
2214 RESYNC_AFTER_DECL_ERROR,
2215 WAITING_FOR_DESTRUCTOR_SYMBOL,
2216 WAITING_FOR_DATATYPE_SYMBOL,
2217 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002218 WAITING_FOR_WILDCARD_ID,
2219 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002220 WAITING_FOR_CLASS_TOKEN,
2221 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002222};
drh75897232000-05-29 14:26:00 +00002223struct pstate {
2224 char *filename; /* Name of the input file */
2225 int tokenlineno; /* Linenumber at which current token starts */
2226 int errorcnt; /* Number of errors so far */
2227 char *tokenstart; /* Text of current token */
2228 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002229 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002230 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002231 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002232 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002233 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002234 int nrhs; /* Number of right-hand side symbols seen */
2235 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002236 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002237 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002238 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002239 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002240 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002241 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002242 enum e_assoc declassoc; /* Assign this association to decl arguments */
2243 int preccounter; /* Assign this precedence to decl arguments */
2244 struct rule *firstrule; /* Pointer to first rule in the grammar */
2245 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2246};
2247
2248/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002249static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002250{
icculus9e44cf12010-02-14 17:14:22 +00002251 const char *x;
drh75897232000-05-29 14:26:00 +00002252 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2253#if 0
2254 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2255 x,psp->state);
2256#endif
2257 switch( psp->state ){
2258 case INITIALIZE:
2259 psp->prevrule = 0;
2260 psp->preccounter = 0;
2261 psp->firstrule = psp->lastrule = 0;
2262 psp->gp->nrule = 0;
2263 /* Fall thru to next case */
2264 case WAITING_FOR_DECL_OR_RULE:
2265 if( x[0]=='%' ){
2266 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002267 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002268 psp->lhs = Symbol_new(x);
2269 psp->nrhs = 0;
2270 psp->lhsalias = 0;
2271 psp->state = WAITING_FOR_ARROW;
2272 }else if( x[0]=='{' ){
2273 if( psp->prevrule==0 ){
2274 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002275"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002276fragment which begins on this line.");
2277 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002278 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002279 ErrorMsg(psp->filename,psp->tokenlineno,
2280"Code fragment beginning on this line is not the first \
2281to follow the previous rule.");
2282 psp->errorcnt++;
drhe94006e2019-12-10 20:41:48 +00002283 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
2284 psp->prevrule->neverReduce = 1;
drh75897232000-05-29 14:26:00 +00002285 }else{
2286 psp->prevrule->line = psp->tokenlineno;
2287 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002288 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002289 }
drh75897232000-05-29 14:26:00 +00002290 }else if( x[0]=='[' ){
2291 psp->state = PRECEDENCE_MARK_1;
2292 }else{
2293 ErrorMsg(psp->filename,psp->tokenlineno,
2294 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2295 x);
2296 psp->errorcnt++;
2297 }
2298 break;
2299 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002300 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002301 ErrorMsg(psp->filename,psp->tokenlineno,
2302 "The precedence symbol must be a terminal.");
2303 psp->errorcnt++;
2304 }else if( psp->prevrule==0 ){
2305 ErrorMsg(psp->filename,psp->tokenlineno,
2306 "There is no prior rule to assign precedence \"[%s]\".",x);
2307 psp->errorcnt++;
2308 }else if( psp->prevrule->precsym!=0 ){
2309 ErrorMsg(psp->filename,psp->tokenlineno,
2310"Precedence mark on this line is not the first \
2311to follow the previous rule.");
2312 psp->errorcnt++;
2313 }else{
2314 psp->prevrule->precsym = Symbol_new(x);
2315 }
2316 psp->state = PRECEDENCE_MARK_2;
2317 break;
2318 case PRECEDENCE_MARK_2:
2319 if( x[0]!=']' ){
2320 ErrorMsg(psp->filename,psp->tokenlineno,
2321 "Missing \"]\" on precedence mark.");
2322 psp->errorcnt++;
2323 }
2324 psp->state = WAITING_FOR_DECL_OR_RULE;
2325 break;
2326 case WAITING_FOR_ARROW:
2327 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2328 psp->state = IN_RHS;
2329 }else if( x[0]=='(' ){
2330 psp->state = LHS_ALIAS_1;
2331 }else{
2332 ErrorMsg(psp->filename,psp->tokenlineno,
2333 "Expected to see a \":\" following the LHS symbol \"%s\".",
2334 psp->lhs->name);
2335 psp->errorcnt++;
2336 psp->state = RESYNC_AFTER_RULE_ERROR;
2337 }
2338 break;
2339 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002340 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002341 psp->lhsalias = x;
2342 psp->state = LHS_ALIAS_2;
2343 }else{
2344 ErrorMsg(psp->filename,psp->tokenlineno,
2345 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2346 x,psp->lhs->name);
2347 psp->errorcnt++;
2348 psp->state = RESYNC_AFTER_RULE_ERROR;
2349 }
2350 break;
2351 case LHS_ALIAS_2:
2352 if( x[0]==')' ){
2353 psp->state = LHS_ALIAS_3;
2354 }else{
2355 ErrorMsg(psp->filename,psp->tokenlineno,
2356 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2357 psp->errorcnt++;
2358 psp->state = RESYNC_AFTER_RULE_ERROR;
2359 }
2360 break;
2361 case LHS_ALIAS_3:
2362 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2363 psp->state = IN_RHS;
2364 }else{
2365 ErrorMsg(psp->filename,psp->tokenlineno,
2366 "Missing \"->\" following: \"%s(%s)\".",
2367 psp->lhs->name,psp->lhsalias);
2368 psp->errorcnt++;
2369 psp->state = RESYNC_AFTER_RULE_ERROR;
2370 }
2371 break;
2372 case IN_RHS:
2373 if( x[0]=='.' ){
2374 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002375 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002376 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002377 if( rp==0 ){
2378 ErrorMsg(psp->filename,psp->tokenlineno,
2379 "Can't allocate enough memory for this rule.");
2380 psp->errorcnt++;
2381 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002382 }else{
drh75897232000-05-29 14:26:00 +00002383 int i;
2384 rp->ruleline = psp->tokenlineno;
2385 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002386 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002387 for(i=0; i<psp->nrhs; i++){
2388 rp->rhs[i] = psp->rhs[i];
2389 rp->rhsalias[i] = psp->alias[i];
drh539e7412018-04-21 20:24:19 +00002390 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
drhf2f105d2012-08-20 15:53:54 +00002391 }
drh75897232000-05-29 14:26:00 +00002392 rp->lhs = psp->lhs;
2393 rp->lhsalias = psp->lhsalias;
2394 rp->nrhs = psp->nrhs;
2395 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002396 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002397 rp->precsym = 0;
2398 rp->index = psp->gp->nrule++;
2399 rp->nextlhs = rp->lhs->rule;
2400 rp->lhs->rule = rp;
2401 rp->next = 0;
2402 if( psp->firstrule==0 ){
2403 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002404 }else{
drh75897232000-05-29 14:26:00 +00002405 psp->lastrule->next = rp;
2406 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002407 }
drh75897232000-05-29 14:26:00 +00002408 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002409 }
drh75897232000-05-29 14:26:00 +00002410 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002411 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002412 if( psp->nrhs>=MAXRHS ){
2413 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002414 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002415 x);
2416 psp->errorcnt++;
2417 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002418 }else{
drh75897232000-05-29 14:26:00 +00002419 psp->rhs[psp->nrhs] = Symbol_new(x);
2420 psp->alias[psp->nrhs] = 0;
2421 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002422 }
drhfd405312005-11-06 04:06:59 +00002423 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2424 struct symbol *msp = psp->rhs[psp->nrhs-1];
2425 if( msp->type!=MULTITERMINAL ){
2426 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002427 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002428 memset(msp, 0, sizeof(*msp));
2429 msp->type = MULTITERMINAL;
2430 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002431 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002432 msp->subsym[0] = origsp;
2433 msp->name = origsp->name;
2434 psp->rhs[psp->nrhs-1] = msp;
2435 }
2436 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002437 msp->subsym = (struct symbol **) realloc(msp->subsym,
2438 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002439 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002440 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002441 ErrorMsg(psp->filename,psp->tokenlineno,
2442 "Cannot form a compound containing a non-terminal");
2443 psp->errorcnt++;
2444 }
drh75897232000-05-29 14:26:00 +00002445 }else if( x[0]=='(' && psp->nrhs>0 ){
2446 psp->state = RHS_ALIAS_1;
2447 }else{
2448 ErrorMsg(psp->filename,psp->tokenlineno,
2449 "Illegal character on RHS of rule: \"%s\".",x);
2450 psp->errorcnt++;
2451 psp->state = RESYNC_AFTER_RULE_ERROR;
2452 }
2453 break;
2454 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002455 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002456 psp->alias[psp->nrhs-1] = x;
2457 psp->state = RHS_ALIAS_2;
2458 }else{
2459 ErrorMsg(psp->filename,psp->tokenlineno,
2460 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2461 x,psp->rhs[psp->nrhs-1]->name);
2462 psp->errorcnt++;
2463 psp->state = RESYNC_AFTER_RULE_ERROR;
2464 }
2465 break;
2466 case RHS_ALIAS_2:
2467 if( x[0]==')' ){
2468 psp->state = IN_RHS;
2469 }else{
2470 ErrorMsg(psp->filename,psp->tokenlineno,
2471 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2472 psp->errorcnt++;
2473 psp->state = RESYNC_AFTER_RULE_ERROR;
2474 }
2475 break;
2476 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002477 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002478 psp->declkeyword = x;
2479 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002480 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002481 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002482 psp->state = WAITING_FOR_DECL_ARG;
2483 if( strcmp(x,"name")==0 ){
2484 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002485 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002486 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002487 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002488 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002489 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002490 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002491 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002492 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002493 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002494 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002495 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002496 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002497 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002498 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002499 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002500 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002501 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002502 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002503 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002504 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002505 }else if( strcmp(x,"extra_argument")==0 ){
2506 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002507 psp->insertLineMacro = 0;
drhfb32c442018-04-21 13:51:42 +00002508 }else if( strcmp(x,"extra_context")==0 ){
2509 psp->declargslot = &(psp->gp->ctx);
2510 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002511 }else if( strcmp(x,"token_type")==0 ){
2512 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002513 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002514 }else if( strcmp(x,"default_type")==0 ){
2515 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002516 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002517 }else if( strcmp(x,"stack_size")==0 ){
2518 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002519 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002520 }else if( strcmp(x,"start_symbol")==0 ){
2521 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002522 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002523 }else if( strcmp(x,"left")==0 ){
2524 psp->preccounter++;
2525 psp->declassoc = LEFT;
2526 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2527 }else if( strcmp(x,"right")==0 ){
2528 psp->preccounter++;
2529 psp->declassoc = RIGHT;
2530 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2531 }else if( strcmp(x,"nonassoc")==0 ){
2532 psp->preccounter++;
2533 psp->declassoc = NONE;
2534 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002535 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002536 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002537 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002538 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002539 }else if( strcmp(x,"fallback")==0 ){
2540 psp->fallback = 0;
2541 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002542 }else if( strcmp(x,"token")==0 ){
2543 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002544 }else if( strcmp(x,"wildcard")==0 ){
2545 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002546 }else if( strcmp(x,"token_class")==0 ){
2547 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002548 }else{
2549 ErrorMsg(psp->filename,psp->tokenlineno,
2550 "Unknown declaration keyword: \"%%%s\".",x);
2551 psp->errorcnt++;
2552 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002553 }
drh75897232000-05-29 14:26:00 +00002554 }else{
2555 ErrorMsg(psp->filename,psp->tokenlineno,
2556 "Illegal declaration keyword: \"%s\".",x);
2557 psp->errorcnt++;
2558 psp->state = RESYNC_AFTER_DECL_ERROR;
2559 }
2560 break;
2561 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002562 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002563 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002564 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002565 psp->errorcnt++;
2566 psp->state = RESYNC_AFTER_DECL_ERROR;
2567 }else{
icculusd286fa62010-03-03 17:06:32 +00002568 struct symbol *sp = Symbol_new(x);
2569 psp->declargslot = &sp->destructor;
2570 psp->decllinenoslot = &sp->destLineno;
2571 psp->insertLineMacro = 1;
2572 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002573 }
2574 break;
2575 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002576 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002577 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002578 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002579 psp->errorcnt++;
2580 psp->state = RESYNC_AFTER_DECL_ERROR;
2581 }else{
icculus866bf1e2010-02-17 20:31:32 +00002582 struct symbol *sp = Symbol_find(x);
2583 if((sp) && (sp->datatype)){
2584 ErrorMsg(psp->filename,psp->tokenlineno,
2585 "Symbol %%type \"%s\" already defined", x);
2586 psp->errorcnt++;
2587 psp->state = RESYNC_AFTER_DECL_ERROR;
2588 }else{
2589 if (!sp){
2590 sp = Symbol_new(x);
2591 }
2592 psp->declargslot = &sp->datatype;
2593 psp->insertLineMacro = 0;
2594 psp->state = WAITING_FOR_DECL_ARG;
2595 }
drh75897232000-05-29 14:26:00 +00002596 }
2597 break;
2598 case WAITING_FOR_PRECEDENCE_SYMBOL:
2599 if( x[0]=='.' ){
2600 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002601 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002602 struct symbol *sp;
2603 sp = Symbol_new(x);
2604 if( sp->prec>=0 ){
2605 ErrorMsg(psp->filename,psp->tokenlineno,
2606 "Symbol \"%s\" has already be given a precedence.",x);
2607 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002608 }else{
drh75897232000-05-29 14:26:00 +00002609 sp->prec = psp->preccounter;
2610 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002611 }
drh75897232000-05-29 14:26:00 +00002612 }else{
2613 ErrorMsg(psp->filename,psp->tokenlineno,
2614 "Can't assign a precedence to \"%s\".",x);
2615 psp->errorcnt++;
2616 }
2617 break;
2618 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002619 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002620 const char *zOld, *zNew;
2621 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002622 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002623 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002624 char zLine[50];
2625 zNew = x;
2626 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002627 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002628 if( *psp->declargslot ){
2629 zOld = *psp->declargslot;
2630 }else{
2631 zOld = "";
2632 }
drh87cf1372008-08-13 20:09:06 +00002633 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002634 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002635 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002636 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2637 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002638 for(z=psp->filename, nBack=0; *z; z++){
2639 if( *z=='\\' ) nBack++;
2640 }
drh898799f2014-01-10 23:21:00 +00002641 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002642 nLine = lemonStrlen(zLine);
2643 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002644 }
icculus9e44cf12010-02-14 17:14:22 +00002645 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2646 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002647 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002648 if( nOld && zBuf[-1]!='\n' ){
2649 *(zBuf++) = '\n';
2650 }
2651 memcpy(zBuf, zLine, nLine);
2652 zBuf += nLine;
2653 *(zBuf++) = '"';
2654 for(z=psp->filename; *z; z++){
2655 if( *z=='\\' ){
2656 *(zBuf++) = '\\';
2657 }
2658 *(zBuf++) = *z;
2659 }
2660 *(zBuf++) = '"';
2661 *(zBuf++) = '\n';
2662 }
drh4dc8ef52008-07-01 17:13:57 +00002663 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2664 psp->decllinenoslot[0] = psp->tokenlineno;
2665 }
drha5808f32008-04-27 22:19:44 +00002666 memcpy(zBuf, zNew, nNew);
2667 zBuf += nNew;
2668 *zBuf = 0;
2669 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002670 }else{
2671 ErrorMsg(psp->filename,psp->tokenlineno,
2672 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2673 psp->errorcnt++;
2674 psp->state = RESYNC_AFTER_DECL_ERROR;
2675 }
2676 break;
drh0bd1f4e2002-06-06 18:54:39 +00002677 case WAITING_FOR_FALLBACK_ID:
2678 if( x[0]=='.' ){
2679 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002680 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002681 ErrorMsg(psp->filename, psp->tokenlineno,
2682 "%%fallback argument \"%s\" should be a token", x);
2683 psp->errorcnt++;
2684 }else{
2685 struct symbol *sp = Symbol_new(x);
2686 if( psp->fallback==0 ){
2687 psp->fallback = sp;
2688 }else if( sp->fallback ){
2689 ErrorMsg(psp->filename, psp->tokenlineno,
2690 "More than one fallback assigned to token %s", x);
2691 psp->errorcnt++;
2692 }else{
2693 sp->fallback = psp->fallback;
2694 psp->gp->has_fallback = 1;
2695 }
2696 }
2697 break;
drh59c435a2017-08-02 03:21:11 +00002698 case WAITING_FOR_TOKEN_NAME:
2699 /* Tokens do not have to be declared before use. But they can be
2700 ** in order to control their assigned integer number. The number for
2701 ** each token is assigned when it is first seen. So by including
2702 **
2703 ** %token ONE TWO THREE
2704 **
2705 ** early in the grammar file, that assigns small consecutive values
2706 ** to each of the tokens ONE TWO and THREE.
2707 */
2708 if( x[0]=='.' ){
2709 psp->state = WAITING_FOR_DECL_OR_RULE;
2710 }else if( !ISUPPER(x[0]) ){
2711 ErrorMsg(psp->filename, psp->tokenlineno,
2712 "%%token argument \"%s\" should be a token", x);
2713 psp->errorcnt++;
2714 }else{
2715 (void)Symbol_new(x);
2716 }
2717 break;
drhe09daa92006-06-10 13:29:31 +00002718 case WAITING_FOR_WILDCARD_ID:
2719 if( x[0]=='.' ){
2720 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002721 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002722 ErrorMsg(psp->filename, psp->tokenlineno,
2723 "%%wildcard argument \"%s\" should be a token", x);
2724 psp->errorcnt++;
2725 }else{
2726 struct symbol *sp = Symbol_new(x);
2727 if( psp->gp->wildcard==0 ){
2728 psp->gp->wildcard = sp;
2729 }else{
2730 ErrorMsg(psp->filename, psp->tokenlineno,
2731 "Extra wildcard to token: %s", x);
2732 psp->errorcnt++;
2733 }
2734 }
2735 break;
drh61f92cd2014-01-11 03:06:18 +00002736 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002737 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002738 ErrorMsg(psp->filename, psp->tokenlineno,
mistachkind9bc6e82019-05-10 16:16:19 +00002739 "%%token_class must be followed by an identifier: %s", x);
drh61f92cd2014-01-11 03:06:18 +00002740 psp->errorcnt++;
2741 psp->state = RESYNC_AFTER_DECL_ERROR;
2742 }else if( Symbol_find(x) ){
2743 ErrorMsg(psp->filename, psp->tokenlineno,
2744 "Symbol \"%s\" already used", x);
2745 psp->errorcnt++;
2746 psp->state = RESYNC_AFTER_DECL_ERROR;
2747 }else{
2748 psp->tkclass = Symbol_new(x);
2749 psp->tkclass->type = MULTITERMINAL;
2750 psp->state = WAITING_FOR_CLASS_TOKEN;
2751 }
2752 break;
2753 case WAITING_FOR_CLASS_TOKEN:
2754 if( x[0]=='.' ){
2755 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002756 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002757 struct symbol *msp = psp->tkclass;
2758 msp->nsubsym++;
2759 msp->subsym = (struct symbol **) realloc(msp->subsym,
2760 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002761 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002762 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2763 }else{
2764 ErrorMsg(psp->filename, psp->tokenlineno,
2765 "%%token_class argument \"%s\" should be a token", x);
2766 psp->errorcnt++;
2767 psp->state = RESYNC_AFTER_DECL_ERROR;
2768 }
2769 break;
drh75897232000-05-29 14:26:00 +00002770 case RESYNC_AFTER_RULE_ERROR:
2771/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2772** break; */
2773 case RESYNC_AFTER_DECL_ERROR:
2774 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2775 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2776 break;
2777 }
2778}
2779
drh34ff57b2008-07-14 12:27:51 +00002780/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002781** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2782** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2783** comments them out. Text in between is also commented out as appropriate.
2784*/
danielk1977940fac92005-01-23 22:41:37 +00002785static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002786 int i, j, k, n;
2787 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002788 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002789 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002790 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002791 for(i=0; z[i]; i++){
2792 if( z[i]=='\n' ) lineno++;
2793 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002794 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002795 if( exclude ){
2796 exclude--;
2797 if( exclude==0 ){
2798 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2799 }
2800 }
2801 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002802 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2803 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002804 if( exclude ){
2805 exclude++;
2806 }else{
drhc56fac72015-10-29 13:48:15 +00002807 for(j=i+7; ISSPACE(z[j]); j++){}
2808 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002809 exclude = 1;
2810 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002811 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002812 exclude = 0;
2813 break;
2814 }
2815 }
2816 if( z[i+3]=='n' ) exclude = !exclude;
2817 if( exclude ){
2818 start = i;
2819 start_lineno = lineno;
2820 }
2821 }
2822 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2823 }
2824 }
2825 if( exclude ){
2826 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2827 exit(1);
2828 }
2829}
2830
drh75897232000-05-29 14:26:00 +00002831/* In spite of its name, this function is really a scanner. It read
2832** in the entire input file (all at once) then tokenizes it. Each
2833** token is passed to the function "parseonetoken" which builds all
2834** the appropriate data structures in the global state vector "gp".
2835*/
icculus9e44cf12010-02-14 17:14:22 +00002836void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002837{
2838 struct pstate ps;
2839 FILE *fp;
2840 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002841 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002842 int lineno;
2843 int c;
2844 char *cp, *nextcp;
2845 int startline = 0;
2846
rse38514a92007-09-20 11:34:17 +00002847 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002848 ps.gp = gp;
2849 ps.filename = gp->filename;
2850 ps.errorcnt = 0;
2851 ps.state = INITIALIZE;
2852
2853 /* Begin by reading the input file */
2854 fp = fopen(ps.filename,"rb");
2855 if( fp==0 ){
2856 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2857 gp->errorcnt++;
2858 return;
2859 }
2860 fseek(fp,0,2);
2861 filesize = ftell(fp);
2862 rewind(fp);
2863 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002864 if( filesize>100000000 || filebuf==0 ){
2865 ErrorMsg(ps.filename,0,"Input file too large.");
mistachkinc93c6142018-09-08 16:55:18 +00002866 free(filebuf);
drh75897232000-05-29 14:26:00 +00002867 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002868 fclose(fp);
drh75897232000-05-29 14:26:00 +00002869 return;
2870 }
2871 if( fread(filebuf,1,filesize,fp)!=filesize ){
2872 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2873 filesize);
2874 free(filebuf);
2875 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002876 fclose(fp);
drh75897232000-05-29 14:26:00 +00002877 return;
2878 }
2879 fclose(fp);
2880 filebuf[filesize] = 0;
2881
drh6d08b4d2004-07-20 12:45:22 +00002882 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2883 preprocess_input(filebuf);
2884
drh75897232000-05-29 14:26:00 +00002885 /* Now scan the text of the input file */
2886 lineno = 1;
2887 for(cp=filebuf; (c= *cp)!=0; ){
2888 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002889 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002890 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2891 cp+=2;
2892 while( (c= *cp)!=0 && c!='\n' ) cp++;
2893 continue;
2894 }
2895 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2896 cp+=2;
2897 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2898 if( c=='\n' ) lineno++;
2899 cp++;
2900 }
2901 if( c ) cp++;
2902 continue;
2903 }
2904 ps.tokenstart = cp; /* Mark the beginning of the token */
2905 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2906 if( c=='\"' ){ /* String literals */
2907 cp++;
2908 while( (c= *cp)!=0 && c!='\"' ){
2909 if( c=='\n' ) lineno++;
2910 cp++;
2911 }
2912 if( c==0 ){
2913 ErrorMsg(ps.filename,startline,
2914"String starting on this line is not terminated before the end of the file.");
2915 ps.errorcnt++;
2916 nextcp = cp;
2917 }else{
2918 nextcp = cp+1;
2919 }
2920 }else if( c=='{' ){ /* A block of C code */
2921 int level;
2922 cp++;
2923 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2924 if( c=='\n' ) lineno++;
2925 else if( c=='{' ) level++;
2926 else if( c=='}' ) level--;
2927 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2928 int prevc;
2929 cp = &cp[2];
2930 prevc = 0;
2931 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2932 if( c=='\n' ) lineno++;
2933 prevc = c;
2934 cp++;
drhf2f105d2012-08-20 15:53:54 +00002935 }
2936 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002937 cp = &cp[2];
2938 while( (c= *cp)!=0 && c!='\n' ) cp++;
2939 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002940 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002941 int startchar, prevc;
2942 startchar = c;
2943 prevc = 0;
2944 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2945 if( c=='\n' ) lineno++;
2946 if( prevc=='\\' ) prevc = 0;
2947 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002948 }
2949 }
drh75897232000-05-29 14:26:00 +00002950 }
2951 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002952 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002953"C code starting on this line is not terminated before the end of the file.");
2954 ps.errorcnt++;
2955 nextcp = cp;
2956 }else{
2957 nextcp = cp+1;
2958 }
drhc56fac72015-10-29 13:48:15 +00002959 }else if( ISALNUM(c) ){ /* Identifiers */
2960 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002961 nextcp = cp;
2962 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2963 cp += 3;
2964 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002965 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002966 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002967 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002968 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002969 }else{ /* All other (one character) operators */
2970 cp++;
2971 nextcp = cp;
2972 }
2973 c = *cp;
2974 *cp = 0; /* Null terminate the token */
2975 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002976 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002977 cp = nextcp;
2978 }
2979 free(filebuf); /* Release the buffer after parsing */
2980 gp->rule = ps.firstrule;
2981 gp->errorcnt = ps.errorcnt;
2982}
2983/*************************** From the file "plink.c" *********************/
2984/*
2985** Routines processing configuration follow-set propagation links
2986** in the LEMON parser generator.
2987*/
2988static struct plink *plink_freelist = 0;
2989
2990/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00002991struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00002992 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002993
2994 if( plink_freelist==0 ){
2995 int i;
2996 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002997 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002998 if( plink_freelist==0 ){
2999 fprintf(stderr,
3000 "Unable to allocate memory for a new follow-set propagation link.\n");
3001 exit(1);
3002 }
3003 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3004 plink_freelist[amt-1].next = 0;
3005 }
icculus9e44cf12010-02-14 17:14:22 +00003006 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00003007 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00003008 return newlink;
drh75897232000-05-29 14:26:00 +00003009}
3010
3011/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00003012void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00003013{
icculus9e44cf12010-02-14 17:14:22 +00003014 struct plink *newlink;
3015 newlink = Plink_new();
3016 newlink->next = *plpp;
3017 *plpp = newlink;
3018 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00003019}
3020
3021/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00003022void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00003023{
3024 struct plink *nextpl;
3025 while( from ){
3026 nextpl = from->next;
3027 from->next = *to;
3028 *to = from;
3029 from = nextpl;
3030 }
3031}
3032
3033/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00003034void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00003035{
3036 struct plink *nextpl;
3037
3038 while( plp ){
3039 nextpl = plp->next;
3040 plp->next = plink_freelist;
3041 plink_freelist = plp;
3042 plp = nextpl;
3043 }
3044}
3045/*********************** From the file "report.c" **************************/
3046/*
3047** Procedures for generating reports and tables in the LEMON parser generator.
3048*/
3049
3050/* Generate a filename with the given suffix. Space to hold the
3051** name comes from malloc() and must be freed by the calling
3052** function.
3053*/
icculus9e44cf12010-02-14 17:14:22 +00003054PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00003055{
3056 char *name;
3057 char *cp;
drh9f88e6d2018-04-20 20:47:49 +00003058 char *filename = lemp->filename;
3059 int sz;
drh75897232000-05-29 14:26:00 +00003060
drh9f88e6d2018-04-20 20:47:49 +00003061 if( outputDir ){
3062 cp = strrchr(filename, '/');
3063 if( cp ) filename = cp + 1;
3064 }
3065 sz = lemonStrlen(filename);
3066 sz += lemonStrlen(suffix);
3067 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3068 sz += 5;
3069 name = (char*)malloc( sz );
drh75897232000-05-29 14:26:00 +00003070 if( name==0 ){
3071 fprintf(stderr,"Can't allocate space for a filename.\n");
3072 exit(1);
3073 }
drh9f88e6d2018-04-20 20:47:49 +00003074 name[0] = 0;
3075 if( outputDir ){
3076 lemon_strcpy(name, outputDir);
3077 lemon_strcat(name, "/");
3078 }
3079 lemon_strcat(name,filename);
drh75897232000-05-29 14:26:00 +00003080 cp = strrchr(name,'.');
3081 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003082 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003083 return name;
3084}
3085
3086/* Open a file with a name based on the name of the input file,
3087** but with a different (specified) suffix, and return a pointer
3088** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003089PRIVATE FILE *file_open(
3090 struct lemon *lemp,
3091 const char *suffix,
3092 const char *mode
3093){
drh75897232000-05-29 14:26:00 +00003094 FILE *fp;
3095
3096 if( lemp->outname ) free(lemp->outname);
3097 lemp->outname = file_makename(lemp, suffix);
3098 fp = fopen(lemp->outname,mode);
3099 if( fp==0 && *mode=='w' ){
3100 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3101 lemp->errorcnt++;
3102 return 0;
3103 }
3104 return fp;
3105}
3106
drh5c8241b2017-12-24 23:38:10 +00003107/* Print the text of a rule
3108*/
3109void rule_print(FILE *out, struct rule *rp){
3110 int i, j;
3111 fprintf(out, "%s",rp->lhs->name);
3112 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3113 fprintf(out," ::=");
3114 for(i=0; i<rp->nrhs; i++){
3115 struct symbol *sp = rp->rhs[i];
3116 if( sp->type==MULTITERMINAL ){
3117 fprintf(out," %s", sp->subsym[0]->name);
3118 for(j=1; j<sp->nsubsym; j++){
3119 fprintf(out,"|%s", sp->subsym[j]->name);
3120 }
3121 }else{
3122 fprintf(out," %s", sp->name);
3123 }
3124 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3125 }
3126}
3127
drh06f60d82017-04-14 19:46:12 +00003128/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003129** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003130void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003131{
3132 struct rule *rp;
3133 struct symbol *sp;
3134 int i, j, maxlen, len, ncolumns, skip;
3135 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3136 maxlen = 10;
3137 for(i=0; i<lemp->nsymbol; i++){
3138 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003139 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003140 if( len>maxlen ) maxlen = len;
3141 }
3142 ncolumns = 76/(maxlen+5);
3143 if( ncolumns<1 ) ncolumns = 1;
3144 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3145 for(i=0; i<skip; i++){
3146 printf("//");
3147 for(j=i; j<lemp->nsymbol; j+=skip){
3148 sp = lemp->symbols[j];
3149 assert( sp->index==j );
3150 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3151 }
3152 printf("\n");
3153 }
3154 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003155 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003156 printf(".");
3157 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003158 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003159 printf("\n");
3160 }
3161}
3162
drh7e698e92015-09-07 14:22:24 +00003163/* Print a single rule.
3164*/
3165void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003166 struct symbol *sp;
3167 int i, j;
drh75897232000-05-29 14:26:00 +00003168 fprintf(fp,"%s ::=",rp->lhs->name);
3169 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003170 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003171 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003172 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003173 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003174 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003175 for(j=1; j<sp->nsubsym; j++){
3176 fprintf(fp,"|%s",sp->subsym[j]->name);
3177 }
drh61f92cd2014-01-11 03:06:18 +00003178 }else{
3179 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003180 }
drh75897232000-05-29 14:26:00 +00003181 }
3182}
3183
drh7e698e92015-09-07 14:22:24 +00003184/* Print the rule for a configuration.
3185*/
3186void ConfigPrint(FILE *fp, struct config *cfp){
3187 RulePrint(fp, cfp->rp, cfp->dot);
3188}
3189
drh75897232000-05-29 14:26:00 +00003190/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003191#if 0
drh75897232000-05-29 14:26:00 +00003192/* Print a set */
3193PRIVATE void SetPrint(out,set,lemp)
3194FILE *out;
3195char *set;
3196struct lemon *lemp;
3197{
3198 int i;
3199 char *spacer;
3200 spacer = "";
3201 fprintf(out,"%12s[","");
3202 for(i=0; i<lemp->nterminal; i++){
3203 if( SetFind(set,i) ){
3204 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3205 spacer = " ";
3206 }
3207 }
3208 fprintf(out,"]\n");
3209}
3210
3211/* Print a plink chain */
3212PRIVATE void PlinkPrint(out,plp,tag)
3213FILE *out;
3214struct plink *plp;
3215char *tag;
3216{
3217 while( plp ){
drhada354d2005-11-05 15:03:59 +00003218 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003219 ConfigPrint(out,plp->cfp);
3220 fprintf(out,"\n");
3221 plp = plp->next;
3222 }
3223}
3224#endif
3225
3226/* Print an action to the given file descriptor. Return FALSE if
3227** nothing was actually printed.
3228*/
drh7e698e92015-09-07 14:22:24 +00003229int PrintAction(
3230 struct action *ap, /* The action to print */
3231 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003232 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003233){
drh75897232000-05-29 14:26:00 +00003234 int result = 1;
3235 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003236 case SHIFT: {
3237 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003238 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003239 break;
drh7e698e92015-09-07 14:22:24 +00003240 }
3241 case REDUCE: {
3242 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003243 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003244 RulePrint(fp, rp, -1);
3245 break;
3246 }
3247 case SHIFTREDUCE: {
3248 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003249 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003250 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003251 break;
drh7e698e92015-09-07 14:22:24 +00003252 }
drh75897232000-05-29 14:26:00 +00003253 case ACCEPT:
3254 fprintf(fp,"%*s accept",indent,ap->sp->name);
3255 break;
3256 case ERROR:
3257 fprintf(fp,"%*s error",indent,ap->sp->name);
3258 break;
drh9892c5d2007-12-21 00:02:11 +00003259 case SRCONFLICT:
3260 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003261 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003262 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003263 break;
drh9892c5d2007-12-21 00:02:11 +00003264 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003265 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003266 indent,ap->sp->name,ap->x.stp->statenum);
3267 break;
drh75897232000-05-29 14:26:00 +00003268 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003269 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003270 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003271 indent,ap->sp->name,ap->x.stp->statenum);
3272 }else{
3273 result = 0;
3274 }
3275 break;
drh75897232000-05-29 14:26:00 +00003276 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003277 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003278 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003279 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003280 }else{
3281 result = 0;
3282 }
3283 break;
drh75897232000-05-29 14:26:00 +00003284 case NOT_USED:
3285 result = 0;
3286 break;
3287 }
drhc173ad82016-05-23 16:15:02 +00003288 if( result && ap->spOpt ){
3289 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3290 }
drh75897232000-05-29 14:26:00 +00003291 return result;
3292}
3293
drh3bd48ab2015-09-07 18:23:37 +00003294/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003295void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003296{
drh539e7412018-04-21 20:24:19 +00003297 int i, n;
drh75897232000-05-29 14:26:00 +00003298 struct state *stp;
3299 struct config *cfp;
3300 struct action *ap;
drh12f68392018-04-06 19:12:55 +00003301 struct rule *rp;
drh75897232000-05-29 14:26:00 +00003302 FILE *fp;
3303
drh2aa6ca42004-09-10 00:14:04 +00003304 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003305 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003306 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003307 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003308 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003309 if( lemp->basisflag ) cfp=stp->bp;
3310 else cfp=stp->cfp;
3311 while( cfp ){
3312 char buf[20];
3313 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003314 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003315 fprintf(fp," %5s ",buf);
3316 }else{
3317 fprintf(fp," ");
3318 }
3319 ConfigPrint(fp,cfp);
3320 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003321#if 0
drh75897232000-05-29 14:26:00 +00003322 SetPrint(fp,cfp->fws,lemp);
3323 PlinkPrint(fp,cfp->fplp,"To ");
3324 PlinkPrint(fp,cfp->bplp,"From");
3325#endif
3326 if( lemp->basisflag ) cfp=cfp->bp;
3327 else cfp=cfp->next;
3328 }
3329 fprintf(fp,"\n");
3330 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003331 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003332 }
3333 fprintf(fp,"\n");
3334 }
drhe9278182007-07-18 18:16:29 +00003335 fprintf(fp, "----------------------------------------------------\n");
3336 fprintf(fp, "Symbols:\n");
drh539e7412018-04-21 20:24:19 +00003337 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
drhe9278182007-07-18 18:16:29 +00003338 for(i=0; i<lemp->nsymbol; i++){
3339 int j;
3340 struct symbol *sp;
3341
3342 sp = lemp->symbols[i];
3343 fprintf(fp, " %3d: %s", i, sp->name);
3344 if( sp->type==NONTERMINAL ){
3345 fprintf(fp, ":");
3346 if( sp->lambda ){
3347 fprintf(fp, " <lambda>");
3348 }
3349 for(j=0; j<lemp->nterminal; j++){
3350 if( sp->firstset && SetFind(sp->firstset, j) ){
3351 fprintf(fp, " %s", lemp->symbols[j]->name);
3352 }
3353 }
3354 }
drh12f68392018-04-06 19:12:55 +00003355 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
drhe9278182007-07-18 18:16:29 +00003356 fprintf(fp, "\n");
3357 }
drh12f68392018-04-06 19:12:55 +00003358 fprintf(fp, "----------------------------------------------------\n");
drh539e7412018-04-21 20:24:19 +00003359 fprintf(fp, "Syntax-only Symbols:\n");
3360 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3361 for(i=n=0; i<lemp->nsymbol; i++){
3362 int w;
3363 struct symbol *sp = lemp->symbols[i];
3364 if( sp->bContent ) continue;
3365 w = (int)strlen(sp->name);
3366 if( n>0 && n+w>75 ){
3367 fprintf(fp,"\n");
3368 n = 0;
3369 }
3370 if( n>0 ){
3371 fprintf(fp, " ");
3372 n++;
3373 }
3374 fprintf(fp, "%s", sp->name);
3375 n += w;
3376 }
3377 if( n>0 ) fprintf(fp, "\n");
3378 fprintf(fp, "----------------------------------------------------\n");
drh12f68392018-04-06 19:12:55 +00003379 fprintf(fp, "Rules:\n");
3380 for(rp=lemp->rule; rp; rp=rp->next){
3381 fprintf(fp, "%4d: ", rp->iRule);
3382 rule_print(fp, rp);
3383 fprintf(fp,".");
3384 if( rp->precsym ){
3385 fprintf(fp," [%s precedence=%d]",
3386 rp->precsym->name, rp->precsym->prec);
3387 }
3388 fprintf(fp,"\n");
3389 }
drh75897232000-05-29 14:26:00 +00003390 fclose(fp);
3391 return;
3392}
3393
3394/* Search for the file "name" which is in the same directory as
3395** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003396PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003397{
icculus9e44cf12010-02-14 17:14:22 +00003398 const char *pathlist;
3399 char *pathbufptr;
3400 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003401 char *path,*cp;
3402 char c;
drh75897232000-05-29 14:26:00 +00003403
3404#ifdef __WIN32__
3405 cp = strrchr(argv0,'\\');
3406#else
3407 cp = strrchr(argv0,'/');
3408#endif
3409 if( cp ){
3410 c = *cp;
3411 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003412 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003413 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003414 *cp = c;
3415 }else{
drh75897232000-05-29 14:26:00 +00003416 pathlist = getenv("PATH");
3417 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003418 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003419 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003420 if( (pathbuf != 0) && (path!=0) ){
3421 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003422 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003423 while( *pathbuf ){
3424 cp = strchr(pathbuf,':');
3425 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003426 c = *cp;
3427 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003428 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003429 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003430 if( c==0 ) pathbuf[0] = 0;
3431 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003432 if( access(path,modemask)==0 ) break;
3433 }
icculus9e44cf12010-02-14 17:14:22 +00003434 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003435 }
3436 }
3437 return path;
3438}
3439
3440/* Given an action, compute the integer value for that action
3441** which is to be put in the action table of the generated machine.
3442** Return negative if no action should be generated.
3443*/
icculus9e44cf12010-02-14 17:14:22 +00003444PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003445{
3446 int act;
3447 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003448 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003449 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003450 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3451 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3452 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003453 if( ap->sp->index>=lemp->nterminal ){
3454 act = lemp->minReduce + ap->x.rp->iRule;
3455 }else{
3456 act = lemp->minShiftReduce + ap->x.rp->iRule;
3457 }
drhbd8fcc12017-06-28 11:56:18 +00003458 break;
3459 }
drh5c8241b2017-12-24 23:38:10 +00003460 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3461 case ERROR: act = lemp->errAction; break;
3462 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003463 default: act = -1; break;
3464 }
3465 return act;
3466}
3467
3468#define LINESIZE 1000
3469/* The next cluster of routines are for reading the template file
3470** and writing the results to the generated parser */
3471/* The first function transfers data from "in" to "out" until
3472** a line is seen which begins with "%%". The line number is
3473** tracked.
3474**
3475** if name!=0, then any word that begin with "Parse" is changed to
3476** begin with *name instead.
3477*/
icculus9e44cf12010-02-14 17:14:22 +00003478PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003479{
3480 int i, iStart;
3481 char line[LINESIZE];
3482 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3483 (*lineno)++;
3484 iStart = 0;
3485 if( name ){
3486 for(i=0; line[i]; i++){
3487 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003488 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003489 ){
3490 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3491 fprintf(out,"%s",name);
3492 i += 4;
3493 iStart = i+1;
3494 }
3495 }
3496 }
3497 fprintf(out,"%s",&line[iStart]);
3498 }
3499}
3500
3501/* The next function finds the template file and opens it, returning
3502** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003503PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003504{
3505 static char templatename[] = "lempar.c";
3506 char buf[1000];
3507 FILE *in;
3508 char *tpltname;
3509 char *cp;
3510
icculus3e143bd2010-02-14 00:48:49 +00003511 /* first, see if user specified a template filename on the command line. */
3512 if (user_templatename != 0) {
3513 if( access(user_templatename,004)==-1 ){
3514 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3515 user_templatename);
3516 lemp->errorcnt++;
3517 return 0;
3518 }
3519 in = fopen(user_templatename,"rb");
3520 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003521 fprintf(stderr,"Can't open the template file \"%s\".\n",
3522 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003523 lemp->errorcnt++;
3524 return 0;
3525 }
3526 return in;
3527 }
3528
drh75897232000-05-29 14:26:00 +00003529 cp = strrchr(lemp->filename,'.');
3530 if( cp ){
drh898799f2014-01-10 23:21:00 +00003531 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003532 }else{
drh898799f2014-01-10 23:21:00 +00003533 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003534 }
3535 if( access(buf,004)==0 ){
3536 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003537 }else if( access(templatename,004)==0 ){
3538 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003539 }else{
3540 tpltname = pathsearch(lemp->argv0,templatename,0);
3541 }
3542 if( tpltname==0 ){
3543 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3544 templatename);
3545 lemp->errorcnt++;
3546 return 0;
3547 }
drh2aa6ca42004-09-10 00:14:04 +00003548 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003549 if( in==0 ){
3550 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3551 lemp->errorcnt++;
3552 return 0;
3553 }
3554 return in;
3555}
3556
drhaf805ca2004-09-07 11:28:25 +00003557/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003558PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003559{
3560 fprintf(out,"#line %d \"",lineno);
3561 while( *filename ){
3562 if( *filename == '\\' ) putc('\\',out);
3563 putc(*filename,out);
3564 filename++;
3565 }
3566 fprintf(out,"\"\n");
3567}
3568
drh75897232000-05-29 14:26:00 +00003569/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003570PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003571{
3572 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003573 while( *str ){
drh75897232000-05-29 14:26:00 +00003574 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003575 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003576 str++;
3577 }
drh9db55df2004-09-09 14:01:21 +00003578 if( str[-1]!='\n' ){
3579 putc('\n',out);
3580 (*lineno)++;
3581 }
shane58543932008-12-10 20:10:04 +00003582 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003583 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003584 }
drh75897232000-05-29 14:26:00 +00003585 return;
3586}
3587
3588/*
3589** The following routine emits code for the destructor for the
3590** symbol sp
3591*/
icculus9e44cf12010-02-14 17:14:22 +00003592void emit_destructor_code(
3593 FILE *out,
3594 struct symbol *sp,
3595 struct lemon *lemp,
3596 int *lineno
3597){
drhcc83b6e2004-04-23 23:38:42 +00003598 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003599
drh75897232000-05-29 14:26:00 +00003600 if( sp->type==TERMINAL ){
3601 cp = lemp->tokendest;
3602 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003603 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003604 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003605 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003606 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003607 if( !lemp->nolinenosflag ){
3608 (*lineno)++;
3609 tplt_linedir(out,sp->destLineno,lemp->filename);
3610 }
drh960e8c62001-04-03 16:53:21 +00003611 }else if( lemp->vardest ){
3612 cp = lemp->vardest;
3613 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003614 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003615 }else{
3616 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003617 }
3618 for(; *cp; cp++){
3619 if( *cp=='$' && cp[1]=='$' ){
3620 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3621 cp++;
3622 continue;
3623 }
shane58543932008-12-10 20:10:04 +00003624 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003625 fputc(*cp,out);
3626 }
shane58543932008-12-10 20:10:04 +00003627 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003628 if (!lemp->nolinenosflag) {
3629 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003630 }
3631 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003632 return;
3633}
3634
3635/*
drh960e8c62001-04-03 16:53:21 +00003636** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003637*/
icculus9e44cf12010-02-14 17:14:22 +00003638int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003639{
3640 int ret;
3641 if( sp->type==TERMINAL ){
3642 ret = lemp->tokendest!=0;
3643 }else{
drh960e8c62001-04-03 16:53:21 +00003644 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003645 }
3646 return ret;
3647}
3648
drh0bb132b2004-07-20 14:06:51 +00003649/*
3650** Append text to a dynamically allocated string. If zText is 0 then
3651** reset the string to be empty again. Always return the complete text
3652** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003653**
3654** n bytes of zText are stored. If n==0 then all of zText up to the first
3655** \000 terminator is stored. zText can contain up to two instances of
3656** %d. The values of p1 and p2 are written into the first and second
3657** %d.
3658**
3659** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003660*/
icculus9e44cf12010-02-14 17:14:22 +00003661PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3662 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003663 static char *z = 0;
3664 static int alloced = 0;
3665 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003666 int c;
drh0bb132b2004-07-20 14:06:51 +00003667 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003668 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003669 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003670 used = 0;
3671 return z;
3672 }
drh7ac25c72004-08-19 15:12:26 +00003673 if( n<=0 ){
3674 if( n<0 ){
3675 used += n;
3676 assert( used>=0 );
3677 }
drh87cf1372008-08-13 20:09:06 +00003678 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003679 }
drhdf609712010-11-23 20:55:27 +00003680 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003681 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003682 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003683 }
icculus9e44cf12010-02-14 17:14:22 +00003684 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003685 while( n-- > 0 ){
3686 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003687 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003688 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003689 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003690 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003691 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003692 zText++;
3693 n--;
3694 }else{
mistachkin2318d332015-01-12 18:02:52 +00003695 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003696 }
3697 }
3698 z[used] = 0;
3699 return z;
3700}
3701
3702/*
drh711c9812016-05-23 14:24:31 +00003703** Write and transform the rp->code string so that symbols are expanded.
3704** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003705**
3706** Return 1 if the expanded code requires that "yylhsminor" local variable
3707** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003708*/
drhdabd04c2016-02-17 01:46:19 +00003709PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003710 char *cp, *xp;
3711 int i;
drhcf82f0d2016-02-17 04:33:10 +00003712 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003713 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003714 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3715 char lhsused = 0; /* True if the LHS element has been used */
3716 char lhsdirect; /* True if LHS writes directly into stack */
3717 char used[MAXRHS]; /* True for each RHS element which is used */
3718 char zLhs[50]; /* Convert the LHS symbol into this string */
3719 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003720
3721 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3722 lhsused = 0;
3723
drh19c9e562007-03-29 20:13:53 +00003724 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003725 static char newlinestr[2] = { '\n', '\0' };
3726 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003727 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003728 rp->noCode = 1;
3729 }else{
3730 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003731 }
3732
drh4dd0d3f2016-02-17 01:18:33 +00003733
drh2e55b042016-04-30 17:19:30 +00003734 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003735 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3736 lhsdirect = 1;
3737 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003738 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003739 ** we have to call the distructor on the RHS symbol first. */
3740 lhsdirect = 1;
3741 if( has_destructor(rp->rhs[0],lemp) ){
3742 append_str(0,0,0,0);
3743 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3744 rp->rhs[0]->index,1-rp->nrhs);
3745 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003746 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003747 }
drh2e55b042016-04-30 17:19:30 +00003748 }else if( rp->lhsalias==0 ){
3749 /* There is no LHS value symbol. */
3750 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003751 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003752 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003753 ** direct writing is allowed */
3754 lhsdirect = 1;
3755 lhsused = 1;
3756 used[0] = 1;
3757 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3758 ErrorMsg(lemp->filename,rp->ruleline,
3759 "%s(%s) and %s(%s) share the same label but have "
3760 "different datatypes.",
3761 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3762 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003763 }
drh4dd0d3f2016-02-17 01:18:33 +00003764 }else{
drhcf82f0d2016-02-17 04:33:10 +00003765 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3766 rp->lhsalias, rp->rhsalias[0]);
3767 zSkip = strstr(rp->code, zOvwrt);
3768 if( zSkip!=0 ){
3769 /* The code contains a special comment that indicates that it is safe
3770 ** for the LHS label to overwrite left-most RHS label. */
3771 lhsdirect = 1;
3772 }else{
3773 lhsdirect = 0;
3774 }
drh4dd0d3f2016-02-17 01:18:33 +00003775 }
3776 if( lhsdirect ){
3777 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3778 }else{
drhdabd04c2016-02-17 01:46:19 +00003779 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003780 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3781 }
3782
drh0bb132b2004-07-20 14:06:51 +00003783 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003784
3785 /* This const cast is wrong but harmless, if we're careful. */
3786 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003787 if( cp==zSkip ){
3788 append_str(zOvwrt,0,0,0);
3789 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003790 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003791 continue;
3792 }
drhc56fac72015-10-29 13:48:15 +00003793 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003794 char saved;
drhc56fac72015-10-29 13:48:15 +00003795 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003796 saved = *xp;
3797 *xp = 0;
3798 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003799 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003800 cp = xp;
3801 lhsused = 1;
3802 }else{
3803 for(i=0; i<rp->nrhs; i++){
3804 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003805 if( i==0 && dontUseRhs0 ){
3806 ErrorMsg(lemp->filename,rp->ruleline,
3807 "Label %s used after '%s'.",
3808 rp->rhsalias[0], zOvwrt);
3809 lemp->errorcnt++;
3810 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003811 /* If the argument is of the form @X then substituted
3812 ** the token number of X, not the value of X */
3813 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3814 }else{
drhfd405312005-11-06 04:06:59 +00003815 struct symbol *sp = rp->rhs[i];
3816 int dtnum;
3817 if( sp->type==MULTITERMINAL ){
3818 dtnum = sp->subsym[0]->dtnum;
3819 }else{
3820 dtnum = sp->dtnum;
3821 }
3822 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003823 }
drh0bb132b2004-07-20 14:06:51 +00003824 cp = xp;
3825 used[i] = 1;
3826 break;
3827 }
3828 }
3829 }
3830 *xp = saved;
3831 }
3832 append_str(cp, 1, 0, 0);
3833 } /* End loop */
3834
drh4dd0d3f2016-02-17 01:18:33 +00003835 /* Main code generation completed */
3836 cp = append_str(0,0,0,0);
3837 if( cp && cp[0] ) rp->code = Strsafe(cp);
3838 append_str(0,0,0,0);
3839
drh0bb132b2004-07-20 14:06:51 +00003840 /* Check to make sure the LHS has been used */
3841 if( rp->lhsalias && !lhsused ){
3842 ErrorMsg(lemp->filename,rp->ruleline,
3843 "Label \"%s\" for \"%s(%s)\" is never used.",
3844 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3845 lemp->errorcnt++;
3846 }
3847
drh4dd0d3f2016-02-17 01:18:33 +00003848 /* Generate destructor code for RHS minor values which are not referenced.
3849 ** Generate error messages for unused labels and duplicate labels.
3850 */
drh0bb132b2004-07-20 14:06:51 +00003851 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003852 if( rp->rhsalias[i] ){
3853 if( i>0 ){
3854 int j;
3855 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3856 ErrorMsg(lemp->filename,rp->ruleline,
3857 "%s(%s) has the same label as the LHS but is not the left-most "
3858 "symbol on the RHS.",
drhf135cb72019-04-30 14:26:31 +00003859 rp->rhs[i]->name, rp->rhsalias[i]);
drh4dd0d3f2016-02-17 01:18:33 +00003860 lemp->errorcnt++;
3861 }
3862 for(j=0; j<i; j++){
3863 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3864 ErrorMsg(lemp->filename,rp->ruleline,
3865 "Label %s used for multiple symbols on the RHS of a rule.",
3866 rp->rhsalias[i]);
3867 lemp->errorcnt++;
3868 break;
3869 }
3870 }
drh0bb132b2004-07-20 14:06:51 +00003871 }
drh4dd0d3f2016-02-17 01:18:33 +00003872 if( !used[i] ){
3873 ErrorMsg(lemp->filename,rp->ruleline,
3874 "Label %s for \"%s(%s)\" is never used.",
3875 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3876 lemp->errorcnt++;
3877 }
3878 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3879 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3880 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003881 }
3882 }
drh4dd0d3f2016-02-17 01:18:33 +00003883
3884 /* If unable to write LHS values directly into the stack, write the
3885 ** saved LHS value now. */
3886 if( lhsdirect==0 ){
3887 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3888 append_str(zLhs, 0, 0, 0);
3889 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003890 }
drh4dd0d3f2016-02-17 01:18:33 +00003891
3892 /* Suffix code generation complete */
3893 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003894 if( cp && cp[0] ){
3895 rp->codeSuffix = Strsafe(cp);
3896 rp->noCode = 0;
3897 }
drhdabd04c2016-02-17 01:46:19 +00003898
3899 return rc;
drh0bb132b2004-07-20 14:06:51 +00003900}
3901
drh06f60d82017-04-14 19:46:12 +00003902/*
drh75897232000-05-29 14:26:00 +00003903** Generate code which executes when the rule "rp" is reduced. Write
3904** the code to "out". Make sure lineno stays up-to-date.
3905*/
icculus9e44cf12010-02-14 17:14:22 +00003906PRIVATE void emit_code(
3907 FILE *out,
3908 struct rule *rp,
3909 struct lemon *lemp,
3910 int *lineno
3911){
3912 const char *cp;
drh75897232000-05-29 14:26:00 +00003913
drh4dd0d3f2016-02-17 01:18:33 +00003914 /* Setup code prior to the #line directive */
3915 if( rp->codePrefix && rp->codePrefix[0] ){
3916 fprintf(out, "{%s", rp->codePrefix);
3917 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3918 }
3919
drh75897232000-05-29 14:26:00 +00003920 /* Generate code to do the reduce action */
3921 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003922 if( !lemp->nolinenosflag ){
3923 (*lineno)++;
3924 tplt_linedir(out,rp->line,lemp->filename);
3925 }
drhaf805ca2004-09-07 11:28:25 +00003926 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003927 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003928 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003929 if( !lemp->nolinenosflag ){
3930 (*lineno)++;
3931 tplt_linedir(out,*lineno,lemp->outname);
3932 }
drh4dd0d3f2016-02-17 01:18:33 +00003933 }
3934
3935 /* Generate breakdown code that occurs after the #line directive */
3936 if( rp->codeSuffix && rp->codeSuffix[0] ){
3937 fprintf(out, "%s", rp->codeSuffix);
3938 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3939 }
3940
3941 if( rp->codePrefix ){
3942 fprintf(out, "}\n"); (*lineno)++;
3943 }
drh75897232000-05-29 14:26:00 +00003944
drh75897232000-05-29 14:26:00 +00003945 return;
3946}
3947
3948/*
3949** Print the definition of the union used for the parser's data stack.
3950** This union contains fields for every possible data type for tokens
3951** and nonterminals. In the process of computing and printing this
3952** union, also set the ".dtnum" field of every terminal and nonterminal
3953** symbol.
3954*/
icculus9e44cf12010-02-14 17:14:22 +00003955void print_stack_union(
3956 FILE *out, /* The output stream */
3957 struct lemon *lemp, /* The main info structure for this parser */
3958 int *plineno, /* Pointer to the line number */
3959 int mhflag /* True if generating makeheaders output */
3960){
drh75897232000-05-29 14:26:00 +00003961 int lineno = *plineno; /* The line number of the output */
3962 char **types; /* A hash table of datatypes */
3963 int arraysize; /* Size of the "types" array */
3964 int maxdtlength; /* Maximum length of any ".datatype" field. */
3965 char *stddt; /* Standardized name for a datatype */
3966 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003967 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003968 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003969
3970 /* Allocate and initialize types[] and allocate stddt[] */
3971 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003972 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003973 if( types==0 ){
3974 fprintf(stderr,"Out of memory.\n");
3975 exit(1);
3976 }
drh75897232000-05-29 14:26:00 +00003977 for(i=0; i<arraysize; i++) types[i] = 0;
3978 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003979 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003980 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003981 }
drh75897232000-05-29 14:26:00 +00003982 for(i=0; i<lemp->nsymbol; i++){
3983 int len;
3984 struct symbol *sp = lemp->symbols[i];
3985 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003986 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003987 if( len>maxdtlength ) maxdtlength = len;
3988 }
3989 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003990 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003991 fprintf(stderr,"Out of memory.\n");
3992 exit(1);
3993 }
3994
3995 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3996 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003997 ** used for terminal symbols. If there is no %default_type defined then
3998 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3999 ** a datatype using the %type directive.
4000 */
drh75897232000-05-29 14:26:00 +00004001 for(i=0; i<lemp->nsymbol; i++){
4002 struct symbol *sp = lemp->symbols[i];
4003 char *cp;
4004 if( sp==lemp->errsym ){
4005 sp->dtnum = arraysize+1;
4006 continue;
4007 }
drh960e8c62001-04-03 16:53:21 +00004008 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00004009 sp->dtnum = 0;
4010 continue;
4011 }
4012 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00004013 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00004014 j = 0;
drhc56fac72015-10-29 13:48:15 +00004015 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00004016 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00004017 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00004018 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00004019 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00004020 sp->dtnum = 0;
4021 continue;
4022 }
drh75897232000-05-29 14:26:00 +00004023 hash = 0;
4024 for(j=0; stddt[j]; j++){
4025 hash = hash*53 + stddt[j];
4026 }
drh3b2129c2003-05-13 00:34:21 +00004027 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00004028 while( types[hash] ){
4029 if( strcmp(types[hash],stddt)==0 ){
4030 sp->dtnum = hash + 1;
4031 break;
4032 }
4033 hash++;
drh2b51f212013-10-11 23:01:02 +00004034 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00004035 }
4036 if( types[hash]==0 ){
4037 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00004038 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00004039 if( types[hash]==0 ){
4040 fprintf(stderr,"Out of memory.\n");
4041 exit(1);
4042 }
drh898799f2014-01-10 23:21:00 +00004043 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00004044 }
4045 }
4046
4047 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4048 name = lemp->name ? lemp->name : "Parse";
4049 lineno = *plineno;
4050 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4051 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4052 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4053 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4054 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00004055 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004056 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4057 for(i=0; i<arraysize; i++){
4058 if( types[i]==0 ) continue;
4059 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4060 free(types[i]);
4061 }
drhed0c15b2018-04-16 14:31:34 +00004062 if( lemp->errsym && lemp->errsym->useCnt ){
drhc4dd3fd2008-01-22 01:48:05 +00004063 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4064 }
drh75897232000-05-29 14:26:00 +00004065 free(stddt);
4066 free(types);
4067 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4068 *plineno = lineno;
4069}
4070
drhb29b0a52002-02-23 19:39:46 +00004071/*
4072** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00004073** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4074** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00004075*/
drhc75e0162015-09-07 02:23:02 +00004076static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4077 const char *zType = "int";
4078 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00004079 if( lwr>=0 ){
4080 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00004081 zType = "unsigned char";
4082 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004083 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00004084 zType = "unsigned short int";
4085 nByte = 2;
drh8b582012003-10-21 13:16:03 +00004086 }else{
drhc75e0162015-09-07 02:23:02 +00004087 zType = "unsigned int";
4088 nByte = 4;
drh8b582012003-10-21 13:16:03 +00004089 }
4090 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00004091 zType = "signed char";
4092 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004093 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00004094 zType = "short";
4095 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00004096 }
drhc75e0162015-09-07 02:23:02 +00004097 if( pnByte ) *pnByte = nByte;
4098 return zType;
drhb29b0a52002-02-23 19:39:46 +00004099}
4100
drhfdbf9282003-10-21 16:34:41 +00004101/*
4102** Each state contains a set of token transaction and a set of
4103** nonterminal transactions. Each of these sets makes an instance
4104** of the following structure. An array of these structures is used
4105** to order the creation of entries in the yy_action[] table.
4106*/
4107struct axset {
4108 struct state *stp; /* A pointer to a state */
4109 int isTkn; /* True to use tokens. False for non-terminals */
4110 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00004111 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00004112};
4113
4114/*
4115** Compare to axset structures for sorting purposes
4116*/
4117static int axset_compare(const void *a, const void *b){
4118 struct axset *p1 = (struct axset*)a;
4119 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004120 int c;
4121 c = p2->nAction - p1->nAction;
4122 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004123 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004124 }
4125 assert( c!=0 || p1==p2 );
4126 return c;
drhfdbf9282003-10-21 16:34:41 +00004127}
4128
drhc4dd3fd2008-01-22 01:48:05 +00004129/*
4130** Write text on "out" that describes the rule "rp".
4131*/
4132static void writeRuleText(FILE *out, struct rule *rp){
4133 int j;
4134 fprintf(out,"%s ::=", rp->lhs->name);
4135 for(j=0; j<rp->nrhs; j++){
4136 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004137 if( sp->type!=MULTITERMINAL ){
4138 fprintf(out," %s", sp->name);
4139 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004140 int k;
drh61f92cd2014-01-11 03:06:18 +00004141 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004142 for(k=1; k<sp->nsubsym; k++){
4143 fprintf(out,"|%s",sp->subsym[k]->name);
4144 }
4145 }
4146 }
4147}
4148
4149
drh75897232000-05-29 14:26:00 +00004150/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004151void ReportTable(
4152 struct lemon *lemp,
drhfe03dac2019-11-26 02:22:39 +00004153 int mhflag, /* Output in makeheaders format if true */
4154 int sqlFlag /* Generate the *.sql file too */
icculus9e44cf12010-02-14 17:14:22 +00004155){
drhfe03dac2019-11-26 02:22:39 +00004156 FILE *out, *in, *sql;
drh75897232000-05-29 14:26:00 +00004157 char line[LINESIZE];
4158 int lineno;
4159 struct state *stp;
4160 struct action *ap;
4161 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004162 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004163 int i, j, n, sz;
drh2e517162019-08-28 02:09:47 +00004164 int nLookAhead;
drhc75e0162015-09-07 02:23:02 +00004165 int szActionType; /* sizeof(YYACTIONTYPE) */
4166 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004167 const char *name;
drh8b582012003-10-21 13:16:03 +00004168 int mnTknOfst, mxTknOfst;
4169 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004170 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004171
drh5c8241b2017-12-24 23:38:10 +00004172 lemp->minShiftReduce = lemp->nstate;
4173 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4174 lemp->accAction = lemp->errAction + 1;
4175 lemp->noAction = lemp->accAction + 1;
4176 lemp->minReduce = lemp->noAction + 1;
4177 lemp->maxAction = lemp->minReduce + lemp->nrule;
4178
drh75897232000-05-29 14:26:00 +00004179 in = tplt_open(lemp);
4180 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004181 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004182 if( out==0 ){
4183 fclose(in);
4184 return;
4185 }
drhfe03dac2019-11-26 02:22:39 +00004186 if( sqlFlag==0 ){
4187 sql = 0;
4188 }else{
4189 sql = file_open(lemp, ".sql", "wb");
4190 if( sql==0 ){
4191 fclose(in);
4192 fclose(out);
4193 return;
4194 }
4195 fprintf(sql,
drh1417c2f2019-11-29 12:51:00 +00004196 "BEGIN;\n"
drhfe03dac2019-11-26 02:22:39 +00004197 "CREATE TABLE symbol(\n"
4198 " id INTEGER PRIMARY KEY,\n"
4199 " name TEXT NOT NULL,\n"
4200 " isTerminal BOOLEAN NOT NULL,\n"
drh1417c2f2019-11-29 12:51:00 +00004201 " fallback INTEGER REFERENCES symbol"
4202 " DEFERRABLE INITIALLY DEFERRED\n"
drhfe03dac2019-11-26 02:22:39 +00004203 ");\n"
4204 );
4205 for(i=0; i<lemp->nsymbol; i++){
4206 fprintf(sql,
4207 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4208 "VALUES(%d,'%s',%s",
4209 i, lemp->symbols[i]->name,
4210 i<lemp->nterminal ? "TRUE" : "FALSE"
4211 );
4212 if( lemp->symbols[i]->fallback ){
4213 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
4214 }else{
4215 fprintf(sql, ",NULL);\n");
4216 }
4217 }
4218 fprintf(sql,
4219 "CREATE TABLE rule(\n"
4220 " ruleid INTEGER PRIMARY KEY,\n"
4221 " lhs INTEGER REFERENCES symbol(id)\n"
4222 ");\n"
4223 "CREATE TABLE rulerhs(\n"
4224 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4225 " pos INTEGER,\n"
4226 " sym INTEGER REFERENCES symbol(id)\n"
4227 ");\n"
4228 );
4229 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4230 assert( i==rp->iRule );
drh61cb4ed2019-11-29 13:01:57 +00004231 fprintf(sql, "-- ");
4232 writeRuleText(sql, rp);
4233 fprintf(sql, "\n");
drhfe03dac2019-11-26 02:22:39 +00004234 fprintf(sql,
4235 "INSERT INTO rule(ruleid,lhs)VALUES(%d,%d);\n",
4236 rp->iRule, rp->lhs->index
4237 );
4238 for(j=0; j<rp->nrhs; j++){
4239 struct symbol *sp = rp->rhs[j];
4240 if( sp->type!=MULTITERMINAL ){
4241 fprintf(sql,
4242 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4243 i,j,sp->index
4244 );
4245 }else{
4246 int k;
4247 for(k=0; k<sp->nsubsym; k++){
4248 fprintf(sql,
4249 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4250 i,j,sp->subsym[k]->index
4251 );
4252 }
4253 }
4254 }
4255 }
drh1417c2f2019-11-29 12:51:00 +00004256 fprintf(sql, "COMMIT;\n");
drhfe03dac2019-11-26 02:22:39 +00004257 }
drh75897232000-05-29 14:26:00 +00004258 lineno = 1;
4259 tplt_xfer(lemp->name,in,out,&lineno);
4260
4261 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004262 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004263 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004264 char *incName = file_makename(lemp, ".h");
4265 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4266 free(incName);
drh75897232000-05-29 14:26:00 +00004267 }
4268 tplt_xfer(lemp->name,in,out,&lineno);
4269
4270 /* Generate #defines for all tokens */
4271 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004272 const char *prefix;
drh75897232000-05-29 14:26:00 +00004273 fprintf(out,"#if INTERFACE\n"); lineno++;
4274 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4275 else prefix = "";
4276 for(i=1; i<lemp->nterminal; i++){
4277 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4278 lineno++;
4279 }
4280 fprintf(out,"#endif\n"); lineno++;
4281 }
4282 tplt_xfer(lemp->name,in,out,&lineno);
4283
4284 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004285 fprintf(out,"#define YYCODETYPE %s\n",
drhed0c15b2018-04-16 14:31:34 +00004286 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4287 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
drh75897232000-05-29 14:26:00 +00004288 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004289 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004290 if( lemp->wildcard ){
4291 fprintf(out,"#define YYWILDCARD %d\n",
4292 lemp->wildcard->index); lineno++;
4293 }
drh75897232000-05-29 14:26:00 +00004294 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004295 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004296 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004297 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4298 }else{
4299 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4300 }
drhca44b5a2007-02-22 23:06:58 +00004301 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004302 if( mhflag ){
4303 fprintf(out,"#if INTERFACE\n"); lineno++;
4304 }
4305 name = lemp->name ? lemp->name : "Parse";
4306 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004307 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004308 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4309 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004310 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4311 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
drhfb32c442018-04-21 13:51:42 +00004312 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4313 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
drh1f245e42002-03-11 13:55:50 +00004314 name,lemp->arg,&lemp->arg[i]); lineno++;
drhfb32c442018-04-21 13:51:42 +00004315 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
drh1f245e42002-03-11 13:55:50 +00004316 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004317 }else{
drhfb32c442018-04-21 13:51:42 +00004318 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4319 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4320 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
drh1f245e42002-03-11 13:55:50 +00004321 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4322 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004323 }
drhfb32c442018-04-21 13:51:42 +00004324 if( lemp->ctx && lemp->ctx[0] ){
4325 i = lemonStrlen(lemp->ctx);
4326 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4327 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4328 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4329 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4330 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4331 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4332 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4333 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4334 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4335 }else{
4336 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4337 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4338 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4339 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4340 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4341 }
drh75897232000-05-29 14:26:00 +00004342 if( mhflag ){
4343 fprintf(out,"#endif\n"); lineno++;
4344 }
drhed0c15b2018-04-16 14:31:34 +00004345 if( lemp->errsym && lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004346 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4347 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004348 }
drh0bd1f4e2002-06-06 18:54:39 +00004349 if( lemp->has_fallback ){
4350 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4351 }
drh75897232000-05-29 14:26:00 +00004352
drh3bd48ab2015-09-07 18:23:37 +00004353 /* Compute the action table, but do not output it yet. The action
4354 ** table must be computed before generating the YYNSTATE macro because
4355 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004356 */
drh3bd48ab2015-09-07 18:23:37 +00004357 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004358 if( ax==0 ){
4359 fprintf(stderr,"malloc failed\n");
4360 exit(1);
4361 }
drh3bd48ab2015-09-07 18:23:37 +00004362 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004363 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004364 ax[i*2].stp = stp;
4365 ax[i*2].isTkn = 1;
4366 ax[i*2].nAction = stp->nTknAct;
4367 ax[i*2+1].stp = stp;
4368 ax[i*2+1].isTkn = 0;
4369 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004370 }
drh8b582012003-10-21 13:16:03 +00004371 mxTknOfst = mnTknOfst = 0;
4372 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004373 /* In an effort to minimize the action table size, use the heuristic
4374 ** of placing the largest action sets first */
4375 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4376 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh3a9d6c72017-12-25 04:15:38 +00004377 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
drh3bd48ab2015-09-07 18:23:37 +00004378 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004379 stp = ax[i].stp;
4380 if( ax[i].isTkn ){
4381 for(ap=stp->ap; ap; ap=ap->next){
4382 int action;
4383 if( ap->sp->index>=lemp->nterminal ) continue;
4384 action = compute_action(lemp, ap);
4385 if( action<0 ) continue;
4386 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004387 }
drh3a9d6c72017-12-25 04:15:38 +00004388 stp->iTknOfst = acttab_insert(pActtab, 1);
drhfdbf9282003-10-21 16:34:41 +00004389 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4390 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4391 }else{
4392 for(ap=stp->ap; ap; ap=ap->next){
4393 int action;
4394 if( ap->sp->index<lemp->nterminal ) continue;
4395 if( ap->sp->index==lemp->nsymbol ) continue;
4396 action = compute_action(lemp, ap);
4397 if( action<0 ) continue;
4398 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004399 }
drh3a9d6c72017-12-25 04:15:38 +00004400 stp->iNtOfst = acttab_insert(pActtab, 0);
drhfdbf9282003-10-21 16:34:41 +00004401 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4402 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004403 }
drh337cd0d2015-09-07 23:40:42 +00004404#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4405 { int jj, nn;
4406 for(jj=nn=0; jj<pActtab->nAction; jj++){
4407 if( pActtab->aAction[jj].action<0 ) nn++;
4408 }
4409 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4410 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4411 ax[i].nAction, pActtab->nAction, nn);
4412 }
4413#endif
drh8b582012003-10-21 13:16:03 +00004414 }
drhfdbf9282003-10-21 16:34:41 +00004415 free(ax);
drh8b582012003-10-21 13:16:03 +00004416
drh756b41e2016-05-24 18:55:08 +00004417 /* Mark rules that are actually used for reduce actions after all
4418 ** optimizations have been applied
4419 */
4420 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4421 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004422 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4423 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004424 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004425 }
4426 }
4427 }
4428
drh3bd48ab2015-09-07 18:23:37 +00004429 /* Finish rendering the constants now that the action table has
4430 ** been computed */
4431 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4432 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh0d9de992017-12-26 18:04:23 +00004433 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004434 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004435 i = lemp->minShiftReduce;
4436 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4437 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004438 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004439 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4440 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4441 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4442 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4443 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004444 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004445 tplt_xfer(lemp->name,in,out,&lineno);
4446
4447 /* Now output the action table and its associates:
4448 **
4449 ** yy_action[] A single table containing all actions.
4450 ** yy_lookahead[] A table containing the lookahead for each entry in
4451 ** yy_action. Used to detect hash collisions.
4452 ** yy_shift_ofst[] For each state, the offset into yy_action for
4453 ** shifting terminals.
4454 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4455 ** shifting non-terminals after a reduce.
4456 ** yy_default[] Default action for each state.
4457 */
4458
drh8b582012003-10-21 13:16:03 +00004459 /* Output the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +00004460 lemp->nactiontab = n = acttab_action_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004461 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004462 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4463 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004464 for(i=j=0; i<n; i++){
4465 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004466 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004467 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004468 fprintf(out, " %4d,", action);
4469 if( j==9 || i==n-1 ){
4470 fprintf(out, "\n"); lineno++;
4471 j = 0;
4472 }else{
4473 j++;
4474 }
4475 }
4476 fprintf(out, "};\n"); lineno++;
4477
4478 /* Output the yy_lookahead table */
drh3a9d6c72017-12-25 04:15:38 +00004479 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004480 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004481 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004482 for(i=j=0; i<n; i++){
4483 int la = acttab_yylookahead(pActtab, i);
4484 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004485 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004486 fprintf(out, " %4d,", la);
drh2e517162019-08-28 02:09:47 +00004487 if( j==9 ){
drh8b582012003-10-21 13:16:03 +00004488 fprintf(out, "\n"); lineno++;
4489 j = 0;
4490 }else{
4491 j++;
4492 }
4493 }
drh2e517162019-08-28 02:09:47 +00004494 /* Add extra entries to the end of the yy_lookahead[] table so that
4495 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4496 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4497 nLookAhead = lemp->nterminal + lemp->nactiontab;
4498 while( i<nLookAhead ){
4499 if( j==0 ) fprintf(out," /* %5d */ ", i);
4500 fprintf(out, " %4d,", lemp->nterminal);
4501 if( j==9 ){
4502 fprintf(out, "\n"); lineno++;
4503 j = 0;
4504 }else{
4505 j++;
4506 }
4507 i++;
4508 }
mistachkinacf6e082019-09-11 15:25:26 +00004509 if( j>0 ){ fprintf(out, "\n"); lineno++; }
drh8b582012003-10-21 13:16:03 +00004510 fprintf(out, "};\n"); lineno++;
4511
4512 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004513 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004514 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004515 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4516 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4517 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004518 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004519 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4520 lineno++;
drhc75e0162015-09-07 02:23:02 +00004521 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004522 for(i=j=0; i<n; i++){
4523 int ofst;
4524 stp = lemp->sorted[i];
4525 ofst = stp->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004526 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
drhfdbf9282003-10-21 16:34:41 +00004527 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004528 fprintf(out, " %4d,", ofst);
4529 if( j==9 || i==n-1 ){
4530 fprintf(out, "\n"); lineno++;
4531 j = 0;
4532 }else{
4533 j++;
4534 }
4535 }
4536 fprintf(out, "};\n"); lineno++;
4537
4538 /* Output the yy_reduce_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004539 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004540 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004541 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4542 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4543 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004544 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004545 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4546 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004547 for(i=j=0; i<n; i++){
4548 int ofst;
4549 stp = lemp->sorted[i];
4550 ofst = stp->iNtOfst;
4551 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004552 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004553 fprintf(out, " %4d,", ofst);
4554 if( j==9 || i==n-1 ){
4555 fprintf(out, "\n"); lineno++;
4556 j = 0;
4557 }else{
4558 j++;
4559 }
4560 }
4561 fprintf(out, "};\n"); lineno++;
4562
4563 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004564 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004565 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004566 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004567 for(i=j=0; i<n; i++){
4568 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004569 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004570 if( stp->iDfltReduce<0 ){
4571 fprintf(out, " %4d,", lemp->errAction);
4572 }else{
4573 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4574 }
drh8b582012003-10-21 13:16:03 +00004575 if( j==9 || i==n-1 ){
4576 fprintf(out, "\n"); lineno++;
4577 j = 0;
4578 }else{
4579 j++;
4580 }
4581 }
4582 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004583 tplt_xfer(lemp->name,in,out,&lineno);
4584
drh0bd1f4e2002-06-06 18:54:39 +00004585 /* Generate the table of fallback tokens.
4586 */
4587 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004588 int mx = lemp->nterminal - 1;
drh010bdb42019-08-28 11:31:11 +00004589 /* 2019-08-28: Generate fallback entries for every token to avoid
4590 ** having to do a range check on the index */
4591 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
drhc75e0162015-09-07 02:23:02 +00004592 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004593 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004594 struct symbol *p = lemp->symbols[i];
4595 if( p->fallback==0 ){
4596 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4597 }else{
4598 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4599 p->name, p->fallback->name);
4600 }
4601 lineno++;
4602 }
4603 }
4604 tplt_xfer(lemp->name, in, out, &lineno);
4605
4606 /* Generate a table containing the symbolic name of every symbol
4607 */
drh75897232000-05-29 14:26:00 +00004608 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004609 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh3a9d6c72017-12-25 04:15:38 +00004610 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
drh75897232000-05-29 14:26:00 +00004611 }
drh75897232000-05-29 14:26:00 +00004612 tplt_xfer(lemp->name,in,out,&lineno);
4613
drh0bd1f4e2002-06-06 18:54:39 +00004614 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004615 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004616 ** when tracing REDUCE actions.
4617 */
4618 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004619 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004620 fprintf(out," /* %3d */ \"", i);
4621 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004622 fprintf(out,"\",\n"); lineno++;
4623 }
4624 tplt_xfer(lemp->name,in,out,&lineno);
4625
drh75897232000-05-29 14:26:00 +00004626 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004627 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004628 ** (In other words, generate the %destructor actions)
4629 */
drh75897232000-05-29 14:26:00 +00004630 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004631 int once = 1;
drh75897232000-05-29 14:26:00 +00004632 for(i=0; i<lemp->nsymbol; i++){
4633 struct symbol *sp = lemp->symbols[i];
4634 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004635 if( once ){
4636 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4637 once = 0;
4638 }
drhc53eed12009-06-12 17:46:19 +00004639 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004640 }
4641 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4642 if( i<lemp->nsymbol ){
4643 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4644 fprintf(out," break;\n"); lineno++;
4645 }
4646 }
drh8d659732005-01-13 23:54:06 +00004647 if( lemp->vardest ){
4648 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004649 int once = 1;
drh8d659732005-01-13 23:54:06 +00004650 for(i=0; i<lemp->nsymbol; i++){
4651 struct symbol *sp = lemp->symbols[i];
4652 if( sp==0 || sp->type==TERMINAL ||
4653 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004654 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004655 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004656 once = 0;
4657 }
drhc53eed12009-06-12 17:46:19 +00004658 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004659 dflt_sp = sp;
4660 }
4661 if( dflt_sp!=0 ){
4662 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004663 }
drh4dc8ef52008-07-01 17:13:57 +00004664 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004665 }
drh75897232000-05-29 14:26:00 +00004666 for(i=0; i<lemp->nsymbol; i++){
4667 struct symbol *sp = lemp->symbols[i];
4668 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004669 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004670 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004671
4672 /* Combine duplicate destructors into a single case */
4673 for(j=i+1; j<lemp->nsymbol; j++){
4674 struct symbol *sp2 = lemp->symbols[j];
4675 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4676 && sp2->dtnum==sp->dtnum
4677 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004678 fprintf(out," case %d: /* %s */\n",
4679 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004680 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004681 }
4682 }
4683
drh75897232000-05-29 14:26:00 +00004684 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4685 fprintf(out," break;\n"); lineno++;
4686 }
drh75897232000-05-29 14:26:00 +00004687 tplt_xfer(lemp->name,in,out,&lineno);
4688
4689 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004690 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004691 tplt_xfer(lemp->name,in,out,&lineno);
4692
drhcfc45b12018-12-03 23:57:27 +00004693 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4694 ** yyRuleInfoNRhs[].
drh75897232000-05-29 14:26:00 +00004695 **
4696 ** Note: This code depends on the fact that rules are number
4697 ** sequentually beginning with 0.
4698 */
drh5c8241b2017-12-24 23:38:10 +00004699 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drhcfc45b12018-12-03 23:57:27 +00004700 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4701 rule_print(out, rp);
4702 fprintf(out," */\n"); lineno++;
4703 }
4704 tplt_xfer(lemp->name,in,out,&lineno);
4705 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4706 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
drh5c8241b2017-12-24 23:38:10 +00004707 rule_print(out, rp);
4708 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004709 }
4710 tplt_xfer(lemp->name,in,out,&lineno);
4711
4712 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004713 i = 0;
drh75897232000-05-29 14:26:00 +00004714 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004715 i += translate_code(lemp, rp);
4716 }
4717 if( i ){
4718 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004719 }
drhc53eed12009-06-12 17:46:19 +00004720 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004721 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004722 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004723 if( rp->codeEmitted ) continue;
4724 if( rp->noCode ){
4725 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004726 continue;
4727 }
drh4ef07702016-03-16 19:45:54 +00004728 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004729 writeRuleText(out, rp);
4730 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004731 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004732 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4733 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004734 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004735 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004736 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004737 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004738 }
4739 }
drh75897232000-05-29 14:26:00 +00004740 emit_code(out,rp,lemp,&lineno);
4741 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004742 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004743 }
drhc53eed12009-06-12 17:46:19 +00004744 /* Finally, output the default: rule. We choose as the default: all
4745 ** empty actions. */
4746 fprintf(out," default:\n"); lineno++;
4747 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004748 if( rp->codeEmitted ) continue;
4749 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004750 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004751 writeRuleText(out, rp);
drhe94006e2019-12-10 20:41:48 +00004752 if( rp->neverReduce ){
4753 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
4754 rp->iRule); lineno++;
4755 }else if( rp->doesReduce ){
drh756b41e2016-05-24 18:55:08 +00004756 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4757 }else{
4758 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4759 rp->iRule); lineno++;
4760 }
drhc53eed12009-06-12 17:46:19 +00004761 }
4762 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004763 tplt_xfer(lemp->name,in,out,&lineno);
4764
4765 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004766 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004767 tplt_xfer(lemp->name,in,out,&lineno);
4768
4769 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004770 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004771 tplt_xfer(lemp->name,in,out,&lineno);
4772
4773 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004774 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004775 tplt_xfer(lemp->name,in,out,&lineno);
4776
4777 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004778 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004779
drhe2dcc422019-01-15 14:44:23 +00004780 acttab_free(pActtab);
drh75897232000-05-29 14:26:00 +00004781 fclose(in);
4782 fclose(out);
drhfe03dac2019-11-26 02:22:39 +00004783 if( sql ) fclose(sql);
drh75897232000-05-29 14:26:00 +00004784 return;
4785}
4786
4787/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004788void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004789{
4790 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004791 const char *prefix;
drh75897232000-05-29 14:26:00 +00004792 char line[LINESIZE];
4793 char pattern[LINESIZE];
4794 int i;
4795
4796 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4797 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004798 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004799 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004800 int nextChar;
drh75897232000-05-29 14:26:00 +00004801 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004802 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4803 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004804 if( strcmp(line,pattern) ) break;
4805 }
drh8ba0d1c2012-06-16 15:26:31 +00004806 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004807 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004808 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004809 /* No change in the file. Don't rewrite it. */
4810 return;
4811 }
4812 }
drh2aa6ca42004-09-10 00:14:04 +00004813 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004814 if( out ){
4815 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004816 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004817 }
drh06f60d82017-04-14 19:46:12 +00004818 fclose(out);
drh75897232000-05-29 14:26:00 +00004819 }
4820 return;
4821}
4822
4823/* Reduce the size of the action tables, if possible, by making use
4824** of defaults.
4825**
drhb59499c2002-02-23 18:45:13 +00004826** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004827** it the default. Except, there is no default if the wildcard token
4828** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004829*/
icculus9e44cf12010-02-14 17:14:22 +00004830void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004831{
4832 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004833 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004834 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004835 int nbest, n;
drh75897232000-05-29 14:26:00 +00004836 int i;
drhe09daa92006-06-10 13:29:31 +00004837 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004838
4839 for(i=0; i<lemp->nstate; i++){
4840 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004841 nbest = 0;
4842 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004843 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004844
drhb59499c2002-02-23 18:45:13 +00004845 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004846 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4847 usesWildcard = 1;
4848 }
drhb59499c2002-02-23 18:45:13 +00004849 if( ap->type!=REDUCE ) continue;
4850 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004851 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004852 if( rp==rbest ) continue;
4853 n = 1;
4854 for(ap2=ap->next; ap2; ap2=ap2->next){
4855 if( ap2->type!=REDUCE ) continue;
4856 rp2 = ap2->x.rp;
4857 if( rp2==rbest ) continue;
4858 if( rp2==rp ) n++;
4859 }
4860 if( n>nbest ){
4861 nbest = n;
4862 rbest = rp;
drh75897232000-05-29 14:26:00 +00004863 }
4864 }
drh06f60d82017-04-14 19:46:12 +00004865
drhb59499c2002-02-23 18:45:13 +00004866 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004867 ** is not at least 1 or if the wildcard token is a possible
4868 ** lookahead.
4869 */
4870 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004871
drhb59499c2002-02-23 18:45:13 +00004872
4873 /* Combine matching REDUCE actions into a single default */
4874 for(ap=stp->ap; ap; ap=ap->next){
4875 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4876 }
drh75897232000-05-29 14:26:00 +00004877 assert( ap );
4878 ap->sp = Symbol_new("{default}");
4879 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004880 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004881 }
4882 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004883
4884 for(ap=stp->ap; ap; ap=ap->next){
4885 if( ap->type==SHIFT ) break;
4886 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4887 }
4888 if( ap==0 ){
4889 stp->autoReduce = 1;
4890 stp->pDfltReduce = rbest;
4891 }
4892 }
4893
4894 /* Make a second pass over all states and actions. Convert
4895 ** every action that is a SHIFT to an autoReduce state into
4896 ** a SHIFTREDUCE action.
4897 */
4898 for(i=0; i<lemp->nstate; i++){
4899 stp = lemp->sorted[i];
4900 for(ap=stp->ap; ap; ap=ap->next){
4901 struct state *pNextState;
4902 if( ap->type!=SHIFT ) continue;
4903 pNextState = ap->x.stp;
4904 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4905 ap->type = SHIFTREDUCE;
4906 ap->x.rp = pNextState->pDfltReduce;
4907 }
4908 }
drh75897232000-05-29 14:26:00 +00004909 }
drhc173ad82016-05-23 16:15:02 +00004910
4911 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4912 ** (meaning that the SHIFTREDUCE will land back in the state where it
4913 ** started) and if there is no C-code associated with the reduce action,
4914 ** then we can go ahead and convert the action to be the same as the
4915 ** action for the RHS of the rule.
4916 */
4917 for(i=0; i<lemp->nstate; i++){
4918 stp = lemp->sorted[i];
4919 for(ap=stp->ap; ap; ap=nextap){
4920 nextap = ap->next;
4921 if( ap->type!=SHIFTREDUCE ) continue;
4922 rp = ap->x.rp;
4923 if( rp->noCode==0 ) continue;
4924 if( rp->nrhs!=1 ) continue;
4925#if 1
4926 /* Only apply this optimization to non-terminals. It would be OK to
4927 ** apply it to terminal symbols too, but that makes the parser tables
4928 ** larger. */
4929 if( ap->sp->index<lemp->nterminal ) continue;
4930#endif
4931 /* If we reach this point, it means the optimization can be applied */
4932 nextap = ap;
4933 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4934 assert( ap2!=0 );
4935 ap->spOpt = ap2->sp;
4936 ap->type = ap2->type;
4937 ap->x = ap2->x;
4938 }
4939 }
drh75897232000-05-29 14:26:00 +00004940}
drhb59499c2002-02-23 18:45:13 +00004941
drhada354d2005-11-05 15:03:59 +00004942
4943/*
4944** Compare two states for sorting purposes. The smaller state is the
4945** one with the most non-terminal actions. If they have the same number
4946** of non-terminal actions, then the smaller is the one with the most
4947** token actions.
4948*/
4949static int stateResortCompare(const void *a, const void *b){
4950 const struct state *pA = *(const struct state**)a;
4951 const struct state *pB = *(const struct state**)b;
4952 int n;
4953
4954 n = pB->nNtAct - pA->nNtAct;
4955 if( n==0 ){
4956 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004957 if( n==0 ){
4958 n = pB->statenum - pA->statenum;
4959 }
drhada354d2005-11-05 15:03:59 +00004960 }
drhe594bc32009-11-03 13:02:25 +00004961 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004962 return n;
4963}
4964
4965
4966/*
4967** Renumber and resort states so that states with fewer choices
4968** occur at the end. Except, keep state 0 as the first state.
4969*/
icculus9e44cf12010-02-14 17:14:22 +00004970void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004971{
4972 int i;
4973 struct state *stp;
4974 struct action *ap;
4975
4976 for(i=0; i<lemp->nstate; i++){
4977 stp = lemp->sorted[i];
4978 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00004979 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004980 stp->iTknOfst = NO_OFFSET;
4981 stp->iNtOfst = NO_OFFSET;
4982 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004983 int iAction = compute_action(lemp,ap);
4984 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004985 if( ap->sp->index<lemp->nterminal ){
4986 stp->nTknAct++;
4987 }else if( ap->sp->index<lemp->nsymbol ){
4988 stp->nNtAct++;
4989 }else{
drh3bd48ab2015-09-07 18:23:37 +00004990 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00004991 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00004992 }
4993 }
4994 }
4995 }
4996 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4997 stateResortCompare);
4998 for(i=0; i<lemp->nstate; i++){
4999 lemp->sorted[i]->statenum = i;
5000 }
drh3bd48ab2015-09-07 18:23:37 +00005001 lemp->nxstate = lemp->nstate;
5002 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
5003 lemp->nxstate--;
5004 }
drhada354d2005-11-05 15:03:59 +00005005}
5006
5007
drh75897232000-05-29 14:26:00 +00005008/***************** From the file "set.c" ************************************/
5009/*
5010** Set manipulation routines for the LEMON parser generator.
5011*/
5012
5013static int size = 0;
5014
5015/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00005016void SetSize(int n)
drh75897232000-05-29 14:26:00 +00005017{
5018 size = n+1;
5019}
5020
5021/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00005022char *SetNew(void){
drh75897232000-05-29 14:26:00 +00005023 char *s;
drh9892c5d2007-12-21 00:02:11 +00005024 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00005025 if( s==0 ){
drh75897232000-05-29 14:26:00 +00005026 memory_error();
5027 }
drh75897232000-05-29 14:26:00 +00005028 return s;
5029}
5030
5031/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00005032void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00005033{
5034 free(s);
5035}
5036
5037/* Add a new element to the set. Return TRUE if the element was added
5038** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00005039int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00005040{
5041 int rv;
drh9892c5d2007-12-21 00:02:11 +00005042 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00005043 rv = s[e];
5044 s[e] = 1;
5045 return !rv;
5046}
5047
5048/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00005049int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00005050{
5051 int i, progress;
5052 progress = 0;
5053 for(i=0; i<size; i++){
5054 if( s2[i]==0 ) continue;
5055 if( s1[i]==0 ){
5056 progress = 1;
5057 s1[i] = 1;
5058 }
5059 }
5060 return progress;
5061}
5062/********************** From the file "table.c" ****************************/
5063/*
5064** All code in this file has been automatically generated
5065** from a specification in the file
5066** "table.q"
5067** by the associative array code building program "aagen".
5068** Do not edit this file! Instead, edit the specification
5069** file, then rerun aagen.
5070*/
5071/*
5072** Code for processing tables in the LEMON parser generator.
5073*/
5074
drh01f75f22013-10-02 20:46:30 +00005075PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00005076{
drh01f75f22013-10-02 20:46:30 +00005077 unsigned h = 0;
5078 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00005079 return h;
5080}
5081
5082/* Works like strdup, sort of. Save a string in malloced memory, but
5083** keep strings in a table so that the same string is not in more
5084** than one place.
5085*/
icculus9e44cf12010-02-14 17:14:22 +00005086const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00005087{
icculus9e44cf12010-02-14 17:14:22 +00005088 const char *z;
5089 char *cpy;
drh75897232000-05-29 14:26:00 +00005090
drh916f75f2006-07-17 00:19:39 +00005091 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00005092 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00005093 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00005094 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00005095 z = cpy;
drh75897232000-05-29 14:26:00 +00005096 Strsafe_insert(z);
5097 }
5098 MemoryCheck(z);
5099 return z;
5100}
5101
5102/* There is one instance of the following structure for each
5103** associative array of type "x1".
5104*/
5105struct s_x1 {
5106 int size; /* The number of available slots. */
5107 /* Must be a power of 2 greater than or */
5108 /* equal to 1 */
5109 int count; /* Number of currently slots filled */
5110 struct s_x1node *tbl; /* The data stored here */
5111 struct s_x1node **ht; /* Hash table for lookups */
5112};
5113
5114/* There is one instance of this structure for every data element
5115** in an associative array of type "x1".
5116*/
5117typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00005118 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00005119 struct s_x1node *next; /* Next entry with the same hash */
5120 struct s_x1node **from; /* Previous link */
5121} x1node;
5122
5123/* There is only one instance of the array, which is the following */
5124static struct s_x1 *x1a;
5125
5126/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005127void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00005128 if( x1a ) return;
5129 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5130 if( x1a ){
5131 x1a->size = 1024;
5132 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005133 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005134 if( x1a->tbl==0 ){
5135 free(x1a);
5136 x1a = 0;
5137 }else{
5138 int i;
5139 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5140 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5141 }
5142 }
5143}
5144/* Insert a new record into the array. Return TRUE if successful.
5145** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005146int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00005147{
5148 x1node *np;
drh01f75f22013-10-02 20:46:30 +00005149 unsigned h;
5150 unsigned ph;
drh75897232000-05-29 14:26:00 +00005151
5152 if( x1a==0 ) return 0;
5153 ph = strhash(data);
5154 h = ph & (x1a->size-1);
5155 np = x1a->ht[h];
5156 while( np ){
5157 if( strcmp(np->data,data)==0 ){
5158 /* An existing entry with the same key is found. */
5159 /* Fail because overwrite is not allows. */
5160 return 0;
5161 }
5162 np = np->next;
5163 }
5164 if( x1a->count>=x1a->size ){
5165 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005166 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005167 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00005168 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00005169 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00005170 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005171 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005172 array.ht = (x1node**)&(array.tbl[arrSize]);
5173 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005174 for(i=0; i<x1a->count; i++){
5175 x1node *oldnp, *newnp;
5176 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005177 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005178 newnp = &(array.tbl[i]);
5179 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5180 newnp->next = array.ht[h];
5181 newnp->data = oldnp->data;
5182 newnp->from = &(array.ht[h]);
5183 array.ht[h] = newnp;
5184 }
5185 free(x1a->tbl);
5186 *x1a = array;
5187 }
5188 /* Insert the new data */
5189 h = ph & (x1a->size-1);
5190 np = &(x1a->tbl[x1a->count++]);
5191 np->data = data;
5192 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5193 np->next = x1a->ht[h];
5194 x1a->ht[h] = np;
5195 np->from = &(x1a->ht[h]);
5196 return 1;
5197}
5198
5199/* Return a pointer to data assigned to the given key. Return NULL
5200** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005201const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00005202{
drh01f75f22013-10-02 20:46:30 +00005203 unsigned h;
drh75897232000-05-29 14:26:00 +00005204 x1node *np;
5205
5206 if( x1a==0 ) return 0;
5207 h = strhash(key) & (x1a->size-1);
5208 np = x1a->ht[h];
5209 while( np ){
5210 if( strcmp(np->data,key)==0 ) break;
5211 np = np->next;
5212 }
5213 return np ? np->data : 0;
5214}
5215
5216/* Return a pointer to the (terminal or nonterminal) symbol "x".
5217** Create a new symbol if this is the first time "x" has been seen.
5218*/
icculus9e44cf12010-02-14 17:14:22 +00005219struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00005220{
5221 struct symbol *sp;
5222
5223 sp = Symbol_find(x);
5224 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00005225 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00005226 MemoryCheck(sp);
5227 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00005228 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00005229 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00005230 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00005231 sp->prec = -1;
5232 sp->assoc = UNK;
5233 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005234 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005235 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005236 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005237 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005238 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005239 Symbol_insert(sp,sp->name);
5240 }
drhc4dd3fd2008-01-22 01:48:05 +00005241 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005242 return sp;
5243}
5244
drh61f92cd2014-01-11 03:06:18 +00005245/* Compare two symbols for sorting purposes. Return negative,
5246** zero, or positive if a is less then, equal to, or greater
5247** than b.
drh60d31652004-02-22 00:08:04 +00005248**
5249** Symbols that begin with upper case letters (terminals or tokens)
5250** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005251** (non-terminals). And MULTITERMINAL symbols (created using the
5252** %token_class directive) must sort at the very end. Other than
5253** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005254**
5255** We find experimentally that leaving the symbols in their original
5256** order (the order they appeared in the grammar file) gives the
5257** smallest parser tables in SQLite.
5258*/
icculus9e44cf12010-02-14 17:14:22 +00005259int Symbolcmpp(const void *_a, const void *_b)
5260{
drh61f92cd2014-01-11 03:06:18 +00005261 const struct symbol *a = *(const struct symbol **) _a;
5262 const struct symbol *b = *(const struct symbol **) _b;
5263 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5264 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5265 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005266}
5267
5268/* There is one instance of the following structure for each
5269** associative array of type "x2".
5270*/
5271struct s_x2 {
5272 int size; /* The number of available slots. */
5273 /* Must be a power of 2 greater than or */
5274 /* equal to 1 */
5275 int count; /* Number of currently slots filled */
5276 struct s_x2node *tbl; /* The data stored here */
5277 struct s_x2node **ht; /* Hash table for lookups */
5278};
5279
5280/* There is one instance of this structure for every data element
5281** in an associative array of type "x2".
5282*/
5283typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005284 struct symbol *data; /* The data */
5285 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005286 struct s_x2node *next; /* Next entry with the same hash */
5287 struct s_x2node **from; /* Previous link */
5288} x2node;
5289
5290/* There is only one instance of the array, which is the following */
5291static struct s_x2 *x2a;
5292
5293/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005294void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005295 if( x2a ) return;
5296 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5297 if( x2a ){
5298 x2a->size = 128;
5299 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005300 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005301 if( x2a->tbl==0 ){
5302 free(x2a);
5303 x2a = 0;
5304 }else{
5305 int i;
5306 x2a->ht = (x2node**)&(x2a->tbl[128]);
5307 for(i=0; i<128; i++) x2a->ht[i] = 0;
5308 }
5309 }
5310}
5311/* Insert a new record into the array. Return TRUE if successful.
5312** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005313int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005314{
5315 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005316 unsigned h;
5317 unsigned ph;
drh75897232000-05-29 14:26:00 +00005318
5319 if( x2a==0 ) return 0;
5320 ph = strhash(key);
5321 h = ph & (x2a->size-1);
5322 np = x2a->ht[h];
5323 while( np ){
5324 if( strcmp(np->key,key)==0 ){
5325 /* An existing entry with the same key is found. */
5326 /* Fail because overwrite is not allows. */
5327 return 0;
5328 }
5329 np = np->next;
5330 }
5331 if( x2a->count>=x2a->size ){
5332 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005333 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005334 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005335 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005336 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005337 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005338 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005339 array.ht = (x2node**)&(array.tbl[arrSize]);
5340 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005341 for(i=0; i<x2a->count; i++){
5342 x2node *oldnp, *newnp;
5343 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005344 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005345 newnp = &(array.tbl[i]);
5346 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5347 newnp->next = array.ht[h];
5348 newnp->key = oldnp->key;
5349 newnp->data = oldnp->data;
5350 newnp->from = &(array.ht[h]);
5351 array.ht[h] = newnp;
5352 }
5353 free(x2a->tbl);
5354 *x2a = array;
5355 }
5356 /* Insert the new data */
5357 h = ph & (x2a->size-1);
5358 np = &(x2a->tbl[x2a->count++]);
5359 np->key = key;
5360 np->data = data;
5361 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5362 np->next = x2a->ht[h];
5363 x2a->ht[h] = np;
5364 np->from = &(x2a->ht[h]);
5365 return 1;
5366}
5367
5368/* Return a pointer to data assigned to the given key. Return NULL
5369** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005370struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005371{
drh01f75f22013-10-02 20:46:30 +00005372 unsigned h;
drh75897232000-05-29 14:26:00 +00005373 x2node *np;
5374
5375 if( x2a==0 ) return 0;
5376 h = strhash(key) & (x2a->size-1);
5377 np = x2a->ht[h];
5378 while( np ){
5379 if( strcmp(np->key,key)==0 ) break;
5380 np = np->next;
5381 }
5382 return np ? np->data : 0;
5383}
5384
5385/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005386struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005387{
5388 struct symbol *data;
5389 if( x2a && n>0 && n<=x2a->count ){
5390 data = x2a->tbl[n-1].data;
5391 }else{
5392 data = 0;
5393 }
5394 return data;
5395}
5396
5397/* Return the size of the array */
5398int Symbol_count()
5399{
5400 return x2a ? x2a->count : 0;
5401}
5402
5403/* Return an array of pointers to all data in the table.
5404** The array is obtained from malloc. Return NULL if memory allocation
5405** problems, or if the array is empty. */
5406struct symbol **Symbol_arrayof()
5407{
5408 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005409 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005410 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005411 arrSize = x2a->count;
5412 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005413 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005414 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005415 }
5416 return array;
5417}
5418
5419/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005420int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005421{
icculus9e44cf12010-02-14 17:14:22 +00005422 const struct config *a = (struct config *) _a;
5423 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005424 int x;
5425 x = a->rp->index - b->rp->index;
5426 if( x==0 ) x = a->dot - b->dot;
5427 return x;
5428}
5429
5430/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005431PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005432{
5433 int rc;
5434 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5435 rc = a->rp->index - b->rp->index;
5436 if( rc==0 ) rc = a->dot - b->dot;
5437 }
5438 if( rc==0 ){
5439 if( a ) rc = 1;
5440 if( b ) rc = -1;
5441 }
5442 return rc;
5443}
5444
5445/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005446PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005447{
drh01f75f22013-10-02 20:46:30 +00005448 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005449 while( a ){
5450 h = h*571 + a->rp->index*37 + a->dot;
5451 a = a->bp;
5452 }
5453 return h;
5454}
5455
5456/* Allocate a new state structure */
5457struct state *State_new()
5458{
icculus9e44cf12010-02-14 17:14:22 +00005459 struct state *newstate;
5460 newstate = (struct state *)calloc(1, sizeof(struct state) );
5461 MemoryCheck(newstate);
5462 return newstate;
drh75897232000-05-29 14:26:00 +00005463}
5464
5465/* There is one instance of the following structure for each
5466** associative array of type "x3".
5467*/
5468struct s_x3 {
5469 int size; /* The number of available slots. */
5470 /* Must be a power of 2 greater than or */
5471 /* equal to 1 */
5472 int count; /* Number of currently slots filled */
5473 struct s_x3node *tbl; /* The data stored here */
5474 struct s_x3node **ht; /* Hash table for lookups */
5475};
5476
5477/* There is one instance of this structure for every data element
5478** in an associative array of type "x3".
5479*/
5480typedef struct s_x3node {
5481 struct state *data; /* The data */
5482 struct config *key; /* The key */
5483 struct s_x3node *next; /* Next entry with the same hash */
5484 struct s_x3node **from; /* Previous link */
5485} x3node;
5486
5487/* There is only one instance of the array, which is the following */
5488static struct s_x3 *x3a;
5489
5490/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005491void State_init(void){
drh75897232000-05-29 14:26:00 +00005492 if( x3a ) return;
5493 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5494 if( x3a ){
5495 x3a->size = 128;
5496 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005497 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005498 if( x3a->tbl==0 ){
5499 free(x3a);
5500 x3a = 0;
5501 }else{
5502 int i;
5503 x3a->ht = (x3node**)&(x3a->tbl[128]);
5504 for(i=0; i<128; i++) x3a->ht[i] = 0;
5505 }
5506 }
5507}
5508/* Insert a new record into the array. Return TRUE if successful.
5509** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005510int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005511{
5512 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005513 unsigned h;
5514 unsigned ph;
drh75897232000-05-29 14:26:00 +00005515
5516 if( x3a==0 ) return 0;
5517 ph = statehash(key);
5518 h = ph & (x3a->size-1);
5519 np = x3a->ht[h];
5520 while( np ){
5521 if( statecmp(np->key,key)==0 ){
5522 /* An existing entry with the same key is found. */
5523 /* Fail because overwrite is not allows. */
5524 return 0;
5525 }
5526 np = np->next;
5527 }
5528 if( x3a->count>=x3a->size ){
5529 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005530 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005531 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005532 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005533 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005534 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005535 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005536 array.ht = (x3node**)&(array.tbl[arrSize]);
5537 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005538 for(i=0; i<x3a->count; i++){
5539 x3node *oldnp, *newnp;
5540 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005541 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005542 newnp = &(array.tbl[i]);
5543 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5544 newnp->next = array.ht[h];
5545 newnp->key = oldnp->key;
5546 newnp->data = oldnp->data;
5547 newnp->from = &(array.ht[h]);
5548 array.ht[h] = newnp;
5549 }
5550 free(x3a->tbl);
5551 *x3a = array;
5552 }
5553 /* Insert the new data */
5554 h = ph & (x3a->size-1);
5555 np = &(x3a->tbl[x3a->count++]);
5556 np->key = key;
5557 np->data = data;
5558 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5559 np->next = x3a->ht[h];
5560 x3a->ht[h] = np;
5561 np->from = &(x3a->ht[h]);
5562 return 1;
5563}
5564
5565/* Return a pointer to data assigned to the given key. Return NULL
5566** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005567struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005568{
drh01f75f22013-10-02 20:46:30 +00005569 unsigned h;
drh75897232000-05-29 14:26:00 +00005570 x3node *np;
5571
5572 if( x3a==0 ) return 0;
5573 h = statehash(key) & (x3a->size-1);
5574 np = x3a->ht[h];
5575 while( np ){
5576 if( statecmp(np->key,key)==0 ) break;
5577 np = np->next;
5578 }
5579 return np ? np->data : 0;
5580}
5581
5582/* Return an array of pointers to all data in the table.
5583** The array is obtained from malloc. Return NULL if memory allocation
5584** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005585struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005586{
5587 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005588 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005589 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005590 arrSize = x3a->count;
5591 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005592 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005593 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005594 }
5595 return array;
5596}
5597
5598/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005599PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005600{
drh01f75f22013-10-02 20:46:30 +00005601 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005602 h = h*571 + a->rp->index*37 + a->dot;
5603 return h;
5604}
5605
5606/* There is one instance of the following structure for each
5607** associative array of type "x4".
5608*/
5609struct s_x4 {
5610 int size; /* The number of available slots. */
5611 /* Must be a power of 2 greater than or */
5612 /* equal to 1 */
5613 int count; /* Number of currently slots filled */
5614 struct s_x4node *tbl; /* The data stored here */
5615 struct s_x4node **ht; /* Hash table for lookups */
5616};
5617
5618/* There is one instance of this structure for every data element
5619** in an associative array of type "x4".
5620*/
5621typedef struct s_x4node {
5622 struct config *data; /* The data */
5623 struct s_x4node *next; /* Next entry with the same hash */
5624 struct s_x4node **from; /* Previous link */
5625} x4node;
5626
5627/* There is only one instance of the array, which is the following */
5628static struct s_x4 *x4a;
5629
5630/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005631void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005632 if( x4a ) return;
5633 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5634 if( x4a ){
5635 x4a->size = 64;
5636 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005637 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005638 if( x4a->tbl==0 ){
5639 free(x4a);
5640 x4a = 0;
5641 }else{
5642 int i;
5643 x4a->ht = (x4node**)&(x4a->tbl[64]);
5644 for(i=0; i<64; i++) x4a->ht[i] = 0;
5645 }
5646 }
5647}
5648/* Insert a new record into the array. Return TRUE if successful.
5649** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005650int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005651{
5652 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005653 unsigned h;
5654 unsigned ph;
drh75897232000-05-29 14:26:00 +00005655
5656 if( x4a==0 ) return 0;
5657 ph = confighash(data);
5658 h = ph & (x4a->size-1);
5659 np = x4a->ht[h];
5660 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005661 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005662 /* An existing entry with the same key is found. */
5663 /* Fail because overwrite is not allows. */
5664 return 0;
5665 }
5666 np = np->next;
5667 }
5668 if( x4a->count>=x4a->size ){
5669 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005670 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005671 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005672 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005673 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005674 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005675 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005676 array.ht = (x4node**)&(array.tbl[arrSize]);
5677 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005678 for(i=0; i<x4a->count; i++){
5679 x4node *oldnp, *newnp;
5680 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005681 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005682 newnp = &(array.tbl[i]);
5683 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5684 newnp->next = array.ht[h];
5685 newnp->data = oldnp->data;
5686 newnp->from = &(array.ht[h]);
5687 array.ht[h] = newnp;
5688 }
5689 free(x4a->tbl);
5690 *x4a = array;
5691 }
5692 /* Insert the new data */
5693 h = ph & (x4a->size-1);
5694 np = &(x4a->tbl[x4a->count++]);
5695 np->data = data;
5696 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5697 np->next = x4a->ht[h];
5698 x4a->ht[h] = np;
5699 np->from = &(x4a->ht[h]);
5700 return 1;
5701}
5702
5703/* Return a pointer to data assigned to the given key. Return NULL
5704** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005705struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005706{
5707 int h;
5708 x4node *np;
5709
5710 if( x4a==0 ) return 0;
5711 h = confighash(key) & (x4a->size-1);
5712 np = x4a->ht[h];
5713 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005714 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005715 np = np->next;
5716 }
5717 return np ? np->data : 0;
5718}
5719
5720/* Remove all data from the table. Pass each data to the function "f"
5721** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005722void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005723{
5724 int i;
5725 if( x4a==0 || x4a->count==0 ) return;
5726 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5727 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5728 x4a->count = 0;
5729 return;
5730}