blob: d42584d107e6f32b1428d8a408d6cfe2c487811c [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
drhf5c4e0f2010-07-18 11:35:53 +000051static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000052static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000053
drh87cf1372008-08-13 20:09:06 +000054/*
55** Compilers are getting increasingly pedantic about type conversions
56** as C evolves ever closer to Ada.... To work around the latest problems
57** we have to define the following variant of strlen().
58*/
59#define lemonStrlen(X) ((int)strlen(X))
60
drh898799f2014-01-10 23:21:00 +000061/*
62** Compilers are starting to complain about the use of sprintf() and strcpy(),
63** saying they are unsafe. So we define our own versions of those routines too.
64**
65** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
drh25473362015-09-04 18:03:45 +000066** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
drh898799f2014-01-10 23:21:00 +000067** The third is a helper routine for vsnprintf() that adds texts to the end of a
68** buffer, making sure the buffer is always zero-terminated.
69**
70** The string formatter is a minimal subset of stdlib sprintf() supporting only
71** a few simply conversions:
72**
73** %d
74** %s
75** %.*s
76**
77*/
78static void lemon_addtext(
79 char *zBuf, /* The buffer to which text is added */
80 int *pnUsed, /* Slots of the buffer used so far */
81 const char *zIn, /* Text to add */
drh61f92cd2014-01-11 03:06:18 +000082 int nIn, /* Bytes of text to add. -1 to use strlen() */
83 int iWidth /* Field width. Negative to left justify */
drh898799f2014-01-10 23:21:00 +000084){
85 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
drhecaa9d32014-01-11 03:27:37 +000086 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
drh898799f2014-01-10 23:21:00 +000087 if( nIn==0 ) return;
88 memcpy(&zBuf[*pnUsed], zIn, nIn);
89 *pnUsed += nIn;
drhecaa9d32014-01-11 03:27:37 +000090 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
drh898799f2014-01-10 23:21:00 +000091 zBuf[*pnUsed] = 0;
92}
93static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
mistachkin7a429652014-01-14 10:17:21 +000094 int i, j, k, c;
drh898799f2014-01-10 23:21:00 +000095 int nUsed = 0;
96 const char *z;
97 char zTemp[50];
98 str[0] = 0;
99 for(i=j=0; (c = zFormat[i])!=0; i++){
100 if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000101 int iWidth = 0;
102 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000103 c = zFormat[++i];
drhc56fac72015-10-29 13:48:15 +0000104 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
drh61f92cd2014-01-11 03:06:18 +0000105 if( c=='-' ) i++;
drhc56fac72015-10-29 13:48:15 +0000106 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
drh61f92cd2014-01-11 03:06:18 +0000107 if( c=='-' ) iWidth = -iWidth;
108 c = zFormat[i];
109 }
drh898799f2014-01-10 23:21:00 +0000110 if( c=='d' ){
111 int v = va_arg(ap, int);
112 if( v<0 ){
drh61f92cd2014-01-11 03:06:18 +0000113 lemon_addtext(str, &nUsed, "-", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000114 v = -v;
115 }else if( v==0 ){
drh61f92cd2014-01-11 03:06:18 +0000116 lemon_addtext(str, &nUsed, "0", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000117 }
118 k = 0;
119 while( v>0 ){
120 k++;
121 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
122 v /= 10;
123 }
drh61f92cd2014-01-11 03:06:18 +0000124 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
drh898799f2014-01-10 23:21:00 +0000125 }else if( c=='s' ){
126 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000127 lemon_addtext(str, &nUsed, z, -1, iWidth);
drh898799f2014-01-10 23:21:00 +0000128 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
129 i += 2;
130 k = va_arg(ap, int);
131 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000132 lemon_addtext(str, &nUsed, z, k, iWidth);
drh898799f2014-01-10 23:21:00 +0000133 }else if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000134 lemon_addtext(str, &nUsed, "%", 1, 0);
drh898799f2014-01-10 23:21:00 +0000135 }else{
136 fprintf(stderr, "illegal format\n");
137 exit(1);
138 }
139 j = i+1;
140 }
141 }
drh61f92cd2014-01-11 03:06:18 +0000142 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000143 return nUsed;
144}
145static int lemon_sprintf(char *str, const char *format, ...){
146 va_list ap;
147 int rc;
148 va_start(ap, format);
149 rc = lemon_vsprintf(str, format, ap);
150 va_end(ap);
151 return rc;
152}
153static void lemon_strcpy(char *dest, const char *src){
154 while( (*(dest++) = *(src++))!=0 ){}
155}
156static void lemon_strcat(char *dest, const char *src){
157 while( *dest ) dest++;
158 lemon_strcpy(dest, src);
159}
160
161
icculus9e44cf12010-02-14 17:14:22 +0000162/* a few forward declarations... */
163struct rule;
164struct lemon;
165struct action;
166
drhe9278182007-07-18 18:16:29 +0000167static struct action *Action_new(void);
168static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +0000169
170/********** From the file "build.h" ************************************/
drh14d88552017-04-14 19:44:15 +0000171void FindRulePrecedences(struct lemon*);
172void FindFirstSets(struct lemon*);
173void FindStates(struct lemon*);
174void FindLinks(struct lemon*);
175void FindFollowSets(struct lemon*);
176void FindActions(struct lemon*);
drh75897232000-05-29 14:26:00 +0000177
178/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +0000179void Configlist_init(void);
180struct config *Configlist_add(struct rule *, int);
181struct config *Configlist_addbasis(struct rule *, int);
182void Configlist_closure(struct lemon *);
183void Configlist_sort(void);
184void Configlist_sortbasis(void);
185struct config *Configlist_return(void);
186struct config *Configlist_basis(void);
187void Configlist_eat(struct config *);
188void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +0000189
190/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +0000191void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +0000192
193/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +0000194enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
195 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +0000196struct s_options {
icculus9e44cf12010-02-14 17:14:22 +0000197 enum option_type type;
198 const char *label;
drh75897232000-05-29 14:26:00 +0000199 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000200 const char *message;
drh75897232000-05-29 14:26:00 +0000201};
icculus9e44cf12010-02-14 17:14:22 +0000202int OptInit(char**,struct s_options*,FILE*);
203int OptNArgs(void);
204char *OptArg(int);
205void OptErr(int);
206void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000207
208/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000209void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000210
211/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000212struct plink *Plink_new(void);
213void Plink_add(struct plink **, struct config *);
214void Plink_copy(struct plink **, struct plink *);
215void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000216
217/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000218void Reprint(struct lemon *);
219void ReportOutput(struct lemon *);
220void ReportTable(struct lemon *, int);
221void ReportHeader(struct lemon *);
222void CompressTables(struct lemon *);
223void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000224
225/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000226void SetSize(int); /* All sets will be of size N */
227char *SetNew(void); /* A new set for element 0..N */
228void SetFree(char*); /* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +0000229int SetAdd(char*,int); /* Add element to a set */
230int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000231#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
232
233/********** From the file "struct.h" *************************************/
234/*
235** Principal data structures for the LEMON parser generator.
236*/
237
drhaa9f1122007-08-23 02:50:56 +0000238typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000239
240/* Symbols (terminals and nonterminals) of the grammar are stored
241** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000242enum symbol_type {
243 TERMINAL,
244 NONTERMINAL,
245 MULTITERMINAL
246};
247enum e_assoc {
drh75897232000-05-29 14:26:00 +0000248 LEFT,
249 RIGHT,
250 NONE,
251 UNK
icculus9e44cf12010-02-14 17:14:22 +0000252};
253struct symbol {
254 const char *name; /* Name of the symbol */
255 int index; /* Index number for this symbol */
256 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
257 struct rule *rule; /* Linked list of rules of this (if an NT) */
258 struct symbol *fallback; /* fallback token in case this token doesn't parse */
259 int prec; /* Precedence if defined (-1 otherwise) */
260 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000261 char *firstset; /* First-set for all rules of this symbol */
262 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000263 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000264 char *destructor; /* Code which executes whenever this symbol is
265 ** popped from the stack during error processing */
drh0f832dd2016-08-16 16:46:40 +0000266 int destLineno; /* Line number for start of destructor. Set to
267 ** -1 for duplicate destructors. */
drh75897232000-05-29 14:26:00 +0000268 char *datatype; /* The data type of information held by this
269 ** object. Only used if type==NONTERMINAL */
270 int dtnum; /* The data type number. In the parser, the value
271 ** stack is a union. The .yy%d element of this
272 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000273 /* The following fields are used by MULTITERMINALs only */
274 int nsubsym; /* Number of constituent symbols in the MULTI */
275 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000276};
277
278/* Each production rule in the grammar is stored in the following
279** structure. */
280struct rule {
281 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000282 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000283 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000284 int ruleline; /* Line number for the rule */
285 int nrhs; /* Number of RHS symbols */
286 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000287 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000288 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000289 const char *code; /* The code executed when this rule is reduced */
drh4dd0d3f2016-02-17 01:18:33 +0000290 const char *codePrefix; /* Setup code before code[] above */
291 const char *codeSuffix; /* Breakdown code after code[] above */
drh711c9812016-05-23 14:24:31 +0000292 int noCode; /* True if this rule has no associated C code */
293 int codeEmitted; /* True if the code has been emitted already */
drh75897232000-05-29 14:26:00 +0000294 struct symbol *precsym; /* Precedence symbol for this rule */
295 int index; /* An index number for this rule */
drh4ef07702016-03-16 19:45:54 +0000296 int iRule; /* Rule number as used in the generated tables */
drh75897232000-05-29 14:26:00 +0000297 Boolean canReduce; /* True if this rule is ever reduced */
drh756b41e2016-05-24 18:55:08 +0000298 Boolean doesReduce; /* Reduce actions occur after optimization */
drh75897232000-05-29 14:26:00 +0000299 struct rule *nextlhs; /* Next rule with the same LHS */
300 struct rule *next; /* Next rule in the global list */
301};
302
303/* A configuration is a production rule of the grammar together with
304** a mark (dot) showing how much of that rule has been processed so far.
305** Configurations also contain a follow-set which is a list of terminal
306** symbols which are allowed to immediately follow the end of the rule.
307** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000308enum cfgstatus {
309 COMPLETE,
310 INCOMPLETE
311};
drh75897232000-05-29 14:26:00 +0000312struct config {
313 struct rule *rp; /* The rule upon which the configuration is based */
314 int dot; /* The parse point */
315 char *fws; /* Follow-set for this configuration only */
316 struct plink *fplp; /* Follow-set forward propagation links */
317 struct plink *bplp; /* Follow-set backwards propagation links */
318 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000319 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000320 struct config *next; /* Next configuration in the state */
321 struct config *bp; /* The next basis configuration */
322};
323
icculus9e44cf12010-02-14 17:14:22 +0000324enum e_action {
325 SHIFT,
326 ACCEPT,
327 REDUCE,
328 ERROR,
329 SSCONFLICT, /* A shift/shift conflict */
330 SRCONFLICT, /* Was a reduce, but part of a conflict */
331 RRCONFLICT, /* Was a reduce, but part of a conflict */
332 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
333 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000334 NOT_USED, /* Deleted by compression */
335 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000336};
337
drh75897232000-05-29 14:26:00 +0000338/* Every shift or reduce operation is stored as one of the following */
339struct action {
340 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000341 enum e_action type;
drh75897232000-05-29 14:26:00 +0000342 union {
343 struct state *stp; /* The new state, if a shift */
344 struct rule *rp; /* The rule, if a reduce */
345 } x;
drhc173ad82016-05-23 16:15:02 +0000346 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
drh75897232000-05-29 14:26:00 +0000347 struct action *next; /* Next action for this state */
348 struct action *collide; /* Next action with the same hash */
349};
350
351/* Each state of the generated parser's finite state machine
352** is encoded as an instance of the following structure. */
353struct state {
354 struct config *bp; /* The basis configurations for this state */
355 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000356 int statenum; /* Sequential number for this state */
drh711c9812016-05-23 14:24:31 +0000357 struct action *ap; /* List of actions for this state */
drh8b582012003-10-21 13:16:03 +0000358 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
359 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000360 int iDfltReduce; /* Default action is to REDUCE by this rule */
361 struct rule *pDfltReduce;/* The default REDUCE rule. */
362 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000363};
drh8b582012003-10-21 13:16:03 +0000364#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000365
366/* A followset propagation link indicates that the contents of one
367** configuration followset should be propagated to another whenever
368** the first changes. */
369struct plink {
370 struct config *cfp; /* The configuration to which linked */
371 struct plink *next; /* The next propagate link */
372};
373
374/* The state vector for the entire parser generator is recorded as
375** follows. (LEMON uses no global variables and makes little use of
376** static variables. Fields in the following structure can be thought
377** of as begin global variables in the program.) */
378struct lemon {
379 struct state **sorted; /* Table of states sorted by state number */
380 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000381 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000382 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000383 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000384 int nrule; /* Number of rules */
385 int nsymbol; /* Number of terminal and nonterminal symbols */
386 int nterminal; /* Number of terminal symbols */
drh5c8241b2017-12-24 23:38:10 +0000387 int minShiftReduce; /* Minimum shift-reduce action value */
388 int errAction; /* Error action value */
389 int accAction; /* Accept action value */
390 int noAction; /* No-op action value */
391 int minReduce; /* Minimum reduce action */
392 int maxAction; /* Maximum action value of any kind */
drh75897232000-05-29 14:26:00 +0000393 struct symbol **symbols; /* Sorted array of pointers to symbols */
394 int errorcnt; /* Number of errors */
395 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000396 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000397 char *name; /* Name of the generated parser */
398 char *arg; /* Declaration of the 3th argument to parser */
399 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000400 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000401 char *start; /* Name of the start symbol for the grammar */
402 char *stacksize; /* Size of the parser stack */
403 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000404 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000405 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000406 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000407 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000408 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000409 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000410 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000411 char *filename; /* Name of the input file */
412 char *outname; /* Name of the current output file */
413 char *tokenprefix; /* A prefix added to token names in the .h file */
414 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000415 int nactiontab; /* Number of entries in the yy_action[] table */
drh3a9d6c72017-12-25 04:15:38 +0000416 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
drhc75e0162015-09-07 02:23:02 +0000417 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000418 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000419 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000420 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000421 char *argv0; /* Name of the program */
422};
423
424#define MemoryCheck(X) if((X)==0){ \
425 extern void memory_error(); \
426 memory_error(); \
427}
428
429/**************** From the file "table.h" *********************************/
430/*
431** All code in this file has been automatically generated
432** from a specification in the file
433** "table.q"
434** by the associative array code building program "aagen".
435** Do not edit this file! Instead, edit the specification
436** file, then rerun aagen.
437*/
438/*
439** Code for processing tables in the LEMON parser generator.
440*/
drh75897232000-05-29 14:26:00 +0000441/* Routines for handling a strings */
442
icculus9e44cf12010-02-14 17:14:22 +0000443const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000444
icculus9e44cf12010-02-14 17:14:22 +0000445void Strsafe_init(void);
446int Strsafe_insert(const char *);
447const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000448
449/* Routines for handling symbols of the grammar */
450
icculus9e44cf12010-02-14 17:14:22 +0000451struct symbol *Symbol_new(const char *);
452int Symbolcmpp(const void *, const void *);
453void Symbol_init(void);
454int Symbol_insert(struct symbol *, const char *);
455struct symbol *Symbol_find(const char *);
456struct symbol *Symbol_Nth(int);
457int Symbol_count(void);
458struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000459
460/* Routines to manage the state table */
461
icculus9e44cf12010-02-14 17:14:22 +0000462int Configcmp(const char *, const char *);
463struct state *State_new(void);
464void State_init(void);
465int State_insert(struct state *, struct config *);
466struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000467struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000468
469/* Routines used for efficiency in Configlist_add */
470
icculus9e44cf12010-02-14 17:14:22 +0000471void Configtable_init(void);
472int Configtable_insert(struct config *);
473struct config *Configtable_find(struct config *);
474void Configtable_clear(int(*)(struct config *));
475
drh75897232000-05-29 14:26:00 +0000476/****************** From the file "action.c" *******************************/
477/*
478** Routines processing parser actions in the LEMON parser generator.
479*/
480
481/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000482static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000483 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000484 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000485
486 if( freelist==0 ){
487 int i;
488 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000489 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000490 if( freelist==0 ){
491 fprintf(stderr,"Unable to allocate memory for a new parser action.");
492 exit(1);
493 }
494 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
495 freelist[amt-1].next = 0;
496 }
icculus9e44cf12010-02-14 17:14:22 +0000497 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000498 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000499 return newaction;
drh75897232000-05-29 14:26:00 +0000500}
501
drhe9278182007-07-18 18:16:29 +0000502/* Compare two actions for sorting purposes. Return negative, zero, or
503** positive if the first action is less than, equal to, or greater than
504** the first
505*/
506static int actioncmp(
507 struct action *ap1,
508 struct action *ap2
509){
drh75897232000-05-29 14:26:00 +0000510 int rc;
511 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000512 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000513 rc = (int)ap1->type - (int)ap2->type;
514 }
drh3bd48ab2015-09-07 18:23:37 +0000515 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000516 rc = ap1->x.rp->index - ap2->x.rp->index;
517 }
drhe594bc32009-11-03 13:02:25 +0000518 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000519 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000520 }
drh75897232000-05-29 14:26:00 +0000521 return rc;
522}
523
524/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000525static struct action *Action_sort(
526 struct action *ap
527){
528 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
529 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000530 return ap;
531}
532
icculus9e44cf12010-02-14 17:14:22 +0000533void Action_add(
534 struct action **app,
535 enum e_action type,
536 struct symbol *sp,
537 char *arg
538){
539 struct action *newaction;
540 newaction = Action_new();
541 newaction->next = *app;
542 *app = newaction;
543 newaction->type = type;
544 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000545 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000546 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000547 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000548 }else{
icculus9e44cf12010-02-14 17:14:22 +0000549 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000550 }
551}
drh8b582012003-10-21 13:16:03 +0000552/********************** New code to implement the "acttab" module ***********/
553/*
554** This module implements routines use to construct the yy_action[] table.
555*/
556
557/*
558** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000559** the following structure.
560**
561** The yy_action table maps the pair (state_number, lookahead) into an
562** action_number. The table is an array of integers pairs. The state_number
563** determines an initial offset into the yy_action array. The lookahead
564** value is then added to this initial offset to get an index X into the
565** yy_action array. If the aAction[X].lookahead equals the value of the
566** of the lookahead input, then the value of the action_number output is
567** aAction[X].action. If the lookaheads do not match then the
568** default action for the state_number is returned.
569**
570** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000571** into aLookahead[] using multiple calls to acttab_action(). Then the
572** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000573** array with a single call to acttab_insert(). The acttab_insert() call
574** also resets the aLookahead[] array in preparation for the next
575** state number.
drh8b582012003-10-21 13:16:03 +0000576*/
icculus9e44cf12010-02-14 17:14:22 +0000577struct lookahead_action {
578 int lookahead; /* Value of the lookahead token */
579 int action; /* Action to take on the given lookahead */
580};
drh8b582012003-10-21 13:16:03 +0000581typedef struct acttab acttab;
582struct acttab {
583 int nAction; /* Number of used slots in aAction[] */
584 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000585 struct lookahead_action
586 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000587 *aLookahead; /* A single new transaction set */
588 int mnLookahead; /* Minimum aLookahead[].lookahead */
589 int mnAction; /* Action associated with mnLookahead */
590 int mxLookahead; /* Maximum aLookahead[].lookahead */
591 int nLookahead; /* Used slots in aLookahead[] */
592 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
drh3a9d6c72017-12-25 04:15:38 +0000593 int nterminal; /* Number of terminal symbols */
594 int nsymbol; /* total number of symbols */
drh8b582012003-10-21 13:16:03 +0000595};
596
597/* Return the number of entries in the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +0000598#define acttab_lookahead_size(X) ((X)->nAction)
drh8b582012003-10-21 13:16:03 +0000599
600/* The value for the N-th entry in yy_action */
601#define acttab_yyaction(X,N) ((X)->aAction[N].action)
602
603/* The value for the N-th entry in yy_lookahead */
604#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
605
606/* Free all memory associated with the given acttab */
607void acttab_free(acttab *p){
608 free( p->aAction );
609 free( p->aLookahead );
610 free( p );
611}
612
613/* Allocate a new acttab structure */
drh3a9d6c72017-12-25 04:15:38 +0000614acttab *acttab_alloc(int nsymbol, int nterminal){
icculus9e44cf12010-02-14 17:14:22 +0000615 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000616 if( p==0 ){
617 fprintf(stderr,"Unable to allocate memory for a new acttab.");
618 exit(1);
619 }
620 memset(p, 0, sizeof(*p));
drh3a9d6c72017-12-25 04:15:38 +0000621 p->nsymbol = nsymbol;
622 p->nterminal = nterminal;
drh8b582012003-10-21 13:16:03 +0000623 return p;
624}
625
drh06f60d82017-04-14 19:46:12 +0000626/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000627**
628** This routine is called once for each lookahead for a particular
629** state.
drh8b582012003-10-21 13:16:03 +0000630*/
631void acttab_action(acttab *p, int lookahead, int action){
632 if( p->nLookahead>=p->nLookaheadAlloc ){
633 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000634 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000635 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
636 if( p->aLookahead==0 ){
637 fprintf(stderr,"malloc failed\n");
638 exit(1);
639 }
640 }
641 if( p->nLookahead==0 ){
642 p->mxLookahead = lookahead;
643 p->mnLookahead = lookahead;
644 p->mnAction = action;
645 }else{
646 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
647 if( p->mnLookahead>lookahead ){
648 p->mnLookahead = lookahead;
649 p->mnAction = action;
650 }
651 }
652 p->aLookahead[p->nLookahead].lookahead = lookahead;
653 p->aLookahead[p->nLookahead].action = action;
654 p->nLookahead++;
655}
656
657/*
658** Add the transaction set built up with prior calls to acttab_action()
659** into the current action table. Then reset the transaction set back
660** to an empty set in preparation for a new round of acttab_action() calls.
661**
662** Return the offset into the action table of the new transaction.
drh3a9d6c72017-12-25 04:15:38 +0000663**
664** If the makeItSafe parameter is true, then the offset is chosen so that
665** it is impossible to overread the yy_lookaside[] table regardless of
666** the lookaside token. This is done for the terminal symbols, as they
667** come from external inputs and can contain syntax errors. When makeItSafe
668** is false, there is more flexibility in selecting offsets, resulting in
669** a smaller table. For non-terminal symbols, which are never syntax errors,
670** makeItSafe can be false.
drh8b582012003-10-21 13:16:03 +0000671*/
drh3a9d6c72017-12-25 04:15:38 +0000672int acttab_insert(acttab *p, int makeItSafe){
673 int i, j, k, n, end;
drh8b582012003-10-21 13:16:03 +0000674 assert( p->nLookahead>0 );
675
676 /* Make sure we have enough space to hold the expanded action table
677 ** in the worst case. The worst case occurs if the transaction set
678 ** must be appended to the current action table
679 */
drh3a9d6c72017-12-25 04:15:38 +0000680 n = p->nsymbol + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000681 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000682 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000683 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000684 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000685 sizeof(p->aAction[0])*p->nActionAlloc);
686 if( p->aAction==0 ){
687 fprintf(stderr,"malloc failed\n");
688 exit(1);
689 }
drhfdbf9282003-10-21 16:34:41 +0000690 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000691 p->aAction[i].lookahead = -1;
692 p->aAction[i].action = -1;
693 }
694 }
695
drh06f60d82017-04-14 19:46:12 +0000696 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000697 ** duplicate of the current transaction set. Fall out of the loop
698 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000699 **
700 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
701 */
drh3a9d6c72017-12-25 04:15:38 +0000702 end = makeItSafe ? p->mnLookahead : 0;
703 for(i=p->nAction-1; i>=end; i--){
drhf16371d2009-11-03 19:18:31 +0000704 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000705 /* All lookaheads and actions in the aLookahead[] transaction
706 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000707 if( p->aAction[i].action!=p->mnAction ) continue;
708 for(j=0; j<p->nLookahead; j++){
709 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
710 if( k<0 || k>=p->nAction ) break;
711 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
712 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
713 }
714 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000715
716 /* No possible lookahead value that is not in the aLookahead[]
717 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000718 n = 0;
719 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000720 if( p->aAction[j].lookahead<0 ) continue;
721 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000722 }
drhfdbf9282003-10-21 16:34:41 +0000723 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000724 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000725 }
drh8b582012003-10-21 13:16:03 +0000726 }
727 }
drh8dc3e8f2010-01-07 03:53:03 +0000728
729 /* If no existing offsets exactly match the current transaction, find an
730 ** an empty offset in the aAction[] table in which we can add the
731 ** aLookahead[] transaction.
732 */
drh3a9d6c72017-12-25 04:15:38 +0000733 if( i<end ){
drh8dc3e8f2010-01-07 03:53:03 +0000734 /* Look for holes in the aAction[] table that fit the current
735 ** aLookahead[] transaction. Leave i set to the offset of the hole.
736 ** If no holes are found, i is left at p->nAction, which means the
737 ** transaction will be appended. */
drh3a9d6c72017-12-25 04:15:38 +0000738 i = makeItSafe ? p->mnLookahead : 0;
739 for(; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000740 if( p->aAction[i].lookahead<0 ){
741 for(j=0; j<p->nLookahead; j++){
742 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
743 if( k<0 ) break;
744 if( p->aAction[k].lookahead>=0 ) break;
745 }
746 if( j<p->nLookahead ) continue;
747 for(j=0; j<p->nAction; j++){
748 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
749 }
750 if( j==p->nAction ){
751 break; /* Fits in empty slots */
752 }
753 }
754 }
755 }
drh8b582012003-10-21 13:16:03 +0000756 /* Insert transaction set at index i. */
drh3a9d6c72017-12-25 04:15:38 +0000757#if 0
758 printf("Acttab:");
759 for(j=0; j<p->nLookahead; j++){
760 printf(" %d", p->aLookahead[j].lookahead);
761 }
762 printf(" inserted at %d\n", i);
763#endif
drh8b582012003-10-21 13:16:03 +0000764 for(j=0; j<p->nLookahead; j++){
765 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
766 p->aAction[k] = p->aLookahead[j];
767 if( k>=p->nAction ) p->nAction = k+1;
768 }
drh4396c612017-12-27 15:21:16 +0000769 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
drh8b582012003-10-21 13:16:03 +0000770 p->nLookahead = 0;
771
772 /* Return the offset that is added to the lookahead in order to get the
773 ** index into yy_action of the action */
774 return i - p->mnLookahead;
775}
776
drh3a9d6c72017-12-25 04:15:38 +0000777/*
778** Return the size of the action table without the trailing syntax error
779** entries.
780*/
781int acttab_action_size(acttab *p){
782 int n = p->nAction;
783 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
784 return n;
785}
786
drh75897232000-05-29 14:26:00 +0000787/********************** From the file "build.c" *****************************/
788/*
789** Routines to construction the finite state machine for the LEMON
790** parser generator.
791*/
792
793/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000794**
drh75897232000-05-29 14:26:00 +0000795** Those rules which have a precedence symbol coded in the input
796** grammar using the "[symbol]" construct will already have the
797** rp->precsym field filled. Other rules take as their precedence
798** symbol the first RHS symbol with a defined precedence. If there
799** are not RHS symbols with a defined precedence, the precedence
800** symbol field is left blank.
801*/
icculus9e44cf12010-02-14 17:14:22 +0000802void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000803{
804 struct rule *rp;
805 for(rp=xp->rule; rp; rp=rp->next){
806 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000807 int i, j;
808 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
809 struct symbol *sp = rp->rhs[i];
810 if( sp->type==MULTITERMINAL ){
811 for(j=0; j<sp->nsubsym; j++){
812 if( sp->subsym[j]->prec>=0 ){
813 rp->precsym = sp->subsym[j];
814 break;
815 }
816 }
817 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000818 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000819 }
drh75897232000-05-29 14:26:00 +0000820 }
821 }
822 }
823 return;
824}
825
826/* Find all nonterminals which will generate the empty string.
827** Then go back and compute the first sets of every nonterminal.
828** The first set is the set of all terminal symbols which can begin
829** a string generated by that nonterminal.
830*/
icculus9e44cf12010-02-14 17:14:22 +0000831void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000832{
drhfd405312005-11-06 04:06:59 +0000833 int i, j;
drh75897232000-05-29 14:26:00 +0000834 struct rule *rp;
835 int progress;
836
837 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000838 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000839 }
840 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
841 lemp->symbols[i]->firstset = SetNew();
842 }
843
844 /* First compute all lambdas */
845 do{
846 progress = 0;
847 for(rp=lemp->rule; rp; rp=rp->next){
848 if( rp->lhs->lambda ) continue;
849 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000850 struct symbol *sp = rp->rhs[i];
851 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
852 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000853 }
854 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000855 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000856 progress = 1;
857 }
858 }
859 }while( progress );
860
861 /* Now compute all first sets */
862 do{
863 struct symbol *s1, *s2;
864 progress = 0;
865 for(rp=lemp->rule; rp; rp=rp->next){
866 s1 = rp->lhs;
867 for(i=0; i<rp->nrhs; i++){
868 s2 = rp->rhs[i];
869 if( s2->type==TERMINAL ){
870 progress += SetAdd(s1->firstset,s2->index);
871 break;
drhfd405312005-11-06 04:06:59 +0000872 }else if( s2->type==MULTITERMINAL ){
873 for(j=0; j<s2->nsubsym; j++){
874 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
875 }
876 break;
drhf2f105d2012-08-20 15:53:54 +0000877 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000878 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000879 }else{
drh75897232000-05-29 14:26:00 +0000880 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000881 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000882 }
drh75897232000-05-29 14:26:00 +0000883 }
884 }
885 }while( progress );
886 return;
887}
888
889/* Compute all LR(0) states for the grammar. Links
890** are added to between some states so that the LR(1) follow sets
891** can be computed later.
892*/
icculus9e44cf12010-02-14 17:14:22 +0000893PRIVATE struct state *getstate(struct lemon *); /* forward reference */
894void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000895{
896 struct symbol *sp;
897 struct rule *rp;
898
899 Configlist_init();
900
901 /* Find the start symbol */
902 if( lemp->start ){
903 sp = Symbol_find(lemp->start);
904 if( sp==0 ){
905 ErrorMsg(lemp->filename,0,
906"The specified start symbol \"%s\" is not \
907in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000908symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000909 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000910 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000911 }
912 }else{
drh4ef07702016-03-16 19:45:54 +0000913 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000914 }
915
916 /* Make sure the start symbol doesn't occur on the right-hand side of
917 ** any rule. Report an error if it does. (YACC would generate a new
918 ** start symbol in this case.) */
919 for(rp=lemp->rule; rp; rp=rp->next){
920 int i;
921 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000922 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000923 ErrorMsg(lemp->filename,0,
924"The start symbol \"%s\" occurs on the \
925right-hand side of a rule. This will result in a parser which \
926does not work properly.",sp->name);
927 lemp->errorcnt++;
928 }
929 }
930 }
931
932 /* The basis configuration set for the first state
933 ** is all rules which have the start symbol as their
934 ** left-hand side */
935 for(rp=sp->rule; rp; rp=rp->nextlhs){
936 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000937 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000938 newcfp = Configlist_addbasis(rp,0);
939 SetAdd(newcfp->fws,0);
940 }
941
942 /* Compute the first state. All other states will be
943 ** computed automatically during the computation of the first one.
944 ** The returned pointer to the first state is not used. */
945 (void)getstate(lemp);
946 return;
947}
948
949/* Return a pointer to a state which is described by the configuration
950** list which has been built from calls to Configlist_add.
951*/
icculus9e44cf12010-02-14 17:14:22 +0000952PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
953PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000954{
955 struct config *cfp, *bp;
956 struct state *stp;
957
958 /* Extract the sorted basis of the new state. The basis was constructed
959 ** by prior calls to "Configlist_addbasis()". */
960 Configlist_sortbasis();
961 bp = Configlist_basis();
962
963 /* Get a state with the same basis */
964 stp = State_find(bp);
965 if( stp ){
966 /* A state with the same basis already exists! Copy all the follow-set
967 ** propagation links from the state under construction into the
968 ** preexisting state, then return a pointer to the preexisting state */
969 struct config *x, *y;
970 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
971 Plink_copy(&y->bplp,x->bplp);
972 Plink_delete(x->fplp);
973 x->fplp = x->bplp = 0;
974 }
975 cfp = Configlist_return();
976 Configlist_eat(cfp);
977 }else{
978 /* This really is a new state. Construct all the details */
979 Configlist_closure(lemp); /* Compute the configuration closure */
980 Configlist_sort(); /* Sort the configuration closure */
981 cfp = Configlist_return(); /* Get a pointer to the config list */
982 stp = State_new(); /* A new state structure */
983 MemoryCheck(stp);
984 stp->bp = bp; /* Remember the configuration basis */
985 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000986 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000987 stp->ap = 0; /* No actions, yet. */
988 State_insert(stp,stp->bp); /* Add to the state table */
989 buildshifts(lemp,stp); /* Recursively compute successor states */
990 }
991 return stp;
992}
993
drhfd405312005-11-06 04:06:59 +0000994/*
995** Return true if two symbols are the same.
996*/
icculus9e44cf12010-02-14 17:14:22 +0000997int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000998{
999 int i;
1000 if( a==b ) return 1;
1001 if( a->type!=MULTITERMINAL ) return 0;
1002 if( b->type!=MULTITERMINAL ) return 0;
1003 if( a->nsubsym!=b->nsubsym ) return 0;
1004 for(i=0; i<a->nsubsym; i++){
1005 if( a->subsym[i]!=b->subsym[i] ) return 0;
1006 }
1007 return 1;
1008}
1009
drh75897232000-05-29 14:26:00 +00001010/* Construct all successor states to the given state. A "successor"
1011** state is any state which can be reached by a shift action.
1012*/
icculus9e44cf12010-02-14 17:14:22 +00001013PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +00001014{
1015 struct config *cfp; /* For looping thru the config closure of "stp" */
1016 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +00001017 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +00001018 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1019 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1020 struct state *newstp; /* A pointer to a successor state */
1021
1022 /* Each configuration becomes complete after it contibutes to a successor
1023 ** state. Initially, all configurations are incomplete */
1024 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1025
1026 /* Loop through all configurations of the state "stp" */
1027 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1028 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1029 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1030 Configlist_reset(); /* Reset the new config set */
1031 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1032
1033 /* For every configuration in the state "stp" which has the symbol "sp"
1034 ** following its dot, add the same configuration to the basis set under
1035 ** construction but with the dot shifted one symbol to the right. */
1036 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1037 if( bcfp->status==COMPLETE ) continue; /* Already used */
1038 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1039 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001040 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001041 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001042 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1043 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001044 }
1045
1046 /* Get a pointer to the state described by the basis configuration set
1047 ** constructed in the preceding loop */
1048 newstp = getstate(lemp);
1049
1050 /* The state "newstp" is reached from the state "stp" by a shift action
1051 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001052 if( sp->type==MULTITERMINAL ){
1053 int i;
1054 for(i=0; i<sp->nsubsym; i++){
1055 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1056 }
1057 }else{
1058 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1059 }
drh75897232000-05-29 14:26:00 +00001060 }
1061}
1062
1063/*
1064** Construct the propagation links
1065*/
icculus9e44cf12010-02-14 17:14:22 +00001066void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001067{
1068 int i;
1069 struct config *cfp, *other;
1070 struct state *stp;
1071 struct plink *plp;
1072
1073 /* Housekeeping detail:
1074 ** Add to every propagate link a pointer back to the state to
1075 ** which the link is attached. */
1076 for(i=0; i<lemp->nstate; i++){
1077 stp = lemp->sorted[i];
1078 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1079 cfp->stp = stp;
1080 }
1081 }
1082
1083 /* Convert all backlinks into forward links. Only the forward
1084 ** links are used in the follow-set computation. */
1085 for(i=0; i<lemp->nstate; i++){
1086 stp = lemp->sorted[i];
1087 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1088 for(plp=cfp->bplp; plp; plp=plp->next){
1089 other = plp->cfp;
1090 Plink_add(&other->fplp,cfp);
1091 }
1092 }
1093 }
1094}
1095
1096/* Compute all followsets.
1097**
1098** A followset is the set of all symbols which can come immediately
1099** after a configuration.
1100*/
icculus9e44cf12010-02-14 17:14:22 +00001101void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001102{
1103 int i;
1104 struct config *cfp;
1105 struct plink *plp;
1106 int progress;
1107 int change;
1108
1109 for(i=0; i<lemp->nstate; i++){
1110 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1111 cfp->status = INCOMPLETE;
1112 }
1113 }
drh06f60d82017-04-14 19:46:12 +00001114
drh75897232000-05-29 14:26:00 +00001115 do{
1116 progress = 0;
1117 for(i=0; i<lemp->nstate; i++){
1118 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1119 if( cfp->status==COMPLETE ) continue;
1120 for(plp=cfp->fplp; plp; plp=plp->next){
1121 change = SetUnion(plp->cfp->fws,cfp->fws);
1122 if( change ){
1123 plp->cfp->status = INCOMPLETE;
1124 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001125 }
1126 }
drh75897232000-05-29 14:26:00 +00001127 cfp->status = COMPLETE;
1128 }
1129 }
1130 }while( progress );
1131}
1132
drh3cb2f6e2012-01-09 14:19:05 +00001133static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001134
1135/* Compute the reduce actions, and resolve conflicts.
1136*/
icculus9e44cf12010-02-14 17:14:22 +00001137void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001138{
1139 int i,j;
1140 struct config *cfp;
1141 struct state *stp;
1142 struct symbol *sp;
1143 struct rule *rp;
1144
drh06f60d82017-04-14 19:46:12 +00001145 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001146 ** A reduce action is added for each element of the followset of
1147 ** a configuration which has its dot at the extreme right.
1148 */
1149 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1150 stp = lemp->sorted[i];
1151 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1152 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1153 for(j=0; j<lemp->nterminal; j++){
1154 if( SetFind(cfp->fws,j) ){
1155 /* Add a reduce action to the state "stp" which will reduce by the
1156 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001157 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001158 }
drhf2f105d2012-08-20 15:53:54 +00001159 }
drh75897232000-05-29 14:26:00 +00001160 }
1161 }
1162 }
1163
1164 /* Add the accepting token */
1165 if( lemp->start ){
1166 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001167 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001168 }else{
drh4ef07702016-03-16 19:45:54 +00001169 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001170 }
1171 /* Add to the first state (which is always the starting state of the
1172 ** finite state machine) an action to ACCEPT if the lookahead is the
1173 ** start nonterminal. */
1174 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1175
1176 /* Resolve conflicts */
1177 for(i=0; i<lemp->nstate; i++){
1178 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001179 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001180 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001181 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001182 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001183 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1184 /* The two actions "ap" and "nap" have the same lookahead.
1185 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001186 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001187 }
1188 }
1189 }
1190
1191 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001192 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001193 for(i=0; i<lemp->nstate; i++){
1194 struct action *ap;
1195 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001196 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001197 }
1198 }
1199 for(rp=lemp->rule; rp; rp=rp->next){
1200 if( rp->canReduce ) continue;
1201 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1202 lemp->errorcnt++;
1203 }
1204}
1205
1206/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001207** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001208**
1209** NO LONGER TRUE:
1210** To resolve a conflict, first look to see if either action
1211** is on an error rule. In that case, take the action which
1212** is not associated with the error rule. If neither or both
1213** actions are associated with an error rule, then try to
1214** use precedence to resolve the conflict.
1215**
1216** If either action is a SHIFT, then it must be apx. This
1217** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1218*/
icculus9e44cf12010-02-14 17:14:22 +00001219static int resolve_conflict(
1220 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001221 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001222){
drh75897232000-05-29 14:26:00 +00001223 struct symbol *spx, *spy;
1224 int errcnt = 0;
1225 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001226 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001227 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001228 errcnt++;
1229 }
drh75897232000-05-29 14:26:00 +00001230 if( apx->type==SHIFT && apy->type==REDUCE ){
1231 spx = apx->sp;
1232 spy = apy->x.rp->precsym;
1233 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1234 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001235 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001236 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001237 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001238 apy->type = RD_RESOLVED;
1239 }else if( spx->prec<spy->prec ){
1240 apx->type = SH_RESOLVED;
1241 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1242 apy->type = RD_RESOLVED; /* associativity */
1243 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1244 apx->type = SH_RESOLVED;
1245 }else{
1246 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001247 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001248 }
1249 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1250 spx = apx->x.rp->precsym;
1251 spy = apy->x.rp->precsym;
1252 if( spx==0 || spy==0 || spx->prec<0 ||
1253 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001254 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001255 errcnt++;
1256 }else if( spx->prec>spy->prec ){
1257 apy->type = RD_RESOLVED;
1258 }else if( spx->prec<spy->prec ){
1259 apx->type = RD_RESOLVED;
1260 }
1261 }else{
drh06f60d82017-04-14 19:46:12 +00001262 assert(
drhb59499c2002-02-23 18:45:13 +00001263 apx->type==SH_RESOLVED ||
1264 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001265 apx->type==SSCONFLICT ||
1266 apx->type==SRCONFLICT ||
1267 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001268 apy->type==SH_RESOLVED ||
1269 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001270 apy->type==SSCONFLICT ||
1271 apy->type==SRCONFLICT ||
1272 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001273 );
1274 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1275 ** REDUCEs on the list. If we reach this point it must be because
1276 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001277 }
1278 return errcnt;
1279}
1280/********************* From the file "configlist.c" *************************/
1281/*
1282** Routines to processing a configuration list and building a state
1283** in the LEMON parser generator.
1284*/
1285
1286static struct config *freelist = 0; /* List of free configurations */
1287static struct config *current = 0; /* Top of list of configurations */
1288static struct config **currentend = 0; /* Last on list of configs */
1289static struct config *basis = 0; /* Top of list of basis configs */
1290static struct config **basisend = 0; /* End of list of basis configs */
1291
1292/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001293PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001294 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001295 if( freelist==0 ){
1296 int i;
1297 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001298 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001299 if( freelist==0 ){
1300 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1301 exit(1);
1302 }
1303 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1304 freelist[amt-1].next = 0;
1305 }
icculus9e44cf12010-02-14 17:14:22 +00001306 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001307 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001308 return newcfg;
drh75897232000-05-29 14:26:00 +00001309}
1310
1311/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001312PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001313{
1314 old->next = freelist;
1315 freelist = old;
1316}
1317
1318/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001319void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001320 current = 0;
1321 currentend = &current;
1322 basis = 0;
1323 basisend = &basis;
1324 Configtable_init();
1325 return;
1326}
1327
1328/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001329void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001330 current = 0;
1331 currentend = &current;
1332 basis = 0;
1333 basisend = &basis;
1334 Configtable_clear(0);
1335 return;
1336}
1337
1338/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001339struct config *Configlist_add(
1340 struct rule *rp, /* The rule */
1341 int dot /* Index into the RHS of the rule where the dot goes */
1342){
drh75897232000-05-29 14:26:00 +00001343 struct config *cfp, model;
1344
1345 assert( currentend!=0 );
1346 model.rp = rp;
1347 model.dot = dot;
1348 cfp = Configtable_find(&model);
1349 if( cfp==0 ){
1350 cfp = newconfig();
1351 cfp->rp = rp;
1352 cfp->dot = dot;
1353 cfp->fws = SetNew();
1354 cfp->stp = 0;
1355 cfp->fplp = cfp->bplp = 0;
1356 cfp->next = 0;
1357 cfp->bp = 0;
1358 *currentend = cfp;
1359 currentend = &cfp->next;
1360 Configtable_insert(cfp);
1361 }
1362 return cfp;
1363}
1364
1365/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001366struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001367{
1368 struct config *cfp, model;
1369
1370 assert( basisend!=0 );
1371 assert( currentend!=0 );
1372 model.rp = rp;
1373 model.dot = dot;
1374 cfp = Configtable_find(&model);
1375 if( cfp==0 ){
1376 cfp = newconfig();
1377 cfp->rp = rp;
1378 cfp->dot = dot;
1379 cfp->fws = SetNew();
1380 cfp->stp = 0;
1381 cfp->fplp = cfp->bplp = 0;
1382 cfp->next = 0;
1383 cfp->bp = 0;
1384 *currentend = cfp;
1385 currentend = &cfp->next;
1386 *basisend = cfp;
1387 basisend = &cfp->bp;
1388 Configtable_insert(cfp);
1389 }
1390 return cfp;
1391}
1392
1393/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001394void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001395{
1396 struct config *cfp, *newcfp;
1397 struct rule *rp, *newrp;
1398 struct symbol *sp, *xsp;
1399 int i, dot;
1400
1401 assert( currentend!=0 );
1402 for(cfp=current; cfp; cfp=cfp->next){
1403 rp = cfp->rp;
1404 dot = cfp->dot;
1405 if( dot>=rp->nrhs ) continue;
1406 sp = rp->rhs[dot];
1407 if( sp->type==NONTERMINAL ){
1408 if( sp->rule==0 && sp!=lemp->errsym ){
1409 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1410 sp->name);
1411 lemp->errorcnt++;
1412 }
1413 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1414 newcfp = Configlist_add(newrp,0);
1415 for(i=dot+1; i<rp->nrhs; i++){
1416 xsp = rp->rhs[i];
1417 if( xsp->type==TERMINAL ){
1418 SetAdd(newcfp->fws,xsp->index);
1419 break;
drhfd405312005-11-06 04:06:59 +00001420 }else if( xsp->type==MULTITERMINAL ){
1421 int k;
1422 for(k=0; k<xsp->nsubsym; k++){
1423 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1424 }
1425 break;
drhf2f105d2012-08-20 15:53:54 +00001426 }else{
drh75897232000-05-29 14:26:00 +00001427 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001428 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001429 }
1430 }
drh75897232000-05-29 14:26:00 +00001431 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1432 }
1433 }
1434 }
1435 return;
1436}
1437
1438/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001439void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001440 current = (struct config*)msort((char*)current,(char**)&(current->next),
1441 Configcmp);
drh75897232000-05-29 14:26:00 +00001442 currentend = 0;
1443 return;
1444}
1445
1446/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001447void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001448 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1449 Configcmp);
drh75897232000-05-29 14:26:00 +00001450 basisend = 0;
1451 return;
1452}
1453
1454/* Return a pointer to the head of the configuration list and
1455** reset the list */
drh14d88552017-04-14 19:44:15 +00001456struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001457 struct config *old;
1458 old = current;
1459 current = 0;
1460 currentend = 0;
1461 return old;
1462}
1463
1464/* Return a pointer to the head of the configuration list and
1465** reset the list */
drh14d88552017-04-14 19:44:15 +00001466struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001467 struct config *old;
1468 old = basis;
1469 basis = 0;
1470 basisend = 0;
1471 return old;
1472}
1473
1474/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001475void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001476{
1477 struct config *nextcfp;
1478 for(; cfp; cfp=nextcfp){
1479 nextcfp = cfp->next;
1480 assert( cfp->fplp==0 );
1481 assert( cfp->bplp==0 );
1482 if( cfp->fws ) SetFree(cfp->fws);
1483 deleteconfig(cfp);
1484 }
1485 return;
1486}
1487/***************** From the file "error.c" *********************************/
1488/*
1489** Code for printing error message.
1490*/
1491
drhf9a2e7b2003-04-15 01:49:48 +00001492void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001493 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001494 fprintf(stderr, "%s:%d: ", filename, lineno);
1495 va_start(ap, format);
1496 vfprintf(stderr,format,ap);
1497 va_end(ap);
1498 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001499}
1500/**************** From the file "main.c" ************************************/
1501/*
1502** Main program file for the LEMON parser generator.
1503*/
1504
1505/* Report an out-of-memory condition and abort. This function
1506** is used mostly by the "MemoryCheck" macro in struct.h
1507*/
drh14d88552017-04-14 19:44:15 +00001508void memory_error(void){
drh75897232000-05-29 14:26:00 +00001509 fprintf(stderr,"Out of memory. Aborting...\n");
1510 exit(1);
1511}
1512
drh6d08b4d2004-07-20 12:45:22 +00001513static int nDefine = 0; /* Number of -D options on the command line */
1514static char **azDefine = 0; /* Name of the -D macros */
1515
1516/* This routine is called with the argument to each -D command-line option.
1517** Add the macro defined to the azDefine array.
1518*/
1519static void handle_D_option(char *z){
1520 char **paz;
1521 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001522 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001523 if( azDefine==0 ){
1524 fprintf(stderr,"out of memory\n");
1525 exit(1);
1526 }
1527 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001528 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001529 if( *paz==0 ){
1530 fprintf(stderr,"out of memory\n");
1531 exit(1);
1532 }
drh898799f2014-01-10 23:21:00 +00001533 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001534 for(z=*paz; *z && *z!='='; z++){}
1535 *z = 0;
1536}
1537
icculus3e143bd2010-02-14 00:48:49 +00001538static char *user_templatename = NULL;
1539static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001540 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001541 if( user_templatename==0 ){
1542 memory_error();
1543 }
drh898799f2014-01-10 23:21:00 +00001544 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001545}
drh75897232000-05-29 14:26:00 +00001546
drh711c9812016-05-23 14:24:31 +00001547/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001548static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1549 struct rule *pFirst = 0;
1550 struct rule **ppPrev = &pFirst;
1551 while( pA && pB ){
1552 if( pA->iRule<pB->iRule ){
1553 *ppPrev = pA;
1554 ppPrev = &pA->next;
1555 pA = pA->next;
1556 }else{
1557 *ppPrev = pB;
1558 ppPrev = &pB->next;
1559 pB = pB->next;
1560 }
1561 }
1562 if( pA ){
1563 *ppPrev = pA;
1564 }else{
1565 *ppPrev = pB;
1566 }
1567 return pFirst;
1568}
1569
1570/*
1571** Sort a list of rules in order of increasing iRule value
1572*/
1573static struct rule *Rule_sort(struct rule *rp){
1574 int i;
1575 struct rule *pNext;
1576 struct rule *x[32];
1577 memset(x, 0, sizeof(x));
1578 while( rp ){
1579 pNext = rp->next;
1580 rp->next = 0;
1581 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1582 rp = Rule_merge(x[i], rp);
1583 x[i] = 0;
1584 }
1585 x[i] = rp;
1586 rp = pNext;
1587 }
1588 rp = 0;
1589 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1590 rp = Rule_merge(x[i], rp);
1591 }
1592 return rp;
1593}
1594
drhc75e0162015-09-07 02:23:02 +00001595/* forward reference */
1596static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1597
1598/* Print a single line of the "Parser Stats" output
1599*/
1600static void stats_line(const char *zLabel, int iValue){
1601 int nLabel = lemonStrlen(zLabel);
1602 printf(" %s%.*s %5d\n", zLabel,
1603 35-nLabel, "................................",
1604 iValue);
1605}
1606
drh75897232000-05-29 14:26:00 +00001607/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001608int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001609{
1610 static int version = 0;
1611 static int rpflag = 0;
1612 static int basisflag = 0;
1613 static int compress = 0;
1614 static int quiet = 0;
1615 static int statistics = 0;
1616 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001617 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001618 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001619 static struct s_options options[] = {
1620 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1621 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001622 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001623 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001624 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001625 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001626 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1627 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001628 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001629 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1630 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001631 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001632 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001633 {OPT_FLAG, "s", (char*)&statistics,
1634 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001635 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001636 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1637 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001638 {OPT_FLAG,0,0,0}
1639 };
1640 int i;
icculus42585cf2010-02-14 05:19:56 +00001641 int exitcode;
drh75897232000-05-29 14:26:00 +00001642 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001643 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001644
drhb0c86772000-06-02 23:21:26 +00001645 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001646 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001647 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001648 exit(0);
drh75897232000-05-29 14:26:00 +00001649 }
drhb0c86772000-06-02 23:21:26 +00001650 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001651 fprintf(stderr,"Exactly one filename argument is required.\n");
1652 exit(1);
1653 }
drh954f6b42006-06-13 13:27:46 +00001654 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001655 lem.errorcnt = 0;
1656
1657 /* Initialize the machine */
1658 Strsafe_init();
1659 Symbol_init();
1660 State_init();
1661 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001662 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001663 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001664 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001665 Symbol_new("$");
drh75897232000-05-29 14:26:00 +00001666
1667 /* Parse the input file */
1668 Parse(&lem);
1669 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001670 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001671 fprintf(stderr,"Empty grammar.\n");
1672 exit(1);
1673 }
drhed0c15b2018-04-16 14:31:34 +00001674 lem.errsym = Symbol_find("error");
drh75897232000-05-29 14:26:00 +00001675
1676 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001677 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001678 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001679 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001680 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1681 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1682 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1683 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1684 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1685 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001686 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001687 lem.nterminal = i;
1688
drh711c9812016-05-23 14:24:31 +00001689 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1690 ** reduce action C-code associated with them last, so that the switch()
1691 ** statement that selects reduction actions will have a smaller jump table.
1692 */
drh4ef07702016-03-16 19:45:54 +00001693 for(i=0, rp=lem.rule; rp; rp=rp->next){
1694 rp->iRule = rp->code ? i++ : -1;
1695 }
1696 for(rp=lem.rule; rp; rp=rp->next){
1697 if( rp->iRule<0 ) rp->iRule = i++;
1698 }
1699 lem.startRule = lem.rule;
1700 lem.rule = Rule_sort(lem.rule);
1701
drh75897232000-05-29 14:26:00 +00001702 /* Generate a reprint of the grammar, if requested on the command line */
1703 if( rpflag ){
1704 Reprint(&lem);
1705 }else{
1706 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001707 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001708
1709 /* Find the precedence for every production rule (that has one) */
1710 FindRulePrecedences(&lem);
1711
1712 /* Compute the lambda-nonterminals and the first-sets for every
1713 ** nonterminal */
1714 FindFirstSets(&lem);
1715
1716 /* Compute all LR(0) states. Also record follow-set propagation
1717 ** links so that the follow-set can be computed later */
1718 lem.nstate = 0;
1719 FindStates(&lem);
1720 lem.sorted = State_arrayof();
1721
1722 /* Tie up loose ends on the propagation links */
1723 FindLinks(&lem);
1724
1725 /* Compute the follow set of every reducible configuration */
1726 FindFollowSets(&lem);
1727
1728 /* Compute the action tables */
1729 FindActions(&lem);
1730
1731 /* Compress the action tables */
1732 if( compress==0 ) CompressTables(&lem);
1733
drhada354d2005-11-05 15:03:59 +00001734 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001735 ** occur at the end. This is an optimization that helps make the
1736 ** generated parser tables smaller. */
1737 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001738
drh75897232000-05-29 14:26:00 +00001739 /* Generate a report of the parser generated. (the "y.output" file) */
1740 if( !quiet ) ReportOutput(&lem);
1741
1742 /* Generate the source code for the parser */
1743 ReportTable(&lem, mhflag);
1744
1745 /* Produce a header file for use by the scanner. (This step is
1746 ** omitted if the "-m" option is used because makeheaders will
1747 ** generate the file for us.) */
1748 if( !mhflag ) ReportHeader(&lem);
1749 }
1750 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001751 printf("Parser statistics:\n");
1752 stats_line("terminal symbols", lem.nterminal);
1753 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1754 stats_line("total symbols", lem.nsymbol);
1755 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001756 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001757 stats_line("conflicts", lem.nconflict);
1758 stats_line("action table entries", lem.nactiontab);
drh3a9d6c72017-12-25 04:15:38 +00001759 stats_line("lookahead table entries", lem.nlookaheadtab);
drhc75e0162015-09-07 02:23:02 +00001760 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001761 }
icculus8e158022010-02-16 16:09:03 +00001762 if( lem.nconflict > 0 ){
1763 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001764 }
1765
1766 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001767 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001768 exit(exitcode);
1769 return (exitcode);
drh75897232000-05-29 14:26:00 +00001770}
1771/******************** From the file "msort.c" *******************************/
1772/*
1773** A generic merge-sort program.
1774**
1775** USAGE:
1776** Let "ptr" be a pointer to some structure which is at the head of
1777** a null-terminated list. Then to sort the list call:
1778**
1779** ptr = msort(ptr,&(ptr->next),cmpfnc);
1780**
1781** In the above, "cmpfnc" is a pointer to a function which compares
1782** two instances of the structure and returns an integer, as in
1783** strcmp. The second argument is a pointer to the pointer to the
1784** second element of the linked list. This address is used to compute
1785** the offset to the "next" field within the structure. The offset to
1786** the "next" field must be constant for all structures in the list.
1787**
1788** The function returns a new pointer which is the head of the list
1789** after sorting.
1790**
1791** ALGORITHM:
1792** Merge-sort.
1793*/
1794
1795/*
1796** Return a pointer to the next structure in the linked list.
1797*/
drhd25d6922012-04-18 09:59:56 +00001798#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001799
1800/*
1801** Inputs:
1802** a: A sorted, null-terminated linked list. (May be null).
1803** b: A sorted, null-terminated linked list. (May be null).
1804** cmp: A pointer to the comparison function.
1805** offset: Offset in the structure to the "next" field.
1806**
1807** Return Value:
1808** A pointer to the head of a sorted list containing the elements
1809** of both a and b.
1810**
1811** Side effects:
1812** The "next" pointers for elements in the lists a and b are
1813** changed.
1814*/
drhe9278182007-07-18 18:16:29 +00001815static char *merge(
1816 char *a,
1817 char *b,
1818 int (*cmp)(const char*,const char*),
1819 int offset
1820){
drh75897232000-05-29 14:26:00 +00001821 char *ptr, *head;
1822
1823 if( a==0 ){
1824 head = b;
1825 }else if( b==0 ){
1826 head = a;
1827 }else{
drhe594bc32009-11-03 13:02:25 +00001828 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001829 ptr = a;
1830 a = NEXT(a);
1831 }else{
1832 ptr = b;
1833 b = NEXT(b);
1834 }
1835 head = ptr;
1836 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001837 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001838 NEXT(ptr) = a;
1839 ptr = a;
1840 a = NEXT(a);
1841 }else{
1842 NEXT(ptr) = b;
1843 ptr = b;
1844 b = NEXT(b);
1845 }
1846 }
1847 if( a ) NEXT(ptr) = a;
1848 else NEXT(ptr) = b;
1849 }
1850 return head;
1851}
1852
1853/*
1854** Inputs:
1855** list: Pointer to a singly-linked list of structures.
1856** next: Pointer to pointer to the second element of the list.
1857** cmp: A comparison function.
1858**
1859** Return Value:
1860** A pointer to the head of a sorted list containing the elements
1861** orginally in list.
1862**
1863** Side effects:
1864** The "next" pointers for elements in list are changed.
1865*/
1866#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001867static char *msort(
1868 char *list,
1869 char **next,
1870 int (*cmp)(const char*,const char*)
1871){
drhba99af52001-10-25 20:37:16 +00001872 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001873 char *ep;
1874 char *set[LISTSIZE];
1875 int i;
drh1cc0d112015-03-31 15:15:48 +00001876 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001877 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1878 while( list ){
1879 ep = list;
1880 list = NEXT(list);
1881 NEXT(ep) = 0;
1882 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1883 ep = merge(ep,set[i],cmp,offset);
1884 set[i] = 0;
1885 }
1886 set[i] = ep;
1887 }
1888 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001889 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001890 return ep;
1891}
1892/************************ From the file "option.c" **************************/
1893static char **argv;
1894static struct s_options *op;
1895static FILE *errstream;
1896
1897#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1898
1899/*
1900** Print the command line with a carrot pointing to the k-th character
1901** of the n-th field.
1902*/
icculus9e44cf12010-02-14 17:14:22 +00001903static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001904{
1905 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001906 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001907 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001908 for(i=1; i<n && argv[i]; i++){
1909 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001910 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001911 }
1912 spcnt += k;
1913 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1914 if( spcnt<20 ){
1915 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1916 }else{
1917 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1918 }
1919}
1920
1921/*
1922** Return the index of the N-th non-switch argument. Return -1
1923** if N is out of range.
1924*/
icculus9e44cf12010-02-14 17:14:22 +00001925static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001926{
1927 int i;
1928 int dashdash = 0;
1929 if( argv!=0 && *argv!=0 ){
1930 for(i=1; argv[i]; i++){
1931 if( dashdash || !ISOPT(argv[i]) ){
1932 if( n==0 ) return i;
1933 n--;
1934 }
1935 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1936 }
1937 }
1938 return -1;
1939}
1940
1941static char emsg[] = "Command line syntax error: ";
1942
1943/*
1944** Process a flag command line argument.
1945*/
icculus9e44cf12010-02-14 17:14:22 +00001946static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001947{
1948 int v;
1949 int errcnt = 0;
1950 int j;
1951 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001952 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001953 }
1954 v = argv[i][0]=='-' ? 1 : 0;
1955 if( op[j].label==0 ){
1956 if( err ){
1957 fprintf(err,"%sundefined option.\n",emsg);
1958 errline(i,1,err);
1959 }
1960 errcnt++;
drh0325d392015-01-01 19:11:22 +00001961 }else if( op[j].arg==0 ){
1962 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001963 }else if( op[j].type==OPT_FLAG ){
1964 *((int*)op[j].arg) = v;
1965 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001966 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001967 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001968 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001969 }else{
1970 if( err ){
1971 fprintf(err,"%smissing argument on switch.\n",emsg);
1972 errline(i,1,err);
1973 }
1974 errcnt++;
1975 }
1976 return errcnt;
1977}
1978
1979/*
1980** Process a command line switch which has an argument.
1981*/
icculus9e44cf12010-02-14 17:14:22 +00001982static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001983{
1984 int lv = 0;
1985 double dv = 0.0;
1986 char *sv = 0, *end;
1987 char *cp;
1988 int j;
1989 int errcnt = 0;
1990 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001991 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001992 *cp = 0;
1993 for(j=0; op[j].label; j++){
1994 if( strcmp(argv[i],op[j].label)==0 ) break;
1995 }
1996 *cp = '=';
1997 if( op[j].label==0 ){
1998 if( err ){
1999 fprintf(err,"%sundefined option.\n",emsg);
2000 errline(i,0,err);
2001 }
2002 errcnt++;
2003 }else{
2004 cp++;
2005 switch( op[j].type ){
2006 case OPT_FLAG:
2007 case OPT_FFLAG:
2008 if( err ){
2009 fprintf(err,"%soption requires an argument.\n",emsg);
2010 errline(i,0,err);
2011 }
2012 errcnt++;
2013 break;
2014 case OPT_DBL:
2015 case OPT_FDBL:
2016 dv = strtod(cp,&end);
2017 if( *end ){
2018 if( err ){
drh25473362015-09-04 18:03:45 +00002019 fprintf(err,
2020 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00002021 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002022 }
2023 errcnt++;
2024 }
2025 break;
2026 case OPT_INT:
2027 case OPT_FINT:
2028 lv = strtol(cp,&end,0);
2029 if( *end ){
2030 if( err ){
2031 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00002032 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002033 }
2034 errcnt++;
2035 }
2036 break;
2037 case OPT_STR:
2038 case OPT_FSTR:
2039 sv = cp;
2040 break;
2041 }
2042 switch( op[j].type ){
2043 case OPT_FLAG:
2044 case OPT_FFLAG:
2045 break;
2046 case OPT_DBL:
2047 *(double*)(op[j].arg) = dv;
2048 break;
2049 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002050 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002051 break;
2052 case OPT_INT:
2053 *(int*)(op[j].arg) = lv;
2054 break;
2055 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002056 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002057 break;
2058 case OPT_STR:
2059 *(char**)(op[j].arg) = sv;
2060 break;
2061 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002062 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002063 break;
2064 }
2065 }
2066 return errcnt;
2067}
2068
icculus9e44cf12010-02-14 17:14:22 +00002069int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002070{
2071 int errcnt = 0;
2072 argv = a;
2073 op = o;
2074 errstream = err;
2075 if( argv && *argv && op ){
2076 int i;
2077 for(i=1; argv[i]; i++){
2078 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2079 errcnt += handleflags(i,err);
2080 }else if( strchr(argv[i],'=') ){
2081 errcnt += handleswitch(i,err);
2082 }
2083 }
2084 }
2085 if( errcnt>0 ){
2086 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002087 OptPrint();
drh75897232000-05-29 14:26:00 +00002088 exit(1);
2089 }
2090 return 0;
2091}
2092
drh14d88552017-04-14 19:44:15 +00002093int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002094 int cnt = 0;
2095 int dashdash = 0;
2096 int i;
2097 if( argv!=0 && argv[0]!=0 ){
2098 for(i=1; argv[i]; i++){
2099 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2100 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2101 }
2102 }
2103 return cnt;
2104}
2105
icculus9e44cf12010-02-14 17:14:22 +00002106char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002107{
2108 int i;
2109 i = argindex(n);
2110 return i>=0 ? argv[i] : 0;
2111}
2112
icculus9e44cf12010-02-14 17:14:22 +00002113void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002114{
2115 int i;
2116 i = argindex(n);
2117 if( i>=0 ) errline(i,0,errstream);
2118}
2119
drh14d88552017-04-14 19:44:15 +00002120void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002121 int i;
2122 int max, len;
2123 max = 0;
2124 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002125 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002126 switch( op[i].type ){
2127 case OPT_FLAG:
2128 case OPT_FFLAG:
2129 break;
2130 case OPT_INT:
2131 case OPT_FINT:
2132 len += 9; /* length of "<integer>" */
2133 break;
2134 case OPT_DBL:
2135 case OPT_FDBL:
2136 len += 6; /* length of "<real>" */
2137 break;
2138 case OPT_STR:
2139 case OPT_FSTR:
2140 len += 8; /* length of "<string>" */
2141 break;
2142 }
2143 if( len>max ) max = len;
2144 }
2145 for(i=0; op[i].label; i++){
2146 switch( op[i].type ){
2147 case OPT_FLAG:
2148 case OPT_FFLAG:
2149 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2150 break;
2151 case OPT_INT:
2152 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002153 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002154 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002155 break;
2156 case OPT_DBL:
2157 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002158 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002159 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002160 break;
2161 case OPT_STR:
2162 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002163 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002164 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002165 break;
2166 }
2167 }
2168}
2169/*********************** From the file "parse.c" ****************************/
2170/*
2171** Input file parser for the LEMON parser generator.
2172*/
2173
2174/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002175enum e_state {
2176 INITIALIZE,
2177 WAITING_FOR_DECL_OR_RULE,
2178 WAITING_FOR_DECL_KEYWORD,
2179 WAITING_FOR_DECL_ARG,
2180 WAITING_FOR_PRECEDENCE_SYMBOL,
2181 WAITING_FOR_ARROW,
2182 IN_RHS,
2183 LHS_ALIAS_1,
2184 LHS_ALIAS_2,
2185 LHS_ALIAS_3,
2186 RHS_ALIAS_1,
2187 RHS_ALIAS_2,
2188 PRECEDENCE_MARK_1,
2189 PRECEDENCE_MARK_2,
2190 RESYNC_AFTER_RULE_ERROR,
2191 RESYNC_AFTER_DECL_ERROR,
2192 WAITING_FOR_DESTRUCTOR_SYMBOL,
2193 WAITING_FOR_DATATYPE_SYMBOL,
2194 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002195 WAITING_FOR_WILDCARD_ID,
2196 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002197 WAITING_FOR_CLASS_TOKEN,
2198 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002199};
drh75897232000-05-29 14:26:00 +00002200struct pstate {
2201 char *filename; /* Name of the input file */
2202 int tokenlineno; /* Linenumber at which current token starts */
2203 int errorcnt; /* Number of errors so far */
2204 char *tokenstart; /* Text of current token */
2205 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002206 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002207 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002208 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002209 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002210 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002211 int nrhs; /* Number of right-hand side symbols seen */
2212 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002213 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002214 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002215 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002216 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002217 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002218 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002219 enum e_assoc declassoc; /* Assign this association to decl arguments */
2220 int preccounter; /* Assign this precedence to decl arguments */
2221 struct rule *firstrule; /* Pointer to first rule in the grammar */
2222 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2223};
2224
2225/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002226static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002227{
icculus9e44cf12010-02-14 17:14:22 +00002228 const char *x;
drh75897232000-05-29 14:26:00 +00002229 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2230#if 0
2231 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2232 x,psp->state);
2233#endif
2234 switch( psp->state ){
2235 case INITIALIZE:
2236 psp->prevrule = 0;
2237 psp->preccounter = 0;
2238 psp->firstrule = psp->lastrule = 0;
2239 psp->gp->nrule = 0;
2240 /* Fall thru to next case */
2241 case WAITING_FOR_DECL_OR_RULE:
2242 if( x[0]=='%' ){
2243 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002244 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002245 psp->lhs = Symbol_new(x);
2246 psp->nrhs = 0;
2247 psp->lhsalias = 0;
2248 psp->state = WAITING_FOR_ARROW;
2249 }else if( x[0]=='{' ){
2250 if( psp->prevrule==0 ){
2251 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002252"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002253fragment which begins on this line.");
2254 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002255 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002256 ErrorMsg(psp->filename,psp->tokenlineno,
2257"Code fragment beginning on this line is not the first \
2258to follow the previous rule.");
2259 psp->errorcnt++;
2260 }else{
2261 psp->prevrule->line = psp->tokenlineno;
2262 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002263 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002264 }
drh75897232000-05-29 14:26:00 +00002265 }else if( x[0]=='[' ){
2266 psp->state = PRECEDENCE_MARK_1;
2267 }else{
2268 ErrorMsg(psp->filename,psp->tokenlineno,
2269 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2270 x);
2271 psp->errorcnt++;
2272 }
2273 break;
2274 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002275 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002276 ErrorMsg(psp->filename,psp->tokenlineno,
2277 "The precedence symbol must be a terminal.");
2278 psp->errorcnt++;
2279 }else if( psp->prevrule==0 ){
2280 ErrorMsg(psp->filename,psp->tokenlineno,
2281 "There is no prior rule to assign precedence \"[%s]\".",x);
2282 psp->errorcnt++;
2283 }else if( psp->prevrule->precsym!=0 ){
2284 ErrorMsg(psp->filename,psp->tokenlineno,
2285"Precedence mark on this line is not the first \
2286to follow the previous rule.");
2287 psp->errorcnt++;
2288 }else{
2289 psp->prevrule->precsym = Symbol_new(x);
2290 }
2291 psp->state = PRECEDENCE_MARK_2;
2292 break;
2293 case PRECEDENCE_MARK_2:
2294 if( x[0]!=']' ){
2295 ErrorMsg(psp->filename,psp->tokenlineno,
2296 "Missing \"]\" on precedence mark.");
2297 psp->errorcnt++;
2298 }
2299 psp->state = WAITING_FOR_DECL_OR_RULE;
2300 break;
2301 case WAITING_FOR_ARROW:
2302 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2303 psp->state = IN_RHS;
2304 }else if( x[0]=='(' ){
2305 psp->state = LHS_ALIAS_1;
2306 }else{
2307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "Expected to see a \":\" following the LHS symbol \"%s\".",
2309 psp->lhs->name);
2310 psp->errorcnt++;
2311 psp->state = RESYNC_AFTER_RULE_ERROR;
2312 }
2313 break;
2314 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002315 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002316 psp->lhsalias = x;
2317 psp->state = LHS_ALIAS_2;
2318 }else{
2319 ErrorMsg(psp->filename,psp->tokenlineno,
2320 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2321 x,psp->lhs->name);
2322 psp->errorcnt++;
2323 psp->state = RESYNC_AFTER_RULE_ERROR;
2324 }
2325 break;
2326 case LHS_ALIAS_2:
2327 if( x[0]==')' ){
2328 psp->state = LHS_ALIAS_3;
2329 }else{
2330 ErrorMsg(psp->filename,psp->tokenlineno,
2331 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2332 psp->errorcnt++;
2333 psp->state = RESYNC_AFTER_RULE_ERROR;
2334 }
2335 break;
2336 case LHS_ALIAS_3:
2337 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2338 psp->state = IN_RHS;
2339 }else{
2340 ErrorMsg(psp->filename,psp->tokenlineno,
2341 "Missing \"->\" following: \"%s(%s)\".",
2342 psp->lhs->name,psp->lhsalias);
2343 psp->errorcnt++;
2344 psp->state = RESYNC_AFTER_RULE_ERROR;
2345 }
2346 break;
2347 case IN_RHS:
2348 if( x[0]=='.' ){
2349 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002350 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002351 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002352 if( rp==0 ){
2353 ErrorMsg(psp->filename,psp->tokenlineno,
2354 "Can't allocate enough memory for this rule.");
2355 psp->errorcnt++;
2356 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002357 }else{
drh75897232000-05-29 14:26:00 +00002358 int i;
2359 rp->ruleline = psp->tokenlineno;
2360 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002361 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002362 for(i=0; i<psp->nrhs; i++){
2363 rp->rhs[i] = psp->rhs[i];
2364 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002365 }
drh75897232000-05-29 14:26:00 +00002366 rp->lhs = psp->lhs;
2367 rp->lhsalias = psp->lhsalias;
2368 rp->nrhs = psp->nrhs;
2369 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002370 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002371 rp->precsym = 0;
2372 rp->index = psp->gp->nrule++;
2373 rp->nextlhs = rp->lhs->rule;
2374 rp->lhs->rule = rp;
2375 rp->next = 0;
2376 if( psp->firstrule==0 ){
2377 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002378 }else{
drh75897232000-05-29 14:26:00 +00002379 psp->lastrule->next = rp;
2380 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002381 }
drh75897232000-05-29 14:26:00 +00002382 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002383 }
drh75897232000-05-29 14:26:00 +00002384 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002385 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002386 if( psp->nrhs>=MAXRHS ){
2387 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002388 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002389 x);
2390 psp->errorcnt++;
2391 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002392 }else{
drh75897232000-05-29 14:26:00 +00002393 psp->rhs[psp->nrhs] = Symbol_new(x);
2394 psp->alias[psp->nrhs] = 0;
2395 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002396 }
drhfd405312005-11-06 04:06:59 +00002397 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2398 struct symbol *msp = psp->rhs[psp->nrhs-1];
2399 if( msp->type!=MULTITERMINAL ){
2400 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002401 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002402 memset(msp, 0, sizeof(*msp));
2403 msp->type = MULTITERMINAL;
2404 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002405 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002406 msp->subsym[0] = origsp;
2407 msp->name = origsp->name;
2408 psp->rhs[psp->nrhs-1] = msp;
2409 }
2410 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002411 msp->subsym = (struct symbol **) realloc(msp->subsym,
2412 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002413 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002414 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002415 ErrorMsg(psp->filename,psp->tokenlineno,
2416 "Cannot form a compound containing a non-terminal");
2417 psp->errorcnt++;
2418 }
drh75897232000-05-29 14:26:00 +00002419 }else if( x[0]=='(' && psp->nrhs>0 ){
2420 psp->state = RHS_ALIAS_1;
2421 }else{
2422 ErrorMsg(psp->filename,psp->tokenlineno,
2423 "Illegal character on RHS of rule: \"%s\".",x);
2424 psp->errorcnt++;
2425 psp->state = RESYNC_AFTER_RULE_ERROR;
2426 }
2427 break;
2428 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002429 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002430 psp->alias[psp->nrhs-1] = x;
2431 psp->state = RHS_ALIAS_2;
2432 }else{
2433 ErrorMsg(psp->filename,psp->tokenlineno,
2434 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2435 x,psp->rhs[psp->nrhs-1]->name);
2436 psp->errorcnt++;
2437 psp->state = RESYNC_AFTER_RULE_ERROR;
2438 }
2439 break;
2440 case RHS_ALIAS_2:
2441 if( x[0]==')' ){
2442 psp->state = IN_RHS;
2443 }else{
2444 ErrorMsg(psp->filename,psp->tokenlineno,
2445 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2446 psp->errorcnt++;
2447 psp->state = RESYNC_AFTER_RULE_ERROR;
2448 }
2449 break;
2450 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002451 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002452 psp->declkeyword = x;
2453 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002454 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002455 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002456 psp->state = WAITING_FOR_DECL_ARG;
2457 if( strcmp(x,"name")==0 ){
2458 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002459 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002460 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002461 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002462 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002463 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002464 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002465 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002466 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002467 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002468 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002469 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002470 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002471 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002472 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002473 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002474 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002475 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002476 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002477 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002478 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002479 }else if( strcmp(x,"extra_argument")==0 ){
2480 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002481 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002482 }else if( strcmp(x,"token_type")==0 ){
2483 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002484 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002485 }else if( strcmp(x,"default_type")==0 ){
2486 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002487 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002488 }else if( strcmp(x,"stack_size")==0 ){
2489 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002490 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002491 }else if( strcmp(x,"start_symbol")==0 ){
2492 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002493 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002494 }else if( strcmp(x,"left")==0 ){
2495 psp->preccounter++;
2496 psp->declassoc = LEFT;
2497 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2498 }else if( strcmp(x,"right")==0 ){
2499 psp->preccounter++;
2500 psp->declassoc = RIGHT;
2501 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2502 }else if( strcmp(x,"nonassoc")==0 ){
2503 psp->preccounter++;
2504 psp->declassoc = NONE;
2505 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002506 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002507 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002508 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002509 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002510 }else if( strcmp(x,"fallback")==0 ){
2511 psp->fallback = 0;
2512 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002513 }else if( strcmp(x,"token")==0 ){
2514 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002515 }else if( strcmp(x,"wildcard")==0 ){
2516 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002517 }else if( strcmp(x,"token_class")==0 ){
2518 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002519 }else{
2520 ErrorMsg(psp->filename,psp->tokenlineno,
2521 "Unknown declaration keyword: \"%%%s\".",x);
2522 psp->errorcnt++;
2523 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002524 }
drh75897232000-05-29 14:26:00 +00002525 }else{
2526 ErrorMsg(psp->filename,psp->tokenlineno,
2527 "Illegal declaration keyword: \"%s\".",x);
2528 psp->errorcnt++;
2529 psp->state = RESYNC_AFTER_DECL_ERROR;
2530 }
2531 break;
2532 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002533 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002534 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002535 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002536 psp->errorcnt++;
2537 psp->state = RESYNC_AFTER_DECL_ERROR;
2538 }else{
icculusd286fa62010-03-03 17:06:32 +00002539 struct symbol *sp = Symbol_new(x);
2540 psp->declargslot = &sp->destructor;
2541 psp->decllinenoslot = &sp->destLineno;
2542 psp->insertLineMacro = 1;
2543 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002544 }
2545 break;
2546 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002547 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002548 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002549 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002550 psp->errorcnt++;
2551 psp->state = RESYNC_AFTER_DECL_ERROR;
2552 }else{
icculus866bf1e2010-02-17 20:31:32 +00002553 struct symbol *sp = Symbol_find(x);
2554 if((sp) && (sp->datatype)){
2555 ErrorMsg(psp->filename,psp->tokenlineno,
2556 "Symbol %%type \"%s\" already defined", x);
2557 psp->errorcnt++;
2558 psp->state = RESYNC_AFTER_DECL_ERROR;
2559 }else{
2560 if (!sp){
2561 sp = Symbol_new(x);
2562 }
2563 psp->declargslot = &sp->datatype;
2564 psp->insertLineMacro = 0;
2565 psp->state = WAITING_FOR_DECL_ARG;
2566 }
drh75897232000-05-29 14:26:00 +00002567 }
2568 break;
2569 case WAITING_FOR_PRECEDENCE_SYMBOL:
2570 if( x[0]=='.' ){
2571 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002572 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002573 struct symbol *sp;
2574 sp = Symbol_new(x);
2575 if( sp->prec>=0 ){
2576 ErrorMsg(psp->filename,psp->tokenlineno,
2577 "Symbol \"%s\" has already be given a precedence.",x);
2578 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002579 }else{
drh75897232000-05-29 14:26:00 +00002580 sp->prec = psp->preccounter;
2581 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002582 }
drh75897232000-05-29 14:26:00 +00002583 }else{
2584 ErrorMsg(psp->filename,psp->tokenlineno,
2585 "Can't assign a precedence to \"%s\".",x);
2586 psp->errorcnt++;
2587 }
2588 break;
2589 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002590 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002591 const char *zOld, *zNew;
2592 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002593 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002594 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002595 char zLine[50];
2596 zNew = x;
2597 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002598 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002599 if( *psp->declargslot ){
2600 zOld = *psp->declargslot;
2601 }else{
2602 zOld = "";
2603 }
drh87cf1372008-08-13 20:09:06 +00002604 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002605 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002606 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002607 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2608 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002609 for(z=psp->filename, nBack=0; *z; z++){
2610 if( *z=='\\' ) nBack++;
2611 }
drh898799f2014-01-10 23:21:00 +00002612 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002613 nLine = lemonStrlen(zLine);
2614 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002615 }
icculus9e44cf12010-02-14 17:14:22 +00002616 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2617 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002618 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002619 if( nOld && zBuf[-1]!='\n' ){
2620 *(zBuf++) = '\n';
2621 }
2622 memcpy(zBuf, zLine, nLine);
2623 zBuf += nLine;
2624 *(zBuf++) = '"';
2625 for(z=psp->filename; *z; z++){
2626 if( *z=='\\' ){
2627 *(zBuf++) = '\\';
2628 }
2629 *(zBuf++) = *z;
2630 }
2631 *(zBuf++) = '"';
2632 *(zBuf++) = '\n';
2633 }
drh4dc8ef52008-07-01 17:13:57 +00002634 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2635 psp->decllinenoslot[0] = psp->tokenlineno;
2636 }
drha5808f32008-04-27 22:19:44 +00002637 memcpy(zBuf, zNew, nNew);
2638 zBuf += nNew;
2639 *zBuf = 0;
2640 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002641 }else{
2642 ErrorMsg(psp->filename,psp->tokenlineno,
2643 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2644 psp->errorcnt++;
2645 psp->state = RESYNC_AFTER_DECL_ERROR;
2646 }
2647 break;
drh0bd1f4e2002-06-06 18:54:39 +00002648 case WAITING_FOR_FALLBACK_ID:
2649 if( x[0]=='.' ){
2650 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002651 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002652 ErrorMsg(psp->filename, psp->tokenlineno,
2653 "%%fallback argument \"%s\" should be a token", x);
2654 psp->errorcnt++;
2655 }else{
2656 struct symbol *sp = Symbol_new(x);
2657 if( psp->fallback==0 ){
2658 psp->fallback = sp;
2659 }else if( sp->fallback ){
2660 ErrorMsg(psp->filename, psp->tokenlineno,
2661 "More than one fallback assigned to token %s", x);
2662 psp->errorcnt++;
2663 }else{
2664 sp->fallback = psp->fallback;
2665 psp->gp->has_fallback = 1;
2666 }
2667 }
2668 break;
drh59c435a2017-08-02 03:21:11 +00002669 case WAITING_FOR_TOKEN_NAME:
2670 /* Tokens do not have to be declared before use. But they can be
2671 ** in order to control their assigned integer number. The number for
2672 ** each token is assigned when it is first seen. So by including
2673 **
2674 ** %token ONE TWO THREE
2675 **
2676 ** early in the grammar file, that assigns small consecutive values
2677 ** to each of the tokens ONE TWO and THREE.
2678 */
2679 if( x[0]=='.' ){
2680 psp->state = WAITING_FOR_DECL_OR_RULE;
2681 }else if( !ISUPPER(x[0]) ){
2682 ErrorMsg(psp->filename, psp->tokenlineno,
2683 "%%token argument \"%s\" should be a token", x);
2684 psp->errorcnt++;
2685 }else{
2686 (void)Symbol_new(x);
2687 }
2688 break;
drhe09daa92006-06-10 13:29:31 +00002689 case WAITING_FOR_WILDCARD_ID:
2690 if( x[0]=='.' ){
2691 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002692 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002693 ErrorMsg(psp->filename, psp->tokenlineno,
2694 "%%wildcard argument \"%s\" should be a token", x);
2695 psp->errorcnt++;
2696 }else{
2697 struct symbol *sp = Symbol_new(x);
2698 if( psp->gp->wildcard==0 ){
2699 psp->gp->wildcard = sp;
2700 }else{
2701 ErrorMsg(psp->filename, psp->tokenlineno,
2702 "Extra wildcard to token: %s", x);
2703 psp->errorcnt++;
2704 }
2705 }
2706 break;
drh61f92cd2014-01-11 03:06:18 +00002707 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002708 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002709 ErrorMsg(psp->filename, psp->tokenlineno,
2710 "%%token_class must be followed by an identifier: ", x);
2711 psp->errorcnt++;
2712 psp->state = RESYNC_AFTER_DECL_ERROR;
2713 }else if( Symbol_find(x) ){
2714 ErrorMsg(psp->filename, psp->tokenlineno,
2715 "Symbol \"%s\" already used", x);
2716 psp->errorcnt++;
2717 psp->state = RESYNC_AFTER_DECL_ERROR;
2718 }else{
2719 psp->tkclass = Symbol_new(x);
2720 psp->tkclass->type = MULTITERMINAL;
2721 psp->state = WAITING_FOR_CLASS_TOKEN;
2722 }
2723 break;
2724 case WAITING_FOR_CLASS_TOKEN:
2725 if( x[0]=='.' ){
2726 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002727 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002728 struct symbol *msp = psp->tkclass;
2729 msp->nsubsym++;
2730 msp->subsym = (struct symbol **) realloc(msp->subsym,
2731 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002732 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002733 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2734 }else{
2735 ErrorMsg(psp->filename, psp->tokenlineno,
2736 "%%token_class argument \"%s\" should be a token", x);
2737 psp->errorcnt++;
2738 psp->state = RESYNC_AFTER_DECL_ERROR;
2739 }
2740 break;
drh75897232000-05-29 14:26:00 +00002741 case RESYNC_AFTER_RULE_ERROR:
2742/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2743** break; */
2744 case RESYNC_AFTER_DECL_ERROR:
2745 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2746 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2747 break;
2748 }
2749}
2750
drh34ff57b2008-07-14 12:27:51 +00002751/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002752** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2753** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2754** comments them out. Text in between is also commented out as appropriate.
2755*/
danielk1977940fac92005-01-23 22:41:37 +00002756static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002757 int i, j, k, n;
2758 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002759 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002760 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002761 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002762 for(i=0; z[i]; i++){
2763 if( z[i]=='\n' ) lineno++;
2764 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002765 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002766 if( exclude ){
2767 exclude--;
2768 if( exclude==0 ){
2769 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2770 }
2771 }
2772 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002773 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2774 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002775 if( exclude ){
2776 exclude++;
2777 }else{
drhc56fac72015-10-29 13:48:15 +00002778 for(j=i+7; ISSPACE(z[j]); j++){}
2779 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002780 exclude = 1;
2781 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002782 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002783 exclude = 0;
2784 break;
2785 }
2786 }
2787 if( z[i+3]=='n' ) exclude = !exclude;
2788 if( exclude ){
2789 start = i;
2790 start_lineno = lineno;
2791 }
2792 }
2793 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2794 }
2795 }
2796 if( exclude ){
2797 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2798 exit(1);
2799 }
2800}
2801
drh75897232000-05-29 14:26:00 +00002802/* In spite of its name, this function is really a scanner. It read
2803** in the entire input file (all at once) then tokenizes it. Each
2804** token is passed to the function "parseonetoken" which builds all
2805** the appropriate data structures in the global state vector "gp".
2806*/
icculus9e44cf12010-02-14 17:14:22 +00002807void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002808{
2809 struct pstate ps;
2810 FILE *fp;
2811 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002812 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002813 int lineno;
2814 int c;
2815 char *cp, *nextcp;
2816 int startline = 0;
2817
rse38514a92007-09-20 11:34:17 +00002818 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002819 ps.gp = gp;
2820 ps.filename = gp->filename;
2821 ps.errorcnt = 0;
2822 ps.state = INITIALIZE;
2823
2824 /* Begin by reading the input file */
2825 fp = fopen(ps.filename,"rb");
2826 if( fp==0 ){
2827 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2828 gp->errorcnt++;
2829 return;
2830 }
2831 fseek(fp,0,2);
2832 filesize = ftell(fp);
2833 rewind(fp);
2834 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002835 if( filesize>100000000 || filebuf==0 ){
2836 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002837 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002838 fclose(fp);
drh75897232000-05-29 14:26:00 +00002839 return;
2840 }
2841 if( fread(filebuf,1,filesize,fp)!=filesize ){
2842 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2843 filesize);
2844 free(filebuf);
2845 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002846 fclose(fp);
drh75897232000-05-29 14:26:00 +00002847 return;
2848 }
2849 fclose(fp);
2850 filebuf[filesize] = 0;
2851
drh6d08b4d2004-07-20 12:45:22 +00002852 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2853 preprocess_input(filebuf);
2854
drh75897232000-05-29 14:26:00 +00002855 /* Now scan the text of the input file */
2856 lineno = 1;
2857 for(cp=filebuf; (c= *cp)!=0; ){
2858 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002859 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002860 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2861 cp+=2;
2862 while( (c= *cp)!=0 && c!='\n' ) cp++;
2863 continue;
2864 }
2865 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2866 cp+=2;
2867 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2868 if( c=='\n' ) lineno++;
2869 cp++;
2870 }
2871 if( c ) cp++;
2872 continue;
2873 }
2874 ps.tokenstart = cp; /* Mark the beginning of the token */
2875 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2876 if( c=='\"' ){ /* String literals */
2877 cp++;
2878 while( (c= *cp)!=0 && c!='\"' ){
2879 if( c=='\n' ) lineno++;
2880 cp++;
2881 }
2882 if( c==0 ){
2883 ErrorMsg(ps.filename,startline,
2884"String starting on this line is not terminated before the end of the file.");
2885 ps.errorcnt++;
2886 nextcp = cp;
2887 }else{
2888 nextcp = cp+1;
2889 }
2890 }else if( c=='{' ){ /* A block of C code */
2891 int level;
2892 cp++;
2893 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2894 if( c=='\n' ) lineno++;
2895 else if( c=='{' ) level++;
2896 else if( c=='}' ) level--;
2897 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2898 int prevc;
2899 cp = &cp[2];
2900 prevc = 0;
2901 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2902 if( c=='\n' ) lineno++;
2903 prevc = c;
2904 cp++;
drhf2f105d2012-08-20 15:53:54 +00002905 }
2906 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002907 cp = &cp[2];
2908 while( (c= *cp)!=0 && c!='\n' ) cp++;
2909 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002910 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002911 int startchar, prevc;
2912 startchar = c;
2913 prevc = 0;
2914 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2915 if( c=='\n' ) lineno++;
2916 if( prevc=='\\' ) prevc = 0;
2917 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002918 }
2919 }
drh75897232000-05-29 14:26:00 +00002920 }
2921 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002922 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002923"C code starting on this line is not terminated before the end of the file.");
2924 ps.errorcnt++;
2925 nextcp = cp;
2926 }else{
2927 nextcp = cp+1;
2928 }
drhc56fac72015-10-29 13:48:15 +00002929 }else if( ISALNUM(c) ){ /* Identifiers */
2930 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002931 nextcp = cp;
2932 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2933 cp += 3;
2934 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002935 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002936 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002937 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002938 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002939 }else{ /* All other (one character) operators */
2940 cp++;
2941 nextcp = cp;
2942 }
2943 c = *cp;
2944 *cp = 0; /* Null terminate the token */
2945 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002946 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002947 cp = nextcp;
2948 }
2949 free(filebuf); /* Release the buffer after parsing */
2950 gp->rule = ps.firstrule;
2951 gp->errorcnt = ps.errorcnt;
2952}
2953/*************************** From the file "plink.c" *********************/
2954/*
2955** Routines processing configuration follow-set propagation links
2956** in the LEMON parser generator.
2957*/
2958static struct plink *plink_freelist = 0;
2959
2960/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00002961struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00002962 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002963
2964 if( plink_freelist==0 ){
2965 int i;
2966 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002967 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002968 if( plink_freelist==0 ){
2969 fprintf(stderr,
2970 "Unable to allocate memory for a new follow-set propagation link.\n");
2971 exit(1);
2972 }
2973 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2974 plink_freelist[amt-1].next = 0;
2975 }
icculus9e44cf12010-02-14 17:14:22 +00002976 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002977 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002978 return newlink;
drh75897232000-05-29 14:26:00 +00002979}
2980
2981/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002982void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002983{
icculus9e44cf12010-02-14 17:14:22 +00002984 struct plink *newlink;
2985 newlink = Plink_new();
2986 newlink->next = *plpp;
2987 *plpp = newlink;
2988 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002989}
2990
2991/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002992void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002993{
2994 struct plink *nextpl;
2995 while( from ){
2996 nextpl = from->next;
2997 from->next = *to;
2998 *to = from;
2999 from = nextpl;
3000 }
3001}
3002
3003/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00003004void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00003005{
3006 struct plink *nextpl;
3007
3008 while( plp ){
3009 nextpl = plp->next;
3010 plp->next = plink_freelist;
3011 plink_freelist = plp;
3012 plp = nextpl;
3013 }
3014}
3015/*********************** From the file "report.c" **************************/
3016/*
3017** Procedures for generating reports and tables in the LEMON parser generator.
3018*/
3019
3020/* Generate a filename with the given suffix. Space to hold the
3021** name comes from malloc() and must be freed by the calling
3022** function.
3023*/
icculus9e44cf12010-02-14 17:14:22 +00003024PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00003025{
3026 char *name;
3027 char *cp;
3028
icculus9e44cf12010-02-14 17:14:22 +00003029 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00003030 if( name==0 ){
3031 fprintf(stderr,"Can't allocate space for a filename.\n");
3032 exit(1);
3033 }
drh898799f2014-01-10 23:21:00 +00003034 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00003035 cp = strrchr(name,'.');
3036 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003037 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003038 return name;
3039}
3040
3041/* Open a file with a name based on the name of the input file,
3042** but with a different (specified) suffix, and return a pointer
3043** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003044PRIVATE FILE *file_open(
3045 struct lemon *lemp,
3046 const char *suffix,
3047 const char *mode
3048){
drh75897232000-05-29 14:26:00 +00003049 FILE *fp;
3050
3051 if( lemp->outname ) free(lemp->outname);
3052 lemp->outname = file_makename(lemp, suffix);
3053 fp = fopen(lemp->outname,mode);
3054 if( fp==0 && *mode=='w' ){
3055 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3056 lemp->errorcnt++;
3057 return 0;
3058 }
3059 return fp;
3060}
3061
drh5c8241b2017-12-24 23:38:10 +00003062/* Print the text of a rule
3063*/
3064void rule_print(FILE *out, struct rule *rp){
3065 int i, j;
3066 fprintf(out, "%s",rp->lhs->name);
3067 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3068 fprintf(out," ::=");
3069 for(i=0; i<rp->nrhs; i++){
3070 struct symbol *sp = rp->rhs[i];
3071 if( sp->type==MULTITERMINAL ){
3072 fprintf(out," %s", sp->subsym[0]->name);
3073 for(j=1; j<sp->nsubsym; j++){
3074 fprintf(out,"|%s", sp->subsym[j]->name);
3075 }
3076 }else{
3077 fprintf(out," %s", sp->name);
3078 }
3079 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3080 }
3081}
3082
drh06f60d82017-04-14 19:46:12 +00003083/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003084** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003085void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003086{
3087 struct rule *rp;
3088 struct symbol *sp;
3089 int i, j, maxlen, len, ncolumns, skip;
3090 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3091 maxlen = 10;
3092 for(i=0; i<lemp->nsymbol; i++){
3093 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003094 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003095 if( len>maxlen ) maxlen = len;
3096 }
3097 ncolumns = 76/(maxlen+5);
3098 if( ncolumns<1 ) ncolumns = 1;
3099 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3100 for(i=0; i<skip; i++){
3101 printf("//");
3102 for(j=i; j<lemp->nsymbol; j+=skip){
3103 sp = lemp->symbols[j];
3104 assert( sp->index==j );
3105 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3106 }
3107 printf("\n");
3108 }
3109 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003110 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003111 printf(".");
3112 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003113 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003114 printf("\n");
3115 }
3116}
3117
drh7e698e92015-09-07 14:22:24 +00003118/* Print a single rule.
3119*/
3120void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003121 struct symbol *sp;
3122 int i, j;
drh75897232000-05-29 14:26:00 +00003123 fprintf(fp,"%s ::=",rp->lhs->name);
3124 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003125 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003126 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003127 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003128 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003129 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003130 for(j=1; j<sp->nsubsym; j++){
3131 fprintf(fp,"|%s",sp->subsym[j]->name);
3132 }
drh61f92cd2014-01-11 03:06:18 +00003133 }else{
3134 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003135 }
drh75897232000-05-29 14:26:00 +00003136 }
3137}
3138
drh7e698e92015-09-07 14:22:24 +00003139/* Print the rule for a configuration.
3140*/
3141void ConfigPrint(FILE *fp, struct config *cfp){
3142 RulePrint(fp, cfp->rp, cfp->dot);
3143}
3144
drh75897232000-05-29 14:26:00 +00003145/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003146#if 0
drh75897232000-05-29 14:26:00 +00003147/* Print a set */
3148PRIVATE void SetPrint(out,set,lemp)
3149FILE *out;
3150char *set;
3151struct lemon *lemp;
3152{
3153 int i;
3154 char *spacer;
3155 spacer = "";
3156 fprintf(out,"%12s[","");
3157 for(i=0; i<lemp->nterminal; i++){
3158 if( SetFind(set,i) ){
3159 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3160 spacer = " ";
3161 }
3162 }
3163 fprintf(out,"]\n");
3164}
3165
3166/* Print a plink chain */
3167PRIVATE void PlinkPrint(out,plp,tag)
3168FILE *out;
3169struct plink *plp;
3170char *tag;
3171{
3172 while( plp ){
drhada354d2005-11-05 15:03:59 +00003173 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003174 ConfigPrint(out,plp->cfp);
3175 fprintf(out,"\n");
3176 plp = plp->next;
3177 }
3178}
3179#endif
3180
3181/* Print an action to the given file descriptor. Return FALSE if
3182** nothing was actually printed.
3183*/
drh7e698e92015-09-07 14:22:24 +00003184int PrintAction(
3185 struct action *ap, /* The action to print */
3186 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003187 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003188){
drh75897232000-05-29 14:26:00 +00003189 int result = 1;
3190 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003191 case SHIFT: {
3192 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003193 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003194 break;
drh7e698e92015-09-07 14:22:24 +00003195 }
3196 case REDUCE: {
3197 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003198 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003199 RulePrint(fp, rp, -1);
3200 break;
3201 }
3202 case SHIFTREDUCE: {
3203 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003204 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003205 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003206 break;
drh7e698e92015-09-07 14:22:24 +00003207 }
drh75897232000-05-29 14:26:00 +00003208 case ACCEPT:
3209 fprintf(fp,"%*s accept",indent,ap->sp->name);
3210 break;
3211 case ERROR:
3212 fprintf(fp,"%*s error",indent,ap->sp->name);
3213 break;
drh9892c5d2007-12-21 00:02:11 +00003214 case SRCONFLICT:
3215 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003216 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003217 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003218 break;
drh9892c5d2007-12-21 00:02:11 +00003219 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003220 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003221 indent,ap->sp->name,ap->x.stp->statenum);
3222 break;
drh75897232000-05-29 14:26:00 +00003223 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003224 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003225 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003226 indent,ap->sp->name,ap->x.stp->statenum);
3227 }else{
3228 result = 0;
3229 }
3230 break;
drh75897232000-05-29 14:26:00 +00003231 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003232 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003233 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003234 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003235 }else{
3236 result = 0;
3237 }
3238 break;
drh75897232000-05-29 14:26:00 +00003239 case NOT_USED:
3240 result = 0;
3241 break;
3242 }
drhc173ad82016-05-23 16:15:02 +00003243 if( result && ap->spOpt ){
3244 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3245 }
drh75897232000-05-29 14:26:00 +00003246 return result;
3247}
3248
drh3bd48ab2015-09-07 18:23:37 +00003249/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003250void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003251{
3252 int i;
3253 struct state *stp;
3254 struct config *cfp;
3255 struct action *ap;
drh12f68392018-04-06 19:12:55 +00003256 struct rule *rp;
drh75897232000-05-29 14:26:00 +00003257 FILE *fp;
3258
drh2aa6ca42004-09-10 00:14:04 +00003259 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003260 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003261 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003262 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003263 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003264 if( lemp->basisflag ) cfp=stp->bp;
3265 else cfp=stp->cfp;
3266 while( cfp ){
3267 char buf[20];
3268 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003269 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003270 fprintf(fp," %5s ",buf);
3271 }else{
3272 fprintf(fp," ");
3273 }
3274 ConfigPrint(fp,cfp);
3275 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003276#if 0
drh75897232000-05-29 14:26:00 +00003277 SetPrint(fp,cfp->fws,lemp);
3278 PlinkPrint(fp,cfp->fplp,"To ");
3279 PlinkPrint(fp,cfp->bplp,"From");
3280#endif
3281 if( lemp->basisflag ) cfp=cfp->bp;
3282 else cfp=cfp->next;
3283 }
3284 fprintf(fp,"\n");
3285 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003286 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003287 }
3288 fprintf(fp,"\n");
3289 }
drhe9278182007-07-18 18:16:29 +00003290 fprintf(fp, "----------------------------------------------------\n");
3291 fprintf(fp, "Symbols:\n");
3292 for(i=0; i<lemp->nsymbol; i++){
3293 int j;
3294 struct symbol *sp;
3295
3296 sp = lemp->symbols[i];
3297 fprintf(fp, " %3d: %s", i, sp->name);
3298 if( sp->type==NONTERMINAL ){
3299 fprintf(fp, ":");
3300 if( sp->lambda ){
3301 fprintf(fp, " <lambda>");
3302 }
3303 for(j=0; j<lemp->nterminal; j++){
3304 if( sp->firstset && SetFind(sp->firstset, j) ){
3305 fprintf(fp, " %s", lemp->symbols[j]->name);
3306 }
3307 }
3308 }
drh12f68392018-04-06 19:12:55 +00003309 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
drhe9278182007-07-18 18:16:29 +00003310 fprintf(fp, "\n");
3311 }
drh12f68392018-04-06 19:12:55 +00003312 fprintf(fp, "----------------------------------------------------\n");
3313 fprintf(fp, "Rules:\n");
3314 for(rp=lemp->rule; rp; rp=rp->next){
3315 fprintf(fp, "%4d: ", rp->iRule);
3316 rule_print(fp, rp);
3317 fprintf(fp,".");
3318 if( rp->precsym ){
3319 fprintf(fp," [%s precedence=%d]",
3320 rp->precsym->name, rp->precsym->prec);
3321 }
3322 fprintf(fp,"\n");
3323 }
drh75897232000-05-29 14:26:00 +00003324 fclose(fp);
3325 return;
3326}
3327
3328/* Search for the file "name" which is in the same directory as
3329** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003330PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003331{
icculus9e44cf12010-02-14 17:14:22 +00003332 const char *pathlist;
3333 char *pathbufptr;
3334 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003335 char *path,*cp;
3336 char c;
drh75897232000-05-29 14:26:00 +00003337
3338#ifdef __WIN32__
3339 cp = strrchr(argv0,'\\');
3340#else
3341 cp = strrchr(argv0,'/');
3342#endif
3343 if( cp ){
3344 c = *cp;
3345 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003346 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003347 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003348 *cp = c;
3349 }else{
drh75897232000-05-29 14:26:00 +00003350 pathlist = getenv("PATH");
3351 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003352 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003353 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003354 if( (pathbuf != 0) && (path!=0) ){
3355 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003356 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003357 while( *pathbuf ){
3358 cp = strchr(pathbuf,':');
3359 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003360 c = *cp;
3361 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003362 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003363 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003364 if( c==0 ) pathbuf[0] = 0;
3365 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003366 if( access(path,modemask)==0 ) break;
3367 }
icculus9e44cf12010-02-14 17:14:22 +00003368 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003369 }
3370 }
3371 return path;
3372}
3373
3374/* Given an action, compute the integer value for that action
3375** which is to be put in the action table of the generated machine.
3376** Return negative if no action should be generated.
3377*/
icculus9e44cf12010-02-14 17:14:22 +00003378PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003379{
3380 int act;
3381 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003382 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003383 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003384 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3385 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3386 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003387 if( ap->sp->index>=lemp->nterminal ){
3388 act = lemp->minReduce + ap->x.rp->iRule;
3389 }else{
3390 act = lemp->minShiftReduce + ap->x.rp->iRule;
3391 }
drhbd8fcc12017-06-28 11:56:18 +00003392 break;
3393 }
drh5c8241b2017-12-24 23:38:10 +00003394 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3395 case ERROR: act = lemp->errAction; break;
3396 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003397 default: act = -1; break;
3398 }
3399 return act;
3400}
3401
3402#define LINESIZE 1000
3403/* The next cluster of routines are for reading the template file
3404** and writing the results to the generated parser */
3405/* The first function transfers data from "in" to "out" until
3406** a line is seen which begins with "%%". The line number is
3407** tracked.
3408**
3409** if name!=0, then any word that begin with "Parse" is changed to
3410** begin with *name instead.
3411*/
icculus9e44cf12010-02-14 17:14:22 +00003412PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003413{
3414 int i, iStart;
3415 char line[LINESIZE];
3416 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3417 (*lineno)++;
3418 iStart = 0;
3419 if( name ){
3420 for(i=0; line[i]; i++){
3421 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003422 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003423 ){
3424 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3425 fprintf(out,"%s",name);
3426 i += 4;
3427 iStart = i+1;
3428 }
3429 }
3430 }
3431 fprintf(out,"%s",&line[iStart]);
3432 }
3433}
3434
3435/* The next function finds the template file and opens it, returning
3436** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003437PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003438{
3439 static char templatename[] = "lempar.c";
3440 char buf[1000];
3441 FILE *in;
3442 char *tpltname;
3443 char *cp;
3444
icculus3e143bd2010-02-14 00:48:49 +00003445 /* first, see if user specified a template filename on the command line. */
3446 if (user_templatename != 0) {
3447 if( access(user_templatename,004)==-1 ){
3448 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3449 user_templatename);
3450 lemp->errorcnt++;
3451 return 0;
3452 }
3453 in = fopen(user_templatename,"rb");
3454 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003455 fprintf(stderr,"Can't open the template file \"%s\".\n",
3456 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003457 lemp->errorcnt++;
3458 return 0;
3459 }
3460 return in;
3461 }
3462
drh75897232000-05-29 14:26:00 +00003463 cp = strrchr(lemp->filename,'.');
3464 if( cp ){
drh898799f2014-01-10 23:21:00 +00003465 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003466 }else{
drh898799f2014-01-10 23:21:00 +00003467 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003468 }
3469 if( access(buf,004)==0 ){
3470 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003471 }else if( access(templatename,004)==0 ){
3472 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003473 }else{
3474 tpltname = pathsearch(lemp->argv0,templatename,0);
3475 }
3476 if( tpltname==0 ){
3477 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3478 templatename);
3479 lemp->errorcnt++;
3480 return 0;
3481 }
drh2aa6ca42004-09-10 00:14:04 +00003482 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003483 if( in==0 ){
3484 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3485 lemp->errorcnt++;
3486 return 0;
3487 }
3488 return in;
3489}
3490
drhaf805ca2004-09-07 11:28:25 +00003491/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003492PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003493{
3494 fprintf(out,"#line %d \"",lineno);
3495 while( *filename ){
3496 if( *filename == '\\' ) putc('\\',out);
3497 putc(*filename,out);
3498 filename++;
3499 }
3500 fprintf(out,"\"\n");
3501}
3502
drh75897232000-05-29 14:26:00 +00003503/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003504PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003505{
3506 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003507 while( *str ){
drh75897232000-05-29 14:26:00 +00003508 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003509 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003510 str++;
3511 }
drh9db55df2004-09-09 14:01:21 +00003512 if( str[-1]!='\n' ){
3513 putc('\n',out);
3514 (*lineno)++;
3515 }
shane58543932008-12-10 20:10:04 +00003516 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003517 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003518 }
drh75897232000-05-29 14:26:00 +00003519 return;
3520}
3521
3522/*
3523** The following routine emits code for the destructor for the
3524** symbol sp
3525*/
icculus9e44cf12010-02-14 17:14:22 +00003526void emit_destructor_code(
3527 FILE *out,
3528 struct symbol *sp,
3529 struct lemon *lemp,
3530 int *lineno
3531){
drhcc83b6e2004-04-23 23:38:42 +00003532 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003533
drh75897232000-05-29 14:26:00 +00003534 if( sp->type==TERMINAL ){
3535 cp = lemp->tokendest;
3536 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003537 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003538 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003539 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003540 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003541 if( !lemp->nolinenosflag ){
3542 (*lineno)++;
3543 tplt_linedir(out,sp->destLineno,lemp->filename);
3544 }
drh960e8c62001-04-03 16:53:21 +00003545 }else if( lemp->vardest ){
3546 cp = lemp->vardest;
3547 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003548 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003549 }else{
3550 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003551 }
3552 for(; *cp; cp++){
3553 if( *cp=='$' && cp[1]=='$' ){
3554 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3555 cp++;
3556 continue;
3557 }
shane58543932008-12-10 20:10:04 +00003558 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003559 fputc(*cp,out);
3560 }
shane58543932008-12-10 20:10:04 +00003561 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003562 if (!lemp->nolinenosflag) {
3563 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003564 }
3565 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003566 return;
3567}
3568
3569/*
drh960e8c62001-04-03 16:53:21 +00003570** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003571*/
icculus9e44cf12010-02-14 17:14:22 +00003572int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003573{
3574 int ret;
3575 if( sp->type==TERMINAL ){
3576 ret = lemp->tokendest!=0;
3577 }else{
drh960e8c62001-04-03 16:53:21 +00003578 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003579 }
3580 return ret;
3581}
3582
drh0bb132b2004-07-20 14:06:51 +00003583/*
3584** Append text to a dynamically allocated string. If zText is 0 then
3585** reset the string to be empty again. Always return the complete text
3586** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003587**
3588** n bytes of zText are stored. If n==0 then all of zText up to the first
3589** \000 terminator is stored. zText can contain up to two instances of
3590** %d. The values of p1 and p2 are written into the first and second
3591** %d.
3592**
3593** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003594*/
icculus9e44cf12010-02-14 17:14:22 +00003595PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3596 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003597 static char *z = 0;
3598 static int alloced = 0;
3599 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003600 int c;
drh0bb132b2004-07-20 14:06:51 +00003601 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003602 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003603 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003604 used = 0;
3605 return z;
3606 }
drh7ac25c72004-08-19 15:12:26 +00003607 if( n<=0 ){
3608 if( n<0 ){
3609 used += n;
3610 assert( used>=0 );
3611 }
drh87cf1372008-08-13 20:09:06 +00003612 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003613 }
drhdf609712010-11-23 20:55:27 +00003614 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003615 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003616 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003617 }
icculus9e44cf12010-02-14 17:14:22 +00003618 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003619 while( n-- > 0 ){
3620 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003621 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003622 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003623 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003624 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003625 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003626 zText++;
3627 n--;
3628 }else{
mistachkin2318d332015-01-12 18:02:52 +00003629 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003630 }
3631 }
3632 z[used] = 0;
3633 return z;
3634}
3635
3636/*
drh711c9812016-05-23 14:24:31 +00003637** Write and transform the rp->code string so that symbols are expanded.
3638** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003639**
3640** Return 1 if the expanded code requires that "yylhsminor" local variable
3641** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003642*/
drhdabd04c2016-02-17 01:46:19 +00003643PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003644 char *cp, *xp;
3645 int i;
drhcf82f0d2016-02-17 04:33:10 +00003646 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003647 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003648 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3649 char lhsused = 0; /* True if the LHS element has been used */
3650 char lhsdirect; /* True if LHS writes directly into stack */
3651 char used[MAXRHS]; /* True for each RHS element which is used */
3652 char zLhs[50]; /* Convert the LHS symbol into this string */
3653 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003654
3655 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3656 lhsused = 0;
3657
drh19c9e562007-03-29 20:13:53 +00003658 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003659 static char newlinestr[2] = { '\n', '\0' };
3660 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003661 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003662 rp->noCode = 1;
3663 }else{
3664 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003665 }
3666
drh4dd0d3f2016-02-17 01:18:33 +00003667
drh2e55b042016-04-30 17:19:30 +00003668 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003669 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3670 lhsdirect = 1;
3671 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003672 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003673 ** we have to call the distructor on the RHS symbol first. */
3674 lhsdirect = 1;
3675 if( has_destructor(rp->rhs[0],lemp) ){
3676 append_str(0,0,0,0);
3677 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3678 rp->rhs[0]->index,1-rp->nrhs);
3679 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003680 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003681 }
drh2e55b042016-04-30 17:19:30 +00003682 }else if( rp->lhsalias==0 ){
3683 /* There is no LHS value symbol. */
3684 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003685 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003686 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003687 ** direct writing is allowed */
3688 lhsdirect = 1;
3689 lhsused = 1;
3690 used[0] = 1;
3691 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3692 ErrorMsg(lemp->filename,rp->ruleline,
3693 "%s(%s) and %s(%s) share the same label but have "
3694 "different datatypes.",
3695 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3696 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003697 }
drh4dd0d3f2016-02-17 01:18:33 +00003698 }else{
drhcf82f0d2016-02-17 04:33:10 +00003699 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3700 rp->lhsalias, rp->rhsalias[0]);
3701 zSkip = strstr(rp->code, zOvwrt);
3702 if( zSkip!=0 ){
3703 /* The code contains a special comment that indicates that it is safe
3704 ** for the LHS label to overwrite left-most RHS label. */
3705 lhsdirect = 1;
3706 }else{
3707 lhsdirect = 0;
3708 }
drh4dd0d3f2016-02-17 01:18:33 +00003709 }
3710 if( lhsdirect ){
3711 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3712 }else{
drhdabd04c2016-02-17 01:46:19 +00003713 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003714 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3715 }
3716
drh0bb132b2004-07-20 14:06:51 +00003717 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003718
3719 /* This const cast is wrong but harmless, if we're careful. */
3720 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003721 if( cp==zSkip ){
3722 append_str(zOvwrt,0,0,0);
3723 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003724 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003725 continue;
3726 }
drhc56fac72015-10-29 13:48:15 +00003727 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003728 char saved;
drhc56fac72015-10-29 13:48:15 +00003729 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003730 saved = *xp;
3731 *xp = 0;
3732 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003733 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003734 cp = xp;
3735 lhsused = 1;
3736 }else{
3737 for(i=0; i<rp->nrhs; i++){
3738 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003739 if( i==0 && dontUseRhs0 ){
3740 ErrorMsg(lemp->filename,rp->ruleline,
3741 "Label %s used after '%s'.",
3742 rp->rhsalias[0], zOvwrt);
3743 lemp->errorcnt++;
3744 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003745 /* If the argument is of the form @X then substituted
3746 ** the token number of X, not the value of X */
3747 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3748 }else{
drhfd405312005-11-06 04:06:59 +00003749 struct symbol *sp = rp->rhs[i];
3750 int dtnum;
3751 if( sp->type==MULTITERMINAL ){
3752 dtnum = sp->subsym[0]->dtnum;
3753 }else{
3754 dtnum = sp->dtnum;
3755 }
3756 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003757 }
drh0bb132b2004-07-20 14:06:51 +00003758 cp = xp;
3759 used[i] = 1;
3760 break;
3761 }
3762 }
3763 }
3764 *xp = saved;
3765 }
3766 append_str(cp, 1, 0, 0);
3767 } /* End loop */
3768
drh4dd0d3f2016-02-17 01:18:33 +00003769 /* Main code generation completed */
3770 cp = append_str(0,0,0,0);
3771 if( cp && cp[0] ) rp->code = Strsafe(cp);
3772 append_str(0,0,0,0);
3773
drh0bb132b2004-07-20 14:06:51 +00003774 /* Check to make sure the LHS has been used */
3775 if( rp->lhsalias && !lhsused ){
3776 ErrorMsg(lemp->filename,rp->ruleline,
3777 "Label \"%s\" for \"%s(%s)\" is never used.",
3778 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3779 lemp->errorcnt++;
3780 }
3781
drh4dd0d3f2016-02-17 01:18:33 +00003782 /* Generate destructor code for RHS minor values which are not referenced.
3783 ** Generate error messages for unused labels and duplicate labels.
3784 */
drh0bb132b2004-07-20 14:06:51 +00003785 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003786 if( rp->rhsalias[i] ){
3787 if( i>0 ){
3788 int j;
3789 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3790 ErrorMsg(lemp->filename,rp->ruleline,
3791 "%s(%s) has the same label as the LHS but is not the left-most "
3792 "symbol on the RHS.",
3793 rp->rhs[i]->name, rp->rhsalias);
3794 lemp->errorcnt++;
3795 }
3796 for(j=0; j<i; j++){
3797 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3798 ErrorMsg(lemp->filename,rp->ruleline,
3799 "Label %s used for multiple symbols on the RHS of a rule.",
3800 rp->rhsalias[i]);
3801 lemp->errorcnt++;
3802 break;
3803 }
3804 }
drh0bb132b2004-07-20 14:06:51 +00003805 }
drh4dd0d3f2016-02-17 01:18:33 +00003806 if( !used[i] ){
3807 ErrorMsg(lemp->filename,rp->ruleline,
3808 "Label %s for \"%s(%s)\" is never used.",
3809 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3810 lemp->errorcnt++;
3811 }
3812 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3813 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3814 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003815 }
3816 }
drh4dd0d3f2016-02-17 01:18:33 +00003817
3818 /* If unable to write LHS values directly into the stack, write the
3819 ** saved LHS value now. */
3820 if( lhsdirect==0 ){
3821 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3822 append_str(zLhs, 0, 0, 0);
3823 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003824 }
drh4dd0d3f2016-02-17 01:18:33 +00003825
3826 /* Suffix code generation complete */
3827 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003828 if( cp && cp[0] ){
3829 rp->codeSuffix = Strsafe(cp);
3830 rp->noCode = 0;
3831 }
drhdabd04c2016-02-17 01:46:19 +00003832
3833 return rc;
drh0bb132b2004-07-20 14:06:51 +00003834}
3835
drh06f60d82017-04-14 19:46:12 +00003836/*
drh75897232000-05-29 14:26:00 +00003837** Generate code which executes when the rule "rp" is reduced. Write
3838** the code to "out". Make sure lineno stays up-to-date.
3839*/
icculus9e44cf12010-02-14 17:14:22 +00003840PRIVATE void emit_code(
3841 FILE *out,
3842 struct rule *rp,
3843 struct lemon *lemp,
3844 int *lineno
3845){
3846 const char *cp;
drh75897232000-05-29 14:26:00 +00003847
drh4dd0d3f2016-02-17 01:18:33 +00003848 /* Setup code prior to the #line directive */
3849 if( rp->codePrefix && rp->codePrefix[0] ){
3850 fprintf(out, "{%s", rp->codePrefix);
3851 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3852 }
3853
drh75897232000-05-29 14:26:00 +00003854 /* Generate code to do the reduce action */
3855 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003856 if( !lemp->nolinenosflag ){
3857 (*lineno)++;
3858 tplt_linedir(out,rp->line,lemp->filename);
3859 }
drhaf805ca2004-09-07 11:28:25 +00003860 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003861 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003862 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003863 if( !lemp->nolinenosflag ){
3864 (*lineno)++;
3865 tplt_linedir(out,*lineno,lemp->outname);
3866 }
drh4dd0d3f2016-02-17 01:18:33 +00003867 }
3868
3869 /* Generate breakdown code that occurs after the #line directive */
3870 if( rp->codeSuffix && rp->codeSuffix[0] ){
3871 fprintf(out, "%s", rp->codeSuffix);
3872 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3873 }
3874
3875 if( rp->codePrefix ){
3876 fprintf(out, "}\n"); (*lineno)++;
3877 }
drh75897232000-05-29 14:26:00 +00003878
drh75897232000-05-29 14:26:00 +00003879 return;
3880}
3881
3882/*
3883** Print the definition of the union used for the parser's data stack.
3884** This union contains fields for every possible data type for tokens
3885** and nonterminals. In the process of computing and printing this
3886** union, also set the ".dtnum" field of every terminal and nonterminal
3887** symbol.
3888*/
icculus9e44cf12010-02-14 17:14:22 +00003889void print_stack_union(
3890 FILE *out, /* The output stream */
3891 struct lemon *lemp, /* The main info structure for this parser */
3892 int *plineno, /* Pointer to the line number */
3893 int mhflag /* True if generating makeheaders output */
3894){
drh75897232000-05-29 14:26:00 +00003895 int lineno = *plineno; /* The line number of the output */
3896 char **types; /* A hash table of datatypes */
3897 int arraysize; /* Size of the "types" array */
3898 int maxdtlength; /* Maximum length of any ".datatype" field. */
3899 char *stddt; /* Standardized name for a datatype */
3900 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003901 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003902 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003903
3904 /* Allocate and initialize types[] and allocate stddt[] */
3905 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003906 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003907 if( types==0 ){
3908 fprintf(stderr,"Out of memory.\n");
3909 exit(1);
3910 }
drh75897232000-05-29 14:26:00 +00003911 for(i=0; i<arraysize; i++) types[i] = 0;
3912 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003913 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003914 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003915 }
drh75897232000-05-29 14:26:00 +00003916 for(i=0; i<lemp->nsymbol; i++){
3917 int len;
3918 struct symbol *sp = lemp->symbols[i];
3919 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003920 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003921 if( len>maxdtlength ) maxdtlength = len;
3922 }
3923 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003924 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003925 fprintf(stderr,"Out of memory.\n");
3926 exit(1);
3927 }
3928
3929 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3930 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003931 ** used for terminal symbols. If there is no %default_type defined then
3932 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3933 ** a datatype using the %type directive.
3934 */
drh75897232000-05-29 14:26:00 +00003935 for(i=0; i<lemp->nsymbol; i++){
3936 struct symbol *sp = lemp->symbols[i];
3937 char *cp;
3938 if( sp==lemp->errsym ){
3939 sp->dtnum = arraysize+1;
3940 continue;
3941 }
drh960e8c62001-04-03 16:53:21 +00003942 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003943 sp->dtnum = 0;
3944 continue;
3945 }
3946 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003947 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003948 j = 0;
drhc56fac72015-10-29 13:48:15 +00003949 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003950 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003951 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003952 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003953 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003954 sp->dtnum = 0;
3955 continue;
3956 }
drh75897232000-05-29 14:26:00 +00003957 hash = 0;
3958 for(j=0; stddt[j]; j++){
3959 hash = hash*53 + stddt[j];
3960 }
drh3b2129c2003-05-13 00:34:21 +00003961 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003962 while( types[hash] ){
3963 if( strcmp(types[hash],stddt)==0 ){
3964 sp->dtnum = hash + 1;
3965 break;
3966 }
3967 hash++;
drh2b51f212013-10-11 23:01:02 +00003968 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003969 }
3970 if( types[hash]==0 ){
3971 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003972 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003973 if( types[hash]==0 ){
3974 fprintf(stderr,"Out of memory.\n");
3975 exit(1);
3976 }
drh898799f2014-01-10 23:21:00 +00003977 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003978 }
3979 }
3980
3981 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3982 name = lemp->name ? lemp->name : "Parse";
3983 lineno = *plineno;
3984 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3985 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3986 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3987 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3988 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003989 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003990 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3991 for(i=0; i<arraysize; i++){
3992 if( types[i]==0 ) continue;
3993 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3994 free(types[i]);
3995 }
drhed0c15b2018-04-16 14:31:34 +00003996 if( lemp->errsym && lemp->errsym->useCnt ){
drhc4dd3fd2008-01-22 01:48:05 +00003997 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3998 }
drh75897232000-05-29 14:26:00 +00003999 free(stddt);
4000 free(types);
4001 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4002 *plineno = lineno;
4003}
4004
drhb29b0a52002-02-23 19:39:46 +00004005/*
4006** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00004007** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4008** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00004009*/
drhc75e0162015-09-07 02:23:02 +00004010static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4011 const char *zType = "int";
4012 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00004013 if( lwr>=0 ){
4014 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00004015 zType = "unsigned char";
4016 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004017 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00004018 zType = "unsigned short int";
4019 nByte = 2;
drh8b582012003-10-21 13:16:03 +00004020 }else{
drhc75e0162015-09-07 02:23:02 +00004021 zType = "unsigned int";
4022 nByte = 4;
drh8b582012003-10-21 13:16:03 +00004023 }
4024 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00004025 zType = "signed char";
4026 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004027 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00004028 zType = "short";
4029 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00004030 }
drhc75e0162015-09-07 02:23:02 +00004031 if( pnByte ) *pnByte = nByte;
4032 return zType;
drhb29b0a52002-02-23 19:39:46 +00004033}
4034
drhfdbf9282003-10-21 16:34:41 +00004035/*
4036** Each state contains a set of token transaction and a set of
4037** nonterminal transactions. Each of these sets makes an instance
4038** of the following structure. An array of these structures is used
4039** to order the creation of entries in the yy_action[] table.
4040*/
4041struct axset {
4042 struct state *stp; /* A pointer to a state */
4043 int isTkn; /* True to use tokens. False for non-terminals */
4044 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00004045 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00004046};
4047
4048/*
4049** Compare to axset structures for sorting purposes
4050*/
4051static int axset_compare(const void *a, const void *b){
4052 struct axset *p1 = (struct axset*)a;
4053 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004054 int c;
4055 c = p2->nAction - p1->nAction;
4056 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004057 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004058 }
4059 assert( c!=0 || p1==p2 );
4060 return c;
drhfdbf9282003-10-21 16:34:41 +00004061}
4062
drhc4dd3fd2008-01-22 01:48:05 +00004063/*
4064** Write text on "out" that describes the rule "rp".
4065*/
4066static void writeRuleText(FILE *out, struct rule *rp){
4067 int j;
4068 fprintf(out,"%s ::=", rp->lhs->name);
4069 for(j=0; j<rp->nrhs; j++){
4070 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004071 if( sp->type!=MULTITERMINAL ){
4072 fprintf(out," %s", sp->name);
4073 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004074 int k;
drh61f92cd2014-01-11 03:06:18 +00004075 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004076 for(k=1; k<sp->nsubsym; k++){
4077 fprintf(out,"|%s",sp->subsym[k]->name);
4078 }
4079 }
4080 }
4081}
4082
4083
drh75897232000-05-29 14:26:00 +00004084/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004085void ReportTable(
4086 struct lemon *lemp,
4087 int mhflag /* Output in makeheaders format if true */
4088){
drh75897232000-05-29 14:26:00 +00004089 FILE *out, *in;
4090 char line[LINESIZE];
4091 int lineno;
4092 struct state *stp;
4093 struct action *ap;
4094 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004095 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004096 int i, j, n, sz;
4097 int szActionType; /* sizeof(YYACTIONTYPE) */
4098 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004099 const char *name;
drh8b582012003-10-21 13:16:03 +00004100 int mnTknOfst, mxTknOfst;
4101 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004102 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004103
drh5c8241b2017-12-24 23:38:10 +00004104 lemp->minShiftReduce = lemp->nstate;
4105 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4106 lemp->accAction = lemp->errAction + 1;
4107 lemp->noAction = lemp->accAction + 1;
4108 lemp->minReduce = lemp->noAction + 1;
4109 lemp->maxAction = lemp->minReduce + lemp->nrule;
4110
drh75897232000-05-29 14:26:00 +00004111 in = tplt_open(lemp);
4112 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004113 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004114 if( out==0 ){
4115 fclose(in);
4116 return;
4117 }
4118 lineno = 1;
4119 tplt_xfer(lemp->name,in,out,&lineno);
4120
4121 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004122 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004123 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004124 char *incName = file_makename(lemp, ".h");
4125 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4126 free(incName);
drh75897232000-05-29 14:26:00 +00004127 }
4128 tplt_xfer(lemp->name,in,out,&lineno);
4129
4130 /* Generate #defines for all tokens */
4131 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004132 const char *prefix;
drh75897232000-05-29 14:26:00 +00004133 fprintf(out,"#if INTERFACE\n"); lineno++;
4134 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4135 else prefix = "";
4136 for(i=1; i<lemp->nterminal; i++){
4137 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4138 lineno++;
4139 }
4140 fprintf(out,"#endif\n"); lineno++;
4141 }
4142 tplt_xfer(lemp->name,in,out,&lineno);
4143
4144 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004145 fprintf(out,"#define YYCODETYPE %s\n",
drhed0c15b2018-04-16 14:31:34 +00004146 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4147 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
drh75897232000-05-29 14:26:00 +00004148 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004149 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004150 if( lemp->wildcard ){
4151 fprintf(out,"#define YYWILDCARD %d\n",
4152 lemp->wildcard->index); lineno++;
4153 }
drh75897232000-05-29 14:26:00 +00004154 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004155 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004156 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004157 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4158 }else{
4159 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4160 }
drhca44b5a2007-02-22 23:06:58 +00004161 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004162 if( mhflag ){
4163 fprintf(out,"#if INTERFACE\n"); lineno++;
4164 }
4165 name = lemp->name ? lemp->name : "Parse";
4166 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004167 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004168 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4169 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004170 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4171 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4172 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
4173 name,lemp->arg,&lemp->arg[i]); lineno++;
4174 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
4175 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004176 }else{
drh1f245e42002-03-11 13:55:50 +00004177 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4178 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4179 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4180 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004181 }
4182 if( mhflag ){
4183 fprintf(out,"#endif\n"); lineno++;
4184 }
drhed0c15b2018-04-16 14:31:34 +00004185 if( lemp->errsym && lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004186 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4187 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004188 }
drh0bd1f4e2002-06-06 18:54:39 +00004189 if( lemp->has_fallback ){
4190 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4191 }
drh75897232000-05-29 14:26:00 +00004192
drh3bd48ab2015-09-07 18:23:37 +00004193 /* Compute the action table, but do not output it yet. The action
4194 ** table must be computed before generating the YYNSTATE macro because
4195 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004196 */
drh3bd48ab2015-09-07 18:23:37 +00004197 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004198 if( ax==0 ){
4199 fprintf(stderr,"malloc failed\n");
4200 exit(1);
4201 }
drh3bd48ab2015-09-07 18:23:37 +00004202 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004203 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004204 ax[i*2].stp = stp;
4205 ax[i*2].isTkn = 1;
4206 ax[i*2].nAction = stp->nTknAct;
4207 ax[i*2+1].stp = stp;
4208 ax[i*2+1].isTkn = 0;
4209 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004210 }
drh8b582012003-10-21 13:16:03 +00004211 mxTknOfst = mnTknOfst = 0;
4212 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004213 /* In an effort to minimize the action table size, use the heuristic
4214 ** of placing the largest action sets first */
4215 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4216 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh3a9d6c72017-12-25 04:15:38 +00004217 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
drh3bd48ab2015-09-07 18:23:37 +00004218 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004219 stp = ax[i].stp;
4220 if( ax[i].isTkn ){
4221 for(ap=stp->ap; ap; ap=ap->next){
4222 int action;
4223 if( ap->sp->index>=lemp->nterminal ) continue;
4224 action = compute_action(lemp, ap);
4225 if( action<0 ) continue;
4226 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004227 }
drh3a9d6c72017-12-25 04:15:38 +00004228 stp->iTknOfst = acttab_insert(pActtab, 1);
drhfdbf9282003-10-21 16:34:41 +00004229 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4230 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4231 }else{
4232 for(ap=stp->ap; ap; ap=ap->next){
4233 int action;
4234 if( ap->sp->index<lemp->nterminal ) continue;
4235 if( ap->sp->index==lemp->nsymbol ) continue;
4236 action = compute_action(lemp, ap);
4237 if( action<0 ) continue;
4238 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004239 }
drh3a9d6c72017-12-25 04:15:38 +00004240 stp->iNtOfst = acttab_insert(pActtab, 0);
drhfdbf9282003-10-21 16:34:41 +00004241 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4242 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004243 }
drh337cd0d2015-09-07 23:40:42 +00004244#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4245 { int jj, nn;
4246 for(jj=nn=0; jj<pActtab->nAction; jj++){
4247 if( pActtab->aAction[jj].action<0 ) nn++;
4248 }
4249 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4250 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4251 ax[i].nAction, pActtab->nAction, nn);
4252 }
4253#endif
drh8b582012003-10-21 13:16:03 +00004254 }
drhfdbf9282003-10-21 16:34:41 +00004255 free(ax);
drh8b582012003-10-21 13:16:03 +00004256
drh756b41e2016-05-24 18:55:08 +00004257 /* Mark rules that are actually used for reduce actions after all
4258 ** optimizations have been applied
4259 */
4260 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4261 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004262 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4263 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004264 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004265 }
4266 }
4267 }
4268
drh3bd48ab2015-09-07 18:23:37 +00004269 /* Finish rendering the constants now that the action table has
4270 ** been computed */
4271 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4272 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh0d9de992017-12-26 18:04:23 +00004273 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004274 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004275 i = lemp->minShiftReduce;
4276 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4277 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004278 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004279 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4280 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4281 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4282 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4283 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004284 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004285 tplt_xfer(lemp->name,in,out,&lineno);
4286
4287 /* Now output the action table and its associates:
4288 **
4289 ** yy_action[] A single table containing all actions.
4290 ** yy_lookahead[] A table containing the lookahead for each entry in
4291 ** yy_action. Used to detect hash collisions.
4292 ** yy_shift_ofst[] For each state, the offset into yy_action for
4293 ** shifting terminals.
4294 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4295 ** shifting non-terminals after a reduce.
4296 ** yy_default[] Default action for each state.
4297 */
4298
drh8b582012003-10-21 13:16:03 +00004299 /* Output the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +00004300 lemp->nactiontab = n = acttab_action_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004301 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004302 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4303 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004304 for(i=j=0; i<n; i++){
4305 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004306 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004307 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004308 fprintf(out, " %4d,", action);
4309 if( j==9 || i==n-1 ){
4310 fprintf(out, "\n"); lineno++;
4311 j = 0;
4312 }else{
4313 j++;
4314 }
4315 }
4316 fprintf(out, "};\n"); lineno++;
4317
4318 /* Output the yy_lookahead table */
drh3a9d6c72017-12-25 04:15:38 +00004319 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004320 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004321 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004322 for(i=j=0; i<n; i++){
4323 int la = acttab_yylookahead(pActtab, i);
4324 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004325 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004326 fprintf(out, " %4d,", la);
4327 if( j==9 || i==n-1 ){
4328 fprintf(out, "\n"); lineno++;
4329 j = 0;
4330 }else{
4331 j++;
4332 }
4333 }
4334 fprintf(out, "};\n"); lineno++;
4335
4336 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004337 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004338 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004339 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4340 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4341 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004342 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004343 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4344 lineno++;
drhc75e0162015-09-07 02:23:02 +00004345 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004346 for(i=j=0; i<n; i++){
4347 int ofst;
4348 stp = lemp->sorted[i];
4349 ofst = stp->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004350 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
drhfdbf9282003-10-21 16:34:41 +00004351 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004352 fprintf(out, " %4d,", ofst);
4353 if( j==9 || i==n-1 ){
4354 fprintf(out, "\n"); lineno++;
4355 j = 0;
4356 }else{
4357 j++;
4358 }
4359 }
4360 fprintf(out, "};\n"); lineno++;
4361
4362 /* Output the yy_reduce_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004363 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004364 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004365 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4366 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4367 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004368 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004369 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4370 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004371 for(i=j=0; i<n; i++){
4372 int ofst;
4373 stp = lemp->sorted[i];
4374 ofst = stp->iNtOfst;
4375 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004376 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004377 fprintf(out, " %4d,", ofst);
4378 if( j==9 || i==n-1 ){
4379 fprintf(out, "\n"); lineno++;
4380 j = 0;
4381 }else{
4382 j++;
4383 }
4384 }
4385 fprintf(out, "};\n"); lineno++;
4386
4387 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004388 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004389 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004390 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004391 for(i=j=0; i<n; i++){
4392 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004393 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004394 if( stp->iDfltReduce<0 ){
4395 fprintf(out, " %4d,", lemp->errAction);
4396 }else{
4397 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4398 }
drh8b582012003-10-21 13:16:03 +00004399 if( j==9 || i==n-1 ){
4400 fprintf(out, "\n"); lineno++;
4401 j = 0;
4402 }else{
4403 j++;
4404 }
4405 }
4406 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004407 tplt_xfer(lemp->name,in,out,&lineno);
4408
drh0bd1f4e2002-06-06 18:54:39 +00004409 /* Generate the table of fallback tokens.
4410 */
4411 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004412 int mx = lemp->nterminal - 1;
4413 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004414 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004415 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004416 struct symbol *p = lemp->symbols[i];
4417 if( p->fallback==0 ){
4418 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4419 }else{
4420 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4421 p->name, p->fallback->name);
4422 }
4423 lineno++;
4424 }
4425 }
4426 tplt_xfer(lemp->name, in, out, &lineno);
4427
4428 /* Generate a table containing the symbolic name of every symbol
4429 */
drh75897232000-05-29 14:26:00 +00004430 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004431 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh3a9d6c72017-12-25 04:15:38 +00004432 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
drh75897232000-05-29 14:26:00 +00004433 }
drh75897232000-05-29 14:26:00 +00004434 tplt_xfer(lemp->name,in,out,&lineno);
4435
drh0bd1f4e2002-06-06 18:54:39 +00004436 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004437 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004438 ** when tracing REDUCE actions.
4439 */
4440 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004441 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004442 fprintf(out," /* %3d */ \"", i);
4443 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004444 fprintf(out,"\",\n"); lineno++;
4445 }
4446 tplt_xfer(lemp->name,in,out,&lineno);
4447
drh75897232000-05-29 14:26:00 +00004448 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004449 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004450 ** (In other words, generate the %destructor actions)
4451 */
drh75897232000-05-29 14:26:00 +00004452 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004453 int once = 1;
drh75897232000-05-29 14:26:00 +00004454 for(i=0; i<lemp->nsymbol; i++){
4455 struct symbol *sp = lemp->symbols[i];
4456 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004457 if( once ){
4458 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4459 once = 0;
4460 }
drhc53eed12009-06-12 17:46:19 +00004461 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004462 }
4463 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4464 if( i<lemp->nsymbol ){
4465 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4466 fprintf(out," break;\n"); lineno++;
4467 }
4468 }
drh8d659732005-01-13 23:54:06 +00004469 if( lemp->vardest ){
4470 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004471 int once = 1;
drh8d659732005-01-13 23:54:06 +00004472 for(i=0; i<lemp->nsymbol; i++){
4473 struct symbol *sp = lemp->symbols[i];
4474 if( sp==0 || sp->type==TERMINAL ||
4475 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004476 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004477 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004478 once = 0;
4479 }
drhc53eed12009-06-12 17:46:19 +00004480 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004481 dflt_sp = sp;
4482 }
4483 if( dflt_sp!=0 ){
4484 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004485 }
drh4dc8ef52008-07-01 17:13:57 +00004486 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004487 }
drh75897232000-05-29 14:26:00 +00004488 for(i=0; i<lemp->nsymbol; i++){
4489 struct symbol *sp = lemp->symbols[i];
4490 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004491 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004492 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004493
4494 /* Combine duplicate destructors into a single case */
4495 for(j=i+1; j<lemp->nsymbol; j++){
4496 struct symbol *sp2 = lemp->symbols[j];
4497 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4498 && sp2->dtnum==sp->dtnum
4499 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004500 fprintf(out," case %d: /* %s */\n",
4501 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004502 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004503 }
4504 }
4505
drh75897232000-05-29 14:26:00 +00004506 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4507 fprintf(out," break;\n"); lineno++;
4508 }
drh75897232000-05-29 14:26:00 +00004509 tplt_xfer(lemp->name,in,out,&lineno);
4510
4511 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004512 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004513 tplt_xfer(lemp->name,in,out,&lineno);
4514
drh06f60d82017-04-14 19:46:12 +00004515 /* Generate the table of rule information
drh75897232000-05-29 14:26:00 +00004516 **
4517 ** Note: This code depends on the fact that rules are number
4518 ** sequentually beginning with 0.
4519 */
drh5c8241b2017-12-24 23:38:10 +00004520 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4521 fprintf(out," { %4d, %4d }, /* (%d) ",rp->lhs->index,-rp->nrhs,i);
4522 rule_print(out, rp);
4523 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004524 }
4525 tplt_xfer(lemp->name,in,out,&lineno);
4526
4527 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004528 i = 0;
drh75897232000-05-29 14:26:00 +00004529 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004530 i += translate_code(lemp, rp);
4531 }
4532 if( i ){
4533 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004534 }
drhc53eed12009-06-12 17:46:19 +00004535 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004536 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004537 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004538 if( rp->codeEmitted ) continue;
4539 if( rp->noCode ){
4540 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004541 continue;
4542 }
drh4ef07702016-03-16 19:45:54 +00004543 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004544 writeRuleText(out, rp);
4545 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004546 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004547 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4548 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004549 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004550 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004551 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004552 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004553 }
4554 }
drh75897232000-05-29 14:26:00 +00004555 emit_code(out,rp,lemp,&lineno);
4556 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004557 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004558 }
drhc53eed12009-06-12 17:46:19 +00004559 /* Finally, output the default: rule. We choose as the default: all
4560 ** empty actions. */
4561 fprintf(out," default:\n"); lineno++;
4562 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004563 if( rp->codeEmitted ) continue;
4564 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004565 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004566 writeRuleText(out, rp);
drh756b41e2016-05-24 18:55:08 +00004567 if( rp->doesReduce ){
4568 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4569 }else{
4570 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4571 rp->iRule); lineno++;
4572 }
drhc53eed12009-06-12 17:46:19 +00004573 }
4574 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004575 tplt_xfer(lemp->name,in,out,&lineno);
4576
4577 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004578 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004579 tplt_xfer(lemp->name,in,out,&lineno);
4580
4581 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004582 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004583 tplt_xfer(lemp->name,in,out,&lineno);
4584
4585 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004586 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004587 tplt_xfer(lemp->name,in,out,&lineno);
4588
4589 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004590 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004591
4592 fclose(in);
4593 fclose(out);
4594 return;
4595}
4596
4597/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004598void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004599{
4600 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004601 const char *prefix;
drh75897232000-05-29 14:26:00 +00004602 char line[LINESIZE];
4603 char pattern[LINESIZE];
4604 int i;
4605
4606 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4607 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004608 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004609 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004610 int nextChar;
drh75897232000-05-29 14:26:00 +00004611 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004612 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4613 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004614 if( strcmp(line,pattern) ) break;
4615 }
drh8ba0d1c2012-06-16 15:26:31 +00004616 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004617 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004618 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004619 /* No change in the file. Don't rewrite it. */
4620 return;
4621 }
4622 }
drh2aa6ca42004-09-10 00:14:04 +00004623 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004624 if( out ){
4625 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004626 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004627 }
drh06f60d82017-04-14 19:46:12 +00004628 fclose(out);
drh75897232000-05-29 14:26:00 +00004629 }
4630 return;
4631}
4632
4633/* Reduce the size of the action tables, if possible, by making use
4634** of defaults.
4635**
drhb59499c2002-02-23 18:45:13 +00004636** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004637** it the default. Except, there is no default if the wildcard token
4638** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004639*/
icculus9e44cf12010-02-14 17:14:22 +00004640void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004641{
4642 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004643 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004644 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004645 int nbest, n;
drh75897232000-05-29 14:26:00 +00004646 int i;
drhe09daa92006-06-10 13:29:31 +00004647 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004648
4649 for(i=0; i<lemp->nstate; i++){
4650 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004651 nbest = 0;
4652 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004653 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004654
drhb59499c2002-02-23 18:45:13 +00004655 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004656 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4657 usesWildcard = 1;
4658 }
drhb59499c2002-02-23 18:45:13 +00004659 if( ap->type!=REDUCE ) continue;
4660 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004661 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004662 if( rp==rbest ) continue;
4663 n = 1;
4664 for(ap2=ap->next; ap2; ap2=ap2->next){
4665 if( ap2->type!=REDUCE ) continue;
4666 rp2 = ap2->x.rp;
4667 if( rp2==rbest ) continue;
4668 if( rp2==rp ) n++;
4669 }
4670 if( n>nbest ){
4671 nbest = n;
4672 rbest = rp;
drh75897232000-05-29 14:26:00 +00004673 }
4674 }
drh06f60d82017-04-14 19:46:12 +00004675
drhb59499c2002-02-23 18:45:13 +00004676 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004677 ** is not at least 1 or if the wildcard token is a possible
4678 ** lookahead.
4679 */
4680 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004681
drhb59499c2002-02-23 18:45:13 +00004682
4683 /* Combine matching REDUCE actions into a single default */
4684 for(ap=stp->ap; ap; ap=ap->next){
4685 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4686 }
drh75897232000-05-29 14:26:00 +00004687 assert( ap );
4688 ap->sp = Symbol_new("{default}");
4689 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004690 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004691 }
4692 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004693
4694 for(ap=stp->ap; ap; ap=ap->next){
4695 if( ap->type==SHIFT ) break;
4696 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4697 }
4698 if( ap==0 ){
4699 stp->autoReduce = 1;
4700 stp->pDfltReduce = rbest;
4701 }
4702 }
4703
4704 /* Make a second pass over all states and actions. Convert
4705 ** every action that is a SHIFT to an autoReduce state into
4706 ** a SHIFTREDUCE action.
4707 */
4708 for(i=0; i<lemp->nstate; i++){
4709 stp = lemp->sorted[i];
4710 for(ap=stp->ap; ap; ap=ap->next){
4711 struct state *pNextState;
4712 if( ap->type!=SHIFT ) continue;
4713 pNextState = ap->x.stp;
4714 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4715 ap->type = SHIFTREDUCE;
4716 ap->x.rp = pNextState->pDfltReduce;
4717 }
4718 }
drh75897232000-05-29 14:26:00 +00004719 }
drhc173ad82016-05-23 16:15:02 +00004720
4721 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4722 ** (meaning that the SHIFTREDUCE will land back in the state where it
4723 ** started) and if there is no C-code associated with the reduce action,
4724 ** then we can go ahead and convert the action to be the same as the
4725 ** action for the RHS of the rule.
4726 */
4727 for(i=0; i<lemp->nstate; i++){
4728 stp = lemp->sorted[i];
4729 for(ap=stp->ap; ap; ap=nextap){
4730 nextap = ap->next;
4731 if( ap->type!=SHIFTREDUCE ) continue;
4732 rp = ap->x.rp;
4733 if( rp->noCode==0 ) continue;
4734 if( rp->nrhs!=1 ) continue;
4735#if 1
4736 /* Only apply this optimization to non-terminals. It would be OK to
4737 ** apply it to terminal symbols too, but that makes the parser tables
4738 ** larger. */
4739 if( ap->sp->index<lemp->nterminal ) continue;
4740#endif
4741 /* If we reach this point, it means the optimization can be applied */
4742 nextap = ap;
4743 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4744 assert( ap2!=0 );
4745 ap->spOpt = ap2->sp;
4746 ap->type = ap2->type;
4747 ap->x = ap2->x;
4748 }
4749 }
drh75897232000-05-29 14:26:00 +00004750}
drhb59499c2002-02-23 18:45:13 +00004751
drhada354d2005-11-05 15:03:59 +00004752
4753/*
4754** Compare two states for sorting purposes. The smaller state is the
4755** one with the most non-terminal actions. If they have the same number
4756** of non-terminal actions, then the smaller is the one with the most
4757** token actions.
4758*/
4759static int stateResortCompare(const void *a, const void *b){
4760 const struct state *pA = *(const struct state**)a;
4761 const struct state *pB = *(const struct state**)b;
4762 int n;
4763
4764 n = pB->nNtAct - pA->nNtAct;
4765 if( n==0 ){
4766 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004767 if( n==0 ){
4768 n = pB->statenum - pA->statenum;
4769 }
drhada354d2005-11-05 15:03:59 +00004770 }
drhe594bc32009-11-03 13:02:25 +00004771 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004772 return n;
4773}
4774
4775
4776/*
4777** Renumber and resort states so that states with fewer choices
4778** occur at the end. Except, keep state 0 as the first state.
4779*/
icculus9e44cf12010-02-14 17:14:22 +00004780void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004781{
4782 int i;
4783 struct state *stp;
4784 struct action *ap;
4785
4786 for(i=0; i<lemp->nstate; i++){
4787 stp = lemp->sorted[i];
4788 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00004789 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004790 stp->iTknOfst = NO_OFFSET;
4791 stp->iNtOfst = NO_OFFSET;
4792 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004793 int iAction = compute_action(lemp,ap);
4794 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004795 if( ap->sp->index<lemp->nterminal ){
4796 stp->nTknAct++;
4797 }else if( ap->sp->index<lemp->nsymbol ){
4798 stp->nNtAct++;
4799 }else{
drh3bd48ab2015-09-07 18:23:37 +00004800 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00004801 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00004802 }
4803 }
4804 }
4805 }
4806 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4807 stateResortCompare);
4808 for(i=0; i<lemp->nstate; i++){
4809 lemp->sorted[i]->statenum = i;
4810 }
drh3bd48ab2015-09-07 18:23:37 +00004811 lemp->nxstate = lemp->nstate;
4812 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4813 lemp->nxstate--;
4814 }
drhada354d2005-11-05 15:03:59 +00004815}
4816
4817
drh75897232000-05-29 14:26:00 +00004818/***************** From the file "set.c" ************************************/
4819/*
4820** Set manipulation routines for the LEMON parser generator.
4821*/
4822
4823static int size = 0;
4824
4825/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004826void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004827{
4828 size = n+1;
4829}
4830
4831/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00004832char *SetNew(void){
drh75897232000-05-29 14:26:00 +00004833 char *s;
drh9892c5d2007-12-21 00:02:11 +00004834 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004835 if( s==0 ){
4836 extern void memory_error();
4837 memory_error();
4838 }
drh75897232000-05-29 14:26:00 +00004839 return s;
4840}
4841
4842/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004843void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004844{
4845 free(s);
4846}
4847
4848/* Add a new element to the set. Return TRUE if the element was added
4849** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004850int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004851{
4852 int rv;
drh9892c5d2007-12-21 00:02:11 +00004853 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004854 rv = s[e];
4855 s[e] = 1;
4856 return !rv;
4857}
4858
4859/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004860int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004861{
4862 int i, progress;
4863 progress = 0;
4864 for(i=0; i<size; i++){
4865 if( s2[i]==0 ) continue;
4866 if( s1[i]==0 ){
4867 progress = 1;
4868 s1[i] = 1;
4869 }
4870 }
4871 return progress;
4872}
4873/********************** From the file "table.c" ****************************/
4874/*
4875** All code in this file has been automatically generated
4876** from a specification in the file
4877** "table.q"
4878** by the associative array code building program "aagen".
4879** Do not edit this file! Instead, edit the specification
4880** file, then rerun aagen.
4881*/
4882/*
4883** Code for processing tables in the LEMON parser generator.
4884*/
4885
drh01f75f22013-10-02 20:46:30 +00004886PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004887{
drh01f75f22013-10-02 20:46:30 +00004888 unsigned h = 0;
4889 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004890 return h;
4891}
4892
4893/* Works like strdup, sort of. Save a string in malloced memory, but
4894** keep strings in a table so that the same string is not in more
4895** than one place.
4896*/
icculus9e44cf12010-02-14 17:14:22 +00004897const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004898{
icculus9e44cf12010-02-14 17:14:22 +00004899 const char *z;
4900 char *cpy;
drh75897232000-05-29 14:26:00 +00004901
drh916f75f2006-07-17 00:19:39 +00004902 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004903 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004904 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004905 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004906 z = cpy;
drh75897232000-05-29 14:26:00 +00004907 Strsafe_insert(z);
4908 }
4909 MemoryCheck(z);
4910 return z;
4911}
4912
4913/* There is one instance of the following structure for each
4914** associative array of type "x1".
4915*/
4916struct s_x1 {
4917 int size; /* The number of available slots. */
4918 /* Must be a power of 2 greater than or */
4919 /* equal to 1 */
4920 int count; /* Number of currently slots filled */
4921 struct s_x1node *tbl; /* The data stored here */
4922 struct s_x1node **ht; /* Hash table for lookups */
4923};
4924
4925/* There is one instance of this structure for every data element
4926** in an associative array of type "x1".
4927*/
4928typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004929 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004930 struct s_x1node *next; /* Next entry with the same hash */
4931 struct s_x1node **from; /* Previous link */
4932} x1node;
4933
4934/* There is only one instance of the array, which is the following */
4935static struct s_x1 *x1a;
4936
4937/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00004938void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00004939 if( x1a ) return;
4940 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4941 if( x1a ){
4942 x1a->size = 1024;
4943 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004944 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004945 if( x1a->tbl==0 ){
4946 free(x1a);
4947 x1a = 0;
4948 }else{
4949 int i;
4950 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4951 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4952 }
4953 }
4954}
4955/* Insert a new record into the array. Return TRUE if successful.
4956** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004957int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004958{
4959 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004960 unsigned h;
4961 unsigned ph;
drh75897232000-05-29 14:26:00 +00004962
4963 if( x1a==0 ) return 0;
4964 ph = strhash(data);
4965 h = ph & (x1a->size-1);
4966 np = x1a->ht[h];
4967 while( np ){
4968 if( strcmp(np->data,data)==0 ){
4969 /* An existing entry with the same key is found. */
4970 /* Fail because overwrite is not allows. */
4971 return 0;
4972 }
4973 np = np->next;
4974 }
4975 if( x1a->count>=x1a->size ){
4976 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004977 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004978 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004979 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004980 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004981 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004982 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004983 array.ht = (x1node**)&(array.tbl[arrSize]);
4984 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004985 for(i=0; i<x1a->count; i++){
4986 x1node *oldnp, *newnp;
4987 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004988 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004989 newnp = &(array.tbl[i]);
4990 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4991 newnp->next = array.ht[h];
4992 newnp->data = oldnp->data;
4993 newnp->from = &(array.ht[h]);
4994 array.ht[h] = newnp;
4995 }
4996 free(x1a->tbl);
4997 *x1a = array;
4998 }
4999 /* Insert the new data */
5000 h = ph & (x1a->size-1);
5001 np = &(x1a->tbl[x1a->count++]);
5002 np->data = data;
5003 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5004 np->next = x1a->ht[h];
5005 x1a->ht[h] = np;
5006 np->from = &(x1a->ht[h]);
5007 return 1;
5008}
5009
5010/* Return a pointer to data assigned to the given key. Return NULL
5011** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005012const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00005013{
drh01f75f22013-10-02 20:46:30 +00005014 unsigned h;
drh75897232000-05-29 14:26:00 +00005015 x1node *np;
5016
5017 if( x1a==0 ) return 0;
5018 h = strhash(key) & (x1a->size-1);
5019 np = x1a->ht[h];
5020 while( np ){
5021 if( strcmp(np->data,key)==0 ) break;
5022 np = np->next;
5023 }
5024 return np ? np->data : 0;
5025}
5026
5027/* Return a pointer to the (terminal or nonterminal) symbol "x".
5028** Create a new symbol if this is the first time "x" has been seen.
5029*/
icculus9e44cf12010-02-14 17:14:22 +00005030struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00005031{
5032 struct symbol *sp;
5033
5034 sp = Symbol_find(x);
5035 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00005036 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00005037 MemoryCheck(sp);
5038 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00005039 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00005040 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00005041 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00005042 sp->prec = -1;
5043 sp->assoc = UNK;
5044 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005045 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005046 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005047 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005048 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005049 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005050 Symbol_insert(sp,sp->name);
5051 }
drhc4dd3fd2008-01-22 01:48:05 +00005052 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005053 return sp;
5054}
5055
drh61f92cd2014-01-11 03:06:18 +00005056/* Compare two symbols for sorting purposes. Return negative,
5057** zero, or positive if a is less then, equal to, or greater
5058** than b.
drh60d31652004-02-22 00:08:04 +00005059**
5060** Symbols that begin with upper case letters (terminals or tokens)
5061** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005062** (non-terminals). And MULTITERMINAL symbols (created using the
5063** %token_class directive) must sort at the very end. Other than
5064** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005065**
5066** We find experimentally that leaving the symbols in their original
5067** order (the order they appeared in the grammar file) gives the
5068** smallest parser tables in SQLite.
5069*/
icculus9e44cf12010-02-14 17:14:22 +00005070int Symbolcmpp(const void *_a, const void *_b)
5071{
drh61f92cd2014-01-11 03:06:18 +00005072 const struct symbol *a = *(const struct symbol **) _a;
5073 const struct symbol *b = *(const struct symbol **) _b;
5074 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5075 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5076 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005077}
5078
5079/* There is one instance of the following structure for each
5080** associative array of type "x2".
5081*/
5082struct s_x2 {
5083 int size; /* The number of available slots. */
5084 /* Must be a power of 2 greater than or */
5085 /* equal to 1 */
5086 int count; /* Number of currently slots filled */
5087 struct s_x2node *tbl; /* The data stored here */
5088 struct s_x2node **ht; /* Hash table for lookups */
5089};
5090
5091/* There is one instance of this structure for every data element
5092** in an associative array of type "x2".
5093*/
5094typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005095 struct symbol *data; /* The data */
5096 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005097 struct s_x2node *next; /* Next entry with the same hash */
5098 struct s_x2node **from; /* Previous link */
5099} x2node;
5100
5101/* There is only one instance of the array, which is the following */
5102static struct s_x2 *x2a;
5103
5104/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005105void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005106 if( x2a ) return;
5107 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5108 if( x2a ){
5109 x2a->size = 128;
5110 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005111 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005112 if( x2a->tbl==0 ){
5113 free(x2a);
5114 x2a = 0;
5115 }else{
5116 int i;
5117 x2a->ht = (x2node**)&(x2a->tbl[128]);
5118 for(i=0; i<128; i++) x2a->ht[i] = 0;
5119 }
5120 }
5121}
5122/* Insert a new record into the array. Return TRUE if successful.
5123** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005124int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005125{
5126 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005127 unsigned h;
5128 unsigned ph;
drh75897232000-05-29 14:26:00 +00005129
5130 if( x2a==0 ) return 0;
5131 ph = strhash(key);
5132 h = ph & (x2a->size-1);
5133 np = x2a->ht[h];
5134 while( np ){
5135 if( strcmp(np->key,key)==0 ){
5136 /* An existing entry with the same key is found. */
5137 /* Fail because overwrite is not allows. */
5138 return 0;
5139 }
5140 np = np->next;
5141 }
5142 if( x2a->count>=x2a->size ){
5143 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005144 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005145 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005146 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005147 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005148 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005149 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005150 array.ht = (x2node**)&(array.tbl[arrSize]);
5151 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005152 for(i=0; i<x2a->count; i++){
5153 x2node *oldnp, *newnp;
5154 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005155 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005156 newnp = &(array.tbl[i]);
5157 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5158 newnp->next = array.ht[h];
5159 newnp->key = oldnp->key;
5160 newnp->data = oldnp->data;
5161 newnp->from = &(array.ht[h]);
5162 array.ht[h] = newnp;
5163 }
5164 free(x2a->tbl);
5165 *x2a = array;
5166 }
5167 /* Insert the new data */
5168 h = ph & (x2a->size-1);
5169 np = &(x2a->tbl[x2a->count++]);
5170 np->key = key;
5171 np->data = data;
5172 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5173 np->next = x2a->ht[h];
5174 x2a->ht[h] = np;
5175 np->from = &(x2a->ht[h]);
5176 return 1;
5177}
5178
5179/* Return a pointer to data assigned to the given key. Return NULL
5180** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005181struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005182{
drh01f75f22013-10-02 20:46:30 +00005183 unsigned h;
drh75897232000-05-29 14:26:00 +00005184 x2node *np;
5185
5186 if( x2a==0 ) return 0;
5187 h = strhash(key) & (x2a->size-1);
5188 np = x2a->ht[h];
5189 while( np ){
5190 if( strcmp(np->key,key)==0 ) break;
5191 np = np->next;
5192 }
5193 return np ? np->data : 0;
5194}
5195
5196/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005197struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005198{
5199 struct symbol *data;
5200 if( x2a && n>0 && n<=x2a->count ){
5201 data = x2a->tbl[n-1].data;
5202 }else{
5203 data = 0;
5204 }
5205 return data;
5206}
5207
5208/* Return the size of the array */
5209int Symbol_count()
5210{
5211 return x2a ? x2a->count : 0;
5212}
5213
5214/* Return an array of pointers to all data in the table.
5215** The array is obtained from malloc. Return NULL if memory allocation
5216** problems, or if the array is empty. */
5217struct symbol **Symbol_arrayof()
5218{
5219 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005220 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005221 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005222 arrSize = x2a->count;
5223 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005224 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005225 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005226 }
5227 return array;
5228}
5229
5230/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005231int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005232{
icculus9e44cf12010-02-14 17:14:22 +00005233 const struct config *a = (struct config *) _a;
5234 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005235 int x;
5236 x = a->rp->index - b->rp->index;
5237 if( x==0 ) x = a->dot - b->dot;
5238 return x;
5239}
5240
5241/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005242PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005243{
5244 int rc;
5245 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5246 rc = a->rp->index - b->rp->index;
5247 if( rc==0 ) rc = a->dot - b->dot;
5248 }
5249 if( rc==0 ){
5250 if( a ) rc = 1;
5251 if( b ) rc = -1;
5252 }
5253 return rc;
5254}
5255
5256/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005257PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005258{
drh01f75f22013-10-02 20:46:30 +00005259 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005260 while( a ){
5261 h = h*571 + a->rp->index*37 + a->dot;
5262 a = a->bp;
5263 }
5264 return h;
5265}
5266
5267/* Allocate a new state structure */
5268struct state *State_new()
5269{
icculus9e44cf12010-02-14 17:14:22 +00005270 struct state *newstate;
5271 newstate = (struct state *)calloc(1, sizeof(struct state) );
5272 MemoryCheck(newstate);
5273 return newstate;
drh75897232000-05-29 14:26:00 +00005274}
5275
5276/* There is one instance of the following structure for each
5277** associative array of type "x3".
5278*/
5279struct s_x3 {
5280 int size; /* The number of available slots. */
5281 /* Must be a power of 2 greater than or */
5282 /* equal to 1 */
5283 int count; /* Number of currently slots filled */
5284 struct s_x3node *tbl; /* The data stored here */
5285 struct s_x3node **ht; /* Hash table for lookups */
5286};
5287
5288/* There is one instance of this structure for every data element
5289** in an associative array of type "x3".
5290*/
5291typedef struct s_x3node {
5292 struct state *data; /* The data */
5293 struct config *key; /* The key */
5294 struct s_x3node *next; /* Next entry with the same hash */
5295 struct s_x3node **from; /* Previous link */
5296} x3node;
5297
5298/* There is only one instance of the array, which is the following */
5299static struct s_x3 *x3a;
5300
5301/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005302void State_init(void){
drh75897232000-05-29 14:26:00 +00005303 if( x3a ) return;
5304 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5305 if( x3a ){
5306 x3a->size = 128;
5307 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005308 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005309 if( x3a->tbl==0 ){
5310 free(x3a);
5311 x3a = 0;
5312 }else{
5313 int i;
5314 x3a->ht = (x3node**)&(x3a->tbl[128]);
5315 for(i=0; i<128; i++) x3a->ht[i] = 0;
5316 }
5317 }
5318}
5319/* Insert a new record into the array. Return TRUE if successful.
5320** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005321int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005322{
5323 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005324 unsigned h;
5325 unsigned ph;
drh75897232000-05-29 14:26:00 +00005326
5327 if( x3a==0 ) return 0;
5328 ph = statehash(key);
5329 h = ph & (x3a->size-1);
5330 np = x3a->ht[h];
5331 while( np ){
5332 if( statecmp(np->key,key)==0 ){
5333 /* An existing entry with the same key is found. */
5334 /* Fail because overwrite is not allows. */
5335 return 0;
5336 }
5337 np = np->next;
5338 }
5339 if( x3a->count>=x3a->size ){
5340 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005341 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005342 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005343 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005344 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005345 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005346 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005347 array.ht = (x3node**)&(array.tbl[arrSize]);
5348 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005349 for(i=0; i<x3a->count; i++){
5350 x3node *oldnp, *newnp;
5351 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005352 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005353 newnp = &(array.tbl[i]);
5354 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5355 newnp->next = array.ht[h];
5356 newnp->key = oldnp->key;
5357 newnp->data = oldnp->data;
5358 newnp->from = &(array.ht[h]);
5359 array.ht[h] = newnp;
5360 }
5361 free(x3a->tbl);
5362 *x3a = array;
5363 }
5364 /* Insert the new data */
5365 h = ph & (x3a->size-1);
5366 np = &(x3a->tbl[x3a->count++]);
5367 np->key = key;
5368 np->data = data;
5369 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5370 np->next = x3a->ht[h];
5371 x3a->ht[h] = np;
5372 np->from = &(x3a->ht[h]);
5373 return 1;
5374}
5375
5376/* Return a pointer to data assigned to the given key. Return NULL
5377** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005378struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005379{
drh01f75f22013-10-02 20:46:30 +00005380 unsigned h;
drh75897232000-05-29 14:26:00 +00005381 x3node *np;
5382
5383 if( x3a==0 ) return 0;
5384 h = statehash(key) & (x3a->size-1);
5385 np = x3a->ht[h];
5386 while( np ){
5387 if( statecmp(np->key,key)==0 ) break;
5388 np = np->next;
5389 }
5390 return np ? np->data : 0;
5391}
5392
5393/* Return an array of pointers to all data in the table.
5394** The array is obtained from malloc. Return NULL if memory allocation
5395** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005396struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005397{
5398 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005399 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005400 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005401 arrSize = x3a->count;
5402 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005403 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005404 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005405 }
5406 return array;
5407}
5408
5409/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005410PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005411{
drh01f75f22013-10-02 20:46:30 +00005412 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005413 h = h*571 + a->rp->index*37 + a->dot;
5414 return h;
5415}
5416
5417/* There is one instance of the following structure for each
5418** associative array of type "x4".
5419*/
5420struct s_x4 {
5421 int size; /* The number of available slots. */
5422 /* Must be a power of 2 greater than or */
5423 /* equal to 1 */
5424 int count; /* Number of currently slots filled */
5425 struct s_x4node *tbl; /* The data stored here */
5426 struct s_x4node **ht; /* Hash table for lookups */
5427};
5428
5429/* There is one instance of this structure for every data element
5430** in an associative array of type "x4".
5431*/
5432typedef struct s_x4node {
5433 struct config *data; /* The data */
5434 struct s_x4node *next; /* Next entry with the same hash */
5435 struct s_x4node **from; /* Previous link */
5436} x4node;
5437
5438/* There is only one instance of the array, which is the following */
5439static struct s_x4 *x4a;
5440
5441/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005442void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005443 if( x4a ) return;
5444 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5445 if( x4a ){
5446 x4a->size = 64;
5447 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005448 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005449 if( x4a->tbl==0 ){
5450 free(x4a);
5451 x4a = 0;
5452 }else{
5453 int i;
5454 x4a->ht = (x4node**)&(x4a->tbl[64]);
5455 for(i=0; i<64; i++) x4a->ht[i] = 0;
5456 }
5457 }
5458}
5459/* Insert a new record into the array. Return TRUE if successful.
5460** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005461int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005462{
5463 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005464 unsigned h;
5465 unsigned ph;
drh75897232000-05-29 14:26:00 +00005466
5467 if( x4a==0 ) return 0;
5468 ph = confighash(data);
5469 h = ph & (x4a->size-1);
5470 np = x4a->ht[h];
5471 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005472 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005473 /* An existing entry with the same key is found. */
5474 /* Fail because overwrite is not allows. */
5475 return 0;
5476 }
5477 np = np->next;
5478 }
5479 if( x4a->count>=x4a->size ){
5480 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005481 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005482 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005483 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005484 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005485 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005486 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005487 array.ht = (x4node**)&(array.tbl[arrSize]);
5488 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005489 for(i=0; i<x4a->count; i++){
5490 x4node *oldnp, *newnp;
5491 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005492 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005493 newnp = &(array.tbl[i]);
5494 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5495 newnp->next = array.ht[h];
5496 newnp->data = oldnp->data;
5497 newnp->from = &(array.ht[h]);
5498 array.ht[h] = newnp;
5499 }
5500 free(x4a->tbl);
5501 *x4a = array;
5502 }
5503 /* Insert the new data */
5504 h = ph & (x4a->size-1);
5505 np = &(x4a->tbl[x4a->count++]);
5506 np->data = data;
5507 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5508 np->next = x4a->ht[h];
5509 x4a->ht[h] = np;
5510 np->from = &(x4a->ht[h]);
5511 return 1;
5512}
5513
5514/* Return a pointer to data assigned to the given key. Return NULL
5515** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005516struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005517{
5518 int h;
5519 x4node *np;
5520
5521 if( x4a==0 ) return 0;
5522 h = confighash(key) & (x4a->size-1);
5523 np = x4a->ht[h];
5524 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005525 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005526 np = np->next;
5527 }
5528 return np ? np->data : 0;
5529}
5530
5531/* Remove all data from the table. Pass each data to the function "f"
5532** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005533void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005534{
5535 int i;
5536 if( x4a==0 || x4a->count==0 ) return;
5537 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5538 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5539 x4a->count = 0;
5540 return;
5541}