blob: 0a7b05a928b5043e3a46f73a0c9203a5930b4cc5 [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 */
drhce678c22019-12-11 18:53:51 +0000390 int nruleWithAction; /* Number of rules with actions */
drh75897232000-05-29 14:26:00 +0000391 int nsymbol; /* Number of terminal and nonterminal symbols */
392 int nterminal; /* Number of terminal symbols */
drh5c8241b2017-12-24 23:38:10 +0000393 int minShiftReduce; /* Minimum shift-reduce action value */
394 int errAction; /* Error action value */
395 int accAction; /* Accept action value */
396 int noAction; /* No-op action value */
397 int minReduce; /* Minimum reduce action */
398 int maxAction; /* Maximum action value of any kind */
drh75897232000-05-29 14:26:00 +0000399 struct symbol **symbols; /* Sorted array of pointers to symbols */
400 int errorcnt; /* Number of errors */
401 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000402 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000403 char *name; /* Name of the generated parser */
404 char *arg; /* Declaration of the 3th argument to parser */
drhfb32c442018-04-21 13:51:42 +0000405 char *ctx; /* Declaration of 2nd argument to constructor */
drh75897232000-05-29 14:26:00 +0000406 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000407 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000408 char *start; /* Name of the start symbol for the grammar */
409 char *stacksize; /* Size of the parser stack */
410 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000411 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000412 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000413 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000414 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000415 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000416 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000417 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000418 char *filename; /* Name of the input file */
419 char *outname; /* Name of the current output file */
420 char *tokenprefix; /* A prefix added to token names in the .h file */
421 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000422 int nactiontab; /* Number of entries in the yy_action[] table */
drh3a9d6c72017-12-25 04:15:38 +0000423 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
drhc75e0162015-09-07 02:23:02 +0000424 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000425 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000426 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000427 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000428 char *argv0; /* Name of the program */
429};
430
431#define MemoryCheck(X) if((X)==0){ \
432 extern void memory_error(); \
433 memory_error(); \
434}
435
436/**************** From the file "table.h" *********************************/
437/*
438** All code in this file has been automatically generated
439** from a specification in the file
440** "table.q"
441** by the associative array code building program "aagen".
442** Do not edit this file! Instead, edit the specification
443** file, then rerun aagen.
444*/
445/*
446** Code for processing tables in the LEMON parser generator.
447*/
drh75897232000-05-29 14:26:00 +0000448/* Routines for handling a strings */
449
icculus9e44cf12010-02-14 17:14:22 +0000450const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000451
icculus9e44cf12010-02-14 17:14:22 +0000452void Strsafe_init(void);
453int Strsafe_insert(const char *);
454const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000455
456/* Routines for handling symbols of the grammar */
457
icculus9e44cf12010-02-14 17:14:22 +0000458struct symbol *Symbol_new(const char *);
459int Symbolcmpp(const void *, const void *);
460void Symbol_init(void);
461int Symbol_insert(struct symbol *, const char *);
462struct symbol *Symbol_find(const char *);
463struct symbol *Symbol_Nth(int);
464int Symbol_count(void);
465struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000466
467/* Routines to manage the state table */
468
icculus9e44cf12010-02-14 17:14:22 +0000469int Configcmp(const char *, const char *);
470struct state *State_new(void);
471void State_init(void);
472int State_insert(struct state *, struct config *);
473struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000474struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000475
476/* Routines used for efficiency in Configlist_add */
477
icculus9e44cf12010-02-14 17:14:22 +0000478void Configtable_init(void);
479int Configtable_insert(struct config *);
480struct config *Configtable_find(struct config *);
481void Configtable_clear(int(*)(struct config *));
482
drh75897232000-05-29 14:26:00 +0000483/****************** From the file "action.c" *******************************/
484/*
485** Routines processing parser actions in the LEMON parser generator.
486*/
487
488/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000489static struct action *Action_new(void){
mistachkind9bc6e82019-05-10 16:16:19 +0000490 static struct action *actionfreelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000491 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000492
mistachkind9bc6e82019-05-10 16:16:19 +0000493 if( actionfreelist==0 ){
drh75897232000-05-29 14:26:00 +0000494 int i;
495 int amt = 100;
mistachkind9bc6e82019-05-10 16:16:19 +0000496 actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
497 if( actionfreelist==0 ){
drh75897232000-05-29 14:26:00 +0000498 fprintf(stderr,"Unable to allocate memory for a new parser action.");
499 exit(1);
500 }
mistachkind9bc6e82019-05-10 16:16:19 +0000501 for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
502 actionfreelist[amt-1].next = 0;
drh75897232000-05-29 14:26:00 +0000503 }
mistachkind9bc6e82019-05-10 16:16:19 +0000504 newaction = actionfreelist;
505 actionfreelist = actionfreelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000506 return newaction;
drh75897232000-05-29 14:26:00 +0000507}
508
drhe9278182007-07-18 18:16:29 +0000509/* Compare two actions for sorting purposes. Return negative, zero, or
510** positive if the first action is less than, equal to, or greater than
511** the first
512*/
513static int actioncmp(
514 struct action *ap1,
515 struct action *ap2
516){
drh75897232000-05-29 14:26:00 +0000517 int rc;
518 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000519 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000520 rc = (int)ap1->type - (int)ap2->type;
521 }
drh3bd48ab2015-09-07 18:23:37 +0000522 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000523 rc = ap1->x.rp->index - ap2->x.rp->index;
524 }
drhe594bc32009-11-03 13:02:25 +0000525 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000526 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000527 }
drh75897232000-05-29 14:26:00 +0000528 return rc;
529}
530
531/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000532static struct action *Action_sort(
533 struct action *ap
534){
535 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
536 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000537 return ap;
538}
539
icculus9e44cf12010-02-14 17:14:22 +0000540void Action_add(
541 struct action **app,
542 enum e_action type,
543 struct symbol *sp,
544 char *arg
545){
546 struct action *newaction;
547 newaction = Action_new();
548 newaction->next = *app;
549 *app = newaction;
550 newaction->type = type;
551 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000552 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000553 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000554 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000555 }else{
icculus9e44cf12010-02-14 17:14:22 +0000556 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000557 }
558}
drh8b582012003-10-21 13:16:03 +0000559/********************** New code to implement the "acttab" module ***********/
560/*
561** This module implements routines use to construct the yy_action[] table.
562*/
563
564/*
565** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000566** the following structure.
567**
568** The yy_action table maps the pair (state_number, lookahead) into an
569** action_number. The table is an array of integers pairs. The state_number
570** determines an initial offset into the yy_action array. The lookahead
571** value is then added to this initial offset to get an index X into the
572** yy_action array. If the aAction[X].lookahead equals the value of the
573** of the lookahead input, then the value of the action_number output is
574** aAction[X].action. If the lookaheads do not match then the
575** default action for the state_number is returned.
576**
577** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000578** into aLookahead[] using multiple calls to acttab_action(). Then the
579** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000580** array with a single call to acttab_insert(). The acttab_insert() call
581** also resets the aLookahead[] array in preparation for the next
582** state number.
drh8b582012003-10-21 13:16:03 +0000583*/
icculus9e44cf12010-02-14 17:14:22 +0000584struct lookahead_action {
585 int lookahead; /* Value of the lookahead token */
586 int action; /* Action to take on the given lookahead */
587};
drh8b582012003-10-21 13:16:03 +0000588typedef struct acttab acttab;
589struct acttab {
590 int nAction; /* Number of used slots in aAction[] */
591 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000592 struct lookahead_action
593 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000594 *aLookahead; /* A single new transaction set */
595 int mnLookahead; /* Minimum aLookahead[].lookahead */
596 int mnAction; /* Action associated with mnLookahead */
597 int mxLookahead; /* Maximum aLookahead[].lookahead */
598 int nLookahead; /* Used slots in aLookahead[] */
599 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
drh3a9d6c72017-12-25 04:15:38 +0000600 int nterminal; /* Number of terminal symbols */
601 int nsymbol; /* total number of symbols */
drh8b582012003-10-21 13:16:03 +0000602};
603
604/* Return the number of entries in the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +0000605#define acttab_lookahead_size(X) ((X)->nAction)
drh8b582012003-10-21 13:16:03 +0000606
607/* The value for the N-th entry in yy_action */
608#define acttab_yyaction(X,N) ((X)->aAction[N].action)
609
610/* The value for the N-th entry in yy_lookahead */
611#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
612
613/* Free all memory associated with the given acttab */
614void acttab_free(acttab *p){
615 free( p->aAction );
616 free( p->aLookahead );
617 free( p );
618}
619
620/* Allocate a new acttab structure */
drh3a9d6c72017-12-25 04:15:38 +0000621acttab *acttab_alloc(int nsymbol, int nterminal){
icculus9e44cf12010-02-14 17:14:22 +0000622 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000623 if( p==0 ){
624 fprintf(stderr,"Unable to allocate memory for a new acttab.");
625 exit(1);
626 }
627 memset(p, 0, sizeof(*p));
drh3a9d6c72017-12-25 04:15:38 +0000628 p->nsymbol = nsymbol;
629 p->nterminal = nterminal;
drh8b582012003-10-21 13:16:03 +0000630 return p;
631}
632
drh06f60d82017-04-14 19:46:12 +0000633/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000634**
635** This routine is called once for each lookahead for a particular
636** state.
drh8b582012003-10-21 13:16:03 +0000637*/
638void acttab_action(acttab *p, int lookahead, int action){
639 if( p->nLookahead>=p->nLookaheadAlloc ){
640 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000641 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000642 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
643 if( p->aLookahead==0 ){
644 fprintf(stderr,"malloc failed\n");
645 exit(1);
646 }
647 }
648 if( p->nLookahead==0 ){
649 p->mxLookahead = lookahead;
650 p->mnLookahead = lookahead;
651 p->mnAction = action;
652 }else{
653 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
654 if( p->mnLookahead>lookahead ){
655 p->mnLookahead = lookahead;
656 p->mnAction = action;
657 }
658 }
659 p->aLookahead[p->nLookahead].lookahead = lookahead;
660 p->aLookahead[p->nLookahead].action = action;
661 p->nLookahead++;
662}
663
664/*
665** Add the transaction set built up with prior calls to acttab_action()
666** into the current action table. Then reset the transaction set back
667** to an empty set in preparation for a new round of acttab_action() calls.
668**
669** Return the offset into the action table of the new transaction.
drh3a9d6c72017-12-25 04:15:38 +0000670**
671** If the makeItSafe parameter is true, then the offset is chosen so that
672** it is impossible to overread the yy_lookaside[] table regardless of
673** the lookaside token. This is done for the terminal symbols, as they
674** come from external inputs and can contain syntax errors. When makeItSafe
675** is false, there is more flexibility in selecting offsets, resulting in
676** a smaller table. For non-terminal symbols, which are never syntax errors,
677** makeItSafe can be false.
drh8b582012003-10-21 13:16:03 +0000678*/
drh3a9d6c72017-12-25 04:15:38 +0000679int acttab_insert(acttab *p, int makeItSafe){
680 int i, j, k, n, end;
drh8b582012003-10-21 13:16:03 +0000681 assert( p->nLookahead>0 );
682
683 /* Make sure we have enough space to hold the expanded action table
684 ** in the worst case. The worst case occurs if the transaction set
685 ** must be appended to the current action table
686 */
drh3a9d6c72017-12-25 04:15:38 +0000687 n = p->nsymbol + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000688 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000689 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000690 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000691 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000692 sizeof(p->aAction[0])*p->nActionAlloc);
693 if( p->aAction==0 ){
694 fprintf(stderr,"malloc failed\n");
695 exit(1);
696 }
drhfdbf9282003-10-21 16:34:41 +0000697 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000698 p->aAction[i].lookahead = -1;
699 p->aAction[i].action = -1;
700 }
701 }
702
drh06f60d82017-04-14 19:46:12 +0000703 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000704 ** duplicate of the current transaction set. Fall out of the loop
705 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000706 **
707 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
708 */
drh3a9d6c72017-12-25 04:15:38 +0000709 end = makeItSafe ? p->mnLookahead : 0;
710 for(i=p->nAction-1; i>=end; i--){
drhf16371d2009-11-03 19:18:31 +0000711 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000712 /* All lookaheads and actions in the aLookahead[] transaction
713 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000714 if( p->aAction[i].action!=p->mnAction ) continue;
715 for(j=0; j<p->nLookahead; j++){
716 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
717 if( k<0 || k>=p->nAction ) break;
718 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
719 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
720 }
721 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000722
723 /* No possible lookahead value that is not in the aLookahead[]
724 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000725 n = 0;
726 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000727 if( p->aAction[j].lookahead<0 ) continue;
728 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000729 }
drhfdbf9282003-10-21 16:34:41 +0000730 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000731 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000732 }
drh8b582012003-10-21 13:16:03 +0000733 }
734 }
drh8dc3e8f2010-01-07 03:53:03 +0000735
736 /* If no existing offsets exactly match the current transaction, find an
737 ** an empty offset in the aAction[] table in which we can add the
738 ** aLookahead[] transaction.
739 */
drh3a9d6c72017-12-25 04:15:38 +0000740 if( i<end ){
drh8dc3e8f2010-01-07 03:53:03 +0000741 /* Look for holes in the aAction[] table that fit the current
742 ** aLookahead[] transaction. Leave i set to the offset of the hole.
743 ** If no holes are found, i is left at p->nAction, which means the
744 ** transaction will be appended. */
drh3a9d6c72017-12-25 04:15:38 +0000745 i = makeItSafe ? p->mnLookahead : 0;
746 for(; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000747 if( p->aAction[i].lookahead<0 ){
748 for(j=0; j<p->nLookahead; j++){
749 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
750 if( k<0 ) break;
751 if( p->aAction[k].lookahead>=0 ) break;
752 }
753 if( j<p->nLookahead ) continue;
754 for(j=0; j<p->nAction; j++){
755 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
756 }
757 if( j==p->nAction ){
758 break; /* Fits in empty slots */
759 }
760 }
761 }
762 }
drh8b582012003-10-21 13:16:03 +0000763 /* Insert transaction set at index i. */
drh3a9d6c72017-12-25 04:15:38 +0000764#if 0
765 printf("Acttab:");
766 for(j=0; j<p->nLookahead; j++){
767 printf(" %d", p->aLookahead[j].lookahead);
768 }
769 printf(" inserted at %d\n", i);
770#endif
drh8b582012003-10-21 13:16:03 +0000771 for(j=0; j<p->nLookahead; j++){
772 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
773 p->aAction[k] = p->aLookahead[j];
774 if( k>=p->nAction ) p->nAction = k+1;
775 }
drh4396c612017-12-27 15:21:16 +0000776 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
drh8b582012003-10-21 13:16:03 +0000777 p->nLookahead = 0;
778
779 /* Return the offset that is added to the lookahead in order to get the
780 ** index into yy_action of the action */
781 return i - p->mnLookahead;
782}
783
drh3a9d6c72017-12-25 04:15:38 +0000784/*
785** Return the size of the action table without the trailing syntax error
786** entries.
787*/
788int acttab_action_size(acttab *p){
789 int n = p->nAction;
790 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
791 return n;
792}
793
drh75897232000-05-29 14:26:00 +0000794/********************** From the file "build.c" *****************************/
795/*
796** Routines to construction the finite state machine for the LEMON
797** parser generator.
798*/
799
800/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000801**
drh75897232000-05-29 14:26:00 +0000802** Those rules which have a precedence symbol coded in the input
803** grammar using the "[symbol]" construct will already have the
804** rp->precsym field filled. Other rules take as their precedence
805** symbol the first RHS symbol with a defined precedence. If there
806** are not RHS symbols with a defined precedence, the precedence
807** symbol field is left blank.
808*/
icculus9e44cf12010-02-14 17:14:22 +0000809void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000810{
811 struct rule *rp;
812 for(rp=xp->rule; rp; rp=rp->next){
813 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000814 int i, j;
815 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
816 struct symbol *sp = rp->rhs[i];
817 if( sp->type==MULTITERMINAL ){
818 for(j=0; j<sp->nsubsym; j++){
819 if( sp->subsym[j]->prec>=0 ){
820 rp->precsym = sp->subsym[j];
821 break;
822 }
823 }
824 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000825 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000826 }
drh75897232000-05-29 14:26:00 +0000827 }
828 }
829 }
830 return;
831}
832
833/* Find all nonterminals which will generate the empty string.
834** Then go back and compute the first sets of every nonterminal.
835** The first set is the set of all terminal symbols which can begin
836** a string generated by that nonterminal.
837*/
icculus9e44cf12010-02-14 17:14:22 +0000838void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000839{
drhfd405312005-11-06 04:06:59 +0000840 int i, j;
drh75897232000-05-29 14:26:00 +0000841 struct rule *rp;
842 int progress;
843
844 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000845 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000846 }
847 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
848 lemp->symbols[i]->firstset = SetNew();
849 }
850
851 /* First compute all lambdas */
852 do{
853 progress = 0;
854 for(rp=lemp->rule; rp; rp=rp->next){
855 if( rp->lhs->lambda ) continue;
856 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000857 struct symbol *sp = rp->rhs[i];
858 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
859 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000860 }
861 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000862 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000863 progress = 1;
864 }
865 }
866 }while( progress );
867
868 /* Now compute all first sets */
869 do{
870 struct symbol *s1, *s2;
871 progress = 0;
872 for(rp=lemp->rule; rp; rp=rp->next){
873 s1 = rp->lhs;
874 for(i=0; i<rp->nrhs; i++){
875 s2 = rp->rhs[i];
876 if( s2->type==TERMINAL ){
877 progress += SetAdd(s1->firstset,s2->index);
878 break;
drhfd405312005-11-06 04:06:59 +0000879 }else if( s2->type==MULTITERMINAL ){
880 for(j=0; j<s2->nsubsym; j++){
881 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
882 }
883 break;
drhf2f105d2012-08-20 15:53:54 +0000884 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000885 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000886 }else{
drh75897232000-05-29 14:26:00 +0000887 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000888 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000889 }
drh75897232000-05-29 14:26:00 +0000890 }
891 }
892 }while( progress );
893 return;
894}
895
896/* Compute all LR(0) states for the grammar. Links
897** are added to between some states so that the LR(1) follow sets
898** can be computed later.
899*/
icculus9e44cf12010-02-14 17:14:22 +0000900PRIVATE struct state *getstate(struct lemon *); /* forward reference */
901void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000902{
903 struct symbol *sp;
904 struct rule *rp;
905
906 Configlist_init();
907
908 /* Find the start symbol */
909 if( lemp->start ){
910 sp = Symbol_find(lemp->start);
911 if( sp==0 ){
912 ErrorMsg(lemp->filename,0,
913"The specified start symbol \"%s\" is not \
914in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000915symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000916 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000917 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000918 }
919 }else{
drh4ef07702016-03-16 19:45:54 +0000920 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000921 }
922
923 /* Make sure the start symbol doesn't occur on the right-hand side of
924 ** any rule. Report an error if it does. (YACC would generate a new
925 ** start symbol in this case.) */
926 for(rp=lemp->rule; rp; rp=rp->next){
927 int i;
928 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000929 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000930 ErrorMsg(lemp->filename,0,
931"The start symbol \"%s\" occurs on the \
932right-hand side of a rule. This will result in a parser which \
933does not work properly.",sp->name);
934 lemp->errorcnt++;
935 }
936 }
937 }
938
939 /* The basis configuration set for the first state
940 ** is all rules which have the start symbol as their
941 ** left-hand side */
942 for(rp=sp->rule; rp; rp=rp->nextlhs){
943 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000944 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000945 newcfp = Configlist_addbasis(rp,0);
946 SetAdd(newcfp->fws,0);
947 }
948
949 /* Compute the first state. All other states will be
950 ** computed automatically during the computation of the first one.
951 ** The returned pointer to the first state is not used. */
952 (void)getstate(lemp);
953 return;
954}
955
956/* Return a pointer to a state which is described by the configuration
957** list which has been built from calls to Configlist_add.
958*/
icculus9e44cf12010-02-14 17:14:22 +0000959PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
960PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000961{
962 struct config *cfp, *bp;
963 struct state *stp;
964
965 /* Extract the sorted basis of the new state. The basis was constructed
966 ** by prior calls to "Configlist_addbasis()". */
967 Configlist_sortbasis();
968 bp = Configlist_basis();
969
970 /* Get a state with the same basis */
971 stp = State_find(bp);
972 if( stp ){
973 /* A state with the same basis already exists! Copy all the follow-set
974 ** propagation links from the state under construction into the
975 ** preexisting state, then return a pointer to the preexisting state */
976 struct config *x, *y;
977 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
978 Plink_copy(&y->bplp,x->bplp);
979 Plink_delete(x->fplp);
980 x->fplp = x->bplp = 0;
981 }
982 cfp = Configlist_return();
983 Configlist_eat(cfp);
984 }else{
985 /* This really is a new state. Construct all the details */
986 Configlist_closure(lemp); /* Compute the configuration closure */
987 Configlist_sort(); /* Sort the configuration closure */
988 cfp = Configlist_return(); /* Get a pointer to the config list */
989 stp = State_new(); /* A new state structure */
990 MemoryCheck(stp);
991 stp->bp = bp; /* Remember the configuration basis */
992 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000993 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000994 stp->ap = 0; /* No actions, yet. */
995 State_insert(stp,stp->bp); /* Add to the state table */
996 buildshifts(lemp,stp); /* Recursively compute successor states */
997 }
998 return stp;
999}
1000
drhfd405312005-11-06 04:06:59 +00001001/*
1002** Return true if two symbols are the same.
1003*/
icculus9e44cf12010-02-14 17:14:22 +00001004int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +00001005{
1006 int i;
1007 if( a==b ) return 1;
1008 if( a->type!=MULTITERMINAL ) return 0;
1009 if( b->type!=MULTITERMINAL ) return 0;
1010 if( a->nsubsym!=b->nsubsym ) return 0;
1011 for(i=0; i<a->nsubsym; i++){
1012 if( a->subsym[i]!=b->subsym[i] ) return 0;
1013 }
1014 return 1;
1015}
1016
drh75897232000-05-29 14:26:00 +00001017/* Construct all successor states to the given state. A "successor"
1018** state is any state which can be reached by a shift action.
1019*/
icculus9e44cf12010-02-14 17:14:22 +00001020PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +00001021{
1022 struct config *cfp; /* For looping thru the config closure of "stp" */
1023 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +00001024 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +00001025 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1026 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1027 struct state *newstp; /* A pointer to a successor state */
1028
1029 /* Each configuration becomes complete after it contibutes to a successor
1030 ** state. Initially, all configurations are incomplete */
1031 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1032
1033 /* Loop through all configurations of the state "stp" */
1034 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1035 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1036 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1037 Configlist_reset(); /* Reset the new config set */
1038 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1039
1040 /* For every configuration in the state "stp" which has the symbol "sp"
1041 ** following its dot, add the same configuration to the basis set under
1042 ** construction but with the dot shifted one symbol to the right. */
1043 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1044 if( bcfp->status==COMPLETE ) continue; /* Already used */
1045 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1046 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001047 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001048 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001049 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1050 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001051 }
1052
1053 /* Get a pointer to the state described by the basis configuration set
1054 ** constructed in the preceding loop */
1055 newstp = getstate(lemp);
1056
1057 /* The state "newstp" is reached from the state "stp" by a shift action
1058 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001059 if( sp->type==MULTITERMINAL ){
1060 int i;
1061 for(i=0; i<sp->nsubsym; i++){
1062 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1063 }
1064 }else{
1065 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1066 }
drh75897232000-05-29 14:26:00 +00001067 }
1068}
1069
1070/*
1071** Construct the propagation links
1072*/
icculus9e44cf12010-02-14 17:14:22 +00001073void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001074{
1075 int i;
1076 struct config *cfp, *other;
1077 struct state *stp;
1078 struct plink *plp;
1079
1080 /* Housekeeping detail:
1081 ** Add to every propagate link a pointer back to the state to
1082 ** which the link is attached. */
1083 for(i=0; i<lemp->nstate; i++){
1084 stp = lemp->sorted[i];
1085 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1086 cfp->stp = stp;
1087 }
1088 }
1089
1090 /* Convert all backlinks into forward links. Only the forward
1091 ** links are used in the follow-set computation. */
1092 for(i=0; i<lemp->nstate; i++){
1093 stp = lemp->sorted[i];
1094 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1095 for(plp=cfp->bplp; plp; plp=plp->next){
1096 other = plp->cfp;
1097 Plink_add(&other->fplp,cfp);
1098 }
1099 }
1100 }
1101}
1102
1103/* Compute all followsets.
1104**
1105** A followset is the set of all symbols which can come immediately
1106** after a configuration.
1107*/
icculus9e44cf12010-02-14 17:14:22 +00001108void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001109{
1110 int i;
1111 struct config *cfp;
1112 struct plink *plp;
1113 int progress;
1114 int change;
1115
1116 for(i=0; i<lemp->nstate; i++){
1117 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1118 cfp->status = INCOMPLETE;
1119 }
1120 }
drh06f60d82017-04-14 19:46:12 +00001121
drh75897232000-05-29 14:26:00 +00001122 do{
1123 progress = 0;
1124 for(i=0; i<lemp->nstate; i++){
1125 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1126 if( cfp->status==COMPLETE ) continue;
1127 for(plp=cfp->fplp; plp; plp=plp->next){
1128 change = SetUnion(plp->cfp->fws,cfp->fws);
1129 if( change ){
1130 plp->cfp->status = INCOMPLETE;
1131 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001132 }
1133 }
drh75897232000-05-29 14:26:00 +00001134 cfp->status = COMPLETE;
1135 }
1136 }
1137 }while( progress );
1138}
1139
drh3cb2f6e2012-01-09 14:19:05 +00001140static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001141
1142/* Compute the reduce actions, and resolve conflicts.
1143*/
icculus9e44cf12010-02-14 17:14:22 +00001144void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001145{
1146 int i,j;
1147 struct config *cfp;
1148 struct state *stp;
1149 struct symbol *sp;
1150 struct rule *rp;
1151
drh06f60d82017-04-14 19:46:12 +00001152 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001153 ** A reduce action is added for each element of the followset of
1154 ** a configuration which has its dot at the extreme right.
1155 */
1156 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1157 stp = lemp->sorted[i];
1158 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1159 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1160 for(j=0; j<lemp->nterminal; j++){
1161 if( SetFind(cfp->fws,j) ){
1162 /* Add a reduce action to the state "stp" which will reduce by the
1163 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001164 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001165 }
drhf2f105d2012-08-20 15:53:54 +00001166 }
drh75897232000-05-29 14:26:00 +00001167 }
1168 }
1169 }
1170
1171 /* Add the accepting token */
1172 if( lemp->start ){
1173 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001174 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001175 }else{
drh4ef07702016-03-16 19:45:54 +00001176 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001177 }
1178 /* Add to the first state (which is always the starting state of the
1179 ** finite state machine) an action to ACCEPT if the lookahead is the
1180 ** start nonterminal. */
1181 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1182
1183 /* Resolve conflicts */
1184 for(i=0; i<lemp->nstate; i++){
1185 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001186 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001187 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001188 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001189 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001190 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1191 /* The two actions "ap" and "nap" have the same lookahead.
1192 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001193 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001194 }
1195 }
1196 }
1197
1198 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001199 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001200 for(i=0; i<lemp->nstate; i++){
1201 struct action *ap;
1202 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001203 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001204 }
1205 }
1206 for(rp=lemp->rule; rp; rp=rp->next){
1207 if( rp->canReduce ) continue;
1208 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1209 lemp->errorcnt++;
1210 }
1211}
1212
1213/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001214** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001215**
1216** NO LONGER TRUE:
1217** To resolve a conflict, first look to see if either action
1218** is on an error rule. In that case, take the action which
1219** is not associated with the error rule. If neither or both
1220** actions are associated with an error rule, then try to
1221** use precedence to resolve the conflict.
1222**
1223** If either action is a SHIFT, then it must be apx. This
1224** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1225*/
icculus9e44cf12010-02-14 17:14:22 +00001226static int resolve_conflict(
1227 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001228 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001229){
drh75897232000-05-29 14:26:00 +00001230 struct symbol *spx, *spy;
1231 int errcnt = 0;
1232 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001233 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001234 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001235 errcnt++;
1236 }
drh75897232000-05-29 14:26:00 +00001237 if( apx->type==SHIFT && apy->type==REDUCE ){
1238 spx = apx->sp;
1239 spy = apy->x.rp->precsym;
1240 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1241 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001242 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001243 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001244 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001245 apy->type = RD_RESOLVED;
1246 }else if( spx->prec<spy->prec ){
1247 apx->type = SH_RESOLVED;
1248 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1249 apy->type = RD_RESOLVED; /* associativity */
1250 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1251 apx->type = SH_RESOLVED;
1252 }else{
1253 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001254 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001255 }
1256 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1257 spx = apx->x.rp->precsym;
1258 spy = apy->x.rp->precsym;
1259 if( spx==0 || spy==0 || spx->prec<0 ||
1260 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001261 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001262 errcnt++;
1263 }else if( spx->prec>spy->prec ){
1264 apy->type = RD_RESOLVED;
1265 }else if( spx->prec<spy->prec ){
1266 apx->type = RD_RESOLVED;
1267 }
1268 }else{
drh06f60d82017-04-14 19:46:12 +00001269 assert(
drhb59499c2002-02-23 18:45:13 +00001270 apx->type==SH_RESOLVED ||
1271 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001272 apx->type==SSCONFLICT ||
1273 apx->type==SRCONFLICT ||
1274 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001275 apy->type==SH_RESOLVED ||
1276 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001277 apy->type==SSCONFLICT ||
1278 apy->type==SRCONFLICT ||
1279 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001280 );
1281 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1282 ** REDUCEs on the list. If we reach this point it must be because
1283 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001284 }
1285 return errcnt;
1286}
1287/********************* From the file "configlist.c" *************************/
1288/*
1289** Routines to processing a configuration list and building a state
1290** in the LEMON parser generator.
1291*/
1292
1293static struct config *freelist = 0; /* List of free configurations */
1294static struct config *current = 0; /* Top of list of configurations */
1295static struct config **currentend = 0; /* Last on list of configs */
1296static struct config *basis = 0; /* Top of list of basis configs */
1297static struct config **basisend = 0; /* End of list of basis configs */
1298
1299/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001300PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001301 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001302 if( freelist==0 ){
1303 int i;
1304 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001305 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001306 if( freelist==0 ){
1307 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1308 exit(1);
1309 }
1310 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1311 freelist[amt-1].next = 0;
1312 }
icculus9e44cf12010-02-14 17:14:22 +00001313 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001314 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001315 return newcfg;
drh75897232000-05-29 14:26:00 +00001316}
1317
1318/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001319PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001320{
1321 old->next = freelist;
1322 freelist = old;
1323}
1324
1325/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001326void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001327 current = 0;
1328 currentend = &current;
1329 basis = 0;
1330 basisend = &basis;
1331 Configtable_init();
1332 return;
1333}
1334
1335/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001336void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001337 current = 0;
1338 currentend = &current;
1339 basis = 0;
1340 basisend = &basis;
1341 Configtable_clear(0);
1342 return;
1343}
1344
1345/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001346struct config *Configlist_add(
1347 struct rule *rp, /* The rule */
1348 int dot /* Index into the RHS of the rule where the dot goes */
1349){
drh75897232000-05-29 14:26:00 +00001350 struct config *cfp, model;
1351
1352 assert( currentend!=0 );
1353 model.rp = rp;
1354 model.dot = dot;
1355 cfp = Configtable_find(&model);
1356 if( cfp==0 ){
1357 cfp = newconfig();
1358 cfp->rp = rp;
1359 cfp->dot = dot;
1360 cfp->fws = SetNew();
1361 cfp->stp = 0;
1362 cfp->fplp = cfp->bplp = 0;
1363 cfp->next = 0;
1364 cfp->bp = 0;
1365 *currentend = cfp;
1366 currentend = &cfp->next;
1367 Configtable_insert(cfp);
1368 }
1369 return cfp;
1370}
1371
1372/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001373struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001374{
1375 struct config *cfp, model;
1376
1377 assert( basisend!=0 );
1378 assert( currentend!=0 );
1379 model.rp = rp;
1380 model.dot = dot;
1381 cfp = Configtable_find(&model);
1382 if( cfp==0 ){
1383 cfp = newconfig();
1384 cfp->rp = rp;
1385 cfp->dot = dot;
1386 cfp->fws = SetNew();
1387 cfp->stp = 0;
1388 cfp->fplp = cfp->bplp = 0;
1389 cfp->next = 0;
1390 cfp->bp = 0;
1391 *currentend = cfp;
1392 currentend = &cfp->next;
1393 *basisend = cfp;
1394 basisend = &cfp->bp;
1395 Configtable_insert(cfp);
1396 }
1397 return cfp;
1398}
1399
1400/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001401void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001402{
1403 struct config *cfp, *newcfp;
1404 struct rule *rp, *newrp;
1405 struct symbol *sp, *xsp;
1406 int i, dot;
1407
1408 assert( currentend!=0 );
1409 for(cfp=current; cfp; cfp=cfp->next){
1410 rp = cfp->rp;
1411 dot = cfp->dot;
1412 if( dot>=rp->nrhs ) continue;
1413 sp = rp->rhs[dot];
1414 if( sp->type==NONTERMINAL ){
1415 if( sp->rule==0 && sp!=lemp->errsym ){
1416 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1417 sp->name);
1418 lemp->errorcnt++;
1419 }
1420 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1421 newcfp = Configlist_add(newrp,0);
1422 for(i=dot+1; i<rp->nrhs; i++){
1423 xsp = rp->rhs[i];
1424 if( xsp->type==TERMINAL ){
1425 SetAdd(newcfp->fws,xsp->index);
1426 break;
drhfd405312005-11-06 04:06:59 +00001427 }else if( xsp->type==MULTITERMINAL ){
1428 int k;
1429 for(k=0; k<xsp->nsubsym; k++){
1430 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1431 }
1432 break;
drhf2f105d2012-08-20 15:53:54 +00001433 }else{
drh75897232000-05-29 14:26:00 +00001434 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001435 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001436 }
1437 }
drh75897232000-05-29 14:26:00 +00001438 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1439 }
1440 }
1441 }
1442 return;
1443}
1444
1445/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001446void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001447 current = (struct config*)msort((char*)current,(char**)&(current->next),
1448 Configcmp);
drh75897232000-05-29 14:26:00 +00001449 currentend = 0;
1450 return;
1451}
1452
1453/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001454void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001455 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1456 Configcmp);
drh75897232000-05-29 14:26:00 +00001457 basisend = 0;
1458 return;
1459}
1460
1461/* Return a pointer to the head of the configuration list and
1462** reset the list */
drh14d88552017-04-14 19:44:15 +00001463struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001464 struct config *old;
1465 old = current;
1466 current = 0;
1467 currentend = 0;
1468 return old;
1469}
1470
1471/* Return a pointer to the head of the configuration list and
1472** reset the list */
drh14d88552017-04-14 19:44:15 +00001473struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001474 struct config *old;
1475 old = basis;
1476 basis = 0;
1477 basisend = 0;
1478 return old;
1479}
1480
1481/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001482void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001483{
1484 struct config *nextcfp;
1485 for(; cfp; cfp=nextcfp){
1486 nextcfp = cfp->next;
1487 assert( cfp->fplp==0 );
1488 assert( cfp->bplp==0 );
1489 if( cfp->fws ) SetFree(cfp->fws);
1490 deleteconfig(cfp);
1491 }
1492 return;
1493}
1494/***************** From the file "error.c" *********************************/
1495/*
1496** Code for printing error message.
1497*/
1498
drhf9a2e7b2003-04-15 01:49:48 +00001499void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001500 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001501 fprintf(stderr, "%s:%d: ", filename, lineno);
1502 va_start(ap, format);
1503 vfprintf(stderr,format,ap);
1504 va_end(ap);
1505 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001506}
1507/**************** From the file "main.c" ************************************/
1508/*
1509** Main program file for the LEMON parser generator.
1510*/
1511
1512/* Report an out-of-memory condition and abort. This function
1513** is used mostly by the "MemoryCheck" macro in struct.h
1514*/
drh14d88552017-04-14 19:44:15 +00001515void memory_error(void){
drh75897232000-05-29 14:26:00 +00001516 fprintf(stderr,"Out of memory. Aborting...\n");
1517 exit(1);
1518}
1519
drh6d08b4d2004-07-20 12:45:22 +00001520static int nDefine = 0; /* Number of -D options on the command line */
1521static char **azDefine = 0; /* Name of the -D macros */
1522
1523/* This routine is called with the argument to each -D command-line option.
1524** Add the macro defined to the azDefine array.
1525*/
1526static void handle_D_option(char *z){
1527 char **paz;
1528 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001529 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001530 if( azDefine==0 ){
1531 fprintf(stderr,"out of memory\n");
1532 exit(1);
1533 }
1534 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001535 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001536 if( *paz==0 ){
1537 fprintf(stderr,"out of memory\n");
1538 exit(1);
1539 }
drh898799f2014-01-10 23:21:00 +00001540 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001541 for(z=*paz; *z && *z!='='; z++){}
1542 *z = 0;
1543}
1544
drh9f88e6d2018-04-20 20:47:49 +00001545/* Rember the name of the output directory
1546*/
1547static char *outputDir = NULL;
1548static void handle_d_option(char *z){
1549 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1550 if( outputDir==0 ){
1551 fprintf(stderr,"out of memory\n");
1552 exit(1);
1553 }
1554 lemon_strcpy(outputDir, z);
1555}
1556
icculus3e143bd2010-02-14 00:48:49 +00001557static char *user_templatename = NULL;
1558static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001559 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001560 if( user_templatename==0 ){
1561 memory_error();
1562 }
drh898799f2014-01-10 23:21:00 +00001563 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001564}
drh75897232000-05-29 14:26:00 +00001565
drh711c9812016-05-23 14:24:31 +00001566/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001567static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1568 struct rule *pFirst = 0;
1569 struct rule **ppPrev = &pFirst;
1570 while( pA && pB ){
1571 if( pA->iRule<pB->iRule ){
1572 *ppPrev = pA;
1573 ppPrev = &pA->next;
1574 pA = pA->next;
1575 }else{
1576 *ppPrev = pB;
1577 ppPrev = &pB->next;
1578 pB = pB->next;
1579 }
1580 }
1581 if( pA ){
1582 *ppPrev = pA;
1583 }else{
1584 *ppPrev = pB;
1585 }
1586 return pFirst;
1587}
1588
1589/*
1590** Sort a list of rules in order of increasing iRule value
1591*/
1592static struct rule *Rule_sort(struct rule *rp){
1593 int i;
1594 struct rule *pNext;
1595 struct rule *x[32];
1596 memset(x, 0, sizeof(x));
1597 while( rp ){
1598 pNext = rp->next;
1599 rp->next = 0;
1600 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1601 rp = Rule_merge(x[i], rp);
1602 x[i] = 0;
1603 }
1604 x[i] = rp;
1605 rp = pNext;
1606 }
1607 rp = 0;
1608 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1609 rp = Rule_merge(x[i], rp);
1610 }
1611 return rp;
1612}
1613
drhc75e0162015-09-07 02:23:02 +00001614/* forward reference */
1615static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1616
1617/* Print a single line of the "Parser Stats" output
1618*/
1619static void stats_line(const char *zLabel, int iValue){
1620 int nLabel = lemonStrlen(zLabel);
1621 printf(" %s%.*s %5d\n", zLabel,
1622 35-nLabel, "................................",
1623 iValue);
1624}
1625
drh75897232000-05-29 14:26:00 +00001626/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001627int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001628{
1629 static int version = 0;
1630 static int rpflag = 0;
1631 static int basisflag = 0;
1632 static int compress = 0;
1633 static int quiet = 0;
1634 static int statistics = 0;
1635 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001636 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001637 static int noResort = 0;
drhfe03dac2019-11-26 02:22:39 +00001638 static int sqlFlag = 0;
drh9f88e6d2018-04-20 20:47:49 +00001639
drh75897232000-05-29 14:26:00 +00001640 static struct s_options options[] = {
1641 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1642 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh9f88e6d2018-04-20 20:47:49 +00001643 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
drh6d08b4d2004-07-20 12:45:22 +00001644 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001645 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001646 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001647 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001648 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1649 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001650 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001651 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1652 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001653 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001654 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001655 {OPT_FLAG, "s", (char*)&statistics,
1656 "Print parser stats to standard output."},
drhfe03dac2019-11-26 02:22:39 +00001657 {OPT_FLAG, "S", (char*)&sqlFlag,
1658 "Generate the *.sql file describing the parser tables."},
drh75897232000-05-29 14:26:00 +00001659 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001660 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1661 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001662 {OPT_FLAG,0,0,0}
1663 };
1664 int i;
icculus42585cf2010-02-14 05:19:56 +00001665 int exitcode;
drh75897232000-05-29 14:26:00 +00001666 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001667 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001668
drhb0c86772000-06-02 23:21:26 +00001669 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001670 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001671 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001672 exit(0);
drh75897232000-05-29 14:26:00 +00001673 }
drhb0c86772000-06-02 23:21:26 +00001674 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001675 fprintf(stderr,"Exactly one filename argument is required.\n");
1676 exit(1);
1677 }
drh954f6b42006-06-13 13:27:46 +00001678 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001679 lem.errorcnt = 0;
1680
1681 /* Initialize the machine */
1682 Strsafe_init();
1683 Symbol_init();
1684 State_init();
1685 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001686 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001687 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001688 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001689 Symbol_new("$");
drh75897232000-05-29 14:26:00 +00001690
1691 /* Parse the input file */
1692 Parse(&lem);
1693 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001694 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001695 fprintf(stderr,"Empty grammar.\n");
1696 exit(1);
1697 }
drhed0c15b2018-04-16 14:31:34 +00001698 lem.errsym = Symbol_find("error");
drh75897232000-05-29 14:26:00 +00001699
1700 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001701 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001702 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001703 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001704 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1705 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1706 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1707 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1708 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1709 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001710 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001711 lem.nterminal = i;
1712
drh711c9812016-05-23 14:24:31 +00001713 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1714 ** reduce action C-code associated with them last, so that the switch()
1715 ** statement that selects reduction actions will have a smaller jump table.
1716 */
drh4ef07702016-03-16 19:45:54 +00001717 for(i=0, rp=lem.rule; rp; rp=rp->next){
1718 rp->iRule = rp->code ? i++ : -1;
1719 }
drhce678c22019-12-11 18:53:51 +00001720 lem.nruleWithAction = i;
drh4ef07702016-03-16 19:45:54 +00001721 for(rp=lem.rule; rp; rp=rp->next){
1722 if( rp->iRule<0 ) rp->iRule = i++;
1723 }
1724 lem.startRule = lem.rule;
1725 lem.rule = Rule_sort(lem.rule);
1726
drh75897232000-05-29 14:26:00 +00001727 /* Generate a reprint of the grammar, if requested on the command line */
1728 if( rpflag ){
1729 Reprint(&lem);
1730 }else{
1731 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001732 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001733
1734 /* Find the precedence for every production rule (that has one) */
1735 FindRulePrecedences(&lem);
1736
1737 /* Compute the lambda-nonterminals and the first-sets for every
1738 ** nonterminal */
1739 FindFirstSets(&lem);
1740
1741 /* Compute all LR(0) states. Also record follow-set propagation
1742 ** links so that the follow-set can be computed later */
1743 lem.nstate = 0;
1744 FindStates(&lem);
1745 lem.sorted = State_arrayof();
1746
1747 /* Tie up loose ends on the propagation links */
1748 FindLinks(&lem);
1749
1750 /* Compute the follow set of every reducible configuration */
1751 FindFollowSets(&lem);
1752
1753 /* Compute the action tables */
1754 FindActions(&lem);
1755
1756 /* Compress the action tables */
1757 if( compress==0 ) CompressTables(&lem);
1758
drhada354d2005-11-05 15:03:59 +00001759 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001760 ** occur at the end. This is an optimization that helps make the
1761 ** generated parser tables smaller. */
1762 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001763
drh75897232000-05-29 14:26:00 +00001764 /* Generate a report of the parser generated. (the "y.output" file) */
1765 if( !quiet ) ReportOutput(&lem);
1766
1767 /* Generate the source code for the parser */
drhfe03dac2019-11-26 02:22:39 +00001768 ReportTable(&lem, mhflag, sqlFlag);
drh75897232000-05-29 14:26:00 +00001769
1770 /* Produce a header file for use by the scanner. (This step is
1771 ** omitted if the "-m" option is used because makeheaders will
1772 ** generate the file for us.) */
1773 if( !mhflag ) ReportHeader(&lem);
1774 }
1775 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001776 printf("Parser statistics:\n");
1777 stats_line("terminal symbols", lem.nterminal);
1778 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1779 stats_line("total symbols", lem.nsymbol);
1780 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001781 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001782 stats_line("conflicts", lem.nconflict);
1783 stats_line("action table entries", lem.nactiontab);
drh3a9d6c72017-12-25 04:15:38 +00001784 stats_line("lookahead table entries", lem.nlookaheadtab);
drhc75e0162015-09-07 02:23:02 +00001785 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001786 }
icculus8e158022010-02-16 16:09:03 +00001787 if( lem.nconflict > 0 ){
1788 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001789 }
1790
1791 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001792 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001793 exit(exitcode);
1794 return (exitcode);
drh75897232000-05-29 14:26:00 +00001795}
1796/******************** From the file "msort.c" *******************************/
1797/*
1798** A generic merge-sort program.
1799**
1800** USAGE:
1801** Let "ptr" be a pointer to some structure which is at the head of
1802** a null-terminated list. Then to sort the list call:
1803**
1804** ptr = msort(ptr,&(ptr->next),cmpfnc);
1805**
1806** In the above, "cmpfnc" is a pointer to a function which compares
1807** two instances of the structure and returns an integer, as in
1808** strcmp. The second argument is a pointer to the pointer to the
1809** second element of the linked list. This address is used to compute
1810** the offset to the "next" field within the structure. The offset to
1811** the "next" field must be constant for all structures in the list.
1812**
1813** The function returns a new pointer which is the head of the list
1814** after sorting.
1815**
1816** ALGORITHM:
1817** Merge-sort.
1818*/
1819
1820/*
1821** Return a pointer to the next structure in the linked list.
1822*/
drhd25d6922012-04-18 09:59:56 +00001823#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001824
1825/*
1826** Inputs:
1827** a: A sorted, null-terminated linked list. (May be null).
1828** b: A sorted, null-terminated linked list. (May be null).
1829** cmp: A pointer to the comparison function.
1830** offset: Offset in the structure to the "next" field.
1831**
1832** Return Value:
1833** A pointer to the head of a sorted list containing the elements
1834** of both a and b.
1835**
1836** Side effects:
1837** The "next" pointers for elements in the lists a and b are
1838** changed.
1839*/
drhe9278182007-07-18 18:16:29 +00001840static char *merge(
1841 char *a,
1842 char *b,
1843 int (*cmp)(const char*,const char*),
1844 int offset
1845){
drh75897232000-05-29 14:26:00 +00001846 char *ptr, *head;
1847
1848 if( a==0 ){
1849 head = b;
1850 }else if( b==0 ){
1851 head = a;
1852 }else{
drhe594bc32009-11-03 13:02:25 +00001853 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001854 ptr = a;
1855 a = NEXT(a);
1856 }else{
1857 ptr = b;
1858 b = NEXT(b);
1859 }
1860 head = ptr;
1861 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001862 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001863 NEXT(ptr) = a;
1864 ptr = a;
1865 a = NEXT(a);
1866 }else{
1867 NEXT(ptr) = b;
1868 ptr = b;
1869 b = NEXT(b);
1870 }
1871 }
1872 if( a ) NEXT(ptr) = a;
1873 else NEXT(ptr) = b;
1874 }
1875 return head;
1876}
1877
1878/*
1879** Inputs:
1880** list: Pointer to a singly-linked list of structures.
1881** next: Pointer to pointer to the second element of the list.
1882** cmp: A comparison function.
1883**
1884** Return Value:
1885** A pointer to the head of a sorted list containing the elements
1886** orginally in list.
1887**
1888** Side effects:
1889** The "next" pointers for elements in list are changed.
1890*/
1891#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001892static char *msort(
1893 char *list,
1894 char **next,
1895 int (*cmp)(const char*,const char*)
1896){
drhba99af52001-10-25 20:37:16 +00001897 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001898 char *ep;
1899 char *set[LISTSIZE];
1900 int i;
drh1cc0d112015-03-31 15:15:48 +00001901 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001902 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1903 while( list ){
1904 ep = list;
1905 list = NEXT(list);
1906 NEXT(ep) = 0;
1907 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1908 ep = merge(ep,set[i],cmp,offset);
1909 set[i] = 0;
1910 }
1911 set[i] = ep;
1912 }
1913 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001914 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001915 return ep;
1916}
1917/************************ From the file "option.c" **************************/
mistachkind9bc6e82019-05-10 16:16:19 +00001918static char **g_argv;
drh75897232000-05-29 14:26:00 +00001919static struct s_options *op;
1920static FILE *errstream;
1921
1922#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1923
1924/*
1925** Print the command line with a carrot pointing to the k-th character
1926** of the n-th field.
1927*/
icculus9e44cf12010-02-14 17:14:22 +00001928static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001929{
1930 int spcnt, i;
mistachkind9bc6e82019-05-10 16:16:19 +00001931 if( g_argv[0] ) fprintf(err,"%s",g_argv[0]);
1932 spcnt = lemonStrlen(g_argv[0]) + 1;
1933 for(i=1; i<n && g_argv[i]; i++){
1934 fprintf(err," %s",g_argv[i]);
1935 spcnt += lemonStrlen(g_argv[i])+1;
drh75897232000-05-29 14:26:00 +00001936 }
1937 spcnt += k;
mistachkind9bc6e82019-05-10 16:16:19 +00001938 for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
drh75897232000-05-29 14:26:00 +00001939 if( spcnt<20 ){
1940 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1941 }else{
1942 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1943 }
1944}
1945
1946/*
1947** Return the index of the N-th non-switch argument. Return -1
1948** if N is out of range.
1949*/
icculus9e44cf12010-02-14 17:14:22 +00001950static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001951{
1952 int i;
1953 int dashdash = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00001954 if( g_argv!=0 && *g_argv!=0 ){
1955 for(i=1; g_argv[i]; i++){
1956 if( dashdash || !ISOPT(g_argv[i]) ){
drh75897232000-05-29 14:26:00 +00001957 if( n==0 ) return i;
1958 n--;
1959 }
mistachkind9bc6e82019-05-10 16:16:19 +00001960 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
drh75897232000-05-29 14:26:00 +00001961 }
1962 }
1963 return -1;
1964}
1965
1966static char emsg[] = "Command line syntax error: ";
1967
1968/*
1969** Process a flag command line argument.
1970*/
icculus9e44cf12010-02-14 17:14:22 +00001971static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001972{
1973 int v;
1974 int errcnt = 0;
1975 int j;
1976 for(j=0; op[j].label; j++){
mistachkind9bc6e82019-05-10 16:16:19 +00001977 if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001978 }
mistachkind9bc6e82019-05-10 16:16:19 +00001979 v = g_argv[i][0]=='-' ? 1 : 0;
drh75897232000-05-29 14:26:00 +00001980 if( op[j].label==0 ){
1981 if( err ){
1982 fprintf(err,"%sundefined option.\n",emsg);
1983 errline(i,1,err);
1984 }
1985 errcnt++;
drh0325d392015-01-01 19:11:22 +00001986 }else if( op[j].arg==0 ){
1987 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001988 }else if( op[j].type==OPT_FLAG ){
1989 *((int*)op[j].arg) = v;
1990 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001991 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001992 }else if( op[j].type==OPT_FSTR ){
mistachkind9bc6e82019-05-10 16:16:19 +00001993 (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
drh75897232000-05-29 14:26:00 +00001994 }else{
1995 if( err ){
1996 fprintf(err,"%smissing argument on switch.\n",emsg);
1997 errline(i,1,err);
1998 }
1999 errcnt++;
2000 }
2001 return errcnt;
2002}
2003
2004/*
2005** Process a command line switch which has an argument.
2006*/
icculus9e44cf12010-02-14 17:14:22 +00002007static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00002008{
2009 int lv = 0;
2010 double dv = 0.0;
2011 char *sv = 0, *end;
2012 char *cp;
2013 int j;
2014 int errcnt = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00002015 cp = strchr(g_argv[i],'=');
drh43617e92006-03-06 20:55:46 +00002016 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00002017 *cp = 0;
2018 for(j=0; op[j].label; j++){
mistachkind9bc6e82019-05-10 16:16:19 +00002019 if( strcmp(g_argv[i],op[j].label)==0 ) break;
drh75897232000-05-29 14:26:00 +00002020 }
2021 *cp = '=';
2022 if( op[j].label==0 ){
2023 if( err ){
2024 fprintf(err,"%sundefined option.\n",emsg);
2025 errline(i,0,err);
2026 }
2027 errcnt++;
2028 }else{
2029 cp++;
2030 switch( op[j].type ){
2031 case OPT_FLAG:
2032 case OPT_FFLAG:
2033 if( err ){
2034 fprintf(err,"%soption requires an argument.\n",emsg);
2035 errline(i,0,err);
2036 }
2037 errcnt++;
2038 break;
2039 case OPT_DBL:
2040 case OPT_FDBL:
2041 dv = strtod(cp,&end);
2042 if( *end ){
2043 if( err ){
drh25473362015-09-04 18:03:45 +00002044 fprintf(err,
2045 "%sillegal character in floating-point argument.\n",emsg);
mistachkind9bc6e82019-05-10 16:16:19 +00002046 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
drh75897232000-05-29 14:26:00 +00002047 }
2048 errcnt++;
2049 }
2050 break;
2051 case OPT_INT:
2052 case OPT_FINT:
2053 lv = strtol(cp,&end,0);
2054 if( *end ){
2055 if( err ){
2056 fprintf(err,"%sillegal character in integer argument.\n",emsg);
mistachkind9bc6e82019-05-10 16:16:19 +00002057 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
drh75897232000-05-29 14:26:00 +00002058 }
2059 errcnt++;
2060 }
2061 break;
2062 case OPT_STR:
2063 case OPT_FSTR:
2064 sv = cp;
2065 break;
2066 }
2067 switch( op[j].type ){
2068 case OPT_FLAG:
2069 case OPT_FFLAG:
2070 break;
2071 case OPT_DBL:
2072 *(double*)(op[j].arg) = dv;
2073 break;
2074 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002075 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002076 break;
2077 case OPT_INT:
2078 *(int*)(op[j].arg) = lv;
2079 break;
2080 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002081 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002082 break;
2083 case OPT_STR:
2084 *(char**)(op[j].arg) = sv;
2085 break;
2086 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002087 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002088 break;
2089 }
2090 }
2091 return errcnt;
2092}
2093
icculus9e44cf12010-02-14 17:14:22 +00002094int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002095{
2096 int errcnt = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00002097 g_argv = a;
drh75897232000-05-29 14:26:00 +00002098 op = o;
2099 errstream = err;
mistachkind9bc6e82019-05-10 16:16:19 +00002100 if( g_argv && *g_argv && op ){
drh75897232000-05-29 14:26:00 +00002101 int i;
mistachkind9bc6e82019-05-10 16:16:19 +00002102 for(i=1; g_argv[i]; i++){
2103 if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
drh75897232000-05-29 14:26:00 +00002104 errcnt += handleflags(i,err);
mistachkind9bc6e82019-05-10 16:16:19 +00002105 }else if( strchr(g_argv[i],'=') ){
drh75897232000-05-29 14:26:00 +00002106 errcnt += handleswitch(i,err);
2107 }
2108 }
2109 }
2110 if( errcnt>0 ){
2111 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002112 OptPrint();
drh75897232000-05-29 14:26:00 +00002113 exit(1);
2114 }
2115 return 0;
2116}
2117
drh14d88552017-04-14 19:44:15 +00002118int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002119 int cnt = 0;
2120 int dashdash = 0;
2121 int i;
mistachkind9bc6e82019-05-10 16:16:19 +00002122 if( g_argv!=0 && g_argv[0]!=0 ){
2123 for(i=1; g_argv[i]; i++){
2124 if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
2125 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
drh75897232000-05-29 14:26:00 +00002126 }
2127 }
2128 return cnt;
2129}
2130
icculus9e44cf12010-02-14 17:14:22 +00002131char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002132{
2133 int i;
2134 i = argindex(n);
mistachkind9bc6e82019-05-10 16:16:19 +00002135 return i>=0 ? g_argv[i] : 0;
drh75897232000-05-29 14:26:00 +00002136}
2137
icculus9e44cf12010-02-14 17:14:22 +00002138void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002139{
2140 int i;
2141 i = argindex(n);
2142 if( i>=0 ) errline(i,0,errstream);
2143}
2144
drh14d88552017-04-14 19:44:15 +00002145void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002146 int i;
2147 int max, len;
2148 max = 0;
2149 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002150 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002151 switch( op[i].type ){
2152 case OPT_FLAG:
2153 case OPT_FFLAG:
2154 break;
2155 case OPT_INT:
2156 case OPT_FINT:
2157 len += 9; /* length of "<integer>" */
2158 break;
2159 case OPT_DBL:
2160 case OPT_FDBL:
2161 len += 6; /* length of "<real>" */
2162 break;
2163 case OPT_STR:
2164 case OPT_FSTR:
2165 len += 8; /* length of "<string>" */
2166 break;
2167 }
2168 if( len>max ) max = len;
2169 }
2170 for(i=0; op[i].label; i++){
2171 switch( op[i].type ){
2172 case OPT_FLAG:
2173 case OPT_FFLAG:
2174 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2175 break;
2176 case OPT_INT:
2177 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002178 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002179 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002180 break;
2181 case OPT_DBL:
2182 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002183 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002184 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002185 break;
2186 case OPT_STR:
2187 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002188 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002189 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002190 break;
2191 }
2192 }
2193}
2194/*********************** From the file "parse.c" ****************************/
2195/*
2196** Input file parser for the LEMON parser generator.
2197*/
2198
2199/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002200enum e_state {
2201 INITIALIZE,
2202 WAITING_FOR_DECL_OR_RULE,
2203 WAITING_FOR_DECL_KEYWORD,
2204 WAITING_FOR_DECL_ARG,
2205 WAITING_FOR_PRECEDENCE_SYMBOL,
2206 WAITING_FOR_ARROW,
2207 IN_RHS,
2208 LHS_ALIAS_1,
2209 LHS_ALIAS_2,
2210 LHS_ALIAS_3,
2211 RHS_ALIAS_1,
2212 RHS_ALIAS_2,
2213 PRECEDENCE_MARK_1,
2214 PRECEDENCE_MARK_2,
2215 RESYNC_AFTER_RULE_ERROR,
2216 RESYNC_AFTER_DECL_ERROR,
2217 WAITING_FOR_DESTRUCTOR_SYMBOL,
2218 WAITING_FOR_DATATYPE_SYMBOL,
2219 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002220 WAITING_FOR_WILDCARD_ID,
2221 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002222 WAITING_FOR_CLASS_TOKEN,
2223 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002224};
drh75897232000-05-29 14:26:00 +00002225struct pstate {
2226 char *filename; /* Name of the input file */
2227 int tokenlineno; /* Linenumber at which current token starts */
2228 int errorcnt; /* Number of errors so far */
2229 char *tokenstart; /* Text of current token */
2230 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002231 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002232 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002233 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002234 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002235 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002236 int nrhs; /* Number of right-hand side symbols seen */
2237 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002238 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002239 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002240 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002241 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002242 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002243 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002244 enum e_assoc declassoc; /* Assign this association to decl arguments */
2245 int preccounter; /* Assign this precedence to decl arguments */
2246 struct rule *firstrule; /* Pointer to first rule in the grammar */
2247 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2248};
2249
2250/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002251static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002252{
icculus9e44cf12010-02-14 17:14:22 +00002253 const char *x;
drh75897232000-05-29 14:26:00 +00002254 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2255#if 0
2256 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2257 x,psp->state);
2258#endif
2259 switch( psp->state ){
2260 case INITIALIZE:
2261 psp->prevrule = 0;
2262 psp->preccounter = 0;
2263 psp->firstrule = psp->lastrule = 0;
2264 psp->gp->nrule = 0;
2265 /* Fall thru to next case */
2266 case WAITING_FOR_DECL_OR_RULE:
2267 if( x[0]=='%' ){
2268 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002269 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002270 psp->lhs = Symbol_new(x);
2271 psp->nrhs = 0;
2272 psp->lhsalias = 0;
2273 psp->state = WAITING_FOR_ARROW;
2274 }else if( x[0]=='{' ){
2275 if( psp->prevrule==0 ){
2276 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002277"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002278fragment which begins on this line.");
2279 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002280 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002281 ErrorMsg(psp->filename,psp->tokenlineno,
2282"Code fragment beginning on this line is not the first \
2283to follow the previous rule.");
2284 psp->errorcnt++;
drhe94006e2019-12-10 20:41:48 +00002285 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
2286 psp->prevrule->neverReduce = 1;
drh75897232000-05-29 14:26:00 +00002287 }else{
2288 psp->prevrule->line = psp->tokenlineno;
2289 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002290 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002291 }
drh75897232000-05-29 14:26:00 +00002292 }else if( x[0]=='[' ){
2293 psp->state = PRECEDENCE_MARK_1;
2294 }else{
2295 ErrorMsg(psp->filename,psp->tokenlineno,
2296 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2297 x);
2298 psp->errorcnt++;
2299 }
2300 break;
2301 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002302 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "The precedence symbol must be a terminal.");
2305 psp->errorcnt++;
2306 }else if( psp->prevrule==0 ){
2307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "There is no prior rule to assign precedence \"[%s]\".",x);
2309 psp->errorcnt++;
2310 }else if( psp->prevrule->precsym!=0 ){
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312"Precedence mark on this line is not the first \
2313to follow the previous rule.");
2314 psp->errorcnt++;
2315 }else{
2316 psp->prevrule->precsym = Symbol_new(x);
2317 }
2318 psp->state = PRECEDENCE_MARK_2;
2319 break;
2320 case PRECEDENCE_MARK_2:
2321 if( x[0]!=']' ){
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "Missing \"]\" on precedence mark.");
2324 psp->errorcnt++;
2325 }
2326 psp->state = WAITING_FOR_DECL_OR_RULE;
2327 break;
2328 case WAITING_FOR_ARROW:
2329 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2330 psp->state = IN_RHS;
2331 }else if( x[0]=='(' ){
2332 psp->state = LHS_ALIAS_1;
2333 }else{
2334 ErrorMsg(psp->filename,psp->tokenlineno,
2335 "Expected to see a \":\" following the LHS symbol \"%s\".",
2336 psp->lhs->name);
2337 psp->errorcnt++;
2338 psp->state = RESYNC_AFTER_RULE_ERROR;
2339 }
2340 break;
2341 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002342 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002343 psp->lhsalias = x;
2344 psp->state = LHS_ALIAS_2;
2345 }else{
2346 ErrorMsg(psp->filename,psp->tokenlineno,
2347 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2348 x,psp->lhs->name);
2349 psp->errorcnt++;
2350 psp->state = RESYNC_AFTER_RULE_ERROR;
2351 }
2352 break;
2353 case LHS_ALIAS_2:
2354 if( x[0]==')' ){
2355 psp->state = LHS_ALIAS_3;
2356 }else{
2357 ErrorMsg(psp->filename,psp->tokenlineno,
2358 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2359 psp->errorcnt++;
2360 psp->state = RESYNC_AFTER_RULE_ERROR;
2361 }
2362 break;
2363 case LHS_ALIAS_3:
2364 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2365 psp->state = IN_RHS;
2366 }else{
2367 ErrorMsg(psp->filename,psp->tokenlineno,
2368 "Missing \"->\" following: \"%s(%s)\".",
2369 psp->lhs->name,psp->lhsalias);
2370 psp->errorcnt++;
2371 psp->state = RESYNC_AFTER_RULE_ERROR;
2372 }
2373 break;
2374 case IN_RHS:
2375 if( x[0]=='.' ){
2376 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002377 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002378 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002379 if( rp==0 ){
2380 ErrorMsg(psp->filename,psp->tokenlineno,
2381 "Can't allocate enough memory for this rule.");
2382 psp->errorcnt++;
2383 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002384 }else{
drh75897232000-05-29 14:26:00 +00002385 int i;
2386 rp->ruleline = psp->tokenlineno;
2387 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002388 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002389 for(i=0; i<psp->nrhs; i++){
2390 rp->rhs[i] = psp->rhs[i];
2391 rp->rhsalias[i] = psp->alias[i];
drh539e7412018-04-21 20:24:19 +00002392 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
drhf2f105d2012-08-20 15:53:54 +00002393 }
drh75897232000-05-29 14:26:00 +00002394 rp->lhs = psp->lhs;
2395 rp->lhsalias = psp->lhsalias;
2396 rp->nrhs = psp->nrhs;
2397 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002398 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002399 rp->precsym = 0;
2400 rp->index = psp->gp->nrule++;
2401 rp->nextlhs = rp->lhs->rule;
2402 rp->lhs->rule = rp;
2403 rp->next = 0;
2404 if( psp->firstrule==0 ){
2405 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002406 }else{
drh75897232000-05-29 14:26:00 +00002407 psp->lastrule->next = rp;
2408 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002409 }
drh75897232000-05-29 14:26:00 +00002410 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002411 }
drh75897232000-05-29 14:26:00 +00002412 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002413 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002414 if( psp->nrhs>=MAXRHS ){
2415 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002416 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002417 x);
2418 psp->errorcnt++;
2419 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002420 }else{
drh75897232000-05-29 14:26:00 +00002421 psp->rhs[psp->nrhs] = Symbol_new(x);
2422 psp->alias[psp->nrhs] = 0;
2423 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002424 }
drhfd405312005-11-06 04:06:59 +00002425 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2426 struct symbol *msp = psp->rhs[psp->nrhs-1];
2427 if( msp->type!=MULTITERMINAL ){
2428 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002429 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002430 memset(msp, 0, sizeof(*msp));
2431 msp->type = MULTITERMINAL;
2432 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002433 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002434 msp->subsym[0] = origsp;
2435 msp->name = origsp->name;
2436 psp->rhs[psp->nrhs-1] = msp;
2437 }
2438 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002439 msp->subsym = (struct symbol **) realloc(msp->subsym,
2440 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002441 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002442 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002443 ErrorMsg(psp->filename,psp->tokenlineno,
2444 "Cannot form a compound containing a non-terminal");
2445 psp->errorcnt++;
2446 }
drh75897232000-05-29 14:26:00 +00002447 }else if( x[0]=='(' && psp->nrhs>0 ){
2448 psp->state = RHS_ALIAS_1;
2449 }else{
2450 ErrorMsg(psp->filename,psp->tokenlineno,
2451 "Illegal character on RHS of rule: \"%s\".",x);
2452 psp->errorcnt++;
2453 psp->state = RESYNC_AFTER_RULE_ERROR;
2454 }
2455 break;
2456 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002457 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002458 psp->alias[psp->nrhs-1] = x;
2459 psp->state = RHS_ALIAS_2;
2460 }else{
2461 ErrorMsg(psp->filename,psp->tokenlineno,
2462 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2463 x,psp->rhs[psp->nrhs-1]->name);
2464 psp->errorcnt++;
2465 psp->state = RESYNC_AFTER_RULE_ERROR;
2466 }
2467 break;
2468 case RHS_ALIAS_2:
2469 if( x[0]==')' ){
2470 psp->state = IN_RHS;
2471 }else{
2472 ErrorMsg(psp->filename,psp->tokenlineno,
2473 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2474 psp->errorcnt++;
2475 psp->state = RESYNC_AFTER_RULE_ERROR;
2476 }
2477 break;
2478 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002479 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002480 psp->declkeyword = x;
2481 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002482 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002483 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002484 psp->state = WAITING_FOR_DECL_ARG;
2485 if( strcmp(x,"name")==0 ){
2486 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002487 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002488 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002489 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002490 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002491 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002492 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002493 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002494 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002495 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002496 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002497 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002498 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002499 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002500 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002501 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002502 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002503 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002504 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002505 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002506 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002507 }else if( strcmp(x,"extra_argument")==0 ){
2508 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002509 psp->insertLineMacro = 0;
drhfb32c442018-04-21 13:51:42 +00002510 }else if( strcmp(x,"extra_context")==0 ){
2511 psp->declargslot = &(psp->gp->ctx);
2512 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002513 }else if( strcmp(x,"token_type")==0 ){
2514 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002515 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002516 }else if( strcmp(x,"default_type")==0 ){
2517 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002518 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002519 }else if( strcmp(x,"stack_size")==0 ){
2520 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002521 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002522 }else if( strcmp(x,"start_symbol")==0 ){
2523 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002524 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002525 }else if( strcmp(x,"left")==0 ){
2526 psp->preccounter++;
2527 psp->declassoc = LEFT;
2528 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2529 }else if( strcmp(x,"right")==0 ){
2530 psp->preccounter++;
2531 psp->declassoc = RIGHT;
2532 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2533 }else if( strcmp(x,"nonassoc")==0 ){
2534 psp->preccounter++;
2535 psp->declassoc = NONE;
2536 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002537 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002538 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002539 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002540 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002541 }else if( strcmp(x,"fallback")==0 ){
2542 psp->fallback = 0;
2543 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002544 }else if( strcmp(x,"token")==0 ){
2545 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002546 }else if( strcmp(x,"wildcard")==0 ){
2547 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002548 }else if( strcmp(x,"token_class")==0 ){
2549 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002550 }else{
2551 ErrorMsg(psp->filename,psp->tokenlineno,
2552 "Unknown declaration keyword: \"%%%s\".",x);
2553 psp->errorcnt++;
2554 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002555 }
drh75897232000-05-29 14:26:00 +00002556 }else{
2557 ErrorMsg(psp->filename,psp->tokenlineno,
2558 "Illegal declaration keyword: \"%s\".",x);
2559 psp->errorcnt++;
2560 psp->state = RESYNC_AFTER_DECL_ERROR;
2561 }
2562 break;
2563 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002564 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002565 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002566 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002567 psp->errorcnt++;
2568 psp->state = RESYNC_AFTER_DECL_ERROR;
2569 }else{
icculusd286fa62010-03-03 17:06:32 +00002570 struct symbol *sp = Symbol_new(x);
2571 psp->declargslot = &sp->destructor;
2572 psp->decllinenoslot = &sp->destLineno;
2573 psp->insertLineMacro = 1;
2574 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002575 }
2576 break;
2577 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002578 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002579 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002580 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002581 psp->errorcnt++;
2582 psp->state = RESYNC_AFTER_DECL_ERROR;
2583 }else{
icculus866bf1e2010-02-17 20:31:32 +00002584 struct symbol *sp = Symbol_find(x);
2585 if((sp) && (sp->datatype)){
2586 ErrorMsg(psp->filename,psp->tokenlineno,
2587 "Symbol %%type \"%s\" already defined", x);
2588 psp->errorcnt++;
2589 psp->state = RESYNC_AFTER_DECL_ERROR;
2590 }else{
2591 if (!sp){
2592 sp = Symbol_new(x);
2593 }
2594 psp->declargslot = &sp->datatype;
2595 psp->insertLineMacro = 0;
2596 psp->state = WAITING_FOR_DECL_ARG;
2597 }
drh75897232000-05-29 14:26:00 +00002598 }
2599 break;
2600 case WAITING_FOR_PRECEDENCE_SYMBOL:
2601 if( x[0]=='.' ){
2602 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002603 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002604 struct symbol *sp;
2605 sp = Symbol_new(x);
2606 if( sp->prec>=0 ){
2607 ErrorMsg(psp->filename,psp->tokenlineno,
2608 "Symbol \"%s\" has already be given a precedence.",x);
2609 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002610 }else{
drh75897232000-05-29 14:26:00 +00002611 sp->prec = psp->preccounter;
2612 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002613 }
drh75897232000-05-29 14:26:00 +00002614 }else{
2615 ErrorMsg(psp->filename,psp->tokenlineno,
2616 "Can't assign a precedence to \"%s\".",x);
2617 psp->errorcnt++;
2618 }
2619 break;
2620 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002621 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002622 const char *zOld, *zNew;
2623 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002624 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002625 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002626 char zLine[50];
2627 zNew = x;
2628 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002629 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002630 if( *psp->declargslot ){
2631 zOld = *psp->declargslot;
2632 }else{
2633 zOld = "";
2634 }
drh87cf1372008-08-13 20:09:06 +00002635 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002636 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002637 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002638 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2639 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002640 for(z=psp->filename, nBack=0; *z; z++){
2641 if( *z=='\\' ) nBack++;
2642 }
drh898799f2014-01-10 23:21:00 +00002643 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002644 nLine = lemonStrlen(zLine);
2645 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002646 }
icculus9e44cf12010-02-14 17:14:22 +00002647 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2648 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002649 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002650 if( nOld && zBuf[-1]!='\n' ){
2651 *(zBuf++) = '\n';
2652 }
2653 memcpy(zBuf, zLine, nLine);
2654 zBuf += nLine;
2655 *(zBuf++) = '"';
2656 for(z=psp->filename; *z; z++){
2657 if( *z=='\\' ){
2658 *(zBuf++) = '\\';
2659 }
2660 *(zBuf++) = *z;
2661 }
2662 *(zBuf++) = '"';
2663 *(zBuf++) = '\n';
2664 }
drh4dc8ef52008-07-01 17:13:57 +00002665 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2666 psp->decllinenoslot[0] = psp->tokenlineno;
2667 }
drha5808f32008-04-27 22:19:44 +00002668 memcpy(zBuf, zNew, nNew);
2669 zBuf += nNew;
2670 *zBuf = 0;
2671 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002672 }else{
2673 ErrorMsg(psp->filename,psp->tokenlineno,
2674 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2675 psp->errorcnt++;
2676 psp->state = RESYNC_AFTER_DECL_ERROR;
2677 }
2678 break;
drh0bd1f4e2002-06-06 18:54:39 +00002679 case WAITING_FOR_FALLBACK_ID:
2680 if( x[0]=='.' ){
2681 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002682 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002683 ErrorMsg(psp->filename, psp->tokenlineno,
2684 "%%fallback argument \"%s\" should be a token", x);
2685 psp->errorcnt++;
2686 }else{
2687 struct symbol *sp = Symbol_new(x);
2688 if( psp->fallback==0 ){
2689 psp->fallback = sp;
2690 }else if( sp->fallback ){
2691 ErrorMsg(psp->filename, psp->tokenlineno,
2692 "More than one fallback assigned to token %s", x);
2693 psp->errorcnt++;
2694 }else{
2695 sp->fallback = psp->fallback;
2696 psp->gp->has_fallback = 1;
2697 }
2698 }
2699 break;
drh59c435a2017-08-02 03:21:11 +00002700 case WAITING_FOR_TOKEN_NAME:
2701 /* Tokens do not have to be declared before use. But they can be
2702 ** in order to control their assigned integer number. The number for
2703 ** each token is assigned when it is first seen. So by including
2704 **
2705 ** %token ONE TWO THREE
2706 **
2707 ** early in the grammar file, that assigns small consecutive values
2708 ** to each of the tokens ONE TWO and THREE.
2709 */
2710 if( x[0]=='.' ){
2711 psp->state = WAITING_FOR_DECL_OR_RULE;
2712 }else if( !ISUPPER(x[0]) ){
2713 ErrorMsg(psp->filename, psp->tokenlineno,
2714 "%%token argument \"%s\" should be a token", x);
2715 psp->errorcnt++;
2716 }else{
2717 (void)Symbol_new(x);
2718 }
2719 break;
drhe09daa92006-06-10 13:29:31 +00002720 case WAITING_FOR_WILDCARD_ID:
2721 if( x[0]=='.' ){
2722 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002723 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002724 ErrorMsg(psp->filename, psp->tokenlineno,
2725 "%%wildcard argument \"%s\" should be a token", x);
2726 psp->errorcnt++;
2727 }else{
2728 struct symbol *sp = Symbol_new(x);
2729 if( psp->gp->wildcard==0 ){
2730 psp->gp->wildcard = sp;
2731 }else{
2732 ErrorMsg(psp->filename, psp->tokenlineno,
2733 "Extra wildcard to token: %s", x);
2734 psp->errorcnt++;
2735 }
2736 }
2737 break;
drh61f92cd2014-01-11 03:06:18 +00002738 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002739 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002740 ErrorMsg(psp->filename, psp->tokenlineno,
mistachkind9bc6e82019-05-10 16:16:19 +00002741 "%%token_class must be followed by an identifier: %s", x);
drh61f92cd2014-01-11 03:06:18 +00002742 psp->errorcnt++;
2743 psp->state = RESYNC_AFTER_DECL_ERROR;
2744 }else if( Symbol_find(x) ){
2745 ErrorMsg(psp->filename, psp->tokenlineno,
2746 "Symbol \"%s\" already used", x);
2747 psp->errorcnt++;
2748 psp->state = RESYNC_AFTER_DECL_ERROR;
2749 }else{
2750 psp->tkclass = Symbol_new(x);
2751 psp->tkclass->type = MULTITERMINAL;
2752 psp->state = WAITING_FOR_CLASS_TOKEN;
2753 }
2754 break;
2755 case WAITING_FOR_CLASS_TOKEN:
2756 if( x[0]=='.' ){
2757 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002758 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002759 struct symbol *msp = psp->tkclass;
2760 msp->nsubsym++;
2761 msp->subsym = (struct symbol **) realloc(msp->subsym,
2762 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002763 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002764 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2765 }else{
2766 ErrorMsg(psp->filename, psp->tokenlineno,
2767 "%%token_class argument \"%s\" should be a token", x);
2768 psp->errorcnt++;
2769 psp->state = RESYNC_AFTER_DECL_ERROR;
2770 }
2771 break;
drh75897232000-05-29 14:26:00 +00002772 case RESYNC_AFTER_RULE_ERROR:
2773/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2774** break; */
2775 case RESYNC_AFTER_DECL_ERROR:
2776 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2777 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2778 break;
2779 }
2780}
2781
drh34ff57b2008-07-14 12:27:51 +00002782/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002783** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2784** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2785** comments them out. Text in between is also commented out as appropriate.
2786*/
danielk1977940fac92005-01-23 22:41:37 +00002787static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002788 int i, j, k, n;
2789 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002790 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002791 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002792 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002793 for(i=0; z[i]; i++){
2794 if( z[i]=='\n' ) lineno++;
2795 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002796 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002797 if( exclude ){
2798 exclude--;
2799 if( exclude==0 ){
2800 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2801 }
2802 }
2803 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002804 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2805 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002806 if( exclude ){
2807 exclude++;
2808 }else{
drhc56fac72015-10-29 13:48:15 +00002809 for(j=i+7; ISSPACE(z[j]); j++){}
2810 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002811 exclude = 1;
2812 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002813 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002814 exclude = 0;
2815 break;
2816 }
2817 }
2818 if( z[i+3]=='n' ) exclude = !exclude;
2819 if( exclude ){
2820 start = i;
2821 start_lineno = lineno;
2822 }
2823 }
2824 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2825 }
2826 }
2827 if( exclude ){
2828 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2829 exit(1);
2830 }
2831}
2832
drh75897232000-05-29 14:26:00 +00002833/* In spite of its name, this function is really a scanner. It read
2834** in the entire input file (all at once) then tokenizes it. Each
2835** token is passed to the function "parseonetoken" which builds all
2836** the appropriate data structures in the global state vector "gp".
2837*/
icculus9e44cf12010-02-14 17:14:22 +00002838void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002839{
2840 struct pstate ps;
2841 FILE *fp;
2842 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002843 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002844 int lineno;
2845 int c;
2846 char *cp, *nextcp;
2847 int startline = 0;
2848
rse38514a92007-09-20 11:34:17 +00002849 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002850 ps.gp = gp;
2851 ps.filename = gp->filename;
2852 ps.errorcnt = 0;
2853 ps.state = INITIALIZE;
2854
2855 /* Begin by reading the input file */
2856 fp = fopen(ps.filename,"rb");
2857 if( fp==0 ){
2858 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2859 gp->errorcnt++;
2860 return;
2861 }
2862 fseek(fp,0,2);
2863 filesize = ftell(fp);
2864 rewind(fp);
2865 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002866 if( filesize>100000000 || filebuf==0 ){
2867 ErrorMsg(ps.filename,0,"Input file too large.");
mistachkinc93c6142018-09-08 16:55:18 +00002868 free(filebuf);
drh75897232000-05-29 14:26:00 +00002869 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002870 fclose(fp);
drh75897232000-05-29 14:26:00 +00002871 return;
2872 }
2873 if( fread(filebuf,1,filesize,fp)!=filesize ){
2874 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2875 filesize);
2876 free(filebuf);
2877 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002878 fclose(fp);
drh75897232000-05-29 14:26:00 +00002879 return;
2880 }
2881 fclose(fp);
2882 filebuf[filesize] = 0;
2883
drh6d08b4d2004-07-20 12:45:22 +00002884 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2885 preprocess_input(filebuf);
2886
drh75897232000-05-29 14:26:00 +00002887 /* Now scan the text of the input file */
2888 lineno = 1;
2889 for(cp=filebuf; (c= *cp)!=0; ){
2890 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002891 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002892 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2893 cp+=2;
2894 while( (c= *cp)!=0 && c!='\n' ) cp++;
2895 continue;
2896 }
2897 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2898 cp+=2;
2899 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2900 if( c=='\n' ) lineno++;
2901 cp++;
2902 }
2903 if( c ) cp++;
2904 continue;
2905 }
2906 ps.tokenstart = cp; /* Mark the beginning of the token */
2907 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2908 if( c=='\"' ){ /* String literals */
2909 cp++;
2910 while( (c= *cp)!=0 && c!='\"' ){
2911 if( c=='\n' ) lineno++;
2912 cp++;
2913 }
2914 if( c==0 ){
2915 ErrorMsg(ps.filename,startline,
2916"String starting on this line is not terminated before the end of the file.");
2917 ps.errorcnt++;
2918 nextcp = cp;
2919 }else{
2920 nextcp = cp+1;
2921 }
2922 }else if( c=='{' ){ /* A block of C code */
2923 int level;
2924 cp++;
2925 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2926 if( c=='\n' ) lineno++;
2927 else if( c=='{' ) level++;
2928 else if( c=='}' ) level--;
2929 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2930 int prevc;
2931 cp = &cp[2];
2932 prevc = 0;
2933 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2934 if( c=='\n' ) lineno++;
2935 prevc = c;
2936 cp++;
drhf2f105d2012-08-20 15:53:54 +00002937 }
2938 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002939 cp = &cp[2];
2940 while( (c= *cp)!=0 && c!='\n' ) cp++;
2941 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002942 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002943 int startchar, prevc;
2944 startchar = c;
2945 prevc = 0;
2946 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2947 if( c=='\n' ) lineno++;
2948 if( prevc=='\\' ) prevc = 0;
2949 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002950 }
2951 }
drh75897232000-05-29 14:26:00 +00002952 }
2953 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002954 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002955"C code starting on this line is not terminated before the end of the file.");
2956 ps.errorcnt++;
2957 nextcp = cp;
2958 }else{
2959 nextcp = cp+1;
2960 }
drhc56fac72015-10-29 13:48:15 +00002961 }else if( ISALNUM(c) ){ /* Identifiers */
2962 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002963 nextcp = cp;
2964 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2965 cp += 3;
2966 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002967 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002968 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002969 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002970 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002971 }else{ /* All other (one character) operators */
2972 cp++;
2973 nextcp = cp;
2974 }
2975 c = *cp;
2976 *cp = 0; /* Null terminate the token */
2977 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002978 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002979 cp = nextcp;
2980 }
2981 free(filebuf); /* Release the buffer after parsing */
2982 gp->rule = ps.firstrule;
2983 gp->errorcnt = ps.errorcnt;
2984}
2985/*************************** From the file "plink.c" *********************/
2986/*
2987** Routines processing configuration follow-set propagation links
2988** in the LEMON parser generator.
2989*/
2990static struct plink *plink_freelist = 0;
2991
2992/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00002993struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00002994 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002995
2996 if( plink_freelist==0 ){
2997 int i;
2998 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002999 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00003000 if( plink_freelist==0 ){
3001 fprintf(stderr,
3002 "Unable to allocate memory for a new follow-set propagation link.\n");
3003 exit(1);
3004 }
3005 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3006 plink_freelist[amt-1].next = 0;
3007 }
icculus9e44cf12010-02-14 17:14:22 +00003008 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00003009 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00003010 return newlink;
drh75897232000-05-29 14:26:00 +00003011}
3012
3013/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00003014void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00003015{
icculus9e44cf12010-02-14 17:14:22 +00003016 struct plink *newlink;
3017 newlink = Plink_new();
3018 newlink->next = *plpp;
3019 *plpp = newlink;
3020 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00003021}
3022
3023/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00003024void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00003025{
3026 struct plink *nextpl;
3027 while( from ){
3028 nextpl = from->next;
3029 from->next = *to;
3030 *to = from;
3031 from = nextpl;
3032 }
3033}
3034
3035/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00003036void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00003037{
3038 struct plink *nextpl;
3039
3040 while( plp ){
3041 nextpl = plp->next;
3042 plp->next = plink_freelist;
3043 plink_freelist = plp;
3044 plp = nextpl;
3045 }
3046}
3047/*********************** From the file "report.c" **************************/
3048/*
3049** Procedures for generating reports and tables in the LEMON parser generator.
3050*/
3051
3052/* Generate a filename with the given suffix. Space to hold the
3053** name comes from malloc() and must be freed by the calling
3054** function.
3055*/
icculus9e44cf12010-02-14 17:14:22 +00003056PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00003057{
3058 char *name;
3059 char *cp;
drh9f88e6d2018-04-20 20:47:49 +00003060 char *filename = lemp->filename;
3061 int sz;
drh75897232000-05-29 14:26:00 +00003062
drh9f88e6d2018-04-20 20:47:49 +00003063 if( outputDir ){
3064 cp = strrchr(filename, '/');
3065 if( cp ) filename = cp + 1;
3066 }
3067 sz = lemonStrlen(filename);
3068 sz += lemonStrlen(suffix);
3069 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3070 sz += 5;
3071 name = (char*)malloc( sz );
drh75897232000-05-29 14:26:00 +00003072 if( name==0 ){
3073 fprintf(stderr,"Can't allocate space for a filename.\n");
3074 exit(1);
3075 }
drh9f88e6d2018-04-20 20:47:49 +00003076 name[0] = 0;
3077 if( outputDir ){
3078 lemon_strcpy(name, outputDir);
3079 lemon_strcat(name, "/");
3080 }
3081 lemon_strcat(name,filename);
drh75897232000-05-29 14:26:00 +00003082 cp = strrchr(name,'.');
3083 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003084 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003085 return name;
3086}
3087
3088/* Open a file with a name based on the name of the input file,
3089** but with a different (specified) suffix, and return a pointer
3090** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003091PRIVATE FILE *file_open(
3092 struct lemon *lemp,
3093 const char *suffix,
3094 const char *mode
3095){
drh75897232000-05-29 14:26:00 +00003096 FILE *fp;
3097
3098 if( lemp->outname ) free(lemp->outname);
3099 lemp->outname = file_makename(lemp, suffix);
3100 fp = fopen(lemp->outname,mode);
3101 if( fp==0 && *mode=='w' ){
3102 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3103 lemp->errorcnt++;
3104 return 0;
3105 }
3106 return fp;
3107}
3108
drh5c8241b2017-12-24 23:38:10 +00003109/* Print the text of a rule
3110*/
3111void rule_print(FILE *out, struct rule *rp){
3112 int i, j;
3113 fprintf(out, "%s",rp->lhs->name);
3114 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3115 fprintf(out," ::=");
3116 for(i=0; i<rp->nrhs; i++){
3117 struct symbol *sp = rp->rhs[i];
3118 if( sp->type==MULTITERMINAL ){
3119 fprintf(out," %s", sp->subsym[0]->name);
3120 for(j=1; j<sp->nsubsym; j++){
3121 fprintf(out,"|%s", sp->subsym[j]->name);
3122 }
3123 }else{
3124 fprintf(out," %s", sp->name);
3125 }
3126 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3127 }
3128}
3129
drh06f60d82017-04-14 19:46:12 +00003130/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003131** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003132void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003133{
3134 struct rule *rp;
3135 struct symbol *sp;
3136 int i, j, maxlen, len, ncolumns, skip;
3137 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3138 maxlen = 10;
3139 for(i=0; i<lemp->nsymbol; i++){
3140 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003141 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003142 if( len>maxlen ) maxlen = len;
3143 }
3144 ncolumns = 76/(maxlen+5);
3145 if( ncolumns<1 ) ncolumns = 1;
3146 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3147 for(i=0; i<skip; i++){
3148 printf("//");
3149 for(j=i; j<lemp->nsymbol; j+=skip){
3150 sp = lemp->symbols[j];
3151 assert( sp->index==j );
3152 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3153 }
3154 printf("\n");
3155 }
3156 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003157 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003158 printf(".");
3159 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003160 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003161 printf("\n");
3162 }
3163}
3164
drh7e698e92015-09-07 14:22:24 +00003165/* Print a single rule.
3166*/
3167void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003168 struct symbol *sp;
3169 int i, j;
drh75897232000-05-29 14:26:00 +00003170 fprintf(fp,"%s ::=",rp->lhs->name);
3171 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003172 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003173 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003174 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003175 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003176 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003177 for(j=1; j<sp->nsubsym; j++){
3178 fprintf(fp,"|%s",sp->subsym[j]->name);
3179 }
drh61f92cd2014-01-11 03:06:18 +00003180 }else{
3181 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003182 }
drh75897232000-05-29 14:26:00 +00003183 }
3184}
3185
drh7e698e92015-09-07 14:22:24 +00003186/* Print the rule for a configuration.
3187*/
3188void ConfigPrint(FILE *fp, struct config *cfp){
3189 RulePrint(fp, cfp->rp, cfp->dot);
3190}
3191
drh75897232000-05-29 14:26:00 +00003192/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003193#if 0
drh75897232000-05-29 14:26:00 +00003194/* Print a set */
3195PRIVATE void SetPrint(out,set,lemp)
3196FILE *out;
3197char *set;
3198struct lemon *lemp;
3199{
3200 int i;
3201 char *spacer;
3202 spacer = "";
3203 fprintf(out,"%12s[","");
3204 for(i=0; i<lemp->nterminal; i++){
3205 if( SetFind(set,i) ){
3206 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3207 spacer = " ";
3208 }
3209 }
3210 fprintf(out,"]\n");
3211}
3212
3213/* Print a plink chain */
3214PRIVATE void PlinkPrint(out,plp,tag)
3215FILE *out;
3216struct plink *plp;
3217char *tag;
3218{
3219 while( plp ){
drhada354d2005-11-05 15:03:59 +00003220 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003221 ConfigPrint(out,plp->cfp);
3222 fprintf(out,"\n");
3223 plp = plp->next;
3224 }
3225}
3226#endif
3227
3228/* Print an action to the given file descriptor. Return FALSE if
3229** nothing was actually printed.
3230*/
drh7e698e92015-09-07 14:22:24 +00003231int PrintAction(
3232 struct action *ap, /* The action to print */
3233 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003234 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003235){
drh75897232000-05-29 14:26:00 +00003236 int result = 1;
3237 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003238 case SHIFT: {
3239 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003240 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003241 break;
drh7e698e92015-09-07 14:22:24 +00003242 }
3243 case REDUCE: {
3244 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003245 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003246 RulePrint(fp, rp, -1);
3247 break;
3248 }
3249 case SHIFTREDUCE: {
3250 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003251 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003252 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003253 break;
drh7e698e92015-09-07 14:22:24 +00003254 }
drh75897232000-05-29 14:26:00 +00003255 case ACCEPT:
3256 fprintf(fp,"%*s accept",indent,ap->sp->name);
3257 break;
3258 case ERROR:
3259 fprintf(fp,"%*s error",indent,ap->sp->name);
3260 break;
drh9892c5d2007-12-21 00:02:11 +00003261 case SRCONFLICT:
3262 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003263 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003264 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003265 break;
drh9892c5d2007-12-21 00:02:11 +00003266 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003267 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003268 indent,ap->sp->name,ap->x.stp->statenum);
3269 break;
drh75897232000-05-29 14:26:00 +00003270 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003271 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003272 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003273 indent,ap->sp->name,ap->x.stp->statenum);
3274 }else{
3275 result = 0;
3276 }
3277 break;
drh75897232000-05-29 14:26:00 +00003278 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003279 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003280 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003281 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003282 }else{
3283 result = 0;
3284 }
3285 break;
drh75897232000-05-29 14:26:00 +00003286 case NOT_USED:
3287 result = 0;
3288 break;
3289 }
drhc173ad82016-05-23 16:15:02 +00003290 if( result && ap->spOpt ){
3291 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3292 }
drh75897232000-05-29 14:26:00 +00003293 return result;
3294}
3295
drh3bd48ab2015-09-07 18:23:37 +00003296/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003297void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003298{
drh539e7412018-04-21 20:24:19 +00003299 int i, n;
drh75897232000-05-29 14:26:00 +00003300 struct state *stp;
3301 struct config *cfp;
3302 struct action *ap;
drh12f68392018-04-06 19:12:55 +00003303 struct rule *rp;
drh75897232000-05-29 14:26:00 +00003304 FILE *fp;
3305
drh2aa6ca42004-09-10 00:14:04 +00003306 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003307 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003308 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003309 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003310 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003311 if( lemp->basisflag ) cfp=stp->bp;
3312 else cfp=stp->cfp;
3313 while( cfp ){
3314 char buf[20];
3315 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003316 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003317 fprintf(fp," %5s ",buf);
3318 }else{
3319 fprintf(fp," ");
3320 }
3321 ConfigPrint(fp,cfp);
3322 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003323#if 0
drh75897232000-05-29 14:26:00 +00003324 SetPrint(fp,cfp->fws,lemp);
3325 PlinkPrint(fp,cfp->fplp,"To ");
3326 PlinkPrint(fp,cfp->bplp,"From");
3327#endif
3328 if( lemp->basisflag ) cfp=cfp->bp;
3329 else cfp=cfp->next;
3330 }
3331 fprintf(fp,"\n");
3332 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003333 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003334 }
3335 fprintf(fp,"\n");
3336 }
drhe9278182007-07-18 18:16:29 +00003337 fprintf(fp, "----------------------------------------------------\n");
3338 fprintf(fp, "Symbols:\n");
drh539e7412018-04-21 20:24:19 +00003339 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
drhe9278182007-07-18 18:16:29 +00003340 for(i=0; i<lemp->nsymbol; i++){
3341 int j;
3342 struct symbol *sp;
3343
3344 sp = lemp->symbols[i];
3345 fprintf(fp, " %3d: %s", i, sp->name);
3346 if( sp->type==NONTERMINAL ){
3347 fprintf(fp, ":");
3348 if( sp->lambda ){
3349 fprintf(fp, " <lambda>");
3350 }
3351 for(j=0; j<lemp->nterminal; j++){
3352 if( sp->firstset && SetFind(sp->firstset, j) ){
3353 fprintf(fp, " %s", lemp->symbols[j]->name);
3354 }
3355 }
3356 }
drh12f68392018-04-06 19:12:55 +00003357 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
drhe9278182007-07-18 18:16:29 +00003358 fprintf(fp, "\n");
3359 }
drh12f68392018-04-06 19:12:55 +00003360 fprintf(fp, "----------------------------------------------------\n");
drh539e7412018-04-21 20:24:19 +00003361 fprintf(fp, "Syntax-only Symbols:\n");
3362 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3363 for(i=n=0; i<lemp->nsymbol; i++){
3364 int w;
3365 struct symbol *sp = lemp->symbols[i];
3366 if( sp->bContent ) continue;
3367 w = (int)strlen(sp->name);
3368 if( n>0 && n+w>75 ){
3369 fprintf(fp,"\n");
3370 n = 0;
3371 }
3372 if( n>0 ){
3373 fprintf(fp, " ");
3374 n++;
3375 }
3376 fprintf(fp, "%s", sp->name);
3377 n += w;
3378 }
3379 if( n>0 ) fprintf(fp, "\n");
3380 fprintf(fp, "----------------------------------------------------\n");
drh12f68392018-04-06 19:12:55 +00003381 fprintf(fp, "Rules:\n");
3382 for(rp=lemp->rule; rp; rp=rp->next){
3383 fprintf(fp, "%4d: ", rp->iRule);
3384 rule_print(fp, rp);
3385 fprintf(fp,".");
3386 if( rp->precsym ){
3387 fprintf(fp," [%s precedence=%d]",
3388 rp->precsym->name, rp->precsym->prec);
3389 }
3390 fprintf(fp,"\n");
3391 }
drh75897232000-05-29 14:26:00 +00003392 fclose(fp);
3393 return;
3394}
3395
3396/* Search for the file "name" which is in the same directory as
3397** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003398PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003399{
icculus9e44cf12010-02-14 17:14:22 +00003400 const char *pathlist;
3401 char *pathbufptr;
3402 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003403 char *path,*cp;
3404 char c;
drh75897232000-05-29 14:26:00 +00003405
3406#ifdef __WIN32__
3407 cp = strrchr(argv0,'\\');
3408#else
3409 cp = strrchr(argv0,'/');
3410#endif
3411 if( cp ){
3412 c = *cp;
3413 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003414 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003415 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003416 *cp = c;
3417 }else{
drh75897232000-05-29 14:26:00 +00003418 pathlist = getenv("PATH");
3419 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003420 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003421 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003422 if( (pathbuf != 0) && (path!=0) ){
3423 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003424 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003425 while( *pathbuf ){
3426 cp = strchr(pathbuf,':');
3427 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003428 c = *cp;
3429 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003430 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003431 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003432 if( c==0 ) pathbuf[0] = 0;
3433 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003434 if( access(path,modemask)==0 ) break;
3435 }
icculus9e44cf12010-02-14 17:14:22 +00003436 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003437 }
3438 }
3439 return path;
3440}
3441
3442/* Given an action, compute the integer value for that action
3443** which is to be put in the action table of the generated machine.
3444** Return negative if no action should be generated.
3445*/
icculus9e44cf12010-02-14 17:14:22 +00003446PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003447{
3448 int act;
3449 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003450 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003451 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003452 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3453 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3454 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003455 if( ap->sp->index>=lemp->nterminal ){
3456 act = lemp->minReduce + ap->x.rp->iRule;
3457 }else{
3458 act = lemp->minShiftReduce + ap->x.rp->iRule;
3459 }
drhbd8fcc12017-06-28 11:56:18 +00003460 break;
3461 }
drh5c8241b2017-12-24 23:38:10 +00003462 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3463 case ERROR: act = lemp->errAction; break;
3464 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003465 default: act = -1; break;
3466 }
3467 return act;
3468}
3469
3470#define LINESIZE 1000
3471/* The next cluster of routines are for reading the template file
3472** and writing the results to the generated parser */
3473/* The first function transfers data from "in" to "out" until
3474** a line is seen which begins with "%%". The line number is
3475** tracked.
3476**
3477** if name!=0, then any word that begin with "Parse" is changed to
3478** begin with *name instead.
3479*/
icculus9e44cf12010-02-14 17:14:22 +00003480PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003481{
3482 int i, iStart;
3483 char line[LINESIZE];
3484 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3485 (*lineno)++;
3486 iStart = 0;
3487 if( name ){
3488 for(i=0; line[i]; i++){
3489 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003490 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003491 ){
3492 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3493 fprintf(out,"%s",name);
3494 i += 4;
3495 iStart = i+1;
3496 }
3497 }
3498 }
3499 fprintf(out,"%s",&line[iStart]);
3500 }
3501}
3502
3503/* The next function finds the template file and opens it, returning
3504** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003505PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003506{
3507 static char templatename[] = "lempar.c";
3508 char buf[1000];
3509 FILE *in;
3510 char *tpltname;
3511 char *cp;
3512
icculus3e143bd2010-02-14 00:48:49 +00003513 /* first, see if user specified a template filename on the command line. */
3514 if (user_templatename != 0) {
3515 if( access(user_templatename,004)==-1 ){
3516 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3517 user_templatename);
3518 lemp->errorcnt++;
3519 return 0;
3520 }
3521 in = fopen(user_templatename,"rb");
3522 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003523 fprintf(stderr,"Can't open the template file \"%s\".\n",
3524 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003525 lemp->errorcnt++;
3526 return 0;
3527 }
3528 return in;
3529 }
3530
drh75897232000-05-29 14:26:00 +00003531 cp = strrchr(lemp->filename,'.');
3532 if( cp ){
drh898799f2014-01-10 23:21:00 +00003533 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003534 }else{
drh898799f2014-01-10 23:21:00 +00003535 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003536 }
3537 if( access(buf,004)==0 ){
3538 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003539 }else if( access(templatename,004)==0 ){
3540 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003541 }else{
3542 tpltname = pathsearch(lemp->argv0,templatename,0);
3543 }
3544 if( tpltname==0 ){
3545 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3546 templatename);
3547 lemp->errorcnt++;
3548 return 0;
3549 }
drh2aa6ca42004-09-10 00:14:04 +00003550 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003551 if( in==0 ){
3552 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3553 lemp->errorcnt++;
3554 return 0;
3555 }
3556 return in;
3557}
3558
drhaf805ca2004-09-07 11:28:25 +00003559/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003560PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003561{
3562 fprintf(out,"#line %d \"",lineno);
3563 while( *filename ){
3564 if( *filename == '\\' ) putc('\\',out);
3565 putc(*filename,out);
3566 filename++;
3567 }
3568 fprintf(out,"\"\n");
3569}
3570
drh75897232000-05-29 14:26:00 +00003571/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003572PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003573{
3574 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003575 while( *str ){
drh75897232000-05-29 14:26:00 +00003576 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003577 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003578 str++;
3579 }
drh9db55df2004-09-09 14:01:21 +00003580 if( str[-1]!='\n' ){
3581 putc('\n',out);
3582 (*lineno)++;
3583 }
shane58543932008-12-10 20:10:04 +00003584 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003585 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003586 }
drh75897232000-05-29 14:26:00 +00003587 return;
3588}
3589
3590/*
3591** The following routine emits code for the destructor for the
3592** symbol sp
3593*/
icculus9e44cf12010-02-14 17:14:22 +00003594void emit_destructor_code(
3595 FILE *out,
3596 struct symbol *sp,
3597 struct lemon *lemp,
3598 int *lineno
3599){
drhcc83b6e2004-04-23 23:38:42 +00003600 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003601
drh75897232000-05-29 14:26:00 +00003602 if( sp->type==TERMINAL ){
3603 cp = lemp->tokendest;
3604 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003605 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003606 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003607 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003608 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003609 if( !lemp->nolinenosflag ){
3610 (*lineno)++;
3611 tplt_linedir(out,sp->destLineno,lemp->filename);
3612 }
drh960e8c62001-04-03 16:53:21 +00003613 }else if( lemp->vardest ){
3614 cp = lemp->vardest;
3615 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003616 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003617 }else{
3618 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003619 }
3620 for(; *cp; cp++){
3621 if( *cp=='$' && cp[1]=='$' ){
3622 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3623 cp++;
3624 continue;
3625 }
shane58543932008-12-10 20:10:04 +00003626 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003627 fputc(*cp,out);
3628 }
shane58543932008-12-10 20:10:04 +00003629 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003630 if (!lemp->nolinenosflag) {
3631 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003632 }
3633 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003634 return;
3635}
3636
3637/*
drh960e8c62001-04-03 16:53:21 +00003638** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003639*/
icculus9e44cf12010-02-14 17:14:22 +00003640int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003641{
3642 int ret;
3643 if( sp->type==TERMINAL ){
3644 ret = lemp->tokendest!=0;
3645 }else{
drh960e8c62001-04-03 16:53:21 +00003646 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003647 }
3648 return ret;
3649}
3650
drh0bb132b2004-07-20 14:06:51 +00003651/*
3652** Append text to a dynamically allocated string. If zText is 0 then
3653** reset the string to be empty again. Always return the complete text
3654** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003655**
3656** n bytes of zText are stored. If n==0 then all of zText up to the first
3657** \000 terminator is stored. zText can contain up to two instances of
3658** %d. The values of p1 and p2 are written into the first and second
3659** %d.
3660**
3661** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003662*/
icculus9e44cf12010-02-14 17:14:22 +00003663PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3664 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003665 static char *z = 0;
3666 static int alloced = 0;
3667 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003668 int c;
drh0bb132b2004-07-20 14:06:51 +00003669 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003670 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003671 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003672 used = 0;
3673 return z;
3674 }
drh7ac25c72004-08-19 15:12:26 +00003675 if( n<=0 ){
3676 if( n<0 ){
3677 used += n;
3678 assert( used>=0 );
3679 }
drh87cf1372008-08-13 20:09:06 +00003680 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003681 }
drhdf609712010-11-23 20:55:27 +00003682 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003683 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003684 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003685 }
icculus9e44cf12010-02-14 17:14:22 +00003686 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003687 while( n-- > 0 ){
3688 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003689 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003690 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003691 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003692 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003693 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003694 zText++;
3695 n--;
3696 }else{
mistachkin2318d332015-01-12 18:02:52 +00003697 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003698 }
3699 }
3700 z[used] = 0;
3701 return z;
3702}
3703
3704/*
drh711c9812016-05-23 14:24:31 +00003705** Write and transform the rp->code string so that symbols are expanded.
3706** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003707**
3708** Return 1 if the expanded code requires that "yylhsminor" local variable
3709** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003710*/
drhdabd04c2016-02-17 01:46:19 +00003711PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003712 char *cp, *xp;
3713 int i;
drhcf82f0d2016-02-17 04:33:10 +00003714 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003715 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003716 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3717 char lhsused = 0; /* True if the LHS element has been used */
3718 char lhsdirect; /* True if LHS writes directly into stack */
3719 char used[MAXRHS]; /* True for each RHS element which is used */
3720 char zLhs[50]; /* Convert the LHS symbol into this string */
3721 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003722
3723 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3724 lhsused = 0;
3725
drh19c9e562007-03-29 20:13:53 +00003726 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003727 static char newlinestr[2] = { '\n', '\0' };
3728 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003729 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003730 rp->noCode = 1;
3731 }else{
3732 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003733 }
3734
drh4dd0d3f2016-02-17 01:18:33 +00003735
drh2e55b042016-04-30 17:19:30 +00003736 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003737 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3738 lhsdirect = 1;
3739 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003740 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003741 ** we have to call the distructor on the RHS symbol first. */
3742 lhsdirect = 1;
3743 if( has_destructor(rp->rhs[0],lemp) ){
3744 append_str(0,0,0,0);
3745 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3746 rp->rhs[0]->index,1-rp->nrhs);
3747 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003748 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003749 }
drh2e55b042016-04-30 17:19:30 +00003750 }else if( rp->lhsalias==0 ){
3751 /* There is no LHS value symbol. */
3752 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003753 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003754 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003755 ** direct writing is allowed */
3756 lhsdirect = 1;
3757 lhsused = 1;
3758 used[0] = 1;
3759 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3760 ErrorMsg(lemp->filename,rp->ruleline,
3761 "%s(%s) and %s(%s) share the same label but have "
3762 "different datatypes.",
3763 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3764 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003765 }
drh4dd0d3f2016-02-17 01:18:33 +00003766 }else{
drhcf82f0d2016-02-17 04:33:10 +00003767 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3768 rp->lhsalias, rp->rhsalias[0]);
3769 zSkip = strstr(rp->code, zOvwrt);
3770 if( zSkip!=0 ){
3771 /* The code contains a special comment that indicates that it is safe
3772 ** for the LHS label to overwrite left-most RHS label. */
3773 lhsdirect = 1;
3774 }else{
3775 lhsdirect = 0;
3776 }
drh4dd0d3f2016-02-17 01:18:33 +00003777 }
3778 if( lhsdirect ){
3779 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3780 }else{
drhdabd04c2016-02-17 01:46:19 +00003781 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003782 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3783 }
3784
drh0bb132b2004-07-20 14:06:51 +00003785 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003786
3787 /* This const cast is wrong but harmless, if we're careful. */
3788 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003789 if( cp==zSkip ){
3790 append_str(zOvwrt,0,0,0);
3791 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003792 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003793 continue;
3794 }
drhc56fac72015-10-29 13:48:15 +00003795 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003796 char saved;
drhc56fac72015-10-29 13:48:15 +00003797 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003798 saved = *xp;
3799 *xp = 0;
3800 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003801 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003802 cp = xp;
3803 lhsused = 1;
3804 }else{
3805 for(i=0; i<rp->nrhs; i++){
3806 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003807 if( i==0 && dontUseRhs0 ){
3808 ErrorMsg(lemp->filename,rp->ruleline,
3809 "Label %s used after '%s'.",
3810 rp->rhsalias[0], zOvwrt);
3811 lemp->errorcnt++;
3812 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003813 /* If the argument is of the form @X then substituted
3814 ** the token number of X, not the value of X */
3815 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3816 }else{
drhfd405312005-11-06 04:06:59 +00003817 struct symbol *sp = rp->rhs[i];
3818 int dtnum;
3819 if( sp->type==MULTITERMINAL ){
3820 dtnum = sp->subsym[0]->dtnum;
3821 }else{
3822 dtnum = sp->dtnum;
3823 }
3824 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003825 }
drh0bb132b2004-07-20 14:06:51 +00003826 cp = xp;
3827 used[i] = 1;
3828 break;
3829 }
3830 }
3831 }
3832 *xp = saved;
3833 }
3834 append_str(cp, 1, 0, 0);
3835 } /* End loop */
3836
drh4dd0d3f2016-02-17 01:18:33 +00003837 /* Main code generation completed */
3838 cp = append_str(0,0,0,0);
3839 if( cp && cp[0] ) rp->code = Strsafe(cp);
3840 append_str(0,0,0,0);
3841
drh0bb132b2004-07-20 14:06:51 +00003842 /* Check to make sure the LHS has been used */
3843 if( rp->lhsalias && !lhsused ){
3844 ErrorMsg(lemp->filename,rp->ruleline,
3845 "Label \"%s\" for \"%s(%s)\" is never used.",
3846 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3847 lemp->errorcnt++;
3848 }
3849
drh4dd0d3f2016-02-17 01:18:33 +00003850 /* Generate destructor code for RHS minor values which are not referenced.
3851 ** Generate error messages for unused labels and duplicate labels.
3852 */
drh0bb132b2004-07-20 14:06:51 +00003853 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003854 if( rp->rhsalias[i] ){
3855 if( i>0 ){
3856 int j;
3857 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3858 ErrorMsg(lemp->filename,rp->ruleline,
3859 "%s(%s) has the same label as the LHS but is not the left-most "
3860 "symbol on the RHS.",
drhf135cb72019-04-30 14:26:31 +00003861 rp->rhs[i]->name, rp->rhsalias[i]);
drh4dd0d3f2016-02-17 01:18:33 +00003862 lemp->errorcnt++;
3863 }
3864 for(j=0; j<i; j++){
3865 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3866 ErrorMsg(lemp->filename,rp->ruleline,
3867 "Label %s used for multiple symbols on the RHS of a rule.",
3868 rp->rhsalias[i]);
3869 lemp->errorcnt++;
3870 break;
3871 }
3872 }
drh0bb132b2004-07-20 14:06:51 +00003873 }
drh4dd0d3f2016-02-17 01:18:33 +00003874 if( !used[i] ){
3875 ErrorMsg(lemp->filename,rp->ruleline,
3876 "Label %s for \"%s(%s)\" is never used.",
3877 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3878 lemp->errorcnt++;
3879 }
3880 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3881 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3882 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003883 }
3884 }
drh4dd0d3f2016-02-17 01:18:33 +00003885
3886 /* If unable to write LHS values directly into the stack, write the
3887 ** saved LHS value now. */
3888 if( lhsdirect==0 ){
3889 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3890 append_str(zLhs, 0, 0, 0);
3891 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003892 }
drh4dd0d3f2016-02-17 01:18:33 +00003893
3894 /* Suffix code generation complete */
3895 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003896 if( cp && cp[0] ){
3897 rp->codeSuffix = Strsafe(cp);
3898 rp->noCode = 0;
3899 }
drhdabd04c2016-02-17 01:46:19 +00003900
3901 return rc;
drh0bb132b2004-07-20 14:06:51 +00003902}
3903
drh06f60d82017-04-14 19:46:12 +00003904/*
drh75897232000-05-29 14:26:00 +00003905** Generate code which executes when the rule "rp" is reduced. Write
3906** the code to "out". Make sure lineno stays up-to-date.
3907*/
icculus9e44cf12010-02-14 17:14:22 +00003908PRIVATE void emit_code(
3909 FILE *out,
3910 struct rule *rp,
3911 struct lemon *lemp,
3912 int *lineno
3913){
3914 const char *cp;
drh75897232000-05-29 14:26:00 +00003915
drh4dd0d3f2016-02-17 01:18:33 +00003916 /* Setup code prior to the #line directive */
3917 if( rp->codePrefix && rp->codePrefix[0] ){
3918 fprintf(out, "{%s", rp->codePrefix);
3919 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3920 }
3921
drh75897232000-05-29 14:26:00 +00003922 /* Generate code to do the reduce action */
3923 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003924 if( !lemp->nolinenosflag ){
3925 (*lineno)++;
3926 tplt_linedir(out,rp->line,lemp->filename);
3927 }
drhaf805ca2004-09-07 11:28:25 +00003928 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003929 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003930 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003931 if( !lemp->nolinenosflag ){
3932 (*lineno)++;
3933 tplt_linedir(out,*lineno,lemp->outname);
3934 }
drh4dd0d3f2016-02-17 01:18:33 +00003935 }
3936
3937 /* Generate breakdown code that occurs after the #line directive */
3938 if( rp->codeSuffix && rp->codeSuffix[0] ){
3939 fprintf(out, "%s", rp->codeSuffix);
3940 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3941 }
3942
3943 if( rp->codePrefix ){
3944 fprintf(out, "}\n"); (*lineno)++;
3945 }
drh75897232000-05-29 14:26:00 +00003946
drh75897232000-05-29 14:26:00 +00003947 return;
3948}
3949
3950/*
3951** Print the definition of the union used for the parser's data stack.
3952** This union contains fields for every possible data type for tokens
3953** and nonterminals. In the process of computing and printing this
3954** union, also set the ".dtnum" field of every terminal and nonterminal
3955** symbol.
3956*/
icculus9e44cf12010-02-14 17:14:22 +00003957void print_stack_union(
3958 FILE *out, /* The output stream */
3959 struct lemon *lemp, /* The main info structure for this parser */
3960 int *plineno, /* Pointer to the line number */
3961 int mhflag /* True if generating makeheaders output */
3962){
drh75897232000-05-29 14:26:00 +00003963 int lineno = *plineno; /* The line number of the output */
3964 char **types; /* A hash table of datatypes */
3965 int arraysize; /* Size of the "types" array */
3966 int maxdtlength; /* Maximum length of any ".datatype" field. */
3967 char *stddt; /* Standardized name for a datatype */
3968 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003969 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003970 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003971
3972 /* Allocate and initialize types[] and allocate stddt[] */
3973 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003974 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003975 if( types==0 ){
3976 fprintf(stderr,"Out of memory.\n");
3977 exit(1);
3978 }
drh75897232000-05-29 14:26:00 +00003979 for(i=0; i<arraysize; i++) types[i] = 0;
3980 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003981 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003982 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003983 }
drh75897232000-05-29 14:26:00 +00003984 for(i=0; i<lemp->nsymbol; i++){
3985 int len;
3986 struct symbol *sp = lemp->symbols[i];
3987 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003988 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003989 if( len>maxdtlength ) maxdtlength = len;
3990 }
3991 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003992 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003993 fprintf(stderr,"Out of memory.\n");
3994 exit(1);
3995 }
3996
3997 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3998 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003999 ** used for terminal symbols. If there is no %default_type defined then
4000 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4001 ** a datatype using the %type directive.
4002 */
drh75897232000-05-29 14:26:00 +00004003 for(i=0; i<lemp->nsymbol; i++){
4004 struct symbol *sp = lemp->symbols[i];
4005 char *cp;
4006 if( sp==lemp->errsym ){
4007 sp->dtnum = arraysize+1;
4008 continue;
4009 }
drh960e8c62001-04-03 16:53:21 +00004010 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00004011 sp->dtnum = 0;
4012 continue;
4013 }
4014 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00004015 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00004016 j = 0;
drhc56fac72015-10-29 13:48:15 +00004017 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00004018 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00004019 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00004020 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00004021 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00004022 sp->dtnum = 0;
4023 continue;
4024 }
drh75897232000-05-29 14:26:00 +00004025 hash = 0;
4026 for(j=0; stddt[j]; j++){
4027 hash = hash*53 + stddt[j];
4028 }
drh3b2129c2003-05-13 00:34:21 +00004029 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00004030 while( types[hash] ){
4031 if( strcmp(types[hash],stddt)==0 ){
4032 sp->dtnum = hash + 1;
4033 break;
4034 }
4035 hash++;
drh2b51f212013-10-11 23:01:02 +00004036 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00004037 }
4038 if( types[hash]==0 ){
4039 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00004040 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00004041 if( types[hash]==0 ){
4042 fprintf(stderr,"Out of memory.\n");
4043 exit(1);
4044 }
drh898799f2014-01-10 23:21:00 +00004045 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00004046 }
4047 }
4048
4049 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4050 name = lemp->name ? lemp->name : "Parse";
4051 lineno = *plineno;
4052 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4053 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4054 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4055 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4056 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00004057 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004058 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4059 for(i=0; i<arraysize; i++){
4060 if( types[i]==0 ) continue;
4061 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4062 free(types[i]);
4063 }
drhed0c15b2018-04-16 14:31:34 +00004064 if( lemp->errsym && lemp->errsym->useCnt ){
drhc4dd3fd2008-01-22 01:48:05 +00004065 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4066 }
drh75897232000-05-29 14:26:00 +00004067 free(stddt);
4068 free(types);
4069 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4070 *plineno = lineno;
4071}
4072
drhb29b0a52002-02-23 19:39:46 +00004073/*
4074** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00004075** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4076** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00004077*/
drhc75e0162015-09-07 02:23:02 +00004078static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4079 const char *zType = "int";
4080 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00004081 if( lwr>=0 ){
4082 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00004083 zType = "unsigned char";
4084 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004085 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00004086 zType = "unsigned short int";
4087 nByte = 2;
drh8b582012003-10-21 13:16:03 +00004088 }else{
drhc75e0162015-09-07 02:23:02 +00004089 zType = "unsigned int";
4090 nByte = 4;
drh8b582012003-10-21 13:16:03 +00004091 }
4092 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00004093 zType = "signed char";
4094 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004095 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00004096 zType = "short";
4097 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00004098 }
drhc75e0162015-09-07 02:23:02 +00004099 if( pnByte ) *pnByte = nByte;
4100 return zType;
drhb29b0a52002-02-23 19:39:46 +00004101}
4102
drhfdbf9282003-10-21 16:34:41 +00004103/*
4104** Each state contains a set of token transaction and a set of
4105** nonterminal transactions. Each of these sets makes an instance
4106** of the following structure. An array of these structures is used
4107** to order the creation of entries in the yy_action[] table.
4108*/
4109struct axset {
4110 struct state *stp; /* A pointer to a state */
4111 int isTkn; /* True to use tokens. False for non-terminals */
4112 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00004113 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00004114};
4115
4116/*
4117** Compare to axset structures for sorting purposes
4118*/
4119static int axset_compare(const void *a, const void *b){
4120 struct axset *p1 = (struct axset*)a;
4121 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004122 int c;
4123 c = p2->nAction - p1->nAction;
4124 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004125 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004126 }
4127 assert( c!=0 || p1==p2 );
4128 return c;
drhfdbf9282003-10-21 16:34:41 +00004129}
4130
drhc4dd3fd2008-01-22 01:48:05 +00004131/*
4132** Write text on "out" that describes the rule "rp".
4133*/
4134static void writeRuleText(FILE *out, struct rule *rp){
4135 int j;
4136 fprintf(out,"%s ::=", rp->lhs->name);
4137 for(j=0; j<rp->nrhs; j++){
4138 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004139 if( sp->type!=MULTITERMINAL ){
4140 fprintf(out," %s", sp->name);
4141 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004142 int k;
drh61f92cd2014-01-11 03:06:18 +00004143 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004144 for(k=1; k<sp->nsubsym; k++){
4145 fprintf(out,"|%s",sp->subsym[k]->name);
4146 }
4147 }
4148 }
4149}
4150
4151
drh75897232000-05-29 14:26:00 +00004152/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004153void ReportTable(
4154 struct lemon *lemp,
drhfe03dac2019-11-26 02:22:39 +00004155 int mhflag, /* Output in makeheaders format if true */
4156 int sqlFlag /* Generate the *.sql file too */
icculus9e44cf12010-02-14 17:14:22 +00004157){
drhfe03dac2019-11-26 02:22:39 +00004158 FILE *out, *in, *sql;
drh75897232000-05-29 14:26:00 +00004159 char line[LINESIZE];
4160 int lineno;
4161 struct state *stp;
4162 struct action *ap;
4163 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004164 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004165 int i, j, n, sz;
drh2e517162019-08-28 02:09:47 +00004166 int nLookAhead;
drhc75e0162015-09-07 02:23:02 +00004167 int szActionType; /* sizeof(YYACTIONTYPE) */
4168 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004169 const char *name;
drh8b582012003-10-21 13:16:03 +00004170 int mnTknOfst, mxTknOfst;
4171 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004172 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004173
drh5c8241b2017-12-24 23:38:10 +00004174 lemp->minShiftReduce = lemp->nstate;
4175 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4176 lemp->accAction = lemp->errAction + 1;
4177 lemp->noAction = lemp->accAction + 1;
4178 lemp->minReduce = lemp->noAction + 1;
4179 lemp->maxAction = lemp->minReduce + lemp->nrule;
4180
drh75897232000-05-29 14:26:00 +00004181 in = tplt_open(lemp);
4182 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004183 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004184 if( out==0 ){
4185 fclose(in);
4186 return;
4187 }
drhfe03dac2019-11-26 02:22:39 +00004188 if( sqlFlag==0 ){
4189 sql = 0;
4190 }else{
4191 sql = file_open(lemp, ".sql", "wb");
4192 if( sql==0 ){
4193 fclose(in);
4194 fclose(out);
4195 return;
4196 }
4197 fprintf(sql,
drh1417c2f2019-11-29 12:51:00 +00004198 "BEGIN;\n"
drhfe03dac2019-11-26 02:22:39 +00004199 "CREATE TABLE symbol(\n"
4200 " id INTEGER PRIMARY KEY,\n"
4201 " name TEXT NOT NULL,\n"
4202 " isTerminal BOOLEAN NOT NULL,\n"
drh1417c2f2019-11-29 12:51:00 +00004203 " fallback INTEGER REFERENCES symbol"
4204 " DEFERRABLE INITIALLY DEFERRED\n"
drhfe03dac2019-11-26 02:22:39 +00004205 ");\n"
4206 );
4207 for(i=0; i<lemp->nsymbol; i++){
4208 fprintf(sql,
4209 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4210 "VALUES(%d,'%s',%s",
4211 i, lemp->symbols[i]->name,
4212 i<lemp->nterminal ? "TRUE" : "FALSE"
4213 );
4214 if( lemp->symbols[i]->fallback ){
4215 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
4216 }else{
4217 fprintf(sql, ",NULL);\n");
4218 }
4219 }
4220 fprintf(sql,
4221 "CREATE TABLE rule(\n"
4222 " ruleid INTEGER PRIMARY KEY,\n"
4223 " lhs INTEGER REFERENCES symbol(id)\n"
4224 ");\n"
4225 "CREATE TABLE rulerhs(\n"
4226 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4227 " pos INTEGER,\n"
4228 " sym INTEGER REFERENCES symbol(id)\n"
4229 ");\n"
4230 );
4231 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4232 assert( i==rp->iRule );
drh61cb4ed2019-11-29 13:01:57 +00004233 fprintf(sql, "-- ");
4234 writeRuleText(sql, rp);
4235 fprintf(sql, "\n");
drhfe03dac2019-11-26 02:22:39 +00004236 fprintf(sql,
4237 "INSERT INTO rule(ruleid,lhs)VALUES(%d,%d);\n",
4238 rp->iRule, rp->lhs->index
4239 );
4240 for(j=0; j<rp->nrhs; j++){
4241 struct symbol *sp = rp->rhs[j];
4242 if( sp->type!=MULTITERMINAL ){
4243 fprintf(sql,
4244 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4245 i,j,sp->index
4246 );
4247 }else{
4248 int k;
4249 for(k=0; k<sp->nsubsym; k++){
4250 fprintf(sql,
4251 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4252 i,j,sp->subsym[k]->index
4253 );
4254 }
4255 }
4256 }
4257 }
drh1417c2f2019-11-29 12:51:00 +00004258 fprintf(sql, "COMMIT;\n");
drhfe03dac2019-11-26 02:22:39 +00004259 }
drh75897232000-05-29 14:26:00 +00004260 lineno = 1;
4261 tplt_xfer(lemp->name,in,out,&lineno);
4262
4263 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004264 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004265 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004266 char *incName = file_makename(lemp, ".h");
4267 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4268 free(incName);
drh75897232000-05-29 14:26:00 +00004269 }
4270 tplt_xfer(lemp->name,in,out,&lineno);
4271
4272 /* Generate #defines for all tokens */
4273 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004274 const char *prefix;
drh75897232000-05-29 14:26:00 +00004275 fprintf(out,"#if INTERFACE\n"); lineno++;
4276 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4277 else prefix = "";
4278 for(i=1; i<lemp->nterminal; i++){
4279 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4280 lineno++;
4281 }
4282 fprintf(out,"#endif\n"); lineno++;
4283 }
4284 tplt_xfer(lemp->name,in,out,&lineno);
4285
4286 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004287 fprintf(out,"#define YYCODETYPE %s\n",
drhed0c15b2018-04-16 14:31:34 +00004288 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4289 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
drh75897232000-05-29 14:26:00 +00004290 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004291 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004292 if( lemp->wildcard ){
4293 fprintf(out,"#define YYWILDCARD %d\n",
4294 lemp->wildcard->index); lineno++;
4295 }
drh75897232000-05-29 14:26:00 +00004296 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004297 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004298 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004299 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4300 }else{
4301 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4302 }
drhca44b5a2007-02-22 23:06:58 +00004303 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004304 if( mhflag ){
4305 fprintf(out,"#if INTERFACE\n"); lineno++;
4306 }
4307 name = lemp->name ? lemp->name : "Parse";
4308 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004309 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004310 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4311 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004312 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4313 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
drhfb32c442018-04-21 13:51:42 +00004314 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4315 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
drh1f245e42002-03-11 13:55:50 +00004316 name,lemp->arg,&lemp->arg[i]); lineno++;
drhfb32c442018-04-21 13:51:42 +00004317 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
drh1f245e42002-03-11 13:55:50 +00004318 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004319 }else{
drhfb32c442018-04-21 13:51:42 +00004320 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4321 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4322 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
drh1f245e42002-03-11 13:55:50 +00004323 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4324 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004325 }
drhfb32c442018-04-21 13:51:42 +00004326 if( lemp->ctx && lemp->ctx[0] ){
4327 i = lemonStrlen(lemp->ctx);
4328 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4329 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4330 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4331 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4332 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4333 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4334 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4335 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4336 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4337 }else{
4338 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4339 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4340 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4341 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4342 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4343 }
drh75897232000-05-29 14:26:00 +00004344 if( mhflag ){
4345 fprintf(out,"#endif\n"); lineno++;
4346 }
drhed0c15b2018-04-16 14:31:34 +00004347 if( lemp->errsym && lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004348 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4349 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004350 }
drh0bd1f4e2002-06-06 18:54:39 +00004351 if( lemp->has_fallback ){
4352 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4353 }
drh75897232000-05-29 14:26:00 +00004354
drh3bd48ab2015-09-07 18:23:37 +00004355 /* Compute the action table, but do not output it yet. The action
4356 ** table must be computed before generating the YYNSTATE macro because
4357 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004358 */
drh3bd48ab2015-09-07 18:23:37 +00004359 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004360 if( ax==0 ){
4361 fprintf(stderr,"malloc failed\n");
4362 exit(1);
4363 }
drh3bd48ab2015-09-07 18:23:37 +00004364 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004365 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004366 ax[i*2].stp = stp;
4367 ax[i*2].isTkn = 1;
4368 ax[i*2].nAction = stp->nTknAct;
4369 ax[i*2+1].stp = stp;
4370 ax[i*2+1].isTkn = 0;
4371 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004372 }
drh8b582012003-10-21 13:16:03 +00004373 mxTknOfst = mnTknOfst = 0;
4374 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004375 /* In an effort to minimize the action table size, use the heuristic
4376 ** of placing the largest action sets first */
4377 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4378 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh3a9d6c72017-12-25 04:15:38 +00004379 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
drh3bd48ab2015-09-07 18:23:37 +00004380 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004381 stp = ax[i].stp;
4382 if( ax[i].isTkn ){
4383 for(ap=stp->ap; ap; ap=ap->next){
4384 int action;
4385 if( ap->sp->index>=lemp->nterminal ) continue;
4386 action = compute_action(lemp, ap);
4387 if( action<0 ) continue;
4388 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004389 }
drh3a9d6c72017-12-25 04:15:38 +00004390 stp->iTknOfst = acttab_insert(pActtab, 1);
drhfdbf9282003-10-21 16:34:41 +00004391 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4392 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4393 }else{
4394 for(ap=stp->ap; ap; ap=ap->next){
4395 int action;
4396 if( ap->sp->index<lemp->nterminal ) continue;
4397 if( ap->sp->index==lemp->nsymbol ) continue;
4398 action = compute_action(lemp, ap);
4399 if( action<0 ) continue;
4400 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004401 }
drh3a9d6c72017-12-25 04:15:38 +00004402 stp->iNtOfst = acttab_insert(pActtab, 0);
drhfdbf9282003-10-21 16:34:41 +00004403 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4404 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004405 }
drh337cd0d2015-09-07 23:40:42 +00004406#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4407 { int jj, nn;
4408 for(jj=nn=0; jj<pActtab->nAction; jj++){
4409 if( pActtab->aAction[jj].action<0 ) nn++;
4410 }
4411 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4412 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4413 ax[i].nAction, pActtab->nAction, nn);
4414 }
4415#endif
drh8b582012003-10-21 13:16:03 +00004416 }
drhfdbf9282003-10-21 16:34:41 +00004417 free(ax);
drh8b582012003-10-21 13:16:03 +00004418
drh756b41e2016-05-24 18:55:08 +00004419 /* Mark rules that are actually used for reduce actions after all
4420 ** optimizations have been applied
4421 */
4422 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4423 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004424 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4425 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004426 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004427 }
4428 }
4429 }
4430
drh3bd48ab2015-09-07 18:23:37 +00004431 /* Finish rendering the constants now that the action table has
4432 ** been computed */
4433 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4434 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhce678c22019-12-11 18:53:51 +00004435 fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
4436 lineno++;
drh0d9de992017-12-26 18:04:23 +00004437 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004438 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004439 i = lemp->minShiftReduce;
4440 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4441 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004442 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004443 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4444 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4445 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4446 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4447 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004448 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004449 tplt_xfer(lemp->name,in,out,&lineno);
4450
4451 /* Now output the action table and its associates:
4452 **
4453 ** yy_action[] A single table containing all actions.
4454 ** yy_lookahead[] A table containing the lookahead for each entry in
4455 ** yy_action. Used to detect hash collisions.
4456 ** yy_shift_ofst[] For each state, the offset into yy_action for
4457 ** shifting terminals.
4458 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4459 ** shifting non-terminals after a reduce.
4460 ** yy_default[] Default action for each state.
4461 */
4462
drh8b582012003-10-21 13:16:03 +00004463 /* Output the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +00004464 lemp->nactiontab = n = acttab_action_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004465 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004466 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4467 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004468 for(i=j=0; i<n; i++){
4469 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004470 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004471 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004472 fprintf(out, " %4d,", action);
4473 if( j==9 || i==n-1 ){
4474 fprintf(out, "\n"); lineno++;
4475 j = 0;
4476 }else{
4477 j++;
4478 }
4479 }
4480 fprintf(out, "};\n"); lineno++;
4481
4482 /* Output the yy_lookahead table */
drh3a9d6c72017-12-25 04:15:38 +00004483 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004484 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004485 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004486 for(i=j=0; i<n; i++){
4487 int la = acttab_yylookahead(pActtab, i);
4488 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004489 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004490 fprintf(out, " %4d,", la);
drh2e517162019-08-28 02:09:47 +00004491 if( j==9 ){
drh8b582012003-10-21 13:16:03 +00004492 fprintf(out, "\n"); lineno++;
4493 j = 0;
4494 }else{
4495 j++;
4496 }
4497 }
drh2e517162019-08-28 02:09:47 +00004498 /* Add extra entries to the end of the yy_lookahead[] table so that
4499 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4500 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4501 nLookAhead = lemp->nterminal + lemp->nactiontab;
4502 while( i<nLookAhead ){
4503 if( j==0 ) fprintf(out," /* %5d */ ", i);
4504 fprintf(out, " %4d,", lemp->nterminal);
4505 if( j==9 ){
4506 fprintf(out, "\n"); lineno++;
4507 j = 0;
4508 }else{
4509 j++;
4510 }
4511 i++;
4512 }
mistachkinacf6e082019-09-11 15:25:26 +00004513 if( j>0 ){ fprintf(out, "\n"); lineno++; }
drh8b582012003-10-21 13:16:03 +00004514 fprintf(out, "};\n"); lineno++;
4515
4516 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004517 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004518 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004519 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4520 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4521 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004522 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004523 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4524 lineno++;
drhc75e0162015-09-07 02:23:02 +00004525 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004526 for(i=j=0; i<n; i++){
4527 int ofst;
4528 stp = lemp->sorted[i];
4529 ofst = stp->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004530 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
drhfdbf9282003-10-21 16:34:41 +00004531 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004532 fprintf(out, " %4d,", ofst);
4533 if( j==9 || i==n-1 ){
4534 fprintf(out, "\n"); lineno++;
4535 j = 0;
4536 }else{
4537 j++;
4538 }
4539 }
4540 fprintf(out, "};\n"); lineno++;
4541
4542 /* Output the yy_reduce_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004543 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004544 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004545 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4546 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4547 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004548 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004549 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4550 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004551 for(i=j=0; i<n; i++){
4552 int ofst;
4553 stp = lemp->sorted[i];
4554 ofst = stp->iNtOfst;
4555 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004556 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004557 fprintf(out, " %4d,", ofst);
4558 if( j==9 || i==n-1 ){
4559 fprintf(out, "\n"); lineno++;
4560 j = 0;
4561 }else{
4562 j++;
4563 }
4564 }
4565 fprintf(out, "};\n"); lineno++;
4566
4567 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004568 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004569 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004570 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004571 for(i=j=0; i<n; i++){
4572 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004573 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004574 if( stp->iDfltReduce<0 ){
4575 fprintf(out, " %4d,", lemp->errAction);
4576 }else{
4577 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4578 }
drh8b582012003-10-21 13:16:03 +00004579 if( j==9 || i==n-1 ){
4580 fprintf(out, "\n"); lineno++;
4581 j = 0;
4582 }else{
4583 j++;
4584 }
4585 }
4586 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004587 tplt_xfer(lemp->name,in,out,&lineno);
4588
drh0bd1f4e2002-06-06 18:54:39 +00004589 /* Generate the table of fallback tokens.
4590 */
4591 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004592 int mx = lemp->nterminal - 1;
drh010bdb42019-08-28 11:31:11 +00004593 /* 2019-08-28: Generate fallback entries for every token to avoid
4594 ** having to do a range check on the index */
4595 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
drhc75e0162015-09-07 02:23:02 +00004596 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004597 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004598 struct symbol *p = lemp->symbols[i];
4599 if( p->fallback==0 ){
4600 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4601 }else{
4602 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4603 p->name, p->fallback->name);
4604 }
4605 lineno++;
4606 }
4607 }
4608 tplt_xfer(lemp->name, in, out, &lineno);
4609
4610 /* Generate a table containing the symbolic name of every symbol
4611 */
drh75897232000-05-29 14:26:00 +00004612 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004613 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh3a9d6c72017-12-25 04:15:38 +00004614 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
drh75897232000-05-29 14:26:00 +00004615 }
drh75897232000-05-29 14:26:00 +00004616 tplt_xfer(lemp->name,in,out,&lineno);
4617
drh0bd1f4e2002-06-06 18:54:39 +00004618 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004619 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004620 ** when tracing REDUCE actions.
4621 */
4622 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004623 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004624 fprintf(out," /* %3d */ \"", i);
4625 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004626 fprintf(out,"\",\n"); lineno++;
4627 }
4628 tplt_xfer(lemp->name,in,out,&lineno);
4629
drh75897232000-05-29 14:26:00 +00004630 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004631 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004632 ** (In other words, generate the %destructor actions)
4633 */
drh75897232000-05-29 14:26:00 +00004634 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004635 int once = 1;
drh75897232000-05-29 14:26:00 +00004636 for(i=0; i<lemp->nsymbol; i++){
4637 struct symbol *sp = lemp->symbols[i];
4638 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004639 if( once ){
4640 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4641 once = 0;
4642 }
drhc53eed12009-06-12 17:46:19 +00004643 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004644 }
4645 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4646 if( i<lemp->nsymbol ){
4647 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4648 fprintf(out," break;\n"); lineno++;
4649 }
4650 }
drh8d659732005-01-13 23:54:06 +00004651 if( lemp->vardest ){
4652 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004653 int once = 1;
drh8d659732005-01-13 23:54:06 +00004654 for(i=0; i<lemp->nsymbol; i++){
4655 struct symbol *sp = lemp->symbols[i];
4656 if( sp==0 || sp->type==TERMINAL ||
4657 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004658 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004659 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004660 once = 0;
4661 }
drhc53eed12009-06-12 17:46:19 +00004662 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004663 dflt_sp = sp;
4664 }
4665 if( dflt_sp!=0 ){
4666 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004667 }
drh4dc8ef52008-07-01 17:13:57 +00004668 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004669 }
drh75897232000-05-29 14:26:00 +00004670 for(i=0; i<lemp->nsymbol; i++){
4671 struct symbol *sp = lemp->symbols[i];
4672 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004673 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004674 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004675
4676 /* Combine duplicate destructors into a single case */
4677 for(j=i+1; j<lemp->nsymbol; j++){
4678 struct symbol *sp2 = lemp->symbols[j];
4679 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4680 && sp2->dtnum==sp->dtnum
4681 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004682 fprintf(out," case %d: /* %s */\n",
4683 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004684 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004685 }
4686 }
4687
drh75897232000-05-29 14:26:00 +00004688 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4689 fprintf(out," break;\n"); lineno++;
4690 }
drh75897232000-05-29 14:26:00 +00004691 tplt_xfer(lemp->name,in,out,&lineno);
4692
4693 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004694 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004695 tplt_xfer(lemp->name,in,out,&lineno);
4696
drhcfc45b12018-12-03 23:57:27 +00004697 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4698 ** yyRuleInfoNRhs[].
drh75897232000-05-29 14:26:00 +00004699 **
4700 ** Note: This code depends on the fact that rules are number
4701 ** sequentually beginning with 0.
4702 */
drh5c8241b2017-12-24 23:38:10 +00004703 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drhcfc45b12018-12-03 23:57:27 +00004704 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4705 rule_print(out, rp);
4706 fprintf(out," */\n"); lineno++;
4707 }
4708 tplt_xfer(lemp->name,in,out,&lineno);
4709 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4710 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
drh5c8241b2017-12-24 23:38:10 +00004711 rule_print(out, rp);
4712 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004713 }
4714 tplt_xfer(lemp->name,in,out,&lineno);
4715
4716 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004717 i = 0;
drh75897232000-05-29 14:26:00 +00004718 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004719 i += translate_code(lemp, rp);
4720 }
4721 if( i ){
4722 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004723 }
drhc53eed12009-06-12 17:46:19 +00004724 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004725 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004726 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004727 if( rp->codeEmitted ) continue;
4728 if( rp->noCode ){
4729 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004730 continue;
4731 }
drh4ef07702016-03-16 19:45:54 +00004732 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004733 writeRuleText(out, rp);
4734 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004735 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004736 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4737 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004738 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004739 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004740 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004741 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004742 }
4743 }
drh75897232000-05-29 14:26:00 +00004744 emit_code(out,rp,lemp,&lineno);
4745 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004746 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004747 }
drhc53eed12009-06-12 17:46:19 +00004748 /* Finally, output the default: rule. We choose as the default: all
4749 ** empty actions. */
4750 fprintf(out," default:\n"); lineno++;
4751 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004752 if( rp->codeEmitted ) continue;
4753 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004754 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004755 writeRuleText(out, rp);
drhe94006e2019-12-10 20:41:48 +00004756 if( rp->neverReduce ){
4757 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
4758 rp->iRule); lineno++;
4759 }else if( rp->doesReduce ){
drh756b41e2016-05-24 18:55:08 +00004760 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4761 }else{
4762 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4763 rp->iRule); lineno++;
4764 }
drhc53eed12009-06-12 17:46:19 +00004765 }
4766 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004767 tplt_xfer(lemp->name,in,out,&lineno);
4768
4769 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004770 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004771 tplt_xfer(lemp->name,in,out,&lineno);
4772
4773 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004774 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004775 tplt_xfer(lemp->name,in,out,&lineno);
4776
4777 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004778 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004779 tplt_xfer(lemp->name,in,out,&lineno);
4780
4781 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004782 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004783
drhe2dcc422019-01-15 14:44:23 +00004784 acttab_free(pActtab);
drh75897232000-05-29 14:26:00 +00004785 fclose(in);
4786 fclose(out);
drhfe03dac2019-11-26 02:22:39 +00004787 if( sql ) fclose(sql);
drh75897232000-05-29 14:26:00 +00004788 return;
4789}
4790
4791/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004792void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004793{
4794 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004795 const char *prefix;
drh75897232000-05-29 14:26:00 +00004796 char line[LINESIZE];
4797 char pattern[LINESIZE];
4798 int i;
4799
4800 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4801 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004802 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004803 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004804 int nextChar;
drh75897232000-05-29 14:26:00 +00004805 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004806 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4807 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004808 if( strcmp(line,pattern) ) break;
4809 }
drh8ba0d1c2012-06-16 15:26:31 +00004810 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004811 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004812 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004813 /* No change in the file. Don't rewrite it. */
4814 return;
4815 }
4816 }
drh2aa6ca42004-09-10 00:14:04 +00004817 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004818 if( out ){
4819 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004820 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004821 }
drh06f60d82017-04-14 19:46:12 +00004822 fclose(out);
drh75897232000-05-29 14:26:00 +00004823 }
4824 return;
4825}
4826
4827/* Reduce the size of the action tables, if possible, by making use
4828** of defaults.
4829**
drhb59499c2002-02-23 18:45:13 +00004830** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004831** it the default. Except, there is no default if the wildcard token
4832** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004833*/
icculus9e44cf12010-02-14 17:14:22 +00004834void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004835{
4836 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004837 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004838 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004839 int nbest, n;
drh75897232000-05-29 14:26:00 +00004840 int i;
drhe09daa92006-06-10 13:29:31 +00004841 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004842
4843 for(i=0; i<lemp->nstate; i++){
4844 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004845 nbest = 0;
4846 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004847 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004848
drhb59499c2002-02-23 18:45:13 +00004849 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004850 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4851 usesWildcard = 1;
4852 }
drhb59499c2002-02-23 18:45:13 +00004853 if( ap->type!=REDUCE ) continue;
4854 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004855 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004856 if( rp==rbest ) continue;
4857 n = 1;
4858 for(ap2=ap->next; ap2; ap2=ap2->next){
4859 if( ap2->type!=REDUCE ) continue;
4860 rp2 = ap2->x.rp;
4861 if( rp2==rbest ) continue;
4862 if( rp2==rp ) n++;
4863 }
4864 if( n>nbest ){
4865 nbest = n;
4866 rbest = rp;
drh75897232000-05-29 14:26:00 +00004867 }
4868 }
drh06f60d82017-04-14 19:46:12 +00004869
drhb59499c2002-02-23 18:45:13 +00004870 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004871 ** is not at least 1 or if the wildcard token is a possible
4872 ** lookahead.
4873 */
4874 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004875
drhb59499c2002-02-23 18:45:13 +00004876
4877 /* Combine matching REDUCE actions into a single default */
4878 for(ap=stp->ap; ap; ap=ap->next){
4879 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4880 }
drh75897232000-05-29 14:26:00 +00004881 assert( ap );
4882 ap->sp = Symbol_new("{default}");
4883 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004884 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004885 }
4886 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004887
4888 for(ap=stp->ap; ap; ap=ap->next){
4889 if( ap->type==SHIFT ) break;
4890 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4891 }
4892 if( ap==0 ){
4893 stp->autoReduce = 1;
4894 stp->pDfltReduce = rbest;
4895 }
4896 }
4897
4898 /* Make a second pass over all states and actions. Convert
4899 ** every action that is a SHIFT to an autoReduce state into
4900 ** a SHIFTREDUCE action.
4901 */
4902 for(i=0; i<lemp->nstate; i++){
4903 stp = lemp->sorted[i];
4904 for(ap=stp->ap; ap; ap=ap->next){
4905 struct state *pNextState;
4906 if( ap->type!=SHIFT ) continue;
4907 pNextState = ap->x.stp;
4908 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4909 ap->type = SHIFTREDUCE;
4910 ap->x.rp = pNextState->pDfltReduce;
4911 }
4912 }
drh75897232000-05-29 14:26:00 +00004913 }
drhc173ad82016-05-23 16:15:02 +00004914
4915 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4916 ** (meaning that the SHIFTREDUCE will land back in the state where it
4917 ** started) and if there is no C-code associated with the reduce action,
4918 ** then we can go ahead and convert the action to be the same as the
4919 ** action for the RHS of the rule.
4920 */
4921 for(i=0; i<lemp->nstate; i++){
4922 stp = lemp->sorted[i];
4923 for(ap=stp->ap; ap; ap=nextap){
4924 nextap = ap->next;
4925 if( ap->type!=SHIFTREDUCE ) continue;
4926 rp = ap->x.rp;
4927 if( rp->noCode==0 ) continue;
4928 if( rp->nrhs!=1 ) continue;
4929#if 1
4930 /* Only apply this optimization to non-terminals. It would be OK to
4931 ** apply it to terminal symbols too, but that makes the parser tables
4932 ** larger. */
4933 if( ap->sp->index<lemp->nterminal ) continue;
4934#endif
4935 /* If we reach this point, it means the optimization can be applied */
4936 nextap = ap;
4937 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4938 assert( ap2!=0 );
4939 ap->spOpt = ap2->sp;
4940 ap->type = ap2->type;
4941 ap->x = ap2->x;
4942 }
4943 }
drh75897232000-05-29 14:26:00 +00004944}
drhb59499c2002-02-23 18:45:13 +00004945
drhada354d2005-11-05 15:03:59 +00004946
4947/*
4948** Compare two states for sorting purposes. The smaller state is the
4949** one with the most non-terminal actions. If they have the same number
4950** of non-terminal actions, then the smaller is the one with the most
4951** token actions.
4952*/
4953static int stateResortCompare(const void *a, const void *b){
4954 const struct state *pA = *(const struct state**)a;
4955 const struct state *pB = *(const struct state**)b;
4956 int n;
4957
4958 n = pB->nNtAct - pA->nNtAct;
4959 if( n==0 ){
4960 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004961 if( n==0 ){
4962 n = pB->statenum - pA->statenum;
4963 }
drhada354d2005-11-05 15:03:59 +00004964 }
drhe594bc32009-11-03 13:02:25 +00004965 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004966 return n;
4967}
4968
4969
4970/*
4971** Renumber and resort states so that states with fewer choices
4972** occur at the end. Except, keep state 0 as the first state.
4973*/
icculus9e44cf12010-02-14 17:14:22 +00004974void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004975{
4976 int i;
4977 struct state *stp;
4978 struct action *ap;
4979
4980 for(i=0; i<lemp->nstate; i++){
4981 stp = lemp->sorted[i];
4982 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00004983 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004984 stp->iTknOfst = NO_OFFSET;
4985 stp->iNtOfst = NO_OFFSET;
4986 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004987 int iAction = compute_action(lemp,ap);
4988 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004989 if( ap->sp->index<lemp->nterminal ){
4990 stp->nTknAct++;
4991 }else if( ap->sp->index<lemp->nsymbol ){
4992 stp->nNtAct++;
4993 }else{
drh3bd48ab2015-09-07 18:23:37 +00004994 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00004995 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00004996 }
4997 }
4998 }
4999 }
5000 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
5001 stateResortCompare);
5002 for(i=0; i<lemp->nstate; i++){
5003 lemp->sorted[i]->statenum = i;
5004 }
drh3bd48ab2015-09-07 18:23:37 +00005005 lemp->nxstate = lemp->nstate;
5006 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
5007 lemp->nxstate--;
5008 }
drhada354d2005-11-05 15:03:59 +00005009}
5010
5011
drh75897232000-05-29 14:26:00 +00005012/***************** From the file "set.c" ************************************/
5013/*
5014** Set manipulation routines for the LEMON parser generator.
5015*/
5016
5017static int size = 0;
5018
5019/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00005020void SetSize(int n)
drh75897232000-05-29 14:26:00 +00005021{
5022 size = n+1;
5023}
5024
5025/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00005026char *SetNew(void){
drh75897232000-05-29 14:26:00 +00005027 char *s;
drh9892c5d2007-12-21 00:02:11 +00005028 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00005029 if( s==0 ){
drh75897232000-05-29 14:26:00 +00005030 memory_error();
5031 }
drh75897232000-05-29 14:26:00 +00005032 return s;
5033}
5034
5035/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00005036void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00005037{
5038 free(s);
5039}
5040
5041/* Add a new element to the set. Return TRUE if the element was added
5042** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00005043int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00005044{
5045 int rv;
drh9892c5d2007-12-21 00:02:11 +00005046 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00005047 rv = s[e];
5048 s[e] = 1;
5049 return !rv;
5050}
5051
5052/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00005053int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00005054{
5055 int i, progress;
5056 progress = 0;
5057 for(i=0; i<size; i++){
5058 if( s2[i]==0 ) continue;
5059 if( s1[i]==0 ){
5060 progress = 1;
5061 s1[i] = 1;
5062 }
5063 }
5064 return progress;
5065}
5066/********************** From the file "table.c" ****************************/
5067/*
5068** All code in this file has been automatically generated
5069** from a specification in the file
5070** "table.q"
5071** by the associative array code building program "aagen".
5072** Do not edit this file! Instead, edit the specification
5073** file, then rerun aagen.
5074*/
5075/*
5076** Code for processing tables in the LEMON parser generator.
5077*/
5078
drh01f75f22013-10-02 20:46:30 +00005079PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00005080{
drh01f75f22013-10-02 20:46:30 +00005081 unsigned h = 0;
5082 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00005083 return h;
5084}
5085
5086/* Works like strdup, sort of. Save a string in malloced memory, but
5087** keep strings in a table so that the same string is not in more
5088** than one place.
5089*/
icculus9e44cf12010-02-14 17:14:22 +00005090const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00005091{
icculus9e44cf12010-02-14 17:14:22 +00005092 const char *z;
5093 char *cpy;
drh75897232000-05-29 14:26:00 +00005094
drh916f75f2006-07-17 00:19:39 +00005095 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00005096 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00005097 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00005098 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00005099 z = cpy;
drh75897232000-05-29 14:26:00 +00005100 Strsafe_insert(z);
5101 }
5102 MemoryCheck(z);
5103 return z;
5104}
5105
5106/* There is one instance of the following structure for each
5107** associative array of type "x1".
5108*/
5109struct s_x1 {
5110 int size; /* The number of available slots. */
5111 /* Must be a power of 2 greater than or */
5112 /* equal to 1 */
5113 int count; /* Number of currently slots filled */
5114 struct s_x1node *tbl; /* The data stored here */
5115 struct s_x1node **ht; /* Hash table for lookups */
5116};
5117
5118/* There is one instance of this structure for every data element
5119** in an associative array of type "x1".
5120*/
5121typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00005122 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00005123 struct s_x1node *next; /* Next entry with the same hash */
5124 struct s_x1node **from; /* Previous link */
5125} x1node;
5126
5127/* There is only one instance of the array, which is the following */
5128static struct s_x1 *x1a;
5129
5130/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005131void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00005132 if( x1a ) return;
5133 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5134 if( x1a ){
5135 x1a->size = 1024;
5136 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005137 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005138 if( x1a->tbl==0 ){
5139 free(x1a);
5140 x1a = 0;
5141 }else{
5142 int i;
5143 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5144 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5145 }
5146 }
5147}
5148/* Insert a new record into the array. Return TRUE if successful.
5149** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005150int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00005151{
5152 x1node *np;
drh01f75f22013-10-02 20:46:30 +00005153 unsigned h;
5154 unsigned ph;
drh75897232000-05-29 14:26:00 +00005155
5156 if( x1a==0 ) return 0;
5157 ph = strhash(data);
5158 h = ph & (x1a->size-1);
5159 np = x1a->ht[h];
5160 while( np ){
5161 if( strcmp(np->data,data)==0 ){
5162 /* An existing entry with the same key is found. */
5163 /* Fail because overwrite is not allows. */
5164 return 0;
5165 }
5166 np = np->next;
5167 }
5168 if( x1a->count>=x1a->size ){
5169 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005170 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005171 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00005172 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00005173 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00005174 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005175 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005176 array.ht = (x1node**)&(array.tbl[arrSize]);
5177 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005178 for(i=0; i<x1a->count; i++){
5179 x1node *oldnp, *newnp;
5180 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005181 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005182 newnp = &(array.tbl[i]);
5183 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5184 newnp->next = array.ht[h];
5185 newnp->data = oldnp->data;
5186 newnp->from = &(array.ht[h]);
5187 array.ht[h] = newnp;
5188 }
5189 free(x1a->tbl);
5190 *x1a = array;
5191 }
5192 /* Insert the new data */
5193 h = ph & (x1a->size-1);
5194 np = &(x1a->tbl[x1a->count++]);
5195 np->data = data;
5196 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5197 np->next = x1a->ht[h];
5198 x1a->ht[h] = np;
5199 np->from = &(x1a->ht[h]);
5200 return 1;
5201}
5202
5203/* Return a pointer to data assigned to the given key. Return NULL
5204** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005205const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00005206{
drh01f75f22013-10-02 20:46:30 +00005207 unsigned h;
drh75897232000-05-29 14:26:00 +00005208 x1node *np;
5209
5210 if( x1a==0 ) return 0;
5211 h = strhash(key) & (x1a->size-1);
5212 np = x1a->ht[h];
5213 while( np ){
5214 if( strcmp(np->data,key)==0 ) break;
5215 np = np->next;
5216 }
5217 return np ? np->data : 0;
5218}
5219
5220/* Return a pointer to the (terminal or nonterminal) symbol "x".
5221** Create a new symbol if this is the first time "x" has been seen.
5222*/
icculus9e44cf12010-02-14 17:14:22 +00005223struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00005224{
5225 struct symbol *sp;
5226
5227 sp = Symbol_find(x);
5228 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00005229 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00005230 MemoryCheck(sp);
5231 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00005232 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00005233 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00005234 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00005235 sp->prec = -1;
5236 sp->assoc = UNK;
5237 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005238 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005239 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005240 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005241 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005242 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005243 Symbol_insert(sp,sp->name);
5244 }
drhc4dd3fd2008-01-22 01:48:05 +00005245 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005246 return sp;
5247}
5248
drh61f92cd2014-01-11 03:06:18 +00005249/* Compare two symbols for sorting purposes. Return negative,
5250** zero, or positive if a is less then, equal to, or greater
5251** than b.
drh60d31652004-02-22 00:08:04 +00005252**
5253** Symbols that begin with upper case letters (terminals or tokens)
5254** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005255** (non-terminals). And MULTITERMINAL symbols (created using the
5256** %token_class directive) must sort at the very end. Other than
5257** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005258**
5259** We find experimentally that leaving the symbols in their original
5260** order (the order they appeared in the grammar file) gives the
5261** smallest parser tables in SQLite.
5262*/
icculus9e44cf12010-02-14 17:14:22 +00005263int Symbolcmpp(const void *_a, const void *_b)
5264{
drh61f92cd2014-01-11 03:06:18 +00005265 const struct symbol *a = *(const struct symbol **) _a;
5266 const struct symbol *b = *(const struct symbol **) _b;
5267 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5268 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5269 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005270}
5271
5272/* There is one instance of the following structure for each
5273** associative array of type "x2".
5274*/
5275struct s_x2 {
5276 int size; /* The number of available slots. */
5277 /* Must be a power of 2 greater than or */
5278 /* equal to 1 */
5279 int count; /* Number of currently slots filled */
5280 struct s_x2node *tbl; /* The data stored here */
5281 struct s_x2node **ht; /* Hash table for lookups */
5282};
5283
5284/* There is one instance of this structure for every data element
5285** in an associative array of type "x2".
5286*/
5287typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005288 struct symbol *data; /* The data */
5289 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005290 struct s_x2node *next; /* Next entry with the same hash */
5291 struct s_x2node **from; /* Previous link */
5292} x2node;
5293
5294/* There is only one instance of the array, which is the following */
5295static struct s_x2 *x2a;
5296
5297/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005298void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005299 if( x2a ) return;
5300 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5301 if( x2a ){
5302 x2a->size = 128;
5303 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005304 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005305 if( x2a->tbl==0 ){
5306 free(x2a);
5307 x2a = 0;
5308 }else{
5309 int i;
5310 x2a->ht = (x2node**)&(x2a->tbl[128]);
5311 for(i=0; i<128; i++) x2a->ht[i] = 0;
5312 }
5313 }
5314}
5315/* Insert a new record into the array. Return TRUE if successful.
5316** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005317int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005318{
5319 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005320 unsigned h;
5321 unsigned ph;
drh75897232000-05-29 14:26:00 +00005322
5323 if( x2a==0 ) return 0;
5324 ph = strhash(key);
5325 h = ph & (x2a->size-1);
5326 np = x2a->ht[h];
5327 while( np ){
5328 if( strcmp(np->key,key)==0 ){
5329 /* An existing entry with the same key is found. */
5330 /* Fail because overwrite is not allows. */
5331 return 0;
5332 }
5333 np = np->next;
5334 }
5335 if( x2a->count>=x2a->size ){
5336 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005337 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005338 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005339 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005340 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005341 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005342 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005343 array.ht = (x2node**)&(array.tbl[arrSize]);
5344 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005345 for(i=0; i<x2a->count; i++){
5346 x2node *oldnp, *newnp;
5347 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005348 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005349 newnp = &(array.tbl[i]);
5350 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5351 newnp->next = array.ht[h];
5352 newnp->key = oldnp->key;
5353 newnp->data = oldnp->data;
5354 newnp->from = &(array.ht[h]);
5355 array.ht[h] = newnp;
5356 }
5357 free(x2a->tbl);
5358 *x2a = array;
5359 }
5360 /* Insert the new data */
5361 h = ph & (x2a->size-1);
5362 np = &(x2a->tbl[x2a->count++]);
5363 np->key = key;
5364 np->data = data;
5365 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5366 np->next = x2a->ht[h];
5367 x2a->ht[h] = np;
5368 np->from = &(x2a->ht[h]);
5369 return 1;
5370}
5371
5372/* Return a pointer to data assigned to the given key. Return NULL
5373** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005374struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005375{
drh01f75f22013-10-02 20:46:30 +00005376 unsigned h;
drh75897232000-05-29 14:26:00 +00005377 x2node *np;
5378
5379 if( x2a==0 ) return 0;
5380 h = strhash(key) & (x2a->size-1);
5381 np = x2a->ht[h];
5382 while( np ){
5383 if( strcmp(np->key,key)==0 ) break;
5384 np = np->next;
5385 }
5386 return np ? np->data : 0;
5387}
5388
5389/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005390struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005391{
5392 struct symbol *data;
5393 if( x2a && n>0 && n<=x2a->count ){
5394 data = x2a->tbl[n-1].data;
5395 }else{
5396 data = 0;
5397 }
5398 return data;
5399}
5400
5401/* Return the size of the array */
5402int Symbol_count()
5403{
5404 return x2a ? x2a->count : 0;
5405}
5406
5407/* Return an array of pointers to all data in the table.
5408** The array is obtained from malloc. Return NULL if memory allocation
5409** problems, or if the array is empty. */
5410struct symbol **Symbol_arrayof()
5411{
5412 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005413 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005414 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005415 arrSize = x2a->count;
5416 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005417 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005418 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005419 }
5420 return array;
5421}
5422
5423/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005424int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005425{
icculus9e44cf12010-02-14 17:14:22 +00005426 const struct config *a = (struct config *) _a;
5427 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005428 int x;
5429 x = a->rp->index - b->rp->index;
5430 if( x==0 ) x = a->dot - b->dot;
5431 return x;
5432}
5433
5434/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005435PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005436{
5437 int rc;
5438 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5439 rc = a->rp->index - b->rp->index;
5440 if( rc==0 ) rc = a->dot - b->dot;
5441 }
5442 if( rc==0 ){
5443 if( a ) rc = 1;
5444 if( b ) rc = -1;
5445 }
5446 return rc;
5447}
5448
5449/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005450PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005451{
drh01f75f22013-10-02 20:46:30 +00005452 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005453 while( a ){
5454 h = h*571 + a->rp->index*37 + a->dot;
5455 a = a->bp;
5456 }
5457 return h;
5458}
5459
5460/* Allocate a new state structure */
5461struct state *State_new()
5462{
icculus9e44cf12010-02-14 17:14:22 +00005463 struct state *newstate;
5464 newstate = (struct state *)calloc(1, sizeof(struct state) );
5465 MemoryCheck(newstate);
5466 return newstate;
drh75897232000-05-29 14:26:00 +00005467}
5468
5469/* There is one instance of the following structure for each
5470** associative array of type "x3".
5471*/
5472struct s_x3 {
5473 int size; /* The number of available slots. */
5474 /* Must be a power of 2 greater than or */
5475 /* equal to 1 */
5476 int count; /* Number of currently slots filled */
5477 struct s_x3node *tbl; /* The data stored here */
5478 struct s_x3node **ht; /* Hash table for lookups */
5479};
5480
5481/* There is one instance of this structure for every data element
5482** in an associative array of type "x3".
5483*/
5484typedef struct s_x3node {
5485 struct state *data; /* The data */
5486 struct config *key; /* The key */
5487 struct s_x3node *next; /* Next entry with the same hash */
5488 struct s_x3node **from; /* Previous link */
5489} x3node;
5490
5491/* There is only one instance of the array, which is the following */
5492static struct s_x3 *x3a;
5493
5494/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005495void State_init(void){
drh75897232000-05-29 14:26:00 +00005496 if( x3a ) return;
5497 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5498 if( x3a ){
5499 x3a->size = 128;
5500 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005501 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005502 if( x3a->tbl==0 ){
5503 free(x3a);
5504 x3a = 0;
5505 }else{
5506 int i;
5507 x3a->ht = (x3node**)&(x3a->tbl[128]);
5508 for(i=0; i<128; i++) x3a->ht[i] = 0;
5509 }
5510 }
5511}
5512/* Insert a new record into the array. Return TRUE if successful.
5513** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005514int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005515{
5516 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005517 unsigned h;
5518 unsigned ph;
drh75897232000-05-29 14:26:00 +00005519
5520 if( x3a==0 ) return 0;
5521 ph = statehash(key);
5522 h = ph & (x3a->size-1);
5523 np = x3a->ht[h];
5524 while( np ){
5525 if( statecmp(np->key,key)==0 ){
5526 /* An existing entry with the same key is found. */
5527 /* Fail because overwrite is not allows. */
5528 return 0;
5529 }
5530 np = np->next;
5531 }
5532 if( x3a->count>=x3a->size ){
5533 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005534 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005535 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005536 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005537 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005538 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005539 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005540 array.ht = (x3node**)&(array.tbl[arrSize]);
5541 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005542 for(i=0; i<x3a->count; i++){
5543 x3node *oldnp, *newnp;
5544 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005545 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005546 newnp = &(array.tbl[i]);
5547 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5548 newnp->next = array.ht[h];
5549 newnp->key = oldnp->key;
5550 newnp->data = oldnp->data;
5551 newnp->from = &(array.ht[h]);
5552 array.ht[h] = newnp;
5553 }
5554 free(x3a->tbl);
5555 *x3a = array;
5556 }
5557 /* Insert the new data */
5558 h = ph & (x3a->size-1);
5559 np = &(x3a->tbl[x3a->count++]);
5560 np->key = key;
5561 np->data = data;
5562 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5563 np->next = x3a->ht[h];
5564 x3a->ht[h] = np;
5565 np->from = &(x3a->ht[h]);
5566 return 1;
5567}
5568
5569/* Return a pointer to data assigned to the given key. Return NULL
5570** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005571struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005572{
drh01f75f22013-10-02 20:46:30 +00005573 unsigned h;
drh75897232000-05-29 14:26:00 +00005574 x3node *np;
5575
5576 if( x3a==0 ) return 0;
5577 h = statehash(key) & (x3a->size-1);
5578 np = x3a->ht[h];
5579 while( np ){
5580 if( statecmp(np->key,key)==0 ) break;
5581 np = np->next;
5582 }
5583 return np ? np->data : 0;
5584}
5585
5586/* Return an array of pointers to all data in the table.
5587** The array is obtained from malloc. Return NULL if memory allocation
5588** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005589struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005590{
5591 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005592 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005593 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005594 arrSize = x3a->count;
5595 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005596 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005597 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005598 }
5599 return array;
5600}
5601
5602/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005603PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005604{
drh01f75f22013-10-02 20:46:30 +00005605 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005606 h = h*571 + a->rp->index*37 + a->dot;
5607 return h;
5608}
5609
5610/* There is one instance of the following structure for each
5611** associative array of type "x4".
5612*/
5613struct s_x4 {
5614 int size; /* The number of available slots. */
5615 /* Must be a power of 2 greater than or */
5616 /* equal to 1 */
5617 int count; /* Number of currently slots filled */
5618 struct s_x4node *tbl; /* The data stored here */
5619 struct s_x4node **ht; /* Hash table for lookups */
5620};
5621
5622/* There is one instance of this structure for every data element
5623** in an associative array of type "x4".
5624*/
5625typedef struct s_x4node {
5626 struct config *data; /* The data */
5627 struct s_x4node *next; /* Next entry with the same hash */
5628 struct s_x4node **from; /* Previous link */
5629} x4node;
5630
5631/* There is only one instance of the array, which is the following */
5632static struct s_x4 *x4a;
5633
5634/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005635void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005636 if( x4a ) return;
5637 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5638 if( x4a ){
5639 x4a->size = 64;
5640 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005641 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005642 if( x4a->tbl==0 ){
5643 free(x4a);
5644 x4a = 0;
5645 }else{
5646 int i;
5647 x4a->ht = (x4node**)&(x4a->tbl[64]);
5648 for(i=0; i<64; i++) x4a->ht[i] = 0;
5649 }
5650 }
5651}
5652/* Insert a new record into the array. Return TRUE if successful.
5653** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005654int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005655{
5656 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005657 unsigned h;
5658 unsigned ph;
drh75897232000-05-29 14:26:00 +00005659
5660 if( x4a==0 ) return 0;
5661 ph = confighash(data);
5662 h = ph & (x4a->size-1);
5663 np = x4a->ht[h];
5664 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005665 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005666 /* An existing entry with the same key is found. */
5667 /* Fail because overwrite is not allows. */
5668 return 0;
5669 }
5670 np = np->next;
5671 }
5672 if( x4a->count>=x4a->size ){
5673 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005674 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005675 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005676 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005677 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005678 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005679 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005680 array.ht = (x4node**)&(array.tbl[arrSize]);
5681 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005682 for(i=0; i<x4a->count; i++){
5683 x4node *oldnp, *newnp;
5684 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005685 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005686 newnp = &(array.tbl[i]);
5687 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5688 newnp->next = array.ht[h];
5689 newnp->data = oldnp->data;
5690 newnp->from = &(array.ht[h]);
5691 array.ht[h] = newnp;
5692 }
5693 free(x4a->tbl);
5694 *x4a = array;
5695 }
5696 /* Insert the new data */
5697 h = ph & (x4a->size-1);
5698 np = &(x4a->tbl[x4a->count++]);
5699 np->data = data;
5700 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5701 np->next = x4a->ht[h];
5702 x4a->ht[h] = np;
5703 np->from = &(x4a->ht[h]);
5704 return 1;
5705}
5706
5707/* Return a pointer to data assigned to the given key. Return NULL
5708** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005709struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005710{
5711 int h;
5712 x4node *np;
5713
5714 if( x4a==0 ) return 0;
5715 h = confighash(key) & (x4a->size-1);
5716 np = x4a->ht[h];
5717 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005718 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005719 np = np->next;
5720 }
5721 return np ? np->data : 0;
5722}
5723
5724/* Remove all data from the table. Pass each data to the function "f"
5725** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005726void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005727{
5728 int i;
5729 if( x4a==0 || x4a->count==0 ) return;
5730 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5731 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5732 x4a->count = 0;
5733 return;
5734}