blob: eb4adbbc69b6b19b4eee6d7ec07f13e2e93e1480 [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 */
drh539e7412018-04-21 20:24:19 +0000273 int bContent; /* True if this symbol ever carries content - if
274 ** it is ever more than just syntax */
drhfd405312005-11-06 04:06:59 +0000275 /* The following fields are used by MULTITERMINALs only */
276 int nsubsym; /* Number of constituent symbols in the MULTI */
277 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000278};
279
280/* Each production rule in the grammar is stored in the following
281** structure. */
282struct rule {
283 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000284 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000285 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000286 int ruleline; /* Line number for the rule */
287 int nrhs; /* Number of RHS symbols */
288 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000289 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000290 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000291 const char *code; /* The code executed when this rule is reduced */
drh4dd0d3f2016-02-17 01:18:33 +0000292 const char *codePrefix; /* Setup code before code[] above */
293 const char *codeSuffix; /* Breakdown code after code[] above */
drh711c9812016-05-23 14:24:31 +0000294 int noCode; /* True if this rule has no associated C code */
295 int codeEmitted; /* True if the code has been emitted already */
drh75897232000-05-29 14:26:00 +0000296 struct symbol *precsym; /* Precedence symbol for this rule */
297 int index; /* An index number for this rule */
drh4ef07702016-03-16 19:45:54 +0000298 int iRule; /* Rule number as used in the generated tables */
drh75897232000-05-29 14:26:00 +0000299 Boolean canReduce; /* True if this rule is ever reduced */
drh756b41e2016-05-24 18:55:08 +0000300 Boolean doesReduce; /* Reduce actions occur after optimization */
drh75897232000-05-29 14:26:00 +0000301 struct rule *nextlhs; /* Next rule with the same LHS */
302 struct rule *next; /* Next rule in the global list */
303};
304
305/* A configuration is a production rule of the grammar together with
306** a mark (dot) showing how much of that rule has been processed so far.
307** Configurations also contain a follow-set which is a list of terminal
308** symbols which are allowed to immediately follow the end of the rule.
309** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000310enum cfgstatus {
311 COMPLETE,
312 INCOMPLETE
313};
drh75897232000-05-29 14:26:00 +0000314struct config {
315 struct rule *rp; /* The rule upon which the configuration is based */
316 int dot; /* The parse point */
317 char *fws; /* Follow-set for this configuration only */
318 struct plink *fplp; /* Follow-set forward propagation links */
319 struct plink *bplp; /* Follow-set backwards propagation links */
320 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000321 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000322 struct config *next; /* Next configuration in the state */
323 struct config *bp; /* The next basis configuration */
324};
325
icculus9e44cf12010-02-14 17:14:22 +0000326enum e_action {
327 SHIFT,
328 ACCEPT,
329 REDUCE,
330 ERROR,
331 SSCONFLICT, /* A shift/shift conflict */
332 SRCONFLICT, /* Was a reduce, but part of a conflict */
333 RRCONFLICT, /* Was a reduce, but part of a conflict */
334 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
335 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000336 NOT_USED, /* Deleted by compression */
337 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000338};
339
drh75897232000-05-29 14:26:00 +0000340/* Every shift or reduce operation is stored as one of the following */
341struct action {
342 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000343 enum e_action type;
drh75897232000-05-29 14:26:00 +0000344 union {
345 struct state *stp; /* The new state, if a shift */
346 struct rule *rp; /* The rule, if a reduce */
347 } x;
drhc173ad82016-05-23 16:15:02 +0000348 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
drh75897232000-05-29 14:26:00 +0000349 struct action *next; /* Next action for this state */
350 struct action *collide; /* Next action with the same hash */
351};
352
353/* Each state of the generated parser's finite state machine
354** is encoded as an instance of the following structure. */
355struct state {
356 struct config *bp; /* The basis configurations for this state */
357 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000358 int statenum; /* Sequential number for this state */
drh711c9812016-05-23 14:24:31 +0000359 struct action *ap; /* List of actions for this state */
drh8b582012003-10-21 13:16:03 +0000360 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
361 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000362 int iDfltReduce; /* Default action is to REDUCE by this rule */
363 struct rule *pDfltReduce;/* The default REDUCE rule. */
364 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000365};
drh8b582012003-10-21 13:16:03 +0000366#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000367
368/* A followset propagation link indicates that the contents of one
369** configuration followset should be propagated to another whenever
370** the first changes. */
371struct plink {
372 struct config *cfp; /* The configuration to which linked */
373 struct plink *next; /* The next propagate link */
374};
375
376/* The state vector for the entire parser generator is recorded as
377** follows. (LEMON uses no global variables and makes little use of
378** static variables. Fields in the following structure can be thought
379** of as begin global variables in the program.) */
380struct lemon {
381 struct state **sorted; /* Table of states sorted by state number */
382 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000383 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000384 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000385 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000386 int nrule; /* Number of rules */
387 int nsymbol; /* Number of terminal and nonterminal symbols */
388 int nterminal; /* Number of terminal symbols */
drh5c8241b2017-12-24 23:38:10 +0000389 int minShiftReduce; /* Minimum shift-reduce action value */
390 int errAction; /* Error action value */
391 int accAction; /* Accept action value */
392 int noAction; /* No-op action value */
393 int minReduce; /* Minimum reduce action */
394 int maxAction; /* Maximum action value of any kind */
drh75897232000-05-29 14:26:00 +0000395 struct symbol **symbols; /* Sorted array of pointers to symbols */
396 int errorcnt; /* Number of errors */
397 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000398 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000399 char *name; /* Name of the generated parser */
400 char *arg; /* Declaration of the 3th argument to parser */
drhfb32c442018-04-21 13:51:42 +0000401 char *ctx; /* Declaration of 2nd argument to constructor */
drh75897232000-05-29 14:26:00 +0000402 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000403 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000404 char *start; /* Name of the start symbol for the grammar */
405 char *stacksize; /* Size of the parser stack */
406 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000407 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000408 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000409 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000410 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000411 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000412 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000413 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000414 char *filename; /* Name of the input file */
415 char *outname; /* Name of the current output file */
416 char *tokenprefix; /* A prefix added to token names in the .h file */
417 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000418 int nactiontab; /* Number of entries in the yy_action[] table */
drh3a9d6c72017-12-25 04:15:38 +0000419 int nlookaheadtab; /* Number of entries in yy_lookahead[] */
drhc75e0162015-09-07 02:23:02 +0000420 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000421 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000422 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000423 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000424 char *argv0; /* Name of the program */
425};
426
427#define MemoryCheck(X) if((X)==0){ \
428 extern void memory_error(); \
429 memory_error(); \
430}
431
432/**************** From the file "table.h" *********************************/
433/*
434** All code in this file has been automatically generated
435** from a specification in the file
436** "table.q"
437** by the associative array code building program "aagen".
438** Do not edit this file! Instead, edit the specification
439** file, then rerun aagen.
440*/
441/*
442** Code for processing tables in the LEMON parser generator.
443*/
drh75897232000-05-29 14:26:00 +0000444/* Routines for handling a strings */
445
icculus9e44cf12010-02-14 17:14:22 +0000446const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000447
icculus9e44cf12010-02-14 17:14:22 +0000448void Strsafe_init(void);
449int Strsafe_insert(const char *);
450const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000451
452/* Routines for handling symbols of the grammar */
453
icculus9e44cf12010-02-14 17:14:22 +0000454struct symbol *Symbol_new(const char *);
455int Symbolcmpp(const void *, const void *);
456void Symbol_init(void);
457int Symbol_insert(struct symbol *, const char *);
458struct symbol *Symbol_find(const char *);
459struct symbol *Symbol_Nth(int);
460int Symbol_count(void);
461struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000462
463/* Routines to manage the state table */
464
icculus9e44cf12010-02-14 17:14:22 +0000465int Configcmp(const char *, const char *);
466struct state *State_new(void);
467void State_init(void);
468int State_insert(struct state *, struct config *);
469struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000470struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000471
472/* Routines used for efficiency in Configlist_add */
473
icculus9e44cf12010-02-14 17:14:22 +0000474void Configtable_init(void);
475int Configtable_insert(struct config *);
476struct config *Configtable_find(struct config *);
477void Configtable_clear(int(*)(struct config *));
478
drh75897232000-05-29 14:26:00 +0000479/****************** From the file "action.c" *******************************/
480/*
481** Routines processing parser actions in the LEMON parser generator.
482*/
483
484/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000485static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000486 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000487 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000488
489 if( freelist==0 ){
490 int i;
491 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000492 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000493 if( freelist==0 ){
494 fprintf(stderr,"Unable to allocate memory for a new parser action.");
495 exit(1);
496 }
497 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
498 freelist[amt-1].next = 0;
499 }
icculus9e44cf12010-02-14 17:14:22 +0000500 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000501 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000502 return newaction;
drh75897232000-05-29 14:26:00 +0000503}
504
drhe9278182007-07-18 18:16:29 +0000505/* Compare two actions for sorting purposes. Return negative, zero, or
506** positive if the first action is less than, equal to, or greater than
507** the first
508*/
509static int actioncmp(
510 struct action *ap1,
511 struct action *ap2
512){
drh75897232000-05-29 14:26:00 +0000513 int rc;
514 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000515 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000516 rc = (int)ap1->type - (int)ap2->type;
517 }
drh3bd48ab2015-09-07 18:23:37 +0000518 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000519 rc = ap1->x.rp->index - ap2->x.rp->index;
520 }
drhe594bc32009-11-03 13:02:25 +0000521 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000522 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000523 }
drh75897232000-05-29 14:26:00 +0000524 return rc;
525}
526
527/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000528static struct action *Action_sort(
529 struct action *ap
530){
531 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
532 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000533 return ap;
534}
535
icculus9e44cf12010-02-14 17:14:22 +0000536void Action_add(
537 struct action **app,
538 enum e_action type,
539 struct symbol *sp,
540 char *arg
541){
542 struct action *newaction;
543 newaction = Action_new();
544 newaction->next = *app;
545 *app = newaction;
546 newaction->type = type;
547 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000548 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000549 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000550 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000551 }else{
icculus9e44cf12010-02-14 17:14:22 +0000552 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000553 }
554}
drh8b582012003-10-21 13:16:03 +0000555/********************** New code to implement the "acttab" module ***********/
556/*
557** This module implements routines use to construct the yy_action[] table.
558*/
559
560/*
561** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000562** the following structure.
563**
564** The yy_action table maps the pair (state_number, lookahead) into an
565** action_number. The table is an array of integers pairs. The state_number
566** determines an initial offset into the yy_action array. The lookahead
567** value is then added to this initial offset to get an index X into the
568** yy_action array. If the aAction[X].lookahead equals the value of the
569** of the lookahead input, then the value of the action_number output is
570** aAction[X].action. If the lookaheads do not match then the
571** default action for the state_number is returned.
572**
573** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000574** into aLookahead[] using multiple calls to acttab_action(). Then the
575** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000576** array with a single call to acttab_insert(). The acttab_insert() call
577** also resets the aLookahead[] array in preparation for the next
578** state number.
drh8b582012003-10-21 13:16:03 +0000579*/
icculus9e44cf12010-02-14 17:14:22 +0000580struct lookahead_action {
581 int lookahead; /* Value of the lookahead token */
582 int action; /* Action to take on the given lookahead */
583};
drh8b582012003-10-21 13:16:03 +0000584typedef struct acttab acttab;
585struct acttab {
586 int nAction; /* Number of used slots in aAction[] */
587 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000588 struct lookahead_action
589 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000590 *aLookahead; /* A single new transaction set */
591 int mnLookahead; /* Minimum aLookahead[].lookahead */
592 int mnAction; /* Action associated with mnLookahead */
593 int mxLookahead; /* Maximum aLookahead[].lookahead */
594 int nLookahead; /* Used slots in aLookahead[] */
595 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
drh3a9d6c72017-12-25 04:15:38 +0000596 int nterminal; /* Number of terminal symbols */
597 int nsymbol; /* total number of symbols */
drh8b582012003-10-21 13:16:03 +0000598};
599
600/* Return the number of entries in the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +0000601#define acttab_lookahead_size(X) ((X)->nAction)
drh8b582012003-10-21 13:16:03 +0000602
603/* The value for the N-th entry in yy_action */
604#define acttab_yyaction(X,N) ((X)->aAction[N].action)
605
606/* The value for the N-th entry in yy_lookahead */
607#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
608
609/* Free all memory associated with the given acttab */
610void acttab_free(acttab *p){
611 free( p->aAction );
612 free( p->aLookahead );
613 free( p );
614}
615
616/* Allocate a new acttab structure */
drh3a9d6c72017-12-25 04:15:38 +0000617acttab *acttab_alloc(int nsymbol, int nterminal){
icculus9e44cf12010-02-14 17:14:22 +0000618 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000619 if( p==0 ){
620 fprintf(stderr,"Unable to allocate memory for a new acttab.");
621 exit(1);
622 }
623 memset(p, 0, sizeof(*p));
drh3a9d6c72017-12-25 04:15:38 +0000624 p->nsymbol = nsymbol;
625 p->nterminal = nterminal;
drh8b582012003-10-21 13:16:03 +0000626 return p;
627}
628
drh06f60d82017-04-14 19:46:12 +0000629/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000630**
631** This routine is called once for each lookahead for a particular
632** state.
drh8b582012003-10-21 13:16:03 +0000633*/
634void acttab_action(acttab *p, int lookahead, int action){
635 if( p->nLookahead>=p->nLookaheadAlloc ){
636 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000637 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000638 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
639 if( p->aLookahead==0 ){
640 fprintf(stderr,"malloc failed\n");
641 exit(1);
642 }
643 }
644 if( p->nLookahead==0 ){
645 p->mxLookahead = lookahead;
646 p->mnLookahead = lookahead;
647 p->mnAction = action;
648 }else{
649 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
650 if( p->mnLookahead>lookahead ){
651 p->mnLookahead = lookahead;
652 p->mnAction = action;
653 }
654 }
655 p->aLookahead[p->nLookahead].lookahead = lookahead;
656 p->aLookahead[p->nLookahead].action = action;
657 p->nLookahead++;
658}
659
660/*
661** Add the transaction set built up with prior calls to acttab_action()
662** into the current action table. Then reset the transaction set back
663** to an empty set in preparation for a new round of acttab_action() calls.
664**
665** Return the offset into the action table of the new transaction.
drh3a9d6c72017-12-25 04:15:38 +0000666**
667** If the makeItSafe parameter is true, then the offset is chosen so that
668** it is impossible to overread the yy_lookaside[] table regardless of
669** the lookaside token. This is done for the terminal symbols, as they
670** come from external inputs and can contain syntax errors. When makeItSafe
671** is false, there is more flexibility in selecting offsets, resulting in
672** a smaller table. For non-terminal symbols, which are never syntax errors,
673** makeItSafe can be false.
drh8b582012003-10-21 13:16:03 +0000674*/
drh3a9d6c72017-12-25 04:15:38 +0000675int acttab_insert(acttab *p, int makeItSafe){
676 int i, j, k, n, end;
drh8b582012003-10-21 13:16:03 +0000677 assert( p->nLookahead>0 );
678
679 /* Make sure we have enough space to hold the expanded action table
680 ** in the worst case. The worst case occurs if the transaction set
681 ** must be appended to the current action table
682 */
drh3a9d6c72017-12-25 04:15:38 +0000683 n = p->nsymbol + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000684 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000685 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000686 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000687 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000688 sizeof(p->aAction[0])*p->nActionAlloc);
689 if( p->aAction==0 ){
690 fprintf(stderr,"malloc failed\n");
691 exit(1);
692 }
drhfdbf9282003-10-21 16:34:41 +0000693 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000694 p->aAction[i].lookahead = -1;
695 p->aAction[i].action = -1;
696 }
697 }
698
drh06f60d82017-04-14 19:46:12 +0000699 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000700 ** duplicate of the current transaction set. Fall out of the loop
701 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000702 **
703 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
704 */
drh3a9d6c72017-12-25 04:15:38 +0000705 end = makeItSafe ? p->mnLookahead : 0;
706 for(i=p->nAction-1; i>=end; i--){
drhf16371d2009-11-03 19:18:31 +0000707 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000708 /* All lookaheads and actions in the aLookahead[] transaction
709 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000710 if( p->aAction[i].action!=p->mnAction ) continue;
711 for(j=0; j<p->nLookahead; j++){
712 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
713 if( k<0 || k>=p->nAction ) break;
714 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
715 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
716 }
717 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000718
719 /* No possible lookahead value that is not in the aLookahead[]
720 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000721 n = 0;
722 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000723 if( p->aAction[j].lookahead<0 ) continue;
724 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000725 }
drhfdbf9282003-10-21 16:34:41 +0000726 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000727 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000728 }
drh8b582012003-10-21 13:16:03 +0000729 }
730 }
drh8dc3e8f2010-01-07 03:53:03 +0000731
732 /* If no existing offsets exactly match the current transaction, find an
733 ** an empty offset in the aAction[] table in which we can add the
734 ** aLookahead[] transaction.
735 */
drh3a9d6c72017-12-25 04:15:38 +0000736 if( i<end ){
drh8dc3e8f2010-01-07 03:53:03 +0000737 /* Look for holes in the aAction[] table that fit the current
738 ** aLookahead[] transaction. Leave i set to the offset of the hole.
739 ** If no holes are found, i is left at p->nAction, which means the
740 ** transaction will be appended. */
drh3a9d6c72017-12-25 04:15:38 +0000741 i = makeItSafe ? p->mnLookahead : 0;
742 for(; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000743 if( p->aAction[i].lookahead<0 ){
744 for(j=0; j<p->nLookahead; j++){
745 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
746 if( k<0 ) break;
747 if( p->aAction[k].lookahead>=0 ) break;
748 }
749 if( j<p->nLookahead ) continue;
750 for(j=0; j<p->nAction; j++){
751 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
752 }
753 if( j==p->nAction ){
754 break; /* Fits in empty slots */
755 }
756 }
757 }
758 }
drh8b582012003-10-21 13:16:03 +0000759 /* Insert transaction set at index i. */
drh3a9d6c72017-12-25 04:15:38 +0000760#if 0
761 printf("Acttab:");
762 for(j=0; j<p->nLookahead; j++){
763 printf(" %d", p->aLookahead[j].lookahead);
764 }
765 printf(" inserted at %d\n", i);
766#endif
drh8b582012003-10-21 13:16:03 +0000767 for(j=0; j<p->nLookahead; j++){
768 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
769 p->aAction[k] = p->aLookahead[j];
770 if( k>=p->nAction ) p->nAction = k+1;
771 }
drh4396c612017-12-27 15:21:16 +0000772 if( makeItSafe && i+p->nterminal>=p->nAction ) p->nAction = i+p->nterminal+1;
drh8b582012003-10-21 13:16:03 +0000773 p->nLookahead = 0;
774
775 /* Return the offset that is added to the lookahead in order to get the
776 ** index into yy_action of the action */
777 return i - p->mnLookahead;
778}
779
drh3a9d6c72017-12-25 04:15:38 +0000780/*
781** Return the size of the action table without the trailing syntax error
782** entries.
783*/
784int acttab_action_size(acttab *p){
785 int n = p->nAction;
786 while( n>0 && p->aAction[n-1].lookahead<0 ){ n--; }
787 return n;
788}
789
drh75897232000-05-29 14:26:00 +0000790/********************** From the file "build.c" *****************************/
791/*
792** Routines to construction the finite state machine for the LEMON
793** parser generator.
794*/
795
796/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000797**
drh75897232000-05-29 14:26:00 +0000798** Those rules which have a precedence symbol coded in the input
799** grammar using the "[symbol]" construct will already have the
800** rp->precsym field filled. Other rules take as their precedence
801** symbol the first RHS symbol with a defined precedence. If there
802** are not RHS symbols with a defined precedence, the precedence
803** symbol field is left blank.
804*/
icculus9e44cf12010-02-14 17:14:22 +0000805void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000806{
807 struct rule *rp;
808 for(rp=xp->rule; rp; rp=rp->next){
809 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000810 int i, j;
811 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
812 struct symbol *sp = rp->rhs[i];
813 if( sp->type==MULTITERMINAL ){
814 for(j=0; j<sp->nsubsym; j++){
815 if( sp->subsym[j]->prec>=0 ){
816 rp->precsym = sp->subsym[j];
817 break;
818 }
819 }
820 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000821 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000822 }
drh75897232000-05-29 14:26:00 +0000823 }
824 }
825 }
826 return;
827}
828
829/* Find all nonterminals which will generate the empty string.
830** Then go back and compute the first sets of every nonterminal.
831** The first set is the set of all terminal symbols which can begin
832** a string generated by that nonterminal.
833*/
icculus9e44cf12010-02-14 17:14:22 +0000834void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000835{
drhfd405312005-11-06 04:06:59 +0000836 int i, j;
drh75897232000-05-29 14:26:00 +0000837 struct rule *rp;
838 int progress;
839
840 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000841 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000842 }
843 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
844 lemp->symbols[i]->firstset = SetNew();
845 }
846
847 /* First compute all lambdas */
848 do{
849 progress = 0;
850 for(rp=lemp->rule; rp; rp=rp->next){
851 if( rp->lhs->lambda ) continue;
852 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000853 struct symbol *sp = rp->rhs[i];
854 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
855 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000856 }
857 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000858 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000859 progress = 1;
860 }
861 }
862 }while( progress );
863
864 /* Now compute all first sets */
865 do{
866 struct symbol *s1, *s2;
867 progress = 0;
868 for(rp=lemp->rule; rp; rp=rp->next){
869 s1 = rp->lhs;
870 for(i=0; i<rp->nrhs; i++){
871 s2 = rp->rhs[i];
872 if( s2->type==TERMINAL ){
873 progress += SetAdd(s1->firstset,s2->index);
874 break;
drhfd405312005-11-06 04:06:59 +0000875 }else if( s2->type==MULTITERMINAL ){
876 for(j=0; j<s2->nsubsym; j++){
877 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
878 }
879 break;
drhf2f105d2012-08-20 15:53:54 +0000880 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000881 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000882 }else{
drh75897232000-05-29 14:26:00 +0000883 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000884 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000885 }
drh75897232000-05-29 14:26:00 +0000886 }
887 }
888 }while( progress );
889 return;
890}
891
892/* Compute all LR(0) states for the grammar. Links
893** are added to between some states so that the LR(1) follow sets
894** can be computed later.
895*/
icculus9e44cf12010-02-14 17:14:22 +0000896PRIVATE struct state *getstate(struct lemon *); /* forward reference */
897void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000898{
899 struct symbol *sp;
900 struct rule *rp;
901
902 Configlist_init();
903
904 /* Find the start symbol */
905 if( lemp->start ){
906 sp = Symbol_find(lemp->start);
907 if( sp==0 ){
908 ErrorMsg(lemp->filename,0,
909"The specified start symbol \"%s\" is not \
910in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000911symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000912 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000913 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000914 }
915 }else{
drh4ef07702016-03-16 19:45:54 +0000916 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000917 }
918
919 /* Make sure the start symbol doesn't occur on the right-hand side of
920 ** any rule. Report an error if it does. (YACC would generate a new
921 ** start symbol in this case.) */
922 for(rp=lemp->rule; rp; rp=rp->next){
923 int i;
924 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000925 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000926 ErrorMsg(lemp->filename,0,
927"The start symbol \"%s\" occurs on the \
928right-hand side of a rule. This will result in a parser which \
929does not work properly.",sp->name);
930 lemp->errorcnt++;
931 }
932 }
933 }
934
935 /* The basis configuration set for the first state
936 ** is all rules which have the start symbol as their
937 ** left-hand side */
938 for(rp=sp->rule; rp; rp=rp->nextlhs){
939 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000940 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000941 newcfp = Configlist_addbasis(rp,0);
942 SetAdd(newcfp->fws,0);
943 }
944
945 /* Compute the first state. All other states will be
946 ** computed automatically during the computation of the first one.
947 ** The returned pointer to the first state is not used. */
948 (void)getstate(lemp);
949 return;
950}
951
952/* Return a pointer to a state which is described by the configuration
953** list which has been built from calls to Configlist_add.
954*/
icculus9e44cf12010-02-14 17:14:22 +0000955PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
956PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000957{
958 struct config *cfp, *bp;
959 struct state *stp;
960
961 /* Extract the sorted basis of the new state. The basis was constructed
962 ** by prior calls to "Configlist_addbasis()". */
963 Configlist_sortbasis();
964 bp = Configlist_basis();
965
966 /* Get a state with the same basis */
967 stp = State_find(bp);
968 if( stp ){
969 /* A state with the same basis already exists! Copy all the follow-set
970 ** propagation links from the state under construction into the
971 ** preexisting state, then return a pointer to the preexisting state */
972 struct config *x, *y;
973 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
974 Plink_copy(&y->bplp,x->bplp);
975 Plink_delete(x->fplp);
976 x->fplp = x->bplp = 0;
977 }
978 cfp = Configlist_return();
979 Configlist_eat(cfp);
980 }else{
981 /* This really is a new state. Construct all the details */
982 Configlist_closure(lemp); /* Compute the configuration closure */
983 Configlist_sort(); /* Sort the configuration closure */
984 cfp = Configlist_return(); /* Get a pointer to the config list */
985 stp = State_new(); /* A new state structure */
986 MemoryCheck(stp);
987 stp->bp = bp; /* Remember the configuration basis */
988 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000989 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000990 stp->ap = 0; /* No actions, yet. */
991 State_insert(stp,stp->bp); /* Add to the state table */
992 buildshifts(lemp,stp); /* Recursively compute successor states */
993 }
994 return stp;
995}
996
drhfd405312005-11-06 04:06:59 +0000997/*
998** Return true if two symbols are the same.
999*/
icculus9e44cf12010-02-14 17:14:22 +00001000int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +00001001{
1002 int i;
1003 if( a==b ) return 1;
1004 if( a->type!=MULTITERMINAL ) return 0;
1005 if( b->type!=MULTITERMINAL ) return 0;
1006 if( a->nsubsym!=b->nsubsym ) return 0;
1007 for(i=0; i<a->nsubsym; i++){
1008 if( a->subsym[i]!=b->subsym[i] ) return 0;
1009 }
1010 return 1;
1011}
1012
drh75897232000-05-29 14:26:00 +00001013/* Construct all successor states to the given state. A "successor"
1014** state is any state which can be reached by a shift action.
1015*/
icculus9e44cf12010-02-14 17:14:22 +00001016PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +00001017{
1018 struct config *cfp; /* For looping thru the config closure of "stp" */
1019 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +00001020 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +00001021 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
1022 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
1023 struct state *newstp; /* A pointer to a successor state */
1024
1025 /* Each configuration becomes complete after it contibutes to a successor
1026 ** state. Initially, all configurations are incomplete */
1027 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
1028
1029 /* Loop through all configurations of the state "stp" */
1030 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1031 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
1032 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
1033 Configlist_reset(); /* Reset the new config set */
1034 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
1035
1036 /* For every configuration in the state "stp" which has the symbol "sp"
1037 ** following its dot, add the same configuration to the basis set under
1038 ** construction but with the dot shifted one symbol to the right. */
1039 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1040 if( bcfp->status==COMPLETE ) continue; /* Already used */
1041 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1042 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001043 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001044 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001045 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1046 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001047 }
1048
1049 /* Get a pointer to the state described by the basis configuration set
1050 ** constructed in the preceding loop */
1051 newstp = getstate(lemp);
1052
1053 /* The state "newstp" is reached from the state "stp" by a shift action
1054 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001055 if( sp->type==MULTITERMINAL ){
1056 int i;
1057 for(i=0; i<sp->nsubsym; i++){
1058 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1059 }
1060 }else{
1061 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1062 }
drh75897232000-05-29 14:26:00 +00001063 }
1064}
1065
1066/*
1067** Construct the propagation links
1068*/
icculus9e44cf12010-02-14 17:14:22 +00001069void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001070{
1071 int i;
1072 struct config *cfp, *other;
1073 struct state *stp;
1074 struct plink *plp;
1075
1076 /* Housekeeping detail:
1077 ** Add to every propagate link a pointer back to the state to
1078 ** which the link is attached. */
1079 for(i=0; i<lemp->nstate; i++){
1080 stp = lemp->sorted[i];
1081 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1082 cfp->stp = stp;
1083 }
1084 }
1085
1086 /* Convert all backlinks into forward links. Only the forward
1087 ** links are used in the follow-set computation. */
1088 for(i=0; i<lemp->nstate; i++){
1089 stp = lemp->sorted[i];
1090 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1091 for(plp=cfp->bplp; plp; plp=plp->next){
1092 other = plp->cfp;
1093 Plink_add(&other->fplp,cfp);
1094 }
1095 }
1096 }
1097}
1098
1099/* Compute all followsets.
1100**
1101** A followset is the set of all symbols which can come immediately
1102** after a configuration.
1103*/
icculus9e44cf12010-02-14 17:14:22 +00001104void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001105{
1106 int i;
1107 struct config *cfp;
1108 struct plink *plp;
1109 int progress;
1110 int change;
1111
1112 for(i=0; i<lemp->nstate; i++){
1113 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1114 cfp->status = INCOMPLETE;
1115 }
1116 }
drh06f60d82017-04-14 19:46:12 +00001117
drh75897232000-05-29 14:26:00 +00001118 do{
1119 progress = 0;
1120 for(i=0; i<lemp->nstate; i++){
1121 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1122 if( cfp->status==COMPLETE ) continue;
1123 for(plp=cfp->fplp; plp; plp=plp->next){
1124 change = SetUnion(plp->cfp->fws,cfp->fws);
1125 if( change ){
1126 plp->cfp->status = INCOMPLETE;
1127 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001128 }
1129 }
drh75897232000-05-29 14:26:00 +00001130 cfp->status = COMPLETE;
1131 }
1132 }
1133 }while( progress );
1134}
1135
drh3cb2f6e2012-01-09 14:19:05 +00001136static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001137
1138/* Compute the reduce actions, and resolve conflicts.
1139*/
icculus9e44cf12010-02-14 17:14:22 +00001140void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001141{
1142 int i,j;
1143 struct config *cfp;
1144 struct state *stp;
1145 struct symbol *sp;
1146 struct rule *rp;
1147
drh06f60d82017-04-14 19:46:12 +00001148 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001149 ** A reduce action is added for each element of the followset of
1150 ** a configuration which has its dot at the extreme right.
1151 */
1152 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1153 stp = lemp->sorted[i];
1154 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1155 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1156 for(j=0; j<lemp->nterminal; j++){
1157 if( SetFind(cfp->fws,j) ){
1158 /* Add a reduce action to the state "stp" which will reduce by the
1159 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001160 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001161 }
drhf2f105d2012-08-20 15:53:54 +00001162 }
drh75897232000-05-29 14:26:00 +00001163 }
1164 }
1165 }
1166
1167 /* Add the accepting token */
1168 if( lemp->start ){
1169 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001170 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001171 }else{
drh4ef07702016-03-16 19:45:54 +00001172 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001173 }
1174 /* Add to the first state (which is always the starting state of the
1175 ** finite state machine) an action to ACCEPT if the lookahead is the
1176 ** start nonterminal. */
1177 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1178
1179 /* Resolve conflicts */
1180 for(i=0; i<lemp->nstate; i++){
1181 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001182 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001183 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001184 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001185 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001186 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1187 /* The two actions "ap" and "nap" have the same lookahead.
1188 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001189 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001190 }
1191 }
1192 }
1193
1194 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001195 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001196 for(i=0; i<lemp->nstate; i++){
1197 struct action *ap;
1198 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001199 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001200 }
1201 }
1202 for(rp=lemp->rule; rp; rp=rp->next){
1203 if( rp->canReduce ) continue;
1204 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1205 lemp->errorcnt++;
1206 }
1207}
1208
1209/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001210** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001211**
1212** NO LONGER TRUE:
1213** To resolve a conflict, first look to see if either action
1214** is on an error rule. In that case, take the action which
1215** is not associated with the error rule. If neither or both
1216** actions are associated with an error rule, then try to
1217** use precedence to resolve the conflict.
1218**
1219** If either action is a SHIFT, then it must be apx. This
1220** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1221*/
icculus9e44cf12010-02-14 17:14:22 +00001222static int resolve_conflict(
1223 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001224 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001225){
drh75897232000-05-29 14:26:00 +00001226 struct symbol *spx, *spy;
1227 int errcnt = 0;
1228 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001229 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001230 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001231 errcnt++;
1232 }
drh75897232000-05-29 14:26:00 +00001233 if( apx->type==SHIFT && apy->type==REDUCE ){
1234 spx = apx->sp;
1235 spy = apy->x.rp->precsym;
1236 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1237 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001238 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001239 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001240 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001241 apy->type = RD_RESOLVED;
1242 }else if( spx->prec<spy->prec ){
1243 apx->type = SH_RESOLVED;
1244 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1245 apy->type = RD_RESOLVED; /* associativity */
1246 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1247 apx->type = SH_RESOLVED;
1248 }else{
1249 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001250 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001251 }
1252 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1253 spx = apx->x.rp->precsym;
1254 spy = apy->x.rp->precsym;
1255 if( spx==0 || spy==0 || spx->prec<0 ||
1256 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001257 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001258 errcnt++;
1259 }else if( spx->prec>spy->prec ){
1260 apy->type = RD_RESOLVED;
1261 }else if( spx->prec<spy->prec ){
1262 apx->type = RD_RESOLVED;
1263 }
1264 }else{
drh06f60d82017-04-14 19:46:12 +00001265 assert(
drhb59499c2002-02-23 18:45:13 +00001266 apx->type==SH_RESOLVED ||
1267 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001268 apx->type==SSCONFLICT ||
1269 apx->type==SRCONFLICT ||
1270 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001271 apy->type==SH_RESOLVED ||
1272 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001273 apy->type==SSCONFLICT ||
1274 apy->type==SRCONFLICT ||
1275 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001276 );
1277 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1278 ** REDUCEs on the list. If we reach this point it must be because
1279 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001280 }
1281 return errcnt;
1282}
1283/********************* From the file "configlist.c" *************************/
1284/*
1285** Routines to processing a configuration list and building a state
1286** in the LEMON parser generator.
1287*/
1288
1289static struct config *freelist = 0; /* List of free configurations */
1290static struct config *current = 0; /* Top of list of configurations */
1291static struct config **currentend = 0; /* Last on list of configs */
1292static struct config *basis = 0; /* Top of list of basis configs */
1293static struct config **basisend = 0; /* End of list of basis configs */
1294
1295/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001296PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001297 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001298 if( freelist==0 ){
1299 int i;
1300 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001301 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001302 if( freelist==0 ){
1303 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1304 exit(1);
1305 }
1306 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1307 freelist[amt-1].next = 0;
1308 }
icculus9e44cf12010-02-14 17:14:22 +00001309 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001310 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001311 return newcfg;
drh75897232000-05-29 14:26:00 +00001312}
1313
1314/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001315PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001316{
1317 old->next = freelist;
1318 freelist = old;
1319}
1320
1321/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001322void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001323 current = 0;
1324 currentend = &current;
1325 basis = 0;
1326 basisend = &basis;
1327 Configtable_init();
1328 return;
1329}
1330
1331/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001332void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001333 current = 0;
1334 currentend = &current;
1335 basis = 0;
1336 basisend = &basis;
1337 Configtable_clear(0);
1338 return;
1339}
1340
1341/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001342struct config *Configlist_add(
1343 struct rule *rp, /* The rule */
1344 int dot /* Index into the RHS of the rule where the dot goes */
1345){
drh75897232000-05-29 14:26:00 +00001346 struct config *cfp, model;
1347
1348 assert( currentend!=0 );
1349 model.rp = rp;
1350 model.dot = dot;
1351 cfp = Configtable_find(&model);
1352 if( cfp==0 ){
1353 cfp = newconfig();
1354 cfp->rp = rp;
1355 cfp->dot = dot;
1356 cfp->fws = SetNew();
1357 cfp->stp = 0;
1358 cfp->fplp = cfp->bplp = 0;
1359 cfp->next = 0;
1360 cfp->bp = 0;
1361 *currentend = cfp;
1362 currentend = &cfp->next;
1363 Configtable_insert(cfp);
1364 }
1365 return cfp;
1366}
1367
1368/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001369struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001370{
1371 struct config *cfp, model;
1372
1373 assert( basisend!=0 );
1374 assert( currentend!=0 );
1375 model.rp = rp;
1376 model.dot = dot;
1377 cfp = Configtable_find(&model);
1378 if( cfp==0 ){
1379 cfp = newconfig();
1380 cfp->rp = rp;
1381 cfp->dot = dot;
1382 cfp->fws = SetNew();
1383 cfp->stp = 0;
1384 cfp->fplp = cfp->bplp = 0;
1385 cfp->next = 0;
1386 cfp->bp = 0;
1387 *currentend = cfp;
1388 currentend = &cfp->next;
1389 *basisend = cfp;
1390 basisend = &cfp->bp;
1391 Configtable_insert(cfp);
1392 }
1393 return cfp;
1394}
1395
1396/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001397void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001398{
1399 struct config *cfp, *newcfp;
1400 struct rule *rp, *newrp;
1401 struct symbol *sp, *xsp;
1402 int i, dot;
1403
1404 assert( currentend!=0 );
1405 for(cfp=current; cfp; cfp=cfp->next){
1406 rp = cfp->rp;
1407 dot = cfp->dot;
1408 if( dot>=rp->nrhs ) continue;
1409 sp = rp->rhs[dot];
1410 if( sp->type==NONTERMINAL ){
1411 if( sp->rule==0 && sp!=lemp->errsym ){
1412 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1413 sp->name);
1414 lemp->errorcnt++;
1415 }
1416 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1417 newcfp = Configlist_add(newrp,0);
1418 for(i=dot+1; i<rp->nrhs; i++){
1419 xsp = rp->rhs[i];
1420 if( xsp->type==TERMINAL ){
1421 SetAdd(newcfp->fws,xsp->index);
1422 break;
drhfd405312005-11-06 04:06:59 +00001423 }else if( xsp->type==MULTITERMINAL ){
1424 int k;
1425 for(k=0; k<xsp->nsubsym; k++){
1426 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1427 }
1428 break;
drhf2f105d2012-08-20 15:53:54 +00001429 }else{
drh75897232000-05-29 14:26:00 +00001430 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001431 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001432 }
1433 }
drh75897232000-05-29 14:26:00 +00001434 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1435 }
1436 }
1437 }
1438 return;
1439}
1440
1441/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001442void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001443 current = (struct config*)msort((char*)current,(char**)&(current->next),
1444 Configcmp);
drh75897232000-05-29 14:26:00 +00001445 currentend = 0;
1446 return;
1447}
1448
1449/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001450void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001451 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1452 Configcmp);
drh75897232000-05-29 14:26:00 +00001453 basisend = 0;
1454 return;
1455}
1456
1457/* Return a pointer to the head of the configuration list and
1458** reset the list */
drh14d88552017-04-14 19:44:15 +00001459struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001460 struct config *old;
1461 old = current;
1462 current = 0;
1463 currentend = 0;
1464 return old;
1465}
1466
1467/* Return a pointer to the head of the configuration list and
1468** reset the list */
drh14d88552017-04-14 19:44:15 +00001469struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001470 struct config *old;
1471 old = basis;
1472 basis = 0;
1473 basisend = 0;
1474 return old;
1475}
1476
1477/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001478void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001479{
1480 struct config *nextcfp;
1481 for(; cfp; cfp=nextcfp){
1482 nextcfp = cfp->next;
1483 assert( cfp->fplp==0 );
1484 assert( cfp->bplp==0 );
1485 if( cfp->fws ) SetFree(cfp->fws);
1486 deleteconfig(cfp);
1487 }
1488 return;
1489}
1490/***************** From the file "error.c" *********************************/
1491/*
1492** Code for printing error message.
1493*/
1494
drhf9a2e7b2003-04-15 01:49:48 +00001495void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001496 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001497 fprintf(stderr, "%s:%d: ", filename, lineno);
1498 va_start(ap, format);
1499 vfprintf(stderr,format,ap);
1500 va_end(ap);
1501 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001502}
1503/**************** From the file "main.c" ************************************/
1504/*
1505** Main program file for the LEMON parser generator.
1506*/
1507
1508/* Report an out-of-memory condition and abort. This function
1509** is used mostly by the "MemoryCheck" macro in struct.h
1510*/
drh14d88552017-04-14 19:44:15 +00001511void memory_error(void){
drh75897232000-05-29 14:26:00 +00001512 fprintf(stderr,"Out of memory. Aborting...\n");
1513 exit(1);
1514}
1515
drh6d08b4d2004-07-20 12:45:22 +00001516static int nDefine = 0; /* Number of -D options on the command line */
1517static char **azDefine = 0; /* Name of the -D macros */
1518
1519/* This routine is called with the argument to each -D command-line option.
1520** Add the macro defined to the azDefine array.
1521*/
1522static void handle_D_option(char *z){
1523 char **paz;
1524 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001525 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001526 if( azDefine==0 ){
1527 fprintf(stderr,"out of memory\n");
1528 exit(1);
1529 }
1530 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001531 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001532 if( *paz==0 ){
1533 fprintf(stderr,"out of memory\n");
1534 exit(1);
1535 }
drh898799f2014-01-10 23:21:00 +00001536 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001537 for(z=*paz; *z && *z!='='; z++){}
1538 *z = 0;
1539}
1540
drh9f88e6d2018-04-20 20:47:49 +00001541/* Rember the name of the output directory
1542*/
1543static char *outputDir = NULL;
1544static void handle_d_option(char *z){
1545 outputDir = (char *) malloc( lemonStrlen(z)+1 );
1546 if( outputDir==0 ){
1547 fprintf(stderr,"out of memory\n");
1548 exit(1);
1549 }
1550 lemon_strcpy(outputDir, z);
1551}
1552
icculus3e143bd2010-02-14 00:48:49 +00001553static char *user_templatename = NULL;
1554static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001555 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001556 if( user_templatename==0 ){
1557 memory_error();
1558 }
drh898799f2014-01-10 23:21:00 +00001559 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001560}
drh75897232000-05-29 14:26:00 +00001561
drh711c9812016-05-23 14:24:31 +00001562/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001563static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1564 struct rule *pFirst = 0;
1565 struct rule **ppPrev = &pFirst;
1566 while( pA && pB ){
1567 if( pA->iRule<pB->iRule ){
1568 *ppPrev = pA;
1569 ppPrev = &pA->next;
1570 pA = pA->next;
1571 }else{
1572 *ppPrev = pB;
1573 ppPrev = &pB->next;
1574 pB = pB->next;
1575 }
1576 }
1577 if( pA ){
1578 *ppPrev = pA;
1579 }else{
1580 *ppPrev = pB;
1581 }
1582 return pFirst;
1583}
1584
1585/*
1586** Sort a list of rules in order of increasing iRule value
1587*/
1588static struct rule *Rule_sort(struct rule *rp){
1589 int i;
1590 struct rule *pNext;
1591 struct rule *x[32];
1592 memset(x, 0, sizeof(x));
1593 while( rp ){
1594 pNext = rp->next;
1595 rp->next = 0;
1596 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1597 rp = Rule_merge(x[i], rp);
1598 x[i] = 0;
1599 }
1600 x[i] = rp;
1601 rp = pNext;
1602 }
1603 rp = 0;
1604 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1605 rp = Rule_merge(x[i], rp);
1606 }
1607 return rp;
1608}
1609
drhc75e0162015-09-07 02:23:02 +00001610/* forward reference */
1611static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1612
1613/* Print a single line of the "Parser Stats" output
1614*/
1615static void stats_line(const char *zLabel, int iValue){
1616 int nLabel = lemonStrlen(zLabel);
1617 printf(" %s%.*s %5d\n", zLabel,
1618 35-nLabel, "................................",
1619 iValue);
1620}
1621
drh75897232000-05-29 14:26:00 +00001622/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001623int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001624{
1625 static int version = 0;
1626 static int rpflag = 0;
1627 static int basisflag = 0;
1628 static int compress = 0;
1629 static int quiet = 0;
1630 static int statistics = 0;
1631 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001632 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001633 static int noResort = 0;
drh9f88e6d2018-04-20 20:47:49 +00001634
drh75897232000-05-29 14:26:00 +00001635 static struct s_options options[] = {
1636 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1637 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh9f88e6d2018-04-20 20:47:49 +00001638 {OPT_FSTR, "d", (char*)&handle_d_option, "Output directory. Default '.'"},
drh6d08b4d2004-07-20 12:45:22 +00001639 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001640 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001641 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001642 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001643 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1644 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001645 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001646 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1647 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001648 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001649 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001650 {OPT_FLAG, "s", (char*)&statistics,
1651 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001652 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001653 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1654 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001655 {OPT_FLAG,0,0,0}
1656 };
1657 int i;
icculus42585cf2010-02-14 05:19:56 +00001658 int exitcode;
drh75897232000-05-29 14:26:00 +00001659 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001660 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001661
drhb0c86772000-06-02 23:21:26 +00001662 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001663 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001664 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001665 exit(0);
drh75897232000-05-29 14:26:00 +00001666 }
drhb0c86772000-06-02 23:21:26 +00001667 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001668 fprintf(stderr,"Exactly one filename argument is required.\n");
1669 exit(1);
1670 }
drh954f6b42006-06-13 13:27:46 +00001671 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001672 lem.errorcnt = 0;
1673
1674 /* Initialize the machine */
1675 Strsafe_init();
1676 Symbol_init();
1677 State_init();
1678 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001679 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001680 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001681 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001682 Symbol_new("$");
drh75897232000-05-29 14:26:00 +00001683
1684 /* Parse the input file */
1685 Parse(&lem);
1686 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001687 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001688 fprintf(stderr,"Empty grammar.\n");
1689 exit(1);
1690 }
drhed0c15b2018-04-16 14:31:34 +00001691 lem.errsym = Symbol_find("error");
drh75897232000-05-29 14:26:00 +00001692
1693 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001694 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001695 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001696 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001697 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1698 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1699 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1700 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1701 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1702 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001703 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001704 lem.nterminal = i;
1705
drh711c9812016-05-23 14:24:31 +00001706 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1707 ** reduce action C-code associated with them last, so that the switch()
1708 ** statement that selects reduction actions will have a smaller jump table.
1709 */
drh4ef07702016-03-16 19:45:54 +00001710 for(i=0, rp=lem.rule; rp; rp=rp->next){
1711 rp->iRule = rp->code ? i++ : -1;
1712 }
1713 for(rp=lem.rule; rp; rp=rp->next){
1714 if( rp->iRule<0 ) rp->iRule = i++;
1715 }
1716 lem.startRule = lem.rule;
1717 lem.rule = Rule_sort(lem.rule);
1718
drh75897232000-05-29 14:26:00 +00001719 /* Generate a reprint of the grammar, if requested on the command line */
1720 if( rpflag ){
1721 Reprint(&lem);
1722 }else{
1723 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001724 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001725
1726 /* Find the precedence for every production rule (that has one) */
1727 FindRulePrecedences(&lem);
1728
1729 /* Compute the lambda-nonterminals and the first-sets for every
1730 ** nonterminal */
1731 FindFirstSets(&lem);
1732
1733 /* Compute all LR(0) states. Also record follow-set propagation
1734 ** links so that the follow-set can be computed later */
1735 lem.nstate = 0;
1736 FindStates(&lem);
1737 lem.sorted = State_arrayof();
1738
1739 /* Tie up loose ends on the propagation links */
1740 FindLinks(&lem);
1741
1742 /* Compute the follow set of every reducible configuration */
1743 FindFollowSets(&lem);
1744
1745 /* Compute the action tables */
1746 FindActions(&lem);
1747
1748 /* Compress the action tables */
1749 if( compress==0 ) CompressTables(&lem);
1750
drhada354d2005-11-05 15:03:59 +00001751 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001752 ** occur at the end. This is an optimization that helps make the
1753 ** generated parser tables smaller. */
1754 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001755
drh75897232000-05-29 14:26:00 +00001756 /* Generate a report of the parser generated. (the "y.output" file) */
1757 if( !quiet ) ReportOutput(&lem);
1758
1759 /* Generate the source code for the parser */
1760 ReportTable(&lem, mhflag);
1761
1762 /* Produce a header file for use by the scanner. (This step is
1763 ** omitted if the "-m" option is used because makeheaders will
1764 ** generate the file for us.) */
1765 if( !mhflag ) ReportHeader(&lem);
1766 }
1767 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001768 printf("Parser statistics:\n");
1769 stats_line("terminal symbols", lem.nterminal);
1770 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1771 stats_line("total symbols", lem.nsymbol);
1772 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001773 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001774 stats_line("conflicts", lem.nconflict);
1775 stats_line("action table entries", lem.nactiontab);
drh3a9d6c72017-12-25 04:15:38 +00001776 stats_line("lookahead table entries", lem.nlookaheadtab);
drhc75e0162015-09-07 02:23:02 +00001777 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001778 }
icculus8e158022010-02-16 16:09:03 +00001779 if( lem.nconflict > 0 ){
1780 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001781 }
1782
1783 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001784 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001785 exit(exitcode);
1786 return (exitcode);
drh75897232000-05-29 14:26:00 +00001787}
1788/******************** From the file "msort.c" *******************************/
1789/*
1790** A generic merge-sort program.
1791**
1792** USAGE:
1793** Let "ptr" be a pointer to some structure which is at the head of
1794** a null-terminated list. Then to sort the list call:
1795**
1796** ptr = msort(ptr,&(ptr->next),cmpfnc);
1797**
1798** In the above, "cmpfnc" is a pointer to a function which compares
1799** two instances of the structure and returns an integer, as in
1800** strcmp. The second argument is a pointer to the pointer to the
1801** second element of the linked list. This address is used to compute
1802** the offset to the "next" field within the structure. The offset to
1803** the "next" field must be constant for all structures in the list.
1804**
1805** The function returns a new pointer which is the head of the list
1806** after sorting.
1807**
1808** ALGORITHM:
1809** Merge-sort.
1810*/
1811
1812/*
1813** Return a pointer to the next structure in the linked list.
1814*/
drhd25d6922012-04-18 09:59:56 +00001815#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001816
1817/*
1818** Inputs:
1819** a: A sorted, null-terminated linked list. (May be null).
1820** b: A sorted, null-terminated linked list. (May be null).
1821** cmp: A pointer to the comparison function.
1822** offset: Offset in the structure to the "next" field.
1823**
1824** Return Value:
1825** A pointer to the head of a sorted list containing the elements
1826** of both a and b.
1827**
1828** Side effects:
1829** The "next" pointers for elements in the lists a and b are
1830** changed.
1831*/
drhe9278182007-07-18 18:16:29 +00001832static char *merge(
1833 char *a,
1834 char *b,
1835 int (*cmp)(const char*,const char*),
1836 int offset
1837){
drh75897232000-05-29 14:26:00 +00001838 char *ptr, *head;
1839
1840 if( a==0 ){
1841 head = b;
1842 }else if( b==0 ){
1843 head = a;
1844 }else{
drhe594bc32009-11-03 13:02:25 +00001845 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001846 ptr = a;
1847 a = NEXT(a);
1848 }else{
1849 ptr = b;
1850 b = NEXT(b);
1851 }
1852 head = ptr;
1853 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001854 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001855 NEXT(ptr) = a;
1856 ptr = a;
1857 a = NEXT(a);
1858 }else{
1859 NEXT(ptr) = b;
1860 ptr = b;
1861 b = NEXT(b);
1862 }
1863 }
1864 if( a ) NEXT(ptr) = a;
1865 else NEXT(ptr) = b;
1866 }
1867 return head;
1868}
1869
1870/*
1871** Inputs:
1872** list: Pointer to a singly-linked list of structures.
1873** next: Pointer to pointer to the second element of the list.
1874** cmp: A comparison function.
1875**
1876** Return Value:
1877** A pointer to the head of a sorted list containing the elements
1878** orginally in list.
1879**
1880** Side effects:
1881** The "next" pointers for elements in list are changed.
1882*/
1883#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001884static char *msort(
1885 char *list,
1886 char **next,
1887 int (*cmp)(const char*,const char*)
1888){
drhba99af52001-10-25 20:37:16 +00001889 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001890 char *ep;
1891 char *set[LISTSIZE];
1892 int i;
drh1cc0d112015-03-31 15:15:48 +00001893 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001894 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1895 while( list ){
1896 ep = list;
1897 list = NEXT(list);
1898 NEXT(ep) = 0;
1899 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1900 ep = merge(ep,set[i],cmp,offset);
1901 set[i] = 0;
1902 }
1903 set[i] = ep;
1904 }
1905 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001906 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001907 return ep;
1908}
1909/************************ From the file "option.c" **************************/
1910static char **argv;
1911static struct s_options *op;
1912static FILE *errstream;
1913
1914#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1915
1916/*
1917** Print the command line with a carrot pointing to the k-th character
1918** of the n-th field.
1919*/
icculus9e44cf12010-02-14 17:14:22 +00001920static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001921{
1922 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001923 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001924 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001925 for(i=1; i<n && argv[i]; i++){
1926 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001927 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001928 }
1929 spcnt += k;
1930 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1931 if( spcnt<20 ){
1932 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1933 }else{
1934 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1935 }
1936}
1937
1938/*
1939** Return the index of the N-th non-switch argument. Return -1
1940** if N is out of range.
1941*/
icculus9e44cf12010-02-14 17:14:22 +00001942static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001943{
1944 int i;
1945 int dashdash = 0;
1946 if( argv!=0 && *argv!=0 ){
1947 for(i=1; argv[i]; i++){
1948 if( dashdash || !ISOPT(argv[i]) ){
1949 if( n==0 ) return i;
1950 n--;
1951 }
1952 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1953 }
1954 }
1955 return -1;
1956}
1957
1958static char emsg[] = "Command line syntax error: ";
1959
1960/*
1961** Process a flag command line argument.
1962*/
icculus9e44cf12010-02-14 17:14:22 +00001963static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001964{
1965 int v;
1966 int errcnt = 0;
1967 int j;
1968 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001969 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001970 }
1971 v = argv[i][0]=='-' ? 1 : 0;
1972 if( op[j].label==0 ){
1973 if( err ){
1974 fprintf(err,"%sundefined option.\n",emsg);
1975 errline(i,1,err);
1976 }
1977 errcnt++;
drh0325d392015-01-01 19:11:22 +00001978 }else if( op[j].arg==0 ){
1979 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001980 }else if( op[j].type==OPT_FLAG ){
1981 *((int*)op[j].arg) = v;
1982 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001983 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001984 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001985 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001986 }else{
1987 if( err ){
1988 fprintf(err,"%smissing argument on switch.\n",emsg);
1989 errline(i,1,err);
1990 }
1991 errcnt++;
1992 }
1993 return errcnt;
1994}
1995
1996/*
1997** Process a command line switch which has an argument.
1998*/
icculus9e44cf12010-02-14 17:14:22 +00001999static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00002000{
2001 int lv = 0;
2002 double dv = 0.0;
2003 char *sv = 0, *end;
2004 char *cp;
2005 int j;
2006 int errcnt = 0;
2007 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00002008 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00002009 *cp = 0;
2010 for(j=0; op[j].label; j++){
2011 if( strcmp(argv[i],op[j].label)==0 ) break;
2012 }
2013 *cp = '=';
2014 if( op[j].label==0 ){
2015 if( err ){
2016 fprintf(err,"%sundefined option.\n",emsg);
2017 errline(i,0,err);
2018 }
2019 errcnt++;
2020 }else{
2021 cp++;
2022 switch( op[j].type ){
2023 case OPT_FLAG:
2024 case OPT_FFLAG:
2025 if( err ){
2026 fprintf(err,"%soption requires an argument.\n",emsg);
2027 errline(i,0,err);
2028 }
2029 errcnt++;
2030 break;
2031 case OPT_DBL:
2032 case OPT_FDBL:
2033 dv = strtod(cp,&end);
2034 if( *end ){
2035 if( err ){
drh25473362015-09-04 18:03:45 +00002036 fprintf(err,
2037 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00002038 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002039 }
2040 errcnt++;
2041 }
2042 break;
2043 case OPT_INT:
2044 case OPT_FINT:
2045 lv = strtol(cp,&end,0);
2046 if( *end ){
2047 if( err ){
2048 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00002049 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002050 }
2051 errcnt++;
2052 }
2053 break;
2054 case OPT_STR:
2055 case OPT_FSTR:
2056 sv = cp;
2057 break;
2058 }
2059 switch( op[j].type ){
2060 case OPT_FLAG:
2061 case OPT_FFLAG:
2062 break;
2063 case OPT_DBL:
2064 *(double*)(op[j].arg) = dv;
2065 break;
2066 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002067 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002068 break;
2069 case OPT_INT:
2070 *(int*)(op[j].arg) = lv;
2071 break;
2072 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002073 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002074 break;
2075 case OPT_STR:
2076 *(char**)(op[j].arg) = sv;
2077 break;
2078 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002079 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002080 break;
2081 }
2082 }
2083 return errcnt;
2084}
2085
icculus9e44cf12010-02-14 17:14:22 +00002086int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002087{
2088 int errcnt = 0;
2089 argv = a;
2090 op = o;
2091 errstream = err;
2092 if( argv && *argv && op ){
2093 int i;
2094 for(i=1; argv[i]; i++){
2095 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2096 errcnt += handleflags(i,err);
2097 }else if( strchr(argv[i],'=') ){
2098 errcnt += handleswitch(i,err);
2099 }
2100 }
2101 }
2102 if( errcnt>0 ){
2103 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002104 OptPrint();
drh75897232000-05-29 14:26:00 +00002105 exit(1);
2106 }
2107 return 0;
2108}
2109
drh14d88552017-04-14 19:44:15 +00002110int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002111 int cnt = 0;
2112 int dashdash = 0;
2113 int i;
2114 if( argv!=0 && argv[0]!=0 ){
2115 for(i=1; argv[i]; i++){
2116 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2117 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2118 }
2119 }
2120 return cnt;
2121}
2122
icculus9e44cf12010-02-14 17:14:22 +00002123char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002124{
2125 int i;
2126 i = argindex(n);
2127 return i>=0 ? argv[i] : 0;
2128}
2129
icculus9e44cf12010-02-14 17:14:22 +00002130void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002131{
2132 int i;
2133 i = argindex(n);
2134 if( i>=0 ) errline(i,0,errstream);
2135}
2136
drh14d88552017-04-14 19:44:15 +00002137void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002138 int i;
2139 int max, len;
2140 max = 0;
2141 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002142 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002143 switch( op[i].type ){
2144 case OPT_FLAG:
2145 case OPT_FFLAG:
2146 break;
2147 case OPT_INT:
2148 case OPT_FINT:
2149 len += 9; /* length of "<integer>" */
2150 break;
2151 case OPT_DBL:
2152 case OPT_FDBL:
2153 len += 6; /* length of "<real>" */
2154 break;
2155 case OPT_STR:
2156 case OPT_FSTR:
2157 len += 8; /* length of "<string>" */
2158 break;
2159 }
2160 if( len>max ) max = len;
2161 }
2162 for(i=0; op[i].label; i++){
2163 switch( op[i].type ){
2164 case OPT_FLAG:
2165 case OPT_FFLAG:
2166 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2167 break;
2168 case OPT_INT:
2169 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002170 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002171 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002172 break;
2173 case OPT_DBL:
2174 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002175 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002176 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002177 break;
2178 case OPT_STR:
2179 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002180 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002181 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002182 break;
2183 }
2184 }
2185}
2186/*********************** From the file "parse.c" ****************************/
2187/*
2188** Input file parser for the LEMON parser generator.
2189*/
2190
2191/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002192enum e_state {
2193 INITIALIZE,
2194 WAITING_FOR_DECL_OR_RULE,
2195 WAITING_FOR_DECL_KEYWORD,
2196 WAITING_FOR_DECL_ARG,
2197 WAITING_FOR_PRECEDENCE_SYMBOL,
2198 WAITING_FOR_ARROW,
2199 IN_RHS,
2200 LHS_ALIAS_1,
2201 LHS_ALIAS_2,
2202 LHS_ALIAS_3,
2203 RHS_ALIAS_1,
2204 RHS_ALIAS_2,
2205 PRECEDENCE_MARK_1,
2206 PRECEDENCE_MARK_2,
2207 RESYNC_AFTER_RULE_ERROR,
2208 RESYNC_AFTER_DECL_ERROR,
2209 WAITING_FOR_DESTRUCTOR_SYMBOL,
2210 WAITING_FOR_DATATYPE_SYMBOL,
2211 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002212 WAITING_FOR_WILDCARD_ID,
2213 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002214 WAITING_FOR_CLASS_TOKEN,
2215 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002216};
drh75897232000-05-29 14:26:00 +00002217struct pstate {
2218 char *filename; /* Name of the input file */
2219 int tokenlineno; /* Linenumber at which current token starts */
2220 int errorcnt; /* Number of errors so far */
2221 char *tokenstart; /* Text of current token */
2222 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002223 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002224 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002225 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002226 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002227 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002228 int nrhs; /* Number of right-hand side symbols seen */
2229 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002230 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002231 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002232 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002233 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002234 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002235 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002236 enum e_assoc declassoc; /* Assign this association to decl arguments */
2237 int preccounter; /* Assign this precedence to decl arguments */
2238 struct rule *firstrule; /* Pointer to first rule in the grammar */
2239 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2240};
2241
2242/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002243static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002244{
icculus9e44cf12010-02-14 17:14:22 +00002245 const char *x;
drh75897232000-05-29 14:26:00 +00002246 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2247#if 0
2248 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2249 x,psp->state);
2250#endif
2251 switch( psp->state ){
2252 case INITIALIZE:
2253 psp->prevrule = 0;
2254 psp->preccounter = 0;
2255 psp->firstrule = psp->lastrule = 0;
2256 psp->gp->nrule = 0;
2257 /* Fall thru to next case */
2258 case WAITING_FOR_DECL_OR_RULE:
2259 if( x[0]=='%' ){
2260 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002261 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002262 psp->lhs = Symbol_new(x);
2263 psp->nrhs = 0;
2264 psp->lhsalias = 0;
2265 psp->state = WAITING_FOR_ARROW;
2266 }else if( x[0]=='{' ){
2267 if( psp->prevrule==0 ){
2268 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002269"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002270fragment which begins on this line.");
2271 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002272 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002273 ErrorMsg(psp->filename,psp->tokenlineno,
2274"Code fragment beginning on this line is not the first \
2275to follow the previous rule.");
2276 psp->errorcnt++;
2277 }else{
2278 psp->prevrule->line = psp->tokenlineno;
2279 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002280 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002281 }
drh75897232000-05-29 14:26:00 +00002282 }else if( x[0]=='[' ){
2283 psp->state = PRECEDENCE_MARK_1;
2284 }else{
2285 ErrorMsg(psp->filename,psp->tokenlineno,
2286 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2287 x);
2288 psp->errorcnt++;
2289 }
2290 break;
2291 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002292 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002293 ErrorMsg(psp->filename,psp->tokenlineno,
2294 "The precedence symbol must be a terminal.");
2295 psp->errorcnt++;
2296 }else if( psp->prevrule==0 ){
2297 ErrorMsg(psp->filename,psp->tokenlineno,
2298 "There is no prior rule to assign precedence \"[%s]\".",x);
2299 psp->errorcnt++;
2300 }else if( psp->prevrule->precsym!=0 ){
2301 ErrorMsg(psp->filename,psp->tokenlineno,
2302"Precedence mark on this line is not the first \
2303to follow the previous rule.");
2304 psp->errorcnt++;
2305 }else{
2306 psp->prevrule->precsym = Symbol_new(x);
2307 }
2308 psp->state = PRECEDENCE_MARK_2;
2309 break;
2310 case PRECEDENCE_MARK_2:
2311 if( x[0]!=']' ){
2312 ErrorMsg(psp->filename,psp->tokenlineno,
2313 "Missing \"]\" on precedence mark.");
2314 psp->errorcnt++;
2315 }
2316 psp->state = WAITING_FOR_DECL_OR_RULE;
2317 break;
2318 case WAITING_FOR_ARROW:
2319 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2320 psp->state = IN_RHS;
2321 }else if( x[0]=='(' ){
2322 psp->state = LHS_ALIAS_1;
2323 }else{
2324 ErrorMsg(psp->filename,psp->tokenlineno,
2325 "Expected to see a \":\" following the LHS symbol \"%s\".",
2326 psp->lhs->name);
2327 psp->errorcnt++;
2328 psp->state = RESYNC_AFTER_RULE_ERROR;
2329 }
2330 break;
2331 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002332 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002333 psp->lhsalias = x;
2334 psp->state = LHS_ALIAS_2;
2335 }else{
2336 ErrorMsg(psp->filename,psp->tokenlineno,
2337 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2338 x,psp->lhs->name);
2339 psp->errorcnt++;
2340 psp->state = RESYNC_AFTER_RULE_ERROR;
2341 }
2342 break;
2343 case LHS_ALIAS_2:
2344 if( x[0]==')' ){
2345 psp->state = LHS_ALIAS_3;
2346 }else{
2347 ErrorMsg(psp->filename,psp->tokenlineno,
2348 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2349 psp->errorcnt++;
2350 psp->state = RESYNC_AFTER_RULE_ERROR;
2351 }
2352 break;
2353 case LHS_ALIAS_3:
2354 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2355 psp->state = IN_RHS;
2356 }else{
2357 ErrorMsg(psp->filename,psp->tokenlineno,
2358 "Missing \"->\" following: \"%s(%s)\".",
2359 psp->lhs->name,psp->lhsalias);
2360 psp->errorcnt++;
2361 psp->state = RESYNC_AFTER_RULE_ERROR;
2362 }
2363 break;
2364 case IN_RHS:
2365 if( x[0]=='.' ){
2366 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002367 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002368 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002369 if( rp==0 ){
2370 ErrorMsg(psp->filename,psp->tokenlineno,
2371 "Can't allocate enough memory for this rule.");
2372 psp->errorcnt++;
2373 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002374 }else{
drh75897232000-05-29 14:26:00 +00002375 int i;
2376 rp->ruleline = psp->tokenlineno;
2377 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002378 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002379 for(i=0; i<psp->nrhs; i++){
2380 rp->rhs[i] = psp->rhs[i];
2381 rp->rhsalias[i] = psp->alias[i];
drh539e7412018-04-21 20:24:19 +00002382 if( rp->rhsalias[i]!=0 ){ rp->rhs[i]->bContent = 1; }
drhf2f105d2012-08-20 15:53:54 +00002383 }
drh75897232000-05-29 14:26:00 +00002384 rp->lhs = psp->lhs;
2385 rp->lhsalias = psp->lhsalias;
2386 rp->nrhs = psp->nrhs;
2387 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002388 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002389 rp->precsym = 0;
2390 rp->index = psp->gp->nrule++;
2391 rp->nextlhs = rp->lhs->rule;
2392 rp->lhs->rule = rp;
2393 rp->next = 0;
2394 if( psp->firstrule==0 ){
2395 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002396 }else{
drh75897232000-05-29 14:26:00 +00002397 psp->lastrule->next = rp;
2398 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002399 }
drh75897232000-05-29 14:26:00 +00002400 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002401 }
drh75897232000-05-29 14:26:00 +00002402 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002403 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002404 if( psp->nrhs>=MAXRHS ){
2405 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002406 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002407 x);
2408 psp->errorcnt++;
2409 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002410 }else{
drh75897232000-05-29 14:26:00 +00002411 psp->rhs[psp->nrhs] = Symbol_new(x);
2412 psp->alias[psp->nrhs] = 0;
2413 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002414 }
drhfd405312005-11-06 04:06:59 +00002415 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2416 struct symbol *msp = psp->rhs[psp->nrhs-1];
2417 if( msp->type!=MULTITERMINAL ){
2418 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002419 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002420 memset(msp, 0, sizeof(*msp));
2421 msp->type = MULTITERMINAL;
2422 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002423 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002424 msp->subsym[0] = origsp;
2425 msp->name = origsp->name;
2426 psp->rhs[psp->nrhs-1] = msp;
2427 }
2428 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002429 msp->subsym = (struct symbol **) realloc(msp->subsym,
2430 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002431 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002432 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002433 ErrorMsg(psp->filename,psp->tokenlineno,
2434 "Cannot form a compound containing a non-terminal");
2435 psp->errorcnt++;
2436 }
drh75897232000-05-29 14:26:00 +00002437 }else if( x[0]=='(' && psp->nrhs>0 ){
2438 psp->state = RHS_ALIAS_1;
2439 }else{
2440 ErrorMsg(psp->filename,psp->tokenlineno,
2441 "Illegal character on RHS of rule: \"%s\".",x);
2442 psp->errorcnt++;
2443 psp->state = RESYNC_AFTER_RULE_ERROR;
2444 }
2445 break;
2446 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002447 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002448 psp->alias[psp->nrhs-1] = x;
2449 psp->state = RHS_ALIAS_2;
2450 }else{
2451 ErrorMsg(psp->filename,psp->tokenlineno,
2452 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2453 x,psp->rhs[psp->nrhs-1]->name);
2454 psp->errorcnt++;
2455 psp->state = RESYNC_AFTER_RULE_ERROR;
2456 }
2457 break;
2458 case RHS_ALIAS_2:
2459 if( x[0]==')' ){
2460 psp->state = IN_RHS;
2461 }else{
2462 ErrorMsg(psp->filename,psp->tokenlineno,
2463 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2464 psp->errorcnt++;
2465 psp->state = RESYNC_AFTER_RULE_ERROR;
2466 }
2467 break;
2468 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002469 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002470 psp->declkeyword = x;
2471 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002472 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002473 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002474 psp->state = WAITING_FOR_DECL_ARG;
2475 if( strcmp(x,"name")==0 ){
2476 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002477 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002478 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002479 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002480 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002481 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002482 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002483 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002484 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002485 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002486 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002487 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002488 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002489 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002490 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002491 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002492 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002493 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002494 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002495 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002496 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002497 }else if( strcmp(x,"extra_argument")==0 ){
2498 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002499 psp->insertLineMacro = 0;
drhfb32c442018-04-21 13:51:42 +00002500 }else if( strcmp(x,"extra_context")==0 ){
2501 psp->declargslot = &(psp->gp->ctx);
2502 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002503 }else if( strcmp(x,"token_type")==0 ){
2504 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002505 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002506 }else if( strcmp(x,"default_type")==0 ){
2507 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002508 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002509 }else if( strcmp(x,"stack_size")==0 ){
2510 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002511 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002512 }else if( strcmp(x,"start_symbol")==0 ){
2513 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002514 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002515 }else if( strcmp(x,"left")==0 ){
2516 psp->preccounter++;
2517 psp->declassoc = LEFT;
2518 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2519 }else if( strcmp(x,"right")==0 ){
2520 psp->preccounter++;
2521 psp->declassoc = RIGHT;
2522 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2523 }else if( strcmp(x,"nonassoc")==0 ){
2524 psp->preccounter++;
2525 psp->declassoc = NONE;
2526 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002527 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002528 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002529 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002530 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002531 }else if( strcmp(x,"fallback")==0 ){
2532 psp->fallback = 0;
2533 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002534 }else if( strcmp(x,"token")==0 ){
2535 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002536 }else if( strcmp(x,"wildcard")==0 ){
2537 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002538 }else if( strcmp(x,"token_class")==0 ){
2539 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002540 }else{
2541 ErrorMsg(psp->filename,psp->tokenlineno,
2542 "Unknown declaration keyword: \"%%%s\".",x);
2543 psp->errorcnt++;
2544 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002545 }
drh75897232000-05-29 14:26:00 +00002546 }else{
2547 ErrorMsg(psp->filename,psp->tokenlineno,
2548 "Illegal declaration keyword: \"%s\".",x);
2549 psp->errorcnt++;
2550 psp->state = RESYNC_AFTER_DECL_ERROR;
2551 }
2552 break;
2553 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002554 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002555 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002556 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002557 psp->errorcnt++;
2558 psp->state = RESYNC_AFTER_DECL_ERROR;
2559 }else{
icculusd286fa62010-03-03 17:06:32 +00002560 struct symbol *sp = Symbol_new(x);
2561 psp->declargslot = &sp->destructor;
2562 psp->decllinenoslot = &sp->destLineno;
2563 psp->insertLineMacro = 1;
2564 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002565 }
2566 break;
2567 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002568 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002569 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002570 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002571 psp->errorcnt++;
2572 psp->state = RESYNC_AFTER_DECL_ERROR;
2573 }else{
icculus866bf1e2010-02-17 20:31:32 +00002574 struct symbol *sp = Symbol_find(x);
2575 if((sp) && (sp->datatype)){
2576 ErrorMsg(psp->filename,psp->tokenlineno,
2577 "Symbol %%type \"%s\" already defined", x);
2578 psp->errorcnt++;
2579 psp->state = RESYNC_AFTER_DECL_ERROR;
2580 }else{
2581 if (!sp){
2582 sp = Symbol_new(x);
2583 }
2584 psp->declargslot = &sp->datatype;
2585 psp->insertLineMacro = 0;
2586 psp->state = WAITING_FOR_DECL_ARG;
2587 }
drh75897232000-05-29 14:26:00 +00002588 }
2589 break;
2590 case WAITING_FOR_PRECEDENCE_SYMBOL:
2591 if( x[0]=='.' ){
2592 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002593 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002594 struct symbol *sp;
2595 sp = Symbol_new(x);
2596 if( sp->prec>=0 ){
2597 ErrorMsg(psp->filename,psp->tokenlineno,
2598 "Symbol \"%s\" has already be given a precedence.",x);
2599 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002600 }else{
drh75897232000-05-29 14:26:00 +00002601 sp->prec = psp->preccounter;
2602 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002603 }
drh75897232000-05-29 14:26:00 +00002604 }else{
2605 ErrorMsg(psp->filename,psp->tokenlineno,
2606 "Can't assign a precedence to \"%s\".",x);
2607 psp->errorcnt++;
2608 }
2609 break;
2610 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002611 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002612 const char *zOld, *zNew;
2613 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002614 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002615 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002616 char zLine[50];
2617 zNew = x;
2618 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002619 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002620 if( *psp->declargslot ){
2621 zOld = *psp->declargslot;
2622 }else{
2623 zOld = "";
2624 }
drh87cf1372008-08-13 20:09:06 +00002625 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002626 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002627 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002628 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2629 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002630 for(z=psp->filename, nBack=0; *z; z++){
2631 if( *z=='\\' ) nBack++;
2632 }
drh898799f2014-01-10 23:21:00 +00002633 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002634 nLine = lemonStrlen(zLine);
2635 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002636 }
icculus9e44cf12010-02-14 17:14:22 +00002637 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2638 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002639 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002640 if( nOld && zBuf[-1]!='\n' ){
2641 *(zBuf++) = '\n';
2642 }
2643 memcpy(zBuf, zLine, nLine);
2644 zBuf += nLine;
2645 *(zBuf++) = '"';
2646 for(z=psp->filename; *z; z++){
2647 if( *z=='\\' ){
2648 *(zBuf++) = '\\';
2649 }
2650 *(zBuf++) = *z;
2651 }
2652 *(zBuf++) = '"';
2653 *(zBuf++) = '\n';
2654 }
drh4dc8ef52008-07-01 17:13:57 +00002655 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2656 psp->decllinenoslot[0] = psp->tokenlineno;
2657 }
drha5808f32008-04-27 22:19:44 +00002658 memcpy(zBuf, zNew, nNew);
2659 zBuf += nNew;
2660 *zBuf = 0;
2661 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002662 }else{
2663 ErrorMsg(psp->filename,psp->tokenlineno,
2664 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2665 psp->errorcnt++;
2666 psp->state = RESYNC_AFTER_DECL_ERROR;
2667 }
2668 break;
drh0bd1f4e2002-06-06 18:54:39 +00002669 case WAITING_FOR_FALLBACK_ID:
2670 if( x[0]=='.' ){
2671 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002672 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002673 ErrorMsg(psp->filename, psp->tokenlineno,
2674 "%%fallback argument \"%s\" should be a token", x);
2675 psp->errorcnt++;
2676 }else{
2677 struct symbol *sp = Symbol_new(x);
2678 if( psp->fallback==0 ){
2679 psp->fallback = sp;
2680 }else if( sp->fallback ){
2681 ErrorMsg(psp->filename, psp->tokenlineno,
2682 "More than one fallback assigned to token %s", x);
2683 psp->errorcnt++;
2684 }else{
2685 sp->fallback = psp->fallback;
2686 psp->gp->has_fallback = 1;
2687 }
2688 }
2689 break;
drh59c435a2017-08-02 03:21:11 +00002690 case WAITING_FOR_TOKEN_NAME:
2691 /* Tokens do not have to be declared before use. But they can be
2692 ** in order to control their assigned integer number. The number for
2693 ** each token is assigned when it is first seen. So by including
2694 **
2695 ** %token ONE TWO THREE
2696 **
2697 ** early in the grammar file, that assigns small consecutive values
2698 ** to each of the tokens ONE TWO and THREE.
2699 */
2700 if( x[0]=='.' ){
2701 psp->state = WAITING_FOR_DECL_OR_RULE;
2702 }else if( !ISUPPER(x[0]) ){
2703 ErrorMsg(psp->filename, psp->tokenlineno,
2704 "%%token argument \"%s\" should be a token", x);
2705 psp->errorcnt++;
2706 }else{
2707 (void)Symbol_new(x);
2708 }
2709 break;
drhe09daa92006-06-10 13:29:31 +00002710 case WAITING_FOR_WILDCARD_ID:
2711 if( x[0]=='.' ){
2712 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002713 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002714 ErrorMsg(psp->filename, psp->tokenlineno,
2715 "%%wildcard argument \"%s\" should be a token", x);
2716 psp->errorcnt++;
2717 }else{
2718 struct symbol *sp = Symbol_new(x);
2719 if( psp->gp->wildcard==0 ){
2720 psp->gp->wildcard = sp;
2721 }else{
2722 ErrorMsg(psp->filename, psp->tokenlineno,
2723 "Extra wildcard to token: %s", x);
2724 psp->errorcnt++;
2725 }
2726 }
2727 break;
drh61f92cd2014-01-11 03:06:18 +00002728 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002729 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002730 ErrorMsg(psp->filename, psp->tokenlineno,
2731 "%%token_class must be followed by an identifier: ", x);
2732 psp->errorcnt++;
2733 psp->state = RESYNC_AFTER_DECL_ERROR;
2734 }else if( Symbol_find(x) ){
2735 ErrorMsg(psp->filename, psp->tokenlineno,
2736 "Symbol \"%s\" already used", x);
2737 psp->errorcnt++;
2738 psp->state = RESYNC_AFTER_DECL_ERROR;
2739 }else{
2740 psp->tkclass = Symbol_new(x);
2741 psp->tkclass->type = MULTITERMINAL;
2742 psp->state = WAITING_FOR_CLASS_TOKEN;
2743 }
2744 break;
2745 case WAITING_FOR_CLASS_TOKEN:
2746 if( x[0]=='.' ){
2747 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002748 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002749 struct symbol *msp = psp->tkclass;
2750 msp->nsubsym++;
2751 msp->subsym = (struct symbol **) realloc(msp->subsym,
2752 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002753 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002754 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2755 }else{
2756 ErrorMsg(psp->filename, psp->tokenlineno,
2757 "%%token_class argument \"%s\" should be a token", x);
2758 psp->errorcnt++;
2759 psp->state = RESYNC_AFTER_DECL_ERROR;
2760 }
2761 break;
drh75897232000-05-29 14:26:00 +00002762 case RESYNC_AFTER_RULE_ERROR:
2763/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2764** break; */
2765 case RESYNC_AFTER_DECL_ERROR:
2766 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2767 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2768 break;
2769 }
2770}
2771
drh34ff57b2008-07-14 12:27:51 +00002772/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002773** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2774** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2775** comments them out. Text in between is also commented out as appropriate.
2776*/
danielk1977940fac92005-01-23 22:41:37 +00002777static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002778 int i, j, k, n;
2779 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002780 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002781 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002782 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002783 for(i=0; z[i]; i++){
2784 if( z[i]=='\n' ) lineno++;
2785 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002786 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002787 if( exclude ){
2788 exclude--;
2789 if( exclude==0 ){
2790 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2791 }
2792 }
2793 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002794 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2795 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002796 if( exclude ){
2797 exclude++;
2798 }else{
drhc56fac72015-10-29 13:48:15 +00002799 for(j=i+7; ISSPACE(z[j]); j++){}
2800 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002801 exclude = 1;
2802 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002803 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002804 exclude = 0;
2805 break;
2806 }
2807 }
2808 if( z[i+3]=='n' ) exclude = !exclude;
2809 if( exclude ){
2810 start = i;
2811 start_lineno = lineno;
2812 }
2813 }
2814 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2815 }
2816 }
2817 if( exclude ){
2818 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2819 exit(1);
2820 }
2821}
2822
drh75897232000-05-29 14:26:00 +00002823/* In spite of its name, this function is really a scanner. It read
2824** in the entire input file (all at once) then tokenizes it. Each
2825** token is passed to the function "parseonetoken" which builds all
2826** the appropriate data structures in the global state vector "gp".
2827*/
icculus9e44cf12010-02-14 17:14:22 +00002828void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002829{
2830 struct pstate ps;
2831 FILE *fp;
2832 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002833 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002834 int lineno;
2835 int c;
2836 char *cp, *nextcp;
2837 int startline = 0;
2838
rse38514a92007-09-20 11:34:17 +00002839 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002840 ps.gp = gp;
2841 ps.filename = gp->filename;
2842 ps.errorcnt = 0;
2843 ps.state = INITIALIZE;
2844
2845 /* Begin by reading the input file */
2846 fp = fopen(ps.filename,"rb");
2847 if( fp==0 ){
2848 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2849 gp->errorcnt++;
2850 return;
2851 }
2852 fseek(fp,0,2);
2853 filesize = ftell(fp);
2854 rewind(fp);
2855 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002856 if( filesize>100000000 || filebuf==0 ){
2857 ErrorMsg(ps.filename,0,"Input file too large.");
mistachkinc93c6142018-09-08 16:55:18 +00002858 free(filebuf);
drh75897232000-05-29 14:26:00 +00002859 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002860 fclose(fp);
drh75897232000-05-29 14:26:00 +00002861 return;
2862 }
2863 if( fread(filebuf,1,filesize,fp)!=filesize ){
2864 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2865 filesize);
2866 free(filebuf);
2867 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002868 fclose(fp);
drh75897232000-05-29 14:26:00 +00002869 return;
2870 }
2871 fclose(fp);
2872 filebuf[filesize] = 0;
2873
drh6d08b4d2004-07-20 12:45:22 +00002874 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2875 preprocess_input(filebuf);
2876
drh75897232000-05-29 14:26:00 +00002877 /* Now scan the text of the input file */
2878 lineno = 1;
2879 for(cp=filebuf; (c= *cp)!=0; ){
2880 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002881 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002882 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2883 cp+=2;
2884 while( (c= *cp)!=0 && c!='\n' ) cp++;
2885 continue;
2886 }
2887 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2888 cp+=2;
2889 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2890 if( c=='\n' ) lineno++;
2891 cp++;
2892 }
2893 if( c ) cp++;
2894 continue;
2895 }
2896 ps.tokenstart = cp; /* Mark the beginning of the token */
2897 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2898 if( c=='\"' ){ /* String literals */
2899 cp++;
2900 while( (c= *cp)!=0 && c!='\"' ){
2901 if( c=='\n' ) lineno++;
2902 cp++;
2903 }
2904 if( c==0 ){
2905 ErrorMsg(ps.filename,startline,
2906"String starting on this line is not terminated before the end of the file.");
2907 ps.errorcnt++;
2908 nextcp = cp;
2909 }else{
2910 nextcp = cp+1;
2911 }
2912 }else if( c=='{' ){ /* A block of C code */
2913 int level;
2914 cp++;
2915 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2916 if( c=='\n' ) lineno++;
2917 else if( c=='{' ) level++;
2918 else if( c=='}' ) level--;
2919 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2920 int prevc;
2921 cp = &cp[2];
2922 prevc = 0;
2923 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2924 if( c=='\n' ) lineno++;
2925 prevc = c;
2926 cp++;
drhf2f105d2012-08-20 15:53:54 +00002927 }
2928 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002929 cp = &cp[2];
2930 while( (c= *cp)!=0 && c!='\n' ) cp++;
2931 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002932 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002933 int startchar, prevc;
2934 startchar = c;
2935 prevc = 0;
2936 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2937 if( c=='\n' ) lineno++;
2938 if( prevc=='\\' ) prevc = 0;
2939 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002940 }
2941 }
drh75897232000-05-29 14:26:00 +00002942 }
2943 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002944 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002945"C code starting on this line is not terminated before the end of the file.");
2946 ps.errorcnt++;
2947 nextcp = cp;
2948 }else{
2949 nextcp = cp+1;
2950 }
drhc56fac72015-10-29 13:48:15 +00002951 }else if( ISALNUM(c) ){ /* Identifiers */
2952 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002953 nextcp = cp;
2954 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2955 cp += 3;
2956 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002957 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002958 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002959 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002960 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002961 }else{ /* All other (one character) operators */
2962 cp++;
2963 nextcp = cp;
2964 }
2965 c = *cp;
2966 *cp = 0; /* Null terminate the token */
2967 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002968 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002969 cp = nextcp;
2970 }
2971 free(filebuf); /* Release the buffer after parsing */
2972 gp->rule = ps.firstrule;
2973 gp->errorcnt = ps.errorcnt;
2974}
2975/*************************** From the file "plink.c" *********************/
2976/*
2977** Routines processing configuration follow-set propagation links
2978** in the LEMON parser generator.
2979*/
2980static struct plink *plink_freelist = 0;
2981
2982/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00002983struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00002984 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002985
2986 if( plink_freelist==0 ){
2987 int i;
2988 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002989 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002990 if( plink_freelist==0 ){
2991 fprintf(stderr,
2992 "Unable to allocate memory for a new follow-set propagation link.\n");
2993 exit(1);
2994 }
2995 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2996 plink_freelist[amt-1].next = 0;
2997 }
icculus9e44cf12010-02-14 17:14:22 +00002998 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002999 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00003000 return newlink;
drh75897232000-05-29 14:26:00 +00003001}
3002
3003/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00003004void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00003005{
icculus9e44cf12010-02-14 17:14:22 +00003006 struct plink *newlink;
3007 newlink = Plink_new();
3008 newlink->next = *plpp;
3009 *plpp = newlink;
3010 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00003011}
3012
3013/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00003014void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00003015{
3016 struct plink *nextpl;
3017 while( from ){
3018 nextpl = from->next;
3019 from->next = *to;
3020 *to = from;
3021 from = nextpl;
3022 }
3023}
3024
3025/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00003026void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00003027{
3028 struct plink *nextpl;
3029
3030 while( plp ){
3031 nextpl = plp->next;
3032 plp->next = plink_freelist;
3033 plink_freelist = plp;
3034 plp = nextpl;
3035 }
3036}
3037/*********************** From the file "report.c" **************************/
3038/*
3039** Procedures for generating reports and tables in the LEMON parser generator.
3040*/
3041
3042/* Generate a filename with the given suffix. Space to hold the
3043** name comes from malloc() and must be freed by the calling
3044** function.
3045*/
icculus9e44cf12010-02-14 17:14:22 +00003046PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00003047{
3048 char *name;
3049 char *cp;
drh9f88e6d2018-04-20 20:47:49 +00003050 char *filename = lemp->filename;
3051 int sz;
drh75897232000-05-29 14:26:00 +00003052
drh9f88e6d2018-04-20 20:47:49 +00003053 if( outputDir ){
3054 cp = strrchr(filename, '/');
3055 if( cp ) filename = cp + 1;
3056 }
3057 sz = lemonStrlen(filename);
3058 sz += lemonStrlen(suffix);
3059 if( outputDir ) sz += lemonStrlen(outputDir) + 1;
3060 sz += 5;
3061 name = (char*)malloc( sz );
drh75897232000-05-29 14:26:00 +00003062 if( name==0 ){
3063 fprintf(stderr,"Can't allocate space for a filename.\n");
3064 exit(1);
3065 }
drh9f88e6d2018-04-20 20:47:49 +00003066 name[0] = 0;
3067 if( outputDir ){
3068 lemon_strcpy(name, outputDir);
3069 lemon_strcat(name, "/");
3070 }
3071 lemon_strcat(name,filename);
drh75897232000-05-29 14:26:00 +00003072 cp = strrchr(name,'.');
3073 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003074 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003075 return name;
3076}
3077
3078/* Open a file with a name based on the name of the input file,
3079** but with a different (specified) suffix, and return a pointer
3080** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003081PRIVATE FILE *file_open(
3082 struct lemon *lemp,
3083 const char *suffix,
3084 const char *mode
3085){
drh75897232000-05-29 14:26:00 +00003086 FILE *fp;
3087
3088 if( lemp->outname ) free(lemp->outname);
3089 lemp->outname = file_makename(lemp, suffix);
3090 fp = fopen(lemp->outname,mode);
3091 if( fp==0 && *mode=='w' ){
3092 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3093 lemp->errorcnt++;
3094 return 0;
3095 }
3096 return fp;
3097}
3098
drh5c8241b2017-12-24 23:38:10 +00003099/* Print the text of a rule
3100*/
3101void rule_print(FILE *out, struct rule *rp){
3102 int i, j;
3103 fprintf(out, "%s",rp->lhs->name);
3104 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3105 fprintf(out," ::=");
3106 for(i=0; i<rp->nrhs; i++){
3107 struct symbol *sp = rp->rhs[i];
3108 if( sp->type==MULTITERMINAL ){
3109 fprintf(out," %s", sp->subsym[0]->name);
3110 for(j=1; j<sp->nsubsym; j++){
3111 fprintf(out,"|%s", sp->subsym[j]->name);
3112 }
3113 }else{
3114 fprintf(out," %s", sp->name);
3115 }
3116 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3117 }
3118}
3119
drh06f60d82017-04-14 19:46:12 +00003120/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003121** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003122void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003123{
3124 struct rule *rp;
3125 struct symbol *sp;
3126 int i, j, maxlen, len, ncolumns, skip;
3127 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3128 maxlen = 10;
3129 for(i=0; i<lemp->nsymbol; i++){
3130 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003131 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003132 if( len>maxlen ) maxlen = len;
3133 }
3134 ncolumns = 76/(maxlen+5);
3135 if( ncolumns<1 ) ncolumns = 1;
3136 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3137 for(i=0; i<skip; i++){
3138 printf("//");
3139 for(j=i; j<lemp->nsymbol; j+=skip){
3140 sp = lemp->symbols[j];
3141 assert( sp->index==j );
3142 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3143 }
3144 printf("\n");
3145 }
3146 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003147 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003148 printf(".");
3149 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003150 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003151 printf("\n");
3152 }
3153}
3154
drh7e698e92015-09-07 14:22:24 +00003155/* Print a single rule.
3156*/
3157void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003158 struct symbol *sp;
3159 int i, j;
drh75897232000-05-29 14:26:00 +00003160 fprintf(fp,"%s ::=",rp->lhs->name);
3161 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003162 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003163 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003164 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003165 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003166 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003167 for(j=1; j<sp->nsubsym; j++){
3168 fprintf(fp,"|%s",sp->subsym[j]->name);
3169 }
drh61f92cd2014-01-11 03:06:18 +00003170 }else{
3171 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003172 }
drh75897232000-05-29 14:26:00 +00003173 }
3174}
3175
drh7e698e92015-09-07 14:22:24 +00003176/* Print the rule for a configuration.
3177*/
3178void ConfigPrint(FILE *fp, struct config *cfp){
3179 RulePrint(fp, cfp->rp, cfp->dot);
3180}
3181
drh75897232000-05-29 14:26:00 +00003182/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003183#if 0
drh75897232000-05-29 14:26:00 +00003184/* Print a set */
3185PRIVATE void SetPrint(out,set,lemp)
3186FILE *out;
3187char *set;
3188struct lemon *lemp;
3189{
3190 int i;
3191 char *spacer;
3192 spacer = "";
3193 fprintf(out,"%12s[","");
3194 for(i=0; i<lemp->nterminal; i++){
3195 if( SetFind(set,i) ){
3196 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3197 spacer = " ";
3198 }
3199 }
3200 fprintf(out,"]\n");
3201}
3202
3203/* Print a plink chain */
3204PRIVATE void PlinkPrint(out,plp,tag)
3205FILE *out;
3206struct plink *plp;
3207char *tag;
3208{
3209 while( plp ){
drhada354d2005-11-05 15:03:59 +00003210 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003211 ConfigPrint(out,plp->cfp);
3212 fprintf(out,"\n");
3213 plp = plp->next;
3214 }
3215}
3216#endif
3217
3218/* Print an action to the given file descriptor. Return FALSE if
3219** nothing was actually printed.
3220*/
drh7e698e92015-09-07 14:22:24 +00003221int PrintAction(
3222 struct action *ap, /* The action to print */
3223 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003224 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003225){
drh75897232000-05-29 14:26:00 +00003226 int result = 1;
3227 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003228 case SHIFT: {
3229 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003230 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003231 break;
drh7e698e92015-09-07 14:22:24 +00003232 }
3233 case REDUCE: {
3234 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003235 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003236 RulePrint(fp, rp, -1);
3237 break;
3238 }
3239 case SHIFTREDUCE: {
3240 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003241 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003242 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003243 break;
drh7e698e92015-09-07 14:22:24 +00003244 }
drh75897232000-05-29 14:26:00 +00003245 case ACCEPT:
3246 fprintf(fp,"%*s accept",indent,ap->sp->name);
3247 break;
3248 case ERROR:
3249 fprintf(fp,"%*s error",indent,ap->sp->name);
3250 break;
drh9892c5d2007-12-21 00:02:11 +00003251 case SRCONFLICT:
3252 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003253 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003254 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003255 break;
drh9892c5d2007-12-21 00:02:11 +00003256 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003257 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003258 indent,ap->sp->name,ap->x.stp->statenum);
3259 break;
drh75897232000-05-29 14:26:00 +00003260 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003261 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003262 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003263 indent,ap->sp->name,ap->x.stp->statenum);
3264 }else{
3265 result = 0;
3266 }
3267 break;
drh75897232000-05-29 14:26:00 +00003268 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003269 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003270 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003271 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003272 }else{
3273 result = 0;
3274 }
3275 break;
drh75897232000-05-29 14:26:00 +00003276 case NOT_USED:
3277 result = 0;
3278 break;
3279 }
drhc173ad82016-05-23 16:15:02 +00003280 if( result && ap->spOpt ){
3281 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3282 }
drh75897232000-05-29 14:26:00 +00003283 return result;
3284}
3285
drh3bd48ab2015-09-07 18:23:37 +00003286/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003287void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003288{
drh539e7412018-04-21 20:24:19 +00003289 int i, n;
drh75897232000-05-29 14:26:00 +00003290 struct state *stp;
3291 struct config *cfp;
3292 struct action *ap;
drh12f68392018-04-06 19:12:55 +00003293 struct rule *rp;
drh75897232000-05-29 14:26:00 +00003294 FILE *fp;
3295
drh2aa6ca42004-09-10 00:14:04 +00003296 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003297 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003298 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003299 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003300 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003301 if( lemp->basisflag ) cfp=stp->bp;
3302 else cfp=stp->cfp;
3303 while( cfp ){
3304 char buf[20];
3305 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003306 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003307 fprintf(fp," %5s ",buf);
3308 }else{
3309 fprintf(fp," ");
3310 }
3311 ConfigPrint(fp,cfp);
3312 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003313#if 0
drh75897232000-05-29 14:26:00 +00003314 SetPrint(fp,cfp->fws,lemp);
3315 PlinkPrint(fp,cfp->fplp,"To ");
3316 PlinkPrint(fp,cfp->bplp,"From");
3317#endif
3318 if( lemp->basisflag ) cfp=cfp->bp;
3319 else cfp=cfp->next;
3320 }
3321 fprintf(fp,"\n");
3322 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003323 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003324 }
3325 fprintf(fp,"\n");
3326 }
drhe9278182007-07-18 18:16:29 +00003327 fprintf(fp, "----------------------------------------------------\n");
3328 fprintf(fp, "Symbols:\n");
drh539e7412018-04-21 20:24:19 +00003329 fprintf(fp, "The first-set of non-terminals is shown after the name.\n\n");
drhe9278182007-07-18 18:16:29 +00003330 for(i=0; i<lemp->nsymbol; i++){
3331 int j;
3332 struct symbol *sp;
3333
3334 sp = lemp->symbols[i];
3335 fprintf(fp, " %3d: %s", i, sp->name);
3336 if( sp->type==NONTERMINAL ){
3337 fprintf(fp, ":");
3338 if( sp->lambda ){
3339 fprintf(fp, " <lambda>");
3340 }
3341 for(j=0; j<lemp->nterminal; j++){
3342 if( sp->firstset && SetFind(sp->firstset, j) ){
3343 fprintf(fp, " %s", lemp->symbols[j]->name);
3344 }
3345 }
3346 }
drh12f68392018-04-06 19:12:55 +00003347 if( sp->prec>=0 ) fprintf(fp," (precedence=%d)", sp->prec);
drhe9278182007-07-18 18:16:29 +00003348 fprintf(fp, "\n");
3349 }
drh12f68392018-04-06 19:12:55 +00003350 fprintf(fp, "----------------------------------------------------\n");
drh539e7412018-04-21 20:24:19 +00003351 fprintf(fp, "Syntax-only Symbols:\n");
3352 fprintf(fp, "The following symbols never carry semantic content.\n\n");
3353 for(i=n=0; i<lemp->nsymbol; i++){
3354 int w;
3355 struct symbol *sp = lemp->symbols[i];
3356 if( sp->bContent ) continue;
3357 w = (int)strlen(sp->name);
3358 if( n>0 && n+w>75 ){
3359 fprintf(fp,"\n");
3360 n = 0;
3361 }
3362 if( n>0 ){
3363 fprintf(fp, " ");
3364 n++;
3365 }
3366 fprintf(fp, "%s", sp->name);
3367 n += w;
3368 }
3369 if( n>0 ) fprintf(fp, "\n");
3370 fprintf(fp, "----------------------------------------------------\n");
drh12f68392018-04-06 19:12:55 +00003371 fprintf(fp, "Rules:\n");
3372 for(rp=lemp->rule; rp; rp=rp->next){
3373 fprintf(fp, "%4d: ", rp->iRule);
3374 rule_print(fp, rp);
3375 fprintf(fp,".");
3376 if( rp->precsym ){
3377 fprintf(fp," [%s precedence=%d]",
3378 rp->precsym->name, rp->precsym->prec);
3379 }
3380 fprintf(fp,"\n");
3381 }
drh75897232000-05-29 14:26:00 +00003382 fclose(fp);
3383 return;
3384}
3385
3386/* Search for the file "name" which is in the same directory as
3387** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003388PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003389{
icculus9e44cf12010-02-14 17:14:22 +00003390 const char *pathlist;
3391 char *pathbufptr;
3392 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003393 char *path,*cp;
3394 char c;
drh75897232000-05-29 14:26:00 +00003395
3396#ifdef __WIN32__
3397 cp = strrchr(argv0,'\\');
3398#else
3399 cp = strrchr(argv0,'/');
3400#endif
3401 if( cp ){
3402 c = *cp;
3403 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003404 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003405 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003406 *cp = c;
3407 }else{
drh75897232000-05-29 14:26:00 +00003408 pathlist = getenv("PATH");
3409 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003410 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003411 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003412 if( (pathbuf != 0) && (path!=0) ){
3413 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003414 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003415 while( *pathbuf ){
3416 cp = strchr(pathbuf,':');
3417 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003418 c = *cp;
3419 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003420 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003421 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003422 if( c==0 ) pathbuf[0] = 0;
3423 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003424 if( access(path,modemask)==0 ) break;
3425 }
icculus9e44cf12010-02-14 17:14:22 +00003426 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003427 }
3428 }
3429 return path;
3430}
3431
3432/* Given an action, compute the integer value for that action
3433** which is to be put in the action table of the generated machine.
3434** Return negative if no action should be generated.
3435*/
icculus9e44cf12010-02-14 17:14:22 +00003436PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003437{
3438 int act;
3439 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003440 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003441 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003442 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3443 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3444 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003445 if( ap->sp->index>=lemp->nterminal ){
3446 act = lemp->minReduce + ap->x.rp->iRule;
3447 }else{
3448 act = lemp->minShiftReduce + ap->x.rp->iRule;
3449 }
drhbd8fcc12017-06-28 11:56:18 +00003450 break;
3451 }
drh5c8241b2017-12-24 23:38:10 +00003452 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3453 case ERROR: act = lemp->errAction; break;
3454 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003455 default: act = -1; break;
3456 }
3457 return act;
3458}
3459
3460#define LINESIZE 1000
3461/* The next cluster of routines are for reading the template file
3462** and writing the results to the generated parser */
3463/* The first function transfers data from "in" to "out" until
3464** a line is seen which begins with "%%". The line number is
3465** tracked.
3466**
3467** if name!=0, then any word that begin with "Parse" is changed to
3468** begin with *name instead.
3469*/
icculus9e44cf12010-02-14 17:14:22 +00003470PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003471{
3472 int i, iStart;
3473 char line[LINESIZE];
3474 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3475 (*lineno)++;
3476 iStart = 0;
3477 if( name ){
3478 for(i=0; line[i]; i++){
3479 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003480 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003481 ){
3482 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3483 fprintf(out,"%s",name);
3484 i += 4;
3485 iStart = i+1;
3486 }
3487 }
3488 }
3489 fprintf(out,"%s",&line[iStart]);
3490 }
3491}
3492
3493/* The next function finds the template file and opens it, returning
3494** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003495PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003496{
3497 static char templatename[] = "lempar.c";
3498 char buf[1000];
3499 FILE *in;
3500 char *tpltname;
3501 char *cp;
3502
icculus3e143bd2010-02-14 00:48:49 +00003503 /* first, see if user specified a template filename on the command line. */
3504 if (user_templatename != 0) {
3505 if( access(user_templatename,004)==-1 ){
3506 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3507 user_templatename);
3508 lemp->errorcnt++;
3509 return 0;
3510 }
3511 in = fopen(user_templatename,"rb");
3512 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003513 fprintf(stderr,"Can't open the template file \"%s\".\n",
3514 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003515 lemp->errorcnt++;
3516 return 0;
3517 }
3518 return in;
3519 }
3520
drh75897232000-05-29 14:26:00 +00003521 cp = strrchr(lemp->filename,'.');
3522 if( cp ){
drh898799f2014-01-10 23:21:00 +00003523 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003524 }else{
drh898799f2014-01-10 23:21:00 +00003525 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003526 }
3527 if( access(buf,004)==0 ){
3528 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003529 }else if( access(templatename,004)==0 ){
3530 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003531 }else{
3532 tpltname = pathsearch(lemp->argv0,templatename,0);
3533 }
3534 if( tpltname==0 ){
3535 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3536 templatename);
3537 lemp->errorcnt++;
3538 return 0;
3539 }
drh2aa6ca42004-09-10 00:14:04 +00003540 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003541 if( in==0 ){
3542 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3543 lemp->errorcnt++;
3544 return 0;
3545 }
3546 return in;
3547}
3548
drhaf805ca2004-09-07 11:28:25 +00003549/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003550PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003551{
3552 fprintf(out,"#line %d \"",lineno);
3553 while( *filename ){
3554 if( *filename == '\\' ) putc('\\',out);
3555 putc(*filename,out);
3556 filename++;
3557 }
3558 fprintf(out,"\"\n");
3559}
3560
drh75897232000-05-29 14:26:00 +00003561/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003562PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003563{
3564 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003565 while( *str ){
drh75897232000-05-29 14:26:00 +00003566 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003567 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003568 str++;
3569 }
drh9db55df2004-09-09 14:01:21 +00003570 if( str[-1]!='\n' ){
3571 putc('\n',out);
3572 (*lineno)++;
3573 }
shane58543932008-12-10 20:10:04 +00003574 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003575 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003576 }
drh75897232000-05-29 14:26:00 +00003577 return;
3578}
3579
3580/*
3581** The following routine emits code for the destructor for the
3582** symbol sp
3583*/
icculus9e44cf12010-02-14 17:14:22 +00003584void emit_destructor_code(
3585 FILE *out,
3586 struct symbol *sp,
3587 struct lemon *lemp,
3588 int *lineno
3589){
drhcc83b6e2004-04-23 23:38:42 +00003590 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003591
drh75897232000-05-29 14:26:00 +00003592 if( sp->type==TERMINAL ){
3593 cp = lemp->tokendest;
3594 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003595 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003596 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003597 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003598 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003599 if( !lemp->nolinenosflag ){
3600 (*lineno)++;
3601 tplt_linedir(out,sp->destLineno,lemp->filename);
3602 }
drh960e8c62001-04-03 16:53:21 +00003603 }else if( lemp->vardest ){
3604 cp = lemp->vardest;
3605 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003606 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003607 }else{
3608 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003609 }
3610 for(; *cp; cp++){
3611 if( *cp=='$' && cp[1]=='$' ){
3612 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3613 cp++;
3614 continue;
3615 }
shane58543932008-12-10 20:10:04 +00003616 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003617 fputc(*cp,out);
3618 }
shane58543932008-12-10 20:10:04 +00003619 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003620 if (!lemp->nolinenosflag) {
3621 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003622 }
3623 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003624 return;
3625}
3626
3627/*
drh960e8c62001-04-03 16:53:21 +00003628** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003629*/
icculus9e44cf12010-02-14 17:14:22 +00003630int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003631{
3632 int ret;
3633 if( sp->type==TERMINAL ){
3634 ret = lemp->tokendest!=0;
3635 }else{
drh960e8c62001-04-03 16:53:21 +00003636 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003637 }
3638 return ret;
3639}
3640
drh0bb132b2004-07-20 14:06:51 +00003641/*
3642** Append text to a dynamically allocated string. If zText is 0 then
3643** reset the string to be empty again. Always return the complete text
3644** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003645**
3646** n bytes of zText are stored. If n==0 then all of zText up to the first
3647** \000 terminator is stored. zText can contain up to two instances of
3648** %d. The values of p1 and p2 are written into the first and second
3649** %d.
3650**
3651** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003652*/
icculus9e44cf12010-02-14 17:14:22 +00003653PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3654 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003655 static char *z = 0;
3656 static int alloced = 0;
3657 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003658 int c;
drh0bb132b2004-07-20 14:06:51 +00003659 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003660 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003661 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003662 used = 0;
3663 return z;
3664 }
drh7ac25c72004-08-19 15:12:26 +00003665 if( n<=0 ){
3666 if( n<0 ){
3667 used += n;
3668 assert( used>=0 );
3669 }
drh87cf1372008-08-13 20:09:06 +00003670 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003671 }
drhdf609712010-11-23 20:55:27 +00003672 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003673 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003674 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003675 }
icculus9e44cf12010-02-14 17:14:22 +00003676 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003677 while( n-- > 0 ){
3678 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003679 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003680 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003681 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003682 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003683 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003684 zText++;
3685 n--;
3686 }else{
mistachkin2318d332015-01-12 18:02:52 +00003687 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003688 }
3689 }
3690 z[used] = 0;
3691 return z;
3692}
3693
3694/*
drh711c9812016-05-23 14:24:31 +00003695** Write and transform the rp->code string so that symbols are expanded.
3696** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003697**
3698** Return 1 if the expanded code requires that "yylhsminor" local variable
3699** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003700*/
drhdabd04c2016-02-17 01:46:19 +00003701PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003702 char *cp, *xp;
3703 int i;
drhcf82f0d2016-02-17 04:33:10 +00003704 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003705 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003706 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3707 char lhsused = 0; /* True if the LHS element has been used */
3708 char lhsdirect; /* True if LHS writes directly into stack */
3709 char used[MAXRHS]; /* True for each RHS element which is used */
3710 char zLhs[50]; /* Convert the LHS symbol into this string */
3711 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003712
3713 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3714 lhsused = 0;
3715
drh19c9e562007-03-29 20:13:53 +00003716 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003717 static char newlinestr[2] = { '\n', '\0' };
3718 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003719 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003720 rp->noCode = 1;
3721 }else{
3722 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003723 }
3724
drh4dd0d3f2016-02-17 01:18:33 +00003725
drh2e55b042016-04-30 17:19:30 +00003726 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003727 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3728 lhsdirect = 1;
3729 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003730 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003731 ** we have to call the distructor on the RHS symbol first. */
3732 lhsdirect = 1;
3733 if( has_destructor(rp->rhs[0],lemp) ){
3734 append_str(0,0,0,0);
3735 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3736 rp->rhs[0]->index,1-rp->nrhs);
3737 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003738 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003739 }
drh2e55b042016-04-30 17:19:30 +00003740 }else if( rp->lhsalias==0 ){
3741 /* There is no LHS value symbol. */
3742 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003743 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003744 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003745 ** direct writing is allowed */
3746 lhsdirect = 1;
3747 lhsused = 1;
3748 used[0] = 1;
3749 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3750 ErrorMsg(lemp->filename,rp->ruleline,
3751 "%s(%s) and %s(%s) share the same label but have "
3752 "different datatypes.",
3753 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3754 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003755 }
drh4dd0d3f2016-02-17 01:18:33 +00003756 }else{
drhcf82f0d2016-02-17 04:33:10 +00003757 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3758 rp->lhsalias, rp->rhsalias[0]);
3759 zSkip = strstr(rp->code, zOvwrt);
3760 if( zSkip!=0 ){
3761 /* The code contains a special comment that indicates that it is safe
3762 ** for the LHS label to overwrite left-most RHS label. */
3763 lhsdirect = 1;
3764 }else{
3765 lhsdirect = 0;
3766 }
drh4dd0d3f2016-02-17 01:18:33 +00003767 }
3768 if( lhsdirect ){
3769 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3770 }else{
drhdabd04c2016-02-17 01:46:19 +00003771 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003772 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3773 }
3774
drh0bb132b2004-07-20 14:06:51 +00003775 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003776
3777 /* This const cast is wrong but harmless, if we're careful. */
3778 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003779 if( cp==zSkip ){
3780 append_str(zOvwrt,0,0,0);
3781 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003782 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003783 continue;
3784 }
drhc56fac72015-10-29 13:48:15 +00003785 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003786 char saved;
drhc56fac72015-10-29 13:48:15 +00003787 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003788 saved = *xp;
3789 *xp = 0;
3790 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003791 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003792 cp = xp;
3793 lhsused = 1;
3794 }else{
3795 for(i=0; i<rp->nrhs; i++){
3796 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003797 if( i==0 && dontUseRhs0 ){
3798 ErrorMsg(lemp->filename,rp->ruleline,
3799 "Label %s used after '%s'.",
3800 rp->rhsalias[0], zOvwrt);
3801 lemp->errorcnt++;
3802 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003803 /* If the argument is of the form @X then substituted
3804 ** the token number of X, not the value of X */
3805 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3806 }else{
drhfd405312005-11-06 04:06:59 +00003807 struct symbol *sp = rp->rhs[i];
3808 int dtnum;
3809 if( sp->type==MULTITERMINAL ){
3810 dtnum = sp->subsym[0]->dtnum;
3811 }else{
3812 dtnum = sp->dtnum;
3813 }
3814 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003815 }
drh0bb132b2004-07-20 14:06:51 +00003816 cp = xp;
3817 used[i] = 1;
3818 break;
3819 }
3820 }
3821 }
3822 *xp = saved;
3823 }
3824 append_str(cp, 1, 0, 0);
3825 } /* End loop */
3826
drh4dd0d3f2016-02-17 01:18:33 +00003827 /* Main code generation completed */
3828 cp = append_str(0,0,0,0);
3829 if( cp && cp[0] ) rp->code = Strsafe(cp);
3830 append_str(0,0,0,0);
3831
drh0bb132b2004-07-20 14:06:51 +00003832 /* Check to make sure the LHS has been used */
3833 if( rp->lhsalias && !lhsused ){
3834 ErrorMsg(lemp->filename,rp->ruleline,
3835 "Label \"%s\" for \"%s(%s)\" is never used.",
3836 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3837 lemp->errorcnt++;
3838 }
3839
drh4dd0d3f2016-02-17 01:18:33 +00003840 /* Generate destructor code for RHS minor values which are not referenced.
3841 ** Generate error messages for unused labels and duplicate labels.
3842 */
drh0bb132b2004-07-20 14:06:51 +00003843 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003844 if( rp->rhsalias[i] ){
3845 if( i>0 ){
3846 int j;
3847 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3848 ErrorMsg(lemp->filename,rp->ruleline,
3849 "%s(%s) has the same label as the LHS but is not the left-most "
3850 "symbol on the RHS.",
drhf135cb72019-04-30 14:26:31 +00003851 rp->rhs[i]->name, rp->rhsalias[i]);
drh4dd0d3f2016-02-17 01:18:33 +00003852 lemp->errorcnt++;
3853 }
3854 for(j=0; j<i; j++){
3855 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3856 ErrorMsg(lemp->filename,rp->ruleline,
3857 "Label %s used for multiple symbols on the RHS of a rule.",
3858 rp->rhsalias[i]);
3859 lemp->errorcnt++;
3860 break;
3861 }
3862 }
drh0bb132b2004-07-20 14:06:51 +00003863 }
drh4dd0d3f2016-02-17 01:18:33 +00003864 if( !used[i] ){
3865 ErrorMsg(lemp->filename,rp->ruleline,
3866 "Label %s for \"%s(%s)\" is never used.",
3867 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3868 lemp->errorcnt++;
3869 }
3870 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3871 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3872 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003873 }
3874 }
drh4dd0d3f2016-02-17 01:18:33 +00003875
3876 /* If unable to write LHS values directly into the stack, write the
3877 ** saved LHS value now. */
3878 if( lhsdirect==0 ){
3879 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3880 append_str(zLhs, 0, 0, 0);
3881 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003882 }
drh4dd0d3f2016-02-17 01:18:33 +00003883
3884 /* Suffix code generation complete */
3885 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003886 if( cp && cp[0] ){
3887 rp->codeSuffix = Strsafe(cp);
3888 rp->noCode = 0;
3889 }
drhdabd04c2016-02-17 01:46:19 +00003890
3891 return rc;
drh0bb132b2004-07-20 14:06:51 +00003892}
3893
drh06f60d82017-04-14 19:46:12 +00003894/*
drh75897232000-05-29 14:26:00 +00003895** Generate code which executes when the rule "rp" is reduced. Write
3896** the code to "out". Make sure lineno stays up-to-date.
3897*/
icculus9e44cf12010-02-14 17:14:22 +00003898PRIVATE void emit_code(
3899 FILE *out,
3900 struct rule *rp,
3901 struct lemon *lemp,
3902 int *lineno
3903){
3904 const char *cp;
drh75897232000-05-29 14:26:00 +00003905
drh4dd0d3f2016-02-17 01:18:33 +00003906 /* Setup code prior to the #line directive */
3907 if( rp->codePrefix && rp->codePrefix[0] ){
3908 fprintf(out, "{%s", rp->codePrefix);
3909 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3910 }
3911
drh75897232000-05-29 14:26:00 +00003912 /* Generate code to do the reduce action */
3913 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003914 if( !lemp->nolinenosflag ){
3915 (*lineno)++;
3916 tplt_linedir(out,rp->line,lemp->filename);
3917 }
drhaf805ca2004-09-07 11:28:25 +00003918 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003919 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003920 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003921 if( !lemp->nolinenosflag ){
3922 (*lineno)++;
3923 tplt_linedir(out,*lineno,lemp->outname);
3924 }
drh4dd0d3f2016-02-17 01:18:33 +00003925 }
3926
3927 /* Generate breakdown code that occurs after the #line directive */
3928 if( rp->codeSuffix && rp->codeSuffix[0] ){
3929 fprintf(out, "%s", rp->codeSuffix);
3930 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3931 }
3932
3933 if( rp->codePrefix ){
3934 fprintf(out, "}\n"); (*lineno)++;
3935 }
drh75897232000-05-29 14:26:00 +00003936
drh75897232000-05-29 14:26:00 +00003937 return;
3938}
3939
3940/*
3941** Print the definition of the union used for the parser's data stack.
3942** This union contains fields for every possible data type for tokens
3943** and nonterminals. In the process of computing and printing this
3944** union, also set the ".dtnum" field of every terminal and nonterminal
3945** symbol.
3946*/
icculus9e44cf12010-02-14 17:14:22 +00003947void print_stack_union(
3948 FILE *out, /* The output stream */
3949 struct lemon *lemp, /* The main info structure for this parser */
3950 int *plineno, /* Pointer to the line number */
3951 int mhflag /* True if generating makeheaders output */
3952){
drh75897232000-05-29 14:26:00 +00003953 int lineno = *plineno; /* The line number of the output */
3954 char **types; /* A hash table of datatypes */
3955 int arraysize; /* Size of the "types" array */
3956 int maxdtlength; /* Maximum length of any ".datatype" field. */
3957 char *stddt; /* Standardized name for a datatype */
3958 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003959 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003960 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003961
3962 /* Allocate and initialize types[] and allocate stddt[] */
3963 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003964 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003965 if( types==0 ){
3966 fprintf(stderr,"Out of memory.\n");
3967 exit(1);
3968 }
drh75897232000-05-29 14:26:00 +00003969 for(i=0; i<arraysize; i++) types[i] = 0;
3970 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003971 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003972 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003973 }
drh75897232000-05-29 14:26:00 +00003974 for(i=0; i<lemp->nsymbol; i++){
3975 int len;
3976 struct symbol *sp = lemp->symbols[i];
3977 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003978 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003979 if( len>maxdtlength ) maxdtlength = len;
3980 }
3981 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003982 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003983 fprintf(stderr,"Out of memory.\n");
3984 exit(1);
3985 }
3986
3987 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3988 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003989 ** used for terminal symbols. If there is no %default_type defined then
3990 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3991 ** a datatype using the %type directive.
3992 */
drh75897232000-05-29 14:26:00 +00003993 for(i=0; i<lemp->nsymbol; i++){
3994 struct symbol *sp = lemp->symbols[i];
3995 char *cp;
3996 if( sp==lemp->errsym ){
3997 sp->dtnum = arraysize+1;
3998 continue;
3999 }
drh960e8c62001-04-03 16:53:21 +00004000 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00004001 sp->dtnum = 0;
4002 continue;
4003 }
4004 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00004005 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00004006 j = 0;
drhc56fac72015-10-29 13:48:15 +00004007 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00004008 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00004009 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00004010 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00004011 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00004012 sp->dtnum = 0;
4013 continue;
4014 }
drh75897232000-05-29 14:26:00 +00004015 hash = 0;
4016 for(j=0; stddt[j]; j++){
4017 hash = hash*53 + stddt[j];
4018 }
drh3b2129c2003-05-13 00:34:21 +00004019 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00004020 while( types[hash] ){
4021 if( strcmp(types[hash],stddt)==0 ){
4022 sp->dtnum = hash + 1;
4023 break;
4024 }
4025 hash++;
drh2b51f212013-10-11 23:01:02 +00004026 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00004027 }
4028 if( types[hash]==0 ){
4029 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00004030 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00004031 if( types[hash]==0 ){
4032 fprintf(stderr,"Out of memory.\n");
4033 exit(1);
4034 }
drh898799f2014-01-10 23:21:00 +00004035 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00004036 }
4037 }
4038
4039 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
4040 name = lemp->name ? lemp->name : "Parse";
4041 lineno = *plineno;
4042 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
4043 fprintf(out,"#define %sTOKENTYPE %s\n",name,
4044 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
4045 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
4046 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00004047 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004048 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
4049 for(i=0; i<arraysize; i++){
4050 if( types[i]==0 ) continue;
4051 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
4052 free(types[i]);
4053 }
drhed0c15b2018-04-16 14:31:34 +00004054 if( lemp->errsym && lemp->errsym->useCnt ){
drhc4dd3fd2008-01-22 01:48:05 +00004055 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
4056 }
drh75897232000-05-29 14:26:00 +00004057 free(stddt);
4058 free(types);
4059 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
4060 *plineno = lineno;
4061}
4062
drhb29b0a52002-02-23 19:39:46 +00004063/*
4064** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00004065** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
4066** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00004067*/
drhc75e0162015-09-07 02:23:02 +00004068static const char *minimum_size_type(int lwr, int upr, int *pnByte){
4069 const char *zType = "int";
4070 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00004071 if( lwr>=0 ){
4072 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00004073 zType = "unsigned char";
4074 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004075 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00004076 zType = "unsigned short int";
4077 nByte = 2;
drh8b582012003-10-21 13:16:03 +00004078 }else{
drhc75e0162015-09-07 02:23:02 +00004079 zType = "unsigned int";
4080 nByte = 4;
drh8b582012003-10-21 13:16:03 +00004081 }
4082 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00004083 zType = "signed char";
4084 nByte = 1;
drh8b582012003-10-21 13:16:03 +00004085 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00004086 zType = "short";
4087 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00004088 }
drhc75e0162015-09-07 02:23:02 +00004089 if( pnByte ) *pnByte = nByte;
4090 return zType;
drhb29b0a52002-02-23 19:39:46 +00004091}
4092
drhfdbf9282003-10-21 16:34:41 +00004093/*
4094** Each state contains a set of token transaction and a set of
4095** nonterminal transactions. Each of these sets makes an instance
4096** of the following structure. An array of these structures is used
4097** to order the creation of entries in the yy_action[] table.
4098*/
4099struct axset {
4100 struct state *stp; /* A pointer to a state */
4101 int isTkn; /* True to use tokens. False for non-terminals */
4102 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00004103 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00004104};
4105
4106/*
4107** Compare to axset structures for sorting purposes
4108*/
4109static int axset_compare(const void *a, const void *b){
4110 struct axset *p1 = (struct axset*)a;
4111 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004112 int c;
4113 c = p2->nAction - p1->nAction;
4114 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004115 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004116 }
4117 assert( c!=0 || p1==p2 );
4118 return c;
drhfdbf9282003-10-21 16:34:41 +00004119}
4120
drhc4dd3fd2008-01-22 01:48:05 +00004121/*
4122** Write text on "out" that describes the rule "rp".
4123*/
4124static void writeRuleText(FILE *out, struct rule *rp){
4125 int j;
4126 fprintf(out,"%s ::=", rp->lhs->name);
4127 for(j=0; j<rp->nrhs; j++){
4128 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004129 if( sp->type!=MULTITERMINAL ){
4130 fprintf(out," %s", sp->name);
4131 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004132 int k;
drh61f92cd2014-01-11 03:06:18 +00004133 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004134 for(k=1; k<sp->nsubsym; k++){
4135 fprintf(out,"|%s",sp->subsym[k]->name);
4136 }
4137 }
4138 }
4139}
4140
4141
drh75897232000-05-29 14:26:00 +00004142/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004143void ReportTable(
4144 struct lemon *lemp,
4145 int mhflag /* Output in makeheaders format if true */
4146){
drh75897232000-05-29 14:26:00 +00004147 FILE *out, *in;
4148 char line[LINESIZE];
4149 int lineno;
4150 struct state *stp;
4151 struct action *ap;
4152 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004153 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004154 int i, j, n, sz;
4155 int szActionType; /* sizeof(YYACTIONTYPE) */
4156 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004157 const char *name;
drh8b582012003-10-21 13:16:03 +00004158 int mnTknOfst, mxTknOfst;
4159 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004160 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004161
drh5c8241b2017-12-24 23:38:10 +00004162 lemp->minShiftReduce = lemp->nstate;
4163 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4164 lemp->accAction = lemp->errAction + 1;
4165 lemp->noAction = lemp->accAction + 1;
4166 lemp->minReduce = lemp->noAction + 1;
4167 lemp->maxAction = lemp->minReduce + lemp->nrule;
4168
drh75897232000-05-29 14:26:00 +00004169 in = tplt_open(lemp);
4170 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004171 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004172 if( out==0 ){
4173 fclose(in);
4174 return;
4175 }
4176 lineno = 1;
4177 tplt_xfer(lemp->name,in,out,&lineno);
4178
4179 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004180 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004181 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004182 char *incName = file_makename(lemp, ".h");
4183 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4184 free(incName);
drh75897232000-05-29 14:26:00 +00004185 }
4186 tplt_xfer(lemp->name,in,out,&lineno);
4187
4188 /* Generate #defines for all tokens */
4189 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004190 const char *prefix;
drh75897232000-05-29 14:26:00 +00004191 fprintf(out,"#if INTERFACE\n"); lineno++;
4192 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4193 else prefix = "";
4194 for(i=1; i<lemp->nterminal; i++){
4195 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4196 lineno++;
4197 }
4198 fprintf(out,"#endif\n"); lineno++;
4199 }
4200 tplt_xfer(lemp->name,in,out,&lineno);
4201
4202 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004203 fprintf(out,"#define YYCODETYPE %s\n",
drhed0c15b2018-04-16 14:31:34 +00004204 minimum_size_type(0, lemp->nsymbol, &szCodeType)); lineno++;
4205 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol); lineno++;
drh75897232000-05-29 14:26:00 +00004206 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004207 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004208 if( lemp->wildcard ){
4209 fprintf(out,"#define YYWILDCARD %d\n",
4210 lemp->wildcard->index); lineno++;
4211 }
drh75897232000-05-29 14:26:00 +00004212 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004213 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004214 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004215 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4216 }else{
4217 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4218 }
drhca44b5a2007-02-22 23:06:58 +00004219 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004220 if( mhflag ){
4221 fprintf(out,"#if INTERFACE\n"); lineno++;
4222 }
4223 name = lemp->name ? lemp->name : "Parse";
4224 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004225 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004226 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4227 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004228 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4229 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
drhfb32c442018-04-21 13:51:42 +00004230 fprintf(out,"#define %sARG_PARAM ,%s\n",name,&lemp->arg[i]); lineno++;
4231 fprintf(out,"#define %sARG_FETCH %s=yypParser->%s;\n",
drh1f245e42002-03-11 13:55:50 +00004232 name,lemp->arg,&lemp->arg[i]); lineno++;
drhfb32c442018-04-21 13:51:42 +00004233 fprintf(out,"#define %sARG_STORE yypParser->%s=%s;\n",
drh1f245e42002-03-11 13:55:50 +00004234 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004235 }else{
drhfb32c442018-04-21 13:51:42 +00004236 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4237 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4238 fprintf(out,"#define %sARG_PARAM\n",name); lineno++;
drh1f245e42002-03-11 13:55:50 +00004239 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4240 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004241 }
drhfb32c442018-04-21 13:51:42 +00004242 if( lemp->ctx && lemp->ctx[0] ){
4243 i = lemonStrlen(lemp->ctx);
4244 while( i>=1 && ISSPACE(lemp->ctx[i-1]) ) i--;
4245 while( i>=1 && (ISALNUM(lemp->ctx[i-1]) || lemp->ctx[i-1]=='_') ) i--;
4246 fprintf(out,"#define %sCTX_SDECL %s;\n",name,lemp->ctx); lineno++;
4247 fprintf(out,"#define %sCTX_PDECL ,%s\n",name,lemp->ctx); lineno++;
4248 fprintf(out,"#define %sCTX_PARAM ,%s\n",name,&lemp->ctx[i]); lineno++;
4249 fprintf(out,"#define %sCTX_FETCH %s=yypParser->%s;\n",
4250 name,lemp->ctx,&lemp->ctx[i]); lineno++;
4251 fprintf(out,"#define %sCTX_STORE yypParser->%s=%s;\n",
4252 name,&lemp->ctx[i],&lemp->ctx[i]); lineno++;
4253 }else{
4254 fprintf(out,"#define %sCTX_SDECL\n",name); lineno++;
4255 fprintf(out,"#define %sCTX_PDECL\n",name); lineno++;
4256 fprintf(out,"#define %sCTX_PARAM\n",name); lineno++;
4257 fprintf(out,"#define %sCTX_FETCH\n",name); lineno++;
4258 fprintf(out,"#define %sCTX_STORE\n",name); lineno++;
4259 }
drh75897232000-05-29 14:26:00 +00004260 if( mhflag ){
4261 fprintf(out,"#endif\n"); lineno++;
4262 }
drhed0c15b2018-04-16 14:31:34 +00004263 if( lemp->errsym && lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004264 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4265 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004266 }
drh0bd1f4e2002-06-06 18:54:39 +00004267 if( lemp->has_fallback ){
4268 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4269 }
drh75897232000-05-29 14:26:00 +00004270
drh3bd48ab2015-09-07 18:23:37 +00004271 /* Compute the action table, but do not output it yet. The action
4272 ** table must be computed before generating the YYNSTATE macro because
4273 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004274 */
drh3bd48ab2015-09-07 18:23:37 +00004275 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004276 if( ax==0 ){
4277 fprintf(stderr,"malloc failed\n");
4278 exit(1);
4279 }
drh3bd48ab2015-09-07 18:23:37 +00004280 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004281 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004282 ax[i*2].stp = stp;
4283 ax[i*2].isTkn = 1;
4284 ax[i*2].nAction = stp->nTknAct;
4285 ax[i*2+1].stp = stp;
4286 ax[i*2+1].isTkn = 0;
4287 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004288 }
drh8b582012003-10-21 13:16:03 +00004289 mxTknOfst = mnTknOfst = 0;
4290 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004291 /* In an effort to minimize the action table size, use the heuristic
4292 ** of placing the largest action sets first */
4293 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4294 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh3a9d6c72017-12-25 04:15:38 +00004295 pActtab = acttab_alloc(lemp->nsymbol, lemp->nterminal);
drh3bd48ab2015-09-07 18:23:37 +00004296 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004297 stp = ax[i].stp;
4298 if( ax[i].isTkn ){
4299 for(ap=stp->ap; ap; ap=ap->next){
4300 int action;
4301 if( ap->sp->index>=lemp->nterminal ) continue;
4302 action = compute_action(lemp, ap);
4303 if( action<0 ) continue;
4304 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004305 }
drh3a9d6c72017-12-25 04:15:38 +00004306 stp->iTknOfst = acttab_insert(pActtab, 1);
drhfdbf9282003-10-21 16:34:41 +00004307 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4308 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4309 }else{
4310 for(ap=stp->ap; ap; ap=ap->next){
4311 int action;
4312 if( ap->sp->index<lemp->nterminal ) continue;
4313 if( ap->sp->index==lemp->nsymbol ) continue;
4314 action = compute_action(lemp, ap);
4315 if( action<0 ) continue;
4316 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004317 }
drh3a9d6c72017-12-25 04:15:38 +00004318 stp->iNtOfst = acttab_insert(pActtab, 0);
drhfdbf9282003-10-21 16:34:41 +00004319 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4320 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004321 }
drh337cd0d2015-09-07 23:40:42 +00004322#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4323 { int jj, nn;
4324 for(jj=nn=0; jj<pActtab->nAction; jj++){
4325 if( pActtab->aAction[jj].action<0 ) nn++;
4326 }
4327 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4328 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4329 ax[i].nAction, pActtab->nAction, nn);
4330 }
4331#endif
drh8b582012003-10-21 13:16:03 +00004332 }
drhfdbf9282003-10-21 16:34:41 +00004333 free(ax);
drh8b582012003-10-21 13:16:03 +00004334
drh756b41e2016-05-24 18:55:08 +00004335 /* Mark rules that are actually used for reduce actions after all
4336 ** optimizations have been applied
4337 */
4338 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4339 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004340 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4341 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004342 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004343 }
4344 }
4345 }
4346
drh3bd48ab2015-09-07 18:23:37 +00004347 /* Finish rendering the constants now that the action table has
4348 ** been computed */
4349 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4350 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh0d9de992017-12-26 18:04:23 +00004351 fprintf(out,"#define YYNTOKEN %d\n",lemp->nterminal); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004352 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004353 i = lemp->minShiftReduce;
4354 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4355 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004356 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004357 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4358 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4359 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4360 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4361 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004362 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004363 tplt_xfer(lemp->name,in,out,&lineno);
4364
4365 /* Now output the action table and its associates:
4366 **
4367 ** yy_action[] A single table containing all actions.
4368 ** yy_lookahead[] A table containing the lookahead for each entry in
4369 ** yy_action. Used to detect hash collisions.
4370 ** yy_shift_ofst[] For each state, the offset into yy_action for
4371 ** shifting terminals.
4372 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4373 ** shifting non-terminals after a reduce.
4374 ** yy_default[] Default action for each state.
4375 */
4376
drh8b582012003-10-21 13:16:03 +00004377 /* Output the yy_action table */
drh3a9d6c72017-12-25 04:15:38 +00004378 lemp->nactiontab = n = acttab_action_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004379 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004380 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4381 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004382 for(i=j=0; i<n; i++){
4383 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004384 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004385 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004386 fprintf(out, " %4d,", action);
4387 if( j==9 || i==n-1 ){
4388 fprintf(out, "\n"); lineno++;
4389 j = 0;
4390 }else{
4391 j++;
4392 }
4393 }
4394 fprintf(out, "};\n"); lineno++;
4395
4396 /* Output the yy_lookahead table */
drh3a9d6c72017-12-25 04:15:38 +00004397 lemp->nlookaheadtab = n = acttab_lookahead_size(pActtab);
drhc75e0162015-09-07 02:23:02 +00004398 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004399 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004400 for(i=j=0; i<n; i++){
4401 int la = acttab_yylookahead(pActtab, i);
4402 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004403 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004404 fprintf(out, " %4d,", la);
4405 if( j==9 || i==n-1 ){
4406 fprintf(out, "\n"); lineno++;
4407 j = 0;
4408 }else{
4409 j++;
4410 }
4411 }
4412 fprintf(out, "};\n"); lineno++;
4413
4414 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004415 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004416 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004417 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4418 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4419 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004420 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004421 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4422 lineno++;
drhc75e0162015-09-07 02:23:02 +00004423 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->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004428 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
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 yy_reduce_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004441 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004442 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004443 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4444 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4445 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004446 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004447 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4448 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004449 for(i=j=0; i<n; i++){
4450 int ofst;
4451 stp = lemp->sorted[i];
4452 ofst = stp->iNtOfst;
4453 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004454 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004455 fprintf(out, " %4d,", ofst);
4456 if( j==9 || i==n-1 ){
4457 fprintf(out, "\n"); lineno++;
4458 j = 0;
4459 }else{
4460 j++;
4461 }
4462 }
4463 fprintf(out, "};\n"); lineno++;
4464
4465 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004466 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004467 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004468 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004469 for(i=j=0; i<n; i++){
4470 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004471 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004472 if( stp->iDfltReduce<0 ){
4473 fprintf(out, " %4d,", lemp->errAction);
4474 }else{
4475 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4476 }
drh8b582012003-10-21 13:16:03 +00004477 if( j==9 || i==n-1 ){
4478 fprintf(out, "\n"); lineno++;
4479 j = 0;
4480 }else{
4481 j++;
4482 }
4483 }
4484 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004485 tplt_xfer(lemp->name,in,out,&lineno);
4486
drh0bd1f4e2002-06-06 18:54:39 +00004487 /* Generate the table of fallback tokens.
4488 */
4489 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004490 int mx = lemp->nterminal - 1;
4491 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004492 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004493 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004494 struct symbol *p = lemp->symbols[i];
4495 if( p->fallback==0 ){
4496 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4497 }else{
4498 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4499 p->name, p->fallback->name);
4500 }
4501 lineno++;
4502 }
4503 }
4504 tplt_xfer(lemp->name, in, out, &lineno);
4505
4506 /* Generate a table containing the symbolic name of every symbol
4507 */
drh75897232000-05-29 14:26:00 +00004508 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004509 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh3a9d6c72017-12-25 04:15:38 +00004510 fprintf(out," /* %4d */ \"%s\",\n",i, lemp->symbols[i]->name); lineno++;
drh75897232000-05-29 14:26:00 +00004511 }
drh75897232000-05-29 14:26:00 +00004512 tplt_xfer(lemp->name,in,out,&lineno);
4513
drh0bd1f4e2002-06-06 18:54:39 +00004514 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004515 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004516 ** when tracing REDUCE actions.
4517 */
4518 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004519 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004520 fprintf(out," /* %3d */ \"", i);
4521 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004522 fprintf(out,"\",\n"); lineno++;
4523 }
4524 tplt_xfer(lemp->name,in,out,&lineno);
4525
drh75897232000-05-29 14:26:00 +00004526 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004527 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004528 ** (In other words, generate the %destructor actions)
4529 */
drh75897232000-05-29 14:26:00 +00004530 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004531 int once = 1;
drh75897232000-05-29 14:26:00 +00004532 for(i=0; i<lemp->nsymbol; i++){
4533 struct symbol *sp = lemp->symbols[i];
4534 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004535 if( once ){
4536 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4537 once = 0;
4538 }
drhc53eed12009-06-12 17:46:19 +00004539 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004540 }
4541 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4542 if( i<lemp->nsymbol ){
4543 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4544 fprintf(out," break;\n"); lineno++;
4545 }
4546 }
drh8d659732005-01-13 23:54:06 +00004547 if( lemp->vardest ){
4548 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004549 int once = 1;
drh8d659732005-01-13 23:54:06 +00004550 for(i=0; i<lemp->nsymbol; i++){
4551 struct symbol *sp = lemp->symbols[i];
4552 if( sp==0 || sp->type==TERMINAL ||
4553 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004554 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004555 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004556 once = 0;
4557 }
drhc53eed12009-06-12 17:46:19 +00004558 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004559 dflt_sp = sp;
4560 }
4561 if( dflt_sp!=0 ){
4562 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004563 }
drh4dc8ef52008-07-01 17:13:57 +00004564 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004565 }
drh75897232000-05-29 14:26:00 +00004566 for(i=0; i<lemp->nsymbol; i++){
4567 struct symbol *sp = lemp->symbols[i];
4568 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004569 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004570 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004571
4572 /* Combine duplicate destructors into a single case */
4573 for(j=i+1; j<lemp->nsymbol; j++){
4574 struct symbol *sp2 = lemp->symbols[j];
4575 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4576 && sp2->dtnum==sp->dtnum
4577 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004578 fprintf(out," case %d: /* %s */\n",
4579 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004580 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004581 }
4582 }
4583
drh75897232000-05-29 14:26:00 +00004584 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4585 fprintf(out," break;\n"); lineno++;
4586 }
drh75897232000-05-29 14:26:00 +00004587 tplt_xfer(lemp->name,in,out,&lineno);
4588
4589 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004590 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004591 tplt_xfer(lemp->name,in,out,&lineno);
4592
drhcfc45b12018-12-03 23:57:27 +00004593 /* Generate the tables of rule information. yyRuleInfoLhs[] and
4594 ** yyRuleInfoNRhs[].
drh75897232000-05-29 14:26:00 +00004595 **
4596 ** Note: This code depends on the fact that rules are number
4597 ** sequentually beginning with 0.
4598 */
drh5c8241b2017-12-24 23:38:10 +00004599 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drhcfc45b12018-12-03 23:57:27 +00004600 fprintf(out," %4d, /* (%d) ", rp->lhs->index, i);
4601 rule_print(out, rp);
4602 fprintf(out," */\n"); lineno++;
4603 }
4604 tplt_xfer(lemp->name,in,out,&lineno);
4605 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4606 fprintf(out," %3d, /* (%d) ", -rp->nrhs, i);
drh5c8241b2017-12-24 23:38:10 +00004607 rule_print(out, rp);
4608 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004609 }
4610 tplt_xfer(lemp->name,in,out,&lineno);
4611
4612 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004613 i = 0;
drh75897232000-05-29 14:26:00 +00004614 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004615 i += translate_code(lemp, rp);
4616 }
4617 if( i ){
4618 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004619 }
drhc53eed12009-06-12 17:46:19 +00004620 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004621 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004622 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004623 if( rp->codeEmitted ) continue;
4624 if( rp->noCode ){
4625 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004626 continue;
4627 }
drh4ef07702016-03-16 19:45:54 +00004628 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004629 writeRuleText(out, rp);
4630 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004631 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004632 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4633 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004634 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004635 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004636 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004637 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004638 }
4639 }
drh75897232000-05-29 14:26:00 +00004640 emit_code(out,rp,lemp,&lineno);
4641 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004642 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004643 }
drhc53eed12009-06-12 17:46:19 +00004644 /* Finally, output the default: rule. We choose as the default: all
4645 ** empty actions. */
4646 fprintf(out," default:\n"); lineno++;
4647 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004648 if( rp->codeEmitted ) continue;
4649 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004650 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004651 writeRuleText(out, rp);
drh756b41e2016-05-24 18:55:08 +00004652 if( rp->doesReduce ){
4653 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4654 }else{
4655 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4656 rp->iRule); lineno++;
4657 }
drhc53eed12009-06-12 17:46:19 +00004658 }
4659 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004660 tplt_xfer(lemp->name,in,out,&lineno);
4661
4662 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004663 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004664 tplt_xfer(lemp->name,in,out,&lineno);
4665
4666 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004667 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004668 tplt_xfer(lemp->name,in,out,&lineno);
4669
4670 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004671 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004672 tplt_xfer(lemp->name,in,out,&lineno);
4673
4674 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004675 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004676
drhe2dcc422019-01-15 14:44:23 +00004677 acttab_free(pActtab);
drh75897232000-05-29 14:26:00 +00004678 fclose(in);
4679 fclose(out);
4680 return;
4681}
4682
4683/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004684void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004685{
4686 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004687 const char *prefix;
drh75897232000-05-29 14:26:00 +00004688 char line[LINESIZE];
4689 char pattern[LINESIZE];
4690 int i;
4691
4692 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4693 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004694 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004695 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004696 int nextChar;
drh75897232000-05-29 14:26:00 +00004697 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004698 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4699 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004700 if( strcmp(line,pattern) ) break;
4701 }
drh8ba0d1c2012-06-16 15:26:31 +00004702 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004703 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004704 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004705 /* No change in the file. Don't rewrite it. */
4706 return;
4707 }
4708 }
drh2aa6ca42004-09-10 00:14:04 +00004709 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004710 if( out ){
4711 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004712 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004713 }
drh06f60d82017-04-14 19:46:12 +00004714 fclose(out);
drh75897232000-05-29 14:26:00 +00004715 }
4716 return;
4717}
4718
4719/* Reduce the size of the action tables, if possible, by making use
4720** of defaults.
4721**
drhb59499c2002-02-23 18:45:13 +00004722** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004723** it the default. Except, there is no default if the wildcard token
4724** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004725*/
icculus9e44cf12010-02-14 17:14:22 +00004726void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004727{
4728 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004729 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004730 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004731 int nbest, n;
drh75897232000-05-29 14:26:00 +00004732 int i;
drhe09daa92006-06-10 13:29:31 +00004733 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004734
4735 for(i=0; i<lemp->nstate; i++){
4736 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004737 nbest = 0;
4738 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004739 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004740
drhb59499c2002-02-23 18:45:13 +00004741 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004742 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4743 usesWildcard = 1;
4744 }
drhb59499c2002-02-23 18:45:13 +00004745 if( ap->type!=REDUCE ) continue;
4746 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004747 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004748 if( rp==rbest ) continue;
4749 n = 1;
4750 for(ap2=ap->next; ap2; ap2=ap2->next){
4751 if( ap2->type!=REDUCE ) continue;
4752 rp2 = ap2->x.rp;
4753 if( rp2==rbest ) continue;
4754 if( rp2==rp ) n++;
4755 }
4756 if( n>nbest ){
4757 nbest = n;
4758 rbest = rp;
drh75897232000-05-29 14:26:00 +00004759 }
4760 }
drh06f60d82017-04-14 19:46:12 +00004761
drhb59499c2002-02-23 18:45:13 +00004762 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004763 ** is not at least 1 or if the wildcard token is a possible
4764 ** lookahead.
4765 */
4766 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004767
drhb59499c2002-02-23 18:45:13 +00004768
4769 /* Combine matching REDUCE actions into a single default */
4770 for(ap=stp->ap; ap; ap=ap->next){
4771 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4772 }
drh75897232000-05-29 14:26:00 +00004773 assert( ap );
4774 ap->sp = Symbol_new("{default}");
4775 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004776 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004777 }
4778 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004779
4780 for(ap=stp->ap; ap; ap=ap->next){
4781 if( ap->type==SHIFT ) break;
4782 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4783 }
4784 if( ap==0 ){
4785 stp->autoReduce = 1;
4786 stp->pDfltReduce = rbest;
4787 }
4788 }
4789
4790 /* Make a second pass over all states and actions. Convert
4791 ** every action that is a SHIFT to an autoReduce state into
4792 ** a SHIFTREDUCE action.
4793 */
4794 for(i=0; i<lemp->nstate; i++){
4795 stp = lemp->sorted[i];
4796 for(ap=stp->ap; ap; ap=ap->next){
4797 struct state *pNextState;
4798 if( ap->type!=SHIFT ) continue;
4799 pNextState = ap->x.stp;
4800 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4801 ap->type = SHIFTREDUCE;
4802 ap->x.rp = pNextState->pDfltReduce;
4803 }
4804 }
drh75897232000-05-29 14:26:00 +00004805 }
drhc173ad82016-05-23 16:15:02 +00004806
4807 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4808 ** (meaning that the SHIFTREDUCE will land back in the state where it
4809 ** started) and if there is no C-code associated with the reduce action,
4810 ** then we can go ahead and convert the action to be the same as the
4811 ** action for the RHS of the rule.
4812 */
4813 for(i=0; i<lemp->nstate; i++){
4814 stp = lemp->sorted[i];
4815 for(ap=stp->ap; ap; ap=nextap){
4816 nextap = ap->next;
4817 if( ap->type!=SHIFTREDUCE ) continue;
4818 rp = ap->x.rp;
4819 if( rp->noCode==0 ) continue;
4820 if( rp->nrhs!=1 ) continue;
4821#if 1
4822 /* Only apply this optimization to non-terminals. It would be OK to
4823 ** apply it to terminal symbols too, but that makes the parser tables
4824 ** larger. */
4825 if( ap->sp->index<lemp->nterminal ) continue;
4826#endif
4827 /* If we reach this point, it means the optimization can be applied */
4828 nextap = ap;
4829 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4830 assert( ap2!=0 );
4831 ap->spOpt = ap2->sp;
4832 ap->type = ap2->type;
4833 ap->x = ap2->x;
4834 }
4835 }
drh75897232000-05-29 14:26:00 +00004836}
drhb59499c2002-02-23 18:45:13 +00004837
drhada354d2005-11-05 15:03:59 +00004838
4839/*
4840** Compare two states for sorting purposes. The smaller state is the
4841** one with the most non-terminal actions. If they have the same number
4842** of non-terminal actions, then the smaller is the one with the most
4843** token actions.
4844*/
4845static int stateResortCompare(const void *a, const void *b){
4846 const struct state *pA = *(const struct state**)a;
4847 const struct state *pB = *(const struct state**)b;
4848 int n;
4849
4850 n = pB->nNtAct - pA->nNtAct;
4851 if( n==0 ){
4852 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004853 if( n==0 ){
4854 n = pB->statenum - pA->statenum;
4855 }
drhada354d2005-11-05 15:03:59 +00004856 }
drhe594bc32009-11-03 13:02:25 +00004857 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004858 return n;
4859}
4860
4861
4862/*
4863** Renumber and resort states so that states with fewer choices
4864** occur at the end. Except, keep state 0 as the first state.
4865*/
icculus9e44cf12010-02-14 17:14:22 +00004866void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004867{
4868 int i;
4869 struct state *stp;
4870 struct action *ap;
4871
4872 for(i=0; i<lemp->nstate; i++){
4873 stp = lemp->sorted[i];
4874 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00004875 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004876 stp->iTknOfst = NO_OFFSET;
4877 stp->iNtOfst = NO_OFFSET;
4878 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004879 int iAction = compute_action(lemp,ap);
4880 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004881 if( ap->sp->index<lemp->nterminal ){
4882 stp->nTknAct++;
4883 }else if( ap->sp->index<lemp->nsymbol ){
4884 stp->nNtAct++;
4885 }else{
drh3bd48ab2015-09-07 18:23:37 +00004886 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00004887 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00004888 }
4889 }
4890 }
4891 }
4892 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4893 stateResortCompare);
4894 for(i=0; i<lemp->nstate; i++){
4895 lemp->sorted[i]->statenum = i;
4896 }
drh3bd48ab2015-09-07 18:23:37 +00004897 lemp->nxstate = lemp->nstate;
4898 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4899 lemp->nxstate--;
4900 }
drhada354d2005-11-05 15:03:59 +00004901}
4902
4903
drh75897232000-05-29 14:26:00 +00004904/***************** From the file "set.c" ************************************/
4905/*
4906** Set manipulation routines for the LEMON parser generator.
4907*/
4908
4909static int size = 0;
4910
4911/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004912void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004913{
4914 size = n+1;
4915}
4916
4917/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00004918char *SetNew(void){
drh75897232000-05-29 14:26:00 +00004919 char *s;
drh9892c5d2007-12-21 00:02:11 +00004920 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004921 if( s==0 ){
4922 extern void memory_error();
4923 memory_error();
4924 }
drh75897232000-05-29 14:26:00 +00004925 return s;
4926}
4927
4928/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004929void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004930{
4931 free(s);
4932}
4933
4934/* Add a new element to the set. Return TRUE if the element was added
4935** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004936int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004937{
4938 int rv;
drh9892c5d2007-12-21 00:02:11 +00004939 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004940 rv = s[e];
4941 s[e] = 1;
4942 return !rv;
4943}
4944
4945/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004946int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004947{
4948 int i, progress;
4949 progress = 0;
4950 for(i=0; i<size; i++){
4951 if( s2[i]==0 ) continue;
4952 if( s1[i]==0 ){
4953 progress = 1;
4954 s1[i] = 1;
4955 }
4956 }
4957 return progress;
4958}
4959/********************** From the file "table.c" ****************************/
4960/*
4961** All code in this file has been automatically generated
4962** from a specification in the file
4963** "table.q"
4964** by the associative array code building program "aagen".
4965** Do not edit this file! Instead, edit the specification
4966** file, then rerun aagen.
4967*/
4968/*
4969** Code for processing tables in the LEMON parser generator.
4970*/
4971
drh01f75f22013-10-02 20:46:30 +00004972PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004973{
drh01f75f22013-10-02 20:46:30 +00004974 unsigned h = 0;
4975 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004976 return h;
4977}
4978
4979/* Works like strdup, sort of. Save a string in malloced memory, but
4980** keep strings in a table so that the same string is not in more
4981** than one place.
4982*/
icculus9e44cf12010-02-14 17:14:22 +00004983const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004984{
icculus9e44cf12010-02-14 17:14:22 +00004985 const char *z;
4986 char *cpy;
drh75897232000-05-29 14:26:00 +00004987
drh916f75f2006-07-17 00:19:39 +00004988 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004989 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004990 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004991 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004992 z = cpy;
drh75897232000-05-29 14:26:00 +00004993 Strsafe_insert(z);
4994 }
4995 MemoryCheck(z);
4996 return z;
4997}
4998
4999/* There is one instance of the following structure for each
5000** associative array of type "x1".
5001*/
5002struct s_x1 {
5003 int size; /* The number of available slots. */
5004 /* Must be a power of 2 greater than or */
5005 /* equal to 1 */
5006 int count; /* Number of currently slots filled */
5007 struct s_x1node *tbl; /* The data stored here */
5008 struct s_x1node **ht; /* Hash table for lookups */
5009};
5010
5011/* There is one instance of this structure for every data element
5012** in an associative array of type "x1".
5013*/
5014typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00005015 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00005016 struct s_x1node *next; /* Next entry with the same hash */
5017 struct s_x1node **from; /* Previous link */
5018} x1node;
5019
5020/* There is only one instance of the array, which is the following */
5021static struct s_x1 *x1a;
5022
5023/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005024void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00005025 if( x1a ) return;
5026 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
5027 if( x1a ){
5028 x1a->size = 1024;
5029 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005030 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005031 if( x1a->tbl==0 ){
5032 free(x1a);
5033 x1a = 0;
5034 }else{
5035 int i;
5036 x1a->ht = (x1node**)&(x1a->tbl[1024]);
5037 for(i=0; i<1024; i++) x1a->ht[i] = 0;
5038 }
5039 }
5040}
5041/* Insert a new record into the array. Return TRUE if successful.
5042** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005043int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00005044{
5045 x1node *np;
drh01f75f22013-10-02 20:46:30 +00005046 unsigned h;
5047 unsigned ph;
drh75897232000-05-29 14:26:00 +00005048
5049 if( x1a==0 ) return 0;
5050 ph = strhash(data);
5051 h = ph & (x1a->size-1);
5052 np = x1a->ht[h];
5053 while( np ){
5054 if( strcmp(np->data,data)==0 ){
5055 /* An existing entry with the same key is found. */
5056 /* Fail because overwrite is not allows. */
5057 return 0;
5058 }
5059 np = np->next;
5060 }
5061 if( x1a->count>=x1a->size ){
5062 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005063 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005064 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00005065 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00005066 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00005067 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00005068 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005069 array.ht = (x1node**)&(array.tbl[arrSize]);
5070 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005071 for(i=0; i<x1a->count; i++){
5072 x1node *oldnp, *newnp;
5073 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005074 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005075 newnp = &(array.tbl[i]);
5076 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5077 newnp->next = array.ht[h];
5078 newnp->data = oldnp->data;
5079 newnp->from = &(array.ht[h]);
5080 array.ht[h] = newnp;
5081 }
5082 free(x1a->tbl);
5083 *x1a = array;
5084 }
5085 /* Insert the new data */
5086 h = ph & (x1a->size-1);
5087 np = &(x1a->tbl[x1a->count++]);
5088 np->data = data;
5089 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
5090 np->next = x1a->ht[h];
5091 x1a->ht[h] = np;
5092 np->from = &(x1a->ht[h]);
5093 return 1;
5094}
5095
5096/* Return a pointer to data assigned to the given key. Return NULL
5097** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005098const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00005099{
drh01f75f22013-10-02 20:46:30 +00005100 unsigned h;
drh75897232000-05-29 14:26:00 +00005101 x1node *np;
5102
5103 if( x1a==0 ) return 0;
5104 h = strhash(key) & (x1a->size-1);
5105 np = x1a->ht[h];
5106 while( np ){
5107 if( strcmp(np->data,key)==0 ) break;
5108 np = np->next;
5109 }
5110 return np ? np->data : 0;
5111}
5112
5113/* Return a pointer to the (terminal or nonterminal) symbol "x".
5114** Create a new symbol if this is the first time "x" has been seen.
5115*/
icculus9e44cf12010-02-14 17:14:22 +00005116struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00005117{
5118 struct symbol *sp;
5119
5120 sp = Symbol_find(x);
5121 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00005122 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00005123 MemoryCheck(sp);
5124 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00005125 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00005126 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00005127 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00005128 sp->prec = -1;
5129 sp->assoc = UNK;
5130 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005131 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005132 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005133 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005134 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005135 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005136 Symbol_insert(sp,sp->name);
5137 }
drhc4dd3fd2008-01-22 01:48:05 +00005138 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005139 return sp;
5140}
5141
drh61f92cd2014-01-11 03:06:18 +00005142/* Compare two symbols for sorting purposes. Return negative,
5143** zero, or positive if a is less then, equal to, or greater
5144** than b.
drh60d31652004-02-22 00:08:04 +00005145**
5146** Symbols that begin with upper case letters (terminals or tokens)
5147** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005148** (non-terminals). And MULTITERMINAL symbols (created using the
5149** %token_class directive) must sort at the very end. Other than
5150** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005151**
5152** We find experimentally that leaving the symbols in their original
5153** order (the order they appeared in the grammar file) gives the
5154** smallest parser tables in SQLite.
5155*/
icculus9e44cf12010-02-14 17:14:22 +00005156int Symbolcmpp(const void *_a, const void *_b)
5157{
drh61f92cd2014-01-11 03:06:18 +00005158 const struct symbol *a = *(const struct symbol **) _a;
5159 const struct symbol *b = *(const struct symbol **) _b;
5160 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5161 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5162 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005163}
5164
5165/* There is one instance of the following structure for each
5166** associative array of type "x2".
5167*/
5168struct s_x2 {
5169 int size; /* The number of available slots. */
5170 /* Must be a power of 2 greater than or */
5171 /* equal to 1 */
5172 int count; /* Number of currently slots filled */
5173 struct s_x2node *tbl; /* The data stored here */
5174 struct s_x2node **ht; /* Hash table for lookups */
5175};
5176
5177/* There is one instance of this structure for every data element
5178** in an associative array of type "x2".
5179*/
5180typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005181 struct symbol *data; /* The data */
5182 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005183 struct s_x2node *next; /* Next entry with the same hash */
5184 struct s_x2node **from; /* Previous link */
5185} x2node;
5186
5187/* There is only one instance of the array, which is the following */
5188static struct s_x2 *x2a;
5189
5190/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005191void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005192 if( x2a ) return;
5193 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5194 if( x2a ){
5195 x2a->size = 128;
5196 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005197 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005198 if( x2a->tbl==0 ){
5199 free(x2a);
5200 x2a = 0;
5201 }else{
5202 int i;
5203 x2a->ht = (x2node**)&(x2a->tbl[128]);
5204 for(i=0; i<128; i++) x2a->ht[i] = 0;
5205 }
5206 }
5207}
5208/* Insert a new record into the array. Return TRUE if successful.
5209** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005210int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005211{
5212 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005213 unsigned h;
5214 unsigned ph;
drh75897232000-05-29 14:26:00 +00005215
5216 if( x2a==0 ) return 0;
5217 ph = strhash(key);
5218 h = ph & (x2a->size-1);
5219 np = x2a->ht[h];
5220 while( np ){
5221 if( strcmp(np->key,key)==0 ){
5222 /* An existing entry with the same key is found. */
5223 /* Fail because overwrite is not allows. */
5224 return 0;
5225 }
5226 np = np->next;
5227 }
5228 if( x2a->count>=x2a->size ){
5229 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005230 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005231 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005232 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005233 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005234 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005235 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005236 array.ht = (x2node**)&(array.tbl[arrSize]);
5237 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005238 for(i=0; i<x2a->count; i++){
5239 x2node *oldnp, *newnp;
5240 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005241 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005242 newnp = &(array.tbl[i]);
5243 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5244 newnp->next = array.ht[h];
5245 newnp->key = oldnp->key;
5246 newnp->data = oldnp->data;
5247 newnp->from = &(array.ht[h]);
5248 array.ht[h] = newnp;
5249 }
5250 free(x2a->tbl);
5251 *x2a = array;
5252 }
5253 /* Insert the new data */
5254 h = ph & (x2a->size-1);
5255 np = &(x2a->tbl[x2a->count++]);
5256 np->key = key;
5257 np->data = data;
5258 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5259 np->next = x2a->ht[h];
5260 x2a->ht[h] = np;
5261 np->from = &(x2a->ht[h]);
5262 return 1;
5263}
5264
5265/* Return a pointer to data assigned to the given key. Return NULL
5266** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005267struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005268{
drh01f75f22013-10-02 20:46:30 +00005269 unsigned h;
drh75897232000-05-29 14:26:00 +00005270 x2node *np;
5271
5272 if( x2a==0 ) return 0;
5273 h = strhash(key) & (x2a->size-1);
5274 np = x2a->ht[h];
5275 while( np ){
5276 if( strcmp(np->key,key)==0 ) break;
5277 np = np->next;
5278 }
5279 return np ? np->data : 0;
5280}
5281
5282/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005283struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005284{
5285 struct symbol *data;
5286 if( x2a && n>0 && n<=x2a->count ){
5287 data = x2a->tbl[n-1].data;
5288 }else{
5289 data = 0;
5290 }
5291 return data;
5292}
5293
5294/* Return the size of the array */
5295int Symbol_count()
5296{
5297 return x2a ? x2a->count : 0;
5298}
5299
5300/* Return an array of pointers to all data in the table.
5301** The array is obtained from malloc. Return NULL if memory allocation
5302** problems, or if the array is empty. */
5303struct symbol **Symbol_arrayof()
5304{
5305 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005306 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005307 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005308 arrSize = x2a->count;
5309 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005310 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005311 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005312 }
5313 return array;
5314}
5315
5316/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005317int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005318{
icculus9e44cf12010-02-14 17:14:22 +00005319 const struct config *a = (struct config *) _a;
5320 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005321 int x;
5322 x = a->rp->index - b->rp->index;
5323 if( x==0 ) x = a->dot - b->dot;
5324 return x;
5325}
5326
5327/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005328PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005329{
5330 int rc;
5331 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5332 rc = a->rp->index - b->rp->index;
5333 if( rc==0 ) rc = a->dot - b->dot;
5334 }
5335 if( rc==0 ){
5336 if( a ) rc = 1;
5337 if( b ) rc = -1;
5338 }
5339 return rc;
5340}
5341
5342/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005343PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005344{
drh01f75f22013-10-02 20:46:30 +00005345 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005346 while( a ){
5347 h = h*571 + a->rp->index*37 + a->dot;
5348 a = a->bp;
5349 }
5350 return h;
5351}
5352
5353/* Allocate a new state structure */
5354struct state *State_new()
5355{
icculus9e44cf12010-02-14 17:14:22 +00005356 struct state *newstate;
5357 newstate = (struct state *)calloc(1, sizeof(struct state) );
5358 MemoryCheck(newstate);
5359 return newstate;
drh75897232000-05-29 14:26:00 +00005360}
5361
5362/* There is one instance of the following structure for each
5363** associative array of type "x3".
5364*/
5365struct s_x3 {
5366 int size; /* The number of available slots. */
5367 /* Must be a power of 2 greater than or */
5368 /* equal to 1 */
5369 int count; /* Number of currently slots filled */
5370 struct s_x3node *tbl; /* The data stored here */
5371 struct s_x3node **ht; /* Hash table for lookups */
5372};
5373
5374/* There is one instance of this structure for every data element
5375** in an associative array of type "x3".
5376*/
5377typedef struct s_x3node {
5378 struct state *data; /* The data */
5379 struct config *key; /* The key */
5380 struct s_x3node *next; /* Next entry with the same hash */
5381 struct s_x3node **from; /* Previous link */
5382} x3node;
5383
5384/* There is only one instance of the array, which is the following */
5385static struct s_x3 *x3a;
5386
5387/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005388void State_init(void){
drh75897232000-05-29 14:26:00 +00005389 if( x3a ) return;
5390 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5391 if( x3a ){
5392 x3a->size = 128;
5393 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005394 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005395 if( x3a->tbl==0 ){
5396 free(x3a);
5397 x3a = 0;
5398 }else{
5399 int i;
5400 x3a->ht = (x3node**)&(x3a->tbl[128]);
5401 for(i=0; i<128; i++) x3a->ht[i] = 0;
5402 }
5403 }
5404}
5405/* Insert a new record into the array. Return TRUE if successful.
5406** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005407int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005408{
5409 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005410 unsigned h;
5411 unsigned ph;
drh75897232000-05-29 14:26:00 +00005412
5413 if( x3a==0 ) return 0;
5414 ph = statehash(key);
5415 h = ph & (x3a->size-1);
5416 np = x3a->ht[h];
5417 while( np ){
5418 if( statecmp(np->key,key)==0 ){
5419 /* An existing entry with the same key is found. */
5420 /* Fail because overwrite is not allows. */
5421 return 0;
5422 }
5423 np = np->next;
5424 }
5425 if( x3a->count>=x3a->size ){
5426 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005427 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005428 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005429 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005430 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005431 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005432 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005433 array.ht = (x3node**)&(array.tbl[arrSize]);
5434 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005435 for(i=0; i<x3a->count; i++){
5436 x3node *oldnp, *newnp;
5437 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005438 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005439 newnp = &(array.tbl[i]);
5440 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5441 newnp->next = array.ht[h];
5442 newnp->key = oldnp->key;
5443 newnp->data = oldnp->data;
5444 newnp->from = &(array.ht[h]);
5445 array.ht[h] = newnp;
5446 }
5447 free(x3a->tbl);
5448 *x3a = array;
5449 }
5450 /* Insert the new data */
5451 h = ph & (x3a->size-1);
5452 np = &(x3a->tbl[x3a->count++]);
5453 np->key = key;
5454 np->data = data;
5455 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5456 np->next = x3a->ht[h];
5457 x3a->ht[h] = np;
5458 np->from = &(x3a->ht[h]);
5459 return 1;
5460}
5461
5462/* Return a pointer to data assigned to the given key. Return NULL
5463** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005464struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005465{
drh01f75f22013-10-02 20:46:30 +00005466 unsigned h;
drh75897232000-05-29 14:26:00 +00005467 x3node *np;
5468
5469 if( x3a==0 ) return 0;
5470 h = statehash(key) & (x3a->size-1);
5471 np = x3a->ht[h];
5472 while( np ){
5473 if( statecmp(np->key,key)==0 ) break;
5474 np = np->next;
5475 }
5476 return np ? np->data : 0;
5477}
5478
5479/* Return an array of pointers to all data in the table.
5480** The array is obtained from malloc. Return NULL if memory allocation
5481** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005482struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005483{
5484 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005485 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005486 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005487 arrSize = x3a->count;
5488 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005489 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005490 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005491 }
5492 return array;
5493}
5494
5495/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005496PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005497{
drh01f75f22013-10-02 20:46:30 +00005498 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005499 h = h*571 + a->rp->index*37 + a->dot;
5500 return h;
5501}
5502
5503/* There is one instance of the following structure for each
5504** associative array of type "x4".
5505*/
5506struct s_x4 {
5507 int size; /* The number of available slots. */
5508 /* Must be a power of 2 greater than or */
5509 /* equal to 1 */
5510 int count; /* Number of currently slots filled */
5511 struct s_x4node *tbl; /* The data stored here */
5512 struct s_x4node **ht; /* Hash table for lookups */
5513};
5514
5515/* There is one instance of this structure for every data element
5516** in an associative array of type "x4".
5517*/
5518typedef struct s_x4node {
5519 struct config *data; /* The data */
5520 struct s_x4node *next; /* Next entry with the same hash */
5521 struct s_x4node **from; /* Previous link */
5522} x4node;
5523
5524/* There is only one instance of the array, which is the following */
5525static struct s_x4 *x4a;
5526
5527/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005528void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005529 if( x4a ) return;
5530 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5531 if( x4a ){
5532 x4a->size = 64;
5533 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005534 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005535 if( x4a->tbl==0 ){
5536 free(x4a);
5537 x4a = 0;
5538 }else{
5539 int i;
5540 x4a->ht = (x4node**)&(x4a->tbl[64]);
5541 for(i=0; i<64; i++) x4a->ht[i] = 0;
5542 }
5543 }
5544}
5545/* Insert a new record into the array. Return TRUE if successful.
5546** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005547int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005548{
5549 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005550 unsigned h;
5551 unsigned ph;
drh75897232000-05-29 14:26:00 +00005552
5553 if( x4a==0 ) return 0;
5554 ph = confighash(data);
5555 h = ph & (x4a->size-1);
5556 np = x4a->ht[h];
5557 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005558 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005559 /* An existing entry with the same key is found. */
5560 /* Fail because overwrite is not allows. */
5561 return 0;
5562 }
5563 np = np->next;
5564 }
5565 if( x4a->count>=x4a->size ){
5566 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005567 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005568 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005569 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005570 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005571 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005572 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005573 array.ht = (x4node**)&(array.tbl[arrSize]);
5574 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005575 for(i=0; i<x4a->count; i++){
5576 x4node *oldnp, *newnp;
5577 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005578 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005579 newnp = &(array.tbl[i]);
5580 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5581 newnp->next = array.ht[h];
5582 newnp->data = oldnp->data;
5583 newnp->from = &(array.ht[h]);
5584 array.ht[h] = newnp;
5585 }
5586 free(x4a->tbl);
5587 *x4a = array;
5588 }
5589 /* Insert the new data */
5590 h = ph & (x4a->size-1);
5591 np = &(x4a->tbl[x4a->count++]);
5592 np->data = data;
5593 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5594 np->next = x4a->ht[h];
5595 x4a->ht[h] = np;
5596 np->from = &(x4a->ht[h]);
5597 return 1;
5598}
5599
5600/* Return a pointer to data assigned to the given key. Return NULL
5601** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005602struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005603{
5604 int h;
5605 x4node *np;
5606
5607 if( x4a==0 ) return 0;
5608 h = confighash(key) & (x4a->size-1);
5609 np = x4a->ht[h];
5610 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005611 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005612 np = np->next;
5613 }
5614 return np ? np->data : 0;
5615}
5616
5617/* Remove all data from the table. Pass each data to the function "f"
5618** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005619void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005620{
5621 int i;
5622 if( x4a==0 || x4a->count==0 ) return;
5623 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5624 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5625 x4a->count = 0;
5626 return;
5627}