blob: 33ef43d1b1ac8f63da0de895ee20f9ad5206f79c [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
drhf9a2e7b2003-04-15 01:49:48 +000010#include <stdarg.h>
drh75897232000-05-29 14:26:00 +000011#include <string.h>
12#include <ctype.h>
drh8b582012003-10-21 13:16:03 +000013#include <stdlib.h>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drhc56fac72015-10-29 13:48:15 +000016#define ISSPACE(X) isspace((unsigned char)(X))
17#define ISDIGIT(X) isdigit((unsigned char)(X))
18#define ISALNUM(X) isalnum((unsigned char)(X))
19#define ISALPHA(X) isalpha((unsigned char)(X))
20#define ISUPPER(X) isupper((unsigned char)(X))
21#define ISLOWER(X) islower((unsigned char)(X))
22
23
drh75897232000-05-29 14:26:00 +000024#ifndef __WIN32__
25# if defined(_WIN32) || defined(WIN32)
drhf2f105d2012-08-20 15:53:54 +000026# define __WIN32__
drh75897232000-05-29 14:26:00 +000027# endif
28#endif
29
rse8f304482007-07-30 18:31:53 +000030#ifdef __WIN32__
drhdf609712010-11-23 20:55:27 +000031#ifdef __cplusplus
32extern "C" {
33#endif
34extern int access(const char *path, int mode);
35#ifdef __cplusplus
36}
37#endif
rse8f304482007-07-30 18:31:53 +000038#else
39#include <unistd.h>
40#endif
41
drh75897232000-05-29 14:26:00 +000042/* #define PRIVATE static */
43#define PRIVATE
44
45#ifdef TEST
46#define MAXRHS 5 /* Set low to exercise exception code */
47#else
48#define MAXRHS 1000
49#endif
50
drhf5c4e0f2010-07-18 11:35:53 +000051static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000052static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000053
drh87cf1372008-08-13 20:09:06 +000054/*
55** Compilers are getting increasingly pedantic about type conversions
56** as C evolves ever closer to Ada.... To work around the latest problems
57** we have to define the following variant of strlen().
58*/
59#define lemonStrlen(X) ((int)strlen(X))
60
drh898799f2014-01-10 23:21:00 +000061/*
62** Compilers are starting to complain about the use of sprintf() and strcpy(),
63** saying they are unsafe. So we define our own versions of those routines too.
64**
65** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
drh25473362015-09-04 18:03:45 +000066** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
drh898799f2014-01-10 23:21:00 +000067** The third is a helper routine for vsnprintf() that adds texts to the end of a
68** buffer, making sure the buffer is always zero-terminated.
69**
70** The string formatter is a minimal subset of stdlib sprintf() supporting only
71** a few simply conversions:
72**
73** %d
74** %s
75** %.*s
76**
77*/
78static void lemon_addtext(
79 char *zBuf, /* The buffer to which text is added */
80 int *pnUsed, /* Slots of the buffer used so far */
81 const char *zIn, /* Text to add */
drh61f92cd2014-01-11 03:06:18 +000082 int nIn, /* Bytes of text to add. -1 to use strlen() */
83 int iWidth /* Field width. Negative to left justify */
drh898799f2014-01-10 23:21:00 +000084){
85 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
drhecaa9d32014-01-11 03:27:37 +000086 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
drh898799f2014-01-10 23:21:00 +000087 if( nIn==0 ) return;
88 memcpy(&zBuf[*pnUsed], zIn, nIn);
89 *pnUsed += nIn;
drhecaa9d32014-01-11 03:27:37 +000090 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
drh898799f2014-01-10 23:21:00 +000091 zBuf[*pnUsed] = 0;
92}
93static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
mistachkin7a429652014-01-14 10:17:21 +000094 int i, j, k, c;
drh898799f2014-01-10 23:21:00 +000095 int nUsed = 0;
96 const char *z;
97 char zTemp[50];
98 str[0] = 0;
99 for(i=j=0; (c = zFormat[i])!=0; i++){
100 if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000101 int iWidth = 0;
102 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000103 c = zFormat[++i];
drhc56fac72015-10-29 13:48:15 +0000104 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
drh61f92cd2014-01-11 03:06:18 +0000105 if( c=='-' ) i++;
drhc56fac72015-10-29 13:48:15 +0000106 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
drh61f92cd2014-01-11 03:06:18 +0000107 if( c=='-' ) iWidth = -iWidth;
108 c = zFormat[i];
109 }
drh898799f2014-01-10 23:21:00 +0000110 if( c=='d' ){
111 int v = va_arg(ap, int);
112 if( v<0 ){
drh61f92cd2014-01-11 03:06:18 +0000113 lemon_addtext(str, &nUsed, "-", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000114 v = -v;
115 }else if( v==0 ){
drh61f92cd2014-01-11 03:06:18 +0000116 lemon_addtext(str, &nUsed, "0", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000117 }
118 k = 0;
119 while( v>0 ){
120 k++;
121 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
122 v /= 10;
123 }
drh61f92cd2014-01-11 03:06:18 +0000124 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
drh898799f2014-01-10 23:21:00 +0000125 }else if( c=='s' ){
126 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000127 lemon_addtext(str, &nUsed, z, -1, iWidth);
drh898799f2014-01-10 23:21:00 +0000128 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
129 i += 2;
130 k = va_arg(ap, int);
131 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000132 lemon_addtext(str, &nUsed, z, k, iWidth);
drh898799f2014-01-10 23:21:00 +0000133 }else if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000134 lemon_addtext(str, &nUsed, "%", 1, 0);
drh898799f2014-01-10 23:21:00 +0000135 }else{
136 fprintf(stderr, "illegal format\n");
137 exit(1);
138 }
139 j = i+1;
140 }
141 }
drh61f92cd2014-01-11 03:06:18 +0000142 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000143 return nUsed;
144}
145static int lemon_sprintf(char *str, const char *format, ...){
146 va_list ap;
147 int rc;
148 va_start(ap, format);
149 rc = lemon_vsprintf(str, format, ap);
150 va_end(ap);
151 return rc;
152}
153static void lemon_strcpy(char *dest, const char *src){
154 while( (*(dest++) = *(src++))!=0 ){}
155}
156static void lemon_strcat(char *dest, const char *src){
157 while( *dest ) dest++;
158 lemon_strcpy(dest, src);
159}
160
161
icculus9e44cf12010-02-14 17:14:22 +0000162/* a few forward declarations... */
163struct rule;
164struct lemon;
165struct action;
166
drhe9278182007-07-18 18:16:29 +0000167static struct action *Action_new(void);
168static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +0000169
170/********** From the file "build.h" ************************************/
drh14d88552017-04-14 19:44:15 +0000171void FindRulePrecedences(struct lemon*);
172void FindFirstSets(struct lemon*);
173void FindStates(struct lemon*);
174void FindLinks(struct lemon*);
175void FindFollowSets(struct lemon*);
176void FindActions(struct lemon*);
drh75897232000-05-29 14:26:00 +0000177
178/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +0000179void Configlist_init(void);
180struct config *Configlist_add(struct rule *, int);
181struct config *Configlist_addbasis(struct rule *, int);
182void Configlist_closure(struct lemon *);
183void Configlist_sort(void);
184void Configlist_sortbasis(void);
185struct config *Configlist_return(void);
186struct config *Configlist_basis(void);
187void Configlist_eat(struct config *);
188void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +0000189
190/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +0000191void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +0000192
193/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +0000194enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
195 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +0000196struct s_options {
icculus9e44cf12010-02-14 17:14:22 +0000197 enum option_type type;
198 const char *label;
drh75897232000-05-29 14:26:00 +0000199 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000200 const char *message;
drh75897232000-05-29 14:26:00 +0000201};
icculus9e44cf12010-02-14 17:14:22 +0000202int OptInit(char**,struct s_options*,FILE*);
203int OptNArgs(void);
204char *OptArg(int);
205void OptErr(int);
206void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000207
208/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000209void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000210
211/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000212struct plink *Plink_new(void);
213void Plink_add(struct plink **, struct config *);
214void Plink_copy(struct plink **, struct plink *);
215void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000216
217/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000218void Reprint(struct lemon *);
219void ReportOutput(struct lemon *);
220void ReportTable(struct lemon *, int);
221void ReportHeader(struct lemon *);
222void CompressTables(struct lemon *);
223void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000224
225/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000226void SetSize(int); /* All sets will be of size N */
227char *SetNew(void); /* A new set for element 0..N */
228void SetFree(char*); /* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +0000229int SetAdd(char*,int); /* Add element to a set */
230int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000231#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
232
233/********** From the file "struct.h" *************************************/
234/*
235** Principal data structures for the LEMON parser generator.
236*/
237
drhaa9f1122007-08-23 02:50:56 +0000238typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000239
240/* Symbols (terminals and nonterminals) of the grammar are stored
241** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000242enum symbol_type {
243 TERMINAL,
244 NONTERMINAL,
245 MULTITERMINAL
246};
247enum e_assoc {
drh75897232000-05-29 14:26:00 +0000248 LEFT,
249 RIGHT,
250 NONE,
251 UNK
icculus9e44cf12010-02-14 17:14:22 +0000252};
253struct symbol {
254 const char *name; /* Name of the symbol */
255 int index; /* Index number for this symbol */
256 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
257 struct rule *rule; /* Linked list of rules of this (if an NT) */
258 struct symbol *fallback; /* fallback token in case this token doesn't parse */
259 int prec; /* Precedence if defined (-1 otherwise) */
260 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000261 char *firstset; /* First-set for all rules of this symbol */
262 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000263 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000264 char *destructor; /* Code which executes whenever this symbol is
265 ** popped from the stack during error processing */
drh0f832dd2016-08-16 16:46:40 +0000266 int destLineno; /* Line number for start of destructor. Set to
267 ** -1 for duplicate destructors. */
drh75897232000-05-29 14:26:00 +0000268 char *datatype; /* The data type of information held by this
269 ** object. Only used if type==NONTERMINAL */
270 int dtnum; /* The data type number. In the parser, the value
271 ** stack is a union. The .yy%d element of this
272 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000273 /* The following fields are used by MULTITERMINALs only */
274 int nsubsym; /* Number of constituent symbols in the MULTI */
275 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000276};
277
278/* Each production rule in the grammar is stored in the following
279** structure. */
280struct rule {
281 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000282 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000283 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000284 int ruleline; /* Line number for the rule */
285 int nrhs; /* Number of RHS symbols */
286 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000287 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000288 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000289 const char *code; /* The code executed when this rule is reduced */
drh4dd0d3f2016-02-17 01:18:33 +0000290 const char *codePrefix; /* Setup code before code[] above */
291 const char *codeSuffix; /* Breakdown code after code[] above */
drh711c9812016-05-23 14:24:31 +0000292 int noCode; /* True if this rule has no associated C code */
293 int codeEmitted; /* True if the code has been emitted already */
drh75897232000-05-29 14:26:00 +0000294 struct symbol *precsym; /* Precedence symbol for this rule */
295 int index; /* An index number for this rule */
drh4ef07702016-03-16 19:45:54 +0000296 int iRule; /* Rule number as used in the generated tables */
drh75897232000-05-29 14:26:00 +0000297 Boolean canReduce; /* True if this rule is ever reduced */
drh756b41e2016-05-24 18:55:08 +0000298 Boolean doesReduce; /* Reduce actions occur after optimization */
drh75897232000-05-29 14:26:00 +0000299 struct rule *nextlhs; /* Next rule with the same LHS */
300 struct rule *next; /* Next rule in the global list */
301};
302
303/* A configuration is a production rule of the grammar together with
304** a mark (dot) showing how much of that rule has been processed so far.
305** Configurations also contain a follow-set which is a list of terminal
306** symbols which are allowed to immediately follow the end of the rule.
307** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000308enum cfgstatus {
309 COMPLETE,
310 INCOMPLETE
311};
drh75897232000-05-29 14:26:00 +0000312struct config {
313 struct rule *rp; /* The rule upon which the configuration is based */
314 int dot; /* The parse point */
315 char *fws; /* Follow-set for this configuration only */
316 struct plink *fplp; /* Follow-set forward propagation links */
317 struct plink *bplp; /* Follow-set backwards propagation links */
318 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000319 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000320 struct config *next; /* Next configuration in the state */
321 struct config *bp; /* The next basis configuration */
322};
323
icculus9e44cf12010-02-14 17:14:22 +0000324enum e_action {
325 SHIFT,
326 ACCEPT,
327 REDUCE,
328 ERROR,
329 SSCONFLICT, /* A shift/shift conflict */
330 SRCONFLICT, /* Was a reduce, but part of a conflict */
331 RRCONFLICT, /* Was a reduce, but part of a conflict */
332 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
333 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000334 NOT_USED, /* Deleted by compression */
335 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000336};
337
drh75897232000-05-29 14:26:00 +0000338/* Every shift or reduce operation is stored as one of the following */
339struct action {
340 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000341 enum e_action type;
drh75897232000-05-29 14:26:00 +0000342 union {
343 struct state *stp; /* The new state, if a shift */
344 struct rule *rp; /* The rule, if a reduce */
345 } x;
drhc173ad82016-05-23 16:15:02 +0000346 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
drh75897232000-05-29 14:26:00 +0000347 struct action *next; /* Next action for this state */
348 struct action *collide; /* Next action with the same hash */
349};
350
351/* Each state of the generated parser's finite state machine
352** is encoded as an instance of the following structure. */
353struct state {
354 struct config *bp; /* The basis configurations for this state */
355 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000356 int statenum; /* Sequential number for this state */
drh711c9812016-05-23 14:24:31 +0000357 struct action *ap; /* List of actions for this state */
drh8b582012003-10-21 13:16:03 +0000358 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
359 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000360 int iDfltReduce; /* Default action is to REDUCE by this rule */
361 struct rule *pDfltReduce;/* The default REDUCE rule. */
362 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000363};
drh8b582012003-10-21 13:16:03 +0000364#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000365
366/* A followset propagation link indicates that the contents of one
367** configuration followset should be propagated to another whenever
368** the first changes. */
369struct plink {
370 struct config *cfp; /* The configuration to which linked */
371 struct plink *next; /* The next propagate link */
372};
373
374/* The state vector for the entire parser generator is recorded as
375** follows. (LEMON uses no global variables and makes little use of
376** static variables. Fields in the following structure can be thought
377** of as begin global variables in the program.) */
378struct lemon {
379 struct state **sorted; /* Table of states sorted by state number */
380 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000381 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000382 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000383 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000384 int nrule; /* Number of rules */
385 int nsymbol; /* Number of terminal and nonterminal symbols */
386 int nterminal; /* Number of terminal symbols */
drh5c8241b2017-12-24 23:38:10 +0000387 int minShiftReduce; /* Minimum shift-reduce action value */
388 int errAction; /* Error action value */
389 int accAction; /* Accept action value */
390 int noAction; /* No-op action value */
391 int minReduce; /* Minimum reduce action */
392 int maxAction; /* Maximum action value of any kind */
drh75897232000-05-29 14:26:00 +0000393 struct symbol **symbols; /* Sorted array of pointers to symbols */
394 int errorcnt; /* Number of errors */
395 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000396 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000397 char *name; /* Name of the generated parser */
398 char *arg; /* Declaration of the 3th argument to parser */
399 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000400 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000401 char *start; /* Name of the start symbol for the grammar */
402 char *stacksize; /* Size of the parser stack */
403 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000404 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000405 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000406 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000407 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000408 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000409 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000410 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000411 char *filename; /* Name of the input file */
412 char *outname; /* Name of the current output file */
413 char *tokenprefix; /* A prefix added to token names in the .h file */
414 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000415 int nactiontab; /* Number of entries in the yy_action[] table */
416 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000417 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000418 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000419 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000420 char *argv0; /* Name of the program */
421};
422
423#define MemoryCheck(X) if((X)==0){ \
424 extern void memory_error(); \
425 memory_error(); \
426}
427
428/**************** From the file "table.h" *********************************/
429/*
430** All code in this file has been automatically generated
431** from a specification in the file
432** "table.q"
433** by the associative array code building program "aagen".
434** Do not edit this file! Instead, edit the specification
435** file, then rerun aagen.
436*/
437/*
438** Code for processing tables in the LEMON parser generator.
439*/
drh75897232000-05-29 14:26:00 +0000440/* Routines for handling a strings */
441
icculus9e44cf12010-02-14 17:14:22 +0000442const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000443
icculus9e44cf12010-02-14 17:14:22 +0000444void Strsafe_init(void);
445int Strsafe_insert(const char *);
446const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000447
448/* Routines for handling symbols of the grammar */
449
icculus9e44cf12010-02-14 17:14:22 +0000450struct symbol *Symbol_new(const char *);
451int Symbolcmpp(const void *, const void *);
452void Symbol_init(void);
453int Symbol_insert(struct symbol *, const char *);
454struct symbol *Symbol_find(const char *);
455struct symbol *Symbol_Nth(int);
456int Symbol_count(void);
457struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000458
459/* Routines to manage the state table */
460
icculus9e44cf12010-02-14 17:14:22 +0000461int Configcmp(const char *, const char *);
462struct state *State_new(void);
463void State_init(void);
464int State_insert(struct state *, struct config *);
465struct state *State_find(struct config *);
drh14d88552017-04-14 19:44:15 +0000466struct state **State_arrayof(void);
drh75897232000-05-29 14:26:00 +0000467
468/* Routines used for efficiency in Configlist_add */
469
icculus9e44cf12010-02-14 17:14:22 +0000470void Configtable_init(void);
471int Configtable_insert(struct config *);
472struct config *Configtable_find(struct config *);
473void Configtable_clear(int(*)(struct config *));
474
drh75897232000-05-29 14:26:00 +0000475/****************** From the file "action.c" *******************************/
476/*
477** Routines processing parser actions in the LEMON parser generator.
478*/
479
480/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000481static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000482 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000483 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000484
485 if( freelist==0 ){
486 int i;
487 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000488 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000489 if( freelist==0 ){
490 fprintf(stderr,"Unable to allocate memory for a new parser action.");
491 exit(1);
492 }
493 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
494 freelist[amt-1].next = 0;
495 }
icculus9e44cf12010-02-14 17:14:22 +0000496 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000497 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000498 return newaction;
drh75897232000-05-29 14:26:00 +0000499}
500
drhe9278182007-07-18 18:16:29 +0000501/* Compare two actions for sorting purposes. Return negative, zero, or
502** positive if the first action is less than, equal to, or greater than
503** the first
504*/
505static int actioncmp(
506 struct action *ap1,
507 struct action *ap2
508){
drh75897232000-05-29 14:26:00 +0000509 int rc;
510 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000511 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000512 rc = (int)ap1->type - (int)ap2->type;
513 }
drh3bd48ab2015-09-07 18:23:37 +0000514 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000515 rc = ap1->x.rp->index - ap2->x.rp->index;
516 }
drhe594bc32009-11-03 13:02:25 +0000517 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000518 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000519 }
drh75897232000-05-29 14:26:00 +0000520 return rc;
521}
522
523/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000524static struct action *Action_sort(
525 struct action *ap
526){
527 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
528 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000529 return ap;
530}
531
icculus9e44cf12010-02-14 17:14:22 +0000532void Action_add(
533 struct action **app,
534 enum e_action type,
535 struct symbol *sp,
536 char *arg
537){
538 struct action *newaction;
539 newaction = Action_new();
540 newaction->next = *app;
541 *app = newaction;
542 newaction->type = type;
543 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000544 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000545 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000546 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000547 }else{
icculus9e44cf12010-02-14 17:14:22 +0000548 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000549 }
550}
drh8b582012003-10-21 13:16:03 +0000551/********************** New code to implement the "acttab" module ***********/
552/*
553** This module implements routines use to construct the yy_action[] table.
554*/
555
556/*
557** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000558** the following structure.
559**
560** The yy_action table maps the pair (state_number, lookahead) into an
561** action_number. The table is an array of integers pairs. The state_number
562** determines an initial offset into the yy_action array. The lookahead
563** value is then added to this initial offset to get an index X into the
564** yy_action array. If the aAction[X].lookahead equals the value of the
565** of the lookahead input, then the value of the action_number output is
566** aAction[X].action. If the lookaheads do not match then the
567** default action for the state_number is returned.
568**
569** All actions associated with a single state_number are first entered
drh06f60d82017-04-14 19:46:12 +0000570** into aLookahead[] using multiple calls to acttab_action(). Then the
571** actions for that single state_number are placed into the aAction[]
drh8dc3e8f2010-01-07 03:53:03 +0000572** array with a single call to acttab_insert(). The acttab_insert() call
573** also resets the aLookahead[] array in preparation for the next
574** state number.
drh8b582012003-10-21 13:16:03 +0000575*/
icculus9e44cf12010-02-14 17:14:22 +0000576struct lookahead_action {
577 int lookahead; /* Value of the lookahead token */
578 int action; /* Action to take on the given lookahead */
579};
drh8b582012003-10-21 13:16:03 +0000580typedef struct acttab acttab;
581struct acttab {
582 int nAction; /* Number of used slots in aAction[] */
583 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000584 struct lookahead_action
585 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000586 *aLookahead; /* A single new transaction set */
587 int mnLookahead; /* Minimum aLookahead[].lookahead */
588 int mnAction; /* Action associated with mnLookahead */
589 int mxLookahead; /* Maximum aLookahead[].lookahead */
590 int nLookahead; /* Used slots in aLookahead[] */
591 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
592};
593
594/* Return the number of entries in the yy_action table */
595#define acttab_size(X) ((X)->nAction)
596
597/* The value for the N-th entry in yy_action */
598#define acttab_yyaction(X,N) ((X)->aAction[N].action)
599
600/* The value for the N-th entry in yy_lookahead */
601#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
602
603/* Free all memory associated with the given acttab */
604void acttab_free(acttab *p){
605 free( p->aAction );
606 free( p->aLookahead );
607 free( p );
608}
609
610/* Allocate a new acttab structure */
611acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000612 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000613 if( p==0 ){
614 fprintf(stderr,"Unable to allocate memory for a new acttab.");
615 exit(1);
616 }
617 memset(p, 0, sizeof(*p));
618 return p;
619}
620
drh06f60d82017-04-14 19:46:12 +0000621/* Add a new action to the current transaction set.
drh8dc3e8f2010-01-07 03:53:03 +0000622**
623** This routine is called once for each lookahead for a particular
624** state.
drh8b582012003-10-21 13:16:03 +0000625*/
626void acttab_action(acttab *p, int lookahead, int action){
627 if( p->nLookahead>=p->nLookaheadAlloc ){
628 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000629 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000630 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
631 if( p->aLookahead==0 ){
632 fprintf(stderr,"malloc failed\n");
633 exit(1);
634 }
635 }
636 if( p->nLookahead==0 ){
637 p->mxLookahead = lookahead;
638 p->mnLookahead = lookahead;
639 p->mnAction = action;
640 }else{
641 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
642 if( p->mnLookahead>lookahead ){
643 p->mnLookahead = lookahead;
644 p->mnAction = action;
645 }
646 }
647 p->aLookahead[p->nLookahead].lookahead = lookahead;
648 p->aLookahead[p->nLookahead].action = action;
649 p->nLookahead++;
650}
651
652/*
653** Add the transaction set built up with prior calls to acttab_action()
654** into the current action table. Then reset the transaction set back
655** to an empty set in preparation for a new round of acttab_action() calls.
656**
657** Return the offset into the action table of the new transaction.
658*/
659int acttab_insert(acttab *p){
660 int i, j, k, n;
661 assert( p->nLookahead>0 );
662
663 /* Make sure we have enough space to hold the expanded action table
664 ** in the worst case. The worst case occurs if the transaction set
665 ** must be appended to the current action table
666 */
drh784d86f2004-02-19 18:41:53 +0000667 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000668 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000669 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000670 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000671 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000672 sizeof(p->aAction[0])*p->nActionAlloc);
673 if( p->aAction==0 ){
674 fprintf(stderr,"malloc failed\n");
675 exit(1);
676 }
drhfdbf9282003-10-21 16:34:41 +0000677 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000678 p->aAction[i].lookahead = -1;
679 p->aAction[i].action = -1;
680 }
681 }
682
drh06f60d82017-04-14 19:46:12 +0000683 /* Scan the existing action table looking for an offset that is a
drh8dc3e8f2010-01-07 03:53:03 +0000684 ** duplicate of the current transaction set. Fall out of the loop
685 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000686 **
687 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
688 */
drh8dc3e8f2010-01-07 03:53:03 +0000689 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000690 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000691 /* All lookaheads and actions in the aLookahead[] transaction
692 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000693 if( p->aAction[i].action!=p->mnAction ) continue;
694 for(j=0; j<p->nLookahead; j++){
695 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
696 if( k<0 || k>=p->nAction ) break;
697 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
698 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
699 }
700 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000701
702 /* No possible lookahead value that is not in the aLookahead[]
703 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000704 n = 0;
705 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000706 if( p->aAction[j].lookahead<0 ) continue;
707 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000708 }
drhfdbf9282003-10-21 16:34:41 +0000709 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000710 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000711 }
drh8b582012003-10-21 13:16:03 +0000712 }
713 }
drh8dc3e8f2010-01-07 03:53:03 +0000714
715 /* If no existing offsets exactly match the current transaction, find an
716 ** an empty offset in the aAction[] table in which we can add the
717 ** aLookahead[] transaction.
718 */
drhf16371d2009-11-03 19:18:31 +0000719 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000720 /* Look for holes in the aAction[] table that fit the current
721 ** aLookahead[] transaction. Leave i set to the offset of the hole.
722 ** If no holes are found, i is left at p->nAction, which means the
723 ** transaction will be appended. */
724 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000725 if( p->aAction[i].lookahead<0 ){
726 for(j=0; j<p->nLookahead; j++){
727 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
728 if( k<0 ) break;
729 if( p->aAction[k].lookahead>=0 ) break;
730 }
731 if( j<p->nLookahead ) continue;
732 for(j=0; j<p->nAction; j++){
733 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
734 }
735 if( j==p->nAction ){
736 break; /* Fits in empty slots */
737 }
738 }
739 }
740 }
drh8b582012003-10-21 13:16:03 +0000741 /* Insert transaction set at index i. */
742 for(j=0; j<p->nLookahead; j++){
743 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
744 p->aAction[k] = p->aLookahead[j];
745 if( k>=p->nAction ) p->nAction = k+1;
746 }
747 p->nLookahead = 0;
748
749 /* Return the offset that is added to the lookahead in order to get the
750 ** index into yy_action of the action */
751 return i - p->mnLookahead;
752}
753
drh75897232000-05-29 14:26:00 +0000754/********************** From the file "build.c" *****************************/
755/*
756** Routines to construction the finite state machine for the LEMON
757** parser generator.
758*/
759
760/* Find a precedence symbol of every rule in the grammar.
drh06f60d82017-04-14 19:46:12 +0000761**
drh75897232000-05-29 14:26:00 +0000762** Those rules which have a precedence symbol coded in the input
763** grammar using the "[symbol]" construct will already have the
764** rp->precsym field filled. Other rules take as their precedence
765** symbol the first RHS symbol with a defined precedence. If there
766** are not RHS symbols with a defined precedence, the precedence
767** symbol field is left blank.
768*/
icculus9e44cf12010-02-14 17:14:22 +0000769void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000770{
771 struct rule *rp;
772 for(rp=xp->rule; rp; rp=rp->next){
773 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000774 int i, j;
775 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
776 struct symbol *sp = rp->rhs[i];
777 if( sp->type==MULTITERMINAL ){
778 for(j=0; j<sp->nsubsym; j++){
779 if( sp->subsym[j]->prec>=0 ){
780 rp->precsym = sp->subsym[j];
781 break;
782 }
783 }
784 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000785 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000786 }
drh75897232000-05-29 14:26:00 +0000787 }
788 }
789 }
790 return;
791}
792
793/* Find all nonterminals which will generate the empty string.
794** Then go back and compute the first sets of every nonterminal.
795** The first set is the set of all terminal symbols which can begin
796** a string generated by that nonterminal.
797*/
icculus9e44cf12010-02-14 17:14:22 +0000798void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000799{
drhfd405312005-11-06 04:06:59 +0000800 int i, j;
drh75897232000-05-29 14:26:00 +0000801 struct rule *rp;
802 int progress;
803
804 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000805 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000806 }
807 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
808 lemp->symbols[i]->firstset = SetNew();
809 }
810
811 /* First compute all lambdas */
812 do{
813 progress = 0;
814 for(rp=lemp->rule; rp; rp=rp->next){
815 if( rp->lhs->lambda ) continue;
816 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000817 struct symbol *sp = rp->rhs[i];
818 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
819 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000820 }
821 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000822 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000823 progress = 1;
824 }
825 }
826 }while( progress );
827
828 /* Now compute all first sets */
829 do{
830 struct symbol *s1, *s2;
831 progress = 0;
832 for(rp=lemp->rule; rp; rp=rp->next){
833 s1 = rp->lhs;
834 for(i=0; i<rp->nrhs; i++){
835 s2 = rp->rhs[i];
836 if( s2->type==TERMINAL ){
837 progress += SetAdd(s1->firstset,s2->index);
838 break;
drhfd405312005-11-06 04:06:59 +0000839 }else if( s2->type==MULTITERMINAL ){
840 for(j=0; j<s2->nsubsym; j++){
841 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
842 }
843 break;
drhf2f105d2012-08-20 15:53:54 +0000844 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000845 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000846 }else{
drh75897232000-05-29 14:26:00 +0000847 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000848 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000849 }
drh75897232000-05-29 14:26:00 +0000850 }
851 }
852 }while( progress );
853 return;
854}
855
856/* Compute all LR(0) states for the grammar. Links
857** are added to between some states so that the LR(1) follow sets
858** can be computed later.
859*/
icculus9e44cf12010-02-14 17:14:22 +0000860PRIVATE struct state *getstate(struct lemon *); /* forward reference */
861void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000862{
863 struct symbol *sp;
864 struct rule *rp;
865
866 Configlist_init();
867
868 /* Find the start symbol */
869 if( lemp->start ){
870 sp = Symbol_find(lemp->start);
871 if( sp==0 ){
872 ErrorMsg(lemp->filename,0,
873"The specified start symbol \"%s\" is not \
874in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000875symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000876 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000877 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000878 }
879 }else{
drh4ef07702016-03-16 19:45:54 +0000880 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000881 }
882
883 /* Make sure the start symbol doesn't occur on the right-hand side of
884 ** any rule. Report an error if it does. (YACC would generate a new
885 ** start symbol in this case.) */
886 for(rp=lemp->rule; rp; rp=rp->next){
887 int i;
888 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000889 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000890 ErrorMsg(lemp->filename,0,
891"The start symbol \"%s\" occurs on the \
892right-hand side of a rule. This will result in a parser which \
893does not work properly.",sp->name);
894 lemp->errorcnt++;
895 }
896 }
897 }
898
899 /* The basis configuration set for the first state
900 ** is all rules which have the start symbol as their
901 ** left-hand side */
902 for(rp=sp->rule; rp; rp=rp->nextlhs){
903 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000904 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000905 newcfp = Configlist_addbasis(rp,0);
906 SetAdd(newcfp->fws,0);
907 }
908
909 /* Compute the first state. All other states will be
910 ** computed automatically during the computation of the first one.
911 ** The returned pointer to the first state is not used. */
912 (void)getstate(lemp);
913 return;
914}
915
916/* Return a pointer to a state which is described by the configuration
917** list which has been built from calls to Configlist_add.
918*/
icculus9e44cf12010-02-14 17:14:22 +0000919PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
920PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000921{
922 struct config *cfp, *bp;
923 struct state *stp;
924
925 /* Extract the sorted basis of the new state. The basis was constructed
926 ** by prior calls to "Configlist_addbasis()". */
927 Configlist_sortbasis();
928 bp = Configlist_basis();
929
930 /* Get a state with the same basis */
931 stp = State_find(bp);
932 if( stp ){
933 /* A state with the same basis already exists! Copy all the follow-set
934 ** propagation links from the state under construction into the
935 ** preexisting state, then return a pointer to the preexisting state */
936 struct config *x, *y;
937 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
938 Plink_copy(&y->bplp,x->bplp);
939 Plink_delete(x->fplp);
940 x->fplp = x->bplp = 0;
941 }
942 cfp = Configlist_return();
943 Configlist_eat(cfp);
944 }else{
945 /* This really is a new state. Construct all the details */
946 Configlist_closure(lemp); /* Compute the configuration closure */
947 Configlist_sort(); /* Sort the configuration closure */
948 cfp = Configlist_return(); /* Get a pointer to the config list */
949 stp = State_new(); /* A new state structure */
950 MemoryCheck(stp);
951 stp->bp = bp; /* Remember the configuration basis */
952 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000953 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000954 stp->ap = 0; /* No actions, yet. */
955 State_insert(stp,stp->bp); /* Add to the state table */
956 buildshifts(lemp,stp); /* Recursively compute successor states */
957 }
958 return stp;
959}
960
drhfd405312005-11-06 04:06:59 +0000961/*
962** Return true if two symbols are the same.
963*/
icculus9e44cf12010-02-14 17:14:22 +0000964int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000965{
966 int i;
967 if( a==b ) return 1;
968 if( a->type!=MULTITERMINAL ) return 0;
969 if( b->type!=MULTITERMINAL ) return 0;
970 if( a->nsubsym!=b->nsubsym ) return 0;
971 for(i=0; i<a->nsubsym; i++){
972 if( a->subsym[i]!=b->subsym[i] ) return 0;
973 }
974 return 1;
975}
976
drh75897232000-05-29 14:26:00 +0000977/* Construct all successor states to the given state. A "successor"
978** state is any state which can be reached by a shift action.
979*/
icculus9e44cf12010-02-14 17:14:22 +0000980PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000981{
982 struct config *cfp; /* For looping thru the config closure of "stp" */
983 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000984 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000985 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
986 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
987 struct state *newstp; /* A pointer to a successor state */
988
989 /* Each configuration becomes complete after it contibutes to a successor
990 ** state. Initially, all configurations are incomplete */
991 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
992
993 /* Loop through all configurations of the state "stp" */
994 for(cfp=stp->cfp; cfp; cfp=cfp->next){
995 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
996 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
997 Configlist_reset(); /* Reset the new config set */
998 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
999
1000 /* For every configuration in the state "stp" which has the symbol "sp"
1001 ** following its dot, add the same configuration to the basis set under
1002 ** construction but with the dot shifted one symbol to the right. */
1003 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
1004 if( bcfp->status==COMPLETE ) continue; /* Already used */
1005 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
1006 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +00001007 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001008 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001009 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1010 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001011 }
1012
1013 /* Get a pointer to the state described by the basis configuration set
1014 ** constructed in the preceding loop */
1015 newstp = getstate(lemp);
1016
1017 /* The state "newstp" is reached from the state "stp" by a shift action
1018 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001019 if( sp->type==MULTITERMINAL ){
1020 int i;
1021 for(i=0; i<sp->nsubsym; i++){
1022 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1023 }
1024 }else{
1025 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1026 }
drh75897232000-05-29 14:26:00 +00001027 }
1028}
1029
1030/*
1031** Construct the propagation links
1032*/
icculus9e44cf12010-02-14 17:14:22 +00001033void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001034{
1035 int i;
1036 struct config *cfp, *other;
1037 struct state *stp;
1038 struct plink *plp;
1039
1040 /* Housekeeping detail:
1041 ** Add to every propagate link a pointer back to the state to
1042 ** which the link is attached. */
1043 for(i=0; i<lemp->nstate; i++){
1044 stp = lemp->sorted[i];
1045 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1046 cfp->stp = stp;
1047 }
1048 }
1049
1050 /* Convert all backlinks into forward links. Only the forward
1051 ** links are used in the follow-set computation. */
1052 for(i=0; i<lemp->nstate; i++){
1053 stp = lemp->sorted[i];
1054 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1055 for(plp=cfp->bplp; plp; plp=plp->next){
1056 other = plp->cfp;
1057 Plink_add(&other->fplp,cfp);
1058 }
1059 }
1060 }
1061}
1062
1063/* Compute all followsets.
1064**
1065** A followset is the set of all symbols which can come immediately
1066** after a configuration.
1067*/
icculus9e44cf12010-02-14 17:14:22 +00001068void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001069{
1070 int i;
1071 struct config *cfp;
1072 struct plink *plp;
1073 int progress;
1074 int change;
1075
1076 for(i=0; i<lemp->nstate; i++){
1077 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1078 cfp->status = INCOMPLETE;
1079 }
1080 }
drh06f60d82017-04-14 19:46:12 +00001081
drh75897232000-05-29 14:26:00 +00001082 do{
1083 progress = 0;
1084 for(i=0; i<lemp->nstate; i++){
1085 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1086 if( cfp->status==COMPLETE ) continue;
1087 for(plp=cfp->fplp; plp; plp=plp->next){
1088 change = SetUnion(plp->cfp->fws,cfp->fws);
1089 if( change ){
1090 plp->cfp->status = INCOMPLETE;
1091 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001092 }
1093 }
drh75897232000-05-29 14:26:00 +00001094 cfp->status = COMPLETE;
1095 }
1096 }
1097 }while( progress );
1098}
1099
drh3cb2f6e2012-01-09 14:19:05 +00001100static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001101
1102/* Compute the reduce actions, and resolve conflicts.
1103*/
icculus9e44cf12010-02-14 17:14:22 +00001104void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001105{
1106 int i,j;
1107 struct config *cfp;
1108 struct state *stp;
1109 struct symbol *sp;
1110 struct rule *rp;
1111
drh06f60d82017-04-14 19:46:12 +00001112 /* Add all of the reduce actions
drh75897232000-05-29 14:26:00 +00001113 ** A reduce action is added for each element of the followset of
1114 ** a configuration which has its dot at the extreme right.
1115 */
1116 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1117 stp = lemp->sorted[i];
1118 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1119 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1120 for(j=0; j<lemp->nterminal; j++){
1121 if( SetFind(cfp->fws,j) ){
1122 /* Add a reduce action to the state "stp" which will reduce by the
1123 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001124 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001125 }
drhf2f105d2012-08-20 15:53:54 +00001126 }
drh75897232000-05-29 14:26:00 +00001127 }
1128 }
1129 }
1130
1131 /* Add the accepting token */
1132 if( lemp->start ){
1133 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001134 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001135 }else{
drh4ef07702016-03-16 19:45:54 +00001136 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001137 }
1138 /* Add to the first state (which is always the starting state of the
1139 ** finite state machine) an action to ACCEPT if the lookahead is the
1140 ** start nonterminal. */
1141 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1142
1143 /* Resolve conflicts */
1144 for(i=0; i<lemp->nstate; i++){
1145 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001146 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001147 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001148 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001149 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001150 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1151 /* The two actions "ap" and "nap" have the same lookahead.
1152 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001153 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001154 }
1155 }
1156 }
1157
1158 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001159 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001160 for(i=0; i<lemp->nstate; i++){
1161 struct action *ap;
1162 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001163 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001164 }
1165 }
1166 for(rp=lemp->rule; rp; rp=rp->next){
1167 if( rp->canReduce ) continue;
1168 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1169 lemp->errorcnt++;
1170 }
1171}
1172
1173/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001174** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001175**
1176** NO LONGER TRUE:
1177** To resolve a conflict, first look to see if either action
1178** is on an error rule. In that case, take the action which
1179** is not associated with the error rule. If neither or both
1180** actions are associated with an error rule, then try to
1181** use precedence to resolve the conflict.
1182**
1183** If either action is a SHIFT, then it must be apx. This
1184** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1185*/
icculus9e44cf12010-02-14 17:14:22 +00001186static int resolve_conflict(
1187 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001188 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001189){
drh75897232000-05-29 14:26:00 +00001190 struct symbol *spx, *spy;
1191 int errcnt = 0;
1192 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001193 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001194 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001195 errcnt++;
1196 }
drh75897232000-05-29 14:26:00 +00001197 if( apx->type==SHIFT && apy->type==REDUCE ){
1198 spx = apx->sp;
1199 spy = apy->x.rp->precsym;
1200 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1201 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001202 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001203 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001204 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001205 apy->type = RD_RESOLVED;
1206 }else if( spx->prec<spy->prec ){
1207 apx->type = SH_RESOLVED;
1208 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1209 apy->type = RD_RESOLVED; /* associativity */
1210 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1211 apx->type = SH_RESOLVED;
1212 }else{
1213 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001214 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001215 }
1216 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1217 spx = apx->x.rp->precsym;
1218 spy = apy->x.rp->precsym;
1219 if( spx==0 || spy==0 || spx->prec<0 ||
1220 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001221 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001222 errcnt++;
1223 }else if( spx->prec>spy->prec ){
1224 apy->type = RD_RESOLVED;
1225 }else if( spx->prec<spy->prec ){
1226 apx->type = RD_RESOLVED;
1227 }
1228 }else{
drh06f60d82017-04-14 19:46:12 +00001229 assert(
drhb59499c2002-02-23 18:45:13 +00001230 apx->type==SH_RESOLVED ||
1231 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001232 apx->type==SSCONFLICT ||
1233 apx->type==SRCONFLICT ||
1234 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001235 apy->type==SH_RESOLVED ||
1236 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001237 apy->type==SSCONFLICT ||
1238 apy->type==SRCONFLICT ||
1239 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001240 );
1241 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1242 ** REDUCEs on the list. If we reach this point it must be because
1243 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001244 }
1245 return errcnt;
1246}
1247/********************* From the file "configlist.c" *************************/
1248/*
1249** Routines to processing a configuration list and building a state
1250** in the LEMON parser generator.
1251*/
1252
1253static struct config *freelist = 0; /* List of free configurations */
1254static struct config *current = 0; /* Top of list of configurations */
1255static struct config **currentend = 0; /* Last on list of configs */
1256static struct config *basis = 0; /* Top of list of basis configs */
1257static struct config **basisend = 0; /* End of list of basis configs */
1258
1259/* Return a pointer to a new configuration */
drh14d88552017-04-14 19:44:15 +00001260PRIVATE struct config *newconfig(void){
icculus9e44cf12010-02-14 17:14:22 +00001261 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001262 if( freelist==0 ){
1263 int i;
1264 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001265 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001266 if( freelist==0 ){
1267 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1268 exit(1);
1269 }
1270 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1271 freelist[amt-1].next = 0;
1272 }
icculus9e44cf12010-02-14 17:14:22 +00001273 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001274 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001275 return newcfg;
drh75897232000-05-29 14:26:00 +00001276}
1277
1278/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001279PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001280{
1281 old->next = freelist;
1282 freelist = old;
1283}
1284
1285/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001286void Configlist_init(void){
drh75897232000-05-29 14:26:00 +00001287 current = 0;
1288 currentend = &current;
1289 basis = 0;
1290 basisend = &basis;
1291 Configtable_init();
1292 return;
1293}
1294
1295/* Initialized the configuration list builder */
drh14d88552017-04-14 19:44:15 +00001296void Configlist_reset(void){
drh75897232000-05-29 14:26:00 +00001297 current = 0;
1298 currentend = &current;
1299 basis = 0;
1300 basisend = &basis;
1301 Configtable_clear(0);
1302 return;
1303}
1304
1305/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001306struct config *Configlist_add(
1307 struct rule *rp, /* The rule */
1308 int dot /* Index into the RHS of the rule where the dot goes */
1309){
drh75897232000-05-29 14:26:00 +00001310 struct config *cfp, model;
1311
1312 assert( currentend!=0 );
1313 model.rp = rp;
1314 model.dot = dot;
1315 cfp = Configtable_find(&model);
1316 if( cfp==0 ){
1317 cfp = newconfig();
1318 cfp->rp = rp;
1319 cfp->dot = dot;
1320 cfp->fws = SetNew();
1321 cfp->stp = 0;
1322 cfp->fplp = cfp->bplp = 0;
1323 cfp->next = 0;
1324 cfp->bp = 0;
1325 *currentend = cfp;
1326 currentend = &cfp->next;
1327 Configtable_insert(cfp);
1328 }
1329 return cfp;
1330}
1331
1332/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001333struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001334{
1335 struct config *cfp, model;
1336
1337 assert( basisend!=0 );
1338 assert( currentend!=0 );
1339 model.rp = rp;
1340 model.dot = dot;
1341 cfp = Configtable_find(&model);
1342 if( cfp==0 ){
1343 cfp = newconfig();
1344 cfp->rp = rp;
1345 cfp->dot = dot;
1346 cfp->fws = SetNew();
1347 cfp->stp = 0;
1348 cfp->fplp = cfp->bplp = 0;
1349 cfp->next = 0;
1350 cfp->bp = 0;
1351 *currentend = cfp;
1352 currentend = &cfp->next;
1353 *basisend = cfp;
1354 basisend = &cfp->bp;
1355 Configtable_insert(cfp);
1356 }
1357 return cfp;
1358}
1359
1360/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001361void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001362{
1363 struct config *cfp, *newcfp;
1364 struct rule *rp, *newrp;
1365 struct symbol *sp, *xsp;
1366 int i, dot;
1367
1368 assert( currentend!=0 );
1369 for(cfp=current; cfp; cfp=cfp->next){
1370 rp = cfp->rp;
1371 dot = cfp->dot;
1372 if( dot>=rp->nrhs ) continue;
1373 sp = rp->rhs[dot];
1374 if( sp->type==NONTERMINAL ){
1375 if( sp->rule==0 && sp!=lemp->errsym ){
1376 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1377 sp->name);
1378 lemp->errorcnt++;
1379 }
1380 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1381 newcfp = Configlist_add(newrp,0);
1382 for(i=dot+1; i<rp->nrhs; i++){
1383 xsp = rp->rhs[i];
1384 if( xsp->type==TERMINAL ){
1385 SetAdd(newcfp->fws,xsp->index);
1386 break;
drhfd405312005-11-06 04:06:59 +00001387 }else if( xsp->type==MULTITERMINAL ){
1388 int k;
1389 for(k=0; k<xsp->nsubsym; k++){
1390 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1391 }
1392 break;
drhf2f105d2012-08-20 15:53:54 +00001393 }else{
drh75897232000-05-29 14:26:00 +00001394 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001395 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001396 }
1397 }
drh75897232000-05-29 14:26:00 +00001398 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1399 }
1400 }
1401 }
1402 return;
1403}
1404
1405/* Sort the configuration list */
drh14d88552017-04-14 19:44:15 +00001406void Configlist_sort(void){
drh25473362015-09-04 18:03:45 +00001407 current = (struct config*)msort((char*)current,(char**)&(current->next),
1408 Configcmp);
drh75897232000-05-29 14:26:00 +00001409 currentend = 0;
1410 return;
1411}
1412
1413/* Sort the basis configuration list */
drh14d88552017-04-14 19:44:15 +00001414void Configlist_sortbasis(void){
drh25473362015-09-04 18:03:45 +00001415 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1416 Configcmp);
drh75897232000-05-29 14:26:00 +00001417 basisend = 0;
1418 return;
1419}
1420
1421/* Return a pointer to the head of the configuration list and
1422** reset the list */
drh14d88552017-04-14 19:44:15 +00001423struct config *Configlist_return(void){
drh75897232000-05-29 14:26:00 +00001424 struct config *old;
1425 old = current;
1426 current = 0;
1427 currentend = 0;
1428 return old;
1429}
1430
1431/* Return a pointer to the head of the configuration list and
1432** reset the list */
drh14d88552017-04-14 19:44:15 +00001433struct config *Configlist_basis(void){
drh75897232000-05-29 14:26:00 +00001434 struct config *old;
1435 old = basis;
1436 basis = 0;
1437 basisend = 0;
1438 return old;
1439}
1440
1441/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001442void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001443{
1444 struct config *nextcfp;
1445 for(; cfp; cfp=nextcfp){
1446 nextcfp = cfp->next;
1447 assert( cfp->fplp==0 );
1448 assert( cfp->bplp==0 );
1449 if( cfp->fws ) SetFree(cfp->fws);
1450 deleteconfig(cfp);
1451 }
1452 return;
1453}
1454/***************** From the file "error.c" *********************************/
1455/*
1456** Code for printing error message.
1457*/
1458
drhf9a2e7b2003-04-15 01:49:48 +00001459void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001460 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001461 fprintf(stderr, "%s:%d: ", filename, lineno);
1462 va_start(ap, format);
1463 vfprintf(stderr,format,ap);
1464 va_end(ap);
1465 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001466}
1467/**************** From the file "main.c" ************************************/
1468/*
1469** Main program file for the LEMON parser generator.
1470*/
1471
1472/* Report an out-of-memory condition and abort. This function
1473** is used mostly by the "MemoryCheck" macro in struct.h
1474*/
drh14d88552017-04-14 19:44:15 +00001475void memory_error(void){
drh75897232000-05-29 14:26:00 +00001476 fprintf(stderr,"Out of memory. Aborting...\n");
1477 exit(1);
1478}
1479
drh6d08b4d2004-07-20 12:45:22 +00001480static int nDefine = 0; /* Number of -D options on the command line */
1481static char **azDefine = 0; /* Name of the -D macros */
1482
1483/* This routine is called with the argument to each -D command-line option.
1484** Add the macro defined to the azDefine array.
1485*/
1486static void handle_D_option(char *z){
1487 char **paz;
1488 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001489 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001490 if( azDefine==0 ){
1491 fprintf(stderr,"out of memory\n");
1492 exit(1);
1493 }
1494 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001495 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001496 if( *paz==0 ){
1497 fprintf(stderr,"out of memory\n");
1498 exit(1);
1499 }
drh898799f2014-01-10 23:21:00 +00001500 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001501 for(z=*paz; *z && *z!='='; z++){}
1502 *z = 0;
1503}
1504
icculus3e143bd2010-02-14 00:48:49 +00001505static char *user_templatename = NULL;
1506static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001507 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001508 if( user_templatename==0 ){
1509 memory_error();
1510 }
drh898799f2014-01-10 23:21:00 +00001511 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001512}
drh75897232000-05-29 14:26:00 +00001513
drh711c9812016-05-23 14:24:31 +00001514/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001515static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1516 struct rule *pFirst = 0;
1517 struct rule **ppPrev = &pFirst;
1518 while( pA && pB ){
1519 if( pA->iRule<pB->iRule ){
1520 *ppPrev = pA;
1521 ppPrev = &pA->next;
1522 pA = pA->next;
1523 }else{
1524 *ppPrev = pB;
1525 ppPrev = &pB->next;
1526 pB = pB->next;
1527 }
1528 }
1529 if( pA ){
1530 *ppPrev = pA;
1531 }else{
1532 *ppPrev = pB;
1533 }
1534 return pFirst;
1535}
1536
1537/*
1538** Sort a list of rules in order of increasing iRule value
1539*/
1540static struct rule *Rule_sort(struct rule *rp){
1541 int i;
1542 struct rule *pNext;
1543 struct rule *x[32];
1544 memset(x, 0, sizeof(x));
1545 while( rp ){
1546 pNext = rp->next;
1547 rp->next = 0;
1548 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1549 rp = Rule_merge(x[i], rp);
1550 x[i] = 0;
1551 }
1552 x[i] = rp;
1553 rp = pNext;
1554 }
1555 rp = 0;
1556 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1557 rp = Rule_merge(x[i], rp);
1558 }
1559 return rp;
1560}
1561
drhc75e0162015-09-07 02:23:02 +00001562/* forward reference */
1563static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1564
1565/* Print a single line of the "Parser Stats" output
1566*/
1567static void stats_line(const char *zLabel, int iValue){
1568 int nLabel = lemonStrlen(zLabel);
1569 printf(" %s%.*s %5d\n", zLabel,
1570 35-nLabel, "................................",
1571 iValue);
1572}
1573
drh75897232000-05-29 14:26:00 +00001574/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001575int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001576{
1577 static int version = 0;
1578 static int rpflag = 0;
1579 static int basisflag = 0;
1580 static int compress = 0;
1581 static int quiet = 0;
1582 static int statistics = 0;
1583 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001584 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001585 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001586 static struct s_options options[] = {
1587 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1588 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001589 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001590 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001591 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001592 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001593 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1594 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001595 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001596 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1597 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001598 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001599 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001600 {OPT_FLAG, "s", (char*)&statistics,
1601 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001602 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001603 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1604 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001605 {OPT_FLAG,0,0,0}
1606 };
1607 int i;
icculus42585cf2010-02-14 05:19:56 +00001608 int exitcode;
drh75897232000-05-29 14:26:00 +00001609 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001610 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001611
drhb0c86772000-06-02 23:21:26 +00001612 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001613 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001614 printf("Lemon version 1.0\n");
drh06f60d82017-04-14 19:46:12 +00001615 exit(0);
drh75897232000-05-29 14:26:00 +00001616 }
drhb0c86772000-06-02 23:21:26 +00001617 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001618 fprintf(stderr,"Exactly one filename argument is required.\n");
1619 exit(1);
1620 }
drh954f6b42006-06-13 13:27:46 +00001621 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001622 lem.errorcnt = 0;
1623
1624 /* Initialize the machine */
1625 Strsafe_init();
1626 Symbol_init();
1627 State_init();
1628 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001629 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001630 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001631 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001632 Symbol_new("$");
1633 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001634 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001635
1636 /* Parse the input file */
1637 Parse(&lem);
1638 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001639 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001640 fprintf(stderr,"Empty grammar.\n");
1641 exit(1);
1642 }
1643
1644 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001645 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001646 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001647 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001648 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1649 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1650 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1651 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1652 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1653 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001654 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001655 lem.nterminal = i;
1656
drh711c9812016-05-23 14:24:31 +00001657 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1658 ** reduce action C-code associated with them last, so that the switch()
1659 ** statement that selects reduction actions will have a smaller jump table.
1660 */
drh4ef07702016-03-16 19:45:54 +00001661 for(i=0, rp=lem.rule; rp; rp=rp->next){
1662 rp->iRule = rp->code ? i++ : -1;
1663 }
1664 for(rp=lem.rule; rp; rp=rp->next){
1665 if( rp->iRule<0 ) rp->iRule = i++;
1666 }
1667 lem.startRule = lem.rule;
1668 lem.rule = Rule_sort(lem.rule);
1669
drh75897232000-05-29 14:26:00 +00001670 /* Generate a reprint of the grammar, if requested on the command line */
1671 if( rpflag ){
1672 Reprint(&lem);
1673 }else{
1674 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001675 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001676
1677 /* Find the precedence for every production rule (that has one) */
1678 FindRulePrecedences(&lem);
1679
1680 /* Compute the lambda-nonterminals and the first-sets for every
1681 ** nonterminal */
1682 FindFirstSets(&lem);
1683
1684 /* Compute all LR(0) states. Also record follow-set propagation
1685 ** links so that the follow-set can be computed later */
1686 lem.nstate = 0;
1687 FindStates(&lem);
1688 lem.sorted = State_arrayof();
1689
1690 /* Tie up loose ends on the propagation links */
1691 FindLinks(&lem);
1692
1693 /* Compute the follow set of every reducible configuration */
1694 FindFollowSets(&lem);
1695
1696 /* Compute the action tables */
1697 FindActions(&lem);
1698
1699 /* Compress the action tables */
1700 if( compress==0 ) CompressTables(&lem);
1701
drhada354d2005-11-05 15:03:59 +00001702 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001703 ** occur at the end. This is an optimization that helps make the
1704 ** generated parser tables smaller. */
1705 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001706
drh75897232000-05-29 14:26:00 +00001707 /* Generate a report of the parser generated. (the "y.output" file) */
1708 if( !quiet ) ReportOutput(&lem);
1709
1710 /* Generate the source code for the parser */
1711 ReportTable(&lem, mhflag);
1712
1713 /* Produce a header file for use by the scanner. (This step is
1714 ** omitted if the "-m" option is used because makeheaders will
1715 ** generate the file for us.) */
1716 if( !mhflag ) ReportHeader(&lem);
1717 }
1718 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001719 printf("Parser statistics:\n");
1720 stats_line("terminal symbols", lem.nterminal);
1721 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1722 stats_line("total symbols", lem.nsymbol);
1723 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001724 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001725 stats_line("conflicts", lem.nconflict);
1726 stats_line("action table entries", lem.nactiontab);
1727 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001728 }
icculus8e158022010-02-16 16:09:03 +00001729 if( lem.nconflict > 0 ){
1730 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001731 }
1732
1733 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001734 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001735 exit(exitcode);
1736 return (exitcode);
drh75897232000-05-29 14:26:00 +00001737}
1738/******************** From the file "msort.c" *******************************/
1739/*
1740** A generic merge-sort program.
1741**
1742** USAGE:
1743** Let "ptr" be a pointer to some structure which is at the head of
1744** a null-terminated list. Then to sort the list call:
1745**
1746** ptr = msort(ptr,&(ptr->next),cmpfnc);
1747**
1748** In the above, "cmpfnc" is a pointer to a function which compares
1749** two instances of the structure and returns an integer, as in
1750** strcmp. The second argument is a pointer to the pointer to the
1751** second element of the linked list. This address is used to compute
1752** the offset to the "next" field within the structure. The offset to
1753** the "next" field must be constant for all structures in the list.
1754**
1755** The function returns a new pointer which is the head of the list
1756** after sorting.
1757**
1758** ALGORITHM:
1759** Merge-sort.
1760*/
1761
1762/*
1763** Return a pointer to the next structure in the linked list.
1764*/
drhd25d6922012-04-18 09:59:56 +00001765#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001766
1767/*
1768** Inputs:
1769** a: A sorted, null-terminated linked list. (May be null).
1770** b: A sorted, null-terminated linked list. (May be null).
1771** cmp: A pointer to the comparison function.
1772** offset: Offset in the structure to the "next" field.
1773**
1774** Return Value:
1775** A pointer to the head of a sorted list containing the elements
1776** of both a and b.
1777**
1778** Side effects:
1779** The "next" pointers for elements in the lists a and b are
1780** changed.
1781*/
drhe9278182007-07-18 18:16:29 +00001782static char *merge(
1783 char *a,
1784 char *b,
1785 int (*cmp)(const char*,const char*),
1786 int offset
1787){
drh75897232000-05-29 14:26:00 +00001788 char *ptr, *head;
1789
1790 if( a==0 ){
1791 head = b;
1792 }else if( b==0 ){
1793 head = a;
1794 }else{
drhe594bc32009-11-03 13:02:25 +00001795 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001796 ptr = a;
1797 a = NEXT(a);
1798 }else{
1799 ptr = b;
1800 b = NEXT(b);
1801 }
1802 head = ptr;
1803 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001804 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001805 NEXT(ptr) = a;
1806 ptr = a;
1807 a = NEXT(a);
1808 }else{
1809 NEXT(ptr) = b;
1810 ptr = b;
1811 b = NEXT(b);
1812 }
1813 }
1814 if( a ) NEXT(ptr) = a;
1815 else NEXT(ptr) = b;
1816 }
1817 return head;
1818}
1819
1820/*
1821** Inputs:
1822** list: Pointer to a singly-linked list of structures.
1823** next: Pointer to pointer to the second element of the list.
1824** cmp: A comparison function.
1825**
1826** Return Value:
1827** A pointer to the head of a sorted list containing the elements
1828** orginally in list.
1829**
1830** Side effects:
1831** The "next" pointers for elements in list are changed.
1832*/
1833#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001834static char *msort(
1835 char *list,
1836 char **next,
1837 int (*cmp)(const char*,const char*)
1838){
drhba99af52001-10-25 20:37:16 +00001839 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001840 char *ep;
1841 char *set[LISTSIZE];
1842 int i;
drh1cc0d112015-03-31 15:15:48 +00001843 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001844 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1845 while( list ){
1846 ep = list;
1847 list = NEXT(list);
1848 NEXT(ep) = 0;
1849 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1850 ep = merge(ep,set[i],cmp,offset);
1851 set[i] = 0;
1852 }
1853 set[i] = ep;
1854 }
1855 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001856 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001857 return ep;
1858}
1859/************************ From the file "option.c" **************************/
1860static char **argv;
1861static struct s_options *op;
1862static FILE *errstream;
1863
1864#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1865
1866/*
1867** Print the command line with a carrot pointing to the k-th character
1868** of the n-th field.
1869*/
icculus9e44cf12010-02-14 17:14:22 +00001870static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001871{
1872 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001873 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001874 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001875 for(i=1; i<n && argv[i]; i++){
1876 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001877 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001878 }
1879 spcnt += k;
1880 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1881 if( spcnt<20 ){
1882 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1883 }else{
1884 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1885 }
1886}
1887
1888/*
1889** Return the index of the N-th non-switch argument. Return -1
1890** if N is out of range.
1891*/
icculus9e44cf12010-02-14 17:14:22 +00001892static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001893{
1894 int i;
1895 int dashdash = 0;
1896 if( argv!=0 && *argv!=0 ){
1897 for(i=1; argv[i]; i++){
1898 if( dashdash || !ISOPT(argv[i]) ){
1899 if( n==0 ) return i;
1900 n--;
1901 }
1902 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1903 }
1904 }
1905 return -1;
1906}
1907
1908static char emsg[] = "Command line syntax error: ";
1909
1910/*
1911** Process a flag command line argument.
1912*/
icculus9e44cf12010-02-14 17:14:22 +00001913static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001914{
1915 int v;
1916 int errcnt = 0;
1917 int j;
1918 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001919 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001920 }
1921 v = argv[i][0]=='-' ? 1 : 0;
1922 if( op[j].label==0 ){
1923 if( err ){
1924 fprintf(err,"%sundefined option.\n",emsg);
1925 errline(i,1,err);
1926 }
1927 errcnt++;
drh0325d392015-01-01 19:11:22 +00001928 }else if( op[j].arg==0 ){
1929 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001930 }else if( op[j].type==OPT_FLAG ){
1931 *((int*)op[j].arg) = v;
1932 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001933 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001934 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001935 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001936 }else{
1937 if( err ){
1938 fprintf(err,"%smissing argument on switch.\n",emsg);
1939 errline(i,1,err);
1940 }
1941 errcnt++;
1942 }
1943 return errcnt;
1944}
1945
1946/*
1947** Process a command line switch which has an argument.
1948*/
icculus9e44cf12010-02-14 17:14:22 +00001949static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001950{
1951 int lv = 0;
1952 double dv = 0.0;
1953 char *sv = 0, *end;
1954 char *cp;
1955 int j;
1956 int errcnt = 0;
1957 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001958 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001959 *cp = 0;
1960 for(j=0; op[j].label; j++){
1961 if( strcmp(argv[i],op[j].label)==0 ) break;
1962 }
1963 *cp = '=';
1964 if( op[j].label==0 ){
1965 if( err ){
1966 fprintf(err,"%sundefined option.\n",emsg);
1967 errline(i,0,err);
1968 }
1969 errcnt++;
1970 }else{
1971 cp++;
1972 switch( op[j].type ){
1973 case OPT_FLAG:
1974 case OPT_FFLAG:
1975 if( err ){
1976 fprintf(err,"%soption requires an argument.\n",emsg);
1977 errline(i,0,err);
1978 }
1979 errcnt++;
1980 break;
1981 case OPT_DBL:
1982 case OPT_FDBL:
1983 dv = strtod(cp,&end);
1984 if( *end ){
1985 if( err ){
drh25473362015-09-04 18:03:45 +00001986 fprintf(err,
1987 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001988 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001989 }
1990 errcnt++;
1991 }
1992 break;
1993 case OPT_INT:
1994 case OPT_FINT:
1995 lv = strtol(cp,&end,0);
1996 if( *end ){
1997 if( err ){
1998 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001999 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00002000 }
2001 errcnt++;
2002 }
2003 break;
2004 case OPT_STR:
2005 case OPT_FSTR:
2006 sv = cp;
2007 break;
2008 }
2009 switch( op[j].type ){
2010 case OPT_FLAG:
2011 case OPT_FFLAG:
2012 break;
2013 case OPT_DBL:
2014 *(double*)(op[j].arg) = dv;
2015 break;
2016 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002017 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002018 break;
2019 case OPT_INT:
2020 *(int*)(op[j].arg) = lv;
2021 break;
2022 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002023 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002024 break;
2025 case OPT_STR:
2026 *(char**)(op[j].arg) = sv;
2027 break;
2028 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002029 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002030 break;
2031 }
2032 }
2033 return errcnt;
2034}
2035
icculus9e44cf12010-02-14 17:14:22 +00002036int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002037{
2038 int errcnt = 0;
2039 argv = a;
2040 op = o;
2041 errstream = err;
2042 if( argv && *argv && op ){
2043 int i;
2044 for(i=1; argv[i]; i++){
2045 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2046 errcnt += handleflags(i,err);
2047 }else if( strchr(argv[i],'=') ){
2048 errcnt += handleswitch(i,err);
2049 }
2050 }
2051 }
2052 if( errcnt>0 ){
2053 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002054 OptPrint();
drh75897232000-05-29 14:26:00 +00002055 exit(1);
2056 }
2057 return 0;
2058}
2059
drh14d88552017-04-14 19:44:15 +00002060int OptNArgs(void){
drh75897232000-05-29 14:26:00 +00002061 int cnt = 0;
2062 int dashdash = 0;
2063 int i;
2064 if( argv!=0 && argv[0]!=0 ){
2065 for(i=1; argv[i]; i++){
2066 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2067 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2068 }
2069 }
2070 return cnt;
2071}
2072
icculus9e44cf12010-02-14 17:14:22 +00002073char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002074{
2075 int i;
2076 i = argindex(n);
2077 return i>=0 ? argv[i] : 0;
2078}
2079
icculus9e44cf12010-02-14 17:14:22 +00002080void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002081{
2082 int i;
2083 i = argindex(n);
2084 if( i>=0 ) errline(i,0,errstream);
2085}
2086
drh14d88552017-04-14 19:44:15 +00002087void OptPrint(void){
drh75897232000-05-29 14:26:00 +00002088 int i;
2089 int max, len;
2090 max = 0;
2091 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002092 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002093 switch( op[i].type ){
2094 case OPT_FLAG:
2095 case OPT_FFLAG:
2096 break;
2097 case OPT_INT:
2098 case OPT_FINT:
2099 len += 9; /* length of "<integer>" */
2100 break;
2101 case OPT_DBL:
2102 case OPT_FDBL:
2103 len += 6; /* length of "<real>" */
2104 break;
2105 case OPT_STR:
2106 case OPT_FSTR:
2107 len += 8; /* length of "<string>" */
2108 break;
2109 }
2110 if( len>max ) max = len;
2111 }
2112 for(i=0; op[i].label; i++){
2113 switch( op[i].type ){
2114 case OPT_FLAG:
2115 case OPT_FFLAG:
2116 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2117 break;
2118 case OPT_INT:
2119 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002120 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002121 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002122 break;
2123 case OPT_DBL:
2124 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002125 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002126 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002127 break;
2128 case OPT_STR:
2129 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002130 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002131 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002132 break;
2133 }
2134 }
2135}
2136/*********************** From the file "parse.c" ****************************/
2137/*
2138** Input file parser for the LEMON parser generator.
2139*/
2140
2141/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002142enum e_state {
2143 INITIALIZE,
2144 WAITING_FOR_DECL_OR_RULE,
2145 WAITING_FOR_DECL_KEYWORD,
2146 WAITING_FOR_DECL_ARG,
2147 WAITING_FOR_PRECEDENCE_SYMBOL,
2148 WAITING_FOR_ARROW,
2149 IN_RHS,
2150 LHS_ALIAS_1,
2151 LHS_ALIAS_2,
2152 LHS_ALIAS_3,
2153 RHS_ALIAS_1,
2154 RHS_ALIAS_2,
2155 PRECEDENCE_MARK_1,
2156 PRECEDENCE_MARK_2,
2157 RESYNC_AFTER_RULE_ERROR,
2158 RESYNC_AFTER_DECL_ERROR,
2159 WAITING_FOR_DESTRUCTOR_SYMBOL,
2160 WAITING_FOR_DATATYPE_SYMBOL,
2161 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002162 WAITING_FOR_WILDCARD_ID,
2163 WAITING_FOR_CLASS_ID,
drh59c435a2017-08-02 03:21:11 +00002164 WAITING_FOR_CLASS_TOKEN,
2165 WAITING_FOR_TOKEN_NAME
icculus9e44cf12010-02-14 17:14:22 +00002166};
drh75897232000-05-29 14:26:00 +00002167struct pstate {
2168 char *filename; /* Name of the input file */
2169 int tokenlineno; /* Linenumber at which current token starts */
2170 int errorcnt; /* Number of errors so far */
2171 char *tokenstart; /* Text of current token */
2172 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002173 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002174 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002175 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002176 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002177 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002178 int nrhs; /* Number of right-hand side symbols seen */
2179 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002180 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002181 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002182 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002183 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002184 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002185 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002186 enum e_assoc declassoc; /* Assign this association to decl arguments */
2187 int preccounter; /* Assign this precedence to decl arguments */
2188 struct rule *firstrule; /* Pointer to first rule in the grammar */
2189 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2190};
2191
2192/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002193static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002194{
icculus9e44cf12010-02-14 17:14:22 +00002195 const char *x;
drh75897232000-05-29 14:26:00 +00002196 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2197#if 0
2198 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2199 x,psp->state);
2200#endif
2201 switch( psp->state ){
2202 case INITIALIZE:
2203 psp->prevrule = 0;
2204 psp->preccounter = 0;
2205 psp->firstrule = psp->lastrule = 0;
2206 psp->gp->nrule = 0;
2207 /* Fall thru to next case */
2208 case WAITING_FOR_DECL_OR_RULE:
2209 if( x[0]=='%' ){
2210 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002211 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002212 psp->lhs = Symbol_new(x);
2213 psp->nrhs = 0;
2214 psp->lhsalias = 0;
2215 psp->state = WAITING_FOR_ARROW;
2216 }else if( x[0]=='{' ){
2217 if( psp->prevrule==0 ){
2218 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002219"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002220fragment which begins on this line.");
2221 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002222 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002223 ErrorMsg(psp->filename,psp->tokenlineno,
2224"Code fragment beginning on this line is not the first \
2225to follow the previous rule.");
2226 psp->errorcnt++;
2227 }else{
2228 psp->prevrule->line = psp->tokenlineno;
2229 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002230 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002231 }
drh75897232000-05-29 14:26:00 +00002232 }else if( x[0]=='[' ){
2233 psp->state = PRECEDENCE_MARK_1;
2234 }else{
2235 ErrorMsg(psp->filename,psp->tokenlineno,
2236 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2237 x);
2238 psp->errorcnt++;
2239 }
2240 break;
2241 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002242 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002243 ErrorMsg(psp->filename,psp->tokenlineno,
2244 "The precedence symbol must be a terminal.");
2245 psp->errorcnt++;
2246 }else if( psp->prevrule==0 ){
2247 ErrorMsg(psp->filename,psp->tokenlineno,
2248 "There is no prior rule to assign precedence \"[%s]\".",x);
2249 psp->errorcnt++;
2250 }else if( psp->prevrule->precsym!=0 ){
2251 ErrorMsg(psp->filename,psp->tokenlineno,
2252"Precedence mark on this line is not the first \
2253to follow the previous rule.");
2254 psp->errorcnt++;
2255 }else{
2256 psp->prevrule->precsym = Symbol_new(x);
2257 }
2258 psp->state = PRECEDENCE_MARK_2;
2259 break;
2260 case PRECEDENCE_MARK_2:
2261 if( x[0]!=']' ){
2262 ErrorMsg(psp->filename,psp->tokenlineno,
2263 "Missing \"]\" on precedence mark.");
2264 psp->errorcnt++;
2265 }
2266 psp->state = WAITING_FOR_DECL_OR_RULE;
2267 break;
2268 case WAITING_FOR_ARROW:
2269 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2270 psp->state = IN_RHS;
2271 }else if( x[0]=='(' ){
2272 psp->state = LHS_ALIAS_1;
2273 }else{
2274 ErrorMsg(psp->filename,psp->tokenlineno,
2275 "Expected to see a \":\" following the LHS symbol \"%s\".",
2276 psp->lhs->name);
2277 psp->errorcnt++;
2278 psp->state = RESYNC_AFTER_RULE_ERROR;
2279 }
2280 break;
2281 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002282 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002283 psp->lhsalias = x;
2284 psp->state = LHS_ALIAS_2;
2285 }else{
2286 ErrorMsg(psp->filename,psp->tokenlineno,
2287 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2288 x,psp->lhs->name);
2289 psp->errorcnt++;
2290 psp->state = RESYNC_AFTER_RULE_ERROR;
2291 }
2292 break;
2293 case LHS_ALIAS_2:
2294 if( x[0]==')' ){
2295 psp->state = LHS_ALIAS_3;
2296 }else{
2297 ErrorMsg(psp->filename,psp->tokenlineno,
2298 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2299 psp->errorcnt++;
2300 psp->state = RESYNC_AFTER_RULE_ERROR;
2301 }
2302 break;
2303 case LHS_ALIAS_3:
2304 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2305 psp->state = IN_RHS;
2306 }else{
2307 ErrorMsg(psp->filename,psp->tokenlineno,
2308 "Missing \"->\" following: \"%s(%s)\".",
2309 psp->lhs->name,psp->lhsalias);
2310 psp->errorcnt++;
2311 psp->state = RESYNC_AFTER_RULE_ERROR;
2312 }
2313 break;
2314 case IN_RHS:
2315 if( x[0]=='.' ){
2316 struct rule *rp;
drh06f60d82017-04-14 19:46:12 +00002317 rp = (struct rule *)calloc( sizeof(struct rule) +
drh9892c5d2007-12-21 00:02:11 +00002318 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002319 if( rp==0 ){
2320 ErrorMsg(psp->filename,psp->tokenlineno,
2321 "Can't allocate enough memory for this rule.");
2322 psp->errorcnt++;
2323 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002324 }else{
drh75897232000-05-29 14:26:00 +00002325 int i;
2326 rp->ruleline = psp->tokenlineno;
2327 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002328 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002329 for(i=0; i<psp->nrhs; i++){
2330 rp->rhs[i] = psp->rhs[i];
2331 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002332 }
drh75897232000-05-29 14:26:00 +00002333 rp->lhs = psp->lhs;
2334 rp->lhsalias = psp->lhsalias;
2335 rp->nrhs = psp->nrhs;
2336 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002337 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002338 rp->precsym = 0;
2339 rp->index = psp->gp->nrule++;
2340 rp->nextlhs = rp->lhs->rule;
2341 rp->lhs->rule = rp;
2342 rp->next = 0;
2343 if( psp->firstrule==0 ){
2344 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002345 }else{
drh75897232000-05-29 14:26:00 +00002346 psp->lastrule->next = rp;
2347 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002348 }
drh75897232000-05-29 14:26:00 +00002349 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002350 }
drh75897232000-05-29 14:26:00 +00002351 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002352 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002353 if( psp->nrhs>=MAXRHS ){
2354 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002355 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002356 x);
2357 psp->errorcnt++;
2358 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002359 }else{
drh75897232000-05-29 14:26:00 +00002360 psp->rhs[psp->nrhs] = Symbol_new(x);
2361 psp->alias[psp->nrhs] = 0;
2362 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002363 }
drhfd405312005-11-06 04:06:59 +00002364 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2365 struct symbol *msp = psp->rhs[psp->nrhs-1];
2366 if( msp->type!=MULTITERMINAL ){
2367 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002368 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002369 memset(msp, 0, sizeof(*msp));
2370 msp->type = MULTITERMINAL;
2371 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002372 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002373 msp->subsym[0] = origsp;
2374 msp->name = origsp->name;
2375 psp->rhs[psp->nrhs-1] = msp;
2376 }
2377 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002378 msp->subsym = (struct symbol **) realloc(msp->subsym,
2379 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002380 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002381 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002382 ErrorMsg(psp->filename,psp->tokenlineno,
2383 "Cannot form a compound containing a non-terminal");
2384 psp->errorcnt++;
2385 }
drh75897232000-05-29 14:26:00 +00002386 }else if( x[0]=='(' && psp->nrhs>0 ){
2387 psp->state = RHS_ALIAS_1;
2388 }else{
2389 ErrorMsg(psp->filename,psp->tokenlineno,
2390 "Illegal character on RHS of rule: \"%s\".",x);
2391 psp->errorcnt++;
2392 psp->state = RESYNC_AFTER_RULE_ERROR;
2393 }
2394 break;
2395 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002396 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002397 psp->alias[psp->nrhs-1] = x;
2398 psp->state = RHS_ALIAS_2;
2399 }else{
2400 ErrorMsg(psp->filename,psp->tokenlineno,
2401 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2402 x,psp->rhs[psp->nrhs-1]->name);
2403 psp->errorcnt++;
2404 psp->state = RESYNC_AFTER_RULE_ERROR;
2405 }
2406 break;
2407 case RHS_ALIAS_2:
2408 if( x[0]==')' ){
2409 psp->state = IN_RHS;
2410 }else{
2411 ErrorMsg(psp->filename,psp->tokenlineno,
2412 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2413 psp->errorcnt++;
2414 psp->state = RESYNC_AFTER_RULE_ERROR;
2415 }
2416 break;
2417 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002418 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002419 psp->declkeyword = x;
2420 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002421 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002422 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002423 psp->state = WAITING_FOR_DECL_ARG;
2424 if( strcmp(x,"name")==0 ){
2425 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002426 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002427 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002428 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002429 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002430 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002431 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002432 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002433 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002434 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002435 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002436 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002437 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002438 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002439 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002440 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002441 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002442 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002443 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002444 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002445 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002446 }else if( strcmp(x,"extra_argument")==0 ){
2447 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002448 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002449 }else if( strcmp(x,"token_type")==0 ){
2450 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002451 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002452 }else if( strcmp(x,"default_type")==0 ){
2453 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002454 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002455 }else if( strcmp(x,"stack_size")==0 ){
2456 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002457 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002458 }else if( strcmp(x,"start_symbol")==0 ){
2459 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002460 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002461 }else if( strcmp(x,"left")==0 ){
2462 psp->preccounter++;
2463 psp->declassoc = LEFT;
2464 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2465 }else if( strcmp(x,"right")==0 ){
2466 psp->preccounter++;
2467 psp->declassoc = RIGHT;
2468 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2469 }else if( strcmp(x,"nonassoc")==0 ){
2470 psp->preccounter++;
2471 psp->declassoc = NONE;
2472 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002473 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002474 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002475 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002476 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002477 }else if( strcmp(x,"fallback")==0 ){
2478 psp->fallback = 0;
2479 psp->state = WAITING_FOR_FALLBACK_ID;
drh59c435a2017-08-02 03:21:11 +00002480 }else if( strcmp(x,"token")==0 ){
2481 psp->state = WAITING_FOR_TOKEN_NAME;
drhe09daa92006-06-10 13:29:31 +00002482 }else if( strcmp(x,"wildcard")==0 ){
2483 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002484 }else if( strcmp(x,"token_class")==0 ){
2485 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002486 }else{
2487 ErrorMsg(psp->filename,psp->tokenlineno,
2488 "Unknown declaration keyword: \"%%%s\".",x);
2489 psp->errorcnt++;
2490 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002491 }
drh75897232000-05-29 14:26:00 +00002492 }else{
2493 ErrorMsg(psp->filename,psp->tokenlineno,
2494 "Illegal declaration keyword: \"%s\".",x);
2495 psp->errorcnt++;
2496 psp->state = RESYNC_AFTER_DECL_ERROR;
2497 }
2498 break;
2499 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002500 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002501 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002502 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002503 psp->errorcnt++;
2504 psp->state = RESYNC_AFTER_DECL_ERROR;
2505 }else{
icculusd286fa62010-03-03 17:06:32 +00002506 struct symbol *sp = Symbol_new(x);
2507 psp->declargslot = &sp->destructor;
2508 psp->decllinenoslot = &sp->destLineno;
2509 psp->insertLineMacro = 1;
2510 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002511 }
2512 break;
2513 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002514 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002515 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002516 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002517 psp->errorcnt++;
2518 psp->state = RESYNC_AFTER_DECL_ERROR;
2519 }else{
icculus866bf1e2010-02-17 20:31:32 +00002520 struct symbol *sp = Symbol_find(x);
2521 if((sp) && (sp->datatype)){
2522 ErrorMsg(psp->filename,psp->tokenlineno,
2523 "Symbol %%type \"%s\" already defined", x);
2524 psp->errorcnt++;
2525 psp->state = RESYNC_AFTER_DECL_ERROR;
2526 }else{
2527 if (!sp){
2528 sp = Symbol_new(x);
2529 }
2530 psp->declargslot = &sp->datatype;
2531 psp->insertLineMacro = 0;
2532 psp->state = WAITING_FOR_DECL_ARG;
2533 }
drh75897232000-05-29 14:26:00 +00002534 }
2535 break;
2536 case WAITING_FOR_PRECEDENCE_SYMBOL:
2537 if( x[0]=='.' ){
2538 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002539 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002540 struct symbol *sp;
2541 sp = Symbol_new(x);
2542 if( sp->prec>=0 ){
2543 ErrorMsg(psp->filename,psp->tokenlineno,
2544 "Symbol \"%s\" has already be given a precedence.",x);
2545 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002546 }else{
drh75897232000-05-29 14:26:00 +00002547 sp->prec = psp->preccounter;
2548 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002549 }
drh75897232000-05-29 14:26:00 +00002550 }else{
2551 ErrorMsg(psp->filename,psp->tokenlineno,
2552 "Can't assign a precedence to \"%s\".",x);
2553 psp->errorcnt++;
2554 }
2555 break;
2556 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002557 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002558 const char *zOld, *zNew;
2559 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002560 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002561 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002562 char zLine[50];
2563 zNew = x;
2564 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002565 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002566 if( *psp->declargslot ){
2567 zOld = *psp->declargslot;
2568 }else{
2569 zOld = "";
2570 }
drh87cf1372008-08-13 20:09:06 +00002571 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002572 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002573 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002574 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2575 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002576 for(z=psp->filename, nBack=0; *z; z++){
2577 if( *z=='\\' ) nBack++;
2578 }
drh898799f2014-01-10 23:21:00 +00002579 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002580 nLine = lemonStrlen(zLine);
2581 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002582 }
icculus9e44cf12010-02-14 17:14:22 +00002583 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2584 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002585 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002586 if( nOld && zBuf[-1]!='\n' ){
2587 *(zBuf++) = '\n';
2588 }
2589 memcpy(zBuf, zLine, nLine);
2590 zBuf += nLine;
2591 *(zBuf++) = '"';
2592 for(z=psp->filename; *z; z++){
2593 if( *z=='\\' ){
2594 *(zBuf++) = '\\';
2595 }
2596 *(zBuf++) = *z;
2597 }
2598 *(zBuf++) = '"';
2599 *(zBuf++) = '\n';
2600 }
drh4dc8ef52008-07-01 17:13:57 +00002601 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2602 psp->decllinenoslot[0] = psp->tokenlineno;
2603 }
drha5808f32008-04-27 22:19:44 +00002604 memcpy(zBuf, zNew, nNew);
2605 zBuf += nNew;
2606 *zBuf = 0;
2607 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002608 }else{
2609 ErrorMsg(psp->filename,psp->tokenlineno,
2610 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2611 psp->errorcnt++;
2612 psp->state = RESYNC_AFTER_DECL_ERROR;
2613 }
2614 break;
drh0bd1f4e2002-06-06 18:54:39 +00002615 case WAITING_FOR_FALLBACK_ID:
2616 if( x[0]=='.' ){
2617 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002618 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002619 ErrorMsg(psp->filename, psp->tokenlineno,
2620 "%%fallback argument \"%s\" should be a token", x);
2621 psp->errorcnt++;
2622 }else{
2623 struct symbol *sp = Symbol_new(x);
2624 if( psp->fallback==0 ){
2625 psp->fallback = sp;
2626 }else if( sp->fallback ){
2627 ErrorMsg(psp->filename, psp->tokenlineno,
2628 "More than one fallback assigned to token %s", x);
2629 psp->errorcnt++;
2630 }else{
2631 sp->fallback = psp->fallback;
2632 psp->gp->has_fallback = 1;
2633 }
2634 }
2635 break;
drh59c435a2017-08-02 03:21:11 +00002636 case WAITING_FOR_TOKEN_NAME:
2637 /* Tokens do not have to be declared before use. But they can be
2638 ** in order to control their assigned integer number. The number for
2639 ** each token is assigned when it is first seen. So by including
2640 **
2641 ** %token ONE TWO THREE
2642 **
2643 ** early in the grammar file, that assigns small consecutive values
2644 ** to each of the tokens ONE TWO and THREE.
2645 */
2646 if( x[0]=='.' ){
2647 psp->state = WAITING_FOR_DECL_OR_RULE;
2648 }else if( !ISUPPER(x[0]) ){
2649 ErrorMsg(psp->filename, psp->tokenlineno,
2650 "%%token argument \"%s\" should be a token", x);
2651 psp->errorcnt++;
2652 }else{
2653 (void)Symbol_new(x);
2654 }
2655 break;
drhe09daa92006-06-10 13:29:31 +00002656 case WAITING_FOR_WILDCARD_ID:
2657 if( x[0]=='.' ){
2658 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002659 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002660 ErrorMsg(psp->filename, psp->tokenlineno,
2661 "%%wildcard argument \"%s\" should be a token", x);
2662 psp->errorcnt++;
2663 }else{
2664 struct symbol *sp = Symbol_new(x);
2665 if( psp->gp->wildcard==0 ){
2666 psp->gp->wildcard = sp;
2667 }else{
2668 ErrorMsg(psp->filename, psp->tokenlineno,
2669 "Extra wildcard to token: %s", x);
2670 psp->errorcnt++;
2671 }
2672 }
2673 break;
drh61f92cd2014-01-11 03:06:18 +00002674 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002675 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002676 ErrorMsg(psp->filename, psp->tokenlineno,
2677 "%%token_class must be followed by an identifier: ", x);
2678 psp->errorcnt++;
2679 psp->state = RESYNC_AFTER_DECL_ERROR;
2680 }else if( Symbol_find(x) ){
2681 ErrorMsg(psp->filename, psp->tokenlineno,
2682 "Symbol \"%s\" already used", x);
2683 psp->errorcnt++;
2684 psp->state = RESYNC_AFTER_DECL_ERROR;
2685 }else{
2686 psp->tkclass = Symbol_new(x);
2687 psp->tkclass->type = MULTITERMINAL;
2688 psp->state = WAITING_FOR_CLASS_TOKEN;
2689 }
2690 break;
2691 case WAITING_FOR_CLASS_TOKEN:
2692 if( x[0]=='.' ){
2693 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002694 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002695 struct symbol *msp = psp->tkclass;
2696 msp->nsubsym++;
2697 msp->subsym = (struct symbol **) realloc(msp->subsym,
2698 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002699 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002700 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2701 }else{
2702 ErrorMsg(psp->filename, psp->tokenlineno,
2703 "%%token_class argument \"%s\" should be a token", x);
2704 psp->errorcnt++;
2705 psp->state = RESYNC_AFTER_DECL_ERROR;
2706 }
2707 break;
drh75897232000-05-29 14:26:00 +00002708 case RESYNC_AFTER_RULE_ERROR:
2709/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2710** break; */
2711 case RESYNC_AFTER_DECL_ERROR:
2712 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2713 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2714 break;
2715 }
2716}
2717
drh34ff57b2008-07-14 12:27:51 +00002718/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002719** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2720** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2721** comments them out. Text in between is also commented out as appropriate.
2722*/
danielk1977940fac92005-01-23 22:41:37 +00002723static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002724 int i, j, k, n;
2725 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002726 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002727 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002728 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002729 for(i=0; z[i]; i++){
2730 if( z[i]=='\n' ) lineno++;
2731 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002732 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002733 if( exclude ){
2734 exclude--;
2735 if( exclude==0 ){
2736 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2737 }
2738 }
2739 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002740 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2741 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002742 if( exclude ){
2743 exclude++;
2744 }else{
drhc56fac72015-10-29 13:48:15 +00002745 for(j=i+7; ISSPACE(z[j]); j++){}
2746 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002747 exclude = 1;
2748 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002749 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002750 exclude = 0;
2751 break;
2752 }
2753 }
2754 if( z[i+3]=='n' ) exclude = !exclude;
2755 if( exclude ){
2756 start = i;
2757 start_lineno = lineno;
2758 }
2759 }
2760 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2761 }
2762 }
2763 if( exclude ){
2764 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2765 exit(1);
2766 }
2767}
2768
drh75897232000-05-29 14:26:00 +00002769/* In spite of its name, this function is really a scanner. It read
2770** in the entire input file (all at once) then tokenizes it. Each
2771** token is passed to the function "parseonetoken" which builds all
2772** the appropriate data structures in the global state vector "gp".
2773*/
icculus9e44cf12010-02-14 17:14:22 +00002774void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002775{
2776 struct pstate ps;
2777 FILE *fp;
2778 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002779 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002780 int lineno;
2781 int c;
2782 char *cp, *nextcp;
2783 int startline = 0;
2784
rse38514a92007-09-20 11:34:17 +00002785 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002786 ps.gp = gp;
2787 ps.filename = gp->filename;
2788 ps.errorcnt = 0;
2789 ps.state = INITIALIZE;
2790
2791 /* Begin by reading the input file */
2792 fp = fopen(ps.filename,"rb");
2793 if( fp==0 ){
2794 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2795 gp->errorcnt++;
2796 return;
2797 }
2798 fseek(fp,0,2);
2799 filesize = ftell(fp);
2800 rewind(fp);
2801 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002802 if( filesize>100000000 || filebuf==0 ){
2803 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002804 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002805 fclose(fp);
drh75897232000-05-29 14:26:00 +00002806 return;
2807 }
2808 if( fread(filebuf,1,filesize,fp)!=filesize ){
2809 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2810 filesize);
2811 free(filebuf);
2812 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002813 fclose(fp);
drh75897232000-05-29 14:26:00 +00002814 return;
2815 }
2816 fclose(fp);
2817 filebuf[filesize] = 0;
2818
drh6d08b4d2004-07-20 12:45:22 +00002819 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2820 preprocess_input(filebuf);
2821
drh75897232000-05-29 14:26:00 +00002822 /* Now scan the text of the input file */
2823 lineno = 1;
2824 for(cp=filebuf; (c= *cp)!=0; ){
2825 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002826 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002827 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2828 cp+=2;
2829 while( (c= *cp)!=0 && c!='\n' ) cp++;
2830 continue;
2831 }
2832 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2833 cp+=2;
2834 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2835 if( c=='\n' ) lineno++;
2836 cp++;
2837 }
2838 if( c ) cp++;
2839 continue;
2840 }
2841 ps.tokenstart = cp; /* Mark the beginning of the token */
2842 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2843 if( c=='\"' ){ /* String literals */
2844 cp++;
2845 while( (c= *cp)!=0 && c!='\"' ){
2846 if( c=='\n' ) lineno++;
2847 cp++;
2848 }
2849 if( c==0 ){
2850 ErrorMsg(ps.filename,startline,
2851"String starting on this line is not terminated before the end of the file.");
2852 ps.errorcnt++;
2853 nextcp = cp;
2854 }else{
2855 nextcp = cp+1;
2856 }
2857 }else if( c=='{' ){ /* A block of C code */
2858 int level;
2859 cp++;
2860 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2861 if( c=='\n' ) lineno++;
2862 else if( c=='{' ) level++;
2863 else if( c=='}' ) level--;
2864 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2865 int prevc;
2866 cp = &cp[2];
2867 prevc = 0;
2868 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2869 if( c=='\n' ) lineno++;
2870 prevc = c;
2871 cp++;
drhf2f105d2012-08-20 15:53:54 +00002872 }
2873 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002874 cp = &cp[2];
2875 while( (c= *cp)!=0 && c!='\n' ) cp++;
2876 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002877 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002878 int startchar, prevc;
2879 startchar = c;
2880 prevc = 0;
2881 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2882 if( c=='\n' ) lineno++;
2883 if( prevc=='\\' ) prevc = 0;
2884 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002885 }
2886 }
drh75897232000-05-29 14:26:00 +00002887 }
2888 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002889 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002890"C code starting on this line is not terminated before the end of the file.");
2891 ps.errorcnt++;
2892 nextcp = cp;
2893 }else{
2894 nextcp = cp+1;
2895 }
drhc56fac72015-10-29 13:48:15 +00002896 }else if( ISALNUM(c) ){ /* Identifiers */
2897 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002898 nextcp = cp;
2899 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2900 cp += 3;
2901 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002902 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002903 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002904 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002905 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002906 }else{ /* All other (one character) operators */
2907 cp++;
2908 nextcp = cp;
2909 }
2910 c = *cp;
2911 *cp = 0; /* Null terminate the token */
2912 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002913 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002914 cp = nextcp;
2915 }
2916 free(filebuf); /* Release the buffer after parsing */
2917 gp->rule = ps.firstrule;
2918 gp->errorcnt = ps.errorcnt;
2919}
2920/*************************** From the file "plink.c" *********************/
2921/*
2922** Routines processing configuration follow-set propagation links
2923** in the LEMON parser generator.
2924*/
2925static struct plink *plink_freelist = 0;
2926
2927/* Allocate a new plink */
drh14d88552017-04-14 19:44:15 +00002928struct plink *Plink_new(void){
icculus9e44cf12010-02-14 17:14:22 +00002929 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002930
2931 if( plink_freelist==0 ){
2932 int i;
2933 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002934 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002935 if( plink_freelist==0 ){
2936 fprintf(stderr,
2937 "Unable to allocate memory for a new follow-set propagation link.\n");
2938 exit(1);
2939 }
2940 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2941 plink_freelist[amt-1].next = 0;
2942 }
icculus9e44cf12010-02-14 17:14:22 +00002943 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002944 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002945 return newlink;
drh75897232000-05-29 14:26:00 +00002946}
2947
2948/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002949void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002950{
icculus9e44cf12010-02-14 17:14:22 +00002951 struct plink *newlink;
2952 newlink = Plink_new();
2953 newlink->next = *plpp;
2954 *plpp = newlink;
2955 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002956}
2957
2958/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002959void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002960{
2961 struct plink *nextpl;
2962 while( from ){
2963 nextpl = from->next;
2964 from->next = *to;
2965 *to = from;
2966 from = nextpl;
2967 }
2968}
2969
2970/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002971void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002972{
2973 struct plink *nextpl;
2974
2975 while( plp ){
2976 nextpl = plp->next;
2977 plp->next = plink_freelist;
2978 plink_freelist = plp;
2979 plp = nextpl;
2980 }
2981}
2982/*********************** From the file "report.c" **************************/
2983/*
2984** Procedures for generating reports and tables in the LEMON parser generator.
2985*/
2986
2987/* Generate a filename with the given suffix. Space to hold the
2988** name comes from malloc() and must be freed by the calling
2989** function.
2990*/
icculus9e44cf12010-02-14 17:14:22 +00002991PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002992{
2993 char *name;
2994 char *cp;
2995
icculus9e44cf12010-02-14 17:14:22 +00002996 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002997 if( name==0 ){
2998 fprintf(stderr,"Can't allocate space for a filename.\n");
2999 exit(1);
3000 }
drh898799f2014-01-10 23:21:00 +00003001 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00003002 cp = strrchr(name,'.');
3003 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00003004 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00003005 return name;
3006}
3007
3008/* Open a file with a name based on the name of the input file,
3009** but with a different (specified) suffix, and return a pointer
3010** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00003011PRIVATE FILE *file_open(
3012 struct lemon *lemp,
3013 const char *suffix,
3014 const char *mode
3015){
drh75897232000-05-29 14:26:00 +00003016 FILE *fp;
3017
3018 if( lemp->outname ) free(lemp->outname);
3019 lemp->outname = file_makename(lemp, suffix);
3020 fp = fopen(lemp->outname,mode);
3021 if( fp==0 && *mode=='w' ){
3022 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
3023 lemp->errorcnt++;
3024 return 0;
3025 }
3026 return fp;
3027}
3028
drh5c8241b2017-12-24 23:38:10 +00003029/* Print the text of a rule
3030*/
3031void rule_print(FILE *out, struct rule *rp){
3032 int i, j;
3033 fprintf(out, "%s",rp->lhs->name);
3034 /* if( rp->lhsalias ) fprintf(out,"(%s)",rp->lhsalias); */
3035 fprintf(out," ::=");
3036 for(i=0; i<rp->nrhs; i++){
3037 struct symbol *sp = rp->rhs[i];
3038 if( sp->type==MULTITERMINAL ){
3039 fprintf(out," %s", sp->subsym[0]->name);
3040 for(j=1; j<sp->nsubsym; j++){
3041 fprintf(out,"|%s", sp->subsym[j]->name);
3042 }
3043 }else{
3044 fprintf(out," %s", sp->name);
3045 }
3046 /* if( rp->rhsalias[i] ) fprintf(out,"(%s)",rp->rhsalias[i]); */
3047 }
3048}
3049
drh06f60d82017-04-14 19:46:12 +00003050/* Duplicate the input file without comments and without actions
drh75897232000-05-29 14:26:00 +00003051** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003052void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003053{
3054 struct rule *rp;
3055 struct symbol *sp;
3056 int i, j, maxlen, len, ncolumns, skip;
3057 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3058 maxlen = 10;
3059 for(i=0; i<lemp->nsymbol; i++){
3060 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003061 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003062 if( len>maxlen ) maxlen = len;
3063 }
3064 ncolumns = 76/(maxlen+5);
3065 if( ncolumns<1 ) ncolumns = 1;
3066 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3067 for(i=0; i<skip; i++){
3068 printf("//");
3069 for(j=i; j<lemp->nsymbol; j+=skip){
3070 sp = lemp->symbols[j];
3071 assert( sp->index==j );
3072 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3073 }
3074 printf("\n");
3075 }
3076 for(rp=lemp->rule; rp; rp=rp->next){
drh5c8241b2017-12-24 23:38:10 +00003077 rule_print(stdout, rp);
drh75897232000-05-29 14:26:00 +00003078 printf(".");
3079 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003080 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003081 printf("\n");
3082 }
3083}
3084
drh7e698e92015-09-07 14:22:24 +00003085/* Print a single rule.
3086*/
3087void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003088 struct symbol *sp;
3089 int i, j;
drh75897232000-05-29 14:26:00 +00003090 fprintf(fp,"%s ::=",rp->lhs->name);
3091 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003092 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003093 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003094 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003095 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003096 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003097 for(j=1; j<sp->nsubsym; j++){
3098 fprintf(fp,"|%s",sp->subsym[j]->name);
3099 }
drh61f92cd2014-01-11 03:06:18 +00003100 }else{
3101 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003102 }
drh75897232000-05-29 14:26:00 +00003103 }
3104}
3105
drh7e698e92015-09-07 14:22:24 +00003106/* Print the rule for a configuration.
3107*/
3108void ConfigPrint(FILE *fp, struct config *cfp){
3109 RulePrint(fp, cfp->rp, cfp->dot);
3110}
3111
drh75897232000-05-29 14:26:00 +00003112/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003113#if 0
drh75897232000-05-29 14:26:00 +00003114/* Print a set */
3115PRIVATE void SetPrint(out,set,lemp)
3116FILE *out;
3117char *set;
3118struct lemon *lemp;
3119{
3120 int i;
3121 char *spacer;
3122 spacer = "";
3123 fprintf(out,"%12s[","");
3124 for(i=0; i<lemp->nterminal; i++){
3125 if( SetFind(set,i) ){
3126 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3127 spacer = " ";
3128 }
3129 }
3130 fprintf(out,"]\n");
3131}
3132
3133/* Print a plink chain */
3134PRIVATE void PlinkPrint(out,plp,tag)
3135FILE *out;
3136struct plink *plp;
3137char *tag;
3138{
3139 while( plp ){
drhada354d2005-11-05 15:03:59 +00003140 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003141 ConfigPrint(out,plp->cfp);
3142 fprintf(out,"\n");
3143 plp = plp->next;
3144 }
3145}
3146#endif
3147
3148/* Print an action to the given file descriptor. Return FALSE if
3149** nothing was actually printed.
3150*/
drh7e698e92015-09-07 14:22:24 +00003151int PrintAction(
3152 struct action *ap, /* The action to print */
3153 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003154 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003155){
drh75897232000-05-29 14:26:00 +00003156 int result = 1;
3157 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003158 case SHIFT: {
3159 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003160 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003161 break;
drh7e698e92015-09-07 14:22:24 +00003162 }
3163 case REDUCE: {
3164 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003165 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003166 RulePrint(fp, rp, -1);
3167 break;
3168 }
3169 case SHIFTREDUCE: {
3170 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003171 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003172 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003173 break;
drh7e698e92015-09-07 14:22:24 +00003174 }
drh75897232000-05-29 14:26:00 +00003175 case ACCEPT:
3176 fprintf(fp,"%*s accept",indent,ap->sp->name);
3177 break;
3178 case ERROR:
3179 fprintf(fp,"%*s error",indent,ap->sp->name);
3180 break;
drh9892c5d2007-12-21 00:02:11 +00003181 case SRCONFLICT:
3182 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003183 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003184 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003185 break;
drh9892c5d2007-12-21 00:02:11 +00003186 case SSCONFLICT:
drh06f60d82017-04-14 19:46:12 +00003187 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003188 indent,ap->sp->name,ap->x.stp->statenum);
3189 break;
drh75897232000-05-29 14:26:00 +00003190 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003191 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003192 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003193 indent,ap->sp->name,ap->x.stp->statenum);
3194 }else{
3195 result = 0;
3196 }
3197 break;
drh75897232000-05-29 14:26:00 +00003198 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003199 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003200 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003201 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003202 }else{
3203 result = 0;
3204 }
3205 break;
drh75897232000-05-29 14:26:00 +00003206 case NOT_USED:
3207 result = 0;
3208 break;
3209 }
drhc173ad82016-05-23 16:15:02 +00003210 if( result && ap->spOpt ){
3211 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3212 }
drh75897232000-05-29 14:26:00 +00003213 return result;
3214}
3215
drh3bd48ab2015-09-07 18:23:37 +00003216/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003217void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003218{
3219 int i;
3220 struct state *stp;
3221 struct config *cfp;
3222 struct action *ap;
3223 FILE *fp;
3224
drh2aa6ca42004-09-10 00:14:04 +00003225 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003226 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003227 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003228 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003229 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003230 if( lemp->basisflag ) cfp=stp->bp;
3231 else cfp=stp->cfp;
3232 while( cfp ){
3233 char buf[20];
3234 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003235 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003236 fprintf(fp," %5s ",buf);
3237 }else{
3238 fprintf(fp," ");
3239 }
3240 ConfigPrint(fp,cfp);
3241 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003242#if 0
drh75897232000-05-29 14:26:00 +00003243 SetPrint(fp,cfp->fws,lemp);
3244 PlinkPrint(fp,cfp->fplp,"To ");
3245 PlinkPrint(fp,cfp->bplp,"From");
3246#endif
3247 if( lemp->basisflag ) cfp=cfp->bp;
3248 else cfp=cfp->next;
3249 }
3250 fprintf(fp,"\n");
3251 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003252 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003253 }
3254 fprintf(fp,"\n");
3255 }
drhe9278182007-07-18 18:16:29 +00003256 fprintf(fp, "----------------------------------------------------\n");
3257 fprintf(fp, "Symbols:\n");
3258 for(i=0; i<lemp->nsymbol; i++){
3259 int j;
3260 struct symbol *sp;
3261
3262 sp = lemp->symbols[i];
3263 fprintf(fp, " %3d: %s", i, sp->name);
3264 if( sp->type==NONTERMINAL ){
3265 fprintf(fp, ":");
3266 if( sp->lambda ){
3267 fprintf(fp, " <lambda>");
3268 }
3269 for(j=0; j<lemp->nterminal; j++){
3270 if( sp->firstset && SetFind(sp->firstset, j) ){
3271 fprintf(fp, " %s", lemp->symbols[j]->name);
3272 }
3273 }
3274 }
3275 fprintf(fp, "\n");
3276 }
drh75897232000-05-29 14:26:00 +00003277 fclose(fp);
3278 return;
3279}
3280
3281/* Search for the file "name" which is in the same directory as
3282** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003283PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003284{
icculus9e44cf12010-02-14 17:14:22 +00003285 const char *pathlist;
3286 char *pathbufptr;
3287 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003288 char *path,*cp;
3289 char c;
drh75897232000-05-29 14:26:00 +00003290
3291#ifdef __WIN32__
3292 cp = strrchr(argv0,'\\');
3293#else
3294 cp = strrchr(argv0,'/');
3295#endif
3296 if( cp ){
3297 c = *cp;
3298 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003299 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003300 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003301 *cp = c;
3302 }else{
drh75897232000-05-29 14:26:00 +00003303 pathlist = getenv("PATH");
3304 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003305 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003306 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003307 if( (pathbuf != 0) && (path!=0) ){
3308 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003309 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003310 while( *pathbuf ){
3311 cp = strchr(pathbuf,':');
3312 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003313 c = *cp;
3314 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003315 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003316 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003317 if( c==0 ) pathbuf[0] = 0;
3318 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003319 if( access(path,modemask)==0 ) break;
3320 }
icculus9e44cf12010-02-14 17:14:22 +00003321 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003322 }
3323 }
3324 return path;
3325}
3326
3327/* Given an action, compute the integer value for that action
3328** which is to be put in the action table of the generated machine.
3329** Return negative if no action should be generated.
3330*/
icculus9e44cf12010-02-14 17:14:22 +00003331PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003332{
3333 int act;
3334 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003335 case SHIFT: act = ap->x.stp->statenum; break;
drhbd8fcc12017-06-28 11:56:18 +00003336 case SHIFTREDUCE: {
drhbd8fcc12017-06-28 11:56:18 +00003337 /* Since a SHIFT is inherient after a prior REDUCE, convert any
3338 ** SHIFTREDUCE action with a nonterminal on the LHS into a simple
3339 ** REDUCE action: */
drh5c8241b2017-12-24 23:38:10 +00003340 if( ap->sp->index>=lemp->nterminal ){
3341 act = lemp->minReduce + ap->x.rp->iRule;
3342 }else{
3343 act = lemp->minShiftReduce + ap->x.rp->iRule;
3344 }
drhbd8fcc12017-06-28 11:56:18 +00003345 break;
3346 }
drh5c8241b2017-12-24 23:38:10 +00003347 case REDUCE: act = lemp->minReduce + ap->x.rp->iRule; break;
3348 case ERROR: act = lemp->errAction; break;
3349 case ACCEPT: act = lemp->accAction; break;
drh75897232000-05-29 14:26:00 +00003350 default: act = -1; break;
3351 }
3352 return act;
3353}
3354
3355#define LINESIZE 1000
3356/* The next cluster of routines are for reading the template file
3357** and writing the results to the generated parser */
3358/* The first function transfers data from "in" to "out" until
3359** a line is seen which begins with "%%". The line number is
3360** tracked.
3361**
3362** if name!=0, then any word that begin with "Parse" is changed to
3363** begin with *name instead.
3364*/
icculus9e44cf12010-02-14 17:14:22 +00003365PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003366{
3367 int i, iStart;
3368 char line[LINESIZE];
3369 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3370 (*lineno)++;
3371 iStart = 0;
3372 if( name ){
3373 for(i=0; line[i]; i++){
3374 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003375 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003376 ){
3377 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3378 fprintf(out,"%s",name);
3379 i += 4;
3380 iStart = i+1;
3381 }
3382 }
3383 }
3384 fprintf(out,"%s",&line[iStart]);
3385 }
3386}
3387
3388/* The next function finds the template file and opens it, returning
3389** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003390PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003391{
3392 static char templatename[] = "lempar.c";
3393 char buf[1000];
3394 FILE *in;
3395 char *tpltname;
3396 char *cp;
3397
icculus3e143bd2010-02-14 00:48:49 +00003398 /* first, see if user specified a template filename on the command line. */
3399 if (user_templatename != 0) {
3400 if( access(user_templatename,004)==-1 ){
3401 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3402 user_templatename);
3403 lemp->errorcnt++;
3404 return 0;
3405 }
3406 in = fopen(user_templatename,"rb");
3407 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003408 fprintf(stderr,"Can't open the template file \"%s\".\n",
3409 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003410 lemp->errorcnt++;
3411 return 0;
3412 }
3413 return in;
3414 }
3415
drh75897232000-05-29 14:26:00 +00003416 cp = strrchr(lemp->filename,'.');
3417 if( cp ){
drh898799f2014-01-10 23:21:00 +00003418 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003419 }else{
drh898799f2014-01-10 23:21:00 +00003420 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003421 }
3422 if( access(buf,004)==0 ){
3423 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003424 }else if( access(templatename,004)==0 ){
3425 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003426 }else{
3427 tpltname = pathsearch(lemp->argv0,templatename,0);
3428 }
3429 if( tpltname==0 ){
3430 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3431 templatename);
3432 lemp->errorcnt++;
3433 return 0;
3434 }
drh2aa6ca42004-09-10 00:14:04 +00003435 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003436 if( in==0 ){
3437 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3438 lemp->errorcnt++;
3439 return 0;
3440 }
3441 return in;
3442}
3443
drhaf805ca2004-09-07 11:28:25 +00003444/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003445PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003446{
3447 fprintf(out,"#line %d \"",lineno);
3448 while( *filename ){
3449 if( *filename == '\\' ) putc('\\',out);
3450 putc(*filename,out);
3451 filename++;
3452 }
3453 fprintf(out,"\"\n");
3454}
3455
drh75897232000-05-29 14:26:00 +00003456/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003457PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003458{
3459 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003460 while( *str ){
drh75897232000-05-29 14:26:00 +00003461 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003462 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003463 str++;
3464 }
drh9db55df2004-09-09 14:01:21 +00003465 if( str[-1]!='\n' ){
3466 putc('\n',out);
3467 (*lineno)++;
3468 }
shane58543932008-12-10 20:10:04 +00003469 if (!lemp->nolinenosflag) {
drh06f60d82017-04-14 19:46:12 +00003470 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003471 }
drh75897232000-05-29 14:26:00 +00003472 return;
3473}
3474
3475/*
3476** The following routine emits code for the destructor for the
3477** symbol sp
3478*/
icculus9e44cf12010-02-14 17:14:22 +00003479void emit_destructor_code(
3480 FILE *out,
3481 struct symbol *sp,
3482 struct lemon *lemp,
3483 int *lineno
3484){
drhcc83b6e2004-04-23 23:38:42 +00003485 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003486
drh75897232000-05-29 14:26:00 +00003487 if( sp->type==TERMINAL ){
3488 cp = lemp->tokendest;
3489 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003490 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003491 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003492 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003493 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003494 if( !lemp->nolinenosflag ){
3495 (*lineno)++;
3496 tplt_linedir(out,sp->destLineno,lemp->filename);
3497 }
drh960e8c62001-04-03 16:53:21 +00003498 }else if( lemp->vardest ){
3499 cp = lemp->vardest;
3500 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003501 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003502 }else{
3503 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003504 }
3505 for(; *cp; cp++){
3506 if( *cp=='$' && cp[1]=='$' ){
3507 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3508 cp++;
3509 continue;
3510 }
shane58543932008-12-10 20:10:04 +00003511 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003512 fputc(*cp,out);
3513 }
shane58543932008-12-10 20:10:04 +00003514 fprintf(out,"\n"); (*lineno)++;
drh06f60d82017-04-14 19:46:12 +00003515 if (!lemp->nolinenosflag) {
3516 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
shane58543932008-12-10 20:10:04 +00003517 }
3518 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003519 return;
3520}
3521
3522/*
drh960e8c62001-04-03 16:53:21 +00003523** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003524*/
icculus9e44cf12010-02-14 17:14:22 +00003525int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003526{
3527 int ret;
3528 if( sp->type==TERMINAL ){
3529 ret = lemp->tokendest!=0;
3530 }else{
drh960e8c62001-04-03 16:53:21 +00003531 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003532 }
3533 return ret;
3534}
3535
drh0bb132b2004-07-20 14:06:51 +00003536/*
3537** Append text to a dynamically allocated string. If zText is 0 then
3538** reset the string to be empty again. Always return the complete text
3539** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003540**
3541** n bytes of zText are stored. If n==0 then all of zText up to the first
3542** \000 terminator is stored. zText can contain up to two instances of
3543** %d. The values of p1 and p2 are written into the first and second
3544** %d.
3545**
3546** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003547*/
icculus9e44cf12010-02-14 17:14:22 +00003548PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3549 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003550 static char *z = 0;
3551 static int alloced = 0;
3552 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003553 int c;
drh0bb132b2004-07-20 14:06:51 +00003554 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003555 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003556 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003557 used = 0;
3558 return z;
3559 }
drh7ac25c72004-08-19 15:12:26 +00003560 if( n<=0 ){
3561 if( n<0 ){
3562 used += n;
3563 assert( used>=0 );
3564 }
drh87cf1372008-08-13 20:09:06 +00003565 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003566 }
drhdf609712010-11-23 20:55:27 +00003567 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003568 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003569 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003570 }
icculus9e44cf12010-02-14 17:14:22 +00003571 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003572 while( n-- > 0 ){
3573 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003574 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003575 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003576 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003577 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003578 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003579 zText++;
3580 n--;
3581 }else{
mistachkin2318d332015-01-12 18:02:52 +00003582 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003583 }
3584 }
3585 z[used] = 0;
3586 return z;
3587}
3588
3589/*
drh711c9812016-05-23 14:24:31 +00003590** Write and transform the rp->code string so that symbols are expanded.
3591** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003592**
3593** Return 1 if the expanded code requires that "yylhsminor" local variable
3594** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003595*/
drhdabd04c2016-02-17 01:46:19 +00003596PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003597 char *cp, *xp;
3598 int i;
drhcf82f0d2016-02-17 04:33:10 +00003599 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003600 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003601 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3602 char lhsused = 0; /* True if the LHS element has been used */
3603 char lhsdirect; /* True if LHS writes directly into stack */
3604 char used[MAXRHS]; /* True for each RHS element which is used */
3605 char zLhs[50]; /* Convert the LHS symbol into this string */
3606 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003607
3608 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3609 lhsused = 0;
3610
drh19c9e562007-03-29 20:13:53 +00003611 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003612 static char newlinestr[2] = { '\n', '\0' };
3613 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003614 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003615 rp->noCode = 1;
3616 }else{
3617 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003618 }
3619
drh4dd0d3f2016-02-17 01:18:33 +00003620
drh2e55b042016-04-30 17:19:30 +00003621 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003622 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3623 lhsdirect = 1;
3624 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003625 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003626 ** we have to call the distructor on the RHS symbol first. */
3627 lhsdirect = 1;
3628 if( has_destructor(rp->rhs[0],lemp) ){
3629 append_str(0,0,0,0);
3630 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3631 rp->rhs[0]->index,1-rp->nrhs);
3632 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003633 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003634 }
drh2e55b042016-04-30 17:19:30 +00003635 }else if( rp->lhsalias==0 ){
3636 /* There is no LHS value symbol. */
3637 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003638 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
drh06f60d82017-04-14 19:46:12 +00003639 /* The LHS symbol and the left-most RHS symbol are the same, so
drh4dd0d3f2016-02-17 01:18:33 +00003640 ** direct writing is allowed */
3641 lhsdirect = 1;
3642 lhsused = 1;
3643 used[0] = 1;
3644 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3645 ErrorMsg(lemp->filename,rp->ruleline,
3646 "%s(%s) and %s(%s) share the same label but have "
3647 "different datatypes.",
3648 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3649 lemp->errorcnt++;
drh06f60d82017-04-14 19:46:12 +00003650 }
drh4dd0d3f2016-02-17 01:18:33 +00003651 }else{
drhcf82f0d2016-02-17 04:33:10 +00003652 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3653 rp->lhsalias, rp->rhsalias[0]);
3654 zSkip = strstr(rp->code, zOvwrt);
3655 if( zSkip!=0 ){
3656 /* The code contains a special comment that indicates that it is safe
3657 ** for the LHS label to overwrite left-most RHS label. */
3658 lhsdirect = 1;
3659 }else{
3660 lhsdirect = 0;
3661 }
drh4dd0d3f2016-02-17 01:18:33 +00003662 }
3663 if( lhsdirect ){
3664 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3665 }else{
drhdabd04c2016-02-17 01:46:19 +00003666 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003667 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3668 }
3669
drh0bb132b2004-07-20 14:06:51 +00003670 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003671
3672 /* This const cast is wrong but harmless, if we're careful. */
3673 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003674 if( cp==zSkip ){
3675 append_str(zOvwrt,0,0,0);
3676 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003677 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003678 continue;
3679 }
drhc56fac72015-10-29 13:48:15 +00003680 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003681 char saved;
drhc56fac72015-10-29 13:48:15 +00003682 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003683 saved = *xp;
3684 *xp = 0;
3685 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003686 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003687 cp = xp;
3688 lhsused = 1;
3689 }else{
3690 for(i=0; i<rp->nrhs; i++){
3691 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003692 if( i==0 && dontUseRhs0 ){
3693 ErrorMsg(lemp->filename,rp->ruleline,
3694 "Label %s used after '%s'.",
3695 rp->rhsalias[0], zOvwrt);
3696 lemp->errorcnt++;
3697 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003698 /* If the argument is of the form @X then substituted
3699 ** the token number of X, not the value of X */
3700 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3701 }else{
drhfd405312005-11-06 04:06:59 +00003702 struct symbol *sp = rp->rhs[i];
3703 int dtnum;
3704 if( sp->type==MULTITERMINAL ){
3705 dtnum = sp->subsym[0]->dtnum;
3706 }else{
3707 dtnum = sp->dtnum;
3708 }
3709 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003710 }
drh0bb132b2004-07-20 14:06:51 +00003711 cp = xp;
3712 used[i] = 1;
3713 break;
3714 }
3715 }
3716 }
3717 *xp = saved;
3718 }
3719 append_str(cp, 1, 0, 0);
3720 } /* End loop */
3721
drh4dd0d3f2016-02-17 01:18:33 +00003722 /* Main code generation completed */
3723 cp = append_str(0,0,0,0);
3724 if( cp && cp[0] ) rp->code = Strsafe(cp);
3725 append_str(0,0,0,0);
3726
drh0bb132b2004-07-20 14:06:51 +00003727 /* Check to make sure the LHS has been used */
3728 if( rp->lhsalias && !lhsused ){
3729 ErrorMsg(lemp->filename,rp->ruleline,
3730 "Label \"%s\" for \"%s(%s)\" is never used.",
3731 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3732 lemp->errorcnt++;
3733 }
3734
drh4dd0d3f2016-02-17 01:18:33 +00003735 /* Generate destructor code for RHS minor values which are not referenced.
3736 ** Generate error messages for unused labels and duplicate labels.
3737 */
drh0bb132b2004-07-20 14:06:51 +00003738 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003739 if( rp->rhsalias[i] ){
3740 if( i>0 ){
3741 int j;
3742 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3743 ErrorMsg(lemp->filename,rp->ruleline,
3744 "%s(%s) has the same label as the LHS but is not the left-most "
3745 "symbol on the RHS.",
3746 rp->rhs[i]->name, rp->rhsalias);
3747 lemp->errorcnt++;
3748 }
3749 for(j=0; j<i; j++){
3750 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3751 ErrorMsg(lemp->filename,rp->ruleline,
3752 "Label %s used for multiple symbols on the RHS of a rule.",
3753 rp->rhsalias[i]);
3754 lemp->errorcnt++;
3755 break;
3756 }
3757 }
drh0bb132b2004-07-20 14:06:51 +00003758 }
drh4dd0d3f2016-02-17 01:18:33 +00003759 if( !used[i] ){
3760 ErrorMsg(lemp->filename,rp->ruleline,
3761 "Label %s for \"%s(%s)\" is never used.",
3762 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3763 lemp->errorcnt++;
3764 }
3765 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3766 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3767 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003768 }
3769 }
drh4dd0d3f2016-02-17 01:18:33 +00003770
3771 /* If unable to write LHS values directly into the stack, write the
3772 ** saved LHS value now. */
3773 if( lhsdirect==0 ){
3774 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3775 append_str(zLhs, 0, 0, 0);
3776 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003777 }
drh4dd0d3f2016-02-17 01:18:33 +00003778
3779 /* Suffix code generation complete */
3780 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003781 if( cp && cp[0] ){
3782 rp->codeSuffix = Strsafe(cp);
3783 rp->noCode = 0;
3784 }
drhdabd04c2016-02-17 01:46:19 +00003785
3786 return rc;
drh0bb132b2004-07-20 14:06:51 +00003787}
3788
drh06f60d82017-04-14 19:46:12 +00003789/*
drh75897232000-05-29 14:26:00 +00003790** Generate code which executes when the rule "rp" is reduced. Write
3791** the code to "out". Make sure lineno stays up-to-date.
3792*/
icculus9e44cf12010-02-14 17:14:22 +00003793PRIVATE void emit_code(
3794 FILE *out,
3795 struct rule *rp,
3796 struct lemon *lemp,
3797 int *lineno
3798){
3799 const char *cp;
drh75897232000-05-29 14:26:00 +00003800
drh4dd0d3f2016-02-17 01:18:33 +00003801 /* Setup code prior to the #line directive */
3802 if( rp->codePrefix && rp->codePrefix[0] ){
3803 fprintf(out, "{%s", rp->codePrefix);
3804 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3805 }
3806
drh75897232000-05-29 14:26:00 +00003807 /* Generate code to do the reduce action */
3808 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003809 if( !lemp->nolinenosflag ){
3810 (*lineno)++;
3811 tplt_linedir(out,rp->line,lemp->filename);
3812 }
drhaf805ca2004-09-07 11:28:25 +00003813 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003814 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003815 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003816 if( !lemp->nolinenosflag ){
3817 (*lineno)++;
3818 tplt_linedir(out,*lineno,lemp->outname);
3819 }
drh4dd0d3f2016-02-17 01:18:33 +00003820 }
3821
3822 /* Generate breakdown code that occurs after the #line directive */
3823 if( rp->codeSuffix && rp->codeSuffix[0] ){
3824 fprintf(out, "%s", rp->codeSuffix);
3825 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3826 }
3827
3828 if( rp->codePrefix ){
3829 fprintf(out, "}\n"); (*lineno)++;
3830 }
drh75897232000-05-29 14:26:00 +00003831
drh75897232000-05-29 14:26:00 +00003832 return;
3833}
3834
3835/*
3836** Print the definition of the union used for the parser's data stack.
3837** This union contains fields for every possible data type for tokens
3838** and nonterminals. In the process of computing and printing this
3839** union, also set the ".dtnum" field of every terminal and nonterminal
3840** symbol.
3841*/
icculus9e44cf12010-02-14 17:14:22 +00003842void print_stack_union(
3843 FILE *out, /* The output stream */
3844 struct lemon *lemp, /* The main info structure for this parser */
3845 int *plineno, /* Pointer to the line number */
3846 int mhflag /* True if generating makeheaders output */
3847){
drh75897232000-05-29 14:26:00 +00003848 int lineno = *plineno; /* The line number of the output */
3849 char **types; /* A hash table of datatypes */
3850 int arraysize; /* Size of the "types" array */
3851 int maxdtlength; /* Maximum length of any ".datatype" field. */
3852 char *stddt; /* Standardized name for a datatype */
3853 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003854 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003855 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003856
3857 /* Allocate and initialize types[] and allocate stddt[] */
3858 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003859 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003860 if( types==0 ){
3861 fprintf(stderr,"Out of memory.\n");
3862 exit(1);
3863 }
drh75897232000-05-29 14:26:00 +00003864 for(i=0; i<arraysize; i++) types[i] = 0;
3865 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003866 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003867 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003868 }
drh75897232000-05-29 14:26:00 +00003869 for(i=0; i<lemp->nsymbol; i++){
3870 int len;
3871 struct symbol *sp = lemp->symbols[i];
3872 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003873 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003874 if( len>maxdtlength ) maxdtlength = len;
3875 }
3876 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003877 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003878 fprintf(stderr,"Out of memory.\n");
3879 exit(1);
3880 }
3881
3882 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3883 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003884 ** used for terminal symbols. If there is no %default_type defined then
3885 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3886 ** a datatype using the %type directive.
3887 */
drh75897232000-05-29 14:26:00 +00003888 for(i=0; i<lemp->nsymbol; i++){
3889 struct symbol *sp = lemp->symbols[i];
3890 char *cp;
3891 if( sp==lemp->errsym ){
3892 sp->dtnum = arraysize+1;
3893 continue;
3894 }
drh960e8c62001-04-03 16:53:21 +00003895 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003896 sp->dtnum = 0;
3897 continue;
3898 }
3899 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003900 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003901 j = 0;
drhc56fac72015-10-29 13:48:15 +00003902 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003903 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003904 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003905 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003906 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003907 sp->dtnum = 0;
3908 continue;
3909 }
drh75897232000-05-29 14:26:00 +00003910 hash = 0;
3911 for(j=0; stddt[j]; j++){
3912 hash = hash*53 + stddt[j];
3913 }
drh3b2129c2003-05-13 00:34:21 +00003914 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003915 while( types[hash] ){
3916 if( strcmp(types[hash],stddt)==0 ){
3917 sp->dtnum = hash + 1;
3918 break;
3919 }
3920 hash++;
drh2b51f212013-10-11 23:01:02 +00003921 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003922 }
3923 if( types[hash]==0 ){
3924 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003925 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003926 if( types[hash]==0 ){
3927 fprintf(stderr,"Out of memory.\n");
3928 exit(1);
3929 }
drh898799f2014-01-10 23:21:00 +00003930 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003931 }
3932 }
3933
3934 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3935 name = lemp->name ? lemp->name : "Parse";
3936 lineno = *plineno;
3937 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3938 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3939 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3940 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3941 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003942 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003943 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3944 for(i=0; i<arraysize; i++){
3945 if( types[i]==0 ) continue;
3946 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3947 free(types[i]);
3948 }
drhc4dd3fd2008-01-22 01:48:05 +00003949 if( lemp->errsym->useCnt ){
3950 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3951 }
drh75897232000-05-29 14:26:00 +00003952 free(stddt);
3953 free(types);
3954 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3955 *plineno = lineno;
3956}
3957
drhb29b0a52002-02-23 19:39:46 +00003958/*
3959** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003960** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3961** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003962*/
drhc75e0162015-09-07 02:23:02 +00003963static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3964 const char *zType = "int";
3965 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003966 if( lwr>=0 ){
3967 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003968 zType = "unsigned char";
3969 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003970 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003971 zType = "unsigned short int";
3972 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003973 }else{
drhc75e0162015-09-07 02:23:02 +00003974 zType = "unsigned int";
3975 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003976 }
3977 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003978 zType = "signed char";
3979 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003980 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003981 zType = "short";
3982 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003983 }
drhc75e0162015-09-07 02:23:02 +00003984 if( pnByte ) *pnByte = nByte;
3985 return zType;
drhb29b0a52002-02-23 19:39:46 +00003986}
3987
drhfdbf9282003-10-21 16:34:41 +00003988/*
3989** Each state contains a set of token transaction and a set of
3990** nonterminal transactions. Each of these sets makes an instance
3991** of the following structure. An array of these structures is used
3992** to order the creation of entries in the yy_action[] table.
3993*/
3994struct axset {
3995 struct state *stp; /* A pointer to a state */
3996 int isTkn; /* True to use tokens. False for non-terminals */
3997 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003998 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003999};
4000
4001/*
4002** Compare to axset structures for sorting purposes
4003*/
4004static int axset_compare(const void *a, const void *b){
4005 struct axset *p1 = (struct axset*)a;
4006 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00004007 int c;
4008 c = p2->nAction - p1->nAction;
4009 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00004010 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00004011 }
4012 assert( c!=0 || p1==p2 );
4013 return c;
drhfdbf9282003-10-21 16:34:41 +00004014}
4015
drhc4dd3fd2008-01-22 01:48:05 +00004016/*
4017** Write text on "out" that describes the rule "rp".
4018*/
4019static void writeRuleText(FILE *out, struct rule *rp){
4020 int j;
4021 fprintf(out,"%s ::=", rp->lhs->name);
4022 for(j=0; j<rp->nrhs; j++){
4023 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00004024 if( sp->type!=MULTITERMINAL ){
4025 fprintf(out," %s", sp->name);
4026 }else{
drhc4dd3fd2008-01-22 01:48:05 +00004027 int k;
drh61f92cd2014-01-11 03:06:18 +00004028 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00004029 for(k=1; k<sp->nsubsym; k++){
4030 fprintf(out,"|%s",sp->subsym[k]->name);
4031 }
4032 }
4033 }
4034}
4035
4036
drh75897232000-05-29 14:26:00 +00004037/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004038void ReportTable(
4039 struct lemon *lemp,
4040 int mhflag /* Output in makeheaders format if true */
4041){
drh75897232000-05-29 14:26:00 +00004042 FILE *out, *in;
4043 char line[LINESIZE];
4044 int lineno;
4045 struct state *stp;
4046 struct action *ap;
4047 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004048 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004049 int i, j, n, sz;
4050 int szActionType; /* sizeof(YYACTIONTYPE) */
4051 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004052 const char *name;
drh8b582012003-10-21 13:16:03 +00004053 int mnTknOfst, mxTknOfst;
4054 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004055 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004056
drh5c8241b2017-12-24 23:38:10 +00004057 lemp->minShiftReduce = lemp->nstate;
4058 lemp->errAction = lemp->minShiftReduce + lemp->nrule;
4059 lemp->accAction = lemp->errAction + 1;
4060 lemp->noAction = lemp->accAction + 1;
4061 lemp->minReduce = lemp->noAction + 1;
4062 lemp->maxAction = lemp->minReduce + lemp->nrule;
4063
drh75897232000-05-29 14:26:00 +00004064 in = tplt_open(lemp);
4065 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004066 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004067 if( out==0 ){
4068 fclose(in);
4069 return;
4070 }
4071 lineno = 1;
4072 tplt_xfer(lemp->name,in,out,&lineno);
4073
4074 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004075 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004076 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004077 char *incName = file_makename(lemp, ".h");
4078 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4079 free(incName);
drh75897232000-05-29 14:26:00 +00004080 }
4081 tplt_xfer(lemp->name,in,out,&lineno);
4082
4083 /* Generate #defines for all tokens */
4084 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004085 const char *prefix;
drh75897232000-05-29 14:26:00 +00004086 fprintf(out,"#if INTERFACE\n"); lineno++;
4087 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4088 else prefix = "";
4089 for(i=1; i<lemp->nterminal; i++){
4090 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4091 lineno++;
4092 }
4093 fprintf(out,"#endif\n"); lineno++;
4094 }
4095 tplt_xfer(lemp->name,in,out,&lineno);
4096
4097 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004098 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00004099 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00004100 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
4101 fprintf(out,"#define YYACTIONTYPE %s\n",
drh5c8241b2017-12-24 23:38:10 +00004102 minimum_size_type(0,lemp->maxAction,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004103 if( lemp->wildcard ){
4104 fprintf(out,"#define YYWILDCARD %d\n",
4105 lemp->wildcard->index); lineno++;
4106 }
drh75897232000-05-29 14:26:00 +00004107 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004108 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004109 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004110 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4111 }else{
4112 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4113 }
drhca44b5a2007-02-22 23:06:58 +00004114 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004115 if( mhflag ){
4116 fprintf(out,"#if INTERFACE\n"); lineno++;
4117 }
4118 name = lemp->name ? lemp->name : "Parse";
4119 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004120 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004121 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4122 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004123 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4124 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4125 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
4126 name,lemp->arg,&lemp->arg[i]); lineno++;
4127 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
4128 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004129 }else{
drh1f245e42002-03-11 13:55:50 +00004130 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4131 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4132 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4133 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004134 }
4135 if( mhflag ){
4136 fprintf(out,"#endif\n"); lineno++;
4137 }
drhc4dd3fd2008-01-22 01:48:05 +00004138 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004139 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4140 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004141 }
drh0bd1f4e2002-06-06 18:54:39 +00004142 if( lemp->has_fallback ){
4143 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4144 }
drh75897232000-05-29 14:26:00 +00004145
drh3bd48ab2015-09-07 18:23:37 +00004146 /* Compute the action table, but do not output it yet. The action
4147 ** table must be computed before generating the YYNSTATE macro because
4148 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004149 */
drh3bd48ab2015-09-07 18:23:37 +00004150 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004151 if( ax==0 ){
4152 fprintf(stderr,"malloc failed\n");
4153 exit(1);
4154 }
drh3bd48ab2015-09-07 18:23:37 +00004155 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004156 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004157 ax[i*2].stp = stp;
4158 ax[i*2].isTkn = 1;
4159 ax[i*2].nAction = stp->nTknAct;
4160 ax[i*2+1].stp = stp;
4161 ax[i*2+1].isTkn = 0;
4162 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004163 }
drh8b582012003-10-21 13:16:03 +00004164 mxTknOfst = mnTknOfst = 0;
4165 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004166 /* In an effort to minimize the action table size, use the heuristic
4167 ** of placing the largest action sets first */
4168 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4169 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004170 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004171 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004172 stp = ax[i].stp;
4173 if( ax[i].isTkn ){
4174 for(ap=stp->ap; ap; ap=ap->next){
4175 int action;
4176 if( ap->sp->index>=lemp->nterminal ) continue;
4177 action = compute_action(lemp, ap);
4178 if( action<0 ) continue;
4179 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004180 }
drhfdbf9282003-10-21 16:34:41 +00004181 stp->iTknOfst = acttab_insert(pActtab);
4182 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4183 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4184 }else{
4185 for(ap=stp->ap; ap; ap=ap->next){
4186 int action;
4187 if( ap->sp->index<lemp->nterminal ) continue;
4188 if( ap->sp->index==lemp->nsymbol ) continue;
4189 action = compute_action(lemp, ap);
4190 if( action<0 ) continue;
4191 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004192 }
drhfdbf9282003-10-21 16:34:41 +00004193 stp->iNtOfst = acttab_insert(pActtab);
4194 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4195 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004196 }
drh337cd0d2015-09-07 23:40:42 +00004197#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4198 { int jj, nn;
4199 for(jj=nn=0; jj<pActtab->nAction; jj++){
4200 if( pActtab->aAction[jj].action<0 ) nn++;
4201 }
4202 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4203 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4204 ax[i].nAction, pActtab->nAction, nn);
4205 }
4206#endif
drh8b582012003-10-21 13:16:03 +00004207 }
drhfdbf9282003-10-21 16:34:41 +00004208 free(ax);
drh8b582012003-10-21 13:16:03 +00004209
drh756b41e2016-05-24 18:55:08 +00004210 /* Mark rules that are actually used for reduce actions after all
4211 ** optimizations have been applied
4212 */
4213 for(rp=lemp->rule; rp; rp=rp->next) rp->doesReduce = LEMON_FALSE;
4214 for(i=0; i<lemp->nxstate; i++){
drh756b41e2016-05-24 18:55:08 +00004215 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
4216 if( ap->type==REDUCE || ap->type==SHIFTREDUCE ){
drh69bfa552017-04-26 04:32:17 +00004217 ap->x.rp->doesReduce = 1;
drh756b41e2016-05-24 18:55:08 +00004218 }
4219 }
4220 }
4221
drh3bd48ab2015-09-07 18:23:37 +00004222 /* Finish rendering the constants now that the action table has
4223 ** been computed */
4224 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4225 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004226 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004227 i = lemp->minShiftReduce;
4228 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",i); lineno++;
4229 i += lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004230 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
drh5c8241b2017-12-24 23:38:10 +00004231 fprintf(out,"#define YY_ERROR_ACTION %d\n", lemp->errAction); lineno++;
4232 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", lemp->accAction); lineno++;
4233 fprintf(out,"#define YY_NO_ACTION %d\n", lemp->noAction); lineno++;
4234 fprintf(out,"#define YY_MIN_REDUCE %d\n", lemp->minReduce); lineno++;
4235 i = lemp->minReduce + lemp->nrule;
drh3bd48ab2015-09-07 18:23:37 +00004236 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004237 tplt_xfer(lemp->name,in,out,&lineno);
4238
4239 /* Now output the action table and its associates:
4240 **
4241 ** yy_action[] A single table containing all actions.
4242 ** yy_lookahead[] A table containing the lookahead for each entry in
4243 ** yy_action. Used to detect hash collisions.
4244 ** yy_shift_ofst[] For each state, the offset into yy_action for
4245 ** shifting terminals.
4246 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4247 ** shifting non-terminals after a reduce.
4248 ** yy_default[] Default action for each state.
4249 */
4250
drh8b582012003-10-21 13:16:03 +00004251 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004252 lemp->nactiontab = n = acttab_size(pActtab);
4253 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004254 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4255 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004256 for(i=j=0; i<n; i++){
4257 int action = acttab_yyaction(pActtab, i);
drh5c8241b2017-12-24 23:38:10 +00004258 if( action<0 ) action = lemp->noAction;
drhfdbf9282003-10-21 16:34:41 +00004259 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004260 fprintf(out, " %4d,", action);
4261 if( j==9 || i==n-1 ){
4262 fprintf(out, "\n"); lineno++;
4263 j = 0;
4264 }else{
4265 j++;
4266 }
4267 }
4268 fprintf(out, "};\n"); lineno++;
4269
4270 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004271 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004272 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004273 for(i=j=0; i<n; i++){
4274 int la = acttab_yylookahead(pActtab, i);
4275 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004276 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004277 fprintf(out, " %4d,", la);
4278 if( j==9 || i==n-1 ){
4279 fprintf(out, "\n"); lineno++;
4280 j = 0;
4281 }else{
4282 j++;
4283 }
4284 }
4285 fprintf(out, "};\n"); lineno++;
4286
4287 /* Output the yy_shift_ofst[] table */
drh3bd48ab2015-09-07 18:23:37 +00004288 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004289 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drh701b6882016-08-10 13:30:43 +00004290 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", lemp->nactiontab); lineno++;
4291 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4292 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4293 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004294 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh701b6882016-08-10 13:30:43 +00004295 minimum_size_type(mnTknOfst, lemp->nterminal+lemp->nactiontab, &sz));
4296 lineno++;
drhc75e0162015-09-07 02:23:02 +00004297 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004298 for(i=j=0; i<n; i++){
4299 int ofst;
4300 stp = lemp->sorted[i];
4301 ofst = stp->iTknOfst;
drh701b6882016-08-10 13:30:43 +00004302 if( ofst==NO_OFFSET ) ofst = lemp->nactiontab;
drhfdbf9282003-10-21 16:34:41 +00004303 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004304 fprintf(out, " %4d,", ofst);
4305 if( j==9 || i==n-1 ){
4306 fprintf(out, "\n"); lineno++;
4307 j = 0;
4308 }else{
4309 j++;
4310 }
4311 }
4312 fprintf(out, "};\n"); lineno++;
4313
4314 /* Output the yy_reduce_ofst[] table */
4315 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004316 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004317 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004318 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4319 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4320 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh06f60d82017-04-14 19:46:12 +00004321 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004322 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4323 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004324 for(i=j=0; i<n; i++){
4325 int ofst;
4326 stp = lemp->sorted[i];
4327 ofst = stp->iNtOfst;
4328 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004329 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004330 fprintf(out, " %4d,", ofst);
4331 if( j==9 || i==n-1 ){
4332 fprintf(out, "\n"); lineno++;
4333 j = 0;
4334 }else{
4335 j++;
4336 }
4337 }
4338 fprintf(out, "};\n"); lineno++;
4339
4340 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004341 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004342 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004343 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004344 for(i=j=0; i<n; i++){
4345 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004346 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh5c8241b2017-12-24 23:38:10 +00004347 if( stp->iDfltReduce<0 ){
4348 fprintf(out, " %4d,", lemp->errAction);
4349 }else{
4350 fprintf(out, " %4d,", stp->iDfltReduce + lemp->minReduce);
4351 }
drh8b582012003-10-21 13:16:03 +00004352 if( j==9 || i==n-1 ){
4353 fprintf(out, "\n"); lineno++;
4354 j = 0;
4355 }else{
4356 j++;
4357 }
4358 }
4359 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004360 tplt_xfer(lemp->name,in,out,&lineno);
4361
drh0bd1f4e2002-06-06 18:54:39 +00004362 /* Generate the table of fallback tokens.
4363 */
4364 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004365 int mx = lemp->nterminal - 1;
4366 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004367 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004368 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004369 struct symbol *p = lemp->symbols[i];
4370 if( p->fallback==0 ){
4371 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4372 }else{
4373 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4374 p->name, p->fallback->name);
4375 }
4376 lineno++;
4377 }
4378 }
4379 tplt_xfer(lemp->name, in, out, &lineno);
4380
4381 /* Generate a table containing the symbolic name of every symbol
4382 */
drh75897232000-05-29 14:26:00 +00004383 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004384 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004385 fprintf(out," %-15s",line);
4386 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4387 }
4388 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4389 tplt_xfer(lemp->name,in,out,&lineno);
4390
drh0bd1f4e2002-06-06 18:54:39 +00004391 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004392 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004393 ** when tracing REDUCE actions.
4394 */
4395 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004396 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004397 fprintf(out," /* %3d */ \"", i);
4398 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004399 fprintf(out,"\",\n"); lineno++;
4400 }
4401 tplt_xfer(lemp->name,in,out,&lineno);
4402
drh75897232000-05-29 14:26:00 +00004403 /* Generate code which executes every time a symbol is popped from
drh06f60d82017-04-14 19:46:12 +00004404 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004405 ** (In other words, generate the %destructor actions)
4406 */
drh75897232000-05-29 14:26:00 +00004407 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004408 int once = 1;
drh75897232000-05-29 14:26:00 +00004409 for(i=0; i<lemp->nsymbol; i++){
4410 struct symbol *sp = lemp->symbols[i];
4411 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004412 if( once ){
4413 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4414 once = 0;
4415 }
drhc53eed12009-06-12 17:46:19 +00004416 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004417 }
4418 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4419 if( i<lemp->nsymbol ){
4420 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4421 fprintf(out," break;\n"); lineno++;
4422 }
4423 }
drh8d659732005-01-13 23:54:06 +00004424 if( lemp->vardest ){
4425 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004426 int once = 1;
drh8d659732005-01-13 23:54:06 +00004427 for(i=0; i<lemp->nsymbol; i++){
4428 struct symbol *sp = lemp->symbols[i];
4429 if( sp==0 || sp->type==TERMINAL ||
4430 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004431 if( once ){
drh5c8241b2017-12-24 23:38:10 +00004432 fprintf(out, " /* Default NON-TERMINAL Destructor */\n");lineno++;
drh4dc8ef52008-07-01 17:13:57 +00004433 once = 0;
4434 }
drhc53eed12009-06-12 17:46:19 +00004435 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004436 dflt_sp = sp;
4437 }
4438 if( dflt_sp!=0 ){
4439 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004440 }
drh4dc8ef52008-07-01 17:13:57 +00004441 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004442 }
drh75897232000-05-29 14:26:00 +00004443 for(i=0; i<lemp->nsymbol; i++){
4444 struct symbol *sp = lemp->symbols[i];
4445 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh0f832dd2016-08-16 16:46:40 +00004446 if( sp->destLineno<0 ) continue; /* Already emitted */
drh75013012009-06-12 15:47:34 +00004447 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004448
4449 /* Combine duplicate destructors into a single case */
4450 for(j=i+1; j<lemp->nsymbol; j++){
4451 struct symbol *sp2 = lemp->symbols[j];
4452 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4453 && sp2->dtnum==sp->dtnum
4454 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004455 fprintf(out," case %d: /* %s */\n",
4456 sp2->index, sp2->name); lineno++;
drh0f832dd2016-08-16 16:46:40 +00004457 sp2->destLineno = -1; /* Avoid emitting this destructor again */
drh0bb132b2004-07-20 14:06:51 +00004458 }
4459 }
4460
drh75897232000-05-29 14:26:00 +00004461 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4462 fprintf(out," break;\n"); lineno++;
4463 }
drh75897232000-05-29 14:26:00 +00004464 tplt_xfer(lemp->name,in,out,&lineno);
4465
4466 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004467 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004468 tplt_xfer(lemp->name,in,out,&lineno);
4469
drh06f60d82017-04-14 19:46:12 +00004470 /* Generate the table of rule information
drh75897232000-05-29 14:26:00 +00004471 **
4472 ** Note: This code depends on the fact that rules are number
4473 ** sequentually beginning with 0.
4474 */
drh5c8241b2017-12-24 23:38:10 +00004475 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4476 fprintf(out," { %4d, %4d }, /* (%d) ",rp->lhs->index,-rp->nrhs,i);
4477 rule_print(out, rp);
4478 fprintf(out," */\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004479 }
4480 tplt_xfer(lemp->name,in,out,&lineno);
4481
4482 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004483 i = 0;
drh75897232000-05-29 14:26:00 +00004484 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004485 i += translate_code(lemp, rp);
4486 }
4487 if( i ){
4488 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004489 }
drhc53eed12009-06-12 17:46:19 +00004490 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004491 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004492 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004493 if( rp->codeEmitted ) continue;
4494 if( rp->noCode ){
4495 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004496 continue;
4497 }
drh4ef07702016-03-16 19:45:54 +00004498 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004499 writeRuleText(out, rp);
4500 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004501 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004502 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4503 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004504 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004505 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004506 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004507 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004508 }
4509 }
drh75897232000-05-29 14:26:00 +00004510 emit_code(out,rp,lemp,&lineno);
4511 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004512 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004513 }
drhc53eed12009-06-12 17:46:19 +00004514 /* Finally, output the default: rule. We choose as the default: all
4515 ** empty actions. */
4516 fprintf(out," default:\n"); lineno++;
4517 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004518 if( rp->codeEmitted ) continue;
4519 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004520 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004521 writeRuleText(out, rp);
drh756b41e2016-05-24 18:55:08 +00004522 if( rp->doesReduce ){
4523 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
4524 }else{
4525 fprintf(out, " (OPTIMIZED OUT) */ assert(yyruleno!=%d);\n",
4526 rp->iRule); lineno++;
4527 }
drhc53eed12009-06-12 17:46:19 +00004528 }
4529 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004530 tplt_xfer(lemp->name,in,out,&lineno);
4531
4532 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004533 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004534 tplt_xfer(lemp->name,in,out,&lineno);
4535
4536 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004537 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004538 tplt_xfer(lemp->name,in,out,&lineno);
4539
4540 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004541 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004542 tplt_xfer(lemp->name,in,out,&lineno);
4543
4544 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004545 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004546
4547 fclose(in);
4548 fclose(out);
4549 return;
4550}
4551
4552/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004553void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004554{
4555 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004556 const char *prefix;
drh75897232000-05-29 14:26:00 +00004557 char line[LINESIZE];
4558 char pattern[LINESIZE];
4559 int i;
4560
4561 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4562 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004563 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004564 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004565 int nextChar;
drh75897232000-05-29 14:26:00 +00004566 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004567 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4568 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004569 if( strcmp(line,pattern) ) break;
4570 }
drh8ba0d1c2012-06-16 15:26:31 +00004571 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004572 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004573 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004574 /* No change in the file. Don't rewrite it. */
4575 return;
4576 }
4577 }
drh2aa6ca42004-09-10 00:14:04 +00004578 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004579 if( out ){
4580 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004581 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004582 }
drh06f60d82017-04-14 19:46:12 +00004583 fclose(out);
drh75897232000-05-29 14:26:00 +00004584 }
4585 return;
4586}
4587
4588/* Reduce the size of the action tables, if possible, by making use
4589** of defaults.
4590**
drhb59499c2002-02-23 18:45:13 +00004591** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004592** it the default. Except, there is no default if the wildcard token
4593** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004594*/
icculus9e44cf12010-02-14 17:14:22 +00004595void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004596{
4597 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004598 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004599 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004600 int nbest, n;
drh75897232000-05-29 14:26:00 +00004601 int i;
drhe09daa92006-06-10 13:29:31 +00004602 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004603
4604 for(i=0; i<lemp->nstate; i++){
4605 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004606 nbest = 0;
4607 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004608 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004609
drhb59499c2002-02-23 18:45:13 +00004610 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004611 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4612 usesWildcard = 1;
4613 }
drhb59499c2002-02-23 18:45:13 +00004614 if( ap->type!=REDUCE ) continue;
4615 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004616 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004617 if( rp==rbest ) continue;
4618 n = 1;
4619 for(ap2=ap->next; ap2; ap2=ap2->next){
4620 if( ap2->type!=REDUCE ) continue;
4621 rp2 = ap2->x.rp;
4622 if( rp2==rbest ) continue;
4623 if( rp2==rp ) n++;
4624 }
4625 if( n>nbest ){
4626 nbest = n;
4627 rbest = rp;
drh75897232000-05-29 14:26:00 +00004628 }
4629 }
drh06f60d82017-04-14 19:46:12 +00004630
drhb59499c2002-02-23 18:45:13 +00004631 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004632 ** is not at least 1 or if the wildcard token is a possible
4633 ** lookahead.
4634 */
4635 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004636
drhb59499c2002-02-23 18:45:13 +00004637
4638 /* Combine matching REDUCE actions into a single default */
4639 for(ap=stp->ap; ap; ap=ap->next){
4640 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4641 }
drh75897232000-05-29 14:26:00 +00004642 assert( ap );
4643 ap->sp = Symbol_new("{default}");
4644 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004645 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004646 }
4647 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004648
4649 for(ap=stp->ap; ap; ap=ap->next){
4650 if( ap->type==SHIFT ) break;
4651 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4652 }
4653 if( ap==0 ){
4654 stp->autoReduce = 1;
4655 stp->pDfltReduce = rbest;
4656 }
4657 }
4658
4659 /* Make a second pass over all states and actions. Convert
4660 ** every action that is a SHIFT to an autoReduce state into
4661 ** a SHIFTREDUCE action.
4662 */
4663 for(i=0; i<lemp->nstate; i++){
4664 stp = lemp->sorted[i];
4665 for(ap=stp->ap; ap; ap=ap->next){
4666 struct state *pNextState;
4667 if( ap->type!=SHIFT ) continue;
4668 pNextState = ap->x.stp;
4669 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4670 ap->type = SHIFTREDUCE;
4671 ap->x.rp = pNextState->pDfltReduce;
4672 }
4673 }
drh75897232000-05-29 14:26:00 +00004674 }
drhc173ad82016-05-23 16:15:02 +00004675
4676 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4677 ** (meaning that the SHIFTREDUCE will land back in the state where it
4678 ** started) and if there is no C-code associated with the reduce action,
4679 ** then we can go ahead and convert the action to be the same as the
4680 ** action for the RHS of the rule.
4681 */
4682 for(i=0; i<lemp->nstate; i++){
4683 stp = lemp->sorted[i];
4684 for(ap=stp->ap; ap; ap=nextap){
4685 nextap = ap->next;
4686 if( ap->type!=SHIFTREDUCE ) continue;
4687 rp = ap->x.rp;
4688 if( rp->noCode==0 ) continue;
4689 if( rp->nrhs!=1 ) continue;
4690#if 1
4691 /* Only apply this optimization to non-terminals. It would be OK to
4692 ** apply it to terminal symbols too, but that makes the parser tables
4693 ** larger. */
4694 if( ap->sp->index<lemp->nterminal ) continue;
4695#endif
4696 /* If we reach this point, it means the optimization can be applied */
4697 nextap = ap;
4698 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4699 assert( ap2!=0 );
4700 ap->spOpt = ap2->sp;
4701 ap->type = ap2->type;
4702 ap->x = ap2->x;
4703 }
4704 }
drh75897232000-05-29 14:26:00 +00004705}
drhb59499c2002-02-23 18:45:13 +00004706
drhada354d2005-11-05 15:03:59 +00004707
4708/*
4709** Compare two states for sorting purposes. The smaller state is the
4710** one with the most non-terminal actions. If they have the same number
4711** of non-terminal actions, then the smaller is the one with the most
4712** token actions.
4713*/
4714static int stateResortCompare(const void *a, const void *b){
4715 const struct state *pA = *(const struct state**)a;
4716 const struct state *pB = *(const struct state**)b;
4717 int n;
4718
4719 n = pB->nNtAct - pA->nNtAct;
4720 if( n==0 ){
4721 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004722 if( n==0 ){
4723 n = pB->statenum - pA->statenum;
4724 }
drhada354d2005-11-05 15:03:59 +00004725 }
drhe594bc32009-11-03 13:02:25 +00004726 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004727 return n;
4728}
4729
4730
4731/*
4732** Renumber and resort states so that states with fewer choices
4733** occur at the end. Except, keep state 0 as the first state.
4734*/
icculus9e44cf12010-02-14 17:14:22 +00004735void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004736{
4737 int i;
4738 struct state *stp;
4739 struct action *ap;
4740
4741 for(i=0; i<lemp->nstate; i++){
4742 stp = lemp->sorted[i];
4743 stp->nTknAct = stp->nNtAct = 0;
drh5c8241b2017-12-24 23:38:10 +00004744 stp->iDfltReduce = -1; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004745 stp->iTknOfst = NO_OFFSET;
4746 stp->iNtOfst = NO_OFFSET;
4747 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004748 int iAction = compute_action(lemp,ap);
4749 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004750 if( ap->sp->index<lemp->nterminal ){
4751 stp->nTknAct++;
4752 }else if( ap->sp->index<lemp->nsymbol ){
4753 stp->nNtAct++;
4754 }else{
drh3bd48ab2015-09-07 18:23:37 +00004755 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
drh5c8241b2017-12-24 23:38:10 +00004756 stp->iDfltReduce = iAction;
drhada354d2005-11-05 15:03:59 +00004757 }
4758 }
4759 }
4760 }
4761 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4762 stateResortCompare);
4763 for(i=0; i<lemp->nstate; i++){
4764 lemp->sorted[i]->statenum = i;
4765 }
drh3bd48ab2015-09-07 18:23:37 +00004766 lemp->nxstate = lemp->nstate;
4767 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4768 lemp->nxstate--;
4769 }
drhada354d2005-11-05 15:03:59 +00004770}
4771
4772
drh75897232000-05-29 14:26:00 +00004773/***************** From the file "set.c" ************************************/
4774/*
4775** Set manipulation routines for the LEMON parser generator.
4776*/
4777
4778static int size = 0;
4779
4780/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004781void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004782{
4783 size = n+1;
4784}
4785
4786/* Allocate a new set */
drh14d88552017-04-14 19:44:15 +00004787char *SetNew(void){
drh75897232000-05-29 14:26:00 +00004788 char *s;
drh9892c5d2007-12-21 00:02:11 +00004789 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004790 if( s==0 ){
4791 extern void memory_error();
4792 memory_error();
4793 }
drh75897232000-05-29 14:26:00 +00004794 return s;
4795}
4796
4797/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004798void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004799{
4800 free(s);
4801}
4802
4803/* Add a new element to the set. Return TRUE if the element was added
4804** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004805int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004806{
4807 int rv;
drh9892c5d2007-12-21 00:02:11 +00004808 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004809 rv = s[e];
4810 s[e] = 1;
4811 return !rv;
4812}
4813
4814/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004815int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004816{
4817 int i, progress;
4818 progress = 0;
4819 for(i=0; i<size; i++){
4820 if( s2[i]==0 ) continue;
4821 if( s1[i]==0 ){
4822 progress = 1;
4823 s1[i] = 1;
4824 }
4825 }
4826 return progress;
4827}
4828/********************** From the file "table.c" ****************************/
4829/*
4830** All code in this file has been automatically generated
4831** from a specification in the file
4832** "table.q"
4833** by the associative array code building program "aagen".
4834** Do not edit this file! Instead, edit the specification
4835** file, then rerun aagen.
4836*/
4837/*
4838** Code for processing tables in the LEMON parser generator.
4839*/
4840
drh01f75f22013-10-02 20:46:30 +00004841PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004842{
drh01f75f22013-10-02 20:46:30 +00004843 unsigned h = 0;
4844 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004845 return h;
4846}
4847
4848/* Works like strdup, sort of. Save a string in malloced memory, but
4849** keep strings in a table so that the same string is not in more
4850** than one place.
4851*/
icculus9e44cf12010-02-14 17:14:22 +00004852const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004853{
icculus9e44cf12010-02-14 17:14:22 +00004854 const char *z;
4855 char *cpy;
drh75897232000-05-29 14:26:00 +00004856
drh916f75f2006-07-17 00:19:39 +00004857 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004858 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004859 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004860 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004861 z = cpy;
drh75897232000-05-29 14:26:00 +00004862 Strsafe_insert(z);
4863 }
4864 MemoryCheck(z);
4865 return z;
4866}
4867
4868/* There is one instance of the following structure for each
4869** associative array of type "x1".
4870*/
4871struct s_x1 {
4872 int size; /* The number of available slots. */
4873 /* Must be a power of 2 greater than or */
4874 /* equal to 1 */
4875 int count; /* Number of currently slots filled */
4876 struct s_x1node *tbl; /* The data stored here */
4877 struct s_x1node **ht; /* Hash table for lookups */
4878};
4879
4880/* There is one instance of this structure for every data element
4881** in an associative array of type "x1".
4882*/
4883typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004884 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004885 struct s_x1node *next; /* Next entry with the same hash */
4886 struct s_x1node **from; /* Previous link */
4887} x1node;
4888
4889/* There is only one instance of the array, which is the following */
4890static struct s_x1 *x1a;
4891
4892/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00004893void Strsafe_init(void){
drh75897232000-05-29 14:26:00 +00004894 if( x1a ) return;
4895 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4896 if( x1a ){
4897 x1a->size = 1024;
4898 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004899 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004900 if( x1a->tbl==0 ){
4901 free(x1a);
4902 x1a = 0;
4903 }else{
4904 int i;
4905 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4906 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4907 }
4908 }
4909}
4910/* Insert a new record into the array. Return TRUE if successful.
4911** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004912int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004913{
4914 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004915 unsigned h;
4916 unsigned ph;
drh75897232000-05-29 14:26:00 +00004917
4918 if( x1a==0 ) return 0;
4919 ph = strhash(data);
4920 h = ph & (x1a->size-1);
4921 np = x1a->ht[h];
4922 while( np ){
4923 if( strcmp(np->data,data)==0 ){
4924 /* An existing entry with the same key is found. */
4925 /* Fail because overwrite is not allows. */
4926 return 0;
4927 }
4928 np = np->next;
4929 }
4930 if( x1a->count>=x1a->size ){
4931 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004932 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004933 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004934 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004935 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004936 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004937 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004938 array.ht = (x1node**)&(array.tbl[arrSize]);
4939 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004940 for(i=0; i<x1a->count; i++){
4941 x1node *oldnp, *newnp;
4942 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004943 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004944 newnp = &(array.tbl[i]);
4945 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4946 newnp->next = array.ht[h];
4947 newnp->data = oldnp->data;
4948 newnp->from = &(array.ht[h]);
4949 array.ht[h] = newnp;
4950 }
4951 free(x1a->tbl);
4952 *x1a = array;
4953 }
4954 /* Insert the new data */
4955 h = ph & (x1a->size-1);
4956 np = &(x1a->tbl[x1a->count++]);
4957 np->data = data;
4958 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4959 np->next = x1a->ht[h];
4960 x1a->ht[h] = np;
4961 np->from = &(x1a->ht[h]);
4962 return 1;
4963}
4964
4965/* Return a pointer to data assigned to the given key. Return NULL
4966** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004967const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004968{
drh01f75f22013-10-02 20:46:30 +00004969 unsigned h;
drh75897232000-05-29 14:26:00 +00004970 x1node *np;
4971
4972 if( x1a==0 ) return 0;
4973 h = strhash(key) & (x1a->size-1);
4974 np = x1a->ht[h];
4975 while( np ){
4976 if( strcmp(np->data,key)==0 ) break;
4977 np = np->next;
4978 }
4979 return np ? np->data : 0;
4980}
4981
4982/* Return a pointer to the (terminal or nonterminal) symbol "x".
4983** Create a new symbol if this is the first time "x" has been seen.
4984*/
icculus9e44cf12010-02-14 17:14:22 +00004985struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004986{
4987 struct symbol *sp;
4988
4989 sp = Symbol_find(x);
4990 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004991 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004992 MemoryCheck(sp);
4993 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004994 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004995 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004996 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004997 sp->prec = -1;
4998 sp->assoc = UNK;
4999 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00005000 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00005001 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00005002 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00005003 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00005004 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00005005 Symbol_insert(sp,sp->name);
5006 }
drhc4dd3fd2008-01-22 01:48:05 +00005007 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00005008 return sp;
5009}
5010
drh61f92cd2014-01-11 03:06:18 +00005011/* Compare two symbols for sorting purposes. Return negative,
5012** zero, or positive if a is less then, equal to, or greater
5013** than b.
drh60d31652004-02-22 00:08:04 +00005014**
5015** Symbols that begin with upper case letters (terminals or tokens)
5016** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00005017** (non-terminals). And MULTITERMINAL symbols (created using the
5018** %token_class directive) must sort at the very end. Other than
5019** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00005020**
5021** We find experimentally that leaving the symbols in their original
5022** order (the order they appeared in the grammar file) gives the
5023** smallest parser tables in SQLite.
5024*/
icculus9e44cf12010-02-14 17:14:22 +00005025int Symbolcmpp(const void *_a, const void *_b)
5026{
drh61f92cd2014-01-11 03:06:18 +00005027 const struct symbol *a = *(const struct symbol **) _a;
5028 const struct symbol *b = *(const struct symbol **) _b;
5029 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
5030 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
5031 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00005032}
5033
5034/* There is one instance of the following structure for each
5035** associative array of type "x2".
5036*/
5037struct s_x2 {
5038 int size; /* The number of available slots. */
5039 /* Must be a power of 2 greater than or */
5040 /* equal to 1 */
5041 int count; /* Number of currently slots filled */
5042 struct s_x2node *tbl; /* The data stored here */
5043 struct s_x2node **ht; /* Hash table for lookups */
5044};
5045
5046/* There is one instance of this structure for every data element
5047** in an associative array of type "x2".
5048*/
5049typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00005050 struct symbol *data; /* The data */
5051 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00005052 struct s_x2node *next; /* Next entry with the same hash */
5053 struct s_x2node **from; /* Previous link */
5054} x2node;
5055
5056/* There is only one instance of the array, which is the following */
5057static struct s_x2 *x2a;
5058
5059/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005060void Symbol_init(void){
drh75897232000-05-29 14:26:00 +00005061 if( x2a ) return;
5062 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
5063 if( x2a ){
5064 x2a->size = 128;
5065 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005066 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005067 if( x2a->tbl==0 ){
5068 free(x2a);
5069 x2a = 0;
5070 }else{
5071 int i;
5072 x2a->ht = (x2node**)&(x2a->tbl[128]);
5073 for(i=0; i<128; i++) x2a->ht[i] = 0;
5074 }
5075 }
5076}
5077/* Insert a new record into the array. Return TRUE if successful.
5078** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005079int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00005080{
5081 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005082 unsigned h;
5083 unsigned ph;
drh75897232000-05-29 14:26:00 +00005084
5085 if( x2a==0 ) return 0;
5086 ph = strhash(key);
5087 h = ph & (x2a->size-1);
5088 np = x2a->ht[h];
5089 while( np ){
5090 if( strcmp(np->key,key)==0 ){
5091 /* An existing entry with the same key is found. */
5092 /* Fail because overwrite is not allows. */
5093 return 0;
5094 }
5095 np = np->next;
5096 }
5097 if( x2a->count>=x2a->size ){
5098 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005099 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005100 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005101 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005102 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005103 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005104 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005105 array.ht = (x2node**)&(array.tbl[arrSize]);
5106 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005107 for(i=0; i<x2a->count; i++){
5108 x2node *oldnp, *newnp;
5109 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005110 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005111 newnp = &(array.tbl[i]);
5112 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5113 newnp->next = array.ht[h];
5114 newnp->key = oldnp->key;
5115 newnp->data = oldnp->data;
5116 newnp->from = &(array.ht[h]);
5117 array.ht[h] = newnp;
5118 }
5119 free(x2a->tbl);
5120 *x2a = array;
5121 }
5122 /* Insert the new data */
5123 h = ph & (x2a->size-1);
5124 np = &(x2a->tbl[x2a->count++]);
5125 np->key = key;
5126 np->data = data;
5127 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5128 np->next = x2a->ht[h];
5129 x2a->ht[h] = np;
5130 np->from = &(x2a->ht[h]);
5131 return 1;
5132}
5133
5134/* Return a pointer to data assigned to the given key. Return NULL
5135** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005136struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005137{
drh01f75f22013-10-02 20:46:30 +00005138 unsigned h;
drh75897232000-05-29 14:26:00 +00005139 x2node *np;
5140
5141 if( x2a==0 ) return 0;
5142 h = strhash(key) & (x2a->size-1);
5143 np = x2a->ht[h];
5144 while( np ){
5145 if( strcmp(np->key,key)==0 ) break;
5146 np = np->next;
5147 }
5148 return np ? np->data : 0;
5149}
5150
5151/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005152struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005153{
5154 struct symbol *data;
5155 if( x2a && n>0 && n<=x2a->count ){
5156 data = x2a->tbl[n-1].data;
5157 }else{
5158 data = 0;
5159 }
5160 return data;
5161}
5162
5163/* Return the size of the array */
5164int Symbol_count()
5165{
5166 return x2a ? x2a->count : 0;
5167}
5168
5169/* Return an array of pointers to all data in the table.
5170** The array is obtained from malloc. Return NULL if memory allocation
5171** problems, or if the array is empty. */
5172struct symbol **Symbol_arrayof()
5173{
5174 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005175 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005176 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005177 arrSize = x2a->count;
5178 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005179 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005180 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005181 }
5182 return array;
5183}
5184
5185/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005186int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005187{
icculus9e44cf12010-02-14 17:14:22 +00005188 const struct config *a = (struct config *) _a;
5189 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005190 int x;
5191 x = a->rp->index - b->rp->index;
5192 if( x==0 ) x = a->dot - b->dot;
5193 return x;
5194}
5195
5196/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005197PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005198{
5199 int rc;
5200 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5201 rc = a->rp->index - b->rp->index;
5202 if( rc==0 ) rc = a->dot - b->dot;
5203 }
5204 if( rc==0 ){
5205 if( a ) rc = 1;
5206 if( b ) rc = -1;
5207 }
5208 return rc;
5209}
5210
5211/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005212PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005213{
drh01f75f22013-10-02 20:46:30 +00005214 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005215 while( a ){
5216 h = h*571 + a->rp->index*37 + a->dot;
5217 a = a->bp;
5218 }
5219 return h;
5220}
5221
5222/* Allocate a new state structure */
5223struct state *State_new()
5224{
icculus9e44cf12010-02-14 17:14:22 +00005225 struct state *newstate;
5226 newstate = (struct state *)calloc(1, sizeof(struct state) );
5227 MemoryCheck(newstate);
5228 return newstate;
drh75897232000-05-29 14:26:00 +00005229}
5230
5231/* There is one instance of the following structure for each
5232** associative array of type "x3".
5233*/
5234struct s_x3 {
5235 int size; /* The number of available slots. */
5236 /* Must be a power of 2 greater than or */
5237 /* equal to 1 */
5238 int count; /* Number of currently slots filled */
5239 struct s_x3node *tbl; /* The data stored here */
5240 struct s_x3node **ht; /* Hash table for lookups */
5241};
5242
5243/* There is one instance of this structure for every data element
5244** in an associative array of type "x3".
5245*/
5246typedef struct s_x3node {
5247 struct state *data; /* The data */
5248 struct config *key; /* The key */
5249 struct s_x3node *next; /* Next entry with the same hash */
5250 struct s_x3node **from; /* Previous link */
5251} x3node;
5252
5253/* There is only one instance of the array, which is the following */
5254static struct s_x3 *x3a;
5255
5256/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005257void State_init(void){
drh75897232000-05-29 14:26:00 +00005258 if( x3a ) return;
5259 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5260 if( x3a ){
5261 x3a->size = 128;
5262 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005263 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005264 if( x3a->tbl==0 ){
5265 free(x3a);
5266 x3a = 0;
5267 }else{
5268 int i;
5269 x3a->ht = (x3node**)&(x3a->tbl[128]);
5270 for(i=0; i<128; i++) x3a->ht[i] = 0;
5271 }
5272 }
5273}
5274/* Insert a new record into the array. Return TRUE if successful.
5275** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005276int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005277{
5278 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005279 unsigned h;
5280 unsigned ph;
drh75897232000-05-29 14:26:00 +00005281
5282 if( x3a==0 ) return 0;
5283 ph = statehash(key);
5284 h = ph & (x3a->size-1);
5285 np = x3a->ht[h];
5286 while( np ){
5287 if( statecmp(np->key,key)==0 ){
5288 /* An existing entry with the same key is found. */
5289 /* Fail because overwrite is not allows. */
5290 return 0;
5291 }
5292 np = np->next;
5293 }
5294 if( x3a->count>=x3a->size ){
5295 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005296 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005297 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005298 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005299 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005300 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005301 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005302 array.ht = (x3node**)&(array.tbl[arrSize]);
5303 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005304 for(i=0; i<x3a->count; i++){
5305 x3node *oldnp, *newnp;
5306 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005307 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005308 newnp = &(array.tbl[i]);
5309 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5310 newnp->next = array.ht[h];
5311 newnp->key = oldnp->key;
5312 newnp->data = oldnp->data;
5313 newnp->from = &(array.ht[h]);
5314 array.ht[h] = newnp;
5315 }
5316 free(x3a->tbl);
5317 *x3a = array;
5318 }
5319 /* Insert the new data */
5320 h = ph & (x3a->size-1);
5321 np = &(x3a->tbl[x3a->count++]);
5322 np->key = key;
5323 np->data = data;
5324 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5325 np->next = x3a->ht[h];
5326 x3a->ht[h] = np;
5327 np->from = &(x3a->ht[h]);
5328 return 1;
5329}
5330
5331/* Return a pointer to data assigned to the given key. Return NULL
5332** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005333struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005334{
drh01f75f22013-10-02 20:46:30 +00005335 unsigned h;
drh75897232000-05-29 14:26:00 +00005336 x3node *np;
5337
5338 if( x3a==0 ) return 0;
5339 h = statehash(key) & (x3a->size-1);
5340 np = x3a->ht[h];
5341 while( np ){
5342 if( statecmp(np->key,key)==0 ) break;
5343 np = np->next;
5344 }
5345 return np ? np->data : 0;
5346}
5347
5348/* Return an array of pointers to all data in the table.
5349** The array is obtained from malloc. Return NULL if memory allocation
5350** problems, or if the array is empty. */
drh14d88552017-04-14 19:44:15 +00005351struct state **State_arrayof(void)
drh75897232000-05-29 14:26:00 +00005352{
5353 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005354 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005355 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005356 arrSize = x3a->count;
5357 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005358 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005359 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005360 }
5361 return array;
5362}
5363
5364/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005365PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005366{
drh01f75f22013-10-02 20:46:30 +00005367 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005368 h = h*571 + a->rp->index*37 + a->dot;
5369 return h;
5370}
5371
5372/* There is one instance of the following structure for each
5373** associative array of type "x4".
5374*/
5375struct s_x4 {
5376 int size; /* The number of available slots. */
5377 /* Must be a power of 2 greater than or */
5378 /* equal to 1 */
5379 int count; /* Number of currently slots filled */
5380 struct s_x4node *tbl; /* The data stored here */
5381 struct s_x4node **ht; /* Hash table for lookups */
5382};
5383
5384/* There is one instance of this structure for every data element
5385** in an associative array of type "x4".
5386*/
5387typedef struct s_x4node {
5388 struct config *data; /* The data */
5389 struct s_x4node *next; /* Next entry with the same hash */
5390 struct s_x4node **from; /* Previous link */
5391} x4node;
5392
5393/* There is only one instance of the array, which is the following */
5394static struct s_x4 *x4a;
5395
5396/* Allocate a new associative array */
drh14d88552017-04-14 19:44:15 +00005397void Configtable_init(void){
drh75897232000-05-29 14:26:00 +00005398 if( x4a ) return;
5399 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5400 if( x4a ){
5401 x4a->size = 64;
5402 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005403 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005404 if( x4a->tbl==0 ){
5405 free(x4a);
5406 x4a = 0;
5407 }else{
5408 int i;
5409 x4a->ht = (x4node**)&(x4a->tbl[64]);
5410 for(i=0; i<64; i++) x4a->ht[i] = 0;
5411 }
5412 }
5413}
5414/* Insert a new record into the array. Return TRUE if successful.
5415** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005416int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005417{
5418 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005419 unsigned h;
5420 unsigned ph;
drh75897232000-05-29 14:26:00 +00005421
5422 if( x4a==0 ) return 0;
5423 ph = confighash(data);
5424 h = ph & (x4a->size-1);
5425 np = x4a->ht[h];
5426 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005427 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005428 /* An existing entry with the same key is found. */
5429 /* Fail because overwrite is not allows. */
5430 return 0;
5431 }
5432 np = np->next;
5433 }
5434 if( x4a->count>=x4a->size ){
5435 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005436 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005437 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005438 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005439 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005440 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005441 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005442 array.ht = (x4node**)&(array.tbl[arrSize]);
5443 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005444 for(i=0; i<x4a->count; i++){
5445 x4node *oldnp, *newnp;
5446 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005447 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005448 newnp = &(array.tbl[i]);
5449 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5450 newnp->next = array.ht[h];
5451 newnp->data = oldnp->data;
5452 newnp->from = &(array.ht[h]);
5453 array.ht[h] = newnp;
5454 }
5455 free(x4a->tbl);
5456 *x4a = array;
5457 }
5458 /* Insert the new data */
5459 h = ph & (x4a->size-1);
5460 np = &(x4a->tbl[x4a->count++]);
5461 np->data = data;
5462 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5463 np->next = x4a->ht[h];
5464 x4a->ht[h] = np;
5465 np->from = &(x4a->ht[h]);
5466 return 1;
5467}
5468
5469/* Return a pointer to data assigned to the given key. Return NULL
5470** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005471struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005472{
5473 int h;
5474 x4node *np;
5475
5476 if( x4a==0 ) return 0;
5477 h = confighash(key) & (x4a->size-1);
5478 np = x4a->ht[h];
5479 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005480 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005481 np = np->next;
5482 }
5483 return np ? np->data : 0;
5484}
5485
5486/* Remove all data from the table. Pass each data to the function "f"
5487** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005488void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005489{
5490 int i;
5491 if( x4a==0 || x4a->count==0 ) return;
5492 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5493 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5494 x4a->count = 0;
5495 return;
5496}