blob: 40e4e2894f799d4b71d92553a044b7d1da96104a [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 */
drh0a34cf52020-07-03 15:41:08 +0000426 int printPreprocessed; /* Show preprocessor output on stdout */
drh34ff57b2008-07-14 12:27:51 +0000427 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000428 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000429 char *argv0; /* Name of the program */
430};
431
432#define MemoryCheck(X) if((X)==0){ \
433 extern void memory_error(); \
434 memory_error(); \
435}
436
437/**************** From the file "table.h" *********************************/
438/*
439** All code in this file has been automatically generated
440** from a specification in the file
441** "table.q"
442** by the associative array code building program "aagen".
443** Do not edit this file! Instead, edit the specification
444** file, then rerun aagen.
445*/
446/*
447** Code for processing tables in the LEMON parser generator.
448*/
drh75897232000-05-29 14:26:00 +0000449/* Routines for handling a strings */
450
icculus9e44cf12010-02-14 17:14:22 +0000451const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000452
icculus9e44cf12010-02-14 17:14:22 +0000453void Strsafe_init(void);
454int Strsafe_insert(const char *);
455const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000456
457/* Routines for handling symbols of the grammar */
458
icculus9e44cf12010-02-14 17:14:22 +0000459struct symbol *Symbol_new(const char *);
460int Symbolcmpp(const void *, const void *);
461void Symbol_init(void);
462int Symbol_insert(struct symbol *, const char *);
463struct symbol *Symbol_find(const char *);
464struct symbol *Symbol_Nth(int);
465int Symbol_count(void);
466struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000467
468/* Routines to manage the state table */
469
icculus9e44cf12010-02-14 17:14:22 +0000470int Configcmp(const char *, const char *);
471struct state *State_new(void);
472void State_init(void);
473int State_insert(struct state *, struct config *);
474struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000475struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000476
477/* Routines used for efficiency in Configlist_add */
478
icculus9e44cf12010-02-14 17:14:22 +0000479void Configtable_init(void);
480int Configtable_insert(struct config *);
481struct config *Configtable_find(struct config *);
482void Configtable_clear(int(*)(struct config *));
483
drh75897232000-05-29 14:26:00 +0000484/****************** From the file "action.c" *******************************/
485/*
486** Routines processing parser actions in the LEMON parser generator.
487*/
488
489/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000490static struct action *Action_new(void){
mistachkind9bc6e82019-05-10 16:16:19 +0000491 static struct action *actionfreelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000492 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000493
mistachkind9bc6e82019-05-10 16:16:19 +0000494 if( actionfreelist==0 ){
drh75897232000-05-29 14:26:00 +0000495 int i;
496 int amt = 100;
mistachkind9bc6e82019-05-10 16:16:19 +0000497 actionfreelist = (struct action *)calloc(amt, sizeof(struct action));
498 if( actionfreelist==0 ){
drh75897232000-05-29 14:26:00 +0000499 fprintf(stderr,"Unable to allocate memory for a new parser action.");
500 exit(1);
501 }
mistachkind9bc6e82019-05-10 16:16:19 +0000502 for(i=0; i<amt-1; i++) actionfreelist[i].next = &actionfreelist[i+1];
503 actionfreelist[amt-1].next = 0;
drh75897232000-05-29 14:26:00 +0000504 }
mistachkind9bc6e82019-05-10 16:16:19 +0000505 newaction = actionfreelist;
506 actionfreelist = actionfreelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000507 return newaction;
drh75897232000-05-29 14:26:00 +0000508}
509
drhe9278182007-07-18 18:16:29 +0000510/* Compare two actions for sorting purposes. Return negative, zero, or
511** positive if the first action is less than, equal to, or greater than
512** the first
513*/
514static int actioncmp(
515 struct action *ap1,
516 struct action *ap2
517){
drh75897232000-05-29 14:26:00 +0000518 int rc;
519 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000520 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000521 rc = (int)ap1->type - (int)ap2->type;
522 }
drh3bd48ab2015-09-07 18:23:37 +0000523 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000524 rc = ap1->x.rp->index - ap2->x.rp->index;
525 }
drhe594bc32009-11-03 13:02:25 +0000526 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000527 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000528 }
drh75897232000-05-29 14:26:00 +0000529 return rc;
530}
531
532/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000533static struct action *Action_sort(
534 struct action *ap
535){
536 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
537 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000538 return ap;
539}
540
icculus9e44cf12010-02-14 17:14:22 +0000541void Action_add(
542 struct action **app,
543 enum e_action type,
544 struct symbol *sp,
545 char *arg
546){
547 struct action *newaction;
548 newaction = Action_new();
549 newaction->next = *app;
550 *app = newaction;
551 newaction->type = type;
552 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000553 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000554 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000555 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000556 }else{
icculus9e44cf12010-02-14 17:14:22 +0000557 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000558 }
559}
drh8b582012003-10-21 13:16:03 +0000560/********************** New code to implement the "acttab" module ***********/
561/*
562** This module implements routines use to construct the yy_action[] table.
563*/
564
565/*
566** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000567** the following structure.
568**
569** The yy_action table maps the pair (state_number, lookahead) into an
570** action_number. The table is an array of integers pairs. The state_number
571** determines an initial offset into the yy_action array. The lookahead
572** value is then added to this initial offset to get an index X into the
573** yy_action array. If the aAction[X].lookahead equals the value of the
574** of the lookahead input, then the value of the action_number output is
575** aAction[X].action. If the lookaheads do not match then the
576** default action for the state_number is returned.
577**
578** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000579** into aLookahead[] using multiple calls to acttab_action(). Then the
580** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000581** array with a single call to acttab_insert(). The acttab_insert() call
582** also resets the aLookahead[] array in preparation for the next
583** state number.
drh8b582012003-10-21 13:16:03 +0000584*/
icculus9e44cf12010-02-14 17:14:22 +0000585struct lookahead_action {
586 int lookahead; /* Value of the lookahead token */
587 int action; /* Action to take on the given lookahead */
588};
drh8b582012003-10-21 13:16:03 +0000589typedef struct acttab acttab;
590struct acttab {
591 int nAction; /* Number of used slots in aAction[] */
592 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000593 struct lookahead_action
594 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000595 *aLookahead; /* A single new transaction set */
596 int mnLookahead; /* Minimum aLookahead[].lookahead */
597 int mnAction; /* Action associated with mnLookahead */
598 int mxLookahead; /* Maximum aLookahead[].lookahead */
599 int nLookahead; /* Used slots in aLookahead[] */
600 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
drh3a9d6c72017-12-25 04:15:38 +0000601 int nterminal; /* Number of terminal symbols */
602 int nsymbol; /* total number of symbols */
drh8b582012003-10-21 13:16:03 +0000603};
604
605/* Return the number of entries in the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +0000606#define acttab_lookahead_size(X) ((X)->nAction)
drh8b582012003-10-21 13:16:03 +0000607
608/* The value for the N-th entry in yy_action */
609#define acttab_yyaction(X,N) ((X)->aAction[N].action)
610
611/* The value for the N-th entry in yy_lookahead */
612#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
613
614/* Free all memory associated with the given acttab */
615void acttab_free(acttab *p){
616 free( p->aAction );
617 free( p->aLookahead );
618 free( p );
619}
620
621/* Allocate a new acttab structure */
drh3a9d6c72017-12-25 04:15:38 +0000622acttab *acttab_alloc(int nsymbol, int nterminal){
icculus9e44cf12010-02-14 17:14:22 +0000623 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000624 if( p==0 ){
625 fprintf(stderr,"Unable to allocate memory for a new acttab.");
626 exit(1);
627 }
628 memset(p, 0, sizeof(*p));
drh3a9d6c72017-12-25 04:15:38 +0000629 p->nsymbol = nsymbol;
630 p->nterminal = nterminal;
drh8b582012003-10-21 13:16:03 +0000631 return p;
632}
633
drh06f60d82017-04-14 19:46:12 +0000634/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000635**
636** This routine is called once for each lookahead for a particular
637** state.
drh8b582012003-10-21 13:16:03 +0000638*/
639void acttab_action(acttab *p, int lookahead, int action){
640 if( p->nLookahead>=p->nLookaheadAlloc ){
641 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000642 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000643 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
644 if( p->aLookahead==0 ){
645 fprintf(stderr,"malloc failed\n");
646 exit(1);
647 }
648 }
649 if( p->nLookahead==0 ){
650 p->mxLookahead = lookahead;
651 p->mnLookahead = lookahead;
652 p->mnAction = action;
653 }else{
654 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
655 if( p->mnLookahead>lookahead ){
656 p->mnLookahead = lookahead;
657 p->mnAction = action;
658 }
659 }
660 p->aLookahead[p->nLookahead].lookahead = lookahead;
661 p->aLookahead[p->nLookahead].action = action;
662 p->nLookahead++;
663}
664
665/*
666** Add the transaction set built up with prior calls to acttab_action()
667** into the current action table. Then reset the transaction set back
668** to an empty set in preparation for a new round of acttab_action() calls.
669**
670** Return the offset into the action table of the new transaction.
drh3a9d6c72017-12-25 04:15:38 +0000671**
672** If the makeItSafe parameter is true, then the offset is chosen so that
673** it is impossible to overread the yy_lookaside[] table regardless of
674** the lookaside token. This is done for the terminal symbols, as they
675** come from external inputs and can contain syntax errors. When makeItSafe
676** is false, there is more flexibility in selecting offsets, resulting in
677** a smaller table. For non-terminal symbols, which are never syntax errors,
678** makeItSafe can be false.
drh8b582012003-10-21 13:16:03 +0000679*/
drh3a9d6c72017-12-25 04:15:38 +0000680int acttab_insert(acttab *p, int makeItSafe){
681 int i, j, k, n, end;
drh8b582012003-10-21 13:16:03 +0000682 assert( p->nLookahead>0 );
683
684 /* Make sure we have enough space to hold the expanded action table
685 ** in the worst case. The worst case occurs if the transaction set
686 ** must be appended to the current action table
687 */
drh3a9d6c72017-12-25 04:15:38 +0000688 n = p->nsymbol + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000689 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000690 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000691 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000692 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000693 sizeof(p->aAction[0])*p->nActionAlloc);
694 if( p->aAction==0 ){
695 fprintf(stderr,"malloc failed\n");
696 exit(1);
697 }
drhfdbf9282003-10-21 16:34:41 +0000698 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000699 p->aAction[i].lookahead = -1;
700 p->aAction[i].action = -1;
701 }
702 }
703
drh06f60d82017-04-14 19:46:12 +0000704 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000705 ** duplicate of the current transaction set. Fall out of the loop
706 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000707 **
708 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
709 */
drh3a9d6c72017-12-25 04:15:38 +0000710 end = makeItSafe ? p->mnLookahead : 0;
711 for(i=p->nAction-1; i>=end; i--){
drhf16371d2009-11-03 19:18:31 +0000712 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000713 /* All lookaheads and actions in the aLookahead[] transaction
714 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000715 if( p->aAction[i].action!=p->mnAction ) continue;
716 for(j=0; j<p->nLookahead; j++){
717 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
718 if( k<0 || k>=p->nAction ) break;
719 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
720 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
721 }
722 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000723
724 /* No possible lookahead value that is not in the aLookahead[]
725 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000726 n = 0;
727 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000728 if( p->aAction[j].lookahead<0 ) continue;
729 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000730 }
drhfdbf9282003-10-21 16:34:41 +0000731 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000732 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000733 }
drh8b582012003-10-21 13:16:03 +0000734 }
735 }
drh8dc3e8f2010-01-07 03:53:03 +0000736
737 /* If no existing offsets exactly match the current transaction, find an
738 ** an empty offset in the aAction[] table in which we can add the
739 ** aLookahead[] transaction.
740 */
drh3a9d6c72017-12-25 04:15:38 +0000741 if( i<end ){
drh8dc3e8f2010-01-07 03:53:03 +0000742 /* Look for holes in the aAction[] table that fit the current
743 ** aLookahead[] transaction. Leave i set to the offset of the hole.
744 ** If no holes are found, i is left at p->nAction, which means the
745 ** transaction will be appended. */
drh3a9d6c72017-12-25 04:15:38 +0000746 i = makeItSafe ? p->mnLookahead : 0;
747 for(; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000748 if( p->aAction[i].lookahead<0 ){
749 for(j=0; j<p->nLookahead; j++){
750 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
751 if( k<0 ) break;
752 if( p->aAction[k].lookahead>=0 ) break;
753 }
754 if( j<p->nLookahead ) continue;
755 for(j=0; j<p->nAction; j++){
756 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
757 }
758 if( j==p->nAction ){
759 break; /* Fits in empty slots */
760 }
761 }
762 }
763 }
drh8b582012003-10-21 13:16:03 +0000764 /* Insert transaction set at index i. */
drh3a9d6c72017-12-25 04:15:38 +0000765#if 0
766 printf("Acttab:");
767 for(j=0; j<p->nLookahead; j++){
768 printf(" %d", p->aLookahead[j].lookahead);
769 }
770 printf(" inserted at %d\n", i);
771#endif
drh8b582012003-10-21 13:16:03 +0000772 for(j=0; j<p->nLookahead; j++){
773 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
774 p->aAction[k] = p->aLookahead[j];
775 if( k>=p->nAction ) p->nAction = k+1;
776 }
drh4396c612017-12-27 15:21:16 +0000777 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
drh8b582012003-10-21 13:16:03 +0000778 p->nLookahead = 0;
779
780 /* Return the offset that is added to the lookahead in order to get the
781 ** index into yy_action of the action */
782 return i - p->mnLookahead;
783}
784
drh3a9d6c72017-12-25 04:15:38 +0000785/*
786** Return the size of the action table without the trailing syntax error
787** entries.
788*/
789int acttab_action_size(acttab *p){
790 int n = p->nAction;
791 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
792 return n;
793}
794
drh75897232000-05-29 14:26:00 +0000795/********************** From the file "build.c" *****************************/
796/*
797** Routines to construction the finite state machine for the LEMON
798** parser generator.
799*/
800
801/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000802**
drh75897232000-05-29 14:26:00 +0000803** Those rules which have a precedence symbol coded in the input
804** grammar using the "[symbol]" construct will already have the
805** rp->precsym field filled. Other rules take as their precedence
806** symbol the first RHS symbol with a defined precedence. If there
807** are not RHS symbols with a defined precedence, the precedence
808** symbol field is left blank.
809*/
icculus9e44cf12010-02-14 17:14:22 +0000810void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000811{
812 struct rule *rp;
813 for(rp=xp->rule; rp; rp=rp->next){
814 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000815 int i, j;
816 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
817 struct symbol *sp = rp->rhs[i];
818 if( sp->type==MULTITERMINAL ){
819 for(j=0; j<sp->nsubsym; j++){
820 if( sp->subsym[j]->prec>=0 ){
821 rp->precsym = sp->subsym[j];
822 break;
823 }
824 }
825 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000826 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000827 }
drh75897232000-05-29 14:26:00 +0000828 }
829 }
830 }
831 return;
832}
833
834/* Find all nonterminals which will generate the empty string.
835** Then go back and compute the first sets of every nonterminal.
836** The first set is the set of all terminal symbols which can begin
837** a string generated by that nonterminal.
838*/
icculus9e44cf12010-02-14 17:14:22 +0000839void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000840{
drhfd405312005-11-06 04:06:59 +0000841 int i, j;
drh75897232000-05-29 14:26:00 +0000842 struct rule *rp;
843 int progress;
844
845 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000846 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000847 }
848 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
849 lemp->symbols[i]->firstset = SetNew();
850 }
851
852 /* First compute all lambdas */
853 do{
854 progress = 0;
855 for(rp=lemp->rule; rp; rp=rp->next){
856 if( rp->lhs->lambda ) continue;
857 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000858 struct symbol *sp = rp->rhs[i];
859 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
860 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000861 }
862 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000863 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000864 progress = 1;
865 }
866 }
867 }while( progress );
868
869 /* Now compute all first sets */
870 do{
871 struct symbol *s1, *s2;
872 progress = 0;
873 for(rp=lemp->rule; rp; rp=rp->next){
874 s1 = rp->lhs;
875 for(i=0; i<rp->nrhs; i++){
876 s2 = rp->rhs[i];
877 if( s2->type==TERMINAL ){
878 progress += SetAdd(s1->firstset,s2->index);
879 break;
drhfd405312005-11-06 04:06:59 +0000880 }else if( s2->type==MULTITERMINAL ){
881 for(j=0; j<s2->nsubsym; j++){
882 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
883 }
884 break;
drhf2f105d2012-08-20 15:53:54 +0000885 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000886 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000887 }else{
drh75897232000-05-29 14:26:00 +0000888 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000889 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000890 }
drh75897232000-05-29 14:26:00 +0000891 }
892 }
893 }while( progress );
894 return;
895}
896
897/* Compute all LR(0) states for the grammar. Links
898** are added to between some states so that the LR(1) follow sets
899** can be computed later.
900*/
icculus9e44cf12010-02-14 17:14:22 +0000901PRIVATE struct state *getstate(struct lemon *); /* forward reference */
902void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000903{
904 struct symbol *sp;
905 struct rule *rp;
906
907 Configlist_init();
908
909 /* Find the start symbol */
910 if( lemp->start ){
911 sp = Symbol_find(lemp->start);
912 if( sp==0 ){
913 ErrorMsg(lemp->filename,0,
drh3ecc05b2019-12-12 00:20:40 +0000914 "The specified start symbol \"%s\" is not "
915 "in a nonterminal of the grammar. \"%s\" will be used as the start "
916 "symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000917 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000918 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000919 }
920 }else{
drh4ef07702016-03-16 19:45:54 +0000921 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000922 }
923
924 /* Make sure the start symbol doesn't occur on the right-hand side of
925 ** any rule. Report an error if it does. (YACC would generate a new
926 ** start symbol in this case.) */
927 for(rp=lemp->rule; rp; rp=rp->next){
928 int i;
929 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000930 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000931 ErrorMsg(lemp->filename,0,
drh3ecc05b2019-12-12 00:20:40 +0000932 "The start symbol \"%s\" occurs on the "
933 "right-hand side of a rule. This will result in a parser which "
934 "does not work properly.",sp->name);
drh75897232000-05-29 14:26:00 +0000935 lemp->errorcnt++;
936 }
937 }
938 }
939
940 /* The basis configuration set for the first state
941 ** is all rules which have the start symbol as their
942 ** left-hand side */
943 for(rp=sp->rule; rp; rp=rp->nextlhs){
944 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000945 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000946 newcfp = Configlist_addbasis(rp,0);
947 SetAdd(newcfp->fws,0);
948 }
949
950 /* Compute the first state. All other states will be
951 ** computed automatically during the computation of the first one.
952 ** The returned pointer to the first state is not used. */
953 (void)getstate(lemp);
954 return;
955}
956
957/* Return a pointer to a state which is described by the configuration
958** list which has been built from calls to Configlist_add.
959*/
icculus9e44cf12010-02-14 17:14:22 +0000960PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
961PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000962{
963 struct config *cfp, *bp;
964 struct state *stp;
965
966 /* Extract the sorted basis of the new state. The basis was constructed
967 ** by prior calls to "Configlist_addbasis()". */
968 Configlist_sortbasis();
969 bp = Configlist_basis();
970
971 /* Get a state with the same basis */
972 stp = State_find(bp);
973 if( stp ){
974 /* A state with the same basis already exists! Copy all the follow-set
975 ** propagation links from the state under construction into the
976 ** preexisting state, then return a pointer to the preexisting state */
977 struct config *x, *y;
978 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
979 Plink_copy(&y->bplp,x->bplp);
980 Plink_delete(x->fplp);
981 x->fplp = x->bplp = 0;
982 }
983 cfp = Configlist_return();
984 Configlist_eat(cfp);
985 }else{
986 /* This really is a new state. Construct all the details */
987 Configlist_closure(lemp); /* Compute the configuration closure */
988 Configlist_sort(); /* Sort the configuration closure */
989 cfp = Configlist_return(); /* Get a pointer to the config list */
990 stp = State_new(); /* A new state structure */
991 MemoryCheck(stp);
992 stp->bp = bp; /* Remember the configuration basis */
993 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000994 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000995 stp->ap = 0; /* No actions, yet. */
996 State_insert(stp,stp->bp); /* Add to the state table */
997 buildshifts(lemp,stp); /* Recursively compute successor states */
998 }
999 return stp;
1000}
1001
drhfd405312005-11-06 04:06:59 +00001002/*
1003** Return true if two symbols are the same.
1004*/
icculus9e44cf12010-02-14 17:14:22 +00001005int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +00001006{
1007 int i;
1008 if( a==b ) return 1;
1009 if( a->type!=MULTITERMINAL ) return 0;
1010 if( b->type!=MULTITERMINAL ) return 0;
1011 if( a->nsubsym!=b->nsubsym ) return 0;
1012 for(i=0; i<a->nsubsym; i++){
1013 if( a->subsym[i]!=b->subsym[i] ) return 0;
1014 }
1015 return 1;
1016}
1017
drh75897232000-05-29 14:26:00 +00001018/* Construct all successor states to the given state. A "successor"
1019** state is any state which can be reached by a shift action.
1020*/
icculus9e44cf12010-02-14 17:14:22 +00001021PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +00001022{
1023 struct config *cfp; /* For looping thru the config closure of "stp" */
1024 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +00001025 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +00001026 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1027 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1028 struct state *newstp; /* A pointer to a successor state */
1029
1030 /* Each configuration becomes complete after it contibutes to a successor
1031 ** state. Initially, all configurations are incomplete */
1032 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1033
1034 /* Loop through all configurations of the state "stp" */
1035 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1036 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1037 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1038 Configlist_reset(); /* Reset the new config set */
1039 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1040
1041 /* For every configuration in the state "stp" which has the symbol "sp"
1042 ** following its dot, add the same configuration to the basis set under
1043 ** construction but with the dot shifted one symbol to the right. */
1044 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1045 if( bcfp->status==COMPLETE ) continue; /* Already used */
1046 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1047 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001048 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001049 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001050 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1051 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001052 }
1053
1054 /* Get a pointer to the state described by the basis configuration set
1055 ** constructed in the preceding loop */
1056 newstp = getstate(lemp);
1057
1058 /* The state "newstp" is reached from the state "stp" by a shift action
1059 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001060 if( sp->type==MULTITERMINAL ){
1061 int i;
1062 for(i=0; i<sp->nsubsym; i++){
1063 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1064 }
1065 }else{
1066 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1067 }
drh75897232000-05-29 14:26:00 +00001068 }
1069}
1070
1071/*
1072** Construct the propagation links
1073*/
icculus9e44cf12010-02-14 17:14:22 +00001074void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001075{
1076 int i;
1077 struct config *cfp, *other;
1078 struct state *stp;
1079 struct plink *plp;
1080
1081 /* Housekeeping detail:
1082 ** Add to every propagate link a pointer back to the state to
1083 ** which the link is attached. */
1084 for(i=0; i<lemp->nstate; i++){
1085 stp = lemp->sorted[i];
1086 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1087 cfp->stp = stp;
1088 }
1089 }
1090
1091 /* Convert all backlinks into forward links. Only the forward
1092 ** links are used in the follow-set computation. */
1093 for(i=0; i<lemp->nstate; i++){
1094 stp = lemp->sorted[i];
1095 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1096 for(plp=cfp->bplp; plp; plp=plp->next){
1097 other = plp->cfp;
1098 Plink_add(&other->fplp,cfp);
1099 }
1100 }
1101 }
1102}
1103
1104/* Compute all followsets.
1105**
1106** A followset is the set of all symbols which can come immediately
1107** after a configuration.
1108*/
icculus9e44cf12010-02-14 17:14:22 +00001109void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001110{
1111 int i;
1112 struct config *cfp;
1113 struct plink *plp;
1114 int progress;
1115 int change;
1116
1117 for(i=0; i<lemp->nstate; i++){
1118 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1119 cfp->status = INCOMPLETE;
1120 }
1121 }
drh06f60d82017-04-14 19:46:12 +00001122
drh75897232000-05-29 14:26:00 +00001123 do{
1124 progress = 0;
1125 for(i=0; i<lemp->nstate; i++){
1126 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1127 if( cfp->status==COMPLETE ) continue;
1128 for(plp=cfp->fplp; plp; plp=plp->next){
1129 change = SetUnion(plp->cfp->fws,cfp->fws);
1130 if( change ){
1131 plp->cfp->status = INCOMPLETE;
1132 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001133 }
1134 }
drh75897232000-05-29 14:26:00 +00001135 cfp->status = COMPLETE;
1136 }
1137 }
1138 }while( progress );
1139}
1140
drh3cb2f6e2012-01-09 14:19:05 +00001141static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001142
1143/* Compute the reduce actions, and resolve conflicts.
1144*/
icculus9e44cf12010-02-14 17:14:22 +00001145void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001146{
1147 int i,j;
1148 struct config *cfp;
1149 struct state *stp;
1150 struct symbol *sp;
1151 struct rule *rp;
1152
drh06f60d82017-04-14 19:46:12 +00001153 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001154 ** A reduce action is added for each element of the followset of
1155 ** a configuration which has its dot at the extreme right.
1156 */
1157 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1158 stp = lemp->sorted[i];
1159 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1160 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1161 for(j=0; j<lemp->nterminal; j++){
1162 if( SetFind(cfp->fws,j) ){
1163 /* Add a reduce action to the state "stp" which will reduce by the
1164 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001165 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001166 }
drhf2f105d2012-08-20 15:53:54 +00001167 }
drh75897232000-05-29 14:26:00 +00001168 }
1169 }
1170 }
1171
1172 /* Add the accepting token */
1173 if( lemp->start ){
1174 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001175 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001176 }else{
drh4ef07702016-03-16 19:45:54 +00001177 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001178 }
1179 /* Add to the first state (which is always the starting state of the
1180 ** finite state machine) an action to ACCEPT if the lookahead is the
1181 ** start nonterminal. */
1182 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1183
1184 /* Resolve conflicts */
1185 for(i=0; i<lemp->nstate; i++){
1186 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001187 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001188 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001189 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001190 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001191 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1192 /* The two actions "ap" and "nap" have the same lookahead.
1193 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001194 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001195 }
1196 }
1197 }
1198
1199 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001200 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001201 for(i=0; i<lemp->nstate; i++){
1202 struct action *ap;
1203 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001204 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001205 }
1206 }
1207 for(rp=lemp->rule; rp; rp=rp->next){
1208 if( rp->canReduce ) continue;
1209 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1210 lemp->errorcnt++;
1211 }
1212}
1213
1214/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001215** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001216**
1217** NO LONGER TRUE:
1218** To resolve a conflict, first look to see if either action
1219** is on an error rule. In that case, take the action which
1220** is not associated with the error rule. If neither or both
1221** actions are associated with an error rule, then try to
1222** use precedence to resolve the conflict.
1223**
1224** If either action is a SHIFT, then it must be apx. This
1225** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1226*/
icculus9e44cf12010-02-14 17:14:22 +00001227static int resolve_conflict(
1228 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001229 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001230){
drh75897232000-05-29 14:26:00 +00001231 struct symbol *spx, *spy;
1232 int errcnt = 0;
1233 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001234 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001235 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001236 errcnt++;
1237 }
drh75897232000-05-29 14:26:00 +00001238 if( apx->type==SHIFT && apy->type==REDUCE ){
1239 spx = apx->sp;
1240 spy = apy->x.rp->precsym;
1241 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1242 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001243 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001244 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001245 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001246 apy->type = RD_RESOLVED;
1247 }else if( spx->prec<spy->prec ){
1248 apx->type = SH_RESOLVED;
1249 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1250 apy->type = RD_RESOLVED; /* associativity */
1251 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1252 apx->type = SH_RESOLVED;
1253 }else{
1254 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001255 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001256 }
1257 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1258 spx = apx->x.rp->precsym;
1259 spy = apy->x.rp->precsym;
1260 if( spx==0 || spy==0 || spx->prec<0 ||
1261 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001262 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001263 errcnt++;
1264 }else if( spx->prec>spy->prec ){
1265 apy->type = RD_RESOLVED;
1266 }else if( spx->prec<spy->prec ){
1267 apx->type = RD_RESOLVED;
1268 }
1269 }else{
drh06f60d82017-04-14 19:46:12 +00001270 assert(
drhb59499c2002-02-23 18:45:13 +00001271 apx->type==SH_RESOLVED ||
1272 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001273 apx->type==SSCONFLICT ||
1274 apx->type==SRCONFLICT ||
1275 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001276 apy->type==SH_RESOLVED ||
1277 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001278 apy->type==SSCONFLICT ||
1279 apy->type==SRCONFLICT ||
1280 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001281 );
1282 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1283 ** REDUCEs on the list. If we reach this point it must be because
1284 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001285 }
1286 return errcnt;
1287}
1288/********************* From the file "configlist.c" *************************/
1289/*
1290** Routines to processing a configuration list and building a state
1291** in the LEMON parser generator.
1292*/
1293
1294static struct config *freelist = 0; /* List of free configurations */
1295static struct config *current = 0; /* Top of list of configurations */
1296static struct config **currentend = 0; /* Last on list of configs */
1297static struct config *basis = 0; /* Top of list of basis configs */
1298static struct config **basisend = 0; /* End of list of basis configs */
1299
1300/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001301PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001302 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001303 if( freelist==0 ){
1304 int i;
1305 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001306 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001307 if( freelist==0 ){
1308 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1309 exit(1);
1310 }
1311 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1312 freelist[amt-1].next = 0;
1313 }
icculus9e44cf12010-02-14 17:14:22 +00001314 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001315 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001316 return newcfg;
drh75897232000-05-29 14:26:00 +00001317}
1318
1319/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001320PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001321{
1322 old->next = freelist;
1323 freelist = old;
1324}
1325
1326/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001327void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001328 current = 0;
1329 currentend = &current;
1330 basis = 0;
1331 basisend = &basis;
1332 Configtable_init();
1333 return;
1334}
1335
1336/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001337void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001338 current = 0;
1339 currentend = &current;
1340 basis = 0;
1341 basisend = &basis;
1342 Configtable_clear(0);
1343 return;
1344}
1345
1346/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001347struct config *Configlist_add(
1348 struct rule *rp, /* The rule */
1349 int dot /* Index into the RHS of the rule where the dot goes */
1350){
drh75897232000-05-29 14:26:00 +00001351 struct config *cfp, model;
1352
1353 assert( currentend!=0 );
1354 model.rp = rp;
1355 model.dot = dot;
1356 cfp = Configtable_find(&model);
1357 if( cfp==0 ){
1358 cfp = newconfig();
1359 cfp->rp = rp;
1360 cfp->dot = dot;
1361 cfp->fws = SetNew();
1362 cfp->stp = 0;
1363 cfp->fplp = cfp->bplp = 0;
1364 cfp->next = 0;
1365 cfp->bp = 0;
1366 *currentend = cfp;
1367 currentend = &cfp->next;
1368 Configtable_insert(cfp);
1369 }
1370 return cfp;
1371}
1372
1373/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001374struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001375{
1376 struct config *cfp, model;
1377
1378 assert( basisend!=0 );
1379 assert( currentend!=0 );
1380 model.rp = rp;
1381 model.dot = dot;
1382 cfp = Configtable_find(&model);
1383 if( cfp==0 ){
1384 cfp = newconfig();
1385 cfp->rp = rp;
1386 cfp->dot = dot;
1387 cfp->fws = SetNew();
1388 cfp->stp = 0;
1389 cfp->fplp = cfp->bplp = 0;
1390 cfp->next = 0;
1391 cfp->bp = 0;
1392 *currentend = cfp;
1393 currentend = &cfp->next;
1394 *basisend = cfp;
1395 basisend = &cfp->bp;
1396 Configtable_insert(cfp);
1397 }
1398 return cfp;
1399}
1400
1401/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001402void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001403{
1404 struct config *cfp, *newcfp;
1405 struct rule *rp, *newrp;
1406 struct symbol *sp, *xsp;
1407 int i, dot;
1408
1409 assert( currentend!=0 );
1410 for(cfp=current; cfp; cfp=cfp->next){
1411 rp = cfp->rp;
1412 dot = cfp->dot;
1413 if( dot>=rp->nrhs ) continue;
1414 sp = rp->rhs[dot];
1415 if( sp->type==NONTERMINAL ){
1416 if( sp->rule==0 && sp!=lemp->errsym ){
1417 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1418 sp->name);
1419 lemp->errorcnt++;
1420 }
1421 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1422 newcfp = Configlist_add(newrp,0);
1423 for(i=dot+1; i<rp->nrhs; i++){
1424 xsp = rp->rhs[i];
1425 if( xsp->type==TERMINAL ){
1426 SetAdd(newcfp->fws,xsp->index);
1427 break;
drhfd405312005-11-06 04:06:59 +00001428 }else if( xsp->type==MULTITERMINAL ){
1429 int k;
1430 for(k=0; k<xsp->nsubsym; k++){
1431 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1432 }
1433 break;
drhf2f105d2012-08-20 15:53:54 +00001434 }else{
drh75897232000-05-29 14:26:00 +00001435 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001436 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001437 }
1438 }
drh75897232000-05-29 14:26:00 +00001439 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1440 }
1441 }
1442 }
1443 return;
1444}
1445
1446/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001447void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001448 current = (struct config*)msort((char*)current,(char**)&(current->next),
1449 Configcmp);
drh75897232000-05-29 14:26:00 +00001450 currentend = 0;
1451 return;
1452}
1453
1454/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001455void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001456 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1457 Configcmp);
drh75897232000-05-29 14:26:00 +00001458 basisend = 0;
1459 return;
1460}
1461
1462/* Return a pointer to the head of the configuration list and
1463** reset the list */
drh14d88552017-04-14 19:44:15 +00001464struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001465 struct config *old;
1466 old = current;
1467 current = 0;
1468 currentend = 0;
1469 return old;
1470}
1471
1472/* Return a pointer to the head of the configuration list and
1473** reset the list */
drh14d88552017-04-14 19:44:15 +00001474struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001475 struct config *old;
1476 old = basis;
1477 basis = 0;
1478 basisend = 0;
1479 return old;
1480}
1481
1482/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001483void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001484{
1485 struct config *nextcfp;
1486 for(; cfp; cfp=nextcfp){
1487 nextcfp = cfp->next;
1488 assert( cfp->fplp==0 );
1489 assert( cfp->bplp==0 );
1490 if( cfp->fws ) SetFree(cfp->fws);
1491 deleteconfig(cfp);
1492 }
1493 return;
1494}
1495/***************** From the file "error.c" *********************************/
1496/*
1497** Code for printing error message.
1498*/
1499
drhf9a2e7b2003-04-15 01:49:48 +00001500void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001501 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001502 fprintf(stderr, "%s:%d: ", filename, lineno);
1503 va_start(ap, format);
1504 vfprintf(stderr,format,ap);
1505 va_end(ap);
1506 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001507}
1508/**************** From the file "main.c" ************************************/
1509/*
1510** Main program file for the LEMON parser generator.
1511*/
1512
1513/* Report an out-of-memory condition and abort. This function
1514** is used mostly by the "MemoryCheck" macro in struct.h
1515*/
drh14d88552017-04-14 19:44:15 +00001516void memory_error(void){
drh75897232000-05-29 14:26:00 +00001517 fprintf(stderr,"Out of memory. Aborting...\n");
1518 exit(1);
1519}
1520
drh6d08b4d2004-07-20 12:45:22 +00001521static int nDefine = 0; /* Number of -D options on the command line */
1522static char **azDefine = 0; /* Name of the -D macros */
1523
1524/* This routine is called with the argument to each -D command-line option.
1525** Add the macro defined to the azDefine array.
1526*/
1527static void handle_D_option(char *z){
1528 char **paz;
1529 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001530 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001531 if( azDefine==0 ){
1532 fprintf(stderr,"out of memory\n");
1533 exit(1);
1534 }
1535 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001536 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001537 if( *paz==0 ){
1538 fprintf(stderr,"out of memory\n");
1539 exit(1);
1540 }
drh898799f2014-01-10 23:21:00 +00001541 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001542 for(z=*paz; *z && *z!='='; z++){}
1543 *z = 0;
1544}
1545
drh9f88e6d2018-04-20 20:47:49 +00001546/* Rember the name of the output directory
1547*/
1548static char *outputDir = NULL;
1549static void handle_d_option(char *z){
1550 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1551 if( outputDir==0 ){
1552 fprintf(stderr,"out of memory\n");
1553 exit(1);
1554 }
1555 lemon_strcpy(outputDir, z);
1556}
1557
icculus3e143bd2010-02-14 00:48:49 +00001558static char *user_templatename = NULL;
1559static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001560 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001561 if( user_templatename==0 ){
1562 memory_error();
1563 }
drh898799f2014-01-10 23:21:00 +00001564 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001565}
drh75897232000-05-29 14:26:00 +00001566
drh711c9812016-05-23 14:24:31 +00001567/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001568static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1569 struct rule *pFirst = 0;
1570 struct rule **ppPrev = &pFirst;
1571 while( pA && pB ){
1572 if( pA->iRule<pB->iRule ){
1573 *ppPrev = pA;
1574 ppPrev = &pA->next;
1575 pA = pA->next;
1576 }else{
1577 *ppPrev = pB;
1578 ppPrev = &pB->next;
1579 pB = pB->next;
1580 }
1581 }
1582 if( pA ){
1583 *ppPrev = pA;
1584 }else{
1585 *ppPrev = pB;
1586 }
1587 return pFirst;
1588}
1589
1590/*
1591** Sort a list of rules in order of increasing iRule value
1592*/
1593static struct rule *Rule_sort(struct rule *rp){
1594 int i;
1595 struct rule *pNext;
1596 struct rule *x[32];
1597 memset(x, 0, sizeof(x));
1598 while( rp ){
1599 pNext = rp->next;
1600 rp->next = 0;
1601 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1602 rp = Rule_merge(x[i], rp);
1603 x[i] = 0;
1604 }
1605 x[i] = rp;
1606 rp = pNext;
1607 }
1608 rp = 0;
1609 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1610 rp = Rule_merge(x[i], rp);
1611 }
1612 return rp;
1613}
1614
drhc75e0162015-09-07 02:23:02 +00001615/* forward reference */
1616static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1617
1618/* Print a single line of the "Parser Stats" output
1619*/
1620static void stats_line(const char *zLabel, int iValue){
1621 int nLabel = lemonStrlen(zLabel);
1622 printf(" %s%.*s %5d\n", zLabel,
1623 35-nLabel, "................................",
1624 iValue);
1625}
1626
drh75897232000-05-29 14:26:00 +00001627/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001628int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001629{
1630 static int version = 0;
1631 static int rpflag = 0;
1632 static int basisflag = 0;
1633 static int compress = 0;
1634 static int quiet = 0;
1635 static int statistics = 0;
1636 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001637 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001638 static int noResort = 0;
drhfe03dac2019-11-26 02:22:39 +00001639 static int sqlFlag = 0;
drh0a34cf52020-07-03 15:41:08 +00001640 static int printPP = 0;
drh9f88e6d2018-04-20 20:47:49 +00001641
drh75897232000-05-29 14:26:00 +00001642 static struct s_options options[] = {
1643 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1644 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh9f88e6d2018-04-20 20:47:49 +00001645 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
drh6d08b4d2004-07-20 12:45:22 +00001646 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0a34cf52020-07-03 15:41:08 +00001647 {OPT_FLAG, "E", (char*)&printPP, "Print input file after preprocessing."},
drh0325d392015-01-01 19:11:22 +00001648 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001649 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001650 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001651 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1652 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001653 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001654 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1655 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001656 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001657 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001658 {OPT_FLAG, "s", (char*)&statistics,
1659 "Print parser stats to standard output."},
drhfe03dac2019-11-26 02:22:39 +00001660 {OPT_FLAG, "S", (char*)&sqlFlag,
1661 "Generate the *.sql file describing the parser tables."},
drh75897232000-05-29 14:26:00 +00001662 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001663 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1664 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001665 {OPT_FLAG,0,0,0}
1666 };
1667 int i;
icculus42585cf2010-02-14 05:19:56 +00001668 int exitcode;
drh75897232000-05-29 14:26:00 +00001669 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001670 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001671
drhb0c86772000-06-02 23:21:26 +00001672 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001673 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001674 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001675 exit(0);
drh75897232000-05-29 14:26:00 +00001676 }
drhb0c86772000-06-02 23:21:26 +00001677 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001678 fprintf(stderr,"Exactly one filename argument is required.\n");
1679 exit(1);
1680 }
drh954f6b42006-06-13 13:27:46 +00001681 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001682 lem.errorcnt = 0;
1683
1684 /* Initialize the machine */
1685 Strsafe_init();
1686 Symbol_init();
1687 State_init();
1688 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001689 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001690 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001691 lem.nolinenosflag = nolinenosflag;
drh0a34cf52020-07-03 15:41:08 +00001692 lem.printPreprocessed = printPP;
drh75897232000-05-29 14:26:00 +00001693 Symbol_new("$");
drh75897232000-05-29 14:26:00 +00001694
1695 /* Parse the input file */
1696 Parse(&lem);
drh0a34cf52020-07-03 15:41:08 +00001697 if( lem.printPreprocessed || lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001698 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001699 fprintf(stderr,"Empty grammar.\n");
1700 exit(1);
1701 }
drhed0c15b2018-04-16 14:31:34 +00001702 lem.errsym = Symbol_find("error");
drh75897232000-05-29 14:26:00 +00001703
1704 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001705 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001706 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001707 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001708 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1709 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1710 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1711 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1712 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1713 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001714 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001715 lem.nterminal = i;
1716
drh711c9812016-05-23 14:24:31 +00001717 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1718 ** reduce action C-code associated with them last, so that the switch()
1719 ** statement that selects reduction actions will have a smaller jump table.
1720 */
drh4ef07702016-03-16 19:45:54 +00001721 for(i=0, rp=lem.rule; rp; rp=rp->next){
1722 rp->iRule = rp->code ? i++ : -1;
1723 }
drhce678c22019-12-11 18:53:51 +00001724 lem.nruleWithAction = i;
drh4ef07702016-03-16 19:45:54 +00001725 for(rp=lem.rule; rp; rp=rp->next){
1726 if( rp->iRule<0 ) rp->iRule = i++;
1727 }
1728 lem.startRule = lem.rule;
1729 lem.rule = Rule_sort(lem.rule);
1730
drh75897232000-05-29 14:26:00 +00001731 /* Generate a reprint of the grammar, if requested on the command line */
1732 if( rpflag ){
1733 Reprint(&lem);
1734 }else{
1735 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001736 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001737
1738 /* Find the precedence for every production rule (that has one) */
1739 FindRulePrecedences(&lem);
1740
1741 /* Compute the lambda-nonterminals and the first-sets for every
1742 ** nonterminal */
1743 FindFirstSets(&lem);
1744
1745 /* Compute all LR(0) states. Also record follow-set propagation
1746 ** links so that the follow-set can be computed later */
1747 lem.nstate = 0;
1748 FindStates(&lem);
1749 lem.sorted = State_arrayof();
1750
1751 /* Tie up loose ends on the propagation links */
1752 FindLinks(&lem);
1753
1754 /* Compute the follow set of every reducible configuration */
1755 FindFollowSets(&lem);
1756
1757 /* Compute the action tables */
1758 FindActions(&lem);
1759
1760 /* Compress the action tables */
1761 if( compress==0 ) CompressTables(&lem);
1762
drhada354d2005-11-05 15:03:59 +00001763 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001764 ** occur at the end. This is an optimization that helps make the
1765 ** generated parser tables smaller. */
1766 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001767
drh75897232000-05-29 14:26:00 +00001768 /* Generate a report of the parser generated. (the "y.output" file) */
1769 if( !quiet ) ReportOutput(&lem);
1770
1771 /* Generate the source code for the parser */
drhfe03dac2019-11-26 02:22:39 +00001772 ReportTable(&lem, mhflag, sqlFlag);
drh75897232000-05-29 14:26:00 +00001773
1774 /* Produce a header file for use by the scanner. (This step is
1775 ** omitted if the "-m" option is used because makeheaders will
1776 ** generate the file for us.) */
1777 if( !mhflag ) ReportHeader(&lem);
1778 }
1779 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001780 printf("Parser statistics:\n");
1781 stats_line("terminal symbols", lem.nterminal);
1782 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1783 stats_line("total symbols", lem.nsymbol);
1784 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001785 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001786 stats_line("conflicts", lem.nconflict);
1787 stats_line("action table entries", lem.nactiontab);
drh3a9d6c72017-12-25 04:15:38 +00001788 stats_line("lookahead table entries", lem.nlookaheadtab);
drhc75e0162015-09-07 02:23:02 +00001789 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001790 }
icculus8e158022010-02-16 16:09:03 +00001791 if( lem.nconflict > 0 ){
1792 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001793 }
1794
1795 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001796 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001797 exit(exitcode);
1798 return (exitcode);
drh75897232000-05-29 14:26:00 +00001799}
1800/******************** From the file "msort.c" *******************************/
1801/*
1802** A generic merge-sort program.
1803**
1804** USAGE:
1805** Let "ptr" be a pointer to some structure which is at the head of
1806** a null-terminated list. Then to sort the list call:
1807**
1808** ptr = msort(ptr,&(ptr->next),cmpfnc);
1809**
1810** In the above, "cmpfnc" is a pointer to a function which compares
1811** two instances of the structure and returns an integer, as in
1812** strcmp. The second argument is a pointer to the pointer to the
1813** second element of the linked list. This address is used to compute
1814** the offset to the "next" field within the structure. The offset to
1815** the "next" field must be constant for all structures in the list.
1816**
1817** The function returns a new pointer which is the head of the list
1818** after sorting.
1819**
1820** ALGORITHM:
1821** Merge-sort.
1822*/
1823
1824/*
1825** Return a pointer to the next structure in the linked list.
1826*/
drhd25d6922012-04-18 09:59:56 +00001827#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001828
1829/*
1830** Inputs:
1831** a: A sorted, null-terminated linked list. (May be null).
1832** b: A sorted, null-terminated linked list. (May be null).
1833** cmp: A pointer to the comparison function.
1834** offset: Offset in the structure to the "next" field.
1835**
1836** Return Value:
1837** A pointer to the head of a sorted list containing the elements
1838** of both a and b.
1839**
1840** Side effects:
1841** The "next" pointers for elements in the lists a and b are
1842** changed.
1843*/
drhe9278182007-07-18 18:16:29 +00001844static char *merge(
1845 char *a,
1846 char *b,
1847 int (*cmp)(const char*,const char*),
1848 int offset
1849){
drh75897232000-05-29 14:26:00 +00001850 char *ptr, *head;
1851
1852 if( a==0 ){
1853 head = b;
1854 }else if( b==0 ){
1855 head = a;
1856 }else{
drhe594bc32009-11-03 13:02:25 +00001857 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001858 ptr = a;
1859 a = NEXT(a);
1860 }else{
1861 ptr = b;
1862 b = NEXT(b);
1863 }
1864 head = ptr;
1865 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001866 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001867 NEXT(ptr) = a;
1868 ptr = a;
1869 a = NEXT(a);
1870 }else{
1871 NEXT(ptr) = b;
1872 ptr = b;
1873 b = NEXT(b);
1874 }
1875 }
1876 if( a ) NEXT(ptr) = a;
1877 else NEXT(ptr) = b;
1878 }
1879 return head;
1880}
1881
1882/*
1883** Inputs:
1884** list: Pointer to a singly-linked list of structures.
1885** next: Pointer to pointer to the second element of the list.
1886** cmp: A comparison function.
1887**
1888** Return Value:
1889** A pointer to the head of a sorted list containing the elements
1890** orginally in list.
1891**
1892** Side effects:
1893** The "next" pointers for elements in list are changed.
1894*/
1895#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001896static char *msort(
1897 char *list,
1898 char **next,
1899 int (*cmp)(const char*,const char*)
1900){
drhba99af52001-10-25 20:37:16 +00001901 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001902 char *ep;
1903 char *set[LISTSIZE];
1904 int i;
drh1cc0d112015-03-31 15:15:48 +00001905 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001906 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1907 while( list ){
1908 ep = list;
1909 list = NEXT(list);
1910 NEXT(ep) = 0;
1911 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1912 ep = merge(ep,set[i],cmp,offset);
1913 set[i] = 0;
1914 }
1915 set[i] = ep;
1916 }
1917 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001918 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001919 return ep;
1920}
1921/************************ From the file "option.c" **************************/
mistachkind9bc6e82019-05-10 16:16:19 +00001922static char **g_argv;
drh75897232000-05-29 14:26:00 +00001923static struct s_options *op;
1924static FILE *errstream;
1925
1926#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1927
1928/*
1929** Print the command line with a carrot pointing to the k-th character
1930** of the n-th field.
1931*/
icculus9e44cf12010-02-14 17:14:22 +00001932static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001933{
1934 int spcnt, i;
mistachkind9bc6e82019-05-10 16:16:19 +00001935 if( g_argv[0] ) fprintf(err,"%s",g_argv[0]);
1936 spcnt = lemonStrlen(g_argv[0]) + 1;
1937 for(i=1; i<n && g_argv[i]; i++){
1938 fprintf(err," %s",g_argv[i]);
1939 spcnt += lemonStrlen(g_argv[i])+1;
drh75897232000-05-29 14:26:00 +00001940 }
1941 spcnt += k;
mistachkind9bc6e82019-05-10 16:16:19 +00001942 for(; g_argv[i]; i++) fprintf(err," %s",g_argv[i]);
drh75897232000-05-29 14:26:00 +00001943 if( spcnt<20 ){
1944 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1945 }else{
1946 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1947 }
1948}
1949
1950/*
1951** Return the index of the N-th non-switch argument. Return -1
1952** if N is out of range.
1953*/
icculus9e44cf12010-02-14 17:14:22 +00001954static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001955{
1956 int i;
1957 int dashdash = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00001958 if( g_argv!=0 && *g_argv!=0 ){
1959 for(i=1; g_argv[i]; i++){
1960 if( dashdash || !ISOPT(g_argv[i]) ){
drh75897232000-05-29 14:26:00 +00001961 if( n==0 ) return i;
1962 n--;
1963 }
mistachkind9bc6e82019-05-10 16:16:19 +00001964 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
drh75897232000-05-29 14:26:00 +00001965 }
1966 }
1967 return -1;
1968}
1969
1970static char emsg[] = "Command line syntax error: ";
1971
1972/*
1973** Process a flag command line argument.
1974*/
icculus9e44cf12010-02-14 17:14:22 +00001975static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001976{
1977 int v;
1978 int errcnt = 0;
1979 int j;
1980 for(j=0; op[j].label; j++){
mistachkind9bc6e82019-05-10 16:16:19 +00001981 if( strncmp(&g_argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001982 }
mistachkind9bc6e82019-05-10 16:16:19 +00001983 v = g_argv[i][0]=='-' ? 1 : 0;
drh75897232000-05-29 14:26:00 +00001984 if( op[j].label==0 ){
1985 if( err ){
1986 fprintf(err,"%sundefined option.\n",emsg);
1987 errline(i,1,err);
1988 }
1989 errcnt++;
drh0325d392015-01-01 19:11:22 +00001990 }else if( op[j].arg==0 ){
1991 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001992 }else if( op[j].type==OPT_FLAG ){
1993 *((int*)op[j].arg) = v;
1994 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001995 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001996 }else if( op[j].type==OPT_FSTR ){
mistachkind9bc6e82019-05-10 16:16:19 +00001997 (*(void(*)(char *))(op[j].arg))(&g_argv[i][2]);
drh75897232000-05-29 14:26:00 +00001998 }else{
1999 if( err ){
2000 fprintf(err,"%smissing argument on switch.\n",emsg);
2001 errline(i,1,err);
2002 }
2003 errcnt++;
2004 }
2005 return errcnt;
2006}
2007
2008/*
2009** Process a command line switch which has an argument.
2010*/
icculus9e44cf12010-02-14 17:14:22 +00002011static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00002012{
2013 int lv = 0;
2014 double dv = 0.0;
2015 char *sv = 0, *end;
2016 char *cp;
2017 int j;
2018 int errcnt = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00002019 cp = strchr(g_argv[i],'=');
drh43617e92006-03-06 20:55:46 +00002020 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00002021 *cp = 0;
2022 for(j=0; op[j].label; j++){
mistachkind9bc6e82019-05-10 16:16:19 +00002023 if( strcmp(g_argv[i],op[j].label)==0 ) break;
drh75897232000-05-29 14:26:00 +00002024 }
2025 *cp = '=';
2026 if( op[j].label==0 ){
2027 if( err ){
2028 fprintf(err,"%sundefined option.\n",emsg);
2029 errline(i,0,err);
2030 }
2031 errcnt++;
2032 }else{
2033 cp++;
2034 switch( op[j].type ){
2035 case OPT_FLAG:
2036 case OPT_FFLAG:
2037 if( err ){
2038 fprintf(err,"%soption requires an argument.\n",emsg);
2039 errline(i,0,err);
2040 }
2041 errcnt++;
2042 break;
2043 case OPT_DBL:
2044 case OPT_FDBL:
2045 dv = strtod(cp,&end);
2046 if( *end ){
2047 if( err ){
drh25473362015-09-04 18:03:45 +00002048 fprintf(err,
2049 "%sillegal character in floating-point argument.\n",emsg);
mistachkind9bc6e82019-05-10 16:16:19 +00002050 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
drh75897232000-05-29 14:26:00 +00002051 }
2052 errcnt++;
2053 }
2054 break;
2055 case OPT_INT:
2056 case OPT_FINT:
2057 lv = strtol(cp,&end,0);
2058 if( *end ){
2059 if( err ){
2060 fprintf(err,"%sillegal character in integer argument.\n",emsg);
mistachkind9bc6e82019-05-10 16:16:19 +00002061 errline(i,(int)((char*)end-(char*)g_argv[i]),err);
drh75897232000-05-29 14:26:00 +00002062 }
2063 errcnt++;
2064 }
2065 break;
2066 case OPT_STR:
2067 case OPT_FSTR:
2068 sv = cp;
2069 break;
2070 }
2071 switch( op[j].type ){
2072 case OPT_FLAG:
2073 case OPT_FFLAG:
2074 break;
2075 case OPT_DBL:
2076 *(double*)(op[j].arg) = dv;
2077 break;
2078 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002079 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002080 break;
2081 case OPT_INT:
2082 *(int*)(op[j].arg) = lv;
2083 break;
2084 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002085 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002086 break;
2087 case OPT_STR:
2088 *(char**)(op[j].arg) = sv;
2089 break;
2090 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002091 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002092 break;
2093 }
2094 }
2095 return errcnt;
2096}
2097
icculus9e44cf12010-02-14 17:14:22 +00002098int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002099{
2100 int errcnt = 0;
mistachkind9bc6e82019-05-10 16:16:19 +00002101 g_argv = a;
drh75897232000-05-29 14:26:00 +00002102 op = o;
2103 errstream = err;
mistachkind9bc6e82019-05-10 16:16:19 +00002104 if( g_argv && *g_argv && op ){
drh75897232000-05-29 14:26:00 +00002105 int i;
mistachkind9bc6e82019-05-10 16:16:19 +00002106 for(i=1; g_argv[i]; i++){
2107 if( g_argv[i][0]=='+' || g_argv[i][0]=='-' ){
drh75897232000-05-29 14:26:00 +00002108 errcnt += handleflags(i,err);
mistachkind9bc6e82019-05-10 16:16:19 +00002109 }else if( strchr(g_argv[i],'=') ){
drh75897232000-05-29 14:26:00 +00002110 errcnt += handleswitch(i,err);
2111 }
2112 }
2113 }
2114 if( errcnt>0 ){
2115 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002116 OptPrint();
drh75897232000-05-29 14:26:00 +00002117 exit(1);
2118 }
2119 return 0;
2120}
2121
drh14d88552017-04-14 19:44:15 +00002122int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002123 int cnt = 0;
2124 int dashdash = 0;
2125 int i;
mistachkind9bc6e82019-05-10 16:16:19 +00002126 if( g_argv!=0 && g_argv[0]!=0 ){
2127 for(i=1; g_argv[i]; i++){
2128 if( dashdash || !ISOPT(g_argv[i]) ) cnt++;
2129 if( strcmp(g_argv[i],"--")==0 ) dashdash = 1;
drh75897232000-05-29 14:26:00 +00002130 }
2131 }
2132 return cnt;
2133}
2134
icculus9e44cf12010-02-14 17:14:22 +00002135char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002136{
2137 int i;
2138 i = argindex(n);
mistachkind9bc6e82019-05-10 16:16:19 +00002139 return i>=0 ? g_argv[i] : 0;
drh75897232000-05-29 14:26:00 +00002140}
2141
icculus9e44cf12010-02-14 17:14:22 +00002142void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002143{
2144 int i;
2145 i = argindex(n);
2146 if( i>=0 ) errline(i,0,errstream);
2147}
2148
drh14d88552017-04-14 19:44:15 +00002149void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002150 int i;
2151 int max, len;
2152 max = 0;
2153 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002154 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002155 switch( op[i].type ){
2156 case OPT_FLAG:
2157 case OPT_FFLAG:
2158 break;
2159 case OPT_INT:
2160 case OPT_FINT:
2161 len += 9; /* length of "<integer>" */
2162 break;
2163 case OPT_DBL:
2164 case OPT_FDBL:
2165 len += 6; /* length of "<real>" */
2166 break;
2167 case OPT_STR:
2168 case OPT_FSTR:
2169 len += 8; /* length of "<string>" */
2170 break;
2171 }
2172 if( len>max ) max = len;
2173 }
2174 for(i=0; op[i].label; i++){
2175 switch( op[i].type ){
2176 case OPT_FLAG:
2177 case OPT_FFLAG:
2178 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2179 break;
2180 case OPT_INT:
2181 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002182 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002183 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002184 break;
2185 case OPT_DBL:
2186 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002187 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002188 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002189 break;
2190 case OPT_STR:
2191 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002192 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002193 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002194 break;
2195 }
2196 }
2197}
2198/*********************** From the file "parse.c" ****************************/
2199/*
2200** Input file parser for the LEMON parser generator.
2201*/
2202
2203/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002204enum e_state {
2205 INITIALIZE,
2206 WAITING_FOR_DECL_OR_RULE,
2207 WAITING_FOR_DECL_KEYWORD,
2208 WAITING_FOR_DECL_ARG,
2209 WAITING_FOR_PRECEDENCE_SYMBOL,
2210 WAITING_FOR_ARROW,
2211 IN_RHS,
2212 LHS_ALIAS_1,
2213 LHS_ALIAS_2,
2214 LHS_ALIAS_3,
2215 RHS_ALIAS_1,
2216 RHS_ALIAS_2,
2217 PRECEDENCE_MARK_1,
2218 PRECEDENCE_MARK_2,
2219 RESYNC_AFTER_RULE_ERROR,
2220 RESYNC_AFTER_DECL_ERROR,
2221 WAITING_FOR_DESTRUCTOR_SYMBOL,
2222 WAITING_FOR_DATATYPE_SYMBOL,
2223 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002224 WAITING_FOR_WILDCARD_ID,
2225 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002226 WAITING_FOR_CLASS_TOKEN,
2227 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002228};
drh75897232000-05-29 14:26:00 +00002229struct pstate {
2230 char *filename; /* Name of the input file */
2231 int tokenlineno; /* Linenumber at which current token starts */
2232 int errorcnt; /* Number of errors so far */
2233 char *tokenstart; /* Text of current token */
2234 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002235 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002236 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002237 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002238 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002239 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002240 int nrhs; /* Number of right-hand side symbols seen */
2241 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002242 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002243 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002244 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002245 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002246 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002247 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002248 enum e_assoc declassoc; /* Assign this association to decl arguments */
2249 int preccounter; /* Assign this precedence to decl arguments */
2250 struct rule *firstrule; /* Pointer to first rule in the grammar */
2251 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2252};
2253
2254/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002255static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002256{
icculus9e44cf12010-02-14 17:14:22 +00002257 const char *x;
drh75897232000-05-29 14:26:00 +00002258 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2259#if 0
2260 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2261 x,psp->state);
2262#endif
2263 switch( psp->state ){
2264 case INITIALIZE:
2265 psp->prevrule = 0;
2266 psp->preccounter = 0;
2267 psp->firstrule = psp->lastrule = 0;
2268 psp->gp->nrule = 0;
2269 /* Fall thru to next case */
2270 case WAITING_FOR_DECL_OR_RULE:
2271 if( x[0]=='%' ){
2272 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002273 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002274 psp->lhs = Symbol_new(x);
2275 psp->nrhs = 0;
2276 psp->lhsalias = 0;
2277 psp->state = WAITING_FOR_ARROW;
2278 }else if( x[0]=='{' ){
2279 if( psp->prevrule==0 ){
2280 ErrorMsg(psp->filename,psp->tokenlineno,
drh3ecc05b2019-12-12 00:20:40 +00002281 "There is no prior rule upon which to attach the code "
2282 "fragment which begins on this line.");
drh75897232000-05-29 14:26:00 +00002283 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002284 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002285 ErrorMsg(psp->filename,psp->tokenlineno,
drh3ecc05b2019-12-12 00:20:40 +00002286 "Code fragment beginning on this line is not the first "
2287 "to follow the previous rule.");
drh75897232000-05-29 14:26:00 +00002288 psp->errorcnt++;
drhe94006e2019-12-10 20:41:48 +00002289 }else if( strcmp(x, "{NEVER-REDUCE")==0 ){
2290 psp->prevrule->neverReduce = 1;
drh75897232000-05-29 14:26:00 +00002291 }else{
2292 psp->prevrule->line = psp->tokenlineno;
2293 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002294 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002295 }
drh75897232000-05-29 14:26:00 +00002296 }else if( x[0]=='[' ){
2297 psp->state = PRECEDENCE_MARK_1;
2298 }else{
2299 ErrorMsg(psp->filename,psp->tokenlineno,
2300 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2301 x);
2302 psp->errorcnt++;
2303 }
2304 break;
2305 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002306 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "The precedence symbol must be a terminal.");
2309 psp->errorcnt++;
2310 }else if( psp->prevrule==0 ){
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "There is no prior rule to assign precedence \"[%s]\".",x);
2313 psp->errorcnt++;
2314 }else if( psp->prevrule->precsym!=0 ){
2315 ErrorMsg(psp->filename,psp->tokenlineno,
drh3ecc05b2019-12-12 00:20:40 +00002316 "Precedence mark on this line is not the first "
2317 "to follow the previous rule.");
drh75897232000-05-29 14:26:00 +00002318 psp->errorcnt++;
2319 }else{
2320 psp->prevrule->precsym = Symbol_new(x);
2321 }
2322 psp->state = PRECEDENCE_MARK_2;
2323 break;
2324 case PRECEDENCE_MARK_2:
2325 if( x[0]!=']' ){
2326 ErrorMsg(psp->filename,psp->tokenlineno,
2327 "Missing \"]\" on precedence mark.");
2328 psp->errorcnt++;
2329 }
2330 psp->state = WAITING_FOR_DECL_OR_RULE;
2331 break;
2332 case WAITING_FOR_ARROW:
2333 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2334 psp->state = IN_RHS;
2335 }else if( x[0]=='(' ){
2336 psp->state = LHS_ALIAS_1;
2337 }else{
2338 ErrorMsg(psp->filename,psp->tokenlineno,
2339 "Expected to see a \":\" following the LHS symbol \"%s\".",
2340 psp->lhs->name);
2341 psp->errorcnt++;
2342 psp->state = RESYNC_AFTER_RULE_ERROR;
2343 }
2344 break;
2345 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002346 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002347 psp->lhsalias = x;
2348 psp->state = LHS_ALIAS_2;
2349 }else{
2350 ErrorMsg(psp->filename,psp->tokenlineno,
2351 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2352 x,psp->lhs->name);
2353 psp->errorcnt++;
2354 psp->state = RESYNC_AFTER_RULE_ERROR;
2355 }
2356 break;
2357 case LHS_ALIAS_2:
2358 if( x[0]==')' ){
2359 psp->state = LHS_ALIAS_3;
2360 }else{
2361 ErrorMsg(psp->filename,psp->tokenlineno,
2362 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2363 psp->errorcnt++;
2364 psp->state = RESYNC_AFTER_RULE_ERROR;
2365 }
2366 break;
2367 case LHS_ALIAS_3:
2368 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2369 psp->state = IN_RHS;
2370 }else{
2371 ErrorMsg(psp->filename,psp->tokenlineno,
2372 "Missing \"->\" following: \"%s(%s)\".",
2373 psp->lhs->name,psp->lhsalias);
2374 psp->errorcnt++;
2375 psp->state = RESYNC_AFTER_RULE_ERROR;
2376 }
2377 break;
2378 case IN_RHS:
2379 if( x[0]=='.' ){
2380 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002381 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002382 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002383 if( rp==0 ){
2384 ErrorMsg(psp->filename,psp->tokenlineno,
2385 "Can't allocate enough memory for this rule.");
2386 psp->errorcnt++;
2387 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002388 }else{
drh75897232000-05-29 14:26:00 +00002389 int i;
2390 rp->ruleline = psp->tokenlineno;
2391 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002392 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002393 for(i=0; i<psp->nrhs; i++){
2394 rp->rhs[i] = psp->rhs[i];
2395 rp->rhsalias[i] = psp->alias[i];
drh539e7412018-04-21 20:24:19 +00002396 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
drhf2f105d2012-08-20 15:53:54 +00002397 }
drh75897232000-05-29 14:26:00 +00002398 rp->lhs = psp->lhs;
2399 rp->lhsalias = psp->lhsalias;
2400 rp->nrhs = psp->nrhs;
2401 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002402 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002403 rp->precsym = 0;
2404 rp->index = psp->gp->nrule++;
2405 rp->nextlhs = rp->lhs->rule;
2406 rp->lhs->rule = rp;
2407 rp->next = 0;
2408 if( psp->firstrule==0 ){
2409 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002410 }else{
drh75897232000-05-29 14:26:00 +00002411 psp->lastrule->next = rp;
2412 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002413 }
drh75897232000-05-29 14:26:00 +00002414 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002415 }
drh75897232000-05-29 14:26:00 +00002416 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002417 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002418 if( psp->nrhs>=MAXRHS ){
2419 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002420 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002421 x);
2422 psp->errorcnt++;
2423 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002424 }else{
drh75897232000-05-29 14:26:00 +00002425 psp->rhs[psp->nrhs] = Symbol_new(x);
2426 psp->alias[psp->nrhs] = 0;
2427 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002428 }
drhfd405312005-11-06 04:06:59 +00002429 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2430 struct symbol *msp = psp->rhs[psp->nrhs-1];
2431 if( msp->type!=MULTITERMINAL ){
2432 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002433 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002434 memset(msp, 0, sizeof(*msp));
2435 msp->type = MULTITERMINAL;
2436 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002437 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002438 msp->subsym[0] = origsp;
2439 msp->name = origsp->name;
2440 psp->rhs[psp->nrhs-1] = msp;
2441 }
2442 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002443 msp->subsym = (struct symbol **) realloc(msp->subsym,
2444 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002445 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002446 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002447 ErrorMsg(psp->filename,psp->tokenlineno,
2448 "Cannot form a compound containing a non-terminal");
2449 psp->errorcnt++;
2450 }
drh75897232000-05-29 14:26:00 +00002451 }else if( x[0]=='(' && psp->nrhs>0 ){
2452 psp->state = RHS_ALIAS_1;
2453 }else{
2454 ErrorMsg(psp->filename,psp->tokenlineno,
2455 "Illegal character on RHS of rule: \"%s\".",x);
2456 psp->errorcnt++;
2457 psp->state = RESYNC_AFTER_RULE_ERROR;
2458 }
2459 break;
2460 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002461 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002462 psp->alias[psp->nrhs-1] = x;
2463 psp->state = RHS_ALIAS_2;
2464 }else{
2465 ErrorMsg(psp->filename,psp->tokenlineno,
2466 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2467 x,psp->rhs[psp->nrhs-1]->name);
2468 psp->errorcnt++;
2469 psp->state = RESYNC_AFTER_RULE_ERROR;
2470 }
2471 break;
2472 case RHS_ALIAS_2:
2473 if( x[0]==')' ){
2474 psp->state = IN_RHS;
2475 }else{
2476 ErrorMsg(psp->filename,psp->tokenlineno,
2477 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2478 psp->errorcnt++;
2479 psp->state = RESYNC_AFTER_RULE_ERROR;
2480 }
2481 break;
2482 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002483 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002484 psp->declkeyword = x;
2485 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002486 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002487 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002488 psp->state = WAITING_FOR_DECL_ARG;
2489 if( strcmp(x,"name")==0 ){
2490 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002491 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002492 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002493 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002494 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002495 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002496 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002497 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002498 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002499 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002500 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002501 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002502 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002503 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002504 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002505 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002506 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002507 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002508 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002509 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002510 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002511 }else if( strcmp(x,"extra_argument")==0 ){
2512 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002513 psp->insertLineMacro = 0;
drhfb32c442018-04-21 13:51:42 +00002514 }else if( strcmp(x,"extra_context")==0 ){
2515 psp->declargslot = &(psp->gp->ctx);
2516 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002517 }else if( strcmp(x,"token_type")==0 ){
2518 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002519 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002520 }else if( strcmp(x,"default_type")==0 ){
2521 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002522 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002523 }else if( strcmp(x,"stack_size")==0 ){
2524 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002525 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002526 }else if( strcmp(x,"start_symbol")==0 ){
2527 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002528 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002529 }else if( strcmp(x,"left")==0 ){
2530 psp->preccounter++;
2531 psp->declassoc = LEFT;
2532 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2533 }else if( strcmp(x,"right")==0 ){
2534 psp->preccounter++;
2535 psp->declassoc = RIGHT;
2536 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2537 }else if( strcmp(x,"nonassoc")==0 ){
2538 psp->preccounter++;
2539 psp->declassoc = NONE;
2540 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002541 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002542 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002543 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002544 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002545 }else if( strcmp(x,"fallback")==0 ){
2546 psp->fallback = 0;
2547 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002548 }else if( strcmp(x,"token")==0 ){
2549 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002550 }else if( strcmp(x,"wildcard")==0 ){
2551 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002552 }else if( strcmp(x,"token_class")==0 ){
2553 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002554 }else{
2555 ErrorMsg(psp->filename,psp->tokenlineno,
2556 "Unknown declaration keyword: \"%%%s\".",x);
2557 psp->errorcnt++;
2558 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002559 }
drh75897232000-05-29 14:26:00 +00002560 }else{
2561 ErrorMsg(psp->filename,psp->tokenlineno,
2562 "Illegal declaration keyword: \"%s\".",x);
2563 psp->errorcnt++;
2564 psp->state = RESYNC_AFTER_DECL_ERROR;
2565 }
2566 break;
2567 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002568 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002569 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002570 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002571 psp->errorcnt++;
2572 psp->state = RESYNC_AFTER_DECL_ERROR;
2573 }else{
icculusd286fa62010-03-03 17:06:32 +00002574 struct symbol *sp = Symbol_new(x);
2575 psp->declargslot = &sp->destructor;
2576 psp->decllinenoslot = &sp->destLineno;
2577 psp->insertLineMacro = 1;
2578 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002579 }
2580 break;
2581 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002582 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002583 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002584 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002585 psp->errorcnt++;
2586 psp->state = RESYNC_AFTER_DECL_ERROR;
2587 }else{
icculus866bf1e2010-02-17 20:31:32 +00002588 struct symbol *sp = Symbol_find(x);
2589 if((sp) && (sp->datatype)){
2590 ErrorMsg(psp->filename,psp->tokenlineno,
2591 "Symbol %%type \"%s\" already defined", x);
2592 psp->errorcnt++;
2593 psp->state = RESYNC_AFTER_DECL_ERROR;
2594 }else{
2595 if (!sp){
2596 sp = Symbol_new(x);
2597 }
2598 psp->declargslot = &sp->datatype;
2599 psp->insertLineMacro = 0;
2600 psp->state = WAITING_FOR_DECL_ARG;
2601 }
drh75897232000-05-29 14:26:00 +00002602 }
2603 break;
2604 case WAITING_FOR_PRECEDENCE_SYMBOL:
2605 if( x[0]=='.' ){
2606 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002607 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002608 struct symbol *sp;
2609 sp = Symbol_new(x);
2610 if( sp->prec>=0 ){
2611 ErrorMsg(psp->filename,psp->tokenlineno,
2612 "Symbol \"%s\" has already be given a precedence.",x);
2613 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002614 }else{
drh75897232000-05-29 14:26:00 +00002615 sp->prec = psp->preccounter;
2616 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002617 }
drh75897232000-05-29 14:26:00 +00002618 }else{
2619 ErrorMsg(psp->filename,psp->tokenlineno,
2620 "Can't assign a precedence to \"%s\".",x);
2621 psp->errorcnt++;
2622 }
2623 break;
2624 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002625 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002626 const char *zOld, *zNew;
2627 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002628 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002629 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002630 char zLine[50];
2631 zNew = x;
2632 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002633 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002634 if( *psp->declargslot ){
2635 zOld = *psp->declargslot;
2636 }else{
2637 zOld = "";
2638 }
drh87cf1372008-08-13 20:09:06 +00002639 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002640 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002641 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002642 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2643 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002644 for(z=psp->filename, nBack=0; *z; z++){
2645 if( *z=='\\' ) nBack++;
2646 }
drh898799f2014-01-10 23:21:00 +00002647 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002648 nLine = lemonStrlen(zLine);
2649 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002650 }
icculus9e44cf12010-02-14 17:14:22 +00002651 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2652 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002653 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002654 if( nOld && zBuf[-1]!='\n' ){
2655 *(zBuf++) = '\n';
2656 }
2657 memcpy(zBuf, zLine, nLine);
2658 zBuf += nLine;
2659 *(zBuf++) = '"';
2660 for(z=psp->filename; *z; z++){
2661 if( *z=='\\' ){
2662 *(zBuf++) = '\\';
2663 }
2664 *(zBuf++) = *z;
2665 }
2666 *(zBuf++) = '"';
2667 *(zBuf++) = '\n';
2668 }
drh4dc8ef52008-07-01 17:13:57 +00002669 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2670 psp->decllinenoslot[0] = psp->tokenlineno;
2671 }
drha5808f32008-04-27 22:19:44 +00002672 memcpy(zBuf, zNew, nNew);
2673 zBuf += nNew;
2674 *zBuf = 0;
2675 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002676 }else{
2677 ErrorMsg(psp->filename,psp->tokenlineno,
2678 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2679 psp->errorcnt++;
2680 psp->state = RESYNC_AFTER_DECL_ERROR;
2681 }
2682 break;
drh0bd1f4e2002-06-06 18:54:39 +00002683 case WAITING_FOR_FALLBACK_ID:
2684 if( x[0]=='.' ){
2685 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002686 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002687 ErrorMsg(psp->filename, psp->tokenlineno,
2688 "%%fallback argument \"%s\" should be a token", x);
2689 psp->errorcnt++;
2690 }else{
2691 struct symbol *sp = Symbol_new(x);
2692 if( psp->fallback==0 ){
2693 psp->fallback = sp;
2694 }else if( sp->fallback ){
2695 ErrorMsg(psp->filename, psp->tokenlineno,
2696 "More than one fallback assigned to token %s", x);
2697 psp->errorcnt++;
2698 }else{
2699 sp->fallback = psp->fallback;
2700 psp->gp->has_fallback = 1;
2701 }
2702 }
2703 break;
drh59c435a2017-08-02 03:21:11 +00002704 case WAITING_FOR_TOKEN_NAME:
2705 /* Tokens do not have to be declared before use. But they can be
2706 ** in order to control their assigned integer number. The number for
2707 ** each token is assigned when it is first seen. So by including
2708 **
2709 ** %token ONE TWO THREE
2710 **
2711 ** early in the grammar file, that assigns small consecutive values
2712 ** to each of the tokens ONE TWO and THREE.
2713 */
2714 if( x[0]=='.' ){
2715 psp->state = WAITING_FOR_DECL_OR_RULE;
2716 }else if( !ISUPPER(x[0]) ){
2717 ErrorMsg(psp->filename, psp->tokenlineno,
2718 "%%token argument \"%s\" should be a token", x);
2719 psp->errorcnt++;
2720 }else{
2721 (void)Symbol_new(x);
2722 }
2723 break;
drhe09daa92006-06-10 13:29:31 +00002724 case WAITING_FOR_WILDCARD_ID:
2725 if( x[0]=='.' ){
2726 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002727 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002728 ErrorMsg(psp->filename, psp->tokenlineno,
2729 "%%wildcard argument \"%s\" should be a token", x);
2730 psp->errorcnt++;
2731 }else{
2732 struct symbol *sp = Symbol_new(x);
2733 if( psp->gp->wildcard==0 ){
2734 psp->gp->wildcard = sp;
2735 }else{
2736 ErrorMsg(psp->filename, psp->tokenlineno,
2737 "Extra wildcard to token: %s", x);
2738 psp->errorcnt++;
2739 }
2740 }
2741 break;
drh61f92cd2014-01-11 03:06:18 +00002742 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002743 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002744 ErrorMsg(psp->filename, psp->tokenlineno,
mistachkind9bc6e82019-05-10 16:16:19 +00002745 "%%token_class must be followed by an identifier: %s", x);
drh61f92cd2014-01-11 03:06:18 +00002746 psp->errorcnt++;
2747 psp->state = RESYNC_AFTER_DECL_ERROR;
2748 }else if( Symbol_find(x) ){
2749 ErrorMsg(psp->filename, psp->tokenlineno,
2750 "Symbol \"%s\" already used", x);
2751 psp->errorcnt++;
2752 psp->state = RESYNC_AFTER_DECL_ERROR;
2753 }else{
2754 psp->tkclass = Symbol_new(x);
2755 psp->tkclass->type = MULTITERMINAL;
2756 psp->state = WAITING_FOR_CLASS_TOKEN;
2757 }
2758 break;
2759 case WAITING_FOR_CLASS_TOKEN:
2760 if( x[0]=='.' ){
2761 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002762 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002763 struct symbol *msp = psp->tkclass;
2764 msp->nsubsym++;
2765 msp->subsym = (struct symbol **) realloc(msp->subsym,
2766 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002767 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002768 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2769 }else{
2770 ErrorMsg(psp->filename, psp->tokenlineno,
2771 "%%token_class argument \"%s\" should be a token", x);
2772 psp->errorcnt++;
2773 psp->state = RESYNC_AFTER_DECL_ERROR;
2774 }
2775 break;
drh75897232000-05-29 14:26:00 +00002776 case RESYNC_AFTER_RULE_ERROR:
2777/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2778** break; */
2779 case RESYNC_AFTER_DECL_ERROR:
2780 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2781 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2782 break;
2783 }
2784}
2785
drh0a34cf52020-07-03 15:41:08 +00002786/* The text in the input is part of the argument to an %ifdef or %ifndef.
2787** Evaluate the text as a boolean expression. Return true or false.
2788*/
2789static int eval_preprocessor_boolean(char *z, int lineno){
2790 int neg = 0;
2791 int res = 0;
2792 int okTerm = 1;
2793 int i;
2794 for(i=0; z[i]!=0; i++){
2795 if( ISSPACE(z[i]) ) continue;
2796 if( z[i]=='!' ){
2797 if( !okTerm ) goto pp_syntax_error;
2798 neg = !neg;
2799 continue;
2800 }
2801 if( z[i]=='|' && z[i+1]=='|' ){
2802 if( okTerm ) goto pp_syntax_error;
2803 if( res ) return 1;
2804 i++;
2805 okTerm = 1;
2806 continue;
2807 }
2808 if( z[i]=='&' && z[i+1]=='&' ){
2809 if( okTerm ) goto pp_syntax_error;
2810 if( !res ) return 0;
2811 i++;
2812 okTerm = 1;
2813 continue;
2814 }
2815 if( z[i]=='(' ){
2816 int k;
2817 int n = 1;
2818 if( !okTerm ) goto pp_syntax_error;
2819 for(k=i+1; z[k]; k++){
2820 if( z[k]==')' ){
2821 n--;
2822 if( n==0 ){
2823 z[k] = 0;
2824 res = eval_preprocessor_boolean(&z[i+1], -1);
2825 z[k] = ')';
2826 if( res<0 ){
2827 i = i-res;
2828 goto pp_syntax_error;
2829 }
2830 i = k;
2831 break;
2832 }
2833 }else if( z[k]=='(' ){
2834 n++;
2835 }else if( z[k]==0 ){
2836 i = k;
2837 goto pp_syntax_error;
2838 }
2839 }
2840 if( neg ){
2841 res = !res;
2842 neg = 0;
2843 }
2844 okTerm = 0;
2845 continue;
2846 }
2847 if( ISALPHA(z[i]) ){
2848 int j, k, n;
2849 if( !okTerm ) goto pp_syntax_error;
2850 for(k=i+1; ISALNUM(z[k]) || z[k]=='_'; k++){}
2851 n = k - i;
2852 res = 0;
2853 for(j=0; j<nDefine; j++){
2854 if( strncmp(azDefine[j],&z[i],n)==0 && azDefine[j][n]==0 ){
2855 res = 1;
2856 break;
2857 }
2858 }
2859 i = k-1;
2860 if( neg ){
2861 res = !res;
2862 neg = 0;
2863 }
2864 okTerm = 0;
2865 continue;
2866 }
2867 goto pp_syntax_error;
2868 }
2869 return res;
2870
2871pp_syntax_error:
2872 if( lineno>0 ){
2873 fprintf(stderr, "%%if syntax error on line %d.\n", lineno);
2874 fprintf(stderr, " %.*s <-- syntax error here\n", i+1, z);
2875 exit(1);
2876 }else{
2877 return -(i+1);
2878 }
2879}
2880
drh34ff57b2008-07-14 12:27:51 +00002881/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002882** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2883** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2884** comments them out. Text in between is also commented out as appropriate.
2885*/
danielk1977940fac92005-01-23 22:41:37 +00002886static void preprocess_input(char *z){
drh0a34cf52020-07-03 15:41:08 +00002887 int i, j, k;
drh6d08b4d2004-07-20 12:45:22 +00002888 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002889 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002890 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002891 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002892 for(i=0; z[i]; i++){
2893 if( z[i]=='\n' ) lineno++;
2894 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002895 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002896 if( exclude ){
2897 exclude--;
2898 if( exclude==0 ){
2899 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2900 }
2901 }
2902 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drh0a34cf52020-07-03 15:41:08 +00002903 }else if( strncmp(&z[i],"%else",5)==0 && ISSPACE(z[i+5]) ){
2904 if( exclude==1){
2905 exclude = 0;
2906 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2907 }else if( exclude==0 ){
2908 exclude = 1;
2909 start = i;
2910 start_lineno = lineno;
2911 }
2912 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2913 }else if( strncmp(&z[i],"%ifdef ",7)==0
2914 || strncmp(&z[i],"%if ",4)==0
2915 || strncmp(&z[i],"%ifndef ",8)==0 ){
drh6d08b4d2004-07-20 12:45:22 +00002916 if( exclude ){
2917 exclude++;
2918 }else{
drh0a34cf52020-07-03 15:41:08 +00002919 int isNot;
2920 int iBool;
2921 for(j=i; z[j] && !ISSPACE(z[j]); j++){}
2922 iBool = j;
2923 isNot = (j==i+7);
2924 while( z[j] && z[j]!='\n' ){ j++; }
2925 k = z[j];
2926 z[j] = 0;
2927 exclude = eval_preprocessor_boolean(&z[iBool], lineno);
2928 z[j] = k;
2929 if( !isNot ) exclude = !exclude;
drh6d08b4d2004-07-20 12:45:22 +00002930 if( exclude ){
2931 start = i;
2932 start_lineno = lineno;
2933 }
2934 }
2935 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2936 }
2937 }
2938 if( exclude ){
2939 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2940 exit(1);
2941 }
2942}
2943
drh75897232000-05-29 14:26:00 +00002944/* In spite of its name, this function is really a scanner. It read
2945** in the entire input file (all at once) then tokenizes it. Each
2946** token is passed to the function "parseonetoken" which builds all
2947** the appropriate data structures in the global state vector "gp".
2948*/
icculus9e44cf12010-02-14 17:14:22 +00002949void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002950{
2951 struct pstate ps;
2952 FILE *fp;
2953 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002954 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002955 int lineno;
2956 int c;
2957 char *cp, *nextcp;
2958 int startline = 0;
2959
rse38514a92007-09-20 11:34:17 +00002960 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002961 ps.gp = gp;
2962 ps.filename = gp->filename;
2963 ps.errorcnt = 0;
2964 ps.state = INITIALIZE;
2965
2966 /* Begin by reading the input file */
2967 fp = fopen(ps.filename,"rb");
2968 if( fp==0 ){
2969 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2970 gp->errorcnt++;
2971 return;
2972 }
2973 fseek(fp,0,2);
2974 filesize = ftell(fp);
2975 rewind(fp);
2976 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002977 if( filesize>100000000 || filebuf==0 ){
2978 ErrorMsg(ps.filename,0,"Input file too large.");
mistachkinc93c6142018-09-08 16:55:18 +00002979 free(filebuf);
drh75897232000-05-29 14:26:00 +00002980 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002981 fclose(fp);
drh75897232000-05-29 14:26:00 +00002982 return;
2983 }
2984 if( fread(filebuf,1,filesize,fp)!=filesize ){
2985 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2986 filesize);
2987 free(filebuf);
2988 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002989 fclose(fp);
drh75897232000-05-29 14:26:00 +00002990 return;
2991 }
2992 fclose(fp);
2993 filebuf[filesize] = 0;
2994
drh6d08b4d2004-07-20 12:45:22 +00002995 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2996 preprocess_input(filebuf);
drh0a34cf52020-07-03 15:41:08 +00002997 if( gp->printPreprocessed ){
2998 printf("%s\n", filebuf);
2999 return;
3000 }
drh6d08b4d2004-07-20 12:45:22 +00003001
drh75897232000-05-29 14:26:00 +00003002 /* Now scan the text of the input file */
3003 lineno = 1;
3004 for(cp=filebuf; (c= *cp)!=0; ){
3005 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00003006 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00003007 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
3008 cp+=2;
3009 while( (c= *cp)!=0 && c!='\n' ) cp++;
3010 continue;
3011 }
3012 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
3013 cp+=2;
3014 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
3015 if( c=='\n' ) lineno++;
3016 cp++;
3017 }
3018 if( c ) cp++;
3019 continue;
3020 }
3021 ps.tokenstart = cp; /* Mark the beginning of the token */
3022 ps.tokenlineno = lineno; /* Linenumber on which token begins */
3023 if( c=='\"' ){ /* String literals */
3024 cp++;
3025 while( (c= *cp)!=0 && c!='\"' ){
3026 if( c=='\n' ) lineno++;
3027 cp++;
3028 }
3029 if( c==0 ){
3030 ErrorMsg(ps.filename,startline,
drh3ecc05b2019-12-12 00:20:40 +00003031 "String starting on this line is not terminated before "
3032 "the end of the file.");
drh75897232000-05-29 14:26:00 +00003033 ps.errorcnt++;
3034 nextcp = cp;
3035 }else{
3036 nextcp = cp+1;
3037 }
3038 }else if( c=='{' ){ /* A block of C code */
3039 int level;
3040 cp++;
3041 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
3042 if( c=='\n' ) lineno++;
3043 else if( c=='{' ) level++;
3044 else if( c=='}' ) level--;
3045 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
3046 int prevc;
3047 cp = &cp[2];
3048 prevc = 0;
3049 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
3050 if( c=='\n' ) lineno++;
3051 prevc = c;
3052 cp++;
drhf2f105d2012-08-20 15:53:54 +00003053 }
3054 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00003055 cp = &cp[2];
3056 while( (c= *cp)!=0 && c!='\n' ) cp++;
3057 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00003058 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00003059 int startchar, prevc;
3060 startchar = c;
3061 prevc = 0;
3062 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
3063 if( c=='\n' ) lineno++;
3064 if( prevc=='\\' ) prevc = 0;
3065 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00003066 }
3067 }
drh75897232000-05-29 14:26:00 +00003068 }
3069 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00003070 ErrorMsg(ps.filename,ps.tokenlineno,
drh3ecc05b2019-12-12 00:20:40 +00003071 "C code starting on this line is not terminated before "
3072 "the end of the file.");
drh75897232000-05-29 14:26:00 +00003073 ps.errorcnt++;
3074 nextcp = cp;
3075 }else{
3076 nextcp = cp+1;
3077 }
drhc56fac72015-10-29 13:48:15 +00003078 }else if( ISALNUM(c) ){ /* Identifiers */
3079 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00003080 nextcp = cp;
3081 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
3082 cp += 3;
3083 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00003084 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00003085 cp += 2;
drhc56fac72015-10-29 13:48:15 +00003086 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00003087 nextcp = cp;
drh75897232000-05-29 14:26:00 +00003088 }else{ /* All other (one character) operators */
3089 cp++;
3090 nextcp = cp;
3091 }
3092 c = *cp;
3093 *cp = 0; /* Null terminate the token */
3094 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00003095 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00003096 cp = nextcp;
3097 }
3098 free(filebuf); /* Release the buffer after parsing */
3099 gp->rule = ps.firstrule;
3100 gp->errorcnt = ps.errorcnt;
3101}
3102/*************************** From the file "plink.c" *********************/
3103/*
3104** Routines processing configuration follow-set propagation links
3105** in the LEMON parser generator.
3106*/
3107static struct plink *plink_freelist = 0;
3108
3109/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00003110struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00003111 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00003112
3113 if( plink_freelist==0 ){
3114 int i;
3115 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00003116 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00003117 if( plink_freelist==0 ){
3118 fprintf(stderr,
3119 "Unable to allocate memory for a new follow-set propagation link.\n");
3120 exit(1);
3121 }
3122 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
3123 plink_freelist[amt-1].next = 0;
3124 }
icculus9e44cf12010-02-14 17:14:22 +00003125 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00003126 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00003127 return newlink;
drh75897232000-05-29 14:26:00 +00003128}
3129
3130/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00003131void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00003132{
icculus9e44cf12010-02-14 17:14:22 +00003133 struct plink *newlink;
3134 newlink = Plink_new();
3135 newlink->next = *plpp;
3136 *plpp = newlink;
3137 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00003138}
3139
3140/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00003141void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00003142{
3143 struct plink *nextpl;
3144 while( from ){
3145 nextpl = from->next;
3146 from->next = *to;
3147 *to = from;
3148 from = nextpl;
3149 }
3150}
3151
3152/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00003153void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00003154{
3155 struct plink *nextpl;
3156
3157 while( plp ){
3158 nextpl = plp->next;
3159 plp->next = plink_freelist;
3160 plink_freelist = plp;
3161 plp = nextpl;
3162 }
3163}
3164/*********************** From the file "report.c" **************************/
3165/*
3166** Procedures for generating reports and tables in the LEMON parser generator.
3167*/
3168
3169/* Generate a filename with the given suffix. Space to hold the
3170** name comes from malloc() and must be freed by the calling
3171** function.
3172*/
icculus9e44cf12010-02-14 17:14:22 +00003173PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00003174{
3175 char *name;
3176 char *cp;
drh9f88e6d2018-04-20 20:47:49 +00003177 char *filename = lemp->filename;
3178 int sz;
drh75897232000-05-29 14:26:00 +00003179
drh9f88e6d2018-04-20 20:47:49 +00003180 if( outputDir ){
3181 cp = strrchr(filename, '/');
3182 if( cp ) filename = cp + 1;
3183 }
3184 sz = lemonStrlen(filename);
3185 sz += lemonStrlen(suffix);
3186 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3187 sz += 5;
3188 name = (char*)malloc( sz );
drh75897232000-05-29 14:26:00 +00003189 if( name==0 ){
3190 fprintf(stderr,"Can't allocate space for a filename.\n");
3191 exit(1);
3192 }
drh9f88e6d2018-04-20 20:47:49 +00003193 name[0] = 0;
3194 if( outputDir ){
3195 lemon_strcpy(name, outputDir);
3196 lemon_strcat(name, "/");
3197 }
3198 lemon_strcat(name,filename);
drh75897232000-05-29 14:26:00 +00003199 cp = strrchr(name,'.');
3200 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003201 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003202 return name;
3203}
3204
3205/* Open a file with a name based on the name of the input file,
3206** but with a different (specified) suffix, and return a pointer
3207** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003208PRIVATE FILE *file_open(
3209 struct lemon *lemp,
3210 const char *suffix,
3211 const char *mode
3212){
drh75897232000-05-29 14:26:00 +00003213 FILE *fp;
3214
3215 if( lemp->outname ) free(lemp->outname);
3216 lemp->outname = file_makename(lemp, suffix);
3217 fp = fopen(lemp->outname,mode);
3218 if( fp==0 && *mode=='w' ){
3219 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3220 lemp->errorcnt++;
3221 return 0;
3222 }
3223 return fp;
3224}
3225
drh5c8241b2017-12-24 23:38:10 +00003226/* Print the text of a rule
3227*/
3228void rule_print(FILE *out, struct rule *rp){
3229 int i, j;
3230 fprintf(out, "%s",rp->lhs->name);
3231 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3232 fprintf(out," ::=");
3233 for(i=0; i<rp->nrhs; i++){
3234 struct symbol *sp = rp->rhs[i];
3235 if( sp->type==MULTITERMINAL ){
3236 fprintf(out," %s", sp->subsym[0]->name);
3237 for(j=1; j<sp->nsubsym; j++){
3238 fprintf(out,"|%s", sp->subsym[j]->name);
3239 }
3240 }else{
3241 fprintf(out," %s", sp->name);
3242 }
3243 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3244 }
3245}
3246
drh06f60d82017-04-14 19:46:12 +00003247/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003248** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003249void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003250{
3251 struct rule *rp;
3252 struct symbol *sp;
3253 int i, j, maxlen, len, ncolumns, skip;
3254 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3255 maxlen = 10;
3256 for(i=0; i<lemp->nsymbol; i++){
3257 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003258 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003259 if( len>maxlen ) maxlen = len;
3260 }
3261 ncolumns = 76/(maxlen+5);
3262 if( ncolumns<1 ) ncolumns = 1;
3263 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3264 for(i=0; i<skip; i++){
3265 printf("//");
3266 for(j=i; j<lemp->nsymbol; j+=skip){
3267 sp = lemp->symbols[j];
3268 assert( sp->index==j );
3269 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3270 }
3271 printf("\n");
3272 }
3273 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003274 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003275 printf(".");
3276 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003277 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003278 printf("\n");
3279 }
3280}
3281
drh7e698e92015-09-07 14:22:24 +00003282/* Print a single rule.
3283*/
3284void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003285 struct symbol *sp;
3286 int i, j;
drh75897232000-05-29 14:26:00 +00003287 fprintf(fp,"%s ::=",rp->lhs->name);
3288 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003289 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003290 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003291 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003292 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003293 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003294 for(j=1; j<sp->nsubsym; j++){
3295 fprintf(fp,"|%s",sp->subsym[j]->name);
3296 }
drh61f92cd2014-01-11 03:06:18 +00003297 }else{
3298 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003299 }
drh75897232000-05-29 14:26:00 +00003300 }
3301}
3302
drh7e698e92015-09-07 14:22:24 +00003303/* Print the rule for a configuration.
3304*/
3305void ConfigPrint(FILE *fp, struct config *cfp){
3306 RulePrint(fp, cfp->rp, cfp->dot);
3307}
3308
drh75897232000-05-29 14:26:00 +00003309/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003310#if 0
drh75897232000-05-29 14:26:00 +00003311/* Print a set */
3312PRIVATE void SetPrint(out,set,lemp)
3313FILE *out;
3314char *set;
3315struct lemon *lemp;
3316{
3317 int i;
3318 char *spacer;
3319 spacer = "";
3320 fprintf(out,"%12s[","");
3321 for(i=0; i<lemp->nterminal; i++){
3322 if( SetFind(set,i) ){
3323 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3324 spacer = " ";
3325 }
3326 }
3327 fprintf(out,"]\n");
3328}
3329
3330/* Print a plink chain */
3331PRIVATE void PlinkPrint(out,plp,tag)
3332FILE *out;
3333struct plink *plp;
3334char *tag;
3335{
3336 while( plp ){
drhada354d2005-11-05 15:03:59 +00003337 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003338 ConfigPrint(out,plp->cfp);
3339 fprintf(out,"\n");
3340 plp = plp->next;
3341 }
3342}
3343#endif
3344
3345/* Print an action to the given file descriptor. Return FALSE if
3346** nothing was actually printed.
3347*/
drh7e698e92015-09-07 14:22:24 +00003348int PrintAction(
3349 struct action *ap, /* The action to print */
3350 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003351 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003352){
drh75897232000-05-29 14:26:00 +00003353 int result = 1;
3354 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003355 case SHIFT: {
3356 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003357 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003358 break;
drh7e698e92015-09-07 14:22:24 +00003359 }
3360 case REDUCE: {
3361 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003362 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003363 RulePrint(fp, rp, -1);
3364 break;
3365 }
3366 case SHIFTREDUCE: {
3367 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003368 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003369 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003370 break;
drh7e698e92015-09-07 14:22:24 +00003371 }
drh75897232000-05-29 14:26:00 +00003372 case ACCEPT:
3373 fprintf(fp,"%*s accept",indent,ap->sp->name);
3374 break;
3375 case ERROR:
3376 fprintf(fp,"%*s error",indent,ap->sp->name);
3377 break;
drh9892c5d2007-12-21 00:02:11 +00003378 case SRCONFLICT:
3379 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003380 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003381 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003382 break;
drh9892c5d2007-12-21 00:02:11 +00003383 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003384 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003385 indent,ap->sp->name,ap->x.stp->statenum);
3386 break;
drh75897232000-05-29 14:26:00 +00003387 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003388 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003389 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003390 indent,ap->sp->name,ap->x.stp->statenum);
3391 }else{
3392 result = 0;
3393 }
3394 break;
drh75897232000-05-29 14:26:00 +00003395 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003396 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003397 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003398 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003399 }else{
3400 result = 0;
3401 }
3402 break;
drh75897232000-05-29 14:26:00 +00003403 case NOT_USED:
3404 result = 0;
3405 break;
3406 }
drhc173ad82016-05-23 16:15:02 +00003407 if( result && ap->spOpt ){
3408 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3409 }
drh75897232000-05-29 14:26:00 +00003410 return result;
3411}
3412
drh3bd48ab2015-09-07 18:23:37 +00003413/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003414void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003415{
drh539e7412018-04-21 20:24:19 +00003416 int i, n;
drh75897232000-05-29 14:26:00 +00003417 struct state *stp;
3418 struct config *cfp;
3419 struct action *ap;
drh12f68392018-04-06 19:12:55 +00003420 struct rule *rp;
drh75897232000-05-29 14:26:00 +00003421 FILE *fp;
3422
drh2aa6ca42004-09-10 00:14:04 +00003423 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003424 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003425 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003426 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003427 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003428 if( lemp->basisflag ) cfp=stp->bp;
3429 else cfp=stp->cfp;
3430 while( cfp ){
3431 char buf[20];
3432 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003433 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003434 fprintf(fp," %5s ",buf);
3435 }else{
3436 fprintf(fp," ");
3437 }
3438 ConfigPrint(fp,cfp);
3439 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003440#if 0
drh75897232000-05-29 14:26:00 +00003441 SetPrint(fp,cfp->fws,lemp);
3442 PlinkPrint(fp,cfp->fplp,"To ");
3443 PlinkPrint(fp,cfp->bplp,"From");
3444#endif
3445 if( lemp->basisflag ) cfp=cfp->bp;
3446 else cfp=cfp->next;
3447 }
3448 fprintf(fp,"\n");
3449 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003450 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003451 }
3452 fprintf(fp,"\n");
3453 }
drhe9278182007-07-18 18:16:29 +00003454 fprintf(fp, "----------------------------------------------------\n");
3455 fprintf(fp, "Symbols:\n");
drh539e7412018-04-21 20:24:19 +00003456 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
drhe9278182007-07-18 18:16:29 +00003457 for(i=0; i<lemp->nsymbol; i++){
3458 int j;
3459 struct symbol *sp;
3460
3461 sp = lemp->symbols[i];
3462 fprintf(fp, " %3d: %s", i, sp->name);
3463 if( sp->type==NONTERMINAL ){
3464 fprintf(fp, ":");
3465 if( sp->lambda ){
3466 fprintf(fp, " <lambda>");
3467 }
3468 for(j=0; j<lemp->nterminal; j++){
3469 if( sp->firstset && SetFind(sp->firstset, j) ){
3470 fprintf(fp, " %s", lemp->symbols[j]->name);
3471 }
3472 }
3473 }
drh12f68392018-04-06 19:12:55 +00003474 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
drhe9278182007-07-18 18:16:29 +00003475 fprintf(fp, "\n");
3476 }
drh12f68392018-04-06 19:12:55 +00003477 fprintf(fp, "----------------------------------------------------\n");
drh539e7412018-04-21 20:24:19 +00003478 fprintf(fp, "Syntax-only Symbols:\n");
3479 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3480 for(i=n=0; i<lemp->nsymbol; i++){
3481 int w;
3482 struct symbol *sp = lemp->symbols[i];
3483 if( sp->bContent ) continue;
3484 w = (int)strlen(sp->name);
3485 if( n>0 && n+w>75 ){
3486 fprintf(fp,"\n");
3487 n = 0;
3488 }
3489 if( n>0 ){
3490 fprintf(fp, " ");
3491 n++;
3492 }
3493 fprintf(fp, "%s", sp->name);
3494 n += w;
3495 }
3496 if( n>0 ) fprintf(fp, "\n");
3497 fprintf(fp, "----------------------------------------------------\n");
drh12f68392018-04-06 19:12:55 +00003498 fprintf(fp, "Rules:\n");
3499 for(rp=lemp->rule; rp; rp=rp->next){
3500 fprintf(fp, "%4d: ", rp->iRule);
3501 rule_print(fp, rp);
3502 fprintf(fp,".");
3503 if( rp->precsym ){
3504 fprintf(fp," [%s precedence=%d]",
3505 rp->precsym->name, rp->precsym->prec);
3506 }
3507 fprintf(fp,"\n");
3508 }
drh75897232000-05-29 14:26:00 +00003509 fclose(fp);
3510 return;
3511}
3512
3513/* Search for the file "name" which is in the same directory as
3514** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003515PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003516{
icculus9e44cf12010-02-14 17:14:22 +00003517 const char *pathlist;
3518 char *pathbufptr;
3519 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003520 char *path,*cp;
3521 char c;
drh75897232000-05-29 14:26:00 +00003522
3523#ifdef __WIN32__
3524 cp = strrchr(argv0,'\\');
3525#else
3526 cp = strrchr(argv0,'/');
3527#endif
3528 if( cp ){
3529 c = *cp;
3530 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003531 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003532 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003533 *cp = c;
3534 }else{
drh75897232000-05-29 14:26:00 +00003535 pathlist = getenv("PATH");
3536 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003537 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003538 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003539 if( (pathbuf != 0) && (path!=0) ){
3540 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003541 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003542 while( *pathbuf ){
3543 cp = strchr(pathbuf,':');
3544 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003545 c = *cp;
3546 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003547 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003548 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003549 if( c==0 ) pathbuf[0] = 0;
3550 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003551 if( access(path,modemask)==0 ) break;
3552 }
icculus9e44cf12010-02-14 17:14:22 +00003553 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003554 }
3555 }
3556 return path;
3557}
3558
3559/* Given an action, compute the integer value for that action
3560** which is to be put in the action table of the generated machine.
3561** Return negative if no action should be generated.
3562*/
icculus9e44cf12010-02-14 17:14:22 +00003563PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003564{
3565 int act;
3566 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003567 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003568 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003569 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3570 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3571 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003572 if( ap->sp->index>=lemp->nterminal ){
3573 act = lemp->minReduce + ap->x.rp->iRule;
3574 }else{
3575 act = lemp->minShiftReduce + ap->x.rp->iRule;
3576 }
drhbd8fcc12017-06-28 11:56:18 +00003577 break;
3578 }
drh5c8241b2017-12-24 23:38:10 +00003579 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3580 case ERROR: act = lemp->errAction; break;
3581 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003582 default: act = -1; break;
3583 }
3584 return act;
3585}
3586
3587#define LINESIZE 1000
3588/* The next cluster of routines are for reading the template file
3589** and writing the results to the generated parser */
3590/* The first function transfers data from "in" to "out" until
3591** a line is seen which begins with "%%". The line number is
3592** tracked.
3593**
3594** if name!=0, then any word that begin with "Parse" is changed to
3595** begin with *name instead.
3596*/
icculus9e44cf12010-02-14 17:14:22 +00003597PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003598{
3599 int i, iStart;
3600 char line[LINESIZE];
3601 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3602 (*lineno)++;
3603 iStart = 0;
3604 if( name ){
3605 for(i=0; line[i]; i++){
3606 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003607 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003608 ){
3609 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3610 fprintf(out,"%s",name);
3611 i += 4;
3612 iStart = i+1;
3613 }
3614 }
3615 }
3616 fprintf(out,"%s",&line[iStart]);
3617 }
3618}
3619
3620/* The next function finds the template file and opens it, returning
3621** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003622PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003623{
3624 static char templatename[] = "lempar.c";
3625 char buf[1000];
3626 FILE *in;
3627 char *tpltname;
3628 char *cp;
3629
icculus3e143bd2010-02-14 00:48:49 +00003630 /* first, see if user specified a template filename on the command line. */
3631 if (user_templatename != 0) {
3632 if( access(user_templatename,004)==-1 ){
3633 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3634 user_templatename);
3635 lemp->errorcnt++;
3636 return 0;
3637 }
3638 in = fopen(user_templatename,"rb");
3639 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003640 fprintf(stderr,"Can't open the template file \"%s\".\n",
3641 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003642 lemp->errorcnt++;
3643 return 0;
3644 }
3645 return in;
3646 }
3647
drh75897232000-05-29 14:26:00 +00003648 cp = strrchr(lemp->filename,'.');
3649 if( cp ){
drh898799f2014-01-10 23:21:00 +00003650 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003651 }else{
drh898799f2014-01-10 23:21:00 +00003652 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003653 }
3654 if( access(buf,004)==0 ){
3655 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003656 }else if( access(templatename,004)==0 ){
3657 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003658 }else{
3659 tpltname = pathsearch(lemp->argv0,templatename,0);
3660 }
3661 if( tpltname==0 ){
3662 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3663 templatename);
3664 lemp->errorcnt++;
3665 return 0;
3666 }
drh2aa6ca42004-09-10 00:14:04 +00003667 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003668 if( in==0 ){
3669 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3670 lemp->errorcnt++;
3671 return 0;
3672 }
3673 return in;
3674}
3675
drhaf805ca2004-09-07 11:28:25 +00003676/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003677PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003678{
3679 fprintf(out,"#line %d \"",lineno);
3680 while( *filename ){
3681 if( *filename == '\\' ) putc('\\',out);
3682 putc(*filename,out);
3683 filename++;
3684 }
3685 fprintf(out,"\"\n");
3686}
3687
drh75897232000-05-29 14:26:00 +00003688/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003689PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003690{
3691 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003692 while( *str ){
drh75897232000-05-29 14:26:00 +00003693 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003694 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003695 str++;
3696 }
drh9db55df2004-09-09 14:01:21 +00003697 if( str[-1]!='\n' ){
3698 putc('\n',out);
3699 (*lineno)++;
3700 }
shane58543932008-12-10 20:10:04 +00003701 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003702 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003703 }
drh75897232000-05-29 14:26:00 +00003704 return;
3705}
3706
3707/*
3708** The following routine emits code for the destructor for the
3709** symbol sp
3710*/
icculus9e44cf12010-02-14 17:14:22 +00003711void emit_destructor_code(
3712 FILE *out,
3713 struct symbol *sp,
3714 struct lemon *lemp,
3715 int *lineno
3716){
drhcc83b6e2004-04-23 23:38:42 +00003717 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003718
drh75897232000-05-29 14:26:00 +00003719 if( sp->type==TERMINAL ){
3720 cp = lemp->tokendest;
3721 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003722 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003723 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003724 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003725 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003726 if( !lemp->nolinenosflag ){
3727 (*lineno)++;
3728 tplt_linedir(out,sp->destLineno,lemp->filename);
3729 }
drh960e8c62001-04-03 16:53:21 +00003730 }else if( lemp->vardest ){
3731 cp = lemp->vardest;
3732 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003733 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003734 }else{
3735 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003736 }
3737 for(; *cp; cp++){
3738 if( *cp=='$' && cp[1]=='$' ){
3739 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3740 cp++;
3741 continue;
3742 }
shane58543932008-12-10 20:10:04 +00003743 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003744 fputc(*cp,out);
3745 }
shane58543932008-12-10 20:10:04 +00003746 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003747 if (!lemp->nolinenosflag) {
3748 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003749 }
3750 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003751 return;
3752}
3753
3754/*
drh960e8c62001-04-03 16:53:21 +00003755** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003756*/
icculus9e44cf12010-02-14 17:14:22 +00003757int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003758{
3759 int ret;
3760 if( sp->type==TERMINAL ){
3761 ret = lemp->tokendest!=0;
3762 }else{
drh960e8c62001-04-03 16:53:21 +00003763 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003764 }
3765 return ret;
3766}
3767
drh0bb132b2004-07-20 14:06:51 +00003768/*
3769** Append text to a dynamically allocated string. If zText is 0 then
3770** reset the string to be empty again. Always return the complete text
3771** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003772**
3773** n bytes of zText are stored. If n==0 then all of zText up to the first
3774** \000 terminator is stored. zText can contain up to two instances of
3775** %d. The values of p1 and p2 are written into the first and second
3776** %d.
3777**
3778** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003779*/
icculus9e44cf12010-02-14 17:14:22 +00003780PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3781 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003782 static char *z = 0;
3783 static int alloced = 0;
3784 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003785 int c;
drh0bb132b2004-07-20 14:06:51 +00003786 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003787 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003788 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003789 used = 0;
3790 return z;
3791 }
drh7ac25c72004-08-19 15:12:26 +00003792 if( n<=0 ){
3793 if( n<0 ){
3794 used += n;
3795 assert( used>=0 );
3796 }
drh87cf1372008-08-13 20:09:06 +00003797 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003798 }
drhdf609712010-11-23 20:55:27 +00003799 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003800 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003801 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003802 }
icculus9e44cf12010-02-14 17:14:22 +00003803 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003804 while( n-- > 0 ){
3805 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003806 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003807 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003808 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003809 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003810 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003811 zText++;
3812 n--;
3813 }else{
mistachkin2318d332015-01-12 18:02:52 +00003814 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003815 }
3816 }
3817 z[used] = 0;
3818 return z;
3819}
3820
3821/*
drh711c9812016-05-23 14:24:31 +00003822** Write and transform the rp->code string so that symbols are expanded.
3823** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003824**
3825** Return 1 if the expanded code requires that "yylhsminor" local variable
3826** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003827*/
drhdabd04c2016-02-17 01:46:19 +00003828PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003829 char *cp, *xp;
3830 int i;
drhcf82f0d2016-02-17 04:33:10 +00003831 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003832 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003833 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3834 char lhsused = 0; /* True if the LHS element has been used */
3835 char lhsdirect; /* True if LHS writes directly into stack */
3836 char used[MAXRHS]; /* True for each RHS element which is used */
3837 char zLhs[50]; /* Convert the LHS symbol into this string */
3838 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003839
3840 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3841 lhsused = 0;
3842
drh19c9e562007-03-29 20:13:53 +00003843 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003844 static char newlinestr[2] = { '\n', '\0' };
3845 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003846 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003847 rp->noCode = 1;
3848 }else{
3849 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003850 }
3851
drh4dd0d3f2016-02-17 01:18:33 +00003852
drh2e55b042016-04-30 17:19:30 +00003853 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003854 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3855 lhsdirect = 1;
3856 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003857 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003858 ** we have to call the distructor on the RHS symbol first. */
3859 lhsdirect = 1;
3860 if( has_destructor(rp->rhs[0],lemp) ){
3861 append_str(0,0,0,0);
3862 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3863 rp->rhs[0]->index,1-rp->nrhs);
3864 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003865 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003866 }
drh2e55b042016-04-30 17:19:30 +00003867 }else if( rp->lhsalias==0 ){
3868 /* There is no LHS value symbol. */
3869 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003870 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003871 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003872 ** direct writing is allowed */
3873 lhsdirect = 1;
3874 lhsused = 1;
3875 used[0] = 1;
3876 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3877 ErrorMsg(lemp->filename,rp->ruleline,
3878 "%s(%s) and %s(%s) share the same label but have "
3879 "different datatypes.",
3880 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3881 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003882 }
drh4dd0d3f2016-02-17 01:18:33 +00003883 }else{
drhcf82f0d2016-02-17 04:33:10 +00003884 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3885 rp->lhsalias, rp->rhsalias[0]);
3886 zSkip = strstr(rp->code, zOvwrt);
3887 if( zSkip!=0 ){
3888 /* The code contains a special comment that indicates that it is safe
3889 ** for the LHS label to overwrite left-most RHS label. */
3890 lhsdirect = 1;
3891 }else{
3892 lhsdirect = 0;
3893 }
drh4dd0d3f2016-02-17 01:18:33 +00003894 }
3895 if( lhsdirect ){
3896 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3897 }else{
drhdabd04c2016-02-17 01:46:19 +00003898 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003899 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3900 }
3901
drh0bb132b2004-07-20 14:06:51 +00003902 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003903
3904 /* This const cast is wrong but harmless, if we're careful. */
3905 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003906 if( cp==zSkip ){
3907 append_str(zOvwrt,0,0,0);
3908 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003909 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003910 continue;
3911 }
drhc56fac72015-10-29 13:48:15 +00003912 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003913 char saved;
drhc56fac72015-10-29 13:48:15 +00003914 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003915 saved = *xp;
3916 *xp = 0;
3917 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003918 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003919 cp = xp;
3920 lhsused = 1;
3921 }else{
3922 for(i=0; i<rp->nrhs; i++){
3923 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003924 if( i==0 && dontUseRhs0 ){
3925 ErrorMsg(lemp->filename,rp->ruleline,
3926 "Label %s used after '%s'.",
3927 rp->rhsalias[0], zOvwrt);
3928 lemp->errorcnt++;
3929 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003930 /* If the argument is of the form @X then substituted
3931 ** the token number of X, not the value of X */
3932 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3933 }else{
drhfd405312005-11-06 04:06:59 +00003934 struct symbol *sp = rp->rhs[i];
3935 int dtnum;
3936 if( sp->type==MULTITERMINAL ){
3937 dtnum = sp->subsym[0]->dtnum;
3938 }else{
3939 dtnum = sp->dtnum;
3940 }
3941 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003942 }
drh0bb132b2004-07-20 14:06:51 +00003943 cp = xp;
3944 used[i] = 1;
3945 break;
3946 }
3947 }
3948 }
3949 *xp = saved;
3950 }
3951 append_str(cp, 1, 0, 0);
3952 } /* End loop */
3953
drh4dd0d3f2016-02-17 01:18:33 +00003954 /* Main code generation completed */
3955 cp = append_str(0,0,0,0);
3956 if( cp && cp[0] ) rp->code = Strsafe(cp);
3957 append_str(0,0,0,0);
3958
drh0bb132b2004-07-20 14:06:51 +00003959 /* Check to make sure the LHS has been used */
3960 if( rp->lhsalias && !lhsused ){
3961 ErrorMsg(lemp->filename,rp->ruleline,
3962 "Label \"%s\" for \"%s(%s)\" is never used.",
3963 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3964 lemp->errorcnt++;
3965 }
3966
drh4dd0d3f2016-02-17 01:18:33 +00003967 /* Generate destructor code for RHS minor values which are not referenced.
3968 ** Generate error messages for unused labels and duplicate labels.
3969 */
drh0bb132b2004-07-20 14:06:51 +00003970 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003971 if( rp->rhsalias[i] ){
3972 if( i>0 ){
3973 int j;
3974 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3975 ErrorMsg(lemp->filename,rp->ruleline,
3976 "%s(%s) has the same label as the LHS but is not the left-most "
3977 "symbol on the RHS.",
drhf135cb72019-04-30 14:26:31 +00003978 rp->rhs[i]->name, rp->rhsalias[i]);
drh4dd0d3f2016-02-17 01:18:33 +00003979 lemp->errorcnt++;
3980 }
3981 for(j=0; j<i; j++){
3982 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3983 ErrorMsg(lemp->filename,rp->ruleline,
3984 "Label %s used for multiple symbols on the RHS of a rule.",
3985 rp->rhsalias[i]);
3986 lemp->errorcnt++;
3987 break;
3988 }
3989 }
drh0bb132b2004-07-20 14:06:51 +00003990 }
drh4dd0d3f2016-02-17 01:18:33 +00003991 if( !used[i] ){
3992 ErrorMsg(lemp->filename,rp->ruleline,
3993 "Label %s for \"%s(%s)\" is never used.",
3994 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3995 lemp->errorcnt++;
3996 }
3997 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3998 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3999 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00004000 }
4001 }
drh4dd0d3f2016-02-17 01:18:33 +00004002
4003 /* If unable to write LHS values directly into the stack, write the
4004 ** saved LHS value now. */
4005 if( lhsdirect==0 ){
4006 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
4007 append_str(zLhs, 0, 0, 0);
4008 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00004009 }
drh4dd0d3f2016-02-17 01:18:33 +00004010
4011 /* Suffix code generation complete */
4012 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00004013 if( cp && cp[0] ){
4014 rp->codeSuffix = Strsafe(cp);
4015 rp->noCode = 0;
4016 }
drhdabd04c2016-02-17 01:46:19 +00004017
4018 return rc;
drh0bb132b2004-07-20 14:06:51 +00004019}
4020
drh06f60d82017-04-14 19:46:12 +00004021/*
drh75897232000-05-29 14:26:00 +00004022** Generate code which executes when the rule "rp" is reduced. Write
4023** the code to "out". Make sure lineno stays up-to-date.
4024*/
icculus9e44cf12010-02-14 17:14:22 +00004025PRIVATE void emit_code(
4026 FILE *out,
4027 struct rule *rp,
4028 struct lemon *lemp,
4029 int *lineno
4030){
4031 const char *cp;
drh75897232000-05-29 14:26:00 +00004032
drh4dd0d3f2016-02-17 01:18:33 +00004033 /* Setup code prior to the #line directive */
4034 if( rp->codePrefix && rp->codePrefix[0] ){
4035 fprintf(out, "{%s", rp->codePrefix);
4036 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4037 }
4038
drh75897232000-05-29 14:26:00 +00004039 /* Generate code to do the reduce action */
4040 if( rp->code ){
drh25473362015-09-04 18:03:45 +00004041 if( !lemp->nolinenosflag ){
4042 (*lineno)++;
4043 tplt_linedir(out,rp->line,lemp->filename);
4044 }
drhaf805ca2004-09-07 11:28:25 +00004045 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00004046 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00004047 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00004048 if( !lemp->nolinenosflag ){
4049 (*lineno)++;
4050 tplt_linedir(out,*lineno,lemp->outname);
4051 }
drh4dd0d3f2016-02-17 01:18:33 +00004052 }
4053
4054 /* Generate breakdown code that occurs after the #line directive */
4055 if( rp->codeSuffix && rp->codeSuffix[0] ){
4056 fprintf(out, "%s", rp->codeSuffix);
4057 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
4058 }
4059
4060 if( rp->codePrefix ){
4061 fprintf(out, "}\n"); (*lineno)++;
4062 }
drh75897232000-05-29 14:26:00 +00004063
drh75897232000-05-29 14:26:00 +00004064 return;
4065}
4066
4067/*
4068** Print the definition of the union used for the parser's data stack.
4069** This union contains fields for every possible data type for tokens
4070** and nonterminals. In the process of computing and printing this
4071** union, also set the ".dtnum" field of every terminal and nonterminal
4072** symbol.
4073*/
icculus9e44cf12010-02-14 17:14:22 +00004074void print_stack_union(
4075 FILE *out, /* The output stream */
4076 struct lemon *lemp, /* The main info structure for this parser */
4077 int *plineno, /* Pointer to the line number */
4078 int mhflag /* True if generating makeheaders output */
4079){
drh75897232000-05-29 14:26:00 +00004080 int lineno = *plineno; /* The line number of the output */
4081 char **types; /* A hash table of datatypes */
4082 int arraysize; /* Size of the "types" array */
4083 int maxdtlength; /* Maximum length of any ".datatype" field. */
4084 char *stddt; /* Standardized name for a datatype */
4085 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00004086 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00004087 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00004088
4089 /* Allocate and initialize types[] and allocate stddt[] */
4090 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00004091 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00004092 if( types==0 ){
4093 fprintf(stderr,"Out of memory.\n");
4094 exit(1);
4095 }
drh75897232000-05-29 14:26:00 +00004096 for(i=0; i<arraysize; i++) types[i] = 0;
4097 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00004098 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00004099 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00004100 }
drh75897232000-05-29 14:26:00 +00004101 for(i=0; i<lemp->nsymbol; i++){
4102 int len;
4103 struct symbol *sp = lemp->symbols[i];
4104 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00004105 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00004106 if( len>maxdtlength ) maxdtlength = len;
4107 }
4108 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00004109 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00004110 fprintf(stderr,"Out of memory.\n");
4111 exit(1);
4112 }
4113
4114 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
4115 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00004116 ** used for terminal symbols. If there is no %default_type defined then
4117 ** 0 is also used as the .dtnum value for nonterminals which do not specify
4118 ** a datatype using the %type directive.
4119 */
drh75897232000-05-29 14:26:00 +00004120 for(i=0; i<lemp->nsymbol; i++){
4121 struct symbol *sp = lemp->symbols[i];
4122 char *cp;
4123 if( sp==lemp->errsym ){
4124 sp->dtnum = arraysize+1;
4125 continue;
4126 }
drh960e8c62001-04-03 16:53:21 +00004127 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00004128 sp->dtnum = 0;
4129 continue;
4130 }
4131 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00004132 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00004133 j = 0;
drhc56fac72015-10-29 13:48:15 +00004134 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00004135 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00004136 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00004137 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00004138 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00004139 sp->dtnum = 0;
4140 continue;
4141 }
drh75897232000-05-29 14:26:00 +00004142 hash = 0;
4143 for(j=0; stddt[j]; j++){
4144 hash = hash*53 + stddt[j];
4145 }
drh3b2129c2003-05-13 00:34:21 +00004146 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00004147 while( types[hash] ){
4148 if( strcmp(types[hash],stddt)==0 ){
4149 sp->dtnum = hash + 1;
4150 break;
4151 }
4152 hash++;
drh2b51f212013-10-11 23:01:02 +00004153 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00004154 }
4155 if( types[hash]==0 ){
4156 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00004157 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00004158 if( types[hash]==0 ){
4159 fprintf(stderr,"Out of memory.\n");
4160 exit(1);
4161 }
drh898799f2014-01-10 23:21:00 +00004162 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00004163 }
4164 }
4165
4166 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4167 name = lemp->name ? lemp->name : "Parse";
4168 lineno = *plineno;
4169 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4170 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4171 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4172 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4173 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00004174 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004175 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4176 for(i=0; i<arraysize; i++){
4177 if( types[i]==0 ) continue;
4178 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4179 free(types[i]);
4180 }
drhed0c15b2018-04-16 14:31:34 +00004181 if( lemp->errsym && lemp->errsym->useCnt ){
drhc4dd3fd2008-01-22 01:48:05 +00004182 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4183 }
drh75897232000-05-29 14:26:00 +00004184 free(stddt);
4185 free(types);
4186 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4187 *plineno = lineno;
4188}
4189
drhb29b0a52002-02-23 19:39:46 +00004190/*
4191** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00004192** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4193** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00004194*/
drhc75e0162015-09-07 02:23:02 +00004195static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4196 const char *zType = "int";
4197 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00004198 if( lwr>=0 ){
4199 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00004200 zType = "unsigned char";
4201 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004202 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00004203 zType = "unsigned short int";
4204 nByte = 2;
drh8b582012003-10-21 13:16:03 +00004205 }else{
drhc75e0162015-09-07 02:23:02 +00004206 zType = "unsigned int";
4207 nByte = 4;
drh8b582012003-10-21 13:16:03 +00004208 }
4209 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00004210 zType = "signed char";
4211 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004212 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00004213 zType = "short";
4214 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00004215 }
drhc75e0162015-09-07 02:23:02 +00004216 if( pnByte ) *pnByte = nByte;
4217 return zType;
drhb29b0a52002-02-23 19:39:46 +00004218}
4219
drhfdbf9282003-10-21 16:34:41 +00004220/*
4221** Each state contains a set of token transaction and a set of
4222** nonterminal transactions. Each of these sets makes an instance
4223** of the following structure. An array of these structures is used
4224** to order the creation of entries in the yy_action[] table.
4225*/
4226struct axset {
4227 struct state *stp; /* A pointer to a state */
4228 int isTkn; /* True to use tokens. False for non-terminals */
4229 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00004230 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00004231};
4232
4233/*
4234** Compare to axset structures for sorting purposes
4235*/
4236static int axset_compare(const void *a, const void *b){
4237 struct axset *p1 = (struct axset*)a;
4238 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004239 int c;
4240 c = p2->nAction - p1->nAction;
4241 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004242 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004243 }
4244 assert( c!=0 || p1==p2 );
4245 return c;
drhfdbf9282003-10-21 16:34:41 +00004246}
4247
drhc4dd3fd2008-01-22 01:48:05 +00004248/*
4249** Write text on "out" that describes the rule "rp".
4250*/
4251static void writeRuleText(FILE *out, struct rule *rp){
4252 int j;
4253 fprintf(out,"%s ::=", rp->lhs->name);
4254 for(j=0; j<rp->nrhs; j++){
4255 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004256 if( sp->type!=MULTITERMINAL ){
4257 fprintf(out," %s", sp->name);
4258 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004259 int k;
drh61f92cd2014-01-11 03:06:18 +00004260 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004261 for(k=1; k<sp->nsubsym; k++){
4262 fprintf(out,"|%s",sp->subsym[k]->name);
4263 }
4264 }
4265 }
4266}
4267
4268
drh75897232000-05-29 14:26:00 +00004269/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004270void ReportTable(
4271 struct lemon *lemp,
drhfe03dac2019-11-26 02:22:39 +00004272 int mhflag, /* Output in makeheaders format if true */
4273 int sqlFlag /* Generate the *.sql file too */
icculus9e44cf12010-02-14 17:14:22 +00004274){
drhfe03dac2019-11-26 02:22:39 +00004275 FILE *out, *in, *sql;
drh75897232000-05-29 14:26:00 +00004276 char line[LINESIZE];
4277 int lineno;
4278 struct state *stp;
4279 struct action *ap;
4280 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004281 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004282 int i, j, n, sz;
drh2e517162019-08-28 02:09:47 +00004283 int nLookAhead;
drhc75e0162015-09-07 02:23:02 +00004284 int szActionType; /* sizeof(YYACTIONTYPE) */
4285 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004286 const char *name;
drh8b582012003-10-21 13:16:03 +00004287 int mnTknOfst, mxTknOfst;
4288 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004289 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004290
drh5c8241b2017-12-24 23:38:10 +00004291 lemp->minShiftReduce = lemp->nstate;
4292 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4293 lemp->accAction = lemp->errAction + 1;
4294 lemp->noAction = lemp->accAction + 1;
4295 lemp->minReduce = lemp->noAction + 1;
4296 lemp->maxAction = lemp->minReduce + lemp->nrule;
4297
drh75897232000-05-29 14:26:00 +00004298 in = tplt_open(lemp);
4299 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004300 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004301 if( out==0 ){
4302 fclose(in);
4303 return;
4304 }
drhfe03dac2019-11-26 02:22:39 +00004305 if( sqlFlag==0 ){
4306 sql = 0;
4307 }else{
4308 sql = file_open(lemp, ".sql", "wb");
4309 if( sql==0 ){
4310 fclose(in);
4311 fclose(out);
4312 return;
4313 }
4314 fprintf(sql,
drh1417c2f2019-11-29 12:51:00 +00004315 "BEGIN;\n"
drhfe03dac2019-11-26 02:22:39 +00004316 "CREATE TABLE symbol(\n"
4317 " id INTEGER PRIMARY KEY,\n"
4318 " name TEXT NOT NULL,\n"
4319 " isTerminal BOOLEAN NOT NULL,\n"
drh1417c2f2019-11-29 12:51:00 +00004320 " fallback INTEGER REFERENCES symbol"
4321 " DEFERRABLE INITIALLY DEFERRED\n"
drhfe03dac2019-11-26 02:22:39 +00004322 ");\n"
4323 );
4324 for(i=0; i<lemp->nsymbol; i++){
4325 fprintf(sql,
4326 "INSERT INTO symbol(id,name,isTerminal,fallback)"
4327 "VALUES(%d,'%s',%s",
4328 i, lemp->symbols[i]->name,
4329 i<lemp->nterminal ? "TRUE" : "FALSE"
4330 );
4331 if( lemp->symbols[i]->fallback ){
4332 fprintf(sql, ",%d);\n", lemp->symbols[i]->fallback->index);
4333 }else{
4334 fprintf(sql, ",NULL);\n");
4335 }
4336 }
4337 fprintf(sql,
4338 "CREATE TABLE rule(\n"
4339 " ruleid INTEGER PRIMARY KEY,\n"
drh3e5f7fe2019-12-19 12:29:31 +00004340 " lhs INTEGER REFERENCES symbol(id),\n"
4341 " txt TEXT\n"
drhfe03dac2019-11-26 02:22:39 +00004342 ");\n"
4343 "CREATE TABLE rulerhs(\n"
4344 " ruleid INTEGER REFERENCES rule(ruleid),\n"
4345 " pos INTEGER,\n"
4346 " sym INTEGER REFERENCES symbol(id)\n"
4347 ");\n"
4348 );
4349 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4350 assert( i==rp->iRule );
4351 fprintf(sql,
drh59c56792019-12-19 13:17:07 +00004352 "INSERT INTO rule(ruleid,lhs,txt)VALUES(%d,%d,'",
drhfe03dac2019-11-26 02:22:39 +00004353 rp->iRule, rp->lhs->index
4354 );
drh3e5f7fe2019-12-19 12:29:31 +00004355 writeRuleText(sql, rp);
4356 fprintf(sql,"');\n");
drhfe03dac2019-11-26 02:22:39 +00004357 for(j=0; j<rp->nrhs; j++){
4358 struct symbol *sp = rp->rhs[j];
4359 if( sp->type!=MULTITERMINAL ){
4360 fprintf(sql,
4361 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4362 i,j,sp->index
4363 );
4364 }else{
4365 int k;
4366 for(k=0; k<sp->nsubsym; k++){
4367 fprintf(sql,
4368 "INSERT INTO rulerhs(ruleid,pos,sym)VALUES(%d,%d,%d);\n",
4369 i,j,sp->subsym[k]->index
4370 );
4371 }
4372 }
4373 }
4374 }
drh1417c2f2019-11-29 12:51:00 +00004375 fprintf(sql, "COMMIT;\n");
drhfe03dac2019-11-26 02:22:39 +00004376 }
drh75897232000-05-29 14:26:00 +00004377 lineno = 1;
4378 tplt_xfer(lemp->name,in,out,&lineno);
4379
4380 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004381 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004382 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004383 char *incName = file_makename(lemp, ".h");
4384 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4385 free(incName);
drh75897232000-05-29 14:26:00 +00004386 }
4387 tplt_xfer(lemp->name,in,out,&lineno);
4388
4389 /* Generate #defines for all tokens */
4390 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004391 const char *prefix;
drh75897232000-05-29 14:26:00 +00004392 fprintf(out,"#if INTERFACE\n"); lineno++;
4393 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4394 else prefix = "";
4395 for(i=1; i<lemp->nterminal; i++){
4396 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4397 lineno++;
4398 }
4399 fprintf(out,"#endif\n"); lineno++;
4400 }
4401 tplt_xfer(lemp->name,in,out,&lineno);
4402
4403 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004404 fprintf(out,"#define YYCODETYPE %s\n",
drhed0c15b2018-04-16 14:31:34 +00004405 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4406 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
drh75897232000-05-29 14:26:00 +00004407 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004408 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004409 if( lemp->wildcard ){
4410 fprintf(out,"#define YYWILDCARD %d\n",
4411 lemp->wildcard->index); lineno++;
4412 }
drh75897232000-05-29 14:26:00 +00004413 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004414 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004415 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004416 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4417 }else{
4418 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4419 }
drhca44b5a2007-02-22 23:06:58 +00004420 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004421 if( mhflag ){
4422 fprintf(out,"#if INTERFACE\n"); lineno++;
4423 }
4424 name = lemp->name ? lemp->name : "Parse";
4425 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004426 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004427 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4428 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004429 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4430 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
drhfb32c442018-04-21 13:51:42 +00004431 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4432 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
drh1f245e42002-03-11 13:55:50 +00004433 name,lemp->arg,&lemp->arg[i]); lineno++;
drhfb32c442018-04-21 13:51:42 +00004434 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
drh1f245e42002-03-11 13:55:50 +00004435 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004436 }else{
drhfb32c442018-04-21 13:51:42 +00004437 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4438 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4439 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
drh1f245e42002-03-11 13:55:50 +00004440 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4441 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004442 }
drhfb32c442018-04-21 13:51:42 +00004443 if( lemp->ctx && lemp->ctx[0] ){
4444 i = lemonStrlen(lemp->ctx);
4445 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4446 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4447 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4448 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4449 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4450 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4451 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4452 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4453 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4454 }else{
4455 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4456 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4457 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4458 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4459 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4460 }
drh75897232000-05-29 14:26:00 +00004461 if( mhflag ){
4462 fprintf(out,"#endif\n"); lineno++;
4463 }
drhed0c15b2018-04-16 14:31:34 +00004464 if( lemp->errsym && lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004465 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4466 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004467 }
drh0bd1f4e2002-06-06 18:54:39 +00004468 if( lemp->has_fallback ){
4469 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4470 }
drh75897232000-05-29 14:26:00 +00004471
drh3bd48ab2015-09-07 18:23:37 +00004472 /* Compute the action table, but do not output it yet. The action
4473 ** table must be computed before generating the YYNSTATE macro because
4474 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004475 */
drh3bd48ab2015-09-07 18:23:37 +00004476 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004477 if( ax==0 ){
4478 fprintf(stderr,"malloc failed\n");
4479 exit(1);
4480 }
drh3bd48ab2015-09-07 18:23:37 +00004481 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004482 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004483 ax[i*2].stp = stp;
4484 ax[i*2].isTkn = 1;
4485 ax[i*2].nAction = stp->nTknAct;
4486 ax[i*2+1].stp = stp;
4487 ax[i*2+1].isTkn = 0;
4488 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004489 }
drh8b582012003-10-21 13:16:03 +00004490 mxTknOfst = mnTknOfst = 0;
4491 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004492 /* In an effort to minimize the action table size, use the heuristic
4493 ** of placing the largest action sets first */
4494 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4495 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh3a9d6c72017-12-25 04:15:38 +00004496 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
drh3bd48ab2015-09-07 18:23:37 +00004497 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004498 stp = ax[i].stp;
4499 if( ax[i].isTkn ){
4500 for(ap=stp->ap; ap; ap=ap->next){
4501 int action;
4502 if( ap->sp->index>=lemp->nterminal ) continue;
4503 action = compute_action(lemp, ap);
4504 if( action<0 ) continue;
4505 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004506 }
drh3a9d6c72017-12-25 04:15:38 +00004507 stp->iTknOfst = acttab_insert(pActtab, 1);
drhfdbf9282003-10-21 16:34:41 +00004508 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4509 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4510 }else{
4511 for(ap=stp->ap; ap; ap=ap->next){
4512 int action;
4513 if( ap->sp->index<lemp->nterminal ) continue;
4514 if( ap->sp->index==lemp->nsymbol ) continue;
4515 action = compute_action(lemp, ap);
4516 if( action<0 ) continue;
4517 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004518 }
drh3a9d6c72017-12-25 04:15:38 +00004519 stp->iNtOfst = acttab_insert(pActtab, 0);
drhfdbf9282003-10-21 16:34:41 +00004520 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4521 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004522 }
drh337cd0d2015-09-07 23:40:42 +00004523#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4524 { int jj, nn;
4525 for(jj=nn=0; jj<pActtab->nAction; jj++){
4526 if( pActtab->aAction[jj].action<0 ) nn++;
4527 }
4528 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4529 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4530 ax[i].nAction, pActtab->nAction, nn);
4531 }
4532#endif
drh8b582012003-10-21 13:16:03 +00004533 }
drhfdbf9282003-10-21 16:34:41 +00004534 free(ax);
drh8b582012003-10-21 13:16:03 +00004535
drh756b41e2016-05-24 18:55:08 +00004536 /* Mark rules that are actually used for reduce actions after all
4537 ** optimizations have been applied
4538 */
4539 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4540 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004541 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4542 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004543 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004544 }
4545 }
4546 }
4547
drh3bd48ab2015-09-07 18:23:37 +00004548 /* Finish rendering the constants now that the action table has
4549 ** been computed */
4550 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4551 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhce678c22019-12-11 18:53:51 +00004552 fprintf(out,"#define YYNRULE_WITH_ACTION %d\n",lemp->nruleWithAction);
4553 lineno++;
drh0d9de992017-12-26 18:04:23 +00004554 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004555 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004556 i = lemp->minShiftReduce;
4557 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4558 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004559 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004560 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4561 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4562 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4563 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4564 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004565 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004566 tplt_xfer(lemp->name,in,out,&lineno);
4567
4568 /* Now output the action table and its associates:
4569 **
4570 ** yy_action[] A single table containing all actions.
4571 ** yy_lookahead[] A table containing the lookahead for each entry in
4572 ** yy_action. Used to detect hash collisions.
4573 ** yy_shift_ofst[] For each state, the offset into yy_action for
4574 ** shifting terminals.
4575 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4576 ** shifting non-terminals after a reduce.
4577 ** yy_default[] Default action for each state.
4578 */
4579
drh8b582012003-10-21 13:16:03 +00004580 /* Output the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +00004581 lemp->nactiontab = n = acttab_action_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004582 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004583 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4584 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004585 for(i=j=0; i<n; i++){
4586 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004587 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004588 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004589 fprintf(out, " %4d,", action);
4590 if( j==9 || i==n-1 ){
4591 fprintf(out, "\n"); lineno++;
4592 j = 0;
4593 }else{
4594 j++;
4595 }
4596 }
4597 fprintf(out, "};\n"); lineno++;
4598
4599 /* Output the yy_lookahead table */
drh3a9d6c72017-12-25 04:15:38 +00004600 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004601 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004602 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004603 for(i=j=0; i<n; i++){
4604 int la = acttab_yylookahead(pActtab, i);
4605 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004606 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004607 fprintf(out, " %4d,", la);
drh2e517162019-08-28 02:09:47 +00004608 if( j==9 ){
drh8b582012003-10-21 13:16:03 +00004609 fprintf(out, "\n"); lineno++;
4610 j = 0;
4611 }else{
4612 j++;
4613 }
4614 }
drh2e517162019-08-28 02:09:47 +00004615 /* Add extra entries to the end of the yy_lookahead[] table so that
4616 ** yy_shift_ofst[]+iToken will always be a valid index into the array,
4617 ** even for the largest possible value of yy_shift_ofst[] and iToken. */
4618 nLookAhead = lemp->nterminal + lemp->nactiontab;
4619 while( i<nLookAhead ){
4620 if( j==0 ) fprintf(out," /* %5d */ ", i);
4621 fprintf(out, " %4d,", lemp->nterminal);
4622 if( j==9 ){
4623 fprintf(out, "\n"); lineno++;
4624 j = 0;
4625 }else{
4626 j++;
4627 }
4628 i++;
4629 }
mistachkinacf6e082019-09-11 15:25:26 +00004630 if( j>0 ){ fprintf(out, "\n"); lineno++; }
drh8b582012003-10-21 13:16:03 +00004631 fprintf(out, "};\n"); lineno++;
4632
4633 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004634 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004635 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004636 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4637 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4638 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004639 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004640 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4641 lineno++;
drhc75e0162015-09-07 02:23:02 +00004642 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004643 for(i=j=0; i<n; i++){
4644 int ofst;
4645 stp = lemp->sorted[i];
4646 ofst = stp->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004647 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
drhfdbf9282003-10-21 16:34:41 +00004648 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004649 fprintf(out, " %4d,", ofst);
4650 if( j==9 || i==n-1 ){
4651 fprintf(out, "\n"); lineno++;
4652 j = 0;
4653 }else{
4654 j++;
4655 }
4656 }
4657 fprintf(out, "};\n"); lineno++;
4658
4659 /* Output the yy_reduce_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004660 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004661 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004662 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4663 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4664 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004665 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004666 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4667 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004668 for(i=j=0; i<n; i++){
4669 int ofst;
4670 stp = lemp->sorted[i];
4671 ofst = stp->iNtOfst;
4672 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004673 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004674 fprintf(out, " %4d,", ofst);
4675 if( j==9 || i==n-1 ){
4676 fprintf(out, "\n"); lineno++;
4677 j = 0;
4678 }else{
4679 j++;
4680 }
4681 }
4682 fprintf(out, "};\n"); lineno++;
4683
4684 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004685 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004686 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004687 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004688 for(i=j=0; i<n; i++){
4689 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004690 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004691 if( stp->iDfltReduce<0 ){
4692 fprintf(out, " %4d,", lemp->errAction);
4693 }else{
4694 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4695 }
drh8b582012003-10-21 13:16:03 +00004696 if( j==9 || i==n-1 ){
4697 fprintf(out, "\n"); lineno++;
4698 j = 0;
4699 }else{
4700 j++;
4701 }
4702 }
4703 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004704 tplt_xfer(lemp->name,in,out,&lineno);
4705
drh0bd1f4e2002-06-06 18:54:39 +00004706 /* Generate the table of fallback tokens.
4707 */
4708 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004709 int mx = lemp->nterminal - 1;
drh010bdb42019-08-28 11:31:11 +00004710 /* 2019-08-28: Generate fallback entries for every token to avoid
4711 ** having to do a range check on the index */
4712 /* while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } */
drhc75e0162015-09-07 02:23:02 +00004713 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004714 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004715 struct symbol *p = lemp->symbols[i];
4716 if( p->fallback==0 ){
4717 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4718 }else{
4719 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4720 p->name, p->fallback->name);
4721 }
4722 lineno++;
4723 }
4724 }
4725 tplt_xfer(lemp->name, in, out, &lineno);
4726
4727 /* Generate a table containing the symbolic name of every symbol
4728 */
drh75897232000-05-29 14:26:00 +00004729 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004730 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh3a9d6c72017-12-25 04:15:38 +00004731 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
drh75897232000-05-29 14:26:00 +00004732 }
drh75897232000-05-29 14:26:00 +00004733 tplt_xfer(lemp->name,in,out,&lineno);
4734
drh0bd1f4e2002-06-06 18:54:39 +00004735 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004736 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004737 ** when tracing REDUCE actions.
4738 */
4739 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004740 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004741 fprintf(out," /* %3d */ \"", i);
4742 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004743 fprintf(out,"\",\n"); lineno++;
4744 }
4745 tplt_xfer(lemp->name,in,out,&lineno);
4746
drh75897232000-05-29 14:26:00 +00004747 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004748 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004749 ** (In other words, generate the %destructor actions)
4750 */
drh75897232000-05-29 14:26:00 +00004751 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004752 int once = 1;
drh75897232000-05-29 14:26:00 +00004753 for(i=0; i<lemp->nsymbol; i++){
4754 struct symbol *sp = lemp->symbols[i];
4755 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004756 if( once ){
4757 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4758 once = 0;
4759 }
drhc53eed12009-06-12 17:46:19 +00004760 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004761 }
4762 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4763 if( i<lemp->nsymbol ){
4764 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4765 fprintf(out," break;\n"); lineno++;
4766 }
4767 }
drh8d659732005-01-13 23:54:06 +00004768 if( lemp->vardest ){
4769 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004770 int once = 1;
drh8d659732005-01-13 23:54:06 +00004771 for(i=0; i<lemp->nsymbol; i++){
4772 struct symbol *sp = lemp->symbols[i];
4773 if( sp==0 || sp->type==TERMINAL ||
4774 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004775 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004776 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004777 once = 0;
4778 }
drhc53eed12009-06-12 17:46:19 +00004779 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004780 dflt_sp = sp;
4781 }
4782 if( dflt_sp!=0 ){
4783 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004784 }
drh4dc8ef52008-07-01 17:13:57 +00004785 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004786 }
drh75897232000-05-29 14:26:00 +00004787 for(i=0; i<lemp->nsymbol; i++){
4788 struct symbol *sp = lemp->symbols[i];
4789 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004790 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004791 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004792
4793 /* Combine duplicate destructors into a single case */
4794 for(j=i+1; j<lemp->nsymbol; j++){
4795 struct symbol *sp2 = lemp->symbols[j];
4796 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4797 && sp2->dtnum==sp->dtnum
4798 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004799 fprintf(out," case %d: /* %s */\n",
4800 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004801 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004802 }
4803 }
4804
drh75897232000-05-29 14:26:00 +00004805 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4806 fprintf(out," break;\n"); lineno++;
4807 }
drh75897232000-05-29 14:26:00 +00004808 tplt_xfer(lemp->name,in,out,&lineno);
4809
4810 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004811 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004812 tplt_xfer(lemp->name,in,out,&lineno);
4813
drhcfc45b12018-12-03 23:57:27 +00004814 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4815 ** yyRuleInfoNRhs[].
drh75897232000-05-29 14:26:00 +00004816 **
4817 ** Note: This code depends on the fact that rules are number
4818 ** sequentually beginning with 0.
4819 */
drh5c8241b2017-12-24 23:38:10 +00004820 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drhcfc45b12018-12-03 23:57:27 +00004821 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4822 rule_print(out, rp);
4823 fprintf(out," */\n"); lineno++;
4824 }
4825 tplt_xfer(lemp->name,in,out,&lineno);
4826 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4827 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
drh5c8241b2017-12-24 23:38:10 +00004828 rule_print(out, rp);
4829 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004830 }
4831 tplt_xfer(lemp->name,in,out,&lineno);
4832
4833 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004834 i = 0;
drh75897232000-05-29 14:26:00 +00004835 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004836 i += translate_code(lemp, rp);
4837 }
4838 if( i ){
4839 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004840 }
drhc53eed12009-06-12 17:46:19 +00004841 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004842 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004843 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004844 if( rp->codeEmitted ) continue;
4845 if( rp->noCode ){
4846 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004847 continue;
4848 }
drh4ef07702016-03-16 19:45:54 +00004849 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004850 writeRuleText(out, rp);
4851 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004852 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004853 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4854 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004855 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004856 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004857 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004858 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004859 }
4860 }
drh75897232000-05-29 14:26:00 +00004861 emit_code(out,rp,lemp,&lineno);
4862 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004863 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004864 }
drhc53eed12009-06-12 17:46:19 +00004865 /* Finally, output the default: rule. We choose as the default: all
4866 ** empty actions. */
4867 fprintf(out," default:\n"); lineno++;
4868 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004869 if( rp->codeEmitted ) continue;
4870 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004871 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004872 writeRuleText(out, rp);
drhe94006e2019-12-10 20:41:48 +00004873 if( rp->neverReduce ){
4874 fprintf(out, " (NEVER REDUCES) */ assert(yyruleno!=%d);\n",
4875 rp->iRule); lineno++;
4876 }else if( rp->doesReduce ){
drh756b41e2016-05-24 18:55:08 +00004877 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4878 }else{
4879 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4880 rp->iRule); lineno++;
4881 }
drhc53eed12009-06-12 17:46:19 +00004882 }
4883 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004884 tplt_xfer(lemp->name,in,out,&lineno);
4885
4886 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004887 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004888 tplt_xfer(lemp->name,in,out,&lineno);
4889
4890 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004891 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004892 tplt_xfer(lemp->name,in,out,&lineno);
4893
4894 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004895 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004896 tplt_xfer(lemp->name,in,out,&lineno);
4897
4898 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004899 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004900
drhe2dcc422019-01-15 14:44:23 +00004901 acttab_free(pActtab);
drh75897232000-05-29 14:26:00 +00004902 fclose(in);
4903 fclose(out);
drhfe03dac2019-11-26 02:22:39 +00004904 if( sql ) fclose(sql);
drh75897232000-05-29 14:26:00 +00004905 return;
4906}
4907
4908/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004909void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004910{
4911 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004912 const char *prefix;
drh75897232000-05-29 14:26:00 +00004913 char line[LINESIZE];
4914 char pattern[LINESIZE];
4915 int i;
4916
4917 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4918 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004919 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004920 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004921 int nextChar;
drh75897232000-05-29 14:26:00 +00004922 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004923 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4924 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004925 if( strcmp(line,pattern) ) break;
4926 }
drh8ba0d1c2012-06-16 15:26:31 +00004927 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004928 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004929 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004930 /* No change in the file. Don't rewrite it. */
4931 return;
4932 }
4933 }
drh2aa6ca42004-09-10 00:14:04 +00004934 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004935 if( out ){
4936 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004937 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004938 }
drh06f60d82017-04-14 19:46:12 +00004939 fclose(out);
drh75897232000-05-29 14:26:00 +00004940 }
4941 return;
4942}
4943
4944/* Reduce the size of the action tables, if possible, by making use
4945** of defaults.
4946**
drhb59499c2002-02-23 18:45:13 +00004947** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004948** it the default. Except, there is no default if the wildcard token
4949** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004950*/
icculus9e44cf12010-02-14 17:14:22 +00004951void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004952{
4953 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004954 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004955 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004956 int nbest, n;
drh75897232000-05-29 14:26:00 +00004957 int i;
drhe09daa92006-06-10 13:29:31 +00004958 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004959
4960 for(i=0; i<lemp->nstate; i++){
4961 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004962 nbest = 0;
4963 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004964 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004965
drhb59499c2002-02-23 18:45:13 +00004966 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004967 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4968 usesWildcard = 1;
4969 }
drhb59499c2002-02-23 18:45:13 +00004970 if( ap->type!=REDUCE ) continue;
4971 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004972 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004973 if( rp==rbest ) continue;
4974 n = 1;
4975 for(ap2=ap->next; ap2; ap2=ap2->next){
4976 if( ap2->type!=REDUCE ) continue;
4977 rp2 = ap2->x.rp;
4978 if( rp2==rbest ) continue;
4979 if( rp2==rp ) n++;
4980 }
4981 if( n>nbest ){
4982 nbest = n;
4983 rbest = rp;
drh75897232000-05-29 14:26:00 +00004984 }
4985 }
drh06f60d82017-04-14 19:46:12 +00004986
drhb59499c2002-02-23 18:45:13 +00004987 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004988 ** is not at least 1 or if the wildcard token is a possible
4989 ** lookahead.
4990 */
4991 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004992
drhb59499c2002-02-23 18:45:13 +00004993
4994 /* Combine matching REDUCE actions into a single default */
4995 for(ap=stp->ap; ap; ap=ap->next){
4996 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4997 }
drh75897232000-05-29 14:26:00 +00004998 assert( ap );
4999 ap->sp = Symbol_new("{default}");
5000 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00005001 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00005002 }
5003 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00005004
5005 for(ap=stp->ap; ap; ap=ap->next){
5006 if( ap->type==SHIFT ) break;
5007 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
5008 }
5009 if( ap==0 ){
5010 stp->autoReduce = 1;
5011 stp->pDfltReduce = rbest;
5012 }
5013 }
5014
5015 /* Make a second pass over all states and actions. Convert
5016 ** every action that is a SHIFT to an autoReduce state into
5017 ** a SHIFTREDUCE action.
5018 */
5019 for(i=0; i<lemp->nstate; i++){
5020 stp = lemp->sorted[i];
5021 for(ap=stp->ap; ap; ap=ap->next){
5022 struct state *pNextState;
5023 if( ap->type!=SHIFT ) continue;
5024 pNextState = ap->x.stp;
5025 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
5026 ap->type = SHIFTREDUCE;
5027 ap->x.rp = pNextState->pDfltReduce;
5028 }
5029 }
drh75897232000-05-29 14:26:00 +00005030 }
drhc173ad82016-05-23 16:15:02 +00005031
5032 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
5033 ** (meaning that the SHIFTREDUCE will land back in the state where it
5034 ** started) and if there is no C-code associated with the reduce action,
5035 ** then we can go ahead and convert the action to be the same as the
5036 ** action for the RHS of the rule.
5037 */
5038 for(i=0; i<lemp->nstate; i++){
5039 stp = lemp->sorted[i];
5040 for(ap=stp->ap; ap; ap=nextap){
5041 nextap = ap->next;
5042 if( ap->type!=SHIFTREDUCE ) continue;
5043 rp = ap->x.rp;
5044 if( rp->noCode==0 ) continue;
5045 if( rp->nrhs!=1 ) continue;
5046#if 1
5047 /* Only apply this optimization to non-terminals. It would be OK to
5048 ** apply it to terminal symbols too, but that makes the parser tables
5049 ** larger. */
5050 if( ap->sp->index<lemp->nterminal ) continue;
5051#endif
5052 /* If we reach this point, it means the optimization can be applied */
5053 nextap = ap;
5054 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
5055 assert( ap2!=0 );
5056 ap->spOpt = ap2->sp;
5057 ap->type = ap2->type;
5058 ap->x = ap2->x;
5059 }
5060 }
drh75897232000-05-29 14:26:00 +00005061}
drhb59499c2002-02-23 18:45:13 +00005062
drhada354d2005-11-05 15:03:59 +00005063
5064/*
5065** Compare two states for sorting purposes. The smaller state is the
5066** one with the most non-terminal actions. If they have the same number
5067** of non-terminal actions, then the smaller is the one with the most
5068** token actions.
5069*/
5070static int stateResortCompare(const void *a, const void *b){
5071 const struct state *pA = *(const struct state**)a;
5072 const struct state *pB = *(const struct state**)b;
5073 int n;
5074
5075 n = pB->nNtAct - pA->nNtAct;
5076 if( n==0 ){
5077 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00005078 if( n==0 ){
5079 n = pB->statenum - pA->statenum;
5080 }
drhada354d2005-11-05 15:03:59 +00005081 }
drhe594bc32009-11-03 13:02:25 +00005082 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00005083 return n;
5084}
5085
5086
5087/*
5088** Renumber and resort states so that states with fewer choices
5089** occur at the end. Except, keep state 0 as the first state.
5090*/
icculus9e44cf12010-02-14 17:14:22 +00005091void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00005092{
5093 int i;
5094 struct state *stp;
5095 struct action *ap;
5096
5097 for(i=0; i<lemp->nstate; i++){
5098 stp = lemp->sorted[i];
5099 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00005100 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00005101 stp->iTknOfst = NO_OFFSET;
5102 stp->iNtOfst = NO_OFFSET;
5103 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00005104 int iAction = compute_action(lemp,ap);
5105 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00005106 if( ap->sp->index<lemp->nterminal ){
5107 stp->nTknAct++;
5108 }else if( ap->sp->index<lemp->nsymbol ){
5109 stp->nNtAct++;
5110 }else{
drh3bd48ab2015-09-07 18:23:37 +00005111 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00005112 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00005113 }
5114 }
5115 }
5116 }
5117 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
5118 stateResortCompare);
5119 for(i=0; i<lemp->nstate; i++){
5120 lemp->sorted[i]->statenum = i;
5121 }
drh3bd48ab2015-09-07 18:23:37 +00005122 lemp->nxstate = lemp->nstate;
5123 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
5124 lemp->nxstate--;
5125 }
drhada354d2005-11-05 15:03:59 +00005126}
5127
5128
drh75897232000-05-29 14:26:00 +00005129/***************** From the file "set.c" ************************************/
5130/*
5131** Set manipulation routines for the LEMON parser generator.
5132*/
5133
5134static int size = 0;
5135
5136/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00005137void SetSize(int n)
drh75897232000-05-29 14:26:00 +00005138{
5139 size = n+1;
5140}
5141
5142/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00005143char *SetNew(void){
drh75897232000-05-29 14:26:00 +00005144 char *s;
drh9892c5d2007-12-21 00:02:11 +00005145 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00005146 if( s==0 ){
drh75897232000-05-29 14:26:00 +00005147 memory_error();
5148 }
drh75897232000-05-29 14:26:00 +00005149 return s;
5150}
5151
5152/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00005153void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00005154{
5155 free(s);
5156}
5157
5158/* Add a new element to the set. Return TRUE if the element was added
5159** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00005160int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00005161{
5162 int rv;
drh9892c5d2007-12-21 00:02:11 +00005163 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00005164 rv = s[e];
5165 s[e] = 1;
5166 return !rv;
5167}
5168
5169/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00005170int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00005171{
5172 int i, progress;
5173 progress = 0;
5174 for(i=0; i<size; i++){
5175 if( s2[i]==0 ) continue;
5176 if( s1[i]==0 ){
5177 progress = 1;
5178 s1[i] = 1;
5179 }
5180 }
5181 return progress;
5182}
5183/********************** From the file "table.c" ****************************/
5184/*
5185** All code in this file has been automatically generated
5186** from a specification in the file
5187** "table.q"
5188** by the associative array code building program "aagen".
5189** Do not edit this file! Instead, edit the specification
5190** file, then rerun aagen.
5191*/
5192/*
5193** Code for processing tables in the LEMON parser generator.
5194*/
5195
drh01f75f22013-10-02 20:46:30 +00005196PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00005197{
drh01f75f22013-10-02 20:46:30 +00005198 unsigned h = 0;
5199 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00005200 return h;
5201}
5202
5203/* Works like strdup, sort of. Save a string in malloced memory, but
5204** keep strings in a table so that the same string is not in more
5205** than one place.
5206*/
icculus9e44cf12010-02-14 17:14:22 +00005207const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00005208{
icculus9e44cf12010-02-14 17:14:22 +00005209 const char *z;
5210 char *cpy;
drh75897232000-05-29 14:26:00 +00005211
drh916f75f2006-07-17 00:19:39 +00005212 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00005213 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00005214 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00005215 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00005216 z = cpy;
drh75897232000-05-29 14:26:00 +00005217 Strsafe_insert(z);
5218 }
5219 MemoryCheck(z);
5220 return z;
5221}
5222
5223/* There is one instance of the following structure for each
5224** associative array of type "x1".
5225*/
5226struct s_x1 {
5227 int size; /* The number of available slots. */
5228 /* Must be a power of 2 greater than or */
5229 /* equal to 1 */
5230 int count; /* Number of currently slots filled */
5231 struct s_x1node *tbl; /* The data stored here */
5232 struct s_x1node **ht; /* Hash table for lookups */
5233};
5234
5235/* There is one instance of this structure for every data element
5236** in an associative array of type "x1".
5237*/
5238typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00005239 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00005240 struct s_x1node *next; /* Next entry with the same hash */
5241 struct s_x1node **from; /* Previous link */
5242} x1node;
5243
5244/* There is only one instance of the array, which is the following */
5245static struct s_x1 *x1a;
5246
5247/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005248void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00005249 if( x1a ) return;
5250 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5251 if( x1a ){
5252 x1a->size = 1024;
5253 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005254 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005255 if( x1a->tbl==0 ){
5256 free(x1a);
5257 x1a = 0;
5258 }else{
5259 int i;
5260 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5261 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5262 }
5263 }
5264}
5265/* Insert a new record into the array. Return TRUE if successful.
5266** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005267int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00005268{
5269 x1node *np;
drh01f75f22013-10-02 20:46:30 +00005270 unsigned h;
5271 unsigned ph;
drh75897232000-05-29 14:26:00 +00005272
5273 if( x1a==0 ) return 0;
5274 ph = strhash(data);
5275 h = ph & (x1a->size-1);
5276 np = x1a->ht[h];
5277 while( np ){
5278 if( strcmp(np->data,data)==0 ){
5279 /* An existing entry with the same key is found. */
5280 /* Fail because overwrite is not allows. */
5281 return 0;
5282 }
5283 np = np->next;
5284 }
5285 if( x1a->count>=x1a->size ){
5286 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005287 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005288 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00005289 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00005290 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00005291 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005292 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005293 array.ht = (x1node**)&(array.tbl[arrSize]);
5294 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005295 for(i=0; i<x1a->count; i++){
5296 x1node *oldnp, *newnp;
5297 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005298 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005299 newnp = &(array.tbl[i]);
5300 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5301 newnp->next = array.ht[h];
5302 newnp->data = oldnp->data;
5303 newnp->from = &(array.ht[h]);
5304 array.ht[h] = newnp;
5305 }
5306 free(x1a->tbl);
5307 *x1a = array;
5308 }
5309 /* Insert the new data */
5310 h = ph & (x1a->size-1);
5311 np = &(x1a->tbl[x1a->count++]);
5312 np->data = data;
5313 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5314 np->next = x1a->ht[h];
5315 x1a->ht[h] = np;
5316 np->from = &(x1a->ht[h]);
5317 return 1;
5318}
5319
5320/* Return a pointer to data assigned to the given key. Return NULL
5321** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005322const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00005323{
drh01f75f22013-10-02 20:46:30 +00005324 unsigned h;
drh75897232000-05-29 14:26:00 +00005325 x1node *np;
5326
5327 if( x1a==0 ) return 0;
5328 h = strhash(key) & (x1a->size-1);
5329 np = x1a->ht[h];
5330 while( np ){
5331 if( strcmp(np->data,key)==0 ) break;
5332 np = np->next;
5333 }
5334 return np ? np->data : 0;
5335}
5336
5337/* Return a pointer to the (terminal or nonterminal) symbol "x".
5338** Create a new symbol if this is the first time "x" has been seen.
5339*/
icculus9e44cf12010-02-14 17:14:22 +00005340struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00005341{
5342 struct symbol *sp;
5343
5344 sp = Symbol_find(x);
5345 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00005346 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00005347 MemoryCheck(sp);
5348 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00005349 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00005350 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00005351 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00005352 sp->prec = -1;
5353 sp->assoc = UNK;
5354 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005355 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005356 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005357 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005358 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005359 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005360 Symbol_insert(sp,sp->name);
5361 }
drhc4dd3fd2008-01-22 01:48:05 +00005362 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005363 return sp;
5364}
5365
drh61f92cd2014-01-11 03:06:18 +00005366/* Compare two symbols for sorting purposes. Return negative,
5367** zero, or positive if a is less then, equal to, or greater
5368** than b.
drh60d31652004-02-22 00:08:04 +00005369**
5370** Symbols that begin with upper case letters (terminals or tokens)
5371** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005372** (non-terminals). And MULTITERMINAL symbols (created using the
5373** %token_class directive) must sort at the very end. Other than
5374** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005375**
5376** We find experimentally that leaving the symbols in their original
5377** order (the order they appeared in the grammar file) gives the
5378** smallest parser tables in SQLite.
5379*/
icculus9e44cf12010-02-14 17:14:22 +00005380int Symbolcmpp(const void *_a, const void *_b)
5381{
drh61f92cd2014-01-11 03:06:18 +00005382 const struct symbol *a = *(const struct symbol **) _a;
5383 const struct symbol *b = *(const struct symbol **) _b;
5384 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5385 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5386 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005387}
5388
5389/* There is one instance of the following structure for each
5390** associative array of type "x2".
5391*/
5392struct s_x2 {
5393 int size; /* The number of available slots. */
5394 /* Must be a power of 2 greater than or */
5395 /* equal to 1 */
5396 int count; /* Number of currently slots filled */
5397 struct s_x2node *tbl; /* The data stored here */
5398 struct s_x2node **ht; /* Hash table for lookups */
5399};
5400
5401/* There is one instance of this structure for every data element
5402** in an associative array of type "x2".
5403*/
5404typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005405 struct symbol *data; /* The data */
5406 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005407 struct s_x2node *next; /* Next entry with the same hash */
5408 struct s_x2node **from; /* Previous link */
5409} x2node;
5410
5411/* There is only one instance of the array, which is the following */
5412static struct s_x2 *x2a;
5413
5414/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005415void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005416 if( x2a ) return;
5417 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5418 if( x2a ){
5419 x2a->size = 128;
5420 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005421 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005422 if( x2a->tbl==0 ){
5423 free(x2a);
5424 x2a = 0;
5425 }else{
5426 int i;
5427 x2a->ht = (x2node**)&(x2a->tbl[128]);
5428 for(i=0; i<128; i++) x2a->ht[i] = 0;
5429 }
5430 }
5431}
5432/* Insert a new record into the array. Return TRUE if successful.
5433** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005434int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005435{
5436 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005437 unsigned h;
5438 unsigned ph;
drh75897232000-05-29 14:26:00 +00005439
5440 if( x2a==0 ) return 0;
5441 ph = strhash(key);
5442 h = ph & (x2a->size-1);
5443 np = x2a->ht[h];
5444 while( np ){
5445 if( strcmp(np->key,key)==0 ){
5446 /* An existing entry with the same key is found. */
5447 /* Fail because overwrite is not allows. */
5448 return 0;
5449 }
5450 np = np->next;
5451 }
5452 if( x2a->count>=x2a->size ){
5453 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005454 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005455 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005456 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005457 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005458 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005459 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005460 array.ht = (x2node**)&(array.tbl[arrSize]);
5461 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005462 for(i=0; i<x2a->count; i++){
5463 x2node *oldnp, *newnp;
5464 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005465 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005466 newnp = &(array.tbl[i]);
5467 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5468 newnp->next = array.ht[h];
5469 newnp->key = oldnp->key;
5470 newnp->data = oldnp->data;
5471 newnp->from = &(array.ht[h]);
5472 array.ht[h] = newnp;
5473 }
5474 free(x2a->tbl);
5475 *x2a = array;
5476 }
5477 /* Insert the new data */
5478 h = ph & (x2a->size-1);
5479 np = &(x2a->tbl[x2a->count++]);
5480 np->key = key;
5481 np->data = data;
5482 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5483 np->next = x2a->ht[h];
5484 x2a->ht[h] = np;
5485 np->from = &(x2a->ht[h]);
5486 return 1;
5487}
5488
5489/* Return a pointer to data assigned to the given key. Return NULL
5490** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005491struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005492{
drh01f75f22013-10-02 20:46:30 +00005493 unsigned h;
drh75897232000-05-29 14:26:00 +00005494 x2node *np;
5495
5496 if( x2a==0 ) return 0;
5497 h = strhash(key) & (x2a->size-1);
5498 np = x2a->ht[h];
5499 while( np ){
5500 if( strcmp(np->key,key)==0 ) break;
5501 np = np->next;
5502 }
5503 return np ? np->data : 0;
5504}
5505
5506/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005507struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005508{
5509 struct symbol *data;
5510 if( x2a && n>0 && n<=x2a->count ){
5511 data = x2a->tbl[n-1].data;
5512 }else{
5513 data = 0;
5514 }
5515 return data;
5516}
5517
5518/* Return the size of the array */
5519int Symbol_count()
5520{
5521 return x2a ? x2a->count : 0;
5522}
5523
5524/* Return an array of pointers to all data in the table.
5525** The array is obtained from malloc. Return NULL if memory allocation
5526** problems, or if the array is empty. */
5527struct symbol **Symbol_arrayof()
5528{
5529 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005530 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005531 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005532 arrSize = x2a->count;
5533 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005534 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005535 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005536 }
5537 return array;
5538}
5539
5540/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005541int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005542{
icculus9e44cf12010-02-14 17:14:22 +00005543 const struct config *a = (struct config *) _a;
5544 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005545 int x;
5546 x = a->rp->index - b->rp->index;
5547 if( x==0 ) x = a->dot - b->dot;
5548 return x;
5549}
5550
5551/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005552PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005553{
5554 int rc;
5555 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5556 rc = a->rp->index - b->rp->index;
5557 if( rc==0 ) rc = a->dot - b->dot;
5558 }
5559 if( rc==0 ){
5560 if( a ) rc = 1;
5561 if( b ) rc = -1;
5562 }
5563 return rc;
5564}
5565
5566/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005567PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005568{
drh01f75f22013-10-02 20:46:30 +00005569 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005570 while( a ){
5571 h = h*571 + a->rp->index*37 + a->dot;
5572 a = a->bp;
5573 }
5574 return h;
5575}
5576
5577/* Allocate a new state structure */
5578struct state *State_new()
5579{
icculus9e44cf12010-02-14 17:14:22 +00005580 struct state *newstate;
5581 newstate = (struct state *)calloc(1, sizeof(struct state) );
5582 MemoryCheck(newstate);
5583 return newstate;
drh75897232000-05-29 14:26:00 +00005584}
5585
5586/* There is one instance of the following structure for each
5587** associative array of type "x3".
5588*/
5589struct s_x3 {
5590 int size; /* The number of available slots. */
5591 /* Must be a power of 2 greater than or */
5592 /* equal to 1 */
5593 int count; /* Number of currently slots filled */
5594 struct s_x3node *tbl; /* The data stored here */
5595 struct s_x3node **ht; /* Hash table for lookups */
5596};
5597
5598/* There is one instance of this structure for every data element
5599** in an associative array of type "x3".
5600*/
5601typedef struct s_x3node {
5602 struct state *data; /* The data */
5603 struct config *key; /* The key */
5604 struct s_x3node *next; /* Next entry with the same hash */
5605 struct s_x3node **from; /* Previous link */
5606} x3node;
5607
5608/* There is only one instance of the array, which is the following */
5609static struct s_x3 *x3a;
5610
5611/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005612void State_init(void){
drh75897232000-05-29 14:26:00 +00005613 if( x3a ) return;
5614 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5615 if( x3a ){
5616 x3a->size = 128;
5617 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005618 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005619 if( x3a->tbl==0 ){
5620 free(x3a);
5621 x3a = 0;
5622 }else{
5623 int i;
5624 x3a->ht = (x3node**)&(x3a->tbl[128]);
5625 for(i=0; i<128; i++) x3a->ht[i] = 0;
5626 }
5627 }
5628}
5629/* Insert a new record into the array. Return TRUE if successful.
5630** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005631int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005632{
5633 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005634 unsigned h;
5635 unsigned ph;
drh75897232000-05-29 14:26:00 +00005636
5637 if( x3a==0 ) return 0;
5638 ph = statehash(key);
5639 h = ph & (x3a->size-1);
5640 np = x3a->ht[h];
5641 while( np ){
5642 if( statecmp(np->key,key)==0 ){
5643 /* An existing entry with the same key is found. */
5644 /* Fail because overwrite is not allows. */
5645 return 0;
5646 }
5647 np = np->next;
5648 }
5649 if( x3a->count>=x3a->size ){
5650 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005651 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005652 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005653 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005654 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005655 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005656 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005657 array.ht = (x3node**)&(array.tbl[arrSize]);
5658 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005659 for(i=0; i<x3a->count; i++){
5660 x3node *oldnp, *newnp;
5661 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005662 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005663 newnp = &(array.tbl[i]);
5664 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5665 newnp->next = array.ht[h];
5666 newnp->key = oldnp->key;
5667 newnp->data = oldnp->data;
5668 newnp->from = &(array.ht[h]);
5669 array.ht[h] = newnp;
5670 }
5671 free(x3a->tbl);
5672 *x3a = array;
5673 }
5674 /* Insert the new data */
5675 h = ph & (x3a->size-1);
5676 np = &(x3a->tbl[x3a->count++]);
5677 np->key = key;
5678 np->data = data;
5679 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5680 np->next = x3a->ht[h];
5681 x3a->ht[h] = np;
5682 np->from = &(x3a->ht[h]);
5683 return 1;
5684}
5685
5686/* Return a pointer to data assigned to the given key. Return NULL
5687** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005688struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005689{
drh01f75f22013-10-02 20:46:30 +00005690 unsigned h;
drh75897232000-05-29 14:26:00 +00005691 x3node *np;
5692
5693 if( x3a==0 ) return 0;
5694 h = statehash(key) & (x3a->size-1);
5695 np = x3a->ht[h];
5696 while( np ){
5697 if( statecmp(np->key,key)==0 ) break;
5698 np = np->next;
5699 }
5700 return np ? np->data : 0;
5701}
5702
5703/* Return an array of pointers to all data in the table.
5704** The array is obtained from malloc. Return NULL if memory allocation
5705** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005706struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005707{
5708 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005709 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005710 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005711 arrSize = x3a->count;
5712 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005713 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005714 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005715 }
5716 return array;
5717}
5718
5719/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005720PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005721{
drh01f75f22013-10-02 20:46:30 +00005722 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005723 h = h*571 + a->rp->index*37 + a->dot;
5724 return h;
5725}
5726
5727/* There is one instance of the following structure for each
5728** associative array of type "x4".
5729*/
5730struct s_x4 {
5731 int size; /* The number of available slots. */
5732 /* Must be a power of 2 greater than or */
5733 /* equal to 1 */
5734 int count; /* Number of currently slots filled */
5735 struct s_x4node *tbl; /* The data stored here */
5736 struct s_x4node **ht; /* Hash table for lookups */
5737};
5738
5739/* There is one instance of this structure for every data element
5740** in an associative array of type "x4".
5741*/
5742typedef struct s_x4node {
5743 struct config *data; /* The data */
5744 struct s_x4node *next; /* Next entry with the same hash */
5745 struct s_x4node **from; /* Previous link */
5746} x4node;
5747
5748/* There is only one instance of the array, which is the following */
5749static struct s_x4 *x4a;
5750
5751/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005752void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005753 if( x4a ) return;
5754 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5755 if( x4a ){
5756 x4a->size = 64;
5757 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005758 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005759 if( x4a->tbl==0 ){
5760 free(x4a);
5761 x4a = 0;
5762 }else{
5763 int i;
5764 x4a->ht = (x4node**)&(x4a->tbl[64]);
5765 for(i=0; i<64; i++) x4a->ht[i] = 0;
5766 }
5767 }
5768}
5769/* Insert a new record into the array. Return TRUE if successful.
5770** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005771int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005772{
5773 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005774 unsigned h;
5775 unsigned ph;
drh75897232000-05-29 14:26:00 +00005776
5777 if( x4a==0 ) return 0;
5778 ph = confighash(data);
5779 h = ph & (x4a->size-1);
5780 np = x4a->ht[h];
5781 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005782 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005783 /* An existing entry with the same key is found. */
5784 /* Fail because overwrite is not allows. */
5785 return 0;
5786 }
5787 np = np->next;
5788 }
5789 if( x4a->count>=x4a->size ){
5790 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005791 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005792 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005793 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005794 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005795 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005796 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005797 array.ht = (x4node**)&(array.tbl[arrSize]);
5798 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005799 for(i=0; i<x4a->count; i++){
5800 x4node *oldnp, *newnp;
5801 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005802 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005803 newnp = &(array.tbl[i]);
5804 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5805 newnp->next = array.ht[h];
5806 newnp->data = oldnp->data;
5807 newnp->from = &(array.ht[h]);
5808 array.ht[h] = newnp;
5809 }
5810 free(x4a->tbl);
5811 *x4a = array;
5812 }
5813 /* Insert the new data */
5814 h = ph & (x4a->size-1);
5815 np = &(x4a->tbl[x4a->count++]);
5816 np->data = data;
5817 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5818 np->next = x4a->ht[h];
5819 x4a->ht[h] = np;
5820 np->from = &(x4a->ht[h]);
5821 return 1;
5822}
5823
5824/* Return a pointer to data assigned to the given key. Return NULL
5825** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005826struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005827{
5828 int h;
5829 x4node *np;
5830
5831 if( x4a==0 ) return 0;
5832 h = confighash(key) & (x4a->size-1);
5833 np = x4a->ht[h];
5834 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005835 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005836 np = np->next;
5837 }
5838 return np ? np->data : 0;
5839}
5840
5841/* Remove all data from the table. Pass each data to the function "f"
5842** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005843void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005844{
5845 int i;
5846 if( x4a==0 || x4a->count==0 ) return;
5847 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5848 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5849 x4a->count = 0;
5850 return;
5851}