blob: 926e4cdd45712cf12879fdbbe7693525b9c39b87 [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 */
drhfb32c442018-04-21 13:51:42 +0000399 char *ctx; /* Declaration of 2nd argument to constructor */
drh75897232000-05-29 14:26:00 +0000400 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000401 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000402 char *start; /* Name of the start symbol for the grammar */
403 char *stacksize; /* Size of the parser stack */
404 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000405 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000406 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000407 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000408 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000409 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000410 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000411 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000412 char *filename; /* Name of the input file */
413 char *outname; /* Name of the current output file */
414 char *tokenprefix; /* A prefix added to token names in the .h file */
415 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000416 int nactiontab; /* Number of entries in the yy_action[] table */
drh3a9d6c72017-12-25 04:15:38 +0000417 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
drhc75e0162015-09-07 02:23:02 +0000418 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000419 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000420 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000421 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000422 char *argv0; /* Name of the program */
423};
424
425#define MemoryCheck(X) if((X)==0){ \
426 extern void memory_error(); \
427 memory_error(); \
428}
429
430/**************** From the file "table.h" *********************************/
431/*
432** All code in this file has been automatically generated
433** from a specification in the file
434** "table.q"
435** by the associative array code building program "aagen".
436** Do not edit this file! Instead, edit the specification
437** file, then rerun aagen.
438*/
439/*
440** Code for processing tables in the LEMON parser generator.
441*/
drh75897232000-05-29 14:26:00 +0000442/* Routines for handling a strings */
443
icculus9e44cf12010-02-14 17:14:22 +0000444const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000445
icculus9e44cf12010-02-14 17:14:22 +0000446void Strsafe_init(void);
447int Strsafe_insert(const char *);
448const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000449
450/* Routines for handling symbols of the grammar */
451
icculus9e44cf12010-02-14 17:14:22 +0000452struct symbol *Symbol_new(const char *);
453int Symbolcmpp(const void *, const void *);
454void Symbol_init(void);
455int Symbol_insert(struct symbol *, const char *);
456struct symbol *Symbol_find(const char *);
457struct symbol *Symbol_Nth(int);
458int Symbol_count(void);
459struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000460
461/* Routines to manage the state table */
462
icculus9e44cf12010-02-14 17:14:22 +0000463int Configcmp(const char *, const char *);
464struct state *State_new(void);
465void State_init(void);
466int State_insert(struct state *, struct config *);
467struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000468struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000469
470/* Routines used for efficiency in Configlist_add */
471
icculus9e44cf12010-02-14 17:14:22 +0000472void Configtable_init(void);
473int Configtable_insert(struct config *);
474struct config *Configtable_find(struct config *);
475void Configtable_clear(int(*)(struct config *));
476
drh75897232000-05-29 14:26:00 +0000477/****************** From the file "action.c" *******************************/
478/*
479** Routines processing parser actions in the LEMON parser generator.
480*/
481
482/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000483static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000484 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000485 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000486
487 if( freelist==0 ){
488 int i;
489 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000490 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000491 if( freelist==0 ){
492 fprintf(stderr,"Unable to allocate memory for a new parser action.");
493 exit(1);
494 }
495 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
496 freelist[amt-1].next = 0;
497 }
icculus9e44cf12010-02-14 17:14:22 +0000498 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000499 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000500 return newaction;
drh75897232000-05-29 14:26:00 +0000501}
502
drhe9278182007-07-18 18:16:29 +0000503/* Compare two actions for sorting purposes. Return negative, zero, or
504** positive if the first action is less than, equal to, or greater than
505** the first
506*/
507static int actioncmp(
508 struct action *ap1,
509 struct action *ap2
510){
drh75897232000-05-29 14:26:00 +0000511 int rc;
512 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000513 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000514 rc = (int)ap1->type - (int)ap2->type;
515 }
drh3bd48ab2015-09-07 18:23:37 +0000516 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000517 rc = ap1->x.rp->index - ap2->x.rp->index;
518 }
drhe594bc32009-11-03 13:02:25 +0000519 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000520 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000521 }
drh75897232000-05-29 14:26:00 +0000522 return rc;
523}
524
525/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000526static struct action *Action_sort(
527 struct action *ap
528){
529 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
530 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000531 return ap;
532}
533
icculus9e44cf12010-02-14 17:14:22 +0000534void Action_add(
535 struct action **app,
536 enum e_action type,
537 struct symbol *sp,
538 char *arg
539){
540 struct action *newaction;
541 newaction = Action_new();
542 newaction->next = *app;
543 *app = newaction;
544 newaction->type = type;
545 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000546 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000547 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000548 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000549 }else{
icculus9e44cf12010-02-14 17:14:22 +0000550 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000551 }
552}
drh8b582012003-10-21 13:16:03 +0000553/********************** New code to implement the "acttab" module ***********/
554/*
555** This module implements routines use to construct the yy_action[] table.
556*/
557
558/*
559** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000560** the following structure.
561**
562** The yy_action table maps the pair (state_number, lookahead) into an
563** action_number. The table is an array of integers pairs. The state_number
564** determines an initial offset into the yy_action array. The lookahead
565** value is then added to this initial offset to get an index X into the
566** yy_action array. If the aAction[X].lookahead equals the value of the
567** of the lookahead input, then the value of the action_number output is
568** aAction[X].action. If the lookaheads do not match then the
569** default action for the state_number is returned.
570**
571** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000572** into aLookahead[] using multiple calls to acttab_action(). Then the
573** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000574** array with a single call to acttab_insert(). The acttab_insert() call
575** also resets the aLookahead[] array in preparation for the next
576** state number.
drh8b582012003-10-21 13:16:03 +0000577*/
icculus9e44cf12010-02-14 17:14:22 +0000578struct lookahead_action {
579 int lookahead; /* Value of the lookahead token */
580 int action; /* Action to take on the given lookahead */
581};
drh8b582012003-10-21 13:16:03 +0000582typedef struct acttab acttab;
583struct acttab {
584 int nAction; /* Number of used slots in aAction[] */
585 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000586 struct lookahead_action
587 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000588 *aLookahead; /* A single new transaction set */
589 int mnLookahead; /* Minimum aLookahead[].lookahead */
590 int mnAction; /* Action associated with mnLookahead */
591 int mxLookahead; /* Maximum aLookahead[].lookahead */
592 int nLookahead; /* Used slots in aLookahead[] */
593 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
drh3a9d6c72017-12-25 04:15:38 +0000594 int nterminal; /* Number of terminal symbols */
595 int nsymbol; /* total number of symbols */
drh8b582012003-10-21 13:16:03 +0000596};
597
598/* Return the number of entries in the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +0000599#define acttab_lookahead_size(X) ((X)->nAction)
drh8b582012003-10-21 13:16:03 +0000600
601/* The value for the N-th entry in yy_action */
602#define acttab_yyaction(X,N) ((X)->aAction[N].action)
603
604/* The value for the N-th entry in yy_lookahead */
605#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
606
607/* Free all memory associated with the given acttab */
608void acttab_free(acttab *p){
609 free( p->aAction );
610 free( p->aLookahead );
611 free( p );
612}
613
614/* Allocate a new acttab structure */
drh3a9d6c72017-12-25 04:15:38 +0000615acttab *acttab_alloc(int nsymbol, int nterminal){
icculus9e44cf12010-02-14 17:14:22 +0000616 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000617 if( p==0 ){
618 fprintf(stderr,"Unable to allocate memory for a new acttab.");
619 exit(1);
620 }
621 memset(p, 0, sizeof(*p));
drh3a9d6c72017-12-25 04:15:38 +0000622 p->nsymbol = nsymbol;
623 p->nterminal = nterminal;
drh8b582012003-10-21 13:16:03 +0000624 return p;
625}
626
drh06f60d82017-04-14 19:46:12 +0000627/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000628**
629** This routine is called once for each lookahead for a particular
630** state.
drh8b582012003-10-21 13:16:03 +0000631*/
632void acttab_action(acttab *p, int lookahead, int action){
633 if( p->nLookahead>=p->nLookaheadAlloc ){
634 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000635 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000636 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
637 if( p->aLookahead==0 ){
638 fprintf(stderr,"malloc failed\n");
639 exit(1);
640 }
641 }
642 if( p->nLookahead==0 ){
643 p->mxLookahead = lookahead;
644 p->mnLookahead = lookahead;
645 p->mnAction = action;
646 }else{
647 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
648 if( p->mnLookahead>lookahead ){
649 p->mnLookahead = lookahead;
650 p->mnAction = action;
651 }
652 }
653 p->aLookahead[p->nLookahead].lookahead = lookahead;
654 p->aLookahead[p->nLookahead].action = action;
655 p->nLookahead++;
656}
657
658/*
659** Add the transaction set built up with prior calls to acttab_action()
660** into the current action table. Then reset the transaction set back
661** to an empty set in preparation for a new round of acttab_action() calls.
662**
663** Return the offset into the action table of the new transaction.
drh3a9d6c72017-12-25 04:15:38 +0000664**
665** If the makeItSafe parameter is true, then the offset is chosen so that
666** it is impossible to overread the yy_lookaside[] table regardless of
667** the lookaside token. This is done for the terminal symbols, as they
668** come from external inputs and can contain syntax errors. When makeItSafe
669** is false, there is more flexibility in selecting offsets, resulting in
670** a smaller table. For non-terminal symbols, which are never syntax errors,
671** makeItSafe can be false.
drh8b582012003-10-21 13:16:03 +0000672*/
drh3a9d6c72017-12-25 04:15:38 +0000673int acttab_insert(acttab *p, int makeItSafe){
674 int i, j, k, n, end;
drh8b582012003-10-21 13:16:03 +0000675 assert( p->nLookahead>0 );
676
677 /* Make sure we have enough space to hold the expanded action table
678 ** in the worst case. The worst case occurs if the transaction set
679 ** must be appended to the current action table
680 */
drh3a9d6c72017-12-25 04:15:38 +0000681 n = p->nsymbol + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000682 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000683 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000684 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000685 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000686 sizeof(p->aAction[0])*p->nActionAlloc);
687 if( p->aAction==0 ){
688 fprintf(stderr,"malloc failed\n");
689 exit(1);
690 }
drhfdbf9282003-10-21 16:34:41 +0000691 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000692 p->aAction[i].lookahead = -1;
693 p->aAction[i].action = -1;
694 }
695 }
696
drh06f60d82017-04-14 19:46:12 +0000697 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000698 ** duplicate of the current transaction set. Fall out of the loop
699 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000700 **
701 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
702 */
drh3a9d6c72017-12-25 04:15:38 +0000703 end = makeItSafe ? p->mnLookahead : 0;
704 for(i=p->nAction-1; i>=end; i--){
drhf16371d2009-11-03 19:18:31 +0000705 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000706 /* All lookaheads and actions in the aLookahead[] transaction
707 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000708 if( p->aAction[i].action!=p->mnAction ) continue;
709 for(j=0; j<p->nLookahead; j++){
710 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
711 if( k<0 || k>=p->nAction ) break;
712 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
713 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
714 }
715 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000716
717 /* No possible lookahead value that is not in the aLookahead[]
718 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000719 n = 0;
720 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000721 if( p->aAction[j].lookahead<0 ) continue;
722 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000723 }
drhfdbf9282003-10-21 16:34:41 +0000724 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000725 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000726 }
drh8b582012003-10-21 13:16:03 +0000727 }
728 }
drh8dc3e8f2010-01-07 03:53:03 +0000729
730 /* If no existing offsets exactly match the current transaction, find an
731 ** an empty offset in the aAction[] table in which we can add the
732 ** aLookahead[] transaction.
733 */
drh3a9d6c72017-12-25 04:15:38 +0000734 if( i<end ){
drh8dc3e8f2010-01-07 03:53:03 +0000735 /* Look for holes in the aAction[] table that fit the current
736 ** aLookahead[] transaction. Leave i set to the offset of the hole.
737 ** If no holes are found, i is left at p->nAction, which means the
738 ** transaction will be appended. */
drh3a9d6c72017-12-25 04:15:38 +0000739 i = makeItSafe ? p->mnLookahead : 0;
740 for(; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000741 if( p->aAction[i].lookahead<0 ){
742 for(j=0; j<p->nLookahead; j++){
743 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
744 if( k<0 ) break;
745 if( p->aAction[k].lookahead>=0 ) break;
746 }
747 if( j<p->nLookahead ) continue;
748 for(j=0; j<p->nAction; j++){
749 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
750 }
751 if( j==p->nAction ){
752 break; /* Fits in empty slots */
753 }
754 }
755 }
756 }
drh8b582012003-10-21 13:16:03 +0000757 /* Insert transaction set at index i. */
drh3a9d6c72017-12-25 04:15:38 +0000758#if 0
759 printf("Acttab:");
760 for(j=0; j<p->nLookahead; j++){
761 printf(" %d", p->aLookahead[j].lookahead);
762 }
763 printf(" inserted at %d\n", i);
764#endif
drh8b582012003-10-21 13:16:03 +0000765 for(j=0; j<p->nLookahead; j++){
766 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
767 p->aAction[k] = p->aLookahead[j];
768 if( k>=p->nAction ) p->nAction = k+1;
769 }
drh4396c612017-12-27 15:21:16 +0000770 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
drh8b582012003-10-21 13:16:03 +0000771 p->nLookahead = 0;
772
773 /* Return the offset that is added to the lookahead in order to get the
774 ** index into yy_action of the action */
775 return i - p->mnLookahead;
776}
777
drh3a9d6c72017-12-25 04:15:38 +0000778/*
779** Return the size of the action table without the trailing syntax error
780** entries.
781*/
782int acttab_action_size(acttab *p){
783 int n = p->nAction;
784 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
785 return n;
786}
787
drh75897232000-05-29 14:26:00 +0000788/********************** From the file "build.c" *****************************/
789/*
790** Routines to construction the finite state machine for the LEMON
791** parser generator.
792*/
793
794/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000795**
drh75897232000-05-29 14:26:00 +0000796** Those rules which have a precedence symbol coded in the input
797** grammar using the "[symbol]" construct will already have the
798** rp->precsym field filled. Other rules take as their precedence
799** symbol the first RHS symbol with a defined precedence. If there
800** are not RHS symbols with a defined precedence, the precedence
801** symbol field is left blank.
802*/
icculus9e44cf12010-02-14 17:14:22 +0000803void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000804{
805 struct rule *rp;
806 for(rp=xp->rule; rp; rp=rp->next){
807 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000808 int i, j;
809 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
810 struct symbol *sp = rp->rhs[i];
811 if( sp->type==MULTITERMINAL ){
812 for(j=0; j<sp->nsubsym; j++){
813 if( sp->subsym[j]->prec>=0 ){
814 rp->precsym = sp->subsym[j];
815 break;
816 }
817 }
818 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000819 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000820 }
drh75897232000-05-29 14:26:00 +0000821 }
822 }
823 }
824 return;
825}
826
827/* Find all nonterminals which will generate the empty string.
828** Then go back and compute the first sets of every nonterminal.
829** The first set is the set of all terminal symbols which can begin
830** a string generated by that nonterminal.
831*/
icculus9e44cf12010-02-14 17:14:22 +0000832void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000833{
drhfd405312005-11-06 04:06:59 +0000834 int i, j;
drh75897232000-05-29 14:26:00 +0000835 struct rule *rp;
836 int progress;
837
838 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000839 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000840 }
841 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
842 lemp->symbols[i]->firstset = SetNew();
843 }
844
845 /* First compute all lambdas */
846 do{
847 progress = 0;
848 for(rp=lemp->rule; rp; rp=rp->next){
849 if( rp->lhs->lambda ) continue;
850 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000851 struct symbol *sp = rp->rhs[i];
852 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
853 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000854 }
855 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000856 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000857 progress = 1;
858 }
859 }
860 }while( progress );
861
862 /* Now compute all first sets */
863 do{
864 struct symbol *s1, *s2;
865 progress = 0;
866 for(rp=lemp->rule; rp; rp=rp->next){
867 s1 = rp->lhs;
868 for(i=0; i<rp->nrhs; i++){
869 s2 = rp->rhs[i];
870 if( s2->type==TERMINAL ){
871 progress += SetAdd(s1->firstset,s2->index);
872 break;
drhfd405312005-11-06 04:06:59 +0000873 }else if( s2->type==MULTITERMINAL ){
874 for(j=0; j<s2->nsubsym; j++){
875 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
876 }
877 break;
drhf2f105d2012-08-20 15:53:54 +0000878 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000879 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000880 }else{
drh75897232000-05-29 14:26:00 +0000881 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000882 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000883 }
drh75897232000-05-29 14:26:00 +0000884 }
885 }
886 }while( progress );
887 return;
888}
889
890/* Compute all LR(0) states for the grammar. Links
891** are added to between some states so that the LR(1) follow sets
892** can be computed later.
893*/
icculus9e44cf12010-02-14 17:14:22 +0000894PRIVATE struct state *getstate(struct lemon *); /* forward reference */
895void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000896{
897 struct symbol *sp;
898 struct rule *rp;
899
900 Configlist_init();
901
902 /* Find the start symbol */
903 if( lemp->start ){
904 sp = Symbol_find(lemp->start);
905 if( sp==0 ){
906 ErrorMsg(lemp->filename,0,
907"The specified start symbol \"%s\" is not \
908in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000909symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000910 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000911 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000912 }
913 }else{
drh4ef07702016-03-16 19:45:54 +0000914 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000915 }
916
917 /* Make sure the start symbol doesn't occur on the right-hand side of
918 ** any rule. Report an error if it does. (YACC would generate a new
919 ** start symbol in this case.) */
920 for(rp=lemp->rule; rp; rp=rp->next){
921 int i;
922 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000923 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000924 ErrorMsg(lemp->filename,0,
925"The start symbol \"%s\" occurs on the \
926right-hand side of a rule. This will result in a parser which \
927does not work properly.",sp->name);
928 lemp->errorcnt++;
929 }
930 }
931 }
932
933 /* The basis configuration set for the first state
934 ** is all rules which have the start symbol as their
935 ** left-hand side */
936 for(rp=sp->rule; rp; rp=rp->nextlhs){
937 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000938 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000939 newcfp = Configlist_addbasis(rp,0);
940 SetAdd(newcfp->fws,0);
941 }
942
943 /* Compute the first state. All other states will be
944 ** computed automatically during the computation of the first one.
945 ** The returned pointer to the first state is not used. */
946 (void)getstate(lemp);
947 return;
948}
949
950/* Return a pointer to a state which is described by the configuration
951** list which has been built from calls to Configlist_add.
952*/
icculus9e44cf12010-02-14 17:14:22 +0000953PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
954PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000955{
956 struct config *cfp, *bp;
957 struct state *stp;
958
959 /* Extract the sorted basis of the new state. The basis was constructed
960 ** by prior calls to "Configlist_addbasis()". */
961 Configlist_sortbasis();
962 bp = Configlist_basis();
963
964 /* Get a state with the same basis */
965 stp = State_find(bp);
966 if( stp ){
967 /* A state with the same basis already exists! Copy all the follow-set
968 ** propagation links from the state under construction into the
969 ** preexisting state, then return a pointer to the preexisting state */
970 struct config *x, *y;
971 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
972 Plink_copy(&y->bplp,x->bplp);
973 Plink_delete(x->fplp);
974 x->fplp = x->bplp = 0;
975 }
976 cfp = Configlist_return();
977 Configlist_eat(cfp);
978 }else{
979 /* This really is a new state. Construct all the details */
980 Configlist_closure(lemp); /* Compute the configuration closure */
981 Configlist_sort(); /* Sort the configuration closure */
982 cfp = Configlist_return(); /* Get a pointer to the config list */
983 stp = State_new(); /* A new state structure */
984 MemoryCheck(stp);
985 stp->bp = bp; /* Remember the configuration basis */
986 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000987 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000988 stp->ap = 0; /* No actions, yet. */
989 State_insert(stp,stp->bp); /* Add to the state table */
990 buildshifts(lemp,stp); /* Recursively compute successor states */
991 }
992 return stp;
993}
994
drhfd405312005-11-06 04:06:59 +0000995/*
996** Return true if two symbols are the same.
997*/
icculus9e44cf12010-02-14 17:14:22 +0000998int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000999{
1000 int i;
1001 if( a==b ) return 1;
1002 if( a->type!=MULTITERMINAL ) return 0;
1003 if( b->type!=MULTITERMINAL ) return 0;
1004 if( a->nsubsym!=b->nsubsym ) return 0;
1005 for(i=0; i<a->nsubsym; i++){
1006 if( a->subsym[i]!=b->subsym[i] ) return 0;
1007 }
1008 return 1;
1009}
1010
drh75897232000-05-29 14:26:00 +00001011/* Construct all successor states to the given state. A "successor"
1012** state is any state which can be reached by a shift action.
1013*/
icculus9e44cf12010-02-14 17:14:22 +00001014PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +00001015{
1016 struct config *cfp; /* For looping thru the config closure of "stp" */
1017 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +00001018 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +00001019 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1020 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1021 struct state *newstp; /* A pointer to a successor state */
1022
1023 /* Each configuration becomes complete after it contibutes to a successor
1024 ** state. Initially, all configurations are incomplete */
1025 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1026
1027 /* Loop through all configurations of the state "stp" */
1028 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1029 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1030 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1031 Configlist_reset(); /* Reset the new config set */
1032 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1033
1034 /* For every configuration in the state "stp" which has the symbol "sp"
1035 ** following its dot, add the same configuration to the basis set under
1036 ** construction but with the dot shifted one symbol to the right. */
1037 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1038 if( bcfp->status==COMPLETE ) continue; /* Already used */
1039 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1040 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001041 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001042 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001043 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1044 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001045 }
1046
1047 /* Get a pointer to the state described by the basis configuration set
1048 ** constructed in the preceding loop */
1049 newstp = getstate(lemp);
1050
1051 /* The state "newstp" is reached from the state "stp" by a shift action
1052 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001053 if( sp->type==MULTITERMINAL ){
1054 int i;
1055 for(i=0; i<sp->nsubsym; i++){
1056 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1057 }
1058 }else{
1059 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1060 }
drh75897232000-05-29 14:26:00 +00001061 }
1062}
1063
1064/*
1065** Construct the propagation links
1066*/
icculus9e44cf12010-02-14 17:14:22 +00001067void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001068{
1069 int i;
1070 struct config *cfp, *other;
1071 struct state *stp;
1072 struct plink *plp;
1073
1074 /* Housekeeping detail:
1075 ** Add to every propagate link a pointer back to the state to
1076 ** which the link is attached. */
1077 for(i=0; i<lemp->nstate; i++){
1078 stp = lemp->sorted[i];
1079 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1080 cfp->stp = stp;
1081 }
1082 }
1083
1084 /* Convert all backlinks into forward links. Only the forward
1085 ** links are used in the follow-set computation. */
1086 for(i=0; i<lemp->nstate; i++){
1087 stp = lemp->sorted[i];
1088 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1089 for(plp=cfp->bplp; plp; plp=plp->next){
1090 other = plp->cfp;
1091 Plink_add(&other->fplp,cfp);
1092 }
1093 }
1094 }
1095}
1096
1097/* Compute all followsets.
1098**
1099** A followset is the set of all symbols which can come immediately
1100** after a configuration.
1101*/
icculus9e44cf12010-02-14 17:14:22 +00001102void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001103{
1104 int i;
1105 struct config *cfp;
1106 struct plink *plp;
1107 int progress;
1108 int change;
1109
1110 for(i=0; i<lemp->nstate; i++){
1111 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1112 cfp->status = INCOMPLETE;
1113 }
1114 }
drh06f60d82017-04-14 19:46:12 +00001115
drh75897232000-05-29 14:26:00 +00001116 do{
1117 progress = 0;
1118 for(i=0; i<lemp->nstate; i++){
1119 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1120 if( cfp->status==COMPLETE ) continue;
1121 for(plp=cfp->fplp; plp; plp=plp->next){
1122 change = SetUnion(plp->cfp->fws,cfp->fws);
1123 if( change ){
1124 plp->cfp->status = INCOMPLETE;
1125 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001126 }
1127 }
drh75897232000-05-29 14:26:00 +00001128 cfp->status = COMPLETE;
1129 }
1130 }
1131 }while( progress );
1132}
1133
drh3cb2f6e2012-01-09 14:19:05 +00001134static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001135
1136/* Compute the reduce actions, and resolve conflicts.
1137*/
icculus9e44cf12010-02-14 17:14:22 +00001138void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001139{
1140 int i,j;
1141 struct config *cfp;
1142 struct state *stp;
1143 struct symbol *sp;
1144 struct rule *rp;
1145
drh06f60d82017-04-14 19:46:12 +00001146 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001147 ** A reduce action is added for each element of the followset of
1148 ** a configuration which has its dot at the extreme right.
1149 */
1150 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1151 stp = lemp->sorted[i];
1152 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1153 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1154 for(j=0; j<lemp->nterminal; j++){
1155 if( SetFind(cfp->fws,j) ){
1156 /* Add a reduce action to the state "stp" which will reduce by the
1157 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001158 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001159 }
drhf2f105d2012-08-20 15:53:54 +00001160 }
drh75897232000-05-29 14:26:00 +00001161 }
1162 }
1163 }
1164
1165 /* Add the accepting token */
1166 if( lemp->start ){
1167 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001168 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001169 }else{
drh4ef07702016-03-16 19:45:54 +00001170 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001171 }
1172 /* Add to the first state (which is always the starting state of the
1173 ** finite state machine) an action to ACCEPT if the lookahead is the
1174 ** start nonterminal. */
1175 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1176
1177 /* Resolve conflicts */
1178 for(i=0; i<lemp->nstate; i++){
1179 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001180 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001181 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001182 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001183 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001184 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1185 /* The two actions "ap" and "nap" have the same lookahead.
1186 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001187 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001188 }
1189 }
1190 }
1191
1192 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001193 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001194 for(i=0; i<lemp->nstate; i++){
1195 struct action *ap;
1196 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001197 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001198 }
1199 }
1200 for(rp=lemp->rule; rp; rp=rp->next){
1201 if( rp->canReduce ) continue;
1202 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1203 lemp->errorcnt++;
1204 }
1205}
1206
1207/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001208** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001209**
1210** NO LONGER TRUE:
1211** To resolve a conflict, first look to see if either action
1212** is on an error rule. In that case, take the action which
1213** is not associated with the error rule. If neither or both
1214** actions are associated with an error rule, then try to
1215** use precedence to resolve the conflict.
1216**
1217** If either action is a SHIFT, then it must be apx. This
1218** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1219*/
icculus9e44cf12010-02-14 17:14:22 +00001220static int resolve_conflict(
1221 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001222 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001223){
drh75897232000-05-29 14:26:00 +00001224 struct symbol *spx, *spy;
1225 int errcnt = 0;
1226 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001227 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001228 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001229 errcnt++;
1230 }
drh75897232000-05-29 14:26:00 +00001231 if( apx->type==SHIFT && apy->type==REDUCE ){
1232 spx = apx->sp;
1233 spy = apy->x.rp->precsym;
1234 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1235 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001236 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001237 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001238 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001239 apy->type = RD_RESOLVED;
1240 }else if( spx->prec<spy->prec ){
1241 apx->type = SH_RESOLVED;
1242 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1243 apy->type = RD_RESOLVED; /* associativity */
1244 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1245 apx->type = SH_RESOLVED;
1246 }else{
1247 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001248 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001249 }
1250 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1251 spx = apx->x.rp->precsym;
1252 spy = apy->x.rp->precsym;
1253 if( spx==0 || spy==0 || spx->prec<0 ||
1254 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001255 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001256 errcnt++;
1257 }else if( spx->prec>spy->prec ){
1258 apy->type = RD_RESOLVED;
1259 }else if( spx->prec<spy->prec ){
1260 apx->type = RD_RESOLVED;
1261 }
1262 }else{
drh06f60d82017-04-14 19:46:12 +00001263 assert(
drhb59499c2002-02-23 18:45:13 +00001264 apx->type==SH_RESOLVED ||
1265 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001266 apx->type==SSCONFLICT ||
1267 apx->type==SRCONFLICT ||
1268 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001269 apy->type==SH_RESOLVED ||
1270 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001271 apy->type==SSCONFLICT ||
1272 apy->type==SRCONFLICT ||
1273 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001274 );
1275 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1276 ** REDUCEs on the list. If we reach this point it must be because
1277 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001278 }
1279 return errcnt;
1280}
1281/********************* From the file "configlist.c" *************************/
1282/*
1283** Routines to processing a configuration list and building a state
1284** in the LEMON parser generator.
1285*/
1286
1287static struct config *freelist = 0; /* List of free configurations */
1288static struct config *current = 0; /* Top of list of configurations */
1289static struct config **currentend = 0; /* Last on list of configs */
1290static struct config *basis = 0; /* Top of list of basis configs */
1291static struct config **basisend = 0; /* End of list of basis configs */
1292
1293/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001294PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001295 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001296 if( freelist==0 ){
1297 int i;
1298 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001299 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001300 if( freelist==0 ){
1301 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1302 exit(1);
1303 }
1304 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1305 freelist[amt-1].next = 0;
1306 }
icculus9e44cf12010-02-14 17:14:22 +00001307 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001308 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001309 return newcfg;
drh75897232000-05-29 14:26:00 +00001310}
1311
1312/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001313PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001314{
1315 old->next = freelist;
1316 freelist = old;
1317}
1318
1319/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001320void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001321 current = 0;
1322 currentend = &current;
1323 basis = 0;
1324 basisend = &basis;
1325 Configtable_init();
1326 return;
1327}
1328
1329/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001330void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001331 current = 0;
1332 currentend = &current;
1333 basis = 0;
1334 basisend = &basis;
1335 Configtable_clear(0);
1336 return;
1337}
1338
1339/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001340struct config *Configlist_add(
1341 struct rule *rp, /* The rule */
1342 int dot /* Index into the RHS of the rule where the dot goes */
1343){
drh75897232000-05-29 14:26:00 +00001344 struct config *cfp, model;
1345
1346 assert( currentend!=0 );
1347 model.rp = rp;
1348 model.dot = dot;
1349 cfp = Configtable_find(&model);
1350 if( cfp==0 ){
1351 cfp = newconfig();
1352 cfp->rp = rp;
1353 cfp->dot = dot;
1354 cfp->fws = SetNew();
1355 cfp->stp = 0;
1356 cfp->fplp = cfp->bplp = 0;
1357 cfp->next = 0;
1358 cfp->bp = 0;
1359 *currentend = cfp;
1360 currentend = &cfp->next;
1361 Configtable_insert(cfp);
1362 }
1363 return cfp;
1364}
1365
1366/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001367struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001368{
1369 struct config *cfp, model;
1370
1371 assert( basisend!=0 );
1372 assert( currentend!=0 );
1373 model.rp = rp;
1374 model.dot = dot;
1375 cfp = Configtable_find(&model);
1376 if( cfp==0 ){
1377 cfp = newconfig();
1378 cfp->rp = rp;
1379 cfp->dot = dot;
1380 cfp->fws = SetNew();
1381 cfp->stp = 0;
1382 cfp->fplp = cfp->bplp = 0;
1383 cfp->next = 0;
1384 cfp->bp = 0;
1385 *currentend = cfp;
1386 currentend = &cfp->next;
1387 *basisend = cfp;
1388 basisend = &cfp->bp;
1389 Configtable_insert(cfp);
1390 }
1391 return cfp;
1392}
1393
1394/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001395void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001396{
1397 struct config *cfp, *newcfp;
1398 struct rule *rp, *newrp;
1399 struct symbol *sp, *xsp;
1400 int i, dot;
1401
1402 assert( currentend!=0 );
1403 for(cfp=current; cfp; cfp=cfp->next){
1404 rp = cfp->rp;
1405 dot = cfp->dot;
1406 if( dot>=rp->nrhs ) continue;
1407 sp = rp->rhs[dot];
1408 if( sp->type==NONTERMINAL ){
1409 if( sp->rule==0 && sp!=lemp->errsym ){
1410 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1411 sp->name);
1412 lemp->errorcnt++;
1413 }
1414 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1415 newcfp = Configlist_add(newrp,0);
1416 for(i=dot+1; i<rp->nrhs; i++){
1417 xsp = rp->rhs[i];
1418 if( xsp->type==TERMINAL ){
1419 SetAdd(newcfp->fws,xsp->index);
1420 break;
drhfd405312005-11-06 04:06:59 +00001421 }else if( xsp->type==MULTITERMINAL ){
1422 int k;
1423 for(k=0; k<xsp->nsubsym; k++){
1424 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1425 }
1426 break;
drhf2f105d2012-08-20 15:53:54 +00001427 }else{
drh75897232000-05-29 14:26:00 +00001428 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001429 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001430 }
1431 }
drh75897232000-05-29 14:26:00 +00001432 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1433 }
1434 }
1435 }
1436 return;
1437}
1438
1439/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001440void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001441 current = (struct config*)msort((char*)current,(char**)&(current->next),
1442 Configcmp);
drh75897232000-05-29 14:26:00 +00001443 currentend = 0;
1444 return;
1445}
1446
1447/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001448void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001449 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1450 Configcmp);
drh75897232000-05-29 14:26:00 +00001451 basisend = 0;
1452 return;
1453}
1454
1455/* Return a pointer to the head of the configuration list and
1456** reset the list */
drh14d88552017-04-14 19:44:15 +00001457struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001458 struct config *old;
1459 old = current;
1460 current = 0;
1461 currentend = 0;
1462 return old;
1463}
1464
1465/* Return a pointer to the head of the configuration list and
1466** reset the list */
drh14d88552017-04-14 19:44:15 +00001467struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001468 struct config *old;
1469 old = basis;
1470 basis = 0;
1471 basisend = 0;
1472 return old;
1473}
1474
1475/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001476void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001477{
1478 struct config *nextcfp;
1479 for(; cfp; cfp=nextcfp){
1480 nextcfp = cfp->next;
1481 assert( cfp->fplp==0 );
1482 assert( cfp->bplp==0 );
1483 if( cfp->fws ) SetFree(cfp->fws);
1484 deleteconfig(cfp);
1485 }
1486 return;
1487}
1488/***************** From the file "error.c" *********************************/
1489/*
1490** Code for printing error message.
1491*/
1492
drhf9a2e7b2003-04-15 01:49:48 +00001493void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001494 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001495 fprintf(stderr, "%s:%d: ", filename, lineno);
1496 va_start(ap, format);
1497 vfprintf(stderr,format,ap);
1498 va_end(ap);
1499 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001500}
1501/**************** From the file "main.c" ************************************/
1502/*
1503** Main program file for the LEMON parser generator.
1504*/
1505
1506/* Report an out-of-memory condition and abort. This function
1507** is used mostly by the "MemoryCheck" macro in struct.h
1508*/
drh14d88552017-04-14 19:44:15 +00001509void memory_error(void){
drh75897232000-05-29 14:26:00 +00001510 fprintf(stderr,"Out of memory. Aborting...\n");
1511 exit(1);
1512}
1513
drh6d08b4d2004-07-20 12:45:22 +00001514static int nDefine = 0; /* Number of -D options on the command line */
1515static char **azDefine = 0; /* Name of the -D macros */
1516
1517/* This routine is called with the argument to each -D command-line option.
1518** Add the macro defined to the azDefine array.
1519*/
1520static void handle_D_option(char *z){
1521 char **paz;
1522 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001523 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001524 if( azDefine==0 ){
1525 fprintf(stderr,"out of memory\n");
1526 exit(1);
1527 }
1528 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001529 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001530 if( *paz==0 ){
1531 fprintf(stderr,"out of memory\n");
1532 exit(1);
1533 }
drh898799f2014-01-10 23:21:00 +00001534 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001535 for(z=*paz; *z && *z!='='; z++){}
1536 *z = 0;
1537}
1538
drh9f88e6d2018-04-20 20:47:49 +00001539/* Rember the name of the output directory
1540*/
1541static char *outputDir = NULL;
1542static void handle_d_option(char *z){
1543 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1544 if( outputDir==0 ){
1545 fprintf(stderr,"out of memory\n");
1546 exit(1);
1547 }
1548 lemon_strcpy(outputDir, z);
1549}
1550
icculus3e143bd2010-02-14 00:48:49 +00001551static char *user_templatename = NULL;
1552static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001553 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001554 if( user_templatename==0 ){
1555 memory_error();
1556 }
drh898799f2014-01-10 23:21:00 +00001557 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001558}
drh75897232000-05-29 14:26:00 +00001559
drh711c9812016-05-23 14:24:31 +00001560/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001561static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1562 struct rule *pFirst = 0;
1563 struct rule **ppPrev = &pFirst;
1564 while( pA && pB ){
1565 if( pA->iRule<pB->iRule ){
1566 *ppPrev = pA;
1567 ppPrev = &pA->next;
1568 pA = pA->next;
1569 }else{
1570 *ppPrev = pB;
1571 ppPrev = &pB->next;
1572 pB = pB->next;
1573 }
1574 }
1575 if( pA ){
1576 *ppPrev = pA;
1577 }else{
1578 *ppPrev = pB;
1579 }
1580 return pFirst;
1581}
1582
1583/*
1584** Sort a list of rules in order of increasing iRule value
1585*/
1586static struct rule *Rule_sort(struct rule *rp){
1587 int i;
1588 struct rule *pNext;
1589 struct rule *x[32];
1590 memset(x, 0, sizeof(x));
1591 while( rp ){
1592 pNext = rp->next;
1593 rp->next = 0;
1594 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1595 rp = Rule_merge(x[i], rp);
1596 x[i] = 0;
1597 }
1598 x[i] = rp;
1599 rp = pNext;
1600 }
1601 rp = 0;
1602 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1603 rp = Rule_merge(x[i], rp);
1604 }
1605 return rp;
1606}
1607
drhc75e0162015-09-07 02:23:02 +00001608/* forward reference */
1609static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1610
1611/* Print a single line of the "Parser Stats" output
1612*/
1613static void stats_line(const char *zLabel, int iValue){
1614 int nLabel = lemonStrlen(zLabel);
1615 printf(" %s%.*s %5d\n", zLabel,
1616 35-nLabel, "................................",
1617 iValue);
1618}
1619
drh75897232000-05-29 14:26:00 +00001620/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001621int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001622{
1623 static int version = 0;
1624 static int rpflag = 0;
1625 static int basisflag = 0;
1626 static int compress = 0;
1627 static int quiet = 0;
1628 static int statistics = 0;
1629 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001630 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001631 static int noResort = 0;
drh9f88e6d2018-04-20 20:47:49 +00001632
drh75897232000-05-29 14:26:00 +00001633 static struct s_options options[] = {
1634 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1635 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh9f88e6d2018-04-20 20:47:49 +00001636 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
drh6d08b4d2004-07-20 12:45:22 +00001637 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001638 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001639 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001640 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001641 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1642 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001643 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001644 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1645 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001646 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001647 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001648 {OPT_FLAG, "s", (char*)&statistics,
1649 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001650 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001651 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1652 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001653 {OPT_FLAG,0,0,0}
1654 };
1655 int i;
icculus42585cf2010-02-14 05:19:56 +00001656 int exitcode;
drh75897232000-05-29 14:26:00 +00001657 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001658 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001659
drhb0c86772000-06-02 23:21:26 +00001660 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001661 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001662 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001663 exit(0);
drh75897232000-05-29 14:26:00 +00001664 }
drhb0c86772000-06-02 23:21:26 +00001665 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001666 fprintf(stderr,"Exactly one filename argument is required.\n");
1667 exit(1);
1668 }
drh954f6b42006-06-13 13:27:46 +00001669 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001670 lem.errorcnt = 0;
1671
1672 /* Initialize the machine */
1673 Strsafe_init();
1674 Symbol_init();
1675 State_init();
1676 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001677 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001678 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001679 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001680 Symbol_new("$");
drh75897232000-05-29 14:26:00 +00001681
1682 /* Parse the input file */
1683 Parse(&lem);
1684 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001685 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001686 fprintf(stderr,"Empty grammar.\n");
1687 exit(1);
1688 }
drhed0c15b2018-04-16 14:31:34 +00001689 lem.errsym = Symbol_find("error");
drh75897232000-05-29 14:26:00 +00001690
1691 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001692 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001693 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001694 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001695 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1696 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1697 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1698 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1699 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1700 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001701 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001702 lem.nterminal = i;
1703
drh711c9812016-05-23 14:24:31 +00001704 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1705 ** reduce action C-code associated with them last, so that the switch()
1706 ** statement that selects reduction actions will have a smaller jump table.
1707 */
drh4ef07702016-03-16 19:45:54 +00001708 for(i=0, rp=lem.rule; rp; rp=rp->next){
1709 rp->iRule = rp->code ? i++ : -1;
1710 }
1711 for(rp=lem.rule; rp; rp=rp->next){
1712 if( rp->iRule<0 ) rp->iRule = i++;
1713 }
1714 lem.startRule = lem.rule;
1715 lem.rule = Rule_sort(lem.rule);
1716
drh75897232000-05-29 14:26:00 +00001717 /* Generate a reprint of the grammar, if requested on the command line */
1718 if( rpflag ){
1719 Reprint(&lem);
1720 }else{
1721 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001722 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001723
1724 /* Find the precedence for every production rule (that has one) */
1725 FindRulePrecedences(&lem);
1726
1727 /* Compute the lambda-nonterminals and the first-sets for every
1728 ** nonterminal */
1729 FindFirstSets(&lem);
1730
1731 /* Compute all LR(0) states. Also record follow-set propagation
1732 ** links so that the follow-set can be computed later */
1733 lem.nstate = 0;
1734 FindStates(&lem);
1735 lem.sorted = State_arrayof();
1736
1737 /* Tie up loose ends on the propagation links */
1738 FindLinks(&lem);
1739
1740 /* Compute the follow set of every reducible configuration */
1741 FindFollowSets(&lem);
1742
1743 /* Compute the action tables */
1744 FindActions(&lem);
1745
1746 /* Compress the action tables */
1747 if( compress==0 ) CompressTables(&lem);
1748
drhada354d2005-11-05 15:03:59 +00001749 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001750 ** occur at the end. This is an optimization that helps make the
1751 ** generated parser tables smaller. */
1752 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001753
drh75897232000-05-29 14:26:00 +00001754 /* Generate a report of the parser generated. (the "y.output" file) */
1755 if( !quiet ) ReportOutput(&lem);
1756
1757 /* Generate the source code for the parser */
1758 ReportTable(&lem, mhflag);
1759
1760 /* Produce a header file for use by the scanner. (This step is
1761 ** omitted if the "-m" option is used because makeheaders will
1762 ** generate the file for us.) */
1763 if( !mhflag ) ReportHeader(&lem);
1764 }
1765 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001766 printf("Parser statistics:\n");
1767 stats_line("terminal symbols", lem.nterminal);
1768 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1769 stats_line("total symbols", lem.nsymbol);
1770 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001771 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001772 stats_line("conflicts", lem.nconflict);
1773 stats_line("action table entries", lem.nactiontab);
drh3a9d6c72017-12-25 04:15:38 +00001774 stats_line("lookahead table entries", lem.nlookaheadtab);
drhc75e0162015-09-07 02:23:02 +00001775 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001776 }
icculus8e158022010-02-16 16:09:03 +00001777 if( lem.nconflict > 0 ){
1778 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001779 }
1780
1781 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001782 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001783 exit(exitcode);
1784 return (exitcode);
drh75897232000-05-29 14:26:00 +00001785}
1786/******************** From the file "msort.c" *******************************/
1787/*
1788** A generic merge-sort program.
1789**
1790** USAGE:
1791** Let "ptr" be a pointer to some structure which is at the head of
1792** a null-terminated list. Then to sort the list call:
1793**
1794** ptr = msort(ptr,&(ptr->next),cmpfnc);
1795**
1796** In the above, "cmpfnc" is a pointer to a function which compares
1797** two instances of the structure and returns an integer, as in
1798** strcmp. The second argument is a pointer to the pointer to the
1799** second element of the linked list. This address is used to compute
1800** the offset to the "next" field within the structure. The offset to
1801** the "next" field must be constant for all structures in the list.
1802**
1803** The function returns a new pointer which is the head of the list
1804** after sorting.
1805**
1806** ALGORITHM:
1807** Merge-sort.
1808*/
1809
1810/*
1811** Return a pointer to the next structure in the linked list.
1812*/
drhd25d6922012-04-18 09:59:56 +00001813#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001814
1815/*
1816** Inputs:
1817** a: A sorted, null-terminated linked list. (May be null).
1818** b: A sorted, null-terminated linked list. (May be null).
1819** cmp: A pointer to the comparison function.
1820** offset: Offset in the structure to the "next" field.
1821**
1822** Return Value:
1823** A pointer to the head of a sorted list containing the elements
1824** of both a and b.
1825**
1826** Side effects:
1827** The "next" pointers for elements in the lists a and b are
1828** changed.
1829*/
drhe9278182007-07-18 18:16:29 +00001830static char *merge(
1831 char *a,
1832 char *b,
1833 int (*cmp)(const char*,const char*),
1834 int offset
1835){
drh75897232000-05-29 14:26:00 +00001836 char *ptr, *head;
1837
1838 if( a==0 ){
1839 head = b;
1840 }else if( b==0 ){
1841 head = a;
1842 }else{
drhe594bc32009-11-03 13:02:25 +00001843 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001844 ptr = a;
1845 a = NEXT(a);
1846 }else{
1847 ptr = b;
1848 b = NEXT(b);
1849 }
1850 head = ptr;
1851 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001852 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001853 NEXT(ptr) = a;
1854 ptr = a;
1855 a = NEXT(a);
1856 }else{
1857 NEXT(ptr) = b;
1858 ptr = b;
1859 b = NEXT(b);
1860 }
1861 }
1862 if( a ) NEXT(ptr) = a;
1863 else NEXT(ptr) = b;
1864 }
1865 return head;
1866}
1867
1868/*
1869** Inputs:
1870** list: Pointer to a singly-linked list of structures.
1871** next: Pointer to pointer to the second element of the list.
1872** cmp: A comparison function.
1873**
1874** Return Value:
1875** A pointer to the head of a sorted list containing the elements
1876** orginally in list.
1877**
1878** Side effects:
1879** The "next" pointers for elements in list are changed.
1880*/
1881#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001882static char *msort(
1883 char *list,
1884 char **next,
1885 int (*cmp)(const char*,const char*)
1886){
drhba99af52001-10-25 20:37:16 +00001887 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001888 char *ep;
1889 char *set[LISTSIZE];
1890 int i;
drh1cc0d112015-03-31 15:15:48 +00001891 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001892 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1893 while( list ){
1894 ep = list;
1895 list = NEXT(list);
1896 NEXT(ep) = 0;
1897 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1898 ep = merge(ep,set[i],cmp,offset);
1899 set[i] = 0;
1900 }
1901 set[i] = ep;
1902 }
1903 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001904 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001905 return ep;
1906}
1907/************************ From the file "option.c" **************************/
1908static char **argv;
1909static struct s_options *op;
1910static FILE *errstream;
1911
1912#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1913
1914/*
1915** Print the command line with a carrot pointing to the k-th character
1916** of the n-th field.
1917*/
icculus9e44cf12010-02-14 17:14:22 +00001918static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001919{
1920 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001921 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001922 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001923 for(i=1; i<n && argv[i]; i++){
1924 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001925 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001926 }
1927 spcnt += k;
1928 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1929 if( spcnt<20 ){
1930 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1931 }else{
1932 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1933 }
1934}
1935
1936/*
1937** Return the index of the N-th non-switch argument. Return -1
1938** if N is out of range.
1939*/
icculus9e44cf12010-02-14 17:14:22 +00001940static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001941{
1942 int i;
1943 int dashdash = 0;
1944 if( argv!=0 && *argv!=0 ){
1945 for(i=1; argv[i]; i++){
1946 if( dashdash || !ISOPT(argv[i]) ){
1947 if( n==0 ) return i;
1948 n--;
1949 }
1950 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1951 }
1952 }
1953 return -1;
1954}
1955
1956static char emsg[] = "Command line syntax error: ";
1957
1958/*
1959** Process a flag command line argument.
1960*/
icculus9e44cf12010-02-14 17:14:22 +00001961static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001962{
1963 int v;
1964 int errcnt = 0;
1965 int j;
1966 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001967 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001968 }
1969 v = argv[i][0]=='-' ? 1 : 0;
1970 if( op[j].label==0 ){
1971 if( err ){
1972 fprintf(err,"%sundefined option.\n",emsg);
1973 errline(i,1,err);
1974 }
1975 errcnt++;
drh0325d392015-01-01 19:11:22 +00001976 }else if( op[j].arg==0 ){
1977 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001978 }else if( op[j].type==OPT_FLAG ){
1979 *((int*)op[j].arg) = v;
1980 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001981 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001982 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001983 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001984 }else{
1985 if( err ){
1986 fprintf(err,"%smissing argument on switch.\n",emsg);
1987 errline(i,1,err);
1988 }
1989 errcnt++;
1990 }
1991 return errcnt;
1992}
1993
1994/*
1995** Process a command line switch which has an argument.
1996*/
icculus9e44cf12010-02-14 17:14:22 +00001997static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001998{
1999 int lv = 0;
2000 double dv = 0.0;
2001 char *sv = 0, *end;
2002 char *cp;
2003 int j;
2004 int errcnt = 0;
2005 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00002006 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00002007 *cp = 0;
2008 for(j=0; op[j].label; j++){
2009 if( strcmp(argv[i],op[j].label)==0 ) break;
2010 }
2011 *cp = '=';
2012 if( op[j].label==0 ){
2013 if( err ){
2014 fprintf(err,"%sundefined option.\n",emsg);
2015 errline(i,0,err);
2016 }
2017 errcnt++;
2018 }else{
2019 cp++;
2020 switch( op[j].type ){
2021 case OPT_FLAG:
2022 case OPT_FFLAG:
2023 if( err ){
2024 fprintf(err,"%soption requires an argument.\n",emsg);
2025 errline(i,0,err);
2026 }
2027 errcnt++;
2028 break;
2029 case OPT_DBL:
2030 case OPT_FDBL:
2031 dv = strtod(cp,&end);
2032 if( *end ){
2033 if( err ){
drh25473362015-09-04 18:03:45 +00002034 fprintf(err,
2035 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00002036 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002037 }
2038 errcnt++;
2039 }
2040 break;
2041 case OPT_INT:
2042 case OPT_FINT:
2043 lv = strtol(cp,&end,0);
2044 if( *end ){
2045 if( err ){
2046 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00002047 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002048 }
2049 errcnt++;
2050 }
2051 break;
2052 case OPT_STR:
2053 case OPT_FSTR:
2054 sv = cp;
2055 break;
2056 }
2057 switch( op[j].type ){
2058 case OPT_FLAG:
2059 case OPT_FFLAG:
2060 break;
2061 case OPT_DBL:
2062 *(double*)(op[j].arg) = dv;
2063 break;
2064 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002065 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002066 break;
2067 case OPT_INT:
2068 *(int*)(op[j].arg) = lv;
2069 break;
2070 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002071 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002072 break;
2073 case OPT_STR:
2074 *(char**)(op[j].arg) = sv;
2075 break;
2076 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002077 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002078 break;
2079 }
2080 }
2081 return errcnt;
2082}
2083
icculus9e44cf12010-02-14 17:14:22 +00002084int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002085{
2086 int errcnt = 0;
2087 argv = a;
2088 op = o;
2089 errstream = err;
2090 if( argv && *argv && op ){
2091 int i;
2092 for(i=1; argv[i]; i++){
2093 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2094 errcnt += handleflags(i,err);
2095 }else if( strchr(argv[i],'=') ){
2096 errcnt += handleswitch(i,err);
2097 }
2098 }
2099 }
2100 if( errcnt>0 ){
2101 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002102 OptPrint();
drh75897232000-05-29 14:26:00 +00002103 exit(1);
2104 }
2105 return 0;
2106}
2107
drh14d88552017-04-14 19:44:15 +00002108int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002109 int cnt = 0;
2110 int dashdash = 0;
2111 int i;
2112 if( argv!=0 && argv[0]!=0 ){
2113 for(i=1; argv[i]; i++){
2114 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2115 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2116 }
2117 }
2118 return cnt;
2119}
2120
icculus9e44cf12010-02-14 17:14:22 +00002121char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002122{
2123 int i;
2124 i = argindex(n);
2125 return i>=0 ? argv[i] : 0;
2126}
2127
icculus9e44cf12010-02-14 17:14:22 +00002128void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002129{
2130 int i;
2131 i = argindex(n);
2132 if( i>=0 ) errline(i,0,errstream);
2133}
2134
drh14d88552017-04-14 19:44:15 +00002135void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002136 int i;
2137 int max, len;
2138 max = 0;
2139 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002140 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002141 switch( op[i].type ){
2142 case OPT_FLAG:
2143 case OPT_FFLAG:
2144 break;
2145 case OPT_INT:
2146 case OPT_FINT:
2147 len += 9; /* length of "<integer>" */
2148 break;
2149 case OPT_DBL:
2150 case OPT_FDBL:
2151 len += 6; /* length of "<real>" */
2152 break;
2153 case OPT_STR:
2154 case OPT_FSTR:
2155 len += 8; /* length of "<string>" */
2156 break;
2157 }
2158 if( len>max ) max = len;
2159 }
2160 for(i=0; op[i].label; i++){
2161 switch( op[i].type ){
2162 case OPT_FLAG:
2163 case OPT_FFLAG:
2164 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2165 break;
2166 case OPT_INT:
2167 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002168 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002169 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002170 break;
2171 case OPT_DBL:
2172 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002173 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002174 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002175 break;
2176 case OPT_STR:
2177 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002178 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002179 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002180 break;
2181 }
2182 }
2183}
2184/*********************** From the file "parse.c" ****************************/
2185/*
2186** Input file parser for the LEMON parser generator.
2187*/
2188
2189/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002190enum e_state {
2191 INITIALIZE,
2192 WAITING_FOR_DECL_OR_RULE,
2193 WAITING_FOR_DECL_KEYWORD,
2194 WAITING_FOR_DECL_ARG,
2195 WAITING_FOR_PRECEDENCE_SYMBOL,
2196 WAITING_FOR_ARROW,
2197 IN_RHS,
2198 LHS_ALIAS_1,
2199 LHS_ALIAS_2,
2200 LHS_ALIAS_3,
2201 RHS_ALIAS_1,
2202 RHS_ALIAS_2,
2203 PRECEDENCE_MARK_1,
2204 PRECEDENCE_MARK_2,
2205 RESYNC_AFTER_RULE_ERROR,
2206 RESYNC_AFTER_DECL_ERROR,
2207 WAITING_FOR_DESTRUCTOR_SYMBOL,
2208 WAITING_FOR_DATATYPE_SYMBOL,
2209 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002210 WAITING_FOR_WILDCARD_ID,
2211 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002212 WAITING_FOR_CLASS_TOKEN,
2213 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002214};
drh75897232000-05-29 14:26:00 +00002215struct pstate {
2216 char *filename; /* Name of the input file */
2217 int tokenlineno; /* Linenumber at which current token starts */
2218 int errorcnt; /* Number of errors so far */
2219 char *tokenstart; /* Text of current token */
2220 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002221 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002222 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002223 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002224 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002225 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002226 int nrhs; /* Number of right-hand side symbols seen */
2227 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002228 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002229 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002230 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002231 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002232 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002233 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002234 enum e_assoc declassoc; /* Assign this association to decl arguments */
2235 int preccounter; /* Assign this precedence to decl arguments */
2236 struct rule *firstrule; /* Pointer to first rule in the grammar */
2237 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2238};
2239
2240/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002241static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002242{
icculus9e44cf12010-02-14 17:14:22 +00002243 const char *x;
drh75897232000-05-29 14:26:00 +00002244 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2245#if 0
2246 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2247 x,psp->state);
2248#endif
2249 switch( psp->state ){
2250 case INITIALIZE:
2251 psp->prevrule = 0;
2252 psp->preccounter = 0;
2253 psp->firstrule = psp->lastrule = 0;
2254 psp->gp->nrule = 0;
2255 /* Fall thru to next case */
2256 case WAITING_FOR_DECL_OR_RULE:
2257 if( x[0]=='%' ){
2258 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002259 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002260 psp->lhs = Symbol_new(x);
2261 psp->nrhs = 0;
2262 psp->lhsalias = 0;
2263 psp->state = WAITING_FOR_ARROW;
2264 }else if( x[0]=='{' ){
2265 if( psp->prevrule==0 ){
2266 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002267"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002268fragment which begins on this line.");
2269 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002270 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002271 ErrorMsg(psp->filename,psp->tokenlineno,
2272"Code fragment beginning on this line is not the first \
2273to follow the previous rule.");
2274 psp->errorcnt++;
2275 }else{
2276 psp->prevrule->line = psp->tokenlineno;
2277 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002278 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002279 }
drh75897232000-05-29 14:26:00 +00002280 }else if( x[0]=='[' ){
2281 psp->state = PRECEDENCE_MARK_1;
2282 }else{
2283 ErrorMsg(psp->filename,psp->tokenlineno,
2284 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2285 x);
2286 psp->errorcnt++;
2287 }
2288 break;
2289 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002290 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002291 ErrorMsg(psp->filename,psp->tokenlineno,
2292 "The precedence symbol must be a terminal.");
2293 psp->errorcnt++;
2294 }else if( psp->prevrule==0 ){
2295 ErrorMsg(psp->filename,psp->tokenlineno,
2296 "There is no prior rule to assign precedence \"[%s]\".",x);
2297 psp->errorcnt++;
2298 }else if( psp->prevrule->precsym!=0 ){
2299 ErrorMsg(psp->filename,psp->tokenlineno,
2300"Precedence mark on this line is not the first \
2301to follow the previous rule.");
2302 psp->errorcnt++;
2303 }else{
2304 psp->prevrule->precsym = Symbol_new(x);
2305 }
2306 psp->state = PRECEDENCE_MARK_2;
2307 break;
2308 case PRECEDENCE_MARK_2:
2309 if( x[0]!=']' ){
2310 ErrorMsg(psp->filename,psp->tokenlineno,
2311 "Missing \"]\" on precedence mark.");
2312 psp->errorcnt++;
2313 }
2314 psp->state = WAITING_FOR_DECL_OR_RULE;
2315 break;
2316 case WAITING_FOR_ARROW:
2317 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2318 psp->state = IN_RHS;
2319 }else if( x[0]=='(' ){
2320 psp->state = LHS_ALIAS_1;
2321 }else{
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "Expected to see a \":\" following the LHS symbol \"%s\".",
2324 psp->lhs->name);
2325 psp->errorcnt++;
2326 psp->state = RESYNC_AFTER_RULE_ERROR;
2327 }
2328 break;
2329 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002330 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002331 psp->lhsalias = x;
2332 psp->state = LHS_ALIAS_2;
2333 }else{
2334 ErrorMsg(psp->filename,psp->tokenlineno,
2335 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2336 x,psp->lhs->name);
2337 psp->errorcnt++;
2338 psp->state = RESYNC_AFTER_RULE_ERROR;
2339 }
2340 break;
2341 case LHS_ALIAS_2:
2342 if( x[0]==')' ){
2343 psp->state = LHS_ALIAS_3;
2344 }else{
2345 ErrorMsg(psp->filename,psp->tokenlineno,
2346 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2347 psp->errorcnt++;
2348 psp->state = RESYNC_AFTER_RULE_ERROR;
2349 }
2350 break;
2351 case LHS_ALIAS_3:
2352 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2353 psp->state = IN_RHS;
2354 }else{
2355 ErrorMsg(psp->filename,psp->tokenlineno,
2356 "Missing \"->\" following: \"%s(%s)\".",
2357 psp->lhs->name,psp->lhsalias);
2358 psp->errorcnt++;
2359 psp->state = RESYNC_AFTER_RULE_ERROR;
2360 }
2361 break;
2362 case IN_RHS:
2363 if( x[0]=='.' ){
2364 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002365 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002366 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002367 if( rp==0 ){
2368 ErrorMsg(psp->filename,psp->tokenlineno,
2369 "Can't allocate enough memory for this rule.");
2370 psp->errorcnt++;
2371 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002372 }else{
drh75897232000-05-29 14:26:00 +00002373 int i;
2374 rp->ruleline = psp->tokenlineno;
2375 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002376 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002377 for(i=0; i<psp->nrhs; i++){
2378 rp->rhs[i] = psp->rhs[i];
2379 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002380 }
drh75897232000-05-29 14:26:00 +00002381 rp->lhs = psp->lhs;
2382 rp->lhsalias = psp->lhsalias;
2383 rp->nrhs = psp->nrhs;
2384 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002385 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002386 rp->precsym = 0;
2387 rp->index = psp->gp->nrule++;
2388 rp->nextlhs = rp->lhs->rule;
2389 rp->lhs->rule = rp;
2390 rp->next = 0;
2391 if( psp->firstrule==0 ){
2392 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002393 }else{
drh75897232000-05-29 14:26:00 +00002394 psp->lastrule->next = rp;
2395 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002396 }
drh75897232000-05-29 14:26:00 +00002397 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002398 }
drh75897232000-05-29 14:26:00 +00002399 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002400 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002401 if( psp->nrhs>=MAXRHS ){
2402 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002403 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002404 x);
2405 psp->errorcnt++;
2406 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002407 }else{
drh75897232000-05-29 14:26:00 +00002408 psp->rhs[psp->nrhs] = Symbol_new(x);
2409 psp->alias[psp->nrhs] = 0;
2410 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002411 }
drhfd405312005-11-06 04:06:59 +00002412 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2413 struct symbol *msp = psp->rhs[psp->nrhs-1];
2414 if( msp->type!=MULTITERMINAL ){
2415 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002416 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002417 memset(msp, 0, sizeof(*msp));
2418 msp->type = MULTITERMINAL;
2419 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002420 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002421 msp->subsym[0] = origsp;
2422 msp->name = origsp->name;
2423 psp->rhs[psp->nrhs-1] = msp;
2424 }
2425 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002426 msp->subsym = (struct symbol **) realloc(msp->subsym,
2427 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002428 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002429 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002430 ErrorMsg(psp->filename,psp->tokenlineno,
2431 "Cannot form a compound containing a non-terminal");
2432 psp->errorcnt++;
2433 }
drh75897232000-05-29 14:26:00 +00002434 }else if( x[0]=='(' && psp->nrhs>0 ){
2435 psp->state = RHS_ALIAS_1;
2436 }else{
2437 ErrorMsg(psp->filename,psp->tokenlineno,
2438 "Illegal character on RHS of rule: \"%s\".",x);
2439 psp->errorcnt++;
2440 psp->state = RESYNC_AFTER_RULE_ERROR;
2441 }
2442 break;
2443 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002444 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002445 psp->alias[psp->nrhs-1] = x;
2446 psp->state = RHS_ALIAS_2;
2447 }else{
2448 ErrorMsg(psp->filename,psp->tokenlineno,
2449 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2450 x,psp->rhs[psp->nrhs-1]->name);
2451 psp->errorcnt++;
2452 psp->state = RESYNC_AFTER_RULE_ERROR;
2453 }
2454 break;
2455 case RHS_ALIAS_2:
2456 if( x[0]==')' ){
2457 psp->state = IN_RHS;
2458 }else{
2459 ErrorMsg(psp->filename,psp->tokenlineno,
2460 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2461 psp->errorcnt++;
2462 psp->state = RESYNC_AFTER_RULE_ERROR;
2463 }
2464 break;
2465 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002466 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002467 psp->declkeyword = x;
2468 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002469 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002470 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002471 psp->state = WAITING_FOR_DECL_ARG;
2472 if( strcmp(x,"name")==0 ){
2473 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002474 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002475 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002476 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002477 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002478 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002479 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002480 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002481 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002482 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002483 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002484 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002485 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002486 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002487 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002488 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002489 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002490 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002491 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002492 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002493 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002494 }else if( strcmp(x,"extra_argument")==0 ){
2495 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002496 psp->insertLineMacro = 0;
drhfb32c442018-04-21 13:51:42 +00002497 }else if( strcmp(x,"extra_context")==0 ){
2498 psp->declargslot = &(psp->gp->ctx);
2499 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002500 }else if( strcmp(x,"token_type")==0 ){
2501 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002502 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002503 }else if( strcmp(x,"default_type")==0 ){
2504 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002505 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002506 }else if( strcmp(x,"stack_size")==0 ){
2507 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002508 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002509 }else if( strcmp(x,"start_symbol")==0 ){
2510 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002511 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002512 }else if( strcmp(x,"left")==0 ){
2513 psp->preccounter++;
2514 psp->declassoc = LEFT;
2515 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2516 }else if( strcmp(x,"right")==0 ){
2517 psp->preccounter++;
2518 psp->declassoc = RIGHT;
2519 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2520 }else if( strcmp(x,"nonassoc")==0 ){
2521 psp->preccounter++;
2522 psp->declassoc = NONE;
2523 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002524 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002525 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002526 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002527 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002528 }else if( strcmp(x,"fallback")==0 ){
2529 psp->fallback = 0;
2530 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002531 }else if( strcmp(x,"token")==0 ){
2532 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002533 }else if( strcmp(x,"wildcard")==0 ){
2534 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002535 }else if( strcmp(x,"token_class")==0 ){
2536 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002537 }else{
2538 ErrorMsg(psp->filename,psp->tokenlineno,
2539 "Unknown declaration keyword: \"%%%s\".",x);
2540 psp->errorcnt++;
2541 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002542 }
drh75897232000-05-29 14:26:00 +00002543 }else{
2544 ErrorMsg(psp->filename,psp->tokenlineno,
2545 "Illegal declaration keyword: \"%s\".",x);
2546 psp->errorcnt++;
2547 psp->state = RESYNC_AFTER_DECL_ERROR;
2548 }
2549 break;
2550 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002551 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002552 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002553 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002554 psp->errorcnt++;
2555 psp->state = RESYNC_AFTER_DECL_ERROR;
2556 }else{
icculusd286fa62010-03-03 17:06:32 +00002557 struct symbol *sp = Symbol_new(x);
2558 psp->declargslot = &sp->destructor;
2559 psp->decllinenoslot = &sp->destLineno;
2560 psp->insertLineMacro = 1;
2561 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002562 }
2563 break;
2564 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002565 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002566 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002567 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002568 psp->errorcnt++;
2569 psp->state = RESYNC_AFTER_DECL_ERROR;
2570 }else{
icculus866bf1e2010-02-17 20:31:32 +00002571 struct symbol *sp = Symbol_find(x);
2572 if((sp) && (sp->datatype)){
2573 ErrorMsg(psp->filename,psp->tokenlineno,
2574 "Symbol %%type \"%s\" already defined", x);
2575 psp->errorcnt++;
2576 psp->state = RESYNC_AFTER_DECL_ERROR;
2577 }else{
2578 if (!sp){
2579 sp = Symbol_new(x);
2580 }
2581 psp->declargslot = &sp->datatype;
2582 psp->insertLineMacro = 0;
2583 psp->state = WAITING_FOR_DECL_ARG;
2584 }
drh75897232000-05-29 14:26:00 +00002585 }
2586 break;
2587 case WAITING_FOR_PRECEDENCE_SYMBOL:
2588 if( x[0]=='.' ){
2589 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002590 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002591 struct symbol *sp;
2592 sp = Symbol_new(x);
2593 if( sp->prec>=0 ){
2594 ErrorMsg(psp->filename,psp->tokenlineno,
2595 "Symbol \"%s\" has already be given a precedence.",x);
2596 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002597 }else{
drh75897232000-05-29 14:26:00 +00002598 sp->prec = psp->preccounter;
2599 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002600 }
drh75897232000-05-29 14:26:00 +00002601 }else{
2602 ErrorMsg(psp->filename,psp->tokenlineno,
2603 "Can't assign a precedence to \"%s\".",x);
2604 psp->errorcnt++;
2605 }
2606 break;
2607 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002608 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002609 const char *zOld, *zNew;
2610 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002611 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002612 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002613 char zLine[50];
2614 zNew = x;
2615 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002616 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002617 if( *psp->declargslot ){
2618 zOld = *psp->declargslot;
2619 }else{
2620 zOld = "";
2621 }
drh87cf1372008-08-13 20:09:06 +00002622 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002623 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002624 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002625 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2626 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002627 for(z=psp->filename, nBack=0; *z; z++){
2628 if( *z=='\\' ) nBack++;
2629 }
drh898799f2014-01-10 23:21:00 +00002630 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002631 nLine = lemonStrlen(zLine);
2632 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002633 }
icculus9e44cf12010-02-14 17:14:22 +00002634 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2635 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002636 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002637 if( nOld && zBuf[-1]!='\n' ){
2638 *(zBuf++) = '\n';
2639 }
2640 memcpy(zBuf, zLine, nLine);
2641 zBuf += nLine;
2642 *(zBuf++) = '"';
2643 for(z=psp->filename; *z; z++){
2644 if( *z=='\\' ){
2645 *(zBuf++) = '\\';
2646 }
2647 *(zBuf++) = *z;
2648 }
2649 *(zBuf++) = '"';
2650 *(zBuf++) = '\n';
2651 }
drh4dc8ef52008-07-01 17:13:57 +00002652 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2653 psp->decllinenoslot[0] = psp->tokenlineno;
2654 }
drha5808f32008-04-27 22:19:44 +00002655 memcpy(zBuf, zNew, nNew);
2656 zBuf += nNew;
2657 *zBuf = 0;
2658 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002659 }else{
2660 ErrorMsg(psp->filename,psp->tokenlineno,
2661 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2662 psp->errorcnt++;
2663 psp->state = RESYNC_AFTER_DECL_ERROR;
2664 }
2665 break;
drh0bd1f4e2002-06-06 18:54:39 +00002666 case WAITING_FOR_FALLBACK_ID:
2667 if( x[0]=='.' ){
2668 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002669 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002670 ErrorMsg(psp->filename, psp->tokenlineno,
2671 "%%fallback argument \"%s\" should be a token", x);
2672 psp->errorcnt++;
2673 }else{
2674 struct symbol *sp = Symbol_new(x);
2675 if( psp->fallback==0 ){
2676 psp->fallback = sp;
2677 }else if( sp->fallback ){
2678 ErrorMsg(psp->filename, psp->tokenlineno,
2679 "More than one fallback assigned to token %s", x);
2680 psp->errorcnt++;
2681 }else{
2682 sp->fallback = psp->fallback;
2683 psp->gp->has_fallback = 1;
2684 }
2685 }
2686 break;
drh59c435a2017-08-02 03:21:11 +00002687 case WAITING_FOR_TOKEN_NAME:
2688 /* Tokens do not have to be declared before use. But they can be
2689 ** in order to control their assigned integer number. The number for
2690 ** each token is assigned when it is first seen. So by including
2691 **
2692 ** %token ONE TWO THREE
2693 **
2694 ** early in the grammar file, that assigns small consecutive values
2695 ** to each of the tokens ONE TWO and THREE.
2696 */
2697 if( x[0]=='.' ){
2698 psp->state = WAITING_FOR_DECL_OR_RULE;
2699 }else if( !ISUPPER(x[0]) ){
2700 ErrorMsg(psp->filename, psp->tokenlineno,
2701 "%%token argument \"%s\" should be a token", x);
2702 psp->errorcnt++;
2703 }else{
2704 (void)Symbol_new(x);
2705 }
2706 break;
drhe09daa92006-06-10 13:29:31 +00002707 case WAITING_FOR_WILDCARD_ID:
2708 if( x[0]=='.' ){
2709 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002710 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002711 ErrorMsg(psp->filename, psp->tokenlineno,
2712 "%%wildcard argument \"%s\" should be a token", x);
2713 psp->errorcnt++;
2714 }else{
2715 struct symbol *sp = Symbol_new(x);
2716 if( psp->gp->wildcard==0 ){
2717 psp->gp->wildcard = sp;
2718 }else{
2719 ErrorMsg(psp->filename, psp->tokenlineno,
2720 "Extra wildcard to token: %s", x);
2721 psp->errorcnt++;
2722 }
2723 }
2724 break;
drh61f92cd2014-01-11 03:06:18 +00002725 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002726 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002727 ErrorMsg(psp->filename, psp->tokenlineno,
2728 "%%token_class must be followed by an identifier: ", x);
2729 psp->errorcnt++;
2730 psp->state = RESYNC_AFTER_DECL_ERROR;
2731 }else if( Symbol_find(x) ){
2732 ErrorMsg(psp->filename, psp->tokenlineno,
2733 "Symbol \"%s\" already used", x);
2734 psp->errorcnt++;
2735 psp->state = RESYNC_AFTER_DECL_ERROR;
2736 }else{
2737 psp->tkclass = Symbol_new(x);
2738 psp->tkclass->type = MULTITERMINAL;
2739 psp->state = WAITING_FOR_CLASS_TOKEN;
2740 }
2741 break;
2742 case WAITING_FOR_CLASS_TOKEN:
2743 if( x[0]=='.' ){
2744 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002745 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002746 struct symbol *msp = psp->tkclass;
2747 msp->nsubsym++;
2748 msp->subsym = (struct symbol **) realloc(msp->subsym,
2749 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002750 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002751 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2752 }else{
2753 ErrorMsg(psp->filename, psp->tokenlineno,
2754 "%%token_class argument \"%s\" should be a token", x);
2755 psp->errorcnt++;
2756 psp->state = RESYNC_AFTER_DECL_ERROR;
2757 }
2758 break;
drh75897232000-05-29 14:26:00 +00002759 case RESYNC_AFTER_RULE_ERROR:
2760/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2761** break; */
2762 case RESYNC_AFTER_DECL_ERROR:
2763 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2764 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2765 break;
2766 }
2767}
2768
drh34ff57b2008-07-14 12:27:51 +00002769/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002770** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2771** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2772** comments them out. Text in between is also commented out as appropriate.
2773*/
danielk1977940fac92005-01-23 22:41:37 +00002774static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002775 int i, j, k, n;
2776 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002777 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002778 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002779 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002780 for(i=0; z[i]; i++){
2781 if( z[i]=='\n' ) lineno++;
2782 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002783 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002784 if( exclude ){
2785 exclude--;
2786 if( exclude==0 ){
2787 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2788 }
2789 }
2790 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002791 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2792 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002793 if( exclude ){
2794 exclude++;
2795 }else{
drhc56fac72015-10-29 13:48:15 +00002796 for(j=i+7; ISSPACE(z[j]); j++){}
2797 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002798 exclude = 1;
2799 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002800 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002801 exclude = 0;
2802 break;
2803 }
2804 }
2805 if( z[i+3]=='n' ) exclude = !exclude;
2806 if( exclude ){
2807 start = i;
2808 start_lineno = lineno;
2809 }
2810 }
2811 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2812 }
2813 }
2814 if( exclude ){
2815 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2816 exit(1);
2817 }
2818}
2819
drh75897232000-05-29 14:26:00 +00002820/* In spite of its name, this function is really a scanner. It read
2821** in the entire input file (all at once) then tokenizes it. Each
2822** token is passed to the function "parseonetoken" which builds all
2823** the appropriate data structures in the global state vector "gp".
2824*/
icculus9e44cf12010-02-14 17:14:22 +00002825void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002826{
2827 struct pstate ps;
2828 FILE *fp;
2829 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002830 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002831 int lineno;
2832 int c;
2833 char *cp, *nextcp;
2834 int startline = 0;
2835
rse38514a92007-09-20 11:34:17 +00002836 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002837 ps.gp = gp;
2838 ps.filename = gp->filename;
2839 ps.errorcnt = 0;
2840 ps.state = INITIALIZE;
2841
2842 /* Begin by reading the input file */
2843 fp = fopen(ps.filename,"rb");
2844 if( fp==0 ){
2845 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2846 gp->errorcnt++;
2847 return;
2848 }
2849 fseek(fp,0,2);
2850 filesize = ftell(fp);
2851 rewind(fp);
2852 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002853 if( filesize>100000000 || filebuf==0 ){
2854 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002855 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002856 fclose(fp);
drh75897232000-05-29 14:26:00 +00002857 return;
2858 }
2859 if( fread(filebuf,1,filesize,fp)!=filesize ){
2860 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2861 filesize);
2862 free(filebuf);
2863 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002864 fclose(fp);
drh75897232000-05-29 14:26:00 +00002865 return;
2866 }
2867 fclose(fp);
2868 filebuf[filesize] = 0;
2869
drh6d08b4d2004-07-20 12:45:22 +00002870 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2871 preprocess_input(filebuf);
2872
drh75897232000-05-29 14:26:00 +00002873 /* Now scan the text of the input file */
2874 lineno = 1;
2875 for(cp=filebuf; (c= *cp)!=0; ){
2876 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002877 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002878 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2879 cp+=2;
2880 while( (c= *cp)!=0 && c!='\n' ) cp++;
2881 continue;
2882 }
2883 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2884 cp+=2;
2885 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2886 if( c=='\n' ) lineno++;
2887 cp++;
2888 }
2889 if( c ) cp++;
2890 continue;
2891 }
2892 ps.tokenstart = cp; /* Mark the beginning of the token */
2893 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2894 if( c=='\"' ){ /* String literals */
2895 cp++;
2896 while( (c= *cp)!=0 && c!='\"' ){
2897 if( c=='\n' ) lineno++;
2898 cp++;
2899 }
2900 if( c==0 ){
2901 ErrorMsg(ps.filename,startline,
2902"String starting on this line is not terminated before the end of the file.");
2903 ps.errorcnt++;
2904 nextcp = cp;
2905 }else{
2906 nextcp = cp+1;
2907 }
2908 }else if( c=='{' ){ /* A block of C code */
2909 int level;
2910 cp++;
2911 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2912 if( c=='\n' ) lineno++;
2913 else if( c=='{' ) level++;
2914 else if( c=='}' ) level--;
2915 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2916 int prevc;
2917 cp = &cp[2];
2918 prevc = 0;
2919 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2920 if( c=='\n' ) lineno++;
2921 prevc = c;
2922 cp++;
drhf2f105d2012-08-20 15:53:54 +00002923 }
2924 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002925 cp = &cp[2];
2926 while( (c= *cp)!=0 && c!='\n' ) cp++;
2927 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002928 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002929 int startchar, prevc;
2930 startchar = c;
2931 prevc = 0;
2932 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2933 if( c=='\n' ) lineno++;
2934 if( prevc=='\\' ) prevc = 0;
2935 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002936 }
2937 }
drh75897232000-05-29 14:26:00 +00002938 }
2939 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002940 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002941"C code starting on this line is not terminated before the end of the file.");
2942 ps.errorcnt++;
2943 nextcp = cp;
2944 }else{
2945 nextcp = cp+1;
2946 }
drhc56fac72015-10-29 13:48:15 +00002947 }else if( ISALNUM(c) ){ /* Identifiers */
2948 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002949 nextcp = cp;
2950 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2951 cp += 3;
2952 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002953 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002954 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002955 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002956 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002957 }else{ /* All other (one character) operators */
2958 cp++;
2959 nextcp = cp;
2960 }
2961 c = *cp;
2962 *cp = 0; /* Null terminate the token */
2963 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002964 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002965 cp = nextcp;
2966 }
2967 free(filebuf); /* Release the buffer after parsing */
2968 gp->rule = ps.firstrule;
2969 gp->errorcnt = ps.errorcnt;
2970}
2971/*************************** From the file "plink.c" *********************/
2972/*
2973** Routines processing configuration follow-set propagation links
2974** in the LEMON parser generator.
2975*/
2976static struct plink *plink_freelist = 0;
2977
2978/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00002979struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00002980 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002981
2982 if( plink_freelist==0 ){
2983 int i;
2984 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002985 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002986 if( plink_freelist==0 ){
2987 fprintf(stderr,
2988 "Unable to allocate memory for a new follow-set propagation link.\n");
2989 exit(1);
2990 }
2991 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2992 plink_freelist[amt-1].next = 0;
2993 }
icculus9e44cf12010-02-14 17:14:22 +00002994 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002995 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002996 return newlink;
drh75897232000-05-29 14:26:00 +00002997}
2998
2999/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00003000void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00003001{
icculus9e44cf12010-02-14 17:14:22 +00003002 struct plink *newlink;
3003 newlink = Plink_new();
3004 newlink->next = *plpp;
3005 *plpp = newlink;
3006 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00003007}
3008
3009/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00003010void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00003011{
3012 struct plink *nextpl;
3013 while( from ){
3014 nextpl = from->next;
3015 from->next = *to;
3016 *to = from;
3017 from = nextpl;
3018 }
3019}
3020
3021/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00003022void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00003023{
3024 struct plink *nextpl;
3025
3026 while( plp ){
3027 nextpl = plp->next;
3028 plp->next = plink_freelist;
3029 plink_freelist = plp;
3030 plp = nextpl;
3031 }
3032}
3033/*********************** From the file "report.c" **************************/
3034/*
3035** Procedures for generating reports and tables in the LEMON parser generator.
3036*/
3037
3038/* Generate a filename with the given suffix. Space to hold the
3039** name comes from malloc() and must be freed by the calling
3040** function.
3041*/
icculus9e44cf12010-02-14 17:14:22 +00003042PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00003043{
3044 char *name;
3045 char *cp;
drh9f88e6d2018-04-20 20:47:49 +00003046 char *filename = lemp->filename;
3047 int sz;
drh75897232000-05-29 14:26:00 +00003048
drh9f88e6d2018-04-20 20:47:49 +00003049 if( outputDir ){
3050 cp = strrchr(filename, '/');
3051 if( cp ) filename = cp + 1;
3052 }
3053 sz = lemonStrlen(filename);
3054 sz += lemonStrlen(suffix);
3055 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3056 sz += 5;
3057 name = (char*)malloc( sz );
drh75897232000-05-29 14:26:00 +00003058 if( name==0 ){
3059 fprintf(stderr,"Can't allocate space for a filename.\n");
3060 exit(1);
3061 }
drh9f88e6d2018-04-20 20:47:49 +00003062 name[0] = 0;
3063 if( outputDir ){
3064 lemon_strcpy(name, outputDir);
3065 lemon_strcat(name, "/");
3066 }
3067 lemon_strcat(name,filename);
drh75897232000-05-29 14:26:00 +00003068 cp = strrchr(name,'.');
3069 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003070 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003071 return name;
3072}
3073
3074/* Open a file with a name based on the name of the input file,
3075** but with a different (specified) suffix, and return a pointer
3076** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003077PRIVATE FILE *file_open(
3078 struct lemon *lemp,
3079 const char *suffix,
3080 const char *mode
3081){
drh75897232000-05-29 14:26:00 +00003082 FILE *fp;
3083
3084 if( lemp->outname ) free(lemp->outname);
3085 lemp->outname = file_makename(lemp, suffix);
3086 fp = fopen(lemp->outname,mode);
3087 if( fp==0 && *mode=='w' ){
3088 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3089 lemp->errorcnt++;
3090 return 0;
3091 }
3092 return fp;
3093}
3094
drh5c8241b2017-12-24 23:38:10 +00003095/* Print the text of a rule
3096*/
3097void rule_print(FILE *out, struct rule *rp){
3098 int i, j;
3099 fprintf(out, "%s",rp->lhs->name);
3100 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3101 fprintf(out," ::=");
3102 for(i=0; i<rp->nrhs; i++){
3103 struct symbol *sp = rp->rhs[i];
3104 if( sp->type==MULTITERMINAL ){
3105 fprintf(out," %s", sp->subsym[0]->name);
3106 for(j=1; j<sp->nsubsym; j++){
3107 fprintf(out,"|%s", sp->subsym[j]->name);
3108 }
3109 }else{
3110 fprintf(out," %s", sp->name);
3111 }
3112 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3113 }
3114}
3115
drh06f60d82017-04-14 19:46:12 +00003116/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003117** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003118void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003119{
3120 struct rule *rp;
3121 struct symbol *sp;
3122 int i, j, maxlen, len, ncolumns, skip;
3123 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3124 maxlen = 10;
3125 for(i=0; i<lemp->nsymbol; i++){
3126 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003127 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003128 if( len>maxlen ) maxlen = len;
3129 }
3130 ncolumns = 76/(maxlen+5);
3131 if( ncolumns<1 ) ncolumns = 1;
3132 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3133 for(i=0; i<skip; i++){
3134 printf("//");
3135 for(j=i; j<lemp->nsymbol; j+=skip){
3136 sp = lemp->symbols[j];
3137 assert( sp->index==j );
3138 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3139 }
3140 printf("\n");
3141 }
3142 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003143 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003144 printf(".");
3145 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003146 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003147 printf("\n");
3148 }
3149}
3150
drh7e698e92015-09-07 14:22:24 +00003151/* Print a single rule.
3152*/
3153void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003154 struct symbol *sp;
3155 int i, j;
drh75897232000-05-29 14:26:00 +00003156 fprintf(fp,"%s ::=",rp->lhs->name);
3157 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003158 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003159 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003160 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003161 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003162 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003163 for(j=1; j<sp->nsubsym; j++){
3164 fprintf(fp,"|%s",sp->subsym[j]->name);
3165 }
drh61f92cd2014-01-11 03:06:18 +00003166 }else{
3167 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003168 }
drh75897232000-05-29 14:26:00 +00003169 }
3170}
3171
drh7e698e92015-09-07 14:22:24 +00003172/* Print the rule for a configuration.
3173*/
3174void ConfigPrint(FILE *fp, struct config *cfp){
3175 RulePrint(fp, cfp->rp, cfp->dot);
3176}
3177
drh75897232000-05-29 14:26:00 +00003178/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003179#if 0
drh75897232000-05-29 14:26:00 +00003180/* Print a set */
3181PRIVATE void SetPrint(out,set,lemp)
3182FILE *out;
3183char *set;
3184struct lemon *lemp;
3185{
3186 int i;
3187 char *spacer;
3188 spacer = "";
3189 fprintf(out,"%12s[","");
3190 for(i=0; i<lemp->nterminal; i++){
3191 if( SetFind(set,i) ){
3192 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3193 spacer = " ";
3194 }
3195 }
3196 fprintf(out,"]\n");
3197}
3198
3199/* Print a plink chain */
3200PRIVATE void PlinkPrint(out,plp,tag)
3201FILE *out;
3202struct plink *plp;
3203char *tag;
3204{
3205 while( plp ){
drhada354d2005-11-05 15:03:59 +00003206 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003207 ConfigPrint(out,plp->cfp);
3208 fprintf(out,"\n");
3209 plp = plp->next;
3210 }
3211}
3212#endif
3213
3214/* Print an action to the given file descriptor. Return FALSE if
3215** nothing was actually printed.
3216*/
drh7e698e92015-09-07 14:22:24 +00003217int PrintAction(
3218 struct action *ap, /* The action to print */
3219 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003220 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003221){
drh75897232000-05-29 14:26:00 +00003222 int result = 1;
3223 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003224 case SHIFT: {
3225 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003226 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003227 break;
drh7e698e92015-09-07 14:22:24 +00003228 }
3229 case REDUCE: {
3230 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003231 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003232 RulePrint(fp, rp, -1);
3233 break;
3234 }
3235 case SHIFTREDUCE: {
3236 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003237 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003238 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003239 break;
drh7e698e92015-09-07 14:22:24 +00003240 }
drh75897232000-05-29 14:26:00 +00003241 case ACCEPT:
3242 fprintf(fp,"%*s accept",indent,ap->sp->name);
3243 break;
3244 case ERROR:
3245 fprintf(fp,"%*s error",indent,ap->sp->name);
3246 break;
drh9892c5d2007-12-21 00:02:11 +00003247 case SRCONFLICT:
3248 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003249 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003250 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003251 break;
drh9892c5d2007-12-21 00:02:11 +00003252 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003253 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003254 indent,ap->sp->name,ap->x.stp->statenum);
3255 break;
drh75897232000-05-29 14:26:00 +00003256 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003257 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003258 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003259 indent,ap->sp->name,ap->x.stp->statenum);
3260 }else{
3261 result = 0;
3262 }
3263 break;
drh75897232000-05-29 14:26:00 +00003264 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003265 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003266 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003267 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003268 }else{
3269 result = 0;
3270 }
3271 break;
drh75897232000-05-29 14:26:00 +00003272 case NOT_USED:
3273 result = 0;
3274 break;
3275 }
drhc173ad82016-05-23 16:15:02 +00003276 if( result && ap->spOpt ){
3277 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3278 }
drh75897232000-05-29 14:26:00 +00003279 return result;
3280}
3281
drh3bd48ab2015-09-07 18:23:37 +00003282/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003283void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003284{
3285 int i;
3286 struct state *stp;
3287 struct config *cfp;
3288 struct action *ap;
drh12f68392018-04-06 19:12:55 +00003289 struct rule *rp;
drh75897232000-05-29 14:26:00 +00003290 FILE *fp;
3291
drh2aa6ca42004-09-10 00:14:04 +00003292 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003293 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003294 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003295 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003296 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003297 if( lemp->basisflag ) cfp=stp->bp;
3298 else cfp=stp->cfp;
3299 while( cfp ){
3300 char buf[20];
3301 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003302 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003303 fprintf(fp," %5s ",buf);
3304 }else{
3305 fprintf(fp," ");
3306 }
3307 ConfigPrint(fp,cfp);
3308 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003309#if 0
drh75897232000-05-29 14:26:00 +00003310 SetPrint(fp,cfp->fws,lemp);
3311 PlinkPrint(fp,cfp->fplp,"To ");
3312 PlinkPrint(fp,cfp->bplp,"From");
3313#endif
3314 if( lemp->basisflag ) cfp=cfp->bp;
3315 else cfp=cfp->next;
3316 }
3317 fprintf(fp,"\n");
3318 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003319 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003320 }
3321 fprintf(fp,"\n");
3322 }
drhe9278182007-07-18 18:16:29 +00003323 fprintf(fp, "----------------------------------------------------\n");
3324 fprintf(fp, "Symbols:\n");
3325 for(i=0; i<lemp->nsymbol; i++){
3326 int j;
3327 struct symbol *sp;
3328
3329 sp = lemp->symbols[i];
3330 fprintf(fp, " %3d: %s", i, sp->name);
3331 if( sp->type==NONTERMINAL ){
3332 fprintf(fp, ":");
3333 if( sp->lambda ){
3334 fprintf(fp, " <lambda>");
3335 }
3336 for(j=0; j<lemp->nterminal; j++){
3337 if( sp->firstset && SetFind(sp->firstset, j) ){
3338 fprintf(fp, " %s", lemp->symbols[j]->name);
3339 }
3340 }
3341 }
drh12f68392018-04-06 19:12:55 +00003342 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
drhe9278182007-07-18 18:16:29 +00003343 fprintf(fp, "\n");
3344 }
drh12f68392018-04-06 19:12:55 +00003345 fprintf(fp, "----------------------------------------------------\n");
3346 fprintf(fp, "Rules:\n");
3347 for(rp=lemp->rule; rp; rp=rp->next){
3348 fprintf(fp, "%4d: ", rp->iRule);
3349 rule_print(fp, rp);
3350 fprintf(fp,".");
3351 if( rp->precsym ){
3352 fprintf(fp," [%s precedence=%d]",
3353 rp->precsym->name, rp->precsym->prec);
3354 }
3355 fprintf(fp,"\n");
3356 }
drh75897232000-05-29 14:26:00 +00003357 fclose(fp);
3358 return;
3359}
3360
3361/* Search for the file "name" which is in the same directory as
3362** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003363PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003364{
icculus9e44cf12010-02-14 17:14:22 +00003365 const char *pathlist;
3366 char *pathbufptr;
3367 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003368 char *path,*cp;
3369 char c;
drh75897232000-05-29 14:26:00 +00003370
3371#ifdef __WIN32__
3372 cp = strrchr(argv0,'\\');
3373#else
3374 cp = strrchr(argv0,'/');
3375#endif
3376 if( cp ){
3377 c = *cp;
3378 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003379 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003380 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003381 *cp = c;
3382 }else{
drh75897232000-05-29 14:26:00 +00003383 pathlist = getenv("PATH");
3384 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003385 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003386 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003387 if( (pathbuf != 0) && (path!=0) ){
3388 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003389 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003390 while( *pathbuf ){
3391 cp = strchr(pathbuf,':');
3392 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003393 c = *cp;
3394 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003395 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003396 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003397 if( c==0 ) pathbuf[0] = 0;
3398 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003399 if( access(path,modemask)==0 ) break;
3400 }
icculus9e44cf12010-02-14 17:14:22 +00003401 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003402 }
3403 }
3404 return path;
3405}
3406
3407/* Given an action, compute the integer value for that action
3408** which is to be put in the action table of the generated machine.
3409** Return negative if no action should be generated.
3410*/
icculus9e44cf12010-02-14 17:14:22 +00003411PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003412{
3413 int act;
3414 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003415 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003416 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003417 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3418 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3419 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003420 if( ap->sp->index>=lemp->nterminal ){
3421 act = lemp->minReduce + ap->x.rp->iRule;
3422 }else{
3423 act = lemp->minShiftReduce + ap->x.rp->iRule;
3424 }
drhbd8fcc12017-06-28 11:56:18 +00003425 break;
3426 }
drh5c8241b2017-12-24 23:38:10 +00003427 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3428 case ERROR: act = lemp->errAction; break;
3429 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003430 default: act = -1; break;
3431 }
3432 return act;
3433}
3434
3435#define LINESIZE 1000
3436/* The next cluster of routines are for reading the template file
3437** and writing the results to the generated parser */
3438/* The first function transfers data from "in" to "out" until
3439** a line is seen which begins with "%%". The line number is
3440** tracked.
3441**
3442** if name!=0, then any word that begin with "Parse" is changed to
3443** begin with *name instead.
3444*/
icculus9e44cf12010-02-14 17:14:22 +00003445PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003446{
3447 int i, iStart;
3448 char line[LINESIZE];
3449 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3450 (*lineno)++;
3451 iStart = 0;
3452 if( name ){
3453 for(i=0; line[i]; i++){
3454 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003455 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003456 ){
3457 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3458 fprintf(out,"%s",name);
3459 i += 4;
3460 iStart = i+1;
3461 }
3462 }
3463 }
3464 fprintf(out,"%s",&line[iStart]);
3465 }
3466}
3467
3468/* The next function finds the template file and opens it, returning
3469** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003470PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003471{
3472 static char templatename[] = "lempar.c";
3473 char buf[1000];
3474 FILE *in;
3475 char *tpltname;
3476 char *cp;
3477
icculus3e143bd2010-02-14 00:48:49 +00003478 /* first, see if user specified a template filename on the command line. */
3479 if (user_templatename != 0) {
3480 if( access(user_templatename,004)==-1 ){
3481 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3482 user_templatename);
3483 lemp->errorcnt++;
3484 return 0;
3485 }
3486 in = fopen(user_templatename,"rb");
3487 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003488 fprintf(stderr,"Can't open the template file \"%s\".\n",
3489 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003490 lemp->errorcnt++;
3491 return 0;
3492 }
3493 return in;
3494 }
3495
drh75897232000-05-29 14:26:00 +00003496 cp = strrchr(lemp->filename,'.');
3497 if( cp ){
drh898799f2014-01-10 23:21:00 +00003498 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003499 }else{
drh898799f2014-01-10 23:21:00 +00003500 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003501 }
3502 if( access(buf,004)==0 ){
3503 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003504 }else if( access(templatename,004)==0 ){
3505 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003506 }else{
3507 tpltname = pathsearch(lemp->argv0,templatename,0);
3508 }
3509 if( tpltname==0 ){
3510 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3511 templatename);
3512 lemp->errorcnt++;
3513 return 0;
3514 }
drh2aa6ca42004-09-10 00:14:04 +00003515 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003516 if( in==0 ){
3517 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3518 lemp->errorcnt++;
3519 return 0;
3520 }
3521 return in;
3522}
3523
drhaf805ca2004-09-07 11:28:25 +00003524/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003525PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003526{
3527 fprintf(out,"#line %d \"",lineno);
3528 while( *filename ){
3529 if( *filename == '\\' ) putc('\\',out);
3530 putc(*filename,out);
3531 filename++;
3532 }
3533 fprintf(out,"\"\n");
3534}
3535
drh75897232000-05-29 14:26:00 +00003536/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003537PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003538{
3539 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003540 while( *str ){
drh75897232000-05-29 14:26:00 +00003541 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003542 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003543 str++;
3544 }
drh9db55df2004-09-09 14:01:21 +00003545 if( str[-1]!='\n' ){
3546 putc('\n',out);
3547 (*lineno)++;
3548 }
shane58543932008-12-10 20:10:04 +00003549 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003550 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003551 }
drh75897232000-05-29 14:26:00 +00003552 return;
3553}
3554
3555/*
3556** The following routine emits code for the destructor for the
3557** symbol sp
3558*/
icculus9e44cf12010-02-14 17:14:22 +00003559void emit_destructor_code(
3560 FILE *out,
3561 struct symbol *sp,
3562 struct lemon *lemp,
3563 int *lineno
3564){
drhcc83b6e2004-04-23 23:38:42 +00003565 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003566
drh75897232000-05-29 14:26:00 +00003567 if( sp->type==TERMINAL ){
3568 cp = lemp->tokendest;
3569 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003570 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003571 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003572 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003573 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003574 if( !lemp->nolinenosflag ){
3575 (*lineno)++;
3576 tplt_linedir(out,sp->destLineno,lemp->filename);
3577 }
drh960e8c62001-04-03 16:53:21 +00003578 }else if( lemp->vardest ){
3579 cp = lemp->vardest;
3580 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003581 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003582 }else{
3583 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003584 }
3585 for(; *cp; cp++){
3586 if( *cp=='$' && cp[1]=='$' ){
3587 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3588 cp++;
3589 continue;
3590 }
shane58543932008-12-10 20:10:04 +00003591 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003592 fputc(*cp,out);
3593 }
shane58543932008-12-10 20:10:04 +00003594 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003595 if (!lemp->nolinenosflag) {
3596 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003597 }
3598 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003599 return;
3600}
3601
3602/*
drh960e8c62001-04-03 16:53:21 +00003603** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003604*/
icculus9e44cf12010-02-14 17:14:22 +00003605int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003606{
3607 int ret;
3608 if( sp->type==TERMINAL ){
3609 ret = lemp->tokendest!=0;
3610 }else{
drh960e8c62001-04-03 16:53:21 +00003611 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003612 }
3613 return ret;
3614}
3615
drh0bb132b2004-07-20 14:06:51 +00003616/*
3617** Append text to a dynamically allocated string. If zText is 0 then
3618** reset the string to be empty again. Always return the complete text
3619** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003620**
3621** n bytes of zText are stored. If n==0 then all of zText up to the first
3622** \000 terminator is stored. zText can contain up to two instances of
3623** %d. The values of p1 and p2 are written into the first and second
3624** %d.
3625**
3626** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003627*/
icculus9e44cf12010-02-14 17:14:22 +00003628PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3629 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003630 static char *z = 0;
3631 static int alloced = 0;
3632 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003633 int c;
drh0bb132b2004-07-20 14:06:51 +00003634 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003635 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003636 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003637 used = 0;
3638 return z;
3639 }
drh7ac25c72004-08-19 15:12:26 +00003640 if( n<=0 ){
3641 if( n<0 ){
3642 used += n;
3643 assert( used>=0 );
3644 }
drh87cf1372008-08-13 20:09:06 +00003645 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003646 }
drhdf609712010-11-23 20:55:27 +00003647 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003648 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003649 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003650 }
icculus9e44cf12010-02-14 17:14:22 +00003651 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003652 while( n-- > 0 ){
3653 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003654 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003655 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003656 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003657 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003658 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003659 zText++;
3660 n--;
3661 }else{
mistachkin2318d332015-01-12 18:02:52 +00003662 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003663 }
3664 }
3665 z[used] = 0;
3666 return z;
3667}
3668
3669/*
drh711c9812016-05-23 14:24:31 +00003670** Write and transform the rp->code string so that symbols are expanded.
3671** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003672**
3673** Return 1 if the expanded code requires that "yylhsminor" local variable
3674** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003675*/
drhdabd04c2016-02-17 01:46:19 +00003676PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003677 char *cp, *xp;
3678 int i;
drhcf82f0d2016-02-17 04:33:10 +00003679 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003680 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003681 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3682 char lhsused = 0; /* True if the LHS element has been used */
3683 char lhsdirect; /* True if LHS writes directly into stack */
3684 char used[MAXRHS]; /* True for each RHS element which is used */
3685 char zLhs[50]; /* Convert the LHS symbol into this string */
3686 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003687
3688 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3689 lhsused = 0;
3690
drh19c9e562007-03-29 20:13:53 +00003691 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003692 static char newlinestr[2] = { '\n', '\0' };
3693 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003694 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003695 rp->noCode = 1;
3696 }else{
3697 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003698 }
3699
drh4dd0d3f2016-02-17 01:18:33 +00003700
drh2e55b042016-04-30 17:19:30 +00003701 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003702 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3703 lhsdirect = 1;
3704 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003705 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003706 ** we have to call the distructor on the RHS symbol first. */
3707 lhsdirect = 1;
3708 if( has_destructor(rp->rhs[0],lemp) ){
3709 append_str(0,0,0,0);
3710 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3711 rp->rhs[0]->index,1-rp->nrhs);
3712 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003713 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003714 }
drh2e55b042016-04-30 17:19:30 +00003715 }else if( rp->lhsalias==0 ){
3716 /* There is no LHS value symbol. */
3717 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003718 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003719 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003720 ** direct writing is allowed */
3721 lhsdirect = 1;
3722 lhsused = 1;
3723 used[0] = 1;
3724 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3725 ErrorMsg(lemp->filename,rp->ruleline,
3726 "%s(%s) and %s(%s) share the same label but have "
3727 "different datatypes.",
3728 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3729 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003730 }
drh4dd0d3f2016-02-17 01:18:33 +00003731 }else{
drhcf82f0d2016-02-17 04:33:10 +00003732 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3733 rp->lhsalias, rp->rhsalias[0]);
3734 zSkip = strstr(rp->code, zOvwrt);
3735 if( zSkip!=0 ){
3736 /* The code contains a special comment that indicates that it is safe
3737 ** for the LHS label to overwrite left-most RHS label. */
3738 lhsdirect = 1;
3739 }else{
3740 lhsdirect = 0;
3741 }
drh4dd0d3f2016-02-17 01:18:33 +00003742 }
3743 if( lhsdirect ){
3744 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3745 }else{
drhdabd04c2016-02-17 01:46:19 +00003746 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003747 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3748 }
3749
drh0bb132b2004-07-20 14:06:51 +00003750 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003751
3752 /* This const cast is wrong but harmless, if we're careful. */
3753 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003754 if( cp==zSkip ){
3755 append_str(zOvwrt,0,0,0);
3756 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003757 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003758 continue;
3759 }
drhc56fac72015-10-29 13:48:15 +00003760 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003761 char saved;
drhc56fac72015-10-29 13:48:15 +00003762 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003763 saved = *xp;
3764 *xp = 0;
3765 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003766 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003767 cp = xp;
3768 lhsused = 1;
3769 }else{
3770 for(i=0; i<rp->nrhs; i++){
3771 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003772 if( i==0 && dontUseRhs0 ){
3773 ErrorMsg(lemp->filename,rp->ruleline,
3774 "Label %s used after '%s'.",
3775 rp->rhsalias[0], zOvwrt);
3776 lemp->errorcnt++;
3777 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003778 /* If the argument is of the form @X then substituted
3779 ** the token number of X, not the value of X */
3780 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3781 }else{
drhfd405312005-11-06 04:06:59 +00003782 struct symbol *sp = rp->rhs[i];
3783 int dtnum;
3784 if( sp->type==MULTITERMINAL ){
3785 dtnum = sp->subsym[0]->dtnum;
3786 }else{
3787 dtnum = sp->dtnum;
3788 }
3789 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003790 }
drh0bb132b2004-07-20 14:06:51 +00003791 cp = xp;
3792 used[i] = 1;
3793 break;
3794 }
3795 }
3796 }
3797 *xp = saved;
3798 }
3799 append_str(cp, 1, 0, 0);
3800 } /* End loop */
3801
drh4dd0d3f2016-02-17 01:18:33 +00003802 /* Main code generation completed */
3803 cp = append_str(0,0,0,0);
3804 if( cp && cp[0] ) rp->code = Strsafe(cp);
3805 append_str(0,0,0,0);
3806
drh0bb132b2004-07-20 14:06:51 +00003807 /* Check to make sure the LHS has been used */
3808 if( rp->lhsalias && !lhsused ){
3809 ErrorMsg(lemp->filename,rp->ruleline,
3810 "Label \"%s\" for \"%s(%s)\" is never used.",
3811 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3812 lemp->errorcnt++;
3813 }
3814
drh4dd0d3f2016-02-17 01:18:33 +00003815 /* Generate destructor code for RHS minor values which are not referenced.
3816 ** Generate error messages for unused labels and duplicate labels.
3817 */
drh0bb132b2004-07-20 14:06:51 +00003818 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003819 if( rp->rhsalias[i] ){
3820 if( i>0 ){
3821 int j;
3822 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3823 ErrorMsg(lemp->filename,rp->ruleline,
3824 "%s(%s) has the same label as the LHS but is not the left-most "
3825 "symbol on the RHS.",
3826 rp->rhs[i]->name, rp->rhsalias);
3827 lemp->errorcnt++;
3828 }
3829 for(j=0; j<i; j++){
3830 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3831 ErrorMsg(lemp->filename,rp->ruleline,
3832 "Label %s used for multiple symbols on the RHS of a rule.",
3833 rp->rhsalias[i]);
3834 lemp->errorcnt++;
3835 break;
3836 }
3837 }
drh0bb132b2004-07-20 14:06:51 +00003838 }
drh4dd0d3f2016-02-17 01:18:33 +00003839 if( !used[i] ){
3840 ErrorMsg(lemp->filename,rp->ruleline,
3841 "Label %s for \"%s(%s)\" is never used.",
3842 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3843 lemp->errorcnt++;
3844 }
3845 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3846 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3847 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003848 }
3849 }
drh4dd0d3f2016-02-17 01:18:33 +00003850
3851 /* If unable to write LHS values directly into the stack, write the
3852 ** saved LHS value now. */
3853 if( lhsdirect==0 ){
3854 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3855 append_str(zLhs, 0, 0, 0);
3856 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003857 }
drh4dd0d3f2016-02-17 01:18:33 +00003858
3859 /* Suffix code generation complete */
3860 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003861 if( cp && cp[0] ){
3862 rp->codeSuffix = Strsafe(cp);
3863 rp->noCode = 0;
3864 }
drhdabd04c2016-02-17 01:46:19 +00003865
3866 return rc;
drh0bb132b2004-07-20 14:06:51 +00003867}
3868
drh06f60d82017-04-14 19:46:12 +00003869/*
drh75897232000-05-29 14:26:00 +00003870** Generate code which executes when the rule "rp" is reduced. Write
3871** the code to "out". Make sure lineno stays up-to-date.
3872*/
icculus9e44cf12010-02-14 17:14:22 +00003873PRIVATE void emit_code(
3874 FILE *out,
3875 struct rule *rp,
3876 struct lemon *lemp,
3877 int *lineno
3878){
3879 const char *cp;
drh75897232000-05-29 14:26:00 +00003880
drh4dd0d3f2016-02-17 01:18:33 +00003881 /* Setup code prior to the #line directive */
3882 if( rp->codePrefix && rp->codePrefix[0] ){
3883 fprintf(out, "{%s", rp->codePrefix);
3884 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3885 }
3886
drh75897232000-05-29 14:26:00 +00003887 /* Generate code to do the reduce action */
3888 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003889 if( !lemp->nolinenosflag ){
3890 (*lineno)++;
3891 tplt_linedir(out,rp->line,lemp->filename);
3892 }
drhaf805ca2004-09-07 11:28:25 +00003893 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003894 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003895 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003896 if( !lemp->nolinenosflag ){
3897 (*lineno)++;
3898 tplt_linedir(out,*lineno,lemp->outname);
3899 }
drh4dd0d3f2016-02-17 01:18:33 +00003900 }
3901
3902 /* Generate breakdown code that occurs after the #line directive */
3903 if( rp->codeSuffix && rp->codeSuffix[0] ){
3904 fprintf(out, "%s", rp->codeSuffix);
3905 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3906 }
3907
3908 if( rp->codePrefix ){
3909 fprintf(out, "}\n"); (*lineno)++;
3910 }
drh75897232000-05-29 14:26:00 +00003911
drh75897232000-05-29 14:26:00 +00003912 return;
3913}
3914
3915/*
3916** Print the definition of the union used for the parser's data stack.
3917** This union contains fields for every possible data type for tokens
3918** and nonterminals. In the process of computing and printing this
3919** union, also set the ".dtnum" field of every terminal and nonterminal
3920** symbol.
3921*/
icculus9e44cf12010-02-14 17:14:22 +00003922void print_stack_union(
3923 FILE *out, /* The output stream */
3924 struct lemon *lemp, /* The main info structure for this parser */
3925 int *plineno, /* Pointer to the line number */
3926 int mhflag /* True if generating makeheaders output */
3927){
drh75897232000-05-29 14:26:00 +00003928 int lineno = *plineno; /* The line number of the output */
3929 char **types; /* A hash table of datatypes */
3930 int arraysize; /* Size of the "types" array */
3931 int maxdtlength; /* Maximum length of any ".datatype" field. */
3932 char *stddt; /* Standardized name for a datatype */
3933 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003934 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003935 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003936
3937 /* Allocate and initialize types[] and allocate stddt[] */
3938 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003939 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003940 if( types==0 ){
3941 fprintf(stderr,"Out of memory.\n");
3942 exit(1);
3943 }
drh75897232000-05-29 14:26:00 +00003944 for(i=0; i<arraysize; i++) types[i] = 0;
3945 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003946 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003947 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003948 }
drh75897232000-05-29 14:26:00 +00003949 for(i=0; i<lemp->nsymbol; i++){
3950 int len;
3951 struct symbol *sp = lemp->symbols[i];
3952 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003953 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003954 if( len>maxdtlength ) maxdtlength = len;
3955 }
3956 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003957 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003958 fprintf(stderr,"Out of memory.\n");
3959 exit(1);
3960 }
3961
3962 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3963 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003964 ** used for terminal symbols. If there is no %default_type defined then
3965 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3966 ** a datatype using the %type directive.
3967 */
drh75897232000-05-29 14:26:00 +00003968 for(i=0; i<lemp->nsymbol; i++){
3969 struct symbol *sp = lemp->symbols[i];
3970 char *cp;
3971 if( sp==lemp->errsym ){
3972 sp->dtnum = arraysize+1;
3973 continue;
3974 }
drh960e8c62001-04-03 16:53:21 +00003975 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003976 sp->dtnum = 0;
3977 continue;
3978 }
3979 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003980 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003981 j = 0;
drhc56fac72015-10-29 13:48:15 +00003982 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003983 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003984 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003985 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003986 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003987 sp->dtnum = 0;
3988 continue;
3989 }
drh75897232000-05-29 14:26:00 +00003990 hash = 0;
3991 for(j=0; stddt[j]; j++){
3992 hash = hash*53 + stddt[j];
3993 }
drh3b2129c2003-05-13 00:34:21 +00003994 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003995 while( types[hash] ){
3996 if( strcmp(types[hash],stddt)==0 ){
3997 sp->dtnum = hash + 1;
3998 break;
3999 }
4000 hash++;
drh2b51f212013-10-11 23:01:02 +00004001 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00004002 }
4003 if( types[hash]==0 ){
4004 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00004005 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00004006 if( types[hash]==0 ){
4007 fprintf(stderr,"Out of memory.\n");
4008 exit(1);
4009 }
drh898799f2014-01-10 23:21:00 +00004010 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00004011 }
4012 }
4013
4014 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4015 name = lemp->name ? lemp->name : "Parse";
4016 lineno = *plineno;
4017 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4018 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4019 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4020 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4021 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00004022 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004023 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4024 for(i=0; i<arraysize; i++){
4025 if( types[i]==0 ) continue;
4026 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4027 free(types[i]);
4028 }
drhed0c15b2018-04-16 14:31:34 +00004029 if( lemp->errsym && lemp->errsym->useCnt ){
drhc4dd3fd2008-01-22 01:48:05 +00004030 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4031 }
drh75897232000-05-29 14:26:00 +00004032 free(stddt);
4033 free(types);
4034 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4035 *plineno = lineno;
4036}
4037
drhb29b0a52002-02-23 19:39:46 +00004038/*
4039** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00004040** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4041** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00004042*/
drhc75e0162015-09-07 02:23:02 +00004043static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4044 const char *zType = "int";
4045 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00004046 if( lwr>=0 ){
4047 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00004048 zType = "unsigned char";
4049 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004050 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00004051 zType = "unsigned short int";
4052 nByte = 2;
drh8b582012003-10-21 13:16:03 +00004053 }else{
drhc75e0162015-09-07 02:23:02 +00004054 zType = "unsigned int";
4055 nByte = 4;
drh8b582012003-10-21 13:16:03 +00004056 }
4057 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00004058 zType = "signed char";
4059 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004060 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00004061 zType = "short";
4062 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00004063 }
drhc75e0162015-09-07 02:23:02 +00004064 if( pnByte ) *pnByte = nByte;
4065 return zType;
drhb29b0a52002-02-23 19:39:46 +00004066}
4067
drhfdbf9282003-10-21 16:34:41 +00004068/*
4069** Each state contains a set of token transaction and a set of
4070** nonterminal transactions. Each of these sets makes an instance
4071** of the following structure. An array of these structures is used
4072** to order the creation of entries in the yy_action[] table.
4073*/
4074struct axset {
4075 struct state *stp; /* A pointer to a state */
4076 int isTkn; /* True to use tokens. False for non-terminals */
4077 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00004078 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00004079};
4080
4081/*
4082** Compare to axset structures for sorting purposes
4083*/
4084static int axset_compare(const void *a, const void *b){
4085 struct axset *p1 = (struct axset*)a;
4086 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004087 int c;
4088 c = p2->nAction - p1->nAction;
4089 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004090 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004091 }
4092 assert( c!=0 || p1==p2 );
4093 return c;
drhfdbf9282003-10-21 16:34:41 +00004094}
4095
drhc4dd3fd2008-01-22 01:48:05 +00004096/*
4097** Write text on "out" that describes the rule "rp".
4098*/
4099static void writeRuleText(FILE *out, struct rule *rp){
4100 int j;
4101 fprintf(out,"%s ::=", rp->lhs->name);
4102 for(j=0; j<rp->nrhs; j++){
4103 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004104 if( sp->type!=MULTITERMINAL ){
4105 fprintf(out," %s", sp->name);
4106 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004107 int k;
drh61f92cd2014-01-11 03:06:18 +00004108 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004109 for(k=1; k<sp->nsubsym; k++){
4110 fprintf(out,"|%s",sp->subsym[k]->name);
4111 }
4112 }
4113 }
4114}
4115
4116
drh75897232000-05-29 14:26:00 +00004117/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004118void ReportTable(
4119 struct lemon *lemp,
4120 int mhflag /* Output in makeheaders format if true */
4121){
drh75897232000-05-29 14:26:00 +00004122 FILE *out, *in;
4123 char line[LINESIZE];
4124 int lineno;
4125 struct state *stp;
4126 struct action *ap;
4127 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004128 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004129 int i, j, n, sz;
4130 int szActionType; /* sizeof(YYACTIONTYPE) */
4131 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004132 const char *name;
drh8b582012003-10-21 13:16:03 +00004133 int mnTknOfst, mxTknOfst;
4134 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004135 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004136
drh5c8241b2017-12-24 23:38:10 +00004137 lemp->minShiftReduce = lemp->nstate;
4138 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4139 lemp->accAction = lemp->errAction + 1;
4140 lemp->noAction = lemp->accAction + 1;
4141 lemp->minReduce = lemp->noAction + 1;
4142 lemp->maxAction = lemp->minReduce + lemp->nrule;
4143
drh75897232000-05-29 14:26:00 +00004144 in = tplt_open(lemp);
4145 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004146 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004147 if( out==0 ){
4148 fclose(in);
4149 return;
4150 }
4151 lineno = 1;
4152 tplt_xfer(lemp->name,in,out,&lineno);
4153
4154 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004155 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004156 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004157 char *incName = file_makename(lemp, ".h");
4158 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4159 free(incName);
drh75897232000-05-29 14:26:00 +00004160 }
4161 tplt_xfer(lemp->name,in,out,&lineno);
4162
4163 /* Generate #defines for all tokens */
4164 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004165 const char *prefix;
drh75897232000-05-29 14:26:00 +00004166 fprintf(out,"#if INTERFACE\n"); lineno++;
4167 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4168 else prefix = "";
4169 for(i=1; i<lemp->nterminal; i++){
4170 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4171 lineno++;
4172 }
4173 fprintf(out,"#endif\n"); lineno++;
4174 }
4175 tplt_xfer(lemp->name,in,out,&lineno);
4176
4177 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004178 fprintf(out,"#define YYCODETYPE %s\n",
drhed0c15b2018-04-16 14:31:34 +00004179 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4180 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
drh75897232000-05-29 14:26:00 +00004181 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004182 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004183 if( lemp->wildcard ){
4184 fprintf(out,"#define YYWILDCARD %d\n",
4185 lemp->wildcard->index); lineno++;
4186 }
drh75897232000-05-29 14:26:00 +00004187 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004188 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004189 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004190 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4191 }else{
4192 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4193 }
drhca44b5a2007-02-22 23:06:58 +00004194 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004195 if( mhflag ){
4196 fprintf(out,"#if INTERFACE\n"); lineno++;
4197 }
4198 name = lemp->name ? lemp->name : "Parse";
4199 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004200 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004201 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4202 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004203 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4204 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
drhfb32c442018-04-21 13:51:42 +00004205 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4206 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
drh1f245e42002-03-11 13:55:50 +00004207 name,lemp->arg,&lemp->arg[i]); lineno++;
drhfb32c442018-04-21 13:51:42 +00004208 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
drh1f245e42002-03-11 13:55:50 +00004209 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004210 }else{
drhfb32c442018-04-21 13:51:42 +00004211 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4212 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4213 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
drh1f245e42002-03-11 13:55:50 +00004214 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4215 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004216 }
drhfb32c442018-04-21 13:51:42 +00004217 if( lemp->ctx && lemp->ctx[0] ){
4218 i = lemonStrlen(lemp->ctx);
4219 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4220 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4221 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4222 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4223 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4224 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4225 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4226 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4227 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4228 }else{
4229 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4230 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4231 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4232 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4233 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4234 }
drh75897232000-05-29 14:26:00 +00004235 if( mhflag ){
4236 fprintf(out,"#endif\n"); lineno++;
4237 }
drhed0c15b2018-04-16 14:31:34 +00004238 if( lemp->errsym && lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004239 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4240 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004241 }
drh0bd1f4e2002-06-06 18:54:39 +00004242 if( lemp->has_fallback ){
4243 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4244 }
drh75897232000-05-29 14:26:00 +00004245
drh3bd48ab2015-09-07 18:23:37 +00004246 /* Compute the action table, but do not output it yet. The action
4247 ** table must be computed before generating the YYNSTATE macro because
4248 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004249 */
drh3bd48ab2015-09-07 18:23:37 +00004250 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004251 if( ax==0 ){
4252 fprintf(stderr,"malloc failed\n");
4253 exit(1);
4254 }
drh3bd48ab2015-09-07 18:23:37 +00004255 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004256 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004257 ax[i*2].stp = stp;
4258 ax[i*2].isTkn = 1;
4259 ax[i*2].nAction = stp->nTknAct;
4260 ax[i*2+1].stp = stp;
4261 ax[i*2+1].isTkn = 0;
4262 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004263 }
drh8b582012003-10-21 13:16:03 +00004264 mxTknOfst = mnTknOfst = 0;
4265 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004266 /* In an effort to minimize the action table size, use the heuristic
4267 ** of placing the largest action sets first */
4268 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4269 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh3a9d6c72017-12-25 04:15:38 +00004270 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
drh3bd48ab2015-09-07 18:23:37 +00004271 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004272 stp = ax[i].stp;
4273 if( ax[i].isTkn ){
4274 for(ap=stp->ap; ap; ap=ap->next){
4275 int action;
4276 if( ap->sp->index>=lemp->nterminal ) continue;
4277 action = compute_action(lemp, ap);
4278 if( action<0 ) continue;
4279 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004280 }
drh3a9d6c72017-12-25 04:15:38 +00004281 stp->iTknOfst = acttab_insert(pActtab, 1);
drhfdbf9282003-10-21 16:34:41 +00004282 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4283 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4284 }else{
4285 for(ap=stp->ap; ap; ap=ap->next){
4286 int action;
4287 if( ap->sp->index<lemp->nterminal ) continue;
4288 if( ap->sp->index==lemp->nsymbol ) continue;
4289 action = compute_action(lemp, ap);
4290 if( action<0 ) continue;
4291 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004292 }
drh3a9d6c72017-12-25 04:15:38 +00004293 stp->iNtOfst = acttab_insert(pActtab, 0);
drhfdbf9282003-10-21 16:34:41 +00004294 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4295 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004296 }
drh337cd0d2015-09-07 23:40:42 +00004297#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4298 { int jj, nn;
4299 for(jj=nn=0; jj<pActtab->nAction; jj++){
4300 if( pActtab->aAction[jj].action<0 ) nn++;
4301 }
4302 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4303 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4304 ax[i].nAction, pActtab->nAction, nn);
4305 }
4306#endif
drh8b582012003-10-21 13:16:03 +00004307 }
drhfdbf9282003-10-21 16:34:41 +00004308 free(ax);
drh8b582012003-10-21 13:16:03 +00004309
drh756b41e2016-05-24 18:55:08 +00004310 /* Mark rules that are actually used for reduce actions after all
4311 ** optimizations have been applied
4312 */
4313 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4314 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004315 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4316 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004317 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004318 }
4319 }
4320 }
4321
drh3bd48ab2015-09-07 18:23:37 +00004322 /* Finish rendering the constants now that the action table has
4323 ** been computed */
4324 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4325 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh0d9de992017-12-26 18:04:23 +00004326 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004327 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004328 i = lemp->minShiftReduce;
4329 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4330 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004331 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004332 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4333 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4334 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4335 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4336 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004337 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004338 tplt_xfer(lemp->name,in,out,&lineno);
4339
4340 /* Now output the action table and its associates:
4341 **
4342 ** yy_action[] A single table containing all actions.
4343 ** yy_lookahead[] A table containing the lookahead for each entry in
4344 ** yy_action. Used to detect hash collisions.
4345 ** yy_shift_ofst[] For each state, the offset into yy_action for
4346 ** shifting terminals.
4347 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4348 ** shifting non-terminals after a reduce.
4349 ** yy_default[] Default action for each state.
4350 */
4351
drh8b582012003-10-21 13:16:03 +00004352 /* Output the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +00004353 lemp->nactiontab = n = acttab_action_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004354 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004355 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4356 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004357 for(i=j=0; i<n; i++){
4358 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004359 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004360 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004361 fprintf(out, " %4d,", action);
4362 if( j==9 || i==n-1 ){
4363 fprintf(out, "\n"); lineno++;
4364 j = 0;
4365 }else{
4366 j++;
4367 }
4368 }
4369 fprintf(out, "};\n"); lineno++;
4370
4371 /* Output the yy_lookahead table */
drh3a9d6c72017-12-25 04:15:38 +00004372 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004373 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004374 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004375 for(i=j=0; i<n; i++){
4376 int la = acttab_yylookahead(pActtab, i);
4377 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004378 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004379 fprintf(out, " %4d,", la);
4380 if( j==9 || i==n-1 ){
4381 fprintf(out, "\n"); lineno++;
4382 j = 0;
4383 }else{
4384 j++;
4385 }
4386 }
4387 fprintf(out, "};\n"); lineno++;
4388
4389 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004390 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004391 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004392 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4393 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4394 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004395 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004396 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4397 lineno++;
drhc75e0162015-09-07 02:23:02 +00004398 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004399 for(i=j=0; i<n; i++){
4400 int ofst;
4401 stp = lemp->sorted[i];
4402 ofst = stp->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004403 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
drhfdbf9282003-10-21 16:34:41 +00004404 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004405 fprintf(out, " %4d,", ofst);
4406 if( j==9 || i==n-1 ){
4407 fprintf(out, "\n"); lineno++;
4408 j = 0;
4409 }else{
4410 j++;
4411 }
4412 }
4413 fprintf(out, "};\n"); lineno++;
4414
4415 /* Output the yy_reduce_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004416 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004417 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004418 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4419 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4420 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004421 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004422 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4423 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004424 for(i=j=0; i<n; i++){
4425 int ofst;
4426 stp = lemp->sorted[i];
4427 ofst = stp->iNtOfst;
4428 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004429 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004430 fprintf(out, " %4d,", ofst);
4431 if( j==9 || i==n-1 ){
4432 fprintf(out, "\n"); lineno++;
4433 j = 0;
4434 }else{
4435 j++;
4436 }
4437 }
4438 fprintf(out, "};\n"); lineno++;
4439
4440 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004441 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004442 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004443 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004444 for(i=j=0; i<n; i++){
4445 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004446 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004447 if( stp->iDfltReduce<0 ){
4448 fprintf(out, " %4d,", lemp->errAction);
4449 }else{
4450 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4451 }
drh8b582012003-10-21 13:16:03 +00004452 if( j==9 || i==n-1 ){
4453 fprintf(out, "\n"); lineno++;
4454 j = 0;
4455 }else{
4456 j++;
4457 }
4458 }
4459 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004460 tplt_xfer(lemp->name,in,out,&lineno);
4461
drh0bd1f4e2002-06-06 18:54:39 +00004462 /* Generate the table of fallback tokens.
4463 */
4464 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004465 int mx = lemp->nterminal - 1;
4466 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004467 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004468 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004469 struct symbol *p = lemp->symbols[i];
4470 if( p->fallback==0 ){
4471 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4472 }else{
4473 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4474 p->name, p->fallback->name);
4475 }
4476 lineno++;
4477 }
4478 }
4479 tplt_xfer(lemp->name, in, out, &lineno);
4480
4481 /* Generate a table containing the symbolic name of every symbol
4482 */
drh75897232000-05-29 14:26:00 +00004483 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004484 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh3a9d6c72017-12-25 04:15:38 +00004485 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
drh75897232000-05-29 14:26:00 +00004486 }
drh75897232000-05-29 14:26:00 +00004487 tplt_xfer(lemp->name,in,out,&lineno);
4488
drh0bd1f4e2002-06-06 18:54:39 +00004489 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004490 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004491 ** when tracing REDUCE actions.
4492 */
4493 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004494 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004495 fprintf(out," /* %3d */ \"", i);
4496 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004497 fprintf(out,"\",\n"); lineno++;
4498 }
4499 tplt_xfer(lemp->name,in,out,&lineno);
4500
drh75897232000-05-29 14:26:00 +00004501 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004502 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004503 ** (In other words, generate the %destructor actions)
4504 */
drh75897232000-05-29 14:26:00 +00004505 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004506 int once = 1;
drh75897232000-05-29 14:26:00 +00004507 for(i=0; i<lemp->nsymbol; i++){
4508 struct symbol *sp = lemp->symbols[i];
4509 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004510 if( once ){
4511 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4512 once = 0;
4513 }
drhc53eed12009-06-12 17:46:19 +00004514 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004515 }
4516 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4517 if( i<lemp->nsymbol ){
4518 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4519 fprintf(out," break;\n"); lineno++;
4520 }
4521 }
drh8d659732005-01-13 23:54:06 +00004522 if( lemp->vardest ){
4523 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004524 int once = 1;
drh8d659732005-01-13 23:54:06 +00004525 for(i=0; i<lemp->nsymbol; i++){
4526 struct symbol *sp = lemp->symbols[i];
4527 if( sp==0 || sp->type==TERMINAL ||
4528 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004529 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004530 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004531 once = 0;
4532 }
drhc53eed12009-06-12 17:46:19 +00004533 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004534 dflt_sp = sp;
4535 }
4536 if( dflt_sp!=0 ){
4537 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004538 }
drh4dc8ef52008-07-01 17:13:57 +00004539 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004540 }
drh75897232000-05-29 14:26:00 +00004541 for(i=0; i<lemp->nsymbol; i++){
4542 struct symbol *sp = lemp->symbols[i];
4543 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004544 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004545 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004546
4547 /* Combine duplicate destructors into a single case */
4548 for(j=i+1; j<lemp->nsymbol; j++){
4549 struct symbol *sp2 = lemp->symbols[j];
4550 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4551 && sp2->dtnum==sp->dtnum
4552 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004553 fprintf(out," case %d: /* %s */\n",
4554 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004555 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004556 }
4557 }
4558
drh75897232000-05-29 14:26:00 +00004559 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4560 fprintf(out," break;\n"); lineno++;
4561 }
drh75897232000-05-29 14:26:00 +00004562 tplt_xfer(lemp->name,in,out,&lineno);
4563
4564 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004565 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004566 tplt_xfer(lemp->name,in,out,&lineno);
4567
drh06f60d82017-04-14 19:46:12 +00004568 /* Generate the table of rule information
drh75897232000-05-29 14:26:00 +00004569 **
4570 ** Note: This code depends on the fact that rules are number
4571 ** sequentually beginning with 0.
4572 */
drh5c8241b2017-12-24 23:38:10 +00004573 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4574 fprintf(out," { %4d, %4d }, /* (%d) ",rp->lhs->index,-rp->nrhs,i);
4575 rule_print(out, rp);
4576 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004577 }
4578 tplt_xfer(lemp->name,in,out,&lineno);
4579
4580 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004581 i = 0;
drh75897232000-05-29 14:26:00 +00004582 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004583 i += translate_code(lemp, rp);
4584 }
4585 if( i ){
4586 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004587 }
drhc53eed12009-06-12 17:46:19 +00004588 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004589 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004590 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004591 if( rp->codeEmitted ) continue;
4592 if( rp->noCode ){
4593 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004594 continue;
4595 }
drh4ef07702016-03-16 19:45:54 +00004596 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004597 writeRuleText(out, rp);
4598 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004599 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004600 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4601 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004602 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004603 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004604 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004605 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004606 }
4607 }
drh75897232000-05-29 14:26:00 +00004608 emit_code(out,rp,lemp,&lineno);
4609 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004610 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004611 }
drhc53eed12009-06-12 17:46:19 +00004612 /* Finally, output the default: rule. We choose as the default: all
4613 ** empty actions. */
4614 fprintf(out," default:\n"); lineno++;
4615 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004616 if( rp->codeEmitted ) continue;
4617 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004618 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004619 writeRuleText(out, rp);
drh756b41e2016-05-24 18:55:08 +00004620 if( rp->doesReduce ){
4621 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4622 }else{
4623 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4624 rp->iRule); lineno++;
4625 }
drhc53eed12009-06-12 17:46:19 +00004626 }
4627 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004628 tplt_xfer(lemp->name,in,out,&lineno);
4629
4630 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004631 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004632 tplt_xfer(lemp->name,in,out,&lineno);
4633
4634 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004635 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004636 tplt_xfer(lemp->name,in,out,&lineno);
4637
4638 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004639 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004640 tplt_xfer(lemp->name,in,out,&lineno);
4641
4642 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004643 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004644
4645 fclose(in);
4646 fclose(out);
4647 return;
4648}
4649
4650/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004651void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004652{
4653 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004654 const char *prefix;
drh75897232000-05-29 14:26:00 +00004655 char line[LINESIZE];
4656 char pattern[LINESIZE];
4657 int i;
4658
4659 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4660 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004661 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004662 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004663 int nextChar;
drh75897232000-05-29 14:26:00 +00004664 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004665 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4666 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004667 if( strcmp(line,pattern) ) break;
4668 }
drh8ba0d1c2012-06-16 15:26:31 +00004669 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004670 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004671 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004672 /* No change in the file. Don't rewrite it. */
4673 return;
4674 }
4675 }
drh2aa6ca42004-09-10 00:14:04 +00004676 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004677 if( out ){
4678 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004679 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004680 }
drh06f60d82017-04-14 19:46:12 +00004681 fclose(out);
drh75897232000-05-29 14:26:00 +00004682 }
4683 return;
4684}
4685
4686/* Reduce the size of the action tables, if possible, by making use
4687** of defaults.
4688**
drhb59499c2002-02-23 18:45:13 +00004689** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004690** it the default. Except, there is no default if the wildcard token
4691** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004692*/
icculus9e44cf12010-02-14 17:14:22 +00004693void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004694{
4695 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004696 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004697 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004698 int nbest, n;
drh75897232000-05-29 14:26:00 +00004699 int i;
drhe09daa92006-06-10 13:29:31 +00004700 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004701
4702 for(i=0; i<lemp->nstate; i++){
4703 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004704 nbest = 0;
4705 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004706 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004707
drhb59499c2002-02-23 18:45:13 +00004708 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004709 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4710 usesWildcard = 1;
4711 }
drhb59499c2002-02-23 18:45:13 +00004712 if( ap->type!=REDUCE ) continue;
4713 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004714 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004715 if( rp==rbest ) continue;
4716 n = 1;
4717 for(ap2=ap->next; ap2; ap2=ap2->next){
4718 if( ap2->type!=REDUCE ) continue;
4719 rp2 = ap2->x.rp;
4720 if( rp2==rbest ) continue;
4721 if( rp2==rp ) n++;
4722 }
4723 if( n>nbest ){
4724 nbest = n;
4725 rbest = rp;
drh75897232000-05-29 14:26:00 +00004726 }
4727 }
drh06f60d82017-04-14 19:46:12 +00004728
drhb59499c2002-02-23 18:45:13 +00004729 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004730 ** is not at least 1 or if the wildcard token is a possible
4731 ** lookahead.
4732 */
4733 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004734
drhb59499c2002-02-23 18:45:13 +00004735
4736 /* Combine matching REDUCE actions into a single default */
4737 for(ap=stp->ap; ap; ap=ap->next){
4738 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4739 }
drh75897232000-05-29 14:26:00 +00004740 assert( ap );
4741 ap->sp = Symbol_new("{default}");
4742 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004743 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004744 }
4745 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004746
4747 for(ap=stp->ap; ap; ap=ap->next){
4748 if( ap->type==SHIFT ) break;
4749 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4750 }
4751 if( ap==0 ){
4752 stp->autoReduce = 1;
4753 stp->pDfltReduce = rbest;
4754 }
4755 }
4756
4757 /* Make a second pass over all states and actions. Convert
4758 ** every action that is a SHIFT to an autoReduce state into
4759 ** a SHIFTREDUCE action.
4760 */
4761 for(i=0; i<lemp->nstate; i++){
4762 stp = lemp->sorted[i];
4763 for(ap=stp->ap; ap; ap=ap->next){
4764 struct state *pNextState;
4765 if( ap->type!=SHIFT ) continue;
4766 pNextState = ap->x.stp;
4767 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4768 ap->type = SHIFTREDUCE;
4769 ap->x.rp = pNextState->pDfltReduce;
4770 }
4771 }
drh75897232000-05-29 14:26:00 +00004772 }
drhc173ad82016-05-23 16:15:02 +00004773
4774 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4775 ** (meaning that the SHIFTREDUCE will land back in the state where it
4776 ** started) and if there is no C-code associated with the reduce action,
4777 ** then we can go ahead and convert the action to be the same as the
4778 ** action for the RHS of the rule.
4779 */
4780 for(i=0; i<lemp->nstate; i++){
4781 stp = lemp->sorted[i];
4782 for(ap=stp->ap; ap; ap=nextap){
4783 nextap = ap->next;
4784 if( ap->type!=SHIFTREDUCE ) continue;
4785 rp = ap->x.rp;
4786 if( rp->noCode==0 ) continue;
4787 if( rp->nrhs!=1 ) continue;
4788#if 1
4789 /* Only apply this optimization to non-terminals. It would be OK to
4790 ** apply it to terminal symbols too, but that makes the parser tables
4791 ** larger. */
4792 if( ap->sp->index<lemp->nterminal ) continue;
4793#endif
4794 /* If we reach this point, it means the optimization can be applied */
4795 nextap = ap;
4796 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4797 assert( ap2!=0 );
4798 ap->spOpt = ap2->sp;
4799 ap->type = ap2->type;
4800 ap->x = ap2->x;
4801 }
4802 }
drh75897232000-05-29 14:26:00 +00004803}
drhb59499c2002-02-23 18:45:13 +00004804
drhada354d2005-11-05 15:03:59 +00004805
4806/*
4807** Compare two states for sorting purposes. The smaller state is the
4808** one with the most non-terminal actions. If they have the same number
4809** of non-terminal actions, then the smaller is the one with the most
4810** token actions.
4811*/
4812static int stateResortCompare(const void *a, const void *b){
4813 const struct state *pA = *(const struct state**)a;
4814 const struct state *pB = *(const struct state**)b;
4815 int n;
4816
4817 n = pB->nNtAct - pA->nNtAct;
4818 if( n==0 ){
4819 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004820 if( n==0 ){
4821 n = pB->statenum - pA->statenum;
4822 }
drhada354d2005-11-05 15:03:59 +00004823 }
drhe594bc32009-11-03 13:02:25 +00004824 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004825 return n;
4826}
4827
4828
4829/*
4830** Renumber and resort states so that states with fewer choices
4831** occur at the end. Except, keep state 0 as the first state.
4832*/
icculus9e44cf12010-02-14 17:14:22 +00004833void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004834{
4835 int i;
4836 struct state *stp;
4837 struct action *ap;
4838
4839 for(i=0; i<lemp->nstate; i++){
4840 stp = lemp->sorted[i];
4841 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00004842 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004843 stp->iTknOfst = NO_OFFSET;
4844 stp->iNtOfst = NO_OFFSET;
4845 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004846 int iAction = compute_action(lemp,ap);
4847 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004848 if( ap->sp->index<lemp->nterminal ){
4849 stp->nTknAct++;
4850 }else if( ap->sp->index<lemp->nsymbol ){
4851 stp->nNtAct++;
4852 }else{
drh3bd48ab2015-09-07 18:23:37 +00004853 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00004854 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00004855 }
4856 }
4857 }
4858 }
4859 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4860 stateResortCompare);
4861 for(i=0; i<lemp->nstate; i++){
4862 lemp->sorted[i]->statenum = i;
4863 }
drh3bd48ab2015-09-07 18:23:37 +00004864 lemp->nxstate = lemp->nstate;
4865 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4866 lemp->nxstate--;
4867 }
drhada354d2005-11-05 15:03:59 +00004868}
4869
4870
drh75897232000-05-29 14:26:00 +00004871/***************** From the file "set.c" ************************************/
4872/*
4873** Set manipulation routines for the LEMON parser generator.
4874*/
4875
4876static int size = 0;
4877
4878/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004879void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004880{
4881 size = n+1;
4882}
4883
4884/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00004885char *SetNew(void){
drh75897232000-05-29 14:26:00 +00004886 char *s;
drh9892c5d2007-12-21 00:02:11 +00004887 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004888 if( s==0 ){
4889 extern void memory_error();
4890 memory_error();
4891 }
drh75897232000-05-29 14:26:00 +00004892 return s;
4893}
4894
4895/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004896void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004897{
4898 free(s);
4899}
4900
4901/* Add a new element to the set. Return TRUE if the element was added
4902** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004903int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004904{
4905 int rv;
drh9892c5d2007-12-21 00:02:11 +00004906 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004907 rv = s[e];
4908 s[e] = 1;
4909 return !rv;
4910}
4911
4912/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004913int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004914{
4915 int i, progress;
4916 progress = 0;
4917 for(i=0; i<size; i++){
4918 if( s2[i]==0 ) continue;
4919 if( s1[i]==0 ){
4920 progress = 1;
4921 s1[i] = 1;
4922 }
4923 }
4924 return progress;
4925}
4926/********************** From the file "table.c" ****************************/
4927/*
4928** All code in this file has been automatically generated
4929** from a specification in the file
4930** "table.q"
4931** by the associative array code building program "aagen".
4932** Do not edit this file! Instead, edit the specification
4933** file, then rerun aagen.
4934*/
4935/*
4936** Code for processing tables in the LEMON parser generator.
4937*/
4938
drh01f75f22013-10-02 20:46:30 +00004939PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004940{
drh01f75f22013-10-02 20:46:30 +00004941 unsigned h = 0;
4942 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004943 return h;
4944}
4945
4946/* Works like strdup, sort of. Save a string in malloced memory, but
4947** keep strings in a table so that the same string is not in more
4948** than one place.
4949*/
icculus9e44cf12010-02-14 17:14:22 +00004950const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004951{
icculus9e44cf12010-02-14 17:14:22 +00004952 const char *z;
4953 char *cpy;
drh75897232000-05-29 14:26:00 +00004954
drh916f75f2006-07-17 00:19:39 +00004955 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004956 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004957 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004958 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004959 z = cpy;
drh75897232000-05-29 14:26:00 +00004960 Strsafe_insert(z);
4961 }
4962 MemoryCheck(z);
4963 return z;
4964}
4965
4966/* There is one instance of the following structure for each
4967** associative array of type "x1".
4968*/
4969struct s_x1 {
4970 int size; /* The number of available slots. */
4971 /* Must be a power of 2 greater than or */
4972 /* equal to 1 */
4973 int count; /* Number of currently slots filled */
4974 struct s_x1node *tbl; /* The data stored here */
4975 struct s_x1node **ht; /* Hash table for lookups */
4976};
4977
4978/* There is one instance of this structure for every data element
4979** in an associative array of type "x1".
4980*/
4981typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004982 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004983 struct s_x1node *next; /* Next entry with the same hash */
4984 struct s_x1node **from; /* Previous link */
4985} x1node;
4986
4987/* There is only one instance of the array, which is the following */
4988static struct s_x1 *x1a;
4989
4990/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00004991void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00004992 if( x1a ) return;
4993 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4994 if( x1a ){
4995 x1a->size = 1024;
4996 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004997 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004998 if( x1a->tbl==0 ){
4999 free(x1a);
5000 x1a = 0;
5001 }else{
5002 int i;
5003 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5004 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5005 }
5006 }
5007}
5008/* Insert a new record into the array. Return TRUE if successful.
5009** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005010int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00005011{
5012 x1node *np;
drh01f75f22013-10-02 20:46:30 +00005013 unsigned h;
5014 unsigned ph;
drh75897232000-05-29 14:26:00 +00005015
5016 if( x1a==0 ) return 0;
5017 ph = strhash(data);
5018 h = ph & (x1a->size-1);
5019 np = x1a->ht[h];
5020 while( np ){
5021 if( strcmp(np->data,data)==0 ){
5022 /* An existing entry with the same key is found. */
5023 /* Fail because overwrite is not allows. */
5024 return 0;
5025 }
5026 np = np->next;
5027 }
5028 if( x1a->count>=x1a->size ){
5029 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005030 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005031 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00005032 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00005033 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00005034 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005035 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005036 array.ht = (x1node**)&(array.tbl[arrSize]);
5037 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005038 for(i=0; i<x1a->count; i++){
5039 x1node *oldnp, *newnp;
5040 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005041 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005042 newnp = &(array.tbl[i]);
5043 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5044 newnp->next = array.ht[h];
5045 newnp->data = oldnp->data;
5046 newnp->from = &(array.ht[h]);
5047 array.ht[h] = newnp;
5048 }
5049 free(x1a->tbl);
5050 *x1a = array;
5051 }
5052 /* Insert the new data */
5053 h = ph & (x1a->size-1);
5054 np = &(x1a->tbl[x1a->count++]);
5055 np->data = data;
5056 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5057 np->next = x1a->ht[h];
5058 x1a->ht[h] = np;
5059 np->from = &(x1a->ht[h]);
5060 return 1;
5061}
5062
5063/* Return a pointer to data assigned to the given key. Return NULL
5064** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005065const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00005066{
drh01f75f22013-10-02 20:46:30 +00005067 unsigned h;
drh75897232000-05-29 14:26:00 +00005068 x1node *np;
5069
5070 if( x1a==0 ) return 0;
5071 h = strhash(key) & (x1a->size-1);
5072 np = x1a->ht[h];
5073 while( np ){
5074 if( strcmp(np->data,key)==0 ) break;
5075 np = np->next;
5076 }
5077 return np ? np->data : 0;
5078}
5079
5080/* Return a pointer to the (terminal or nonterminal) symbol "x".
5081** Create a new symbol if this is the first time "x" has been seen.
5082*/
icculus9e44cf12010-02-14 17:14:22 +00005083struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00005084{
5085 struct symbol *sp;
5086
5087 sp = Symbol_find(x);
5088 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00005089 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00005090 MemoryCheck(sp);
5091 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00005092 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00005093 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00005094 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00005095 sp->prec = -1;
5096 sp->assoc = UNK;
5097 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005098 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005099 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005100 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005101 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005102 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005103 Symbol_insert(sp,sp->name);
5104 }
drhc4dd3fd2008-01-22 01:48:05 +00005105 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005106 return sp;
5107}
5108
drh61f92cd2014-01-11 03:06:18 +00005109/* Compare two symbols for sorting purposes. Return negative,
5110** zero, or positive if a is less then, equal to, or greater
5111** than b.
drh60d31652004-02-22 00:08:04 +00005112**
5113** Symbols that begin with upper case letters (terminals or tokens)
5114** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005115** (non-terminals). And MULTITERMINAL symbols (created using the
5116** %token_class directive) must sort at the very end. Other than
5117** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005118**
5119** We find experimentally that leaving the symbols in their original
5120** order (the order they appeared in the grammar file) gives the
5121** smallest parser tables in SQLite.
5122*/
icculus9e44cf12010-02-14 17:14:22 +00005123int Symbolcmpp(const void *_a, const void *_b)
5124{
drh61f92cd2014-01-11 03:06:18 +00005125 const struct symbol *a = *(const struct symbol **) _a;
5126 const struct symbol *b = *(const struct symbol **) _b;
5127 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5128 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5129 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005130}
5131
5132/* There is one instance of the following structure for each
5133** associative array of type "x2".
5134*/
5135struct s_x2 {
5136 int size; /* The number of available slots. */
5137 /* Must be a power of 2 greater than or */
5138 /* equal to 1 */
5139 int count; /* Number of currently slots filled */
5140 struct s_x2node *tbl; /* The data stored here */
5141 struct s_x2node **ht; /* Hash table for lookups */
5142};
5143
5144/* There is one instance of this structure for every data element
5145** in an associative array of type "x2".
5146*/
5147typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005148 struct symbol *data; /* The data */
5149 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005150 struct s_x2node *next; /* Next entry with the same hash */
5151 struct s_x2node **from; /* Previous link */
5152} x2node;
5153
5154/* There is only one instance of the array, which is the following */
5155static struct s_x2 *x2a;
5156
5157/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005158void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005159 if( x2a ) return;
5160 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5161 if( x2a ){
5162 x2a->size = 128;
5163 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005164 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005165 if( x2a->tbl==0 ){
5166 free(x2a);
5167 x2a = 0;
5168 }else{
5169 int i;
5170 x2a->ht = (x2node**)&(x2a->tbl[128]);
5171 for(i=0; i<128; i++) x2a->ht[i] = 0;
5172 }
5173 }
5174}
5175/* Insert a new record into the array. Return TRUE if successful.
5176** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005177int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005178{
5179 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005180 unsigned h;
5181 unsigned ph;
drh75897232000-05-29 14:26:00 +00005182
5183 if( x2a==0 ) return 0;
5184 ph = strhash(key);
5185 h = ph & (x2a->size-1);
5186 np = x2a->ht[h];
5187 while( np ){
5188 if( strcmp(np->key,key)==0 ){
5189 /* An existing entry with the same key is found. */
5190 /* Fail because overwrite is not allows. */
5191 return 0;
5192 }
5193 np = np->next;
5194 }
5195 if( x2a->count>=x2a->size ){
5196 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005197 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005198 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005199 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005200 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005201 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005202 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005203 array.ht = (x2node**)&(array.tbl[arrSize]);
5204 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005205 for(i=0; i<x2a->count; i++){
5206 x2node *oldnp, *newnp;
5207 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005208 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005209 newnp = &(array.tbl[i]);
5210 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5211 newnp->next = array.ht[h];
5212 newnp->key = oldnp->key;
5213 newnp->data = oldnp->data;
5214 newnp->from = &(array.ht[h]);
5215 array.ht[h] = newnp;
5216 }
5217 free(x2a->tbl);
5218 *x2a = array;
5219 }
5220 /* Insert the new data */
5221 h = ph & (x2a->size-1);
5222 np = &(x2a->tbl[x2a->count++]);
5223 np->key = key;
5224 np->data = data;
5225 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5226 np->next = x2a->ht[h];
5227 x2a->ht[h] = np;
5228 np->from = &(x2a->ht[h]);
5229 return 1;
5230}
5231
5232/* Return a pointer to data assigned to the given key. Return NULL
5233** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005234struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005235{
drh01f75f22013-10-02 20:46:30 +00005236 unsigned h;
drh75897232000-05-29 14:26:00 +00005237 x2node *np;
5238
5239 if( x2a==0 ) return 0;
5240 h = strhash(key) & (x2a->size-1);
5241 np = x2a->ht[h];
5242 while( np ){
5243 if( strcmp(np->key,key)==0 ) break;
5244 np = np->next;
5245 }
5246 return np ? np->data : 0;
5247}
5248
5249/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005250struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005251{
5252 struct symbol *data;
5253 if( x2a && n>0 && n<=x2a->count ){
5254 data = x2a->tbl[n-1].data;
5255 }else{
5256 data = 0;
5257 }
5258 return data;
5259}
5260
5261/* Return the size of the array */
5262int Symbol_count()
5263{
5264 return x2a ? x2a->count : 0;
5265}
5266
5267/* Return an array of pointers to all data in the table.
5268** The array is obtained from malloc. Return NULL if memory allocation
5269** problems, or if the array is empty. */
5270struct symbol **Symbol_arrayof()
5271{
5272 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005273 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005274 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005275 arrSize = x2a->count;
5276 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005277 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005278 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005279 }
5280 return array;
5281}
5282
5283/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005284int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005285{
icculus9e44cf12010-02-14 17:14:22 +00005286 const struct config *a = (struct config *) _a;
5287 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005288 int x;
5289 x = a->rp->index - b->rp->index;
5290 if( x==0 ) x = a->dot - b->dot;
5291 return x;
5292}
5293
5294/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005295PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005296{
5297 int rc;
5298 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5299 rc = a->rp->index - b->rp->index;
5300 if( rc==0 ) rc = a->dot - b->dot;
5301 }
5302 if( rc==0 ){
5303 if( a ) rc = 1;
5304 if( b ) rc = -1;
5305 }
5306 return rc;
5307}
5308
5309/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005310PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005311{
drh01f75f22013-10-02 20:46:30 +00005312 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005313 while( a ){
5314 h = h*571 + a->rp->index*37 + a->dot;
5315 a = a->bp;
5316 }
5317 return h;
5318}
5319
5320/* Allocate a new state structure */
5321struct state *State_new()
5322{
icculus9e44cf12010-02-14 17:14:22 +00005323 struct state *newstate;
5324 newstate = (struct state *)calloc(1, sizeof(struct state) );
5325 MemoryCheck(newstate);
5326 return newstate;
drh75897232000-05-29 14:26:00 +00005327}
5328
5329/* There is one instance of the following structure for each
5330** associative array of type "x3".
5331*/
5332struct s_x3 {
5333 int size; /* The number of available slots. */
5334 /* Must be a power of 2 greater than or */
5335 /* equal to 1 */
5336 int count; /* Number of currently slots filled */
5337 struct s_x3node *tbl; /* The data stored here */
5338 struct s_x3node **ht; /* Hash table for lookups */
5339};
5340
5341/* There is one instance of this structure for every data element
5342** in an associative array of type "x3".
5343*/
5344typedef struct s_x3node {
5345 struct state *data; /* The data */
5346 struct config *key; /* The key */
5347 struct s_x3node *next; /* Next entry with the same hash */
5348 struct s_x3node **from; /* Previous link */
5349} x3node;
5350
5351/* There is only one instance of the array, which is the following */
5352static struct s_x3 *x3a;
5353
5354/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005355void State_init(void){
drh75897232000-05-29 14:26:00 +00005356 if( x3a ) return;
5357 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5358 if( x3a ){
5359 x3a->size = 128;
5360 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005361 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005362 if( x3a->tbl==0 ){
5363 free(x3a);
5364 x3a = 0;
5365 }else{
5366 int i;
5367 x3a->ht = (x3node**)&(x3a->tbl[128]);
5368 for(i=0; i<128; i++) x3a->ht[i] = 0;
5369 }
5370 }
5371}
5372/* Insert a new record into the array. Return TRUE if successful.
5373** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005374int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005375{
5376 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005377 unsigned h;
5378 unsigned ph;
drh75897232000-05-29 14:26:00 +00005379
5380 if( x3a==0 ) return 0;
5381 ph = statehash(key);
5382 h = ph & (x3a->size-1);
5383 np = x3a->ht[h];
5384 while( np ){
5385 if( statecmp(np->key,key)==0 ){
5386 /* An existing entry with the same key is found. */
5387 /* Fail because overwrite is not allows. */
5388 return 0;
5389 }
5390 np = np->next;
5391 }
5392 if( x3a->count>=x3a->size ){
5393 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005394 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005395 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005396 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005397 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005398 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005399 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005400 array.ht = (x3node**)&(array.tbl[arrSize]);
5401 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005402 for(i=0; i<x3a->count; i++){
5403 x3node *oldnp, *newnp;
5404 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005405 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005406 newnp = &(array.tbl[i]);
5407 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5408 newnp->next = array.ht[h];
5409 newnp->key = oldnp->key;
5410 newnp->data = oldnp->data;
5411 newnp->from = &(array.ht[h]);
5412 array.ht[h] = newnp;
5413 }
5414 free(x3a->tbl);
5415 *x3a = array;
5416 }
5417 /* Insert the new data */
5418 h = ph & (x3a->size-1);
5419 np = &(x3a->tbl[x3a->count++]);
5420 np->key = key;
5421 np->data = data;
5422 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5423 np->next = x3a->ht[h];
5424 x3a->ht[h] = np;
5425 np->from = &(x3a->ht[h]);
5426 return 1;
5427}
5428
5429/* Return a pointer to data assigned to the given key. Return NULL
5430** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005431struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005432{
drh01f75f22013-10-02 20:46:30 +00005433 unsigned h;
drh75897232000-05-29 14:26:00 +00005434 x3node *np;
5435
5436 if( x3a==0 ) return 0;
5437 h = statehash(key) & (x3a->size-1);
5438 np = x3a->ht[h];
5439 while( np ){
5440 if( statecmp(np->key,key)==0 ) break;
5441 np = np->next;
5442 }
5443 return np ? np->data : 0;
5444}
5445
5446/* Return an array of pointers to all data in the table.
5447** The array is obtained from malloc. Return NULL if memory allocation
5448** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005449struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005450{
5451 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005452 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005453 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005454 arrSize = x3a->count;
5455 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005456 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005457 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005458 }
5459 return array;
5460}
5461
5462/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005463PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005464{
drh01f75f22013-10-02 20:46:30 +00005465 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005466 h = h*571 + a->rp->index*37 + a->dot;
5467 return h;
5468}
5469
5470/* There is one instance of the following structure for each
5471** associative array of type "x4".
5472*/
5473struct s_x4 {
5474 int size; /* The number of available slots. */
5475 /* Must be a power of 2 greater than or */
5476 /* equal to 1 */
5477 int count; /* Number of currently slots filled */
5478 struct s_x4node *tbl; /* The data stored here */
5479 struct s_x4node **ht; /* Hash table for lookups */
5480};
5481
5482/* There is one instance of this structure for every data element
5483** in an associative array of type "x4".
5484*/
5485typedef struct s_x4node {
5486 struct config *data; /* The data */
5487 struct s_x4node *next; /* Next entry with the same hash */
5488 struct s_x4node **from; /* Previous link */
5489} x4node;
5490
5491/* There is only one instance of the array, which is the following */
5492static struct s_x4 *x4a;
5493
5494/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005495void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005496 if( x4a ) return;
5497 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5498 if( x4a ){
5499 x4a->size = 64;
5500 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005501 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005502 if( x4a->tbl==0 ){
5503 free(x4a);
5504 x4a = 0;
5505 }else{
5506 int i;
5507 x4a->ht = (x4node**)&(x4a->tbl[64]);
5508 for(i=0; i<64; i++) x4a->ht[i] = 0;
5509 }
5510 }
5511}
5512/* Insert a new record into the array. Return TRUE if successful.
5513** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005514int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005515{
5516 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005517 unsigned h;
5518 unsigned ph;
drh75897232000-05-29 14:26:00 +00005519
5520 if( x4a==0 ) return 0;
5521 ph = confighash(data);
5522 h = ph & (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 *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005526 /* An existing entry with the same key is found. */
5527 /* Fail because overwrite is not allows. */
5528 return 0;
5529 }
5530 np = np->next;
5531 }
5532 if( x4a->count>=x4a->size ){
5533 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005534 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005535 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005536 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005537 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005538 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005539 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005540 array.ht = (x4node**)&(array.tbl[arrSize]);
5541 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005542 for(i=0; i<x4a->count; i++){
5543 x4node *oldnp, *newnp;
5544 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005545 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005546 newnp = &(array.tbl[i]);
5547 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5548 newnp->next = array.ht[h];
5549 newnp->data = oldnp->data;
5550 newnp->from = &(array.ht[h]);
5551 array.ht[h] = newnp;
5552 }
5553 free(x4a->tbl);
5554 *x4a = array;
5555 }
5556 /* Insert the new data */
5557 h = ph & (x4a->size-1);
5558 np = &(x4a->tbl[x4a->count++]);
5559 np->data = data;
5560 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5561 np->next = x4a->ht[h];
5562 x4a->ht[h] = np;
5563 np->from = &(x4a->ht[h]);
5564 return 1;
5565}
5566
5567/* Return a pointer to data assigned to the given key. Return NULL
5568** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005569struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005570{
5571 int h;
5572 x4node *np;
5573
5574 if( x4a==0 ) return 0;
5575 h = confighash(key) & (x4a->size-1);
5576 np = x4a->ht[h];
5577 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005578 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005579 np = np->next;
5580 }
5581 return np ? np->data : 0;
5582}
5583
5584/* Remove all data from the table. Pass each data to the function "f"
5585** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005586void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005587{
5588 int i;
5589 if( x4a==0 || x4a->count==0 ) return;
5590 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5591 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5592 x4a->count = 0;
5593 return;
5594}