blob: d643b341e439aee7b413b26a21c0e3a539fc10f2 [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" ************************************/
171void FindRulePrecedences();
172void FindFirstSets();
173void FindStates();
174void FindLinks();
175void FindFollowSets();
176void FindActions();
177
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 */
drh4dc8ef52008-07-01 17:13:57 +0000266 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000267 char *datatype; /* The data type of information held by this
268 ** object. Only used if type==NONTERMINAL */
269 int dtnum; /* The data type number. In the parser, the value
270 ** stack is a union. The .yy%d element of this
271 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000272 /* The following fields are used by MULTITERMINALs only */
273 int nsubsym; /* Number of constituent symbols in the MULTI */
274 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000275};
276
277/* Each production rule in the grammar is stored in the following
278** structure. */
279struct rule {
280 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000281 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000282 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000283 int ruleline; /* Line number for the rule */
284 int nrhs; /* Number of RHS symbols */
285 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000286 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000287 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000288 const char *code; /* The code executed when this rule is reduced */
drh4dd0d3f2016-02-17 01:18:33 +0000289 const char *codePrefix; /* Setup code before code[] above */
290 const char *codeSuffix; /* Breakdown code after code[] above */
drh711c9812016-05-23 14:24:31 +0000291 int noCode; /* True if this rule has no associated C code */
292 int codeEmitted; /* True if the code has been emitted already */
drh75897232000-05-29 14:26:00 +0000293 struct symbol *precsym; /* Precedence symbol for this rule */
294 int index; /* An index number for this rule */
drh4ef07702016-03-16 19:45:54 +0000295 int iRule; /* Rule number as used in the generated tables */
drh75897232000-05-29 14:26:00 +0000296 Boolean canReduce; /* True if this rule is ever reduced */
297 struct rule *nextlhs; /* Next rule with the same LHS */
298 struct rule *next; /* Next rule in the global list */
299};
300
301/* A configuration is a production rule of the grammar together with
302** a mark (dot) showing how much of that rule has been processed so far.
303** Configurations also contain a follow-set which is a list of terminal
304** symbols which are allowed to immediately follow the end of the rule.
305** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000306enum cfgstatus {
307 COMPLETE,
308 INCOMPLETE
309};
drh75897232000-05-29 14:26:00 +0000310struct config {
311 struct rule *rp; /* The rule upon which the configuration is based */
312 int dot; /* The parse point */
313 char *fws; /* Follow-set for this configuration only */
314 struct plink *fplp; /* Follow-set forward propagation links */
315 struct plink *bplp; /* Follow-set backwards propagation links */
316 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000317 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000318 struct config *next; /* Next configuration in the state */
319 struct config *bp; /* The next basis configuration */
320};
321
icculus9e44cf12010-02-14 17:14:22 +0000322enum e_action {
323 SHIFT,
324 ACCEPT,
325 REDUCE,
326 ERROR,
327 SSCONFLICT, /* A shift/shift conflict */
328 SRCONFLICT, /* Was a reduce, but part of a conflict */
329 RRCONFLICT, /* Was a reduce, but part of a conflict */
330 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
331 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000332 NOT_USED, /* Deleted by compression */
333 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000334};
335
drh75897232000-05-29 14:26:00 +0000336/* Every shift or reduce operation is stored as one of the following */
337struct action {
338 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000339 enum e_action type;
drh75897232000-05-29 14:26:00 +0000340 union {
341 struct state *stp; /* The new state, if a shift */
342 struct rule *rp; /* The rule, if a reduce */
343 } x;
drhc173ad82016-05-23 16:15:02 +0000344 struct symbol *spOpt; /* SHIFTREDUCE optimization to this symbol */
drh75897232000-05-29 14:26:00 +0000345 struct action *next; /* Next action for this state */
346 struct action *collide; /* Next action with the same hash */
347};
348
349/* Each state of the generated parser's finite state machine
350** is encoded as an instance of the following structure. */
351struct state {
352 struct config *bp; /* The basis configurations for this state */
353 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000354 int statenum; /* Sequential number for this state */
drh711c9812016-05-23 14:24:31 +0000355 struct action *ap; /* List of actions for this state */
drh8b582012003-10-21 13:16:03 +0000356 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
357 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000358 int iDfltReduce; /* Default action is to REDUCE by this rule */
359 struct rule *pDfltReduce;/* The default REDUCE rule. */
360 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000361};
drh8b582012003-10-21 13:16:03 +0000362#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000363
364/* A followset propagation link indicates that the contents of one
365** configuration followset should be propagated to another whenever
366** the first changes. */
367struct plink {
368 struct config *cfp; /* The configuration to which linked */
369 struct plink *next; /* The next propagate link */
370};
371
372/* The state vector for the entire parser generator is recorded as
373** follows. (LEMON uses no global variables and makes little use of
374** static variables. Fields in the following structure can be thought
375** of as begin global variables in the program.) */
376struct lemon {
377 struct state **sorted; /* Table of states sorted by state number */
378 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000379 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000380 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000381 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000382 int nrule; /* Number of rules */
383 int nsymbol; /* Number of terminal and nonterminal symbols */
384 int nterminal; /* Number of terminal symbols */
385 struct symbol **symbols; /* Sorted array of pointers to symbols */
386 int errorcnt; /* Number of errors */
387 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000388 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000389 char *name; /* Name of the generated parser */
390 char *arg; /* Declaration of the 3th argument to parser */
391 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000392 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000393 char *start; /* Name of the start symbol for the grammar */
394 char *stacksize; /* Size of the parser stack */
395 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000396 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000397 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000398 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000399 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000400 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000401 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000402 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000403 char *filename; /* Name of the input file */
404 char *outname; /* Name of the current output file */
405 char *tokenprefix; /* A prefix added to token names in the .h file */
406 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000407 int nactiontab; /* Number of entries in the yy_action[] table */
408 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000409 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000410 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000411 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000412 char *argv0; /* Name of the program */
413};
414
415#define MemoryCheck(X) if((X)==0){ \
416 extern void memory_error(); \
417 memory_error(); \
418}
419
420/**************** From the file "table.h" *********************************/
421/*
422** All code in this file has been automatically generated
423** from a specification in the file
424** "table.q"
425** by the associative array code building program "aagen".
426** Do not edit this file! Instead, edit the specification
427** file, then rerun aagen.
428*/
429/*
430** Code for processing tables in the LEMON parser generator.
431*/
drh75897232000-05-29 14:26:00 +0000432/* Routines for handling a strings */
433
icculus9e44cf12010-02-14 17:14:22 +0000434const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000435
icculus9e44cf12010-02-14 17:14:22 +0000436void Strsafe_init(void);
437int Strsafe_insert(const char *);
438const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000439
440/* Routines for handling symbols of the grammar */
441
icculus9e44cf12010-02-14 17:14:22 +0000442struct symbol *Symbol_new(const char *);
443int Symbolcmpp(const void *, const void *);
444void Symbol_init(void);
445int Symbol_insert(struct symbol *, const char *);
446struct symbol *Symbol_find(const char *);
447struct symbol *Symbol_Nth(int);
448int Symbol_count(void);
449struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000450
451/* Routines to manage the state table */
452
icculus9e44cf12010-02-14 17:14:22 +0000453int Configcmp(const char *, const char *);
454struct state *State_new(void);
455void State_init(void);
456int State_insert(struct state *, struct config *);
457struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000458struct state **State_arrayof(/* */);
459
460/* Routines used for efficiency in Configlist_add */
461
icculus9e44cf12010-02-14 17:14:22 +0000462void Configtable_init(void);
463int Configtable_insert(struct config *);
464struct config *Configtable_find(struct config *);
465void Configtable_clear(int(*)(struct config *));
466
drh75897232000-05-29 14:26:00 +0000467/****************** From the file "action.c" *******************************/
468/*
469** Routines processing parser actions in the LEMON parser generator.
470*/
471
472/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000473static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000474 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000475 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000476
477 if( freelist==0 ){
478 int i;
479 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000480 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000481 if( freelist==0 ){
482 fprintf(stderr,"Unable to allocate memory for a new parser action.");
483 exit(1);
484 }
485 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
486 freelist[amt-1].next = 0;
487 }
icculus9e44cf12010-02-14 17:14:22 +0000488 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000489 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000490 return newaction;
drh75897232000-05-29 14:26:00 +0000491}
492
drhe9278182007-07-18 18:16:29 +0000493/* Compare two actions for sorting purposes. Return negative, zero, or
494** positive if the first action is less than, equal to, or greater than
495** the first
496*/
497static int actioncmp(
498 struct action *ap1,
499 struct action *ap2
500){
drh75897232000-05-29 14:26:00 +0000501 int rc;
502 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000503 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000504 rc = (int)ap1->type - (int)ap2->type;
505 }
drh3bd48ab2015-09-07 18:23:37 +0000506 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000507 rc = ap1->x.rp->index - ap2->x.rp->index;
508 }
drhe594bc32009-11-03 13:02:25 +0000509 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000510 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000511 }
drh75897232000-05-29 14:26:00 +0000512 return rc;
513}
514
515/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000516static struct action *Action_sort(
517 struct action *ap
518){
519 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
520 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000521 return ap;
522}
523
icculus9e44cf12010-02-14 17:14:22 +0000524void Action_add(
525 struct action **app,
526 enum e_action type,
527 struct symbol *sp,
528 char *arg
529){
530 struct action *newaction;
531 newaction = Action_new();
532 newaction->next = *app;
533 *app = newaction;
534 newaction->type = type;
535 newaction->sp = sp;
drhc173ad82016-05-23 16:15:02 +0000536 newaction->spOpt = 0;
drh75897232000-05-29 14:26:00 +0000537 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000538 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000539 }else{
icculus9e44cf12010-02-14 17:14:22 +0000540 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000541 }
542}
drh8b582012003-10-21 13:16:03 +0000543/********************** New code to implement the "acttab" module ***********/
544/*
545** This module implements routines use to construct the yy_action[] table.
546*/
547
548/*
549** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000550** the following structure.
551**
552** The yy_action table maps the pair (state_number, lookahead) into an
553** action_number. The table is an array of integers pairs. The state_number
554** determines an initial offset into the yy_action array. The lookahead
555** value is then added to this initial offset to get an index X into the
556** yy_action array. If the aAction[X].lookahead equals the value of the
557** of the lookahead input, then the value of the action_number output is
558** aAction[X].action. If the lookaheads do not match then the
559** default action for the state_number is returned.
560**
561** All actions associated with a single state_number are first entered
562** into aLookahead[] using multiple calls to acttab_action(). Then the
563** actions for that single state_number are placed into the aAction[]
564** array with a single call to acttab_insert(). The acttab_insert() call
565** also resets the aLookahead[] array in preparation for the next
566** state number.
drh8b582012003-10-21 13:16:03 +0000567*/
icculus9e44cf12010-02-14 17:14:22 +0000568struct lookahead_action {
569 int lookahead; /* Value of the lookahead token */
570 int action; /* Action to take on the given lookahead */
571};
drh8b582012003-10-21 13:16:03 +0000572typedef struct acttab acttab;
573struct acttab {
574 int nAction; /* Number of used slots in aAction[] */
575 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000576 struct lookahead_action
577 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000578 *aLookahead; /* A single new transaction set */
579 int mnLookahead; /* Minimum aLookahead[].lookahead */
580 int mnAction; /* Action associated with mnLookahead */
581 int mxLookahead; /* Maximum aLookahead[].lookahead */
582 int nLookahead; /* Used slots in aLookahead[] */
583 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
584};
585
586/* Return the number of entries in the yy_action table */
587#define acttab_size(X) ((X)->nAction)
588
589/* The value for the N-th entry in yy_action */
590#define acttab_yyaction(X,N) ((X)->aAction[N].action)
591
592/* The value for the N-th entry in yy_lookahead */
593#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
594
595/* Free all memory associated with the given acttab */
596void acttab_free(acttab *p){
597 free( p->aAction );
598 free( p->aLookahead );
599 free( p );
600}
601
602/* Allocate a new acttab structure */
603acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000604 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000605 if( p==0 ){
606 fprintf(stderr,"Unable to allocate memory for a new acttab.");
607 exit(1);
608 }
609 memset(p, 0, sizeof(*p));
610 return p;
611}
612
drh8dc3e8f2010-01-07 03:53:03 +0000613/* Add a new action to the current transaction set.
614**
615** This routine is called once for each lookahead for a particular
616** state.
drh8b582012003-10-21 13:16:03 +0000617*/
618void acttab_action(acttab *p, int lookahead, int action){
619 if( p->nLookahead>=p->nLookaheadAlloc ){
620 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000621 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000622 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
623 if( p->aLookahead==0 ){
624 fprintf(stderr,"malloc failed\n");
625 exit(1);
626 }
627 }
628 if( p->nLookahead==0 ){
629 p->mxLookahead = lookahead;
630 p->mnLookahead = lookahead;
631 p->mnAction = action;
632 }else{
633 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
634 if( p->mnLookahead>lookahead ){
635 p->mnLookahead = lookahead;
636 p->mnAction = action;
637 }
638 }
639 p->aLookahead[p->nLookahead].lookahead = lookahead;
640 p->aLookahead[p->nLookahead].action = action;
641 p->nLookahead++;
642}
643
644/*
645** Add the transaction set built up with prior calls to acttab_action()
646** into the current action table. Then reset the transaction set back
647** to an empty set in preparation for a new round of acttab_action() calls.
648**
649** Return the offset into the action table of the new transaction.
650*/
651int acttab_insert(acttab *p){
652 int i, j, k, n;
653 assert( p->nLookahead>0 );
654
655 /* Make sure we have enough space to hold the expanded action table
656 ** in the worst case. The worst case occurs if the transaction set
657 ** must be appended to the current action table
658 */
drh784d86f2004-02-19 18:41:53 +0000659 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000660 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000661 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000662 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000663 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000664 sizeof(p->aAction[0])*p->nActionAlloc);
665 if( p->aAction==0 ){
666 fprintf(stderr,"malloc failed\n");
667 exit(1);
668 }
drhfdbf9282003-10-21 16:34:41 +0000669 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000670 p->aAction[i].lookahead = -1;
671 p->aAction[i].action = -1;
672 }
673 }
674
drh8dc3e8f2010-01-07 03:53:03 +0000675 /* Scan the existing action table looking for an offset that is a
676 ** duplicate of the current transaction set. Fall out of the loop
677 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000678 **
679 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
680 */
drh8dc3e8f2010-01-07 03:53:03 +0000681 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000682 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000683 /* All lookaheads and actions in the aLookahead[] transaction
684 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000685 if( p->aAction[i].action!=p->mnAction ) continue;
686 for(j=0; j<p->nLookahead; j++){
687 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
688 if( k<0 || k>=p->nAction ) break;
689 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
690 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
691 }
692 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000693
694 /* No possible lookahead value that is not in the aLookahead[]
695 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000696 n = 0;
697 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000698 if( p->aAction[j].lookahead<0 ) continue;
699 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000700 }
drhfdbf9282003-10-21 16:34:41 +0000701 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000702 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000703 }
drh8b582012003-10-21 13:16:03 +0000704 }
705 }
drh8dc3e8f2010-01-07 03:53:03 +0000706
707 /* If no existing offsets exactly match the current transaction, find an
708 ** an empty offset in the aAction[] table in which we can add the
709 ** aLookahead[] transaction.
710 */
drhf16371d2009-11-03 19:18:31 +0000711 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000712 /* Look for holes in the aAction[] table that fit the current
713 ** aLookahead[] transaction. Leave i set to the offset of the hole.
714 ** If no holes are found, i is left at p->nAction, which means the
715 ** transaction will be appended. */
716 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000717 if( p->aAction[i].lookahead<0 ){
718 for(j=0; j<p->nLookahead; j++){
719 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
720 if( k<0 ) break;
721 if( p->aAction[k].lookahead>=0 ) break;
722 }
723 if( j<p->nLookahead ) continue;
724 for(j=0; j<p->nAction; j++){
725 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
726 }
727 if( j==p->nAction ){
728 break; /* Fits in empty slots */
729 }
730 }
731 }
732 }
drh8b582012003-10-21 13:16:03 +0000733 /* Insert transaction set at index i. */
734 for(j=0; j<p->nLookahead; j++){
735 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
736 p->aAction[k] = p->aLookahead[j];
737 if( k>=p->nAction ) p->nAction = k+1;
738 }
739 p->nLookahead = 0;
740
741 /* Return the offset that is added to the lookahead in order to get the
742 ** index into yy_action of the action */
743 return i - p->mnLookahead;
744}
745
drh75897232000-05-29 14:26:00 +0000746/********************** From the file "build.c" *****************************/
747/*
748** Routines to construction the finite state machine for the LEMON
749** parser generator.
750*/
751
752/* Find a precedence symbol of every rule in the grammar.
753**
754** Those rules which have a precedence symbol coded in the input
755** grammar using the "[symbol]" construct will already have the
756** rp->precsym field filled. Other rules take as their precedence
757** symbol the first RHS symbol with a defined precedence. If there
758** are not RHS symbols with a defined precedence, the precedence
759** symbol field is left blank.
760*/
icculus9e44cf12010-02-14 17:14:22 +0000761void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000762{
763 struct rule *rp;
764 for(rp=xp->rule; rp; rp=rp->next){
765 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000766 int i, j;
767 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
768 struct symbol *sp = rp->rhs[i];
769 if( sp->type==MULTITERMINAL ){
770 for(j=0; j<sp->nsubsym; j++){
771 if( sp->subsym[j]->prec>=0 ){
772 rp->precsym = sp->subsym[j];
773 break;
774 }
775 }
776 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000777 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000778 }
drh75897232000-05-29 14:26:00 +0000779 }
780 }
781 }
782 return;
783}
784
785/* Find all nonterminals which will generate the empty string.
786** Then go back and compute the first sets of every nonterminal.
787** The first set is the set of all terminal symbols which can begin
788** a string generated by that nonterminal.
789*/
icculus9e44cf12010-02-14 17:14:22 +0000790void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000791{
drhfd405312005-11-06 04:06:59 +0000792 int i, j;
drh75897232000-05-29 14:26:00 +0000793 struct rule *rp;
794 int progress;
795
796 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000797 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000798 }
799 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
800 lemp->symbols[i]->firstset = SetNew();
801 }
802
803 /* First compute all lambdas */
804 do{
805 progress = 0;
806 for(rp=lemp->rule; rp; rp=rp->next){
807 if( rp->lhs->lambda ) continue;
808 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000809 struct symbol *sp = rp->rhs[i];
810 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
811 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000812 }
813 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000814 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000815 progress = 1;
816 }
817 }
818 }while( progress );
819
820 /* Now compute all first sets */
821 do{
822 struct symbol *s1, *s2;
823 progress = 0;
824 for(rp=lemp->rule; rp; rp=rp->next){
825 s1 = rp->lhs;
826 for(i=0; i<rp->nrhs; i++){
827 s2 = rp->rhs[i];
828 if( s2->type==TERMINAL ){
829 progress += SetAdd(s1->firstset,s2->index);
830 break;
drhfd405312005-11-06 04:06:59 +0000831 }else if( s2->type==MULTITERMINAL ){
832 for(j=0; j<s2->nsubsym; j++){
833 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
834 }
835 break;
drhf2f105d2012-08-20 15:53:54 +0000836 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000837 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000838 }else{
drh75897232000-05-29 14:26:00 +0000839 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000840 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000841 }
drh75897232000-05-29 14:26:00 +0000842 }
843 }
844 }while( progress );
845 return;
846}
847
848/* Compute all LR(0) states for the grammar. Links
849** are added to between some states so that the LR(1) follow sets
850** can be computed later.
851*/
icculus9e44cf12010-02-14 17:14:22 +0000852PRIVATE struct state *getstate(struct lemon *); /* forward reference */
853void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000854{
855 struct symbol *sp;
856 struct rule *rp;
857
858 Configlist_init();
859
860 /* Find the start symbol */
861 if( lemp->start ){
862 sp = Symbol_find(lemp->start);
863 if( sp==0 ){
864 ErrorMsg(lemp->filename,0,
865"The specified start symbol \"%s\" is not \
866in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000867symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000868 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000869 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000870 }
871 }else{
drh4ef07702016-03-16 19:45:54 +0000872 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000873 }
874
875 /* Make sure the start symbol doesn't occur on the right-hand side of
876 ** any rule. Report an error if it does. (YACC would generate a new
877 ** start symbol in this case.) */
878 for(rp=lemp->rule; rp; rp=rp->next){
879 int i;
880 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000881 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000882 ErrorMsg(lemp->filename,0,
883"The start symbol \"%s\" occurs on the \
884right-hand side of a rule. This will result in a parser which \
885does not work properly.",sp->name);
886 lemp->errorcnt++;
887 }
888 }
889 }
890
891 /* The basis configuration set for the first state
892 ** is all rules which have the start symbol as their
893 ** left-hand side */
894 for(rp=sp->rule; rp; rp=rp->nextlhs){
895 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000896 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000897 newcfp = Configlist_addbasis(rp,0);
898 SetAdd(newcfp->fws,0);
899 }
900
901 /* Compute the first state. All other states will be
902 ** computed automatically during the computation of the first one.
903 ** The returned pointer to the first state is not used. */
904 (void)getstate(lemp);
905 return;
906}
907
908/* Return a pointer to a state which is described by the configuration
909** list which has been built from calls to Configlist_add.
910*/
icculus9e44cf12010-02-14 17:14:22 +0000911PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
912PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000913{
914 struct config *cfp, *bp;
915 struct state *stp;
916
917 /* Extract the sorted basis of the new state. The basis was constructed
918 ** by prior calls to "Configlist_addbasis()". */
919 Configlist_sortbasis();
920 bp = Configlist_basis();
921
922 /* Get a state with the same basis */
923 stp = State_find(bp);
924 if( stp ){
925 /* A state with the same basis already exists! Copy all the follow-set
926 ** propagation links from the state under construction into the
927 ** preexisting state, then return a pointer to the preexisting state */
928 struct config *x, *y;
929 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
930 Plink_copy(&y->bplp,x->bplp);
931 Plink_delete(x->fplp);
932 x->fplp = x->bplp = 0;
933 }
934 cfp = Configlist_return();
935 Configlist_eat(cfp);
936 }else{
937 /* This really is a new state. Construct all the details */
938 Configlist_closure(lemp); /* Compute the configuration closure */
939 Configlist_sort(); /* Sort the configuration closure */
940 cfp = Configlist_return(); /* Get a pointer to the config list */
941 stp = State_new(); /* A new state structure */
942 MemoryCheck(stp);
943 stp->bp = bp; /* Remember the configuration basis */
944 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000945 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000946 stp->ap = 0; /* No actions, yet. */
947 State_insert(stp,stp->bp); /* Add to the state table */
948 buildshifts(lemp,stp); /* Recursively compute successor states */
949 }
950 return stp;
951}
952
drhfd405312005-11-06 04:06:59 +0000953/*
954** Return true if two symbols are the same.
955*/
icculus9e44cf12010-02-14 17:14:22 +0000956int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000957{
958 int i;
959 if( a==b ) return 1;
960 if( a->type!=MULTITERMINAL ) return 0;
961 if( b->type!=MULTITERMINAL ) return 0;
962 if( a->nsubsym!=b->nsubsym ) return 0;
963 for(i=0; i<a->nsubsym; i++){
964 if( a->subsym[i]!=b->subsym[i] ) return 0;
965 }
966 return 1;
967}
968
drh75897232000-05-29 14:26:00 +0000969/* Construct all successor states to the given state. A "successor"
970** state is any state which can be reached by a shift action.
971*/
icculus9e44cf12010-02-14 17:14:22 +0000972PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000973{
974 struct config *cfp; /* For looping thru the config closure of "stp" */
975 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000976 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000977 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
978 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
979 struct state *newstp; /* A pointer to a successor state */
980
981 /* Each configuration becomes complete after it contibutes to a successor
982 ** state. Initially, all configurations are incomplete */
983 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
984
985 /* Loop through all configurations of the state "stp" */
986 for(cfp=stp->cfp; cfp; cfp=cfp->next){
987 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
988 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
989 Configlist_reset(); /* Reset the new config set */
990 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
991
992 /* For every configuration in the state "stp" which has the symbol "sp"
993 ** following its dot, add the same configuration to the basis set under
994 ** construction but with the dot shifted one symbol to the right. */
995 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
996 if( bcfp->status==COMPLETE ) continue; /* Already used */
997 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
998 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000999 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +00001000 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +00001001 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1002 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001003 }
1004
1005 /* Get a pointer to the state described by the basis configuration set
1006 ** constructed in the preceding loop */
1007 newstp = getstate(lemp);
1008
1009 /* The state "newstp" is reached from the state "stp" by a shift action
1010 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001011 if( sp->type==MULTITERMINAL ){
1012 int i;
1013 for(i=0; i<sp->nsubsym; i++){
1014 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1015 }
1016 }else{
1017 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1018 }
drh75897232000-05-29 14:26:00 +00001019 }
1020}
1021
1022/*
1023** Construct the propagation links
1024*/
icculus9e44cf12010-02-14 17:14:22 +00001025void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001026{
1027 int i;
1028 struct config *cfp, *other;
1029 struct state *stp;
1030 struct plink *plp;
1031
1032 /* Housekeeping detail:
1033 ** Add to every propagate link a pointer back to the state to
1034 ** which the link is attached. */
1035 for(i=0; i<lemp->nstate; i++){
1036 stp = lemp->sorted[i];
1037 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1038 cfp->stp = stp;
1039 }
1040 }
1041
1042 /* Convert all backlinks into forward links. Only the forward
1043 ** links are used in the follow-set computation. */
1044 for(i=0; i<lemp->nstate; i++){
1045 stp = lemp->sorted[i];
1046 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1047 for(plp=cfp->bplp; plp; plp=plp->next){
1048 other = plp->cfp;
1049 Plink_add(&other->fplp,cfp);
1050 }
1051 }
1052 }
1053}
1054
1055/* Compute all followsets.
1056**
1057** A followset is the set of all symbols which can come immediately
1058** after a configuration.
1059*/
icculus9e44cf12010-02-14 17:14:22 +00001060void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001061{
1062 int i;
1063 struct config *cfp;
1064 struct plink *plp;
1065 int progress;
1066 int change;
1067
1068 for(i=0; i<lemp->nstate; i++){
1069 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1070 cfp->status = INCOMPLETE;
1071 }
1072 }
1073
1074 do{
1075 progress = 0;
1076 for(i=0; i<lemp->nstate; i++){
1077 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1078 if( cfp->status==COMPLETE ) continue;
1079 for(plp=cfp->fplp; plp; plp=plp->next){
1080 change = SetUnion(plp->cfp->fws,cfp->fws);
1081 if( change ){
1082 plp->cfp->status = INCOMPLETE;
1083 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001084 }
1085 }
drh75897232000-05-29 14:26:00 +00001086 cfp->status = COMPLETE;
1087 }
1088 }
1089 }while( progress );
1090}
1091
drh3cb2f6e2012-01-09 14:19:05 +00001092static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001093
1094/* Compute the reduce actions, and resolve conflicts.
1095*/
icculus9e44cf12010-02-14 17:14:22 +00001096void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001097{
1098 int i,j;
1099 struct config *cfp;
1100 struct state *stp;
1101 struct symbol *sp;
1102 struct rule *rp;
1103
1104 /* Add all of the reduce actions
1105 ** A reduce action is added for each element of the followset of
1106 ** a configuration which has its dot at the extreme right.
1107 */
1108 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1109 stp = lemp->sorted[i];
1110 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1111 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1112 for(j=0; j<lemp->nterminal; j++){
1113 if( SetFind(cfp->fws,j) ){
1114 /* Add a reduce action to the state "stp" which will reduce by the
1115 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001116 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001117 }
drhf2f105d2012-08-20 15:53:54 +00001118 }
drh75897232000-05-29 14:26:00 +00001119 }
1120 }
1121 }
1122
1123 /* Add the accepting token */
1124 if( lemp->start ){
1125 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001126 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001127 }else{
drh4ef07702016-03-16 19:45:54 +00001128 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001129 }
1130 /* Add to the first state (which is always the starting state of the
1131 ** finite state machine) an action to ACCEPT if the lookahead is the
1132 ** start nonterminal. */
1133 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1134
1135 /* Resolve conflicts */
1136 for(i=0; i<lemp->nstate; i++){
1137 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001138 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001139 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001140 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001141 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001142 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1143 /* The two actions "ap" and "nap" have the same lookahead.
1144 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001145 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001146 }
1147 }
1148 }
1149
1150 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001151 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001152 for(i=0; i<lemp->nstate; i++){
1153 struct action *ap;
1154 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001155 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001156 }
1157 }
1158 for(rp=lemp->rule; rp; rp=rp->next){
1159 if( rp->canReduce ) continue;
1160 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1161 lemp->errorcnt++;
1162 }
1163}
1164
1165/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001166** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001167**
1168** NO LONGER TRUE:
1169** To resolve a conflict, first look to see if either action
1170** is on an error rule. In that case, take the action which
1171** is not associated with the error rule. If neither or both
1172** actions are associated with an error rule, then try to
1173** use precedence to resolve the conflict.
1174**
1175** If either action is a SHIFT, then it must be apx. This
1176** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1177*/
icculus9e44cf12010-02-14 17:14:22 +00001178static int resolve_conflict(
1179 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001180 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001181){
drh75897232000-05-29 14:26:00 +00001182 struct symbol *spx, *spy;
1183 int errcnt = 0;
1184 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001185 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001186 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001187 errcnt++;
1188 }
drh75897232000-05-29 14:26:00 +00001189 if( apx->type==SHIFT && apy->type==REDUCE ){
1190 spx = apx->sp;
1191 spy = apy->x.rp->precsym;
1192 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1193 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001194 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001195 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001196 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001197 apy->type = RD_RESOLVED;
1198 }else if( spx->prec<spy->prec ){
1199 apx->type = SH_RESOLVED;
1200 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1201 apy->type = RD_RESOLVED; /* associativity */
1202 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1203 apx->type = SH_RESOLVED;
1204 }else{
1205 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001206 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001207 }
1208 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1209 spx = apx->x.rp->precsym;
1210 spy = apy->x.rp->precsym;
1211 if( spx==0 || spy==0 || spx->prec<0 ||
1212 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001213 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001214 errcnt++;
1215 }else if( spx->prec>spy->prec ){
1216 apy->type = RD_RESOLVED;
1217 }else if( spx->prec<spy->prec ){
1218 apx->type = RD_RESOLVED;
1219 }
1220 }else{
drhb59499c2002-02-23 18:45:13 +00001221 assert(
1222 apx->type==SH_RESOLVED ||
1223 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001224 apx->type==SSCONFLICT ||
1225 apx->type==SRCONFLICT ||
1226 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001227 apy->type==SH_RESOLVED ||
1228 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001229 apy->type==SSCONFLICT ||
1230 apy->type==SRCONFLICT ||
1231 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001232 );
1233 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1234 ** REDUCEs on the list. If we reach this point it must be because
1235 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001236 }
1237 return errcnt;
1238}
1239/********************* From the file "configlist.c" *************************/
1240/*
1241** Routines to processing a configuration list and building a state
1242** in the LEMON parser generator.
1243*/
1244
1245static struct config *freelist = 0; /* List of free configurations */
1246static struct config *current = 0; /* Top of list of configurations */
1247static struct config **currentend = 0; /* Last on list of configs */
1248static struct config *basis = 0; /* Top of list of basis configs */
1249static struct config **basisend = 0; /* End of list of basis configs */
1250
1251/* Return a pointer to a new configuration */
1252PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001253 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001254 if( freelist==0 ){
1255 int i;
1256 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001257 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001258 if( freelist==0 ){
1259 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1260 exit(1);
1261 }
1262 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1263 freelist[amt-1].next = 0;
1264 }
icculus9e44cf12010-02-14 17:14:22 +00001265 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001266 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001267 return newcfg;
drh75897232000-05-29 14:26:00 +00001268}
1269
1270/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001271PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001272{
1273 old->next = freelist;
1274 freelist = old;
1275}
1276
1277/* Initialized the configuration list builder */
1278void Configlist_init(){
1279 current = 0;
1280 currentend = &current;
1281 basis = 0;
1282 basisend = &basis;
1283 Configtable_init();
1284 return;
1285}
1286
1287/* Initialized the configuration list builder */
1288void Configlist_reset(){
1289 current = 0;
1290 currentend = &current;
1291 basis = 0;
1292 basisend = &basis;
1293 Configtable_clear(0);
1294 return;
1295}
1296
1297/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001298struct config *Configlist_add(
1299 struct rule *rp, /* The rule */
1300 int dot /* Index into the RHS of the rule where the dot goes */
1301){
drh75897232000-05-29 14:26:00 +00001302 struct config *cfp, model;
1303
1304 assert( currentend!=0 );
1305 model.rp = rp;
1306 model.dot = dot;
1307 cfp = Configtable_find(&model);
1308 if( cfp==0 ){
1309 cfp = newconfig();
1310 cfp->rp = rp;
1311 cfp->dot = dot;
1312 cfp->fws = SetNew();
1313 cfp->stp = 0;
1314 cfp->fplp = cfp->bplp = 0;
1315 cfp->next = 0;
1316 cfp->bp = 0;
1317 *currentend = cfp;
1318 currentend = &cfp->next;
1319 Configtable_insert(cfp);
1320 }
1321 return cfp;
1322}
1323
1324/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001325struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001326{
1327 struct config *cfp, model;
1328
1329 assert( basisend!=0 );
1330 assert( currentend!=0 );
1331 model.rp = rp;
1332 model.dot = dot;
1333 cfp = Configtable_find(&model);
1334 if( cfp==0 ){
1335 cfp = newconfig();
1336 cfp->rp = rp;
1337 cfp->dot = dot;
1338 cfp->fws = SetNew();
1339 cfp->stp = 0;
1340 cfp->fplp = cfp->bplp = 0;
1341 cfp->next = 0;
1342 cfp->bp = 0;
1343 *currentend = cfp;
1344 currentend = &cfp->next;
1345 *basisend = cfp;
1346 basisend = &cfp->bp;
1347 Configtable_insert(cfp);
1348 }
1349 return cfp;
1350}
1351
1352/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001353void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001354{
1355 struct config *cfp, *newcfp;
1356 struct rule *rp, *newrp;
1357 struct symbol *sp, *xsp;
1358 int i, dot;
1359
1360 assert( currentend!=0 );
1361 for(cfp=current; cfp; cfp=cfp->next){
1362 rp = cfp->rp;
1363 dot = cfp->dot;
1364 if( dot>=rp->nrhs ) continue;
1365 sp = rp->rhs[dot];
1366 if( sp->type==NONTERMINAL ){
1367 if( sp->rule==0 && sp!=lemp->errsym ){
1368 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1369 sp->name);
1370 lemp->errorcnt++;
1371 }
1372 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1373 newcfp = Configlist_add(newrp,0);
1374 for(i=dot+1; i<rp->nrhs; i++){
1375 xsp = rp->rhs[i];
1376 if( xsp->type==TERMINAL ){
1377 SetAdd(newcfp->fws,xsp->index);
1378 break;
drhfd405312005-11-06 04:06:59 +00001379 }else if( xsp->type==MULTITERMINAL ){
1380 int k;
1381 for(k=0; k<xsp->nsubsym; k++){
1382 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1383 }
1384 break;
drhf2f105d2012-08-20 15:53:54 +00001385 }else{
drh75897232000-05-29 14:26:00 +00001386 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001387 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001388 }
1389 }
drh75897232000-05-29 14:26:00 +00001390 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1391 }
1392 }
1393 }
1394 return;
1395}
1396
1397/* Sort the configuration list */
1398void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001399 current = (struct config*)msort((char*)current,(char**)&(current->next),
1400 Configcmp);
drh75897232000-05-29 14:26:00 +00001401 currentend = 0;
1402 return;
1403}
1404
1405/* Sort the basis configuration list */
1406void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001407 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1408 Configcmp);
drh75897232000-05-29 14:26:00 +00001409 basisend = 0;
1410 return;
1411}
1412
1413/* Return a pointer to the head of the configuration list and
1414** reset the list */
1415struct config *Configlist_return(){
1416 struct config *old;
1417 old = current;
1418 current = 0;
1419 currentend = 0;
1420 return old;
1421}
1422
1423/* Return a pointer to the head of the configuration list and
1424** reset the list */
1425struct config *Configlist_basis(){
1426 struct config *old;
1427 old = basis;
1428 basis = 0;
1429 basisend = 0;
1430 return old;
1431}
1432
1433/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001434void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001435{
1436 struct config *nextcfp;
1437 for(; cfp; cfp=nextcfp){
1438 nextcfp = cfp->next;
1439 assert( cfp->fplp==0 );
1440 assert( cfp->bplp==0 );
1441 if( cfp->fws ) SetFree(cfp->fws);
1442 deleteconfig(cfp);
1443 }
1444 return;
1445}
1446/***************** From the file "error.c" *********************************/
1447/*
1448** Code for printing error message.
1449*/
1450
drhf9a2e7b2003-04-15 01:49:48 +00001451void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001452 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001453 fprintf(stderr, "%s:%d: ", filename, lineno);
1454 va_start(ap, format);
1455 vfprintf(stderr,format,ap);
1456 va_end(ap);
1457 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001458}
1459/**************** From the file "main.c" ************************************/
1460/*
1461** Main program file for the LEMON parser generator.
1462*/
1463
1464/* Report an out-of-memory condition and abort. This function
1465** is used mostly by the "MemoryCheck" macro in struct.h
1466*/
1467void memory_error(){
1468 fprintf(stderr,"Out of memory. Aborting...\n");
1469 exit(1);
1470}
1471
drh6d08b4d2004-07-20 12:45:22 +00001472static int nDefine = 0; /* Number of -D options on the command line */
1473static char **azDefine = 0; /* Name of the -D macros */
1474
1475/* This routine is called with the argument to each -D command-line option.
1476** Add the macro defined to the azDefine array.
1477*/
1478static void handle_D_option(char *z){
1479 char **paz;
1480 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001481 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001482 if( azDefine==0 ){
1483 fprintf(stderr,"out of memory\n");
1484 exit(1);
1485 }
1486 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001487 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001488 if( *paz==0 ){
1489 fprintf(stderr,"out of memory\n");
1490 exit(1);
1491 }
drh898799f2014-01-10 23:21:00 +00001492 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001493 for(z=*paz; *z && *z!='='; z++){}
1494 *z = 0;
1495}
1496
icculus3e143bd2010-02-14 00:48:49 +00001497static char *user_templatename = NULL;
1498static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001499 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001500 if( user_templatename==0 ){
1501 memory_error();
1502 }
drh898799f2014-01-10 23:21:00 +00001503 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001504}
drh75897232000-05-29 14:26:00 +00001505
drh711c9812016-05-23 14:24:31 +00001506/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001507static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1508 struct rule *pFirst = 0;
1509 struct rule **ppPrev = &pFirst;
1510 while( pA && pB ){
1511 if( pA->iRule<pB->iRule ){
1512 *ppPrev = pA;
1513 ppPrev = &pA->next;
1514 pA = pA->next;
1515 }else{
1516 *ppPrev = pB;
1517 ppPrev = &pB->next;
1518 pB = pB->next;
1519 }
1520 }
1521 if( pA ){
1522 *ppPrev = pA;
1523 }else{
1524 *ppPrev = pB;
1525 }
1526 return pFirst;
1527}
1528
1529/*
1530** Sort a list of rules in order of increasing iRule value
1531*/
1532static struct rule *Rule_sort(struct rule *rp){
1533 int i;
1534 struct rule *pNext;
1535 struct rule *x[32];
1536 memset(x, 0, sizeof(x));
1537 while( rp ){
1538 pNext = rp->next;
1539 rp->next = 0;
1540 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1541 rp = Rule_merge(x[i], rp);
1542 x[i] = 0;
1543 }
1544 x[i] = rp;
1545 rp = pNext;
1546 }
1547 rp = 0;
1548 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1549 rp = Rule_merge(x[i], rp);
1550 }
1551 return rp;
1552}
1553
drhc75e0162015-09-07 02:23:02 +00001554/* forward reference */
1555static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1556
1557/* Print a single line of the "Parser Stats" output
1558*/
1559static void stats_line(const char *zLabel, int iValue){
1560 int nLabel = lemonStrlen(zLabel);
1561 printf(" %s%.*s %5d\n", zLabel,
1562 35-nLabel, "................................",
1563 iValue);
1564}
1565
drh75897232000-05-29 14:26:00 +00001566/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001567int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001568{
1569 static int version = 0;
1570 static int rpflag = 0;
1571 static int basisflag = 0;
1572 static int compress = 0;
1573 static int quiet = 0;
1574 static int statistics = 0;
1575 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001576 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001577 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001578 static struct s_options options[] = {
1579 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1580 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001581 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001582 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001583 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001584 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001585 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1586 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001587 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001588 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1589 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001590 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001591 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001592 {OPT_FLAG, "s", (char*)&statistics,
1593 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001594 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001595 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1596 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001597 {OPT_FLAG,0,0,0}
1598 };
1599 int i;
icculus42585cf2010-02-14 05:19:56 +00001600 int exitcode;
drh75897232000-05-29 14:26:00 +00001601 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001602 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001603
drhb0c86772000-06-02 23:21:26 +00001604 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001605 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001606 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001607 exit(0);
1608 }
drhb0c86772000-06-02 23:21:26 +00001609 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001610 fprintf(stderr,"Exactly one filename argument is required.\n");
1611 exit(1);
1612 }
drh954f6b42006-06-13 13:27:46 +00001613 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001614 lem.errorcnt = 0;
1615
1616 /* Initialize the machine */
1617 Strsafe_init();
1618 Symbol_init();
1619 State_init();
1620 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001621 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001622 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001623 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001624 Symbol_new("$");
1625 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001626 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001627
1628 /* Parse the input file */
1629 Parse(&lem);
1630 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001631 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001632 fprintf(stderr,"Empty grammar.\n");
1633 exit(1);
1634 }
1635
1636 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001637 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001638 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001639 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001640 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1641 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1642 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1643 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1644 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1645 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001646 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001647 lem.nterminal = i;
1648
drh711c9812016-05-23 14:24:31 +00001649 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1650 ** reduce action C-code associated with them last, so that the switch()
1651 ** statement that selects reduction actions will have a smaller jump table.
1652 */
drh4ef07702016-03-16 19:45:54 +00001653 for(i=0, rp=lem.rule; rp; rp=rp->next){
1654 rp->iRule = rp->code ? i++ : -1;
1655 }
1656 for(rp=lem.rule; rp; rp=rp->next){
1657 if( rp->iRule<0 ) rp->iRule = i++;
1658 }
1659 lem.startRule = lem.rule;
1660 lem.rule = Rule_sort(lem.rule);
1661
drh75897232000-05-29 14:26:00 +00001662 /* Generate a reprint of the grammar, if requested on the command line */
1663 if( rpflag ){
1664 Reprint(&lem);
1665 }else{
1666 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001667 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001668
1669 /* Find the precedence for every production rule (that has one) */
1670 FindRulePrecedences(&lem);
1671
1672 /* Compute the lambda-nonterminals and the first-sets for every
1673 ** nonterminal */
1674 FindFirstSets(&lem);
1675
1676 /* Compute all LR(0) states. Also record follow-set propagation
1677 ** links so that the follow-set can be computed later */
1678 lem.nstate = 0;
1679 FindStates(&lem);
1680 lem.sorted = State_arrayof();
1681
1682 /* Tie up loose ends on the propagation links */
1683 FindLinks(&lem);
1684
1685 /* Compute the follow set of every reducible configuration */
1686 FindFollowSets(&lem);
1687
1688 /* Compute the action tables */
1689 FindActions(&lem);
1690
1691 /* Compress the action tables */
1692 if( compress==0 ) CompressTables(&lem);
1693
drhada354d2005-11-05 15:03:59 +00001694 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001695 ** occur at the end. This is an optimization that helps make the
1696 ** generated parser tables smaller. */
1697 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001698
drh75897232000-05-29 14:26:00 +00001699 /* Generate a report of the parser generated. (the "y.output" file) */
1700 if( !quiet ) ReportOutput(&lem);
1701
1702 /* Generate the source code for the parser */
1703 ReportTable(&lem, mhflag);
1704
1705 /* Produce a header file for use by the scanner. (This step is
1706 ** omitted if the "-m" option is used because makeheaders will
1707 ** generate the file for us.) */
1708 if( !mhflag ) ReportHeader(&lem);
1709 }
1710 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001711 printf("Parser statistics:\n");
1712 stats_line("terminal symbols", lem.nterminal);
1713 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1714 stats_line("total symbols", lem.nsymbol);
1715 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001716 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001717 stats_line("conflicts", lem.nconflict);
1718 stats_line("action table entries", lem.nactiontab);
1719 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001720 }
icculus8e158022010-02-16 16:09:03 +00001721 if( lem.nconflict > 0 ){
1722 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001723 }
1724
1725 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001726 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001727 exit(exitcode);
1728 return (exitcode);
drh75897232000-05-29 14:26:00 +00001729}
1730/******************** From the file "msort.c" *******************************/
1731/*
1732** A generic merge-sort program.
1733**
1734** USAGE:
1735** Let "ptr" be a pointer to some structure which is at the head of
1736** a null-terminated list. Then to sort the list call:
1737**
1738** ptr = msort(ptr,&(ptr->next),cmpfnc);
1739**
1740** In the above, "cmpfnc" is a pointer to a function which compares
1741** two instances of the structure and returns an integer, as in
1742** strcmp. The second argument is a pointer to the pointer to the
1743** second element of the linked list. This address is used to compute
1744** the offset to the "next" field within the structure. The offset to
1745** the "next" field must be constant for all structures in the list.
1746**
1747** The function returns a new pointer which is the head of the list
1748** after sorting.
1749**
1750** ALGORITHM:
1751** Merge-sort.
1752*/
1753
1754/*
1755** Return a pointer to the next structure in the linked list.
1756*/
drhd25d6922012-04-18 09:59:56 +00001757#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001758
1759/*
1760** Inputs:
1761** a: A sorted, null-terminated linked list. (May be null).
1762** b: A sorted, null-terminated linked list. (May be null).
1763** cmp: A pointer to the comparison function.
1764** offset: Offset in the structure to the "next" field.
1765**
1766** Return Value:
1767** A pointer to the head of a sorted list containing the elements
1768** of both a and b.
1769**
1770** Side effects:
1771** The "next" pointers for elements in the lists a and b are
1772** changed.
1773*/
drhe9278182007-07-18 18:16:29 +00001774static char *merge(
1775 char *a,
1776 char *b,
1777 int (*cmp)(const char*,const char*),
1778 int offset
1779){
drh75897232000-05-29 14:26:00 +00001780 char *ptr, *head;
1781
1782 if( a==0 ){
1783 head = b;
1784 }else if( b==0 ){
1785 head = a;
1786 }else{
drhe594bc32009-11-03 13:02:25 +00001787 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001788 ptr = a;
1789 a = NEXT(a);
1790 }else{
1791 ptr = b;
1792 b = NEXT(b);
1793 }
1794 head = ptr;
1795 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001796 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001797 NEXT(ptr) = a;
1798 ptr = a;
1799 a = NEXT(a);
1800 }else{
1801 NEXT(ptr) = b;
1802 ptr = b;
1803 b = NEXT(b);
1804 }
1805 }
1806 if( a ) NEXT(ptr) = a;
1807 else NEXT(ptr) = b;
1808 }
1809 return head;
1810}
1811
1812/*
1813** Inputs:
1814** list: Pointer to a singly-linked list of structures.
1815** next: Pointer to pointer to the second element of the list.
1816** cmp: A comparison function.
1817**
1818** Return Value:
1819** A pointer to the head of a sorted list containing the elements
1820** orginally in list.
1821**
1822** Side effects:
1823** The "next" pointers for elements in list are changed.
1824*/
1825#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001826static char *msort(
1827 char *list,
1828 char **next,
1829 int (*cmp)(const char*,const char*)
1830){
drhba99af52001-10-25 20:37:16 +00001831 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001832 char *ep;
1833 char *set[LISTSIZE];
1834 int i;
drh1cc0d112015-03-31 15:15:48 +00001835 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001836 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1837 while( list ){
1838 ep = list;
1839 list = NEXT(list);
1840 NEXT(ep) = 0;
1841 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1842 ep = merge(ep,set[i],cmp,offset);
1843 set[i] = 0;
1844 }
1845 set[i] = ep;
1846 }
1847 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001848 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001849 return ep;
1850}
1851/************************ From the file "option.c" **************************/
1852static char **argv;
1853static struct s_options *op;
1854static FILE *errstream;
1855
1856#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1857
1858/*
1859** Print the command line with a carrot pointing to the k-th character
1860** of the n-th field.
1861*/
icculus9e44cf12010-02-14 17:14:22 +00001862static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001863{
1864 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001865 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001866 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001867 for(i=1; i<n && argv[i]; i++){
1868 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001869 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001870 }
1871 spcnt += k;
1872 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1873 if( spcnt<20 ){
1874 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1875 }else{
1876 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1877 }
1878}
1879
1880/*
1881** Return the index of the N-th non-switch argument. Return -1
1882** if N is out of range.
1883*/
icculus9e44cf12010-02-14 17:14:22 +00001884static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001885{
1886 int i;
1887 int dashdash = 0;
1888 if( argv!=0 && *argv!=0 ){
1889 for(i=1; argv[i]; i++){
1890 if( dashdash || !ISOPT(argv[i]) ){
1891 if( n==0 ) return i;
1892 n--;
1893 }
1894 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1895 }
1896 }
1897 return -1;
1898}
1899
1900static char emsg[] = "Command line syntax error: ";
1901
1902/*
1903** Process a flag command line argument.
1904*/
icculus9e44cf12010-02-14 17:14:22 +00001905static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001906{
1907 int v;
1908 int errcnt = 0;
1909 int j;
1910 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001911 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001912 }
1913 v = argv[i][0]=='-' ? 1 : 0;
1914 if( op[j].label==0 ){
1915 if( err ){
1916 fprintf(err,"%sundefined option.\n",emsg);
1917 errline(i,1,err);
1918 }
1919 errcnt++;
drh0325d392015-01-01 19:11:22 +00001920 }else if( op[j].arg==0 ){
1921 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001922 }else if( op[j].type==OPT_FLAG ){
1923 *((int*)op[j].arg) = v;
1924 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001925 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001926 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001927 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001928 }else{
1929 if( err ){
1930 fprintf(err,"%smissing argument on switch.\n",emsg);
1931 errline(i,1,err);
1932 }
1933 errcnt++;
1934 }
1935 return errcnt;
1936}
1937
1938/*
1939** Process a command line switch which has an argument.
1940*/
icculus9e44cf12010-02-14 17:14:22 +00001941static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001942{
1943 int lv = 0;
1944 double dv = 0.0;
1945 char *sv = 0, *end;
1946 char *cp;
1947 int j;
1948 int errcnt = 0;
1949 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001950 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001951 *cp = 0;
1952 for(j=0; op[j].label; j++){
1953 if( strcmp(argv[i],op[j].label)==0 ) break;
1954 }
1955 *cp = '=';
1956 if( op[j].label==0 ){
1957 if( err ){
1958 fprintf(err,"%sundefined option.\n",emsg);
1959 errline(i,0,err);
1960 }
1961 errcnt++;
1962 }else{
1963 cp++;
1964 switch( op[j].type ){
1965 case OPT_FLAG:
1966 case OPT_FFLAG:
1967 if( err ){
1968 fprintf(err,"%soption requires an argument.\n",emsg);
1969 errline(i,0,err);
1970 }
1971 errcnt++;
1972 break;
1973 case OPT_DBL:
1974 case OPT_FDBL:
1975 dv = strtod(cp,&end);
1976 if( *end ){
1977 if( err ){
drh25473362015-09-04 18:03:45 +00001978 fprintf(err,
1979 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001980 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001981 }
1982 errcnt++;
1983 }
1984 break;
1985 case OPT_INT:
1986 case OPT_FINT:
1987 lv = strtol(cp,&end,0);
1988 if( *end ){
1989 if( err ){
1990 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001991 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001992 }
1993 errcnt++;
1994 }
1995 break;
1996 case OPT_STR:
1997 case OPT_FSTR:
1998 sv = cp;
1999 break;
2000 }
2001 switch( op[j].type ){
2002 case OPT_FLAG:
2003 case OPT_FFLAG:
2004 break;
2005 case OPT_DBL:
2006 *(double*)(op[j].arg) = dv;
2007 break;
2008 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002009 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002010 break;
2011 case OPT_INT:
2012 *(int*)(op[j].arg) = lv;
2013 break;
2014 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002015 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002016 break;
2017 case OPT_STR:
2018 *(char**)(op[j].arg) = sv;
2019 break;
2020 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002021 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002022 break;
2023 }
2024 }
2025 return errcnt;
2026}
2027
icculus9e44cf12010-02-14 17:14:22 +00002028int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002029{
2030 int errcnt = 0;
2031 argv = a;
2032 op = o;
2033 errstream = err;
2034 if( argv && *argv && op ){
2035 int i;
2036 for(i=1; argv[i]; i++){
2037 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2038 errcnt += handleflags(i,err);
2039 }else if( strchr(argv[i],'=') ){
2040 errcnt += handleswitch(i,err);
2041 }
2042 }
2043 }
2044 if( errcnt>0 ){
2045 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002046 OptPrint();
drh75897232000-05-29 14:26:00 +00002047 exit(1);
2048 }
2049 return 0;
2050}
2051
drhb0c86772000-06-02 23:21:26 +00002052int OptNArgs(){
drh75897232000-05-29 14:26:00 +00002053 int cnt = 0;
2054 int dashdash = 0;
2055 int i;
2056 if( argv!=0 && argv[0]!=0 ){
2057 for(i=1; argv[i]; i++){
2058 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2059 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2060 }
2061 }
2062 return cnt;
2063}
2064
icculus9e44cf12010-02-14 17:14:22 +00002065char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002066{
2067 int i;
2068 i = argindex(n);
2069 return i>=0 ? argv[i] : 0;
2070}
2071
icculus9e44cf12010-02-14 17:14:22 +00002072void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002073{
2074 int i;
2075 i = argindex(n);
2076 if( i>=0 ) errline(i,0,errstream);
2077}
2078
drhb0c86772000-06-02 23:21:26 +00002079void OptPrint(){
drh75897232000-05-29 14:26:00 +00002080 int i;
2081 int max, len;
2082 max = 0;
2083 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002084 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002085 switch( op[i].type ){
2086 case OPT_FLAG:
2087 case OPT_FFLAG:
2088 break;
2089 case OPT_INT:
2090 case OPT_FINT:
2091 len += 9; /* length of "<integer>" */
2092 break;
2093 case OPT_DBL:
2094 case OPT_FDBL:
2095 len += 6; /* length of "<real>" */
2096 break;
2097 case OPT_STR:
2098 case OPT_FSTR:
2099 len += 8; /* length of "<string>" */
2100 break;
2101 }
2102 if( len>max ) max = len;
2103 }
2104 for(i=0; op[i].label; i++){
2105 switch( op[i].type ){
2106 case OPT_FLAG:
2107 case OPT_FFLAG:
2108 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2109 break;
2110 case OPT_INT:
2111 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002112 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002113 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002114 break;
2115 case OPT_DBL:
2116 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002117 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002118 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002119 break;
2120 case OPT_STR:
2121 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002122 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002123 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002124 break;
2125 }
2126 }
2127}
2128/*********************** From the file "parse.c" ****************************/
2129/*
2130** Input file parser for the LEMON parser generator.
2131*/
2132
2133/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002134enum e_state {
2135 INITIALIZE,
2136 WAITING_FOR_DECL_OR_RULE,
2137 WAITING_FOR_DECL_KEYWORD,
2138 WAITING_FOR_DECL_ARG,
2139 WAITING_FOR_PRECEDENCE_SYMBOL,
2140 WAITING_FOR_ARROW,
2141 IN_RHS,
2142 LHS_ALIAS_1,
2143 LHS_ALIAS_2,
2144 LHS_ALIAS_3,
2145 RHS_ALIAS_1,
2146 RHS_ALIAS_2,
2147 PRECEDENCE_MARK_1,
2148 PRECEDENCE_MARK_2,
2149 RESYNC_AFTER_RULE_ERROR,
2150 RESYNC_AFTER_DECL_ERROR,
2151 WAITING_FOR_DESTRUCTOR_SYMBOL,
2152 WAITING_FOR_DATATYPE_SYMBOL,
2153 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002154 WAITING_FOR_WILDCARD_ID,
2155 WAITING_FOR_CLASS_ID,
2156 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002157};
drh75897232000-05-29 14:26:00 +00002158struct pstate {
2159 char *filename; /* Name of the input file */
2160 int tokenlineno; /* Linenumber at which current token starts */
2161 int errorcnt; /* Number of errors so far */
2162 char *tokenstart; /* Text of current token */
2163 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002164 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002165 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002166 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002167 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002168 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002169 int nrhs; /* Number of right-hand side symbols seen */
2170 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002171 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002172 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002173 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002174 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002175 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002176 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002177 enum e_assoc declassoc; /* Assign this association to decl arguments */
2178 int preccounter; /* Assign this precedence to decl arguments */
2179 struct rule *firstrule; /* Pointer to first rule in the grammar */
2180 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2181};
2182
2183/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002184static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002185{
icculus9e44cf12010-02-14 17:14:22 +00002186 const char *x;
drh75897232000-05-29 14:26:00 +00002187 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2188#if 0
2189 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2190 x,psp->state);
2191#endif
2192 switch( psp->state ){
2193 case INITIALIZE:
2194 psp->prevrule = 0;
2195 psp->preccounter = 0;
2196 psp->firstrule = psp->lastrule = 0;
2197 psp->gp->nrule = 0;
2198 /* Fall thru to next case */
2199 case WAITING_FOR_DECL_OR_RULE:
2200 if( x[0]=='%' ){
2201 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002202 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002203 psp->lhs = Symbol_new(x);
2204 psp->nrhs = 0;
2205 psp->lhsalias = 0;
2206 psp->state = WAITING_FOR_ARROW;
2207 }else if( x[0]=='{' ){
2208 if( psp->prevrule==0 ){
2209 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002210"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002211fragment which begins on this line.");
2212 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002213 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002214 ErrorMsg(psp->filename,psp->tokenlineno,
2215"Code fragment beginning on this line is not the first \
2216to follow the previous rule.");
2217 psp->errorcnt++;
2218 }else{
2219 psp->prevrule->line = psp->tokenlineno;
2220 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002221 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002222 }
drh75897232000-05-29 14:26:00 +00002223 }else if( x[0]=='[' ){
2224 psp->state = PRECEDENCE_MARK_1;
2225 }else{
2226 ErrorMsg(psp->filename,psp->tokenlineno,
2227 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2228 x);
2229 psp->errorcnt++;
2230 }
2231 break;
2232 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002233 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002234 ErrorMsg(psp->filename,psp->tokenlineno,
2235 "The precedence symbol must be a terminal.");
2236 psp->errorcnt++;
2237 }else if( psp->prevrule==0 ){
2238 ErrorMsg(psp->filename,psp->tokenlineno,
2239 "There is no prior rule to assign precedence \"[%s]\".",x);
2240 psp->errorcnt++;
2241 }else if( psp->prevrule->precsym!=0 ){
2242 ErrorMsg(psp->filename,psp->tokenlineno,
2243"Precedence mark on this line is not the first \
2244to follow the previous rule.");
2245 psp->errorcnt++;
2246 }else{
2247 psp->prevrule->precsym = Symbol_new(x);
2248 }
2249 psp->state = PRECEDENCE_MARK_2;
2250 break;
2251 case PRECEDENCE_MARK_2:
2252 if( x[0]!=']' ){
2253 ErrorMsg(psp->filename,psp->tokenlineno,
2254 "Missing \"]\" on precedence mark.");
2255 psp->errorcnt++;
2256 }
2257 psp->state = WAITING_FOR_DECL_OR_RULE;
2258 break;
2259 case WAITING_FOR_ARROW:
2260 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2261 psp->state = IN_RHS;
2262 }else if( x[0]=='(' ){
2263 psp->state = LHS_ALIAS_1;
2264 }else{
2265 ErrorMsg(psp->filename,psp->tokenlineno,
2266 "Expected to see a \":\" following the LHS symbol \"%s\".",
2267 psp->lhs->name);
2268 psp->errorcnt++;
2269 psp->state = RESYNC_AFTER_RULE_ERROR;
2270 }
2271 break;
2272 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002273 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002274 psp->lhsalias = x;
2275 psp->state = LHS_ALIAS_2;
2276 }else{
2277 ErrorMsg(psp->filename,psp->tokenlineno,
2278 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2279 x,psp->lhs->name);
2280 psp->errorcnt++;
2281 psp->state = RESYNC_AFTER_RULE_ERROR;
2282 }
2283 break;
2284 case LHS_ALIAS_2:
2285 if( x[0]==')' ){
2286 psp->state = LHS_ALIAS_3;
2287 }else{
2288 ErrorMsg(psp->filename,psp->tokenlineno,
2289 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2290 psp->errorcnt++;
2291 psp->state = RESYNC_AFTER_RULE_ERROR;
2292 }
2293 break;
2294 case LHS_ALIAS_3:
2295 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2296 psp->state = IN_RHS;
2297 }else{
2298 ErrorMsg(psp->filename,psp->tokenlineno,
2299 "Missing \"->\" following: \"%s(%s)\".",
2300 psp->lhs->name,psp->lhsalias);
2301 psp->errorcnt++;
2302 psp->state = RESYNC_AFTER_RULE_ERROR;
2303 }
2304 break;
2305 case IN_RHS:
2306 if( x[0]=='.' ){
2307 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002308 rp = (struct rule *)calloc( sizeof(struct rule) +
2309 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002310 if( rp==0 ){
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "Can't allocate enough memory for this rule.");
2313 psp->errorcnt++;
2314 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002315 }else{
drh75897232000-05-29 14:26:00 +00002316 int i;
2317 rp->ruleline = psp->tokenlineno;
2318 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002319 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002320 for(i=0; i<psp->nrhs; i++){
2321 rp->rhs[i] = psp->rhs[i];
2322 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002323 }
drh75897232000-05-29 14:26:00 +00002324 rp->lhs = psp->lhs;
2325 rp->lhsalias = psp->lhsalias;
2326 rp->nrhs = psp->nrhs;
2327 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002328 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002329 rp->precsym = 0;
2330 rp->index = psp->gp->nrule++;
2331 rp->nextlhs = rp->lhs->rule;
2332 rp->lhs->rule = rp;
2333 rp->next = 0;
2334 if( psp->firstrule==0 ){
2335 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002336 }else{
drh75897232000-05-29 14:26:00 +00002337 psp->lastrule->next = rp;
2338 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002339 }
drh75897232000-05-29 14:26:00 +00002340 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002341 }
drh75897232000-05-29 14:26:00 +00002342 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002343 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002344 if( psp->nrhs>=MAXRHS ){
2345 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002346 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002347 x);
2348 psp->errorcnt++;
2349 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002350 }else{
drh75897232000-05-29 14:26:00 +00002351 psp->rhs[psp->nrhs] = Symbol_new(x);
2352 psp->alias[psp->nrhs] = 0;
2353 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002354 }
drhfd405312005-11-06 04:06:59 +00002355 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2356 struct symbol *msp = psp->rhs[psp->nrhs-1];
2357 if( msp->type!=MULTITERMINAL ){
2358 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002359 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002360 memset(msp, 0, sizeof(*msp));
2361 msp->type = MULTITERMINAL;
2362 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002363 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002364 msp->subsym[0] = origsp;
2365 msp->name = origsp->name;
2366 psp->rhs[psp->nrhs-1] = msp;
2367 }
2368 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002369 msp->subsym = (struct symbol **) realloc(msp->subsym,
2370 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002371 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002372 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002373 ErrorMsg(psp->filename,psp->tokenlineno,
2374 "Cannot form a compound containing a non-terminal");
2375 psp->errorcnt++;
2376 }
drh75897232000-05-29 14:26:00 +00002377 }else if( x[0]=='(' && psp->nrhs>0 ){
2378 psp->state = RHS_ALIAS_1;
2379 }else{
2380 ErrorMsg(psp->filename,psp->tokenlineno,
2381 "Illegal character on RHS of rule: \"%s\".",x);
2382 psp->errorcnt++;
2383 psp->state = RESYNC_AFTER_RULE_ERROR;
2384 }
2385 break;
2386 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002387 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002388 psp->alias[psp->nrhs-1] = x;
2389 psp->state = RHS_ALIAS_2;
2390 }else{
2391 ErrorMsg(psp->filename,psp->tokenlineno,
2392 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2393 x,psp->rhs[psp->nrhs-1]->name);
2394 psp->errorcnt++;
2395 psp->state = RESYNC_AFTER_RULE_ERROR;
2396 }
2397 break;
2398 case RHS_ALIAS_2:
2399 if( x[0]==')' ){
2400 psp->state = IN_RHS;
2401 }else{
2402 ErrorMsg(psp->filename,psp->tokenlineno,
2403 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2404 psp->errorcnt++;
2405 psp->state = RESYNC_AFTER_RULE_ERROR;
2406 }
2407 break;
2408 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002409 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002410 psp->declkeyword = x;
2411 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002412 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002413 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002414 psp->state = WAITING_FOR_DECL_ARG;
2415 if( strcmp(x,"name")==0 ){
2416 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002417 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002418 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002419 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002420 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002421 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002422 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002423 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002424 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002425 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002426 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002427 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002428 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002429 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002430 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002431 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002432 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002433 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002434 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002435 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002436 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002437 }else if( strcmp(x,"extra_argument")==0 ){
2438 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002439 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002440 }else if( strcmp(x,"token_type")==0 ){
2441 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002442 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002443 }else if( strcmp(x,"default_type")==0 ){
2444 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002445 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002446 }else if( strcmp(x,"stack_size")==0 ){
2447 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002448 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002449 }else if( strcmp(x,"start_symbol")==0 ){
2450 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002451 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002452 }else if( strcmp(x,"left")==0 ){
2453 psp->preccounter++;
2454 psp->declassoc = LEFT;
2455 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2456 }else if( strcmp(x,"right")==0 ){
2457 psp->preccounter++;
2458 psp->declassoc = RIGHT;
2459 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2460 }else if( strcmp(x,"nonassoc")==0 ){
2461 psp->preccounter++;
2462 psp->declassoc = NONE;
2463 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002464 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002465 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002466 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002467 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002468 }else if( strcmp(x,"fallback")==0 ){
2469 psp->fallback = 0;
2470 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002471 }else if( strcmp(x,"wildcard")==0 ){
2472 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002473 }else if( strcmp(x,"token_class")==0 ){
2474 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002475 }else{
2476 ErrorMsg(psp->filename,psp->tokenlineno,
2477 "Unknown declaration keyword: \"%%%s\".",x);
2478 psp->errorcnt++;
2479 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002480 }
drh75897232000-05-29 14:26:00 +00002481 }else{
2482 ErrorMsg(psp->filename,psp->tokenlineno,
2483 "Illegal declaration keyword: \"%s\".",x);
2484 psp->errorcnt++;
2485 psp->state = RESYNC_AFTER_DECL_ERROR;
2486 }
2487 break;
2488 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002489 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002490 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002491 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002492 psp->errorcnt++;
2493 psp->state = RESYNC_AFTER_DECL_ERROR;
2494 }else{
icculusd286fa62010-03-03 17:06:32 +00002495 struct symbol *sp = Symbol_new(x);
2496 psp->declargslot = &sp->destructor;
2497 psp->decllinenoslot = &sp->destLineno;
2498 psp->insertLineMacro = 1;
2499 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002500 }
2501 break;
2502 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002503 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002504 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002505 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002506 psp->errorcnt++;
2507 psp->state = RESYNC_AFTER_DECL_ERROR;
2508 }else{
icculus866bf1e2010-02-17 20:31:32 +00002509 struct symbol *sp = Symbol_find(x);
2510 if((sp) && (sp->datatype)){
2511 ErrorMsg(psp->filename,psp->tokenlineno,
2512 "Symbol %%type \"%s\" already defined", x);
2513 psp->errorcnt++;
2514 psp->state = RESYNC_AFTER_DECL_ERROR;
2515 }else{
2516 if (!sp){
2517 sp = Symbol_new(x);
2518 }
2519 psp->declargslot = &sp->datatype;
2520 psp->insertLineMacro = 0;
2521 psp->state = WAITING_FOR_DECL_ARG;
2522 }
drh75897232000-05-29 14:26:00 +00002523 }
2524 break;
2525 case WAITING_FOR_PRECEDENCE_SYMBOL:
2526 if( x[0]=='.' ){
2527 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002528 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002529 struct symbol *sp;
2530 sp = Symbol_new(x);
2531 if( sp->prec>=0 ){
2532 ErrorMsg(psp->filename,psp->tokenlineno,
2533 "Symbol \"%s\" has already be given a precedence.",x);
2534 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002535 }else{
drh75897232000-05-29 14:26:00 +00002536 sp->prec = psp->preccounter;
2537 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002538 }
drh75897232000-05-29 14:26:00 +00002539 }else{
2540 ErrorMsg(psp->filename,psp->tokenlineno,
2541 "Can't assign a precedence to \"%s\".",x);
2542 psp->errorcnt++;
2543 }
2544 break;
2545 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002546 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002547 const char *zOld, *zNew;
2548 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002549 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002550 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002551 char zLine[50];
2552 zNew = x;
2553 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002554 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002555 if( *psp->declargslot ){
2556 zOld = *psp->declargslot;
2557 }else{
2558 zOld = "";
2559 }
drh87cf1372008-08-13 20:09:06 +00002560 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002561 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002562 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002563 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2564 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002565 for(z=psp->filename, nBack=0; *z; z++){
2566 if( *z=='\\' ) nBack++;
2567 }
drh898799f2014-01-10 23:21:00 +00002568 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002569 nLine = lemonStrlen(zLine);
2570 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002571 }
icculus9e44cf12010-02-14 17:14:22 +00002572 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2573 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002574 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002575 if( nOld && zBuf[-1]!='\n' ){
2576 *(zBuf++) = '\n';
2577 }
2578 memcpy(zBuf, zLine, nLine);
2579 zBuf += nLine;
2580 *(zBuf++) = '"';
2581 for(z=psp->filename; *z; z++){
2582 if( *z=='\\' ){
2583 *(zBuf++) = '\\';
2584 }
2585 *(zBuf++) = *z;
2586 }
2587 *(zBuf++) = '"';
2588 *(zBuf++) = '\n';
2589 }
drh4dc8ef52008-07-01 17:13:57 +00002590 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2591 psp->decllinenoslot[0] = psp->tokenlineno;
2592 }
drha5808f32008-04-27 22:19:44 +00002593 memcpy(zBuf, zNew, nNew);
2594 zBuf += nNew;
2595 *zBuf = 0;
2596 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002597 }else{
2598 ErrorMsg(psp->filename,psp->tokenlineno,
2599 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2600 psp->errorcnt++;
2601 psp->state = RESYNC_AFTER_DECL_ERROR;
2602 }
2603 break;
drh0bd1f4e2002-06-06 18:54:39 +00002604 case WAITING_FOR_FALLBACK_ID:
2605 if( x[0]=='.' ){
2606 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002607 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002608 ErrorMsg(psp->filename, psp->tokenlineno,
2609 "%%fallback argument \"%s\" should be a token", x);
2610 psp->errorcnt++;
2611 }else{
2612 struct symbol *sp = Symbol_new(x);
2613 if( psp->fallback==0 ){
2614 psp->fallback = sp;
2615 }else if( sp->fallback ){
2616 ErrorMsg(psp->filename, psp->tokenlineno,
2617 "More than one fallback assigned to token %s", x);
2618 psp->errorcnt++;
2619 }else{
2620 sp->fallback = psp->fallback;
2621 psp->gp->has_fallback = 1;
2622 }
2623 }
2624 break;
drhe09daa92006-06-10 13:29:31 +00002625 case WAITING_FOR_WILDCARD_ID:
2626 if( x[0]=='.' ){
2627 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002628 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002629 ErrorMsg(psp->filename, psp->tokenlineno,
2630 "%%wildcard argument \"%s\" should be a token", x);
2631 psp->errorcnt++;
2632 }else{
2633 struct symbol *sp = Symbol_new(x);
2634 if( psp->gp->wildcard==0 ){
2635 psp->gp->wildcard = sp;
2636 }else{
2637 ErrorMsg(psp->filename, psp->tokenlineno,
2638 "Extra wildcard to token: %s", x);
2639 psp->errorcnt++;
2640 }
2641 }
2642 break;
drh61f92cd2014-01-11 03:06:18 +00002643 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002644 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002645 ErrorMsg(psp->filename, psp->tokenlineno,
2646 "%%token_class must be followed by an identifier: ", x);
2647 psp->errorcnt++;
2648 psp->state = RESYNC_AFTER_DECL_ERROR;
2649 }else if( Symbol_find(x) ){
2650 ErrorMsg(psp->filename, psp->tokenlineno,
2651 "Symbol \"%s\" already used", x);
2652 psp->errorcnt++;
2653 psp->state = RESYNC_AFTER_DECL_ERROR;
2654 }else{
2655 psp->tkclass = Symbol_new(x);
2656 psp->tkclass->type = MULTITERMINAL;
2657 psp->state = WAITING_FOR_CLASS_TOKEN;
2658 }
2659 break;
2660 case WAITING_FOR_CLASS_TOKEN:
2661 if( x[0]=='.' ){
2662 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002663 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002664 struct symbol *msp = psp->tkclass;
2665 msp->nsubsym++;
2666 msp->subsym = (struct symbol **) realloc(msp->subsym,
2667 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002668 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002669 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2670 }else{
2671 ErrorMsg(psp->filename, psp->tokenlineno,
2672 "%%token_class argument \"%s\" should be a token", x);
2673 psp->errorcnt++;
2674 psp->state = RESYNC_AFTER_DECL_ERROR;
2675 }
2676 break;
drh75897232000-05-29 14:26:00 +00002677 case RESYNC_AFTER_RULE_ERROR:
2678/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2679** break; */
2680 case RESYNC_AFTER_DECL_ERROR:
2681 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2682 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2683 break;
2684 }
2685}
2686
drh34ff57b2008-07-14 12:27:51 +00002687/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002688** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2689** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2690** comments them out. Text in between is also commented out as appropriate.
2691*/
danielk1977940fac92005-01-23 22:41:37 +00002692static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002693 int i, j, k, n;
2694 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002695 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002696 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002697 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002698 for(i=0; z[i]; i++){
2699 if( z[i]=='\n' ) lineno++;
2700 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002701 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002702 if( exclude ){
2703 exclude--;
2704 if( exclude==0 ){
2705 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2706 }
2707 }
2708 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002709 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2710 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002711 if( exclude ){
2712 exclude++;
2713 }else{
drhc56fac72015-10-29 13:48:15 +00002714 for(j=i+7; ISSPACE(z[j]); j++){}
2715 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002716 exclude = 1;
2717 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002718 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002719 exclude = 0;
2720 break;
2721 }
2722 }
2723 if( z[i+3]=='n' ) exclude = !exclude;
2724 if( exclude ){
2725 start = i;
2726 start_lineno = lineno;
2727 }
2728 }
2729 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2730 }
2731 }
2732 if( exclude ){
2733 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2734 exit(1);
2735 }
2736}
2737
drh75897232000-05-29 14:26:00 +00002738/* In spite of its name, this function is really a scanner. It read
2739** in the entire input file (all at once) then tokenizes it. Each
2740** token is passed to the function "parseonetoken" which builds all
2741** the appropriate data structures in the global state vector "gp".
2742*/
icculus9e44cf12010-02-14 17:14:22 +00002743void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002744{
2745 struct pstate ps;
2746 FILE *fp;
2747 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002748 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002749 int lineno;
2750 int c;
2751 char *cp, *nextcp;
2752 int startline = 0;
2753
rse38514a92007-09-20 11:34:17 +00002754 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002755 ps.gp = gp;
2756 ps.filename = gp->filename;
2757 ps.errorcnt = 0;
2758 ps.state = INITIALIZE;
2759
2760 /* Begin by reading the input file */
2761 fp = fopen(ps.filename,"rb");
2762 if( fp==0 ){
2763 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2764 gp->errorcnt++;
2765 return;
2766 }
2767 fseek(fp,0,2);
2768 filesize = ftell(fp);
2769 rewind(fp);
2770 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002771 if( filesize>100000000 || filebuf==0 ){
2772 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002773 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002774 fclose(fp);
drh75897232000-05-29 14:26:00 +00002775 return;
2776 }
2777 if( fread(filebuf,1,filesize,fp)!=filesize ){
2778 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2779 filesize);
2780 free(filebuf);
2781 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002782 fclose(fp);
drh75897232000-05-29 14:26:00 +00002783 return;
2784 }
2785 fclose(fp);
2786 filebuf[filesize] = 0;
2787
drh6d08b4d2004-07-20 12:45:22 +00002788 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2789 preprocess_input(filebuf);
2790
drh75897232000-05-29 14:26:00 +00002791 /* Now scan the text of the input file */
2792 lineno = 1;
2793 for(cp=filebuf; (c= *cp)!=0; ){
2794 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002795 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002796 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2797 cp+=2;
2798 while( (c= *cp)!=0 && c!='\n' ) cp++;
2799 continue;
2800 }
2801 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2802 cp+=2;
2803 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2804 if( c=='\n' ) lineno++;
2805 cp++;
2806 }
2807 if( c ) cp++;
2808 continue;
2809 }
2810 ps.tokenstart = cp; /* Mark the beginning of the token */
2811 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2812 if( c=='\"' ){ /* String literals */
2813 cp++;
2814 while( (c= *cp)!=0 && c!='\"' ){
2815 if( c=='\n' ) lineno++;
2816 cp++;
2817 }
2818 if( c==0 ){
2819 ErrorMsg(ps.filename,startline,
2820"String starting on this line is not terminated before the end of the file.");
2821 ps.errorcnt++;
2822 nextcp = cp;
2823 }else{
2824 nextcp = cp+1;
2825 }
2826 }else if( c=='{' ){ /* A block of C code */
2827 int level;
2828 cp++;
2829 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2830 if( c=='\n' ) lineno++;
2831 else if( c=='{' ) level++;
2832 else if( c=='}' ) level--;
2833 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2834 int prevc;
2835 cp = &cp[2];
2836 prevc = 0;
2837 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2838 if( c=='\n' ) lineno++;
2839 prevc = c;
2840 cp++;
drhf2f105d2012-08-20 15:53:54 +00002841 }
2842 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002843 cp = &cp[2];
2844 while( (c= *cp)!=0 && c!='\n' ) cp++;
2845 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002846 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002847 int startchar, prevc;
2848 startchar = c;
2849 prevc = 0;
2850 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2851 if( c=='\n' ) lineno++;
2852 if( prevc=='\\' ) prevc = 0;
2853 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002854 }
2855 }
drh75897232000-05-29 14:26:00 +00002856 }
2857 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002858 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002859"C code starting on this line is not terminated before the end of the file.");
2860 ps.errorcnt++;
2861 nextcp = cp;
2862 }else{
2863 nextcp = cp+1;
2864 }
drhc56fac72015-10-29 13:48:15 +00002865 }else if( ISALNUM(c) ){ /* Identifiers */
2866 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002867 nextcp = cp;
2868 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2869 cp += 3;
2870 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002871 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002872 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002873 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002874 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002875 }else{ /* All other (one character) operators */
2876 cp++;
2877 nextcp = cp;
2878 }
2879 c = *cp;
2880 *cp = 0; /* Null terminate the token */
2881 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002882 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002883 cp = nextcp;
2884 }
2885 free(filebuf); /* Release the buffer after parsing */
2886 gp->rule = ps.firstrule;
2887 gp->errorcnt = ps.errorcnt;
2888}
2889/*************************** From the file "plink.c" *********************/
2890/*
2891** Routines processing configuration follow-set propagation links
2892** in the LEMON parser generator.
2893*/
2894static struct plink *plink_freelist = 0;
2895
2896/* Allocate a new plink */
2897struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002898 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002899
2900 if( plink_freelist==0 ){
2901 int i;
2902 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002903 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002904 if( plink_freelist==0 ){
2905 fprintf(stderr,
2906 "Unable to allocate memory for a new follow-set propagation link.\n");
2907 exit(1);
2908 }
2909 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2910 plink_freelist[amt-1].next = 0;
2911 }
icculus9e44cf12010-02-14 17:14:22 +00002912 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002913 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002914 return newlink;
drh75897232000-05-29 14:26:00 +00002915}
2916
2917/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002918void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002919{
icculus9e44cf12010-02-14 17:14:22 +00002920 struct plink *newlink;
2921 newlink = Plink_new();
2922 newlink->next = *plpp;
2923 *plpp = newlink;
2924 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002925}
2926
2927/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002928void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002929{
2930 struct plink *nextpl;
2931 while( from ){
2932 nextpl = from->next;
2933 from->next = *to;
2934 *to = from;
2935 from = nextpl;
2936 }
2937}
2938
2939/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002940void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002941{
2942 struct plink *nextpl;
2943
2944 while( plp ){
2945 nextpl = plp->next;
2946 plp->next = plink_freelist;
2947 plink_freelist = plp;
2948 plp = nextpl;
2949 }
2950}
2951/*********************** From the file "report.c" **************************/
2952/*
2953** Procedures for generating reports and tables in the LEMON parser generator.
2954*/
2955
2956/* Generate a filename with the given suffix. Space to hold the
2957** name comes from malloc() and must be freed by the calling
2958** function.
2959*/
icculus9e44cf12010-02-14 17:14:22 +00002960PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002961{
2962 char *name;
2963 char *cp;
2964
icculus9e44cf12010-02-14 17:14:22 +00002965 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002966 if( name==0 ){
2967 fprintf(stderr,"Can't allocate space for a filename.\n");
2968 exit(1);
2969 }
drh898799f2014-01-10 23:21:00 +00002970 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002971 cp = strrchr(name,'.');
2972 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002973 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002974 return name;
2975}
2976
2977/* Open a file with a name based on the name of the input file,
2978** but with a different (specified) suffix, and return a pointer
2979** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002980PRIVATE FILE *file_open(
2981 struct lemon *lemp,
2982 const char *suffix,
2983 const char *mode
2984){
drh75897232000-05-29 14:26:00 +00002985 FILE *fp;
2986
2987 if( lemp->outname ) free(lemp->outname);
2988 lemp->outname = file_makename(lemp, suffix);
2989 fp = fopen(lemp->outname,mode);
2990 if( fp==0 && *mode=='w' ){
2991 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2992 lemp->errorcnt++;
2993 return 0;
2994 }
2995 return fp;
2996}
2997
2998/* Duplicate the input file without comments and without actions
2999** on rules */
icculus9e44cf12010-02-14 17:14:22 +00003000void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003001{
3002 struct rule *rp;
3003 struct symbol *sp;
3004 int i, j, maxlen, len, ncolumns, skip;
3005 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3006 maxlen = 10;
3007 for(i=0; i<lemp->nsymbol; i++){
3008 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003009 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003010 if( len>maxlen ) maxlen = len;
3011 }
3012 ncolumns = 76/(maxlen+5);
3013 if( ncolumns<1 ) ncolumns = 1;
3014 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3015 for(i=0; i<skip; i++){
3016 printf("//");
3017 for(j=i; j<lemp->nsymbol; j+=skip){
3018 sp = lemp->symbols[j];
3019 assert( sp->index==j );
3020 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3021 }
3022 printf("\n");
3023 }
3024 for(rp=lemp->rule; rp; rp=rp->next){
3025 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00003026 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00003027 printf(" ::=");
3028 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00003029 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003030 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003031 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003032 for(j=1; j<sp->nsubsym; j++){
3033 printf("|%s", sp->subsym[j]->name);
3034 }
drh61f92cd2014-01-11 03:06:18 +00003035 }else{
3036 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003037 }
3038 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00003039 }
3040 printf(".");
3041 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003042 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003043 printf("\n");
3044 }
3045}
3046
drh7e698e92015-09-07 14:22:24 +00003047/* Print a single rule.
3048*/
3049void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003050 struct symbol *sp;
3051 int i, j;
drh75897232000-05-29 14:26:00 +00003052 fprintf(fp,"%s ::=",rp->lhs->name);
3053 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003054 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003055 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003056 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003057 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003058 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003059 for(j=1; j<sp->nsubsym; j++){
3060 fprintf(fp,"|%s",sp->subsym[j]->name);
3061 }
drh61f92cd2014-01-11 03:06:18 +00003062 }else{
3063 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003064 }
drh75897232000-05-29 14:26:00 +00003065 }
3066}
3067
drh7e698e92015-09-07 14:22:24 +00003068/* Print the rule for a configuration.
3069*/
3070void ConfigPrint(FILE *fp, struct config *cfp){
3071 RulePrint(fp, cfp->rp, cfp->dot);
3072}
3073
drh75897232000-05-29 14:26:00 +00003074/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003075#if 0
drh75897232000-05-29 14:26:00 +00003076/* Print a set */
3077PRIVATE void SetPrint(out,set,lemp)
3078FILE *out;
3079char *set;
3080struct lemon *lemp;
3081{
3082 int i;
3083 char *spacer;
3084 spacer = "";
3085 fprintf(out,"%12s[","");
3086 for(i=0; i<lemp->nterminal; i++){
3087 if( SetFind(set,i) ){
3088 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3089 spacer = " ";
3090 }
3091 }
3092 fprintf(out,"]\n");
3093}
3094
3095/* Print a plink chain */
3096PRIVATE void PlinkPrint(out,plp,tag)
3097FILE *out;
3098struct plink *plp;
3099char *tag;
3100{
3101 while( plp ){
drhada354d2005-11-05 15:03:59 +00003102 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003103 ConfigPrint(out,plp->cfp);
3104 fprintf(out,"\n");
3105 plp = plp->next;
3106 }
3107}
3108#endif
3109
3110/* Print an action to the given file descriptor. Return FALSE if
3111** nothing was actually printed.
3112*/
drh7e698e92015-09-07 14:22:24 +00003113int PrintAction(
3114 struct action *ap, /* The action to print */
3115 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003116 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003117){
drh75897232000-05-29 14:26:00 +00003118 int result = 1;
3119 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003120 case SHIFT: {
3121 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003122 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003123 break;
drh7e698e92015-09-07 14:22:24 +00003124 }
3125 case REDUCE: {
3126 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003127 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003128 RulePrint(fp, rp, -1);
3129 break;
3130 }
3131 case SHIFTREDUCE: {
3132 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003133 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003134 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003135 break;
drh7e698e92015-09-07 14:22:24 +00003136 }
drh75897232000-05-29 14:26:00 +00003137 case ACCEPT:
3138 fprintf(fp,"%*s accept",indent,ap->sp->name);
3139 break;
3140 case ERROR:
3141 fprintf(fp,"%*s error",indent,ap->sp->name);
3142 break;
drh9892c5d2007-12-21 00:02:11 +00003143 case SRCONFLICT:
3144 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003145 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003146 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003147 break;
drh9892c5d2007-12-21 00:02:11 +00003148 case SSCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003149 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003150 indent,ap->sp->name,ap->x.stp->statenum);
3151 break;
drh75897232000-05-29 14:26:00 +00003152 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003153 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003154 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003155 indent,ap->sp->name,ap->x.stp->statenum);
3156 }else{
3157 result = 0;
3158 }
3159 break;
drh75897232000-05-29 14:26:00 +00003160 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003161 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003162 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003163 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003164 }else{
3165 result = 0;
3166 }
3167 break;
drh75897232000-05-29 14:26:00 +00003168 case NOT_USED:
3169 result = 0;
3170 break;
3171 }
drhc173ad82016-05-23 16:15:02 +00003172 if( result && ap->spOpt ){
3173 fprintf(fp," /* because %s==%s */", ap->sp->name, ap->spOpt->name);
3174 }
drh75897232000-05-29 14:26:00 +00003175 return result;
3176}
3177
drh3bd48ab2015-09-07 18:23:37 +00003178/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003179void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003180{
3181 int i;
3182 struct state *stp;
3183 struct config *cfp;
3184 struct action *ap;
3185 FILE *fp;
3186
drh2aa6ca42004-09-10 00:14:04 +00003187 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003188 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003189 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003190 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003191 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003192 if( lemp->basisflag ) cfp=stp->bp;
3193 else cfp=stp->cfp;
3194 while( cfp ){
3195 char buf[20];
3196 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003197 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003198 fprintf(fp," %5s ",buf);
3199 }else{
3200 fprintf(fp," ");
3201 }
3202 ConfigPrint(fp,cfp);
3203 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003204#if 0
drh75897232000-05-29 14:26:00 +00003205 SetPrint(fp,cfp->fws,lemp);
3206 PlinkPrint(fp,cfp->fplp,"To ");
3207 PlinkPrint(fp,cfp->bplp,"From");
3208#endif
3209 if( lemp->basisflag ) cfp=cfp->bp;
3210 else cfp=cfp->next;
3211 }
3212 fprintf(fp,"\n");
3213 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003214 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003215 }
3216 fprintf(fp,"\n");
3217 }
drhe9278182007-07-18 18:16:29 +00003218 fprintf(fp, "----------------------------------------------------\n");
3219 fprintf(fp, "Symbols:\n");
3220 for(i=0; i<lemp->nsymbol; i++){
3221 int j;
3222 struct symbol *sp;
3223
3224 sp = lemp->symbols[i];
3225 fprintf(fp, " %3d: %s", i, sp->name);
3226 if( sp->type==NONTERMINAL ){
3227 fprintf(fp, ":");
3228 if( sp->lambda ){
3229 fprintf(fp, " <lambda>");
3230 }
3231 for(j=0; j<lemp->nterminal; j++){
3232 if( sp->firstset && SetFind(sp->firstset, j) ){
3233 fprintf(fp, " %s", lemp->symbols[j]->name);
3234 }
3235 }
3236 }
3237 fprintf(fp, "\n");
3238 }
drh75897232000-05-29 14:26:00 +00003239 fclose(fp);
3240 return;
3241}
3242
3243/* Search for the file "name" which is in the same directory as
3244** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003245PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003246{
icculus9e44cf12010-02-14 17:14:22 +00003247 const char *pathlist;
3248 char *pathbufptr;
3249 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003250 char *path,*cp;
3251 char c;
drh75897232000-05-29 14:26:00 +00003252
3253#ifdef __WIN32__
3254 cp = strrchr(argv0,'\\');
3255#else
3256 cp = strrchr(argv0,'/');
3257#endif
3258 if( cp ){
3259 c = *cp;
3260 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003261 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003262 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003263 *cp = c;
3264 }else{
drh75897232000-05-29 14:26:00 +00003265 pathlist = getenv("PATH");
3266 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003267 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003268 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003269 if( (pathbuf != 0) && (path!=0) ){
3270 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003271 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003272 while( *pathbuf ){
3273 cp = strchr(pathbuf,':');
3274 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003275 c = *cp;
3276 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003277 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003278 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003279 if( c==0 ) pathbuf[0] = 0;
3280 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003281 if( access(path,modemask)==0 ) break;
3282 }
icculus9e44cf12010-02-14 17:14:22 +00003283 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003284 }
3285 }
3286 return path;
3287}
3288
3289/* Given an action, compute the integer value for that action
3290** which is to be put in the action table of the generated machine.
3291** Return negative if no action should be generated.
3292*/
icculus9e44cf12010-02-14 17:14:22 +00003293PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003294{
3295 int act;
3296 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003297 case SHIFT: act = ap->x.stp->statenum; break;
drh4ef07702016-03-16 19:45:54 +00003298 case SHIFTREDUCE: act = ap->x.rp->iRule + lemp->nstate; break;
3299 case REDUCE: act = ap->x.rp->iRule + lemp->nstate+lemp->nrule; break;
drh3bd48ab2015-09-07 18:23:37 +00003300 case ERROR: act = lemp->nstate + lemp->nrule*2; break;
3301 case ACCEPT: act = lemp->nstate + lemp->nrule*2 + 1; break;
drh75897232000-05-29 14:26:00 +00003302 default: act = -1; break;
3303 }
3304 return act;
3305}
3306
3307#define LINESIZE 1000
3308/* The next cluster of routines are for reading the template file
3309** and writing the results to the generated parser */
3310/* The first function transfers data from "in" to "out" until
3311** a line is seen which begins with "%%". The line number is
3312** tracked.
3313**
3314** if name!=0, then any word that begin with "Parse" is changed to
3315** begin with *name instead.
3316*/
icculus9e44cf12010-02-14 17:14:22 +00003317PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003318{
3319 int i, iStart;
3320 char line[LINESIZE];
3321 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3322 (*lineno)++;
3323 iStart = 0;
3324 if( name ){
3325 for(i=0; line[i]; i++){
3326 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003327 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003328 ){
3329 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3330 fprintf(out,"%s",name);
3331 i += 4;
3332 iStart = i+1;
3333 }
3334 }
3335 }
3336 fprintf(out,"%s",&line[iStart]);
3337 }
3338}
3339
3340/* The next function finds the template file and opens it, returning
3341** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003342PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003343{
3344 static char templatename[] = "lempar.c";
3345 char buf[1000];
3346 FILE *in;
3347 char *tpltname;
3348 char *cp;
3349
icculus3e143bd2010-02-14 00:48:49 +00003350 /* first, see if user specified a template filename on the command line. */
3351 if (user_templatename != 0) {
3352 if( access(user_templatename,004)==-1 ){
3353 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3354 user_templatename);
3355 lemp->errorcnt++;
3356 return 0;
3357 }
3358 in = fopen(user_templatename,"rb");
3359 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003360 fprintf(stderr,"Can't open the template file \"%s\".\n",
3361 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003362 lemp->errorcnt++;
3363 return 0;
3364 }
3365 return in;
3366 }
3367
drh75897232000-05-29 14:26:00 +00003368 cp = strrchr(lemp->filename,'.');
3369 if( cp ){
drh898799f2014-01-10 23:21:00 +00003370 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003371 }else{
drh898799f2014-01-10 23:21:00 +00003372 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003373 }
3374 if( access(buf,004)==0 ){
3375 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003376 }else if( access(templatename,004)==0 ){
3377 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003378 }else{
3379 tpltname = pathsearch(lemp->argv0,templatename,0);
3380 }
3381 if( tpltname==0 ){
3382 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3383 templatename);
3384 lemp->errorcnt++;
3385 return 0;
3386 }
drh2aa6ca42004-09-10 00:14:04 +00003387 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003388 if( in==0 ){
3389 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3390 lemp->errorcnt++;
3391 return 0;
3392 }
3393 return in;
3394}
3395
drhaf805ca2004-09-07 11:28:25 +00003396/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003397PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003398{
3399 fprintf(out,"#line %d \"",lineno);
3400 while( *filename ){
3401 if( *filename == '\\' ) putc('\\',out);
3402 putc(*filename,out);
3403 filename++;
3404 }
3405 fprintf(out,"\"\n");
3406}
3407
drh75897232000-05-29 14:26:00 +00003408/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003409PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003410{
3411 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003412 while( *str ){
drh75897232000-05-29 14:26:00 +00003413 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003414 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003415 str++;
3416 }
drh9db55df2004-09-09 14:01:21 +00003417 if( str[-1]!='\n' ){
3418 putc('\n',out);
3419 (*lineno)++;
3420 }
shane58543932008-12-10 20:10:04 +00003421 if (!lemp->nolinenosflag) {
3422 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3423 }
drh75897232000-05-29 14:26:00 +00003424 return;
3425}
3426
3427/*
3428** The following routine emits code for the destructor for the
3429** symbol sp
3430*/
icculus9e44cf12010-02-14 17:14:22 +00003431void emit_destructor_code(
3432 FILE *out,
3433 struct symbol *sp,
3434 struct lemon *lemp,
3435 int *lineno
3436){
drhcc83b6e2004-04-23 23:38:42 +00003437 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003438
drh75897232000-05-29 14:26:00 +00003439 if( sp->type==TERMINAL ){
3440 cp = lemp->tokendest;
3441 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003442 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003443 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003444 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003445 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003446 if( !lemp->nolinenosflag ){
3447 (*lineno)++;
3448 tplt_linedir(out,sp->destLineno,lemp->filename);
3449 }
drh960e8c62001-04-03 16:53:21 +00003450 }else if( lemp->vardest ){
3451 cp = lemp->vardest;
3452 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003453 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003454 }else{
3455 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003456 }
3457 for(; *cp; cp++){
3458 if( *cp=='$' && cp[1]=='$' ){
3459 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3460 cp++;
3461 continue;
3462 }
shane58543932008-12-10 20:10:04 +00003463 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003464 fputc(*cp,out);
3465 }
shane58543932008-12-10 20:10:04 +00003466 fprintf(out,"\n"); (*lineno)++;
3467 if (!lemp->nolinenosflag) {
3468 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3469 }
3470 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003471 return;
3472}
3473
3474/*
drh960e8c62001-04-03 16:53:21 +00003475** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003476*/
icculus9e44cf12010-02-14 17:14:22 +00003477int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003478{
3479 int ret;
3480 if( sp->type==TERMINAL ){
3481 ret = lemp->tokendest!=0;
3482 }else{
drh960e8c62001-04-03 16:53:21 +00003483 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003484 }
3485 return ret;
3486}
3487
drh0bb132b2004-07-20 14:06:51 +00003488/*
3489** Append text to a dynamically allocated string. If zText is 0 then
3490** reset the string to be empty again. Always return the complete text
3491** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003492**
3493** n bytes of zText are stored. If n==0 then all of zText up to the first
3494** \000 terminator is stored. zText can contain up to two instances of
3495** %d. The values of p1 and p2 are written into the first and second
3496** %d.
3497**
3498** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003499*/
icculus9e44cf12010-02-14 17:14:22 +00003500PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3501 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003502 static char *z = 0;
3503 static int alloced = 0;
3504 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003505 int c;
drh0bb132b2004-07-20 14:06:51 +00003506 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003507 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003508 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003509 used = 0;
3510 return z;
3511 }
drh7ac25c72004-08-19 15:12:26 +00003512 if( n<=0 ){
3513 if( n<0 ){
3514 used += n;
3515 assert( used>=0 );
3516 }
drh87cf1372008-08-13 20:09:06 +00003517 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003518 }
drhdf609712010-11-23 20:55:27 +00003519 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003520 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003521 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003522 }
icculus9e44cf12010-02-14 17:14:22 +00003523 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003524 while( n-- > 0 ){
3525 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003526 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003527 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003528 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003529 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003530 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003531 zText++;
3532 n--;
3533 }else{
mistachkin2318d332015-01-12 18:02:52 +00003534 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003535 }
3536 }
3537 z[used] = 0;
3538 return z;
3539}
3540
3541/*
drh711c9812016-05-23 14:24:31 +00003542** Write and transform the rp->code string so that symbols are expanded.
3543** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003544**
3545** Return 1 if the expanded code requires that "yylhsminor" local variable
3546** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003547*/
drhdabd04c2016-02-17 01:46:19 +00003548PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003549 char *cp, *xp;
3550 int i;
drhcf82f0d2016-02-17 04:33:10 +00003551 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003552 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003553 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3554 char lhsused = 0; /* True if the LHS element has been used */
3555 char lhsdirect; /* True if LHS writes directly into stack */
3556 char used[MAXRHS]; /* True for each RHS element which is used */
3557 char zLhs[50]; /* Convert the LHS symbol into this string */
3558 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003559
3560 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3561 lhsused = 0;
3562
drh19c9e562007-03-29 20:13:53 +00003563 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003564 static char newlinestr[2] = { '\n', '\0' };
3565 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003566 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003567 rp->noCode = 1;
3568 }else{
3569 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003570 }
3571
drh4dd0d3f2016-02-17 01:18:33 +00003572
drh2e55b042016-04-30 17:19:30 +00003573 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003574 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3575 lhsdirect = 1;
3576 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003577 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003578 ** we have to call the distructor on the RHS symbol first. */
3579 lhsdirect = 1;
3580 if( has_destructor(rp->rhs[0],lemp) ){
3581 append_str(0,0,0,0);
3582 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3583 rp->rhs[0]->index,1-rp->nrhs);
3584 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003585 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003586 }
drh2e55b042016-04-30 17:19:30 +00003587 }else if( rp->lhsalias==0 ){
3588 /* There is no LHS value symbol. */
3589 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003590 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3591 /* The LHS symbol and the left-most RHS symbol are the same, so
3592 ** direct writing is allowed */
3593 lhsdirect = 1;
3594 lhsused = 1;
3595 used[0] = 1;
3596 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3597 ErrorMsg(lemp->filename,rp->ruleline,
3598 "%s(%s) and %s(%s) share the same label but have "
3599 "different datatypes.",
3600 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3601 lemp->errorcnt++;
3602 }
3603 }else{
drhcf82f0d2016-02-17 04:33:10 +00003604 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3605 rp->lhsalias, rp->rhsalias[0]);
3606 zSkip = strstr(rp->code, zOvwrt);
3607 if( zSkip!=0 ){
3608 /* The code contains a special comment that indicates that it is safe
3609 ** for the LHS label to overwrite left-most RHS label. */
3610 lhsdirect = 1;
3611 }else{
3612 lhsdirect = 0;
3613 }
drh4dd0d3f2016-02-17 01:18:33 +00003614 }
3615 if( lhsdirect ){
3616 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3617 }else{
drhdabd04c2016-02-17 01:46:19 +00003618 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003619 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3620 }
3621
drh0bb132b2004-07-20 14:06:51 +00003622 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003623
3624 /* This const cast is wrong but harmless, if we're careful. */
3625 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003626 if( cp==zSkip ){
3627 append_str(zOvwrt,0,0,0);
3628 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003629 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003630 continue;
3631 }
drhc56fac72015-10-29 13:48:15 +00003632 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003633 char saved;
drhc56fac72015-10-29 13:48:15 +00003634 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003635 saved = *xp;
3636 *xp = 0;
3637 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003638 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003639 cp = xp;
3640 lhsused = 1;
3641 }else{
3642 for(i=0; i<rp->nrhs; i++){
3643 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003644 if( i==0 && dontUseRhs0 ){
3645 ErrorMsg(lemp->filename,rp->ruleline,
3646 "Label %s used after '%s'.",
3647 rp->rhsalias[0], zOvwrt);
3648 lemp->errorcnt++;
3649 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003650 /* If the argument is of the form @X then substituted
3651 ** the token number of X, not the value of X */
3652 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3653 }else{
drhfd405312005-11-06 04:06:59 +00003654 struct symbol *sp = rp->rhs[i];
3655 int dtnum;
3656 if( sp->type==MULTITERMINAL ){
3657 dtnum = sp->subsym[0]->dtnum;
3658 }else{
3659 dtnum = sp->dtnum;
3660 }
3661 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003662 }
drh0bb132b2004-07-20 14:06:51 +00003663 cp = xp;
3664 used[i] = 1;
3665 break;
3666 }
3667 }
3668 }
3669 *xp = saved;
3670 }
3671 append_str(cp, 1, 0, 0);
3672 } /* End loop */
3673
drh4dd0d3f2016-02-17 01:18:33 +00003674 /* Main code generation completed */
3675 cp = append_str(0,0,0,0);
3676 if( cp && cp[0] ) rp->code = Strsafe(cp);
3677 append_str(0,0,0,0);
3678
drh0bb132b2004-07-20 14:06:51 +00003679 /* Check to make sure the LHS has been used */
3680 if( rp->lhsalias && !lhsused ){
3681 ErrorMsg(lemp->filename,rp->ruleline,
3682 "Label \"%s\" for \"%s(%s)\" is never used.",
3683 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3684 lemp->errorcnt++;
3685 }
3686
drh4dd0d3f2016-02-17 01:18:33 +00003687 /* Generate destructor code for RHS minor values which are not referenced.
3688 ** Generate error messages for unused labels and duplicate labels.
3689 */
drh0bb132b2004-07-20 14:06:51 +00003690 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003691 if( rp->rhsalias[i] ){
3692 if( i>0 ){
3693 int j;
3694 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3695 ErrorMsg(lemp->filename,rp->ruleline,
3696 "%s(%s) has the same label as the LHS but is not the left-most "
3697 "symbol on the RHS.",
3698 rp->rhs[i]->name, rp->rhsalias);
3699 lemp->errorcnt++;
3700 }
3701 for(j=0; j<i; j++){
3702 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3703 ErrorMsg(lemp->filename,rp->ruleline,
3704 "Label %s used for multiple symbols on the RHS of a rule.",
3705 rp->rhsalias[i]);
3706 lemp->errorcnt++;
3707 break;
3708 }
3709 }
drh0bb132b2004-07-20 14:06:51 +00003710 }
drh4dd0d3f2016-02-17 01:18:33 +00003711 if( !used[i] ){
3712 ErrorMsg(lemp->filename,rp->ruleline,
3713 "Label %s for \"%s(%s)\" is never used.",
3714 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3715 lemp->errorcnt++;
3716 }
3717 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3718 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3719 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003720 }
3721 }
drh4dd0d3f2016-02-17 01:18:33 +00003722
3723 /* If unable to write LHS values directly into the stack, write the
3724 ** saved LHS value now. */
3725 if( lhsdirect==0 ){
3726 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3727 append_str(zLhs, 0, 0, 0);
3728 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003729 }
drh4dd0d3f2016-02-17 01:18:33 +00003730
3731 /* Suffix code generation complete */
3732 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003733 if( cp && cp[0] ){
3734 rp->codeSuffix = Strsafe(cp);
3735 rp->noCode = 0;
3736 }
drhdabd04c2016-02-17 01:46:19 +00003737
3738 return rc;
drh0bb132b2004-07-20 14:06:51 +00003739}
3740
drh75897232000-05-29 14:26:00 +00003741/*
3742** Generate code which executes when the rule "rp" is reduced. Write
3743** the code to "out". Make sure lineno stays up-to-date.
3744*/
icculus9e44cf12010-02-14 17:14:22 +00003745PRIVATE void emit_code(
3746 FILE *out,
3747 struct rule *rp,
3748 struct lemon *lemp,
3749 int *lineno
3750){
3751 const char *cp;
drh75897232000-05-29 14:26:00 +00003752
drh4dd0d3f2016-02-17 01:18:33 +00003753 /* Setup code prior to the #line directive */
3754 if( rp->codePrefix && rp->codePrefix[0] ){
3755 fprintf(out, "{%s", rp->codePrefix);
3756 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3757 }
3758
drh75897232000-05-29 14:26:00 +00003759 /* Generate code to do the reduce action */
3760 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003761 if( !lemp->nolinenosflag ){
3762 (*lineno)++;
3763 tplt_linedir(out,rp->line,lemp->filename);
3764 }
drhaf805ca2004-09-07 11:28:25 +00003765 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003766 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003767 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003768 if( !lemp->nolinenosflag ){
3769 (*lineno)++;
3770 tplt_linedir(out,*lineno,lemp->outname);
3771 }
drh4dd0d3f2016-02-17 01:18:33 +00003772 }
3773
3774 /* Generate breakdown code that occurs after the #line directive */
3775 if( rp->codeSuffix && rp->codeSuffix[0] ){
3776 fprintf(out, "%s", rp->codeSuffix);
3777 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3778 }
3779
3780 if( rp->codePrefix ){
3781 fprintf(out, "}\n"); (*lineno)++;
3782 }
drh75897232000-05-29 14:26:00 +00003783
drh75897232000-05-29 14:26:00 +00003784 return;
3785}
3786
3787/*
3788** Print the definition of the union used for the parser's data stack.
3789** This union contains fields for every possible data type for tokens
3790** and nonterminals. In the process of computing and printing this
3791** union, also set the ".dtnum" field of every terminal and nonterminal
3792** symbol.
3793*/
icculus9e44cf12010-02-14 17:14:22 +00003794void print_stack_union(
3795 FILE *out, /* The output stream */
3796 struct lemon *lemp, /* The main info structure for this parser */
3797 int *plineno, /* Pointer to the line number */
3798 int mhflag /* True if generating makeheaders output */
3799){
drh75897232000-05-29 14:26:00 +00003800 int lineno = *plineno; /* The line number of the output */
3801 char **types; /* A hash table of datatypes */
3802 int arraysize; /* Size of the "types" array */
3803 int maxdtlength; /* Maximum length of any ".datatype" field. */
3804 char *stddt; /* Standardized name for a datatype */
3805 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003806 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003807 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003808
3809 /* Allocate and initialize types[] and allocate stddt[] */
3810 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003811 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003812 if( types==0 ){
3813 fprintf(stderr,"Out of memory.\n");
3814 exit(1);
3815 }
drh75897232000-05-29 14:26:00 +00003816 for(i=0; i<arraysize; i++) types[i] = 0;
3817 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003818 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003819 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003820 }
drh75897232000-05-29 14:26:00 +00003821 for(i=0; i<lemp->nsymbol; i++){
3822 int len;
3823 struct symbol *sp = lemp->symbols[i];
3824 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003825 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003826 if( len>maxdtlength ) maxdtlength = len;
3827 }
3828 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003829 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003830 fprintf(stderr,"Out of memory.\n");
3831 exit(1);
3832 }
3833
3834 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3835 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003836 ** used for terminal symbols. If there is no %default_type defined then
3837 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3838 ** a datatype using the %type directive.
3839 */
drh75897232000-05-29 14:26:00 +00003840 for(i=0; i<lemp->nsymbol; i++){
3841 struct symbol *sp = lemp->symbols[i];
3842 char *cp;
3843 if( sp==lemp->errsym ){
3844 sp->dtnum = arraysize+1;
3845 continue;
3846 }
drh960e8c62001-04-03 16:53:21 +00003847 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003848 sp->dtnum = 0;
3849 continue;
3850 }
3851 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003852 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003853 j = 0;
drhc56fac72015-10-29 13:48:15 +00003854 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003855 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003856 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003857 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003858 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003859 sp->dtnum = 0;
3860 continue;
3861 }
drh75897232000-05-29 14:26:00 +00003862 hash = 0;
3863 for(j=0; stddt[j]; j++){
3864 hash = hash*53 + stddt[j];
3865 }
drh3b2129c2003-05-13 00:34:21 +00003866 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003867 while( types[hash] ){
3868 if( strcmp(types[hash],stddt)==0 ){
3869 sp->dtnum = hash + 1;
3870 break;
3871 }
3872 hash++;
drh2b51f212013-10-11 23:01:02 +00003873 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003874 }
3875 if( types[hash]==0 ){
3876 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003877 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003878 if( types[hash]==0 ){
3879 fprintf(stderr,"Out of memory.\n");
3880 exit(1);
3881 }
drh898799f2014-01-10 23:21:00 +00003882 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003883 }
3884 }
3885
3886 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3887 name = lemp->name ? lemp->name : "Parse";
3888 lineno = *plineno;
3889 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3890 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3891 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3892 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3893 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003894 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003895 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3896 for(i=0; i<arraysize; i++){
3897 if( types[i]==0 ) continue;
3898 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3899 free(types[i]);
3900 }
drhc4dd3fd2008-01-22 01:48:05 +00003901 if( lemp->errsym->useCnt ){
3902 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3903 }
drh75897232000-05-29 14:26:00 +00003904 free(stddt);
3905 free(types);
3906 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3907 *plineno = lineno;
3908}
3909
drhb29b0a52002-02-23 19:39:46 +00003910/*
3911** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003912** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3913** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003914*/
drhc75e0162015-09-07 02:23:02 +00003915static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3916 const char *zType = "int";
3917 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003918 if( lwr>=0 ){
3919 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003920 zType = "unsigned char";
3921 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003922 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003923 zType = "unsigned short int";
3924 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003925 }else{
drhc75e0162015-09-07 02:23:02 +00003926 zType = "unsigned int";
3927 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003928 }
3929 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003930 zType = "signed char";
3931 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003932 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003933 zType = "short";
3934 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003935 }
drhc75e0162015-09-07 02:23:02 +00003936 if( pnByte ) *pnByte = nByte;
3937 return zType;
drhb29b0a52002-02-23 19:39:46 +00003938}
3939
drhfdbf9282003-10-21 16:34:41 +00003940/*
3941** Each state contains a set of token transaction and a set of
3942** nonterminal transactions. Each of these sets makes an instance
3943** of the following structure. An array of these structures is used
3944** to order the creation of entries in the yy_action[] table.
3945*/
3946struct axset {
3947 struct state *stp; /* A pointer to a state */
3948 int isTkn; /* True to use tokens. False for non-terminals */
3949 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003950 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003951};
3952
3953/*
3954** Compare to axset structures for sorting purposes
3955*/
3956static int axset_compare(const void *a, const void *b){
3957 struct axset *p1 = (struct axset*)a;
3958 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003959 int c;
3960 c = p2->nAction - p1->nAction;
3961 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003962 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003963 }
3964 assert( c!=0 || p1==p2 );
3965 return c;
drhfdbf9282003-10-21 16:34:41 +00003966}
3967
drhc4dd3fd2008-01-22 01:48:05 +00003968/*
3969** Write text on "out" that describes the rule "rp".
3970*/
3971static void writeRuleText(FILE *out, struct rule *rp){
3972 int j;
3973 fprintf(out,"%s ::=", rp->lhs->name);
3974 for(j=0; j<rp->nrhs; j++){
3975 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003976 if( sp->type!=MULTITERMINAL ){
3977 fprintf(out," %s", sp->name);
3978 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003979 int k;
drh61f92cd2014-01-11 03:06:18 +00003980 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003981 for(k=1; k<sp->nsubsym; k++){
3982 fprintf(out,"|%s",sp->subsym[k]->name);
3983 }
3984 }
3985 }
3986}
3987
3988
drh75897232000-05-29 14:26:00 +00003989/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003990void ReportTable(
3991 struct lemon *lemp,
3992 int mhflag /* Output in makeheaders format if true */
3993){
drh75897232000-05-29 14:26:00 +00003994 FILE *out, *in;
3995 char line[LINESIZE];
3996 int lineno;
3997 struct state *stp;
3998 struct action *ap;
3999 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00004000 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00004001 int i, j, n, sz;
4002 int szActionType; /* sizeof(YYACTIONTYPE) */
4003 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00004004 const char *name;
drh8b582012003-10-21 13:16:03 +00004005 int mnTknOfst, mxTknOfst;
4006 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004007 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004008
4009 in = tplt_open(lemp);
4010 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004011 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004012 if( out==0 ){
4013 fclose(in);
4014 return;
4015 }
4016 lineno = 1;
4017 tplt_xfer(lemp->name,in,out,&lineno);
4018
4019 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004020 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004021 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004022 char *incName = file_makename(lemp, ".h");
4023 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4024 free(incName);
drh75897232000-05-29 14:26:00 +00004025 }
4026 tplt_xfer(lemp->name,in,out,&lineno);
4027
4028 /* Generate #defines for all tokens */
4029 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004030 const char *prefix;
drh75897232000-05-29 14:26:00 +00004031 fprintf(out,"#if INTERFACE\n"); lineno++;
4032 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4033 else prefix = "";
4034 for(i=1; i<lemp->nterminal; i++){
4035 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4036 lineno++;
4037 }
4038 fprintf(out,"#endif\n"); lineno++;
4039 }
4040 tplt_xfer(lemp->name,in,out,&lineno);
4041
4042 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004043 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00004044 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00004045 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
4046 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00004047 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004048 if( lemp->wildcard ){
4049 fprintf(out,"#define YYWILDCARD %d\n",
4050 lemp->wildcard->index); lineno++;
4051 }
drh75897232000-05-29 14:26:00 +00004052 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004053 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004054 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004055 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4056 }else{
4057 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4058 }
drhca44b5a2007-02-22 23:06:58 +00004059 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004060 if( mhflag ){
4061 fprintf(out,"#if INTERFACE\n"); lineno++;
4062 }
4063 name = lemp->name ? lemp->name : "Parse";
4064 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004065 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004066 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4067 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004068 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4069 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4070 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
4071 name,lemp->arg,&lemp->arg[i]); lineno++;
4072 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
4073 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004074 }else{
drh1f245e42002-03-11 13:55:50 +00004075 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4076 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4077 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4078 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004079 }
4080 if( mhflag ){
4081 fprintf(out,"#endif\n"); lineno++;
4082 }
drhc4dd3fd2008-01-22 01:48:05 +00004083 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004084 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4085 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004086 }
drh0bd1f4e2002-06-06 18:54:39 +00004087 if( lemp->has_fallback ){
4088 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4089 }
drh75897232000-05-29 14:26:00 +00004090
drh3bd48ab2015-09-07 18:23:37 +00004091 /* Compute the action table, but do not output it yet. The action
4092 ** table must be computed before generating the YYNSTATE macro because
4093 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004094 */
drh3bd48ab2015-09-07 18:23:37 +00004095 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004096 if( ax==0 ){
4097 fprintf(stderr,"malloc failed\n");
4098 exit(1);
4099 }
drh3bd48ab2015-09-07 18:23:37 +00004100 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004101 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004102 ax[i*2].stp = stp;
4103 ax[i*2].isTkn = 1;
4104 ax[i*2].nAction = stp->nTknAct;
4105 ax[i*2+1].stp = stp;
4106 ax[i*2+1].isTkn = 0;
4107 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004108 }
drh8b582012003-10-21 13:16:03 +00004109 mxTknOfst = mnTknOfst = 0;
4110 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004111 /* In an effort to minimize the action table size, use the heuristic
4112 ** of placing the largest action sets first */
4113 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4114 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004115 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004116 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004117 stp = ax[i].stp;
4118 if( ax[i].isTkn ){
4119 for(ap=stp->ap; ap; ap=ap->next){
4120 int action;
4121 if( ap->sp->index>=lemp->nterminal ) continue;
4122 action = compute_action(lemp, ap);
4123 if( action<0 ) continue;
4124 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004125 }
drhfdbf9282003-10-21 16:34:41 +00004126 stp->iTknOfst = acttab_insert(pActtab);
4127 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4128 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4129 }else{
4130 for(ap=stp->ap; ap; ap=ap->next){
4131 int action;
4132 if( ap->sp->index<lemp->nterminal ) continue;
4133 if( ap->sp->index==lemp->nsymbol ) continue;
4134 action = compute_action(lemp, ap);
4135 if( action<0 ) continue;
4136 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004137 }
drhfdbf9282003-10-21 16:34:41 +00004138 stp->iNtOfst = acttab_insert(pActtab);
4139 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4140 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004141 }
drh337cd0d2015-09-07 23:40:42 +00004142#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4143 { int jj, nn;
4144 for(jj=nn=0; jj<pActtab->nAction; jj++){
4145 if( pActtab->aAction[jj].action<0 ) nn++;
4146 }
4147 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4148 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4149 ax[i].nAction, pActtab->nAction, nn);
4150 }
4151#endif
drh8b582012003-10-21 13:16:03 +00004152 }
drhfdbf9282003-10-21 16:34:41 +00004153 free(ax);
drh8b582012003-10-21 13:16:03 +00004154
drh3bd48ab2015-09-07 18:23:37 +00004155 /* Finish rendering the constants now that the action table has
4156 ** been computed */
4157 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4158 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004159 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004160 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4161 i = lemp->nstate + lemp->nrule;
4162 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4163 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
4164 i = lemp->nstate + lemp->nrule*2;
4165 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4166 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
4167 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
4168 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
4169 tplt_xfer(lemp->name,in,out,&lineno);
4170
4171 /* Now output the action table and its associates:
4172 **
4173 ** yy_action[] A single table containing all actions.
4174 ** yy_lookahead[] A table containing the lookahead for each entry in
4175 ** yy_action. Used to detect hash collisions.
4176 ** yy_shift_ofst[] For each state, the offset into yy_action for
4177 ** shifting terminals.
4178 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4179 ** shifting non-terminals after a reduce.
4180 ** yy_default[] Default action for each state.
4181 */
4182
drh8b582012003-10-21 13:16:03 +00004183 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004184 lemp->nactiontab = n = acttab_size(pActtab);
4185 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004186 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4187 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004188 for(i=j=0; i<n; i++){
4189 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00004190 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00004191 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004192 fprintf(out, " %4d,", action);
4193 if( j==9 || i==n-1 ){
4194 fprintf(out, "\n"); lineno++;
4195 j = 0;
4196 }else{
4197 j++;
4198 }
4199 }
4200 fprintf(out, "};\n"); lineno++;
4201
4202 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004203 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004204 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004205 for(i=j=0; i<n; i++){
4206 int la = acttab_yylookahead(pActtab, i);
4207 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004208 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004209 fprintf(out, " %4d,", la);
4210 if( j==9 || i==n-1 ){
4211 fprintf(out, "\n"); lineno++;
4212 j = 0;
4213 }else{
4214 j++;
4215 }
4216 }
4217 fprintf(out, "};\n"); lineno++;
4218
4219 /* Output the yy_shift_ofst[] table */
4220 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004221 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004222 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004223 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4224 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4225 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004226 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004227 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4228 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004229 for(i=j=0; i<n; i++){
4230 int ofst;
4231 stp = lemp->sorted[i];
4232 ofst = stp->iTknOfst;
4233 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004234 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004235 fprintf(out, " %4d,", ofst);
4236 if( j==9 || i==n-1 ){
4237 fprintf(out, "\n"); lineno++;
4238 j = 0;
4239 }else{
4240 j++;
4241 }
4242 }
4243 fprintf(out, "};\n"); lineno++;
4244
4245 /* Output the yy_reduce_ofst[] table */
4246 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004247 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004248 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004249 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4250 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4251 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004252 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004253 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4254 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004255 for(i=j=0; i<n; i++){
4256 int ofst;
4257 stp = lemp->sorted[i];
4258 ofst = stp->iNtOfst;
4259 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004260 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004261 fprintf(out, " %4d,", ofst);
4262 if( j==9 || i==n-1 ){
4263 fprintf(out, "\n"); lineno++;
4264 j = 0;
4265 }else{
4266 j++;
4267 }
4268 }
4269 fprintf(out, "};\n"); lineno++;
4270
4271 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004272 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004273 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004274 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004275 for(i=j=0; i<n; i++){
4276 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004277 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004278 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004279 if( j==9 || i==n-1 ){
4280 fprintf(out, "\n"); lineno++;
4281 j = 0;
4282 }else{
4283 j++;
4284 }
4285 }
4286 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004287 tplt_xfer(lemp->name,in,out,&lineno);
4288
drh0bd1f4e2002-06-06 18:54:39 +00004289 /* Generate the table of fallback tokens.
4290 */
4291 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004292 int mx = lemp->nterminal - 1;
4293 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004294 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004295 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004296 struct symbol *p = lemp->symbols[i];
4297 if( p->fallback==0 ){
4298 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4299 }else{
4300 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4301 p->name, p->fallback->name);
4302 }
4303 lineno++;
4304 }
4305 }
4306 tplt_xfer(lemp->name, in, out, &lineno);
4307
4308 /* Generate a table containing the symbolic name of every symbol
4309 */
drh75897232000-05-29 14:26:00 +00004310 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004311 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004312 fprintf(out," %-15s",line);
4313 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4314 }
4315 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4316 tplt_xfer(lemp->name,in,out,&lineno);
4317
drh0bd1f4e2002-06-06 18:54:39 +00004318 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004319 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004320 ** when tracing REDUCE actions.
4321 */
4322 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004323 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004324 fprintf(out," /* %3d */ \"", i);
4325 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004326 fprintf(out,"\",\n"); lineno++;
4327 }
4328 tplt_xfer(lemp->name,in,out,&lineno);
4329
drh75897232000-05-29 14:26:00 +00004330 /* Generate code which executes every time a symbol is popped from
4331 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004332 ** (In other words, generate the %destructor actions)
4333 */
drh75897232000-05-29 14:26:00 +00004334 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004335 int once = 1;
drh75897232000-05-29 14:26:00 +00004336 for(i=0; i<lemp->nsymbol; i++){
4337 struct symbol *sp = lemp->symbols[i];
4338 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004339 if( once ){
4340 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4341 once = 0;
4342 }
drhc53eed12009-06-12 17:46:19 +00004343 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004344 }
4345 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4346 if( i<lemp->nsymbol ){
4347 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4348 fprintf(out," break;\n"); lineno++;
4349 }
4350 }
drh8d659732005-01-13 23:54:06 +00004351 if( lemp->vardest ){
4352 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004353 int once = 1;
drh8d659732005-01-13 23:54:06 +00004354 for(i=0; i<lemp->nsymbol; i++){
4355 struct symbol *sp = lemp->symbols[i];
4356 if( sp==0 || sp->type==TERMINAL ||
4357 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004358 if( once ){
4359 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4360 once = 0;
4361 }
drhc53eed12009-06-12 17:46:19 +00004362 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004363 dflt_sp = sp;
4364 }
4365 if( dflt_sp!=0 ){
4366 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004367 }
drh4dc8ef52008-07-01 17:13:57 +00004368 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004369 }
drh75897232000-05-29 14:26:00 +00004370 for(i=0; i<lemp->nsymbol; i++){
4371 struct symbol *sp = lemp->symbols[i];
4372 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004373 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004374
4375 /* Combine duplicate destructors into a single case */
4376 for(j=i+1; j<lemp->nsymbol; j++){
4377 struct symbol *sp2 = lemp->symbols[j];
4378 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4379 && sp2->dtnum==sp->dtnum
4380 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004381 fprintf(out," case %d: /* %s */\n",
4382 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004383 sp2->destructor = 0;
4384 }
4385 }
4386
drh75897232000-05-29 14:26:00 +00004387 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4388 fprintf(out," break;\n"); lineno++;
4389 }
drh75897232000-05-29 14:26:00 +00004390 tplt_xfer(lemp->name,in,out,&lineno);
4391
4392 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004393 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004394 tplt_xfer(lemp->name,in,out,&lineno);
4395
4396 /* Generate the table of rule information
4397 **
4398 ** Note: This code depends on the fact that rules are number
4399 ** sequentually beginning with 0.
4400 */
4401 for(rp=lemp->rule; rp; rp=rp->next){
4402 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4403 }
4404 tplt_xfer(lemp->name,in,out,&lineno);
4405
4406 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004407 i = 0;
drh75897232000-05-29 14:26:00 +00004408 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004409 i += translate_code(lemp, rp);
4410 }
4411 if( i ){
4412 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004413 }
drhc53eed12009-06-12 17:46:19 +00004414 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004415 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004416 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004417 if( rp->codeEmitted ) continue;
4418 if( rp->noCode ){
4419 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004420 continue;
4421 }
drh4ef07702016-03-16 19:45:54 +00004422 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004423 writeRuleText(out, rp);
4424 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004425 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004426 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4427 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004428 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004429 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004430 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004431 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004432 }
4433 }
drh75897232000-05-29 14:26:00 +00004434 emit_code(out,rp,lemp,&lineno);
4435 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004436 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004437 }
drhc53eed12009-06-12 17:46:19 +00004438 /* Finally, output the default: rule. We choose as the default: all
4439 ** empty actions. */
4440 fprintf(out," default:\n"); lineno++;
4441 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004442 if( rp->codeEmitted ) continue;
4443 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004444 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004445 writeRuleText(out, rp);
drh4ef07702016-03-16 19:45:54 +00004446 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
drhc53eed12009-06-12 17:46:19 +00004447 }
4448 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004449 tplt_xfer(lemp->name,in,out,&lineno);
4450
4451 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004452 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004453 tplt_xfer(lemp->name,in,out,&lineno);
4454
4455 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004456 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004457 tplt_xfer(lemp->name,in,out,&lineno);
4458
4459 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004460 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004461 tplt_xfer(lemp->name,in,out,&lineno);
4462
4463 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004464 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004465
4466 fclose(in);
4467 fclose(out);
4468 return;
4469}
4470
4471/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004472void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004473{
4474 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004475 const char *prefix;
drh75897232000-05-29 14:26:00 +00004476 char line[LINESIZE];
4477 char pattern[LINESIZE];
4478 int i;
4479
4480 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4481 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004482 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004483 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004484 int nextChar;
drh75897232000-05-29 14:26:00 +00004485 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004486 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4487 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004488 if( strcmp(line,pattern) ) break;
4489 }
drh8ba0d1c2012-06-16 15:26:31 +00004490 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004491 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004492 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004493 /* No change in the file. Don't rewrite it. */
4494 return;
4495 }
4496 }
drh2aa6ca42004-09-10 00:14:04 +00004497 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004498 if( out ){
4499 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004500 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004501 }
4502 fclose(out);
4503 }
4504 return;
4505}
4506
4507/* Reduce the size of the action tables, if possible, by making use
4508** of defaults.
4509**
drhb59499c2002-02-23 18:45:13 +00004510** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004511** it the default. Except, there is no default if the wildcard token
4512** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004513*/
icculus9e44cf12010-02-14 17:14:22 +00004514void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004515{
4516 struct state *stp;
drhc173ad82016-05-23 16:15:02 +00004517 struct action *ap, *ap2, *nextap;
drhb59499c2002-02-23 18:45:13 +00004518 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004519 int nbest, n;
drh75897232000-05-29 14:26:00 +00004520 int i;
drhe09daa92006-06-10 13:29:31 +00004521 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004522
4523 for(i=0; i<lemp->nstate; i++){
4524 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004525 nbest = 0;
4526 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004527 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004528
drhb59499c2002-02-23 18:45:13 +00004529 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004530 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4531 usesWildcard = 1;
4532 }
drhb59499c2002-02-23 18:45:13 +00004533 if( ap->type!=REDUCE ) continue;
4534 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004535 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004536 if( rp==rbest ) continue;
4537 n = 1;
4538 for(ap2=ap->next; ap2; ap2=ap2->next){
4539 if( ap2->type!=REDUCE ) continue;
4540 rp2 = ap2->x.rp;
4541 if( rp2==rbest ) continue;
4542 if( rp2==rp ) n++;
4543 }
4544 if( n>nbest ){
4545 nbest = n;
4546 rbest = rp;
drh75897232000-05-29 14:26:00 +00004547 }
4548 }
drhb59499c2002-02-23 18:45:13 +00004549
4550 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004551 ** is not at least 1 or if the wildcard token is a possible
4552 ** lookahead.
4553 */
4554 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004555
drhb59499c2002-02-23 18:45:13 +00004556
4557 /* Combine matching REDUCE actions into a single default */
4558 for(ap=stp->ap; ap; ap=ap->next){
4559 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4560 }
drh75897232000-05-29 14:26:00 +00004561 assert( ap );
4562 ap->sp = Symbol_new("{default}");
4563 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004564 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004565 }
4566 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004567
4568 for(ap=stp->ap; ap; ap=ap->next){
4569 if( ap->type==SHIFT ) break;
4570 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4571 }
4572 if( ap==0 ){
4573 stp->autoReduce = 1;
4574 stp->pDfltReduce = rbest;
4575 }
4576 }
4577
4578 /* Make a second pass over all states and actions. Convert
4579 ** every action that is a SHIFT to an autoReduce state into
4580 ** a SHIFTREDUCE action.
4581 */
4582 for(i=0; i<lemp->nstate; i++){
4583 stp = lemp->sorted[i];
4584 for(ap=stp->ap; ap; ap=ap->next){
4585 struct state *pNextState;
4586 if( ap->type!=SHIFT ) continue;
4587 pNextState = ap->x.stp;
4588 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4589 ap->type = SHIFTREDUCE;
4590 ap->x.rp = pNextState->pDfltReduce;
4591 }
4592 }
drh75897232000-05-29 14:26:00 +00004593 }
drhc173ad82016-05-23 16:15:02 +00004594
4595 /* If a SHIFTREDUCE action specifies a rule that has a single RHS term
4596 ** (meaning that the SHIFTREDUCE will land back in the state where it
4597 ** started) and if there is no C-code associated with the reduce action,
4598 ** then we can go ahead and convert the action to be the same as the
4599 ** action for the RHS of the rule.
4600 */
4601 for(i=0; i<lemp->nstate; i++){
4602 stp = lemp->sorted[i];
4603 for(ap=stp->ap; ap; ap=nextap){
4604 nextap = ap->next;
4605 if( ap->type!=SHIFTREDUCE ) continue;
4606 rp = ap->x.rp;
4607 if( rp->noCode==0 ) continue;
4608 if( rp->nrhs!=1 ) continue;
4609#if 1
4610 /* Only apply this optimization to non-terminals. It would be OK to
4611 ** apply it to terminal symbols too, but that makes the parser tables
4612 ** larger. */
4613 if( ap->sp->index<lemp->nterminal ) continue;
4614#endif
4615 /* If we reach this point, it means the optimization can be applied */
4616 nextap = ap;
4617 for(ap2=stp->ap; ap2 && (ap2==ap || ap2->sp!=rp->lhs); ap2=ap2->next){}
4618 assert( ap2!=0 );
4619 ap->spOpt = ap2->sp;
4620 ap->type = ap2->type;
4621 ap->x = ap2->x;
4622 }
4623 }
drh75897232000-05-29 14:26:00 +00004624}
drhb59499c2002-02-23 18:45:13 +00004625
drhada354d2005-11-05 15:03:59 +00004626
4627/*
4628** Compare two states for sorting purposes. The smaller state is the
4629** one with the most non-terminal actions. If they have the same number
4630** of non-terminal actions, then the smaller is the one with the most
4631** token actions.
4632*/
4633static int stateResortCompare(const void *a, const void *b){
4634 const struct state *pA = *(const struct state**)a;
4635 const struct state *pB = *(const struct state**)b;
4636 int n;
4637
4638 n = pB->nNtAct - pA->nNtAct;
4639 if( n==0 ){
4640 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004641 if( n==0 ){
4642 n = pB->statenum - pA->statenum;
4643 }
drhada354d2005-11-05 15:03:59 +00004644 }
drhe594bc32009-11-03 13:02:25 +00004645 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004646 return n;
4647}
4648
4649
4650/*
4651** Renumber and resort states so that states with fewer choices
4652** occur at the end. Except, keep state 0 as the first state.
4653*/
icculus9e44cf12010-02-14 17:14:22 +00004654void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004655{
4656 int i;
4657 struct state *stp;
4658 struct action *ap;
4659
4660 for(i=0; i<lemp->nstate; i++){
4661 stp = lemp->sorted[i];
4662 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004663 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004664 stp->iTknOfst = NO_OFFSET;
4665 stp->iNtOfst = NO_OFFSET;
4666 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004667 int iAction = compute_action(lemp,ap);
4668 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004669 if( ap->sp->index<lemp->nterminal ){
4670 stp->nTknAct++;
4671 }else if( ap->sp->index<lemp->nsymbol ){
4672 stp->nNtAct++;
4673 }else{
drh3bd48ab2015-09-07 18:23:37 +00004674 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4675 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004676 }
4677 }
4678 }
4679 }
4680 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4681 stateResortCompare);
4682 for(i=0; i<lemp->nstate; i++){
4683 lemp->sorted[i]->statenum = i;
4684 }
drh3bd48ab2015-09-07 18:23:37 +00004685 lemp->nxstate = lemp->nstate;
4686 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4687 lemp->nxstate--;
4688 }
drhada354d2005-11-05 15:03:59 +00004689}
4690
4691
drh75897232000-05-29 14:26:00 +00004692/***************** From the file "set.c" ************************************/
4693/*
4694** Set manipulation routines for the LEMON parser generator.
4695*/
4696
4697static int size = 0;
4698
4699/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004700void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004701{
4702 size = n+1;
4703}
4704
4705/* Allocate a new set */
4706char *SetNew(){
4707 char *s;
drh9892c5d2007-12-21 00:02:11 +00004708 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004709 if( s==0 ){
4710 extern void memory_error();
4711 memory_error();
4712 }
drh75897232000-05-29 14:26:00 +00004713 return s;
4714}
4715
4716/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004717void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004718{
4719 free(s);
4720}
4721
4722/* Add a new element to the set. Return TRUE if the element was added
4723** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004724int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004725{
4726 int rv;
drh9892c5d2007-12-21 00:02:11 +00004727 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004728 rv = s[e];
4729 s[e] = 1;
4730 return !rv;
4731}
4732
4733/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004734int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004735{
4736 int i, progress;
4737 progress = 0;
4738 for(i=0; i<size; i++){
4739 if( s2[i]==0 ) continue;
4740 if( s1[i]==0 ){
4741 progress = 1;
4742 s1[i] = 1;
4743 }
4744 }
4745 return progress;
4746}
4747/********************** From the file "table.c" ****************************/
4748/*
4749** All code in this file has been automatically generated
4750** from a specification in the file
4751** "table.q"
4752** by the associative array code building program "aagen".
4753** Do not edit this file! Instead, edit the specification
4754** file, then rerun aagen.
4755*/
4756/*
4757** Code for processing tables in the LEMON parser generator.
4758*/
4759
drh01f75f22013-10-02 20:46:30 +00004760PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004761{
drh01f75f22013-10-02 20:46:30 +00004762 unsigned h = 0;
4763 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004764 return h;
4765}
4766
4767/* Works like strdup, sort of. Save a string in malloced memory, but
4768** keep strings in a table so that the same string is not in more
4769** than one place.
4770*/
icculus9e44cf12010-02-14 17:14:22 +00004771const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004772{
icculus9e44cf12010-02-14 17:14:22 +00004773 const char *z;
4774 char *cpy;
drh75897232000-05-29 14:26:00 +00004775
drh916f75f2006-07-17 00:19:39 +00004776 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004777 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004778 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004779 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004780 z = cpy;
drh75897232000-05-29 14:26:00 +00004781 Strsafe_insert(z);
4782 }
4783 MemoryCheck(z);
4784 return z;
4785}
4786
4787/* There is one instance of the following structure for each
4788** associative array of type "x1".
4789*/
4790struct s_x1 {
4791 int size; /* The number of available slots. */
4792 /* Must be a power of 2 greater than or */
4793 /* equal to 1 */
4794 int count; /* Number of currently slots filled */
4795 struct s_x1node *tbl; /* The data stored here */
4796 struct s_x1node **ht; /* Hash table for lookups */
4797};
4798
4799/* There is one instance of this structure for every data element
4800** in an associative array of type "x1".
4801*/
4802typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004803 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004804 struct s_x1node *next; /* Next entry with the same hash */
4805 struct s_x1node **from; /* Previous link */
4806} x1node;
4807
4808/* There is only one instance of the array, which is the following */
4809static struct s_x1 *x1a;
4810
4811/* Allocate a new associative array */
4812void Strsafe_init(){
4813 if( x1a ) return;
4814 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4815 if( x1a ){
4816 x1a->size = 1024;
4817 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004818 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004819 if( x1a->tbl==0 ){
4820 free(x1a);
4821 x1a = 0;
4822 }else{
4823 int i;
4824 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4825 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4826 }
4827 }
4828}
4829/* Insert a new record into the array. Return TRUE if successful.
4830** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004831int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004832{
4833 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004834 unsigned h;
4835 unsigned ph;
drh75897232000-05-29 14:26:00 +00004836
4837 if( x1a==0 ) return 0;
4838 ph = strhash(data);
4839 h = ph & (x1a->size-1);
4840 np = x1a->ht[h];
4841 while( np ){
4842 if( strcmp(np->data,data)==0 ){
4843 /* An existing entry with the same key is found. */
4844 /* Fail because overwrite is not allows. */
4845 return 0;
4846 }
4847 np = np->next;
4848 }
4849 if( x1a->count>=x1a->size ){
4850 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004851 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004852 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004853 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004854 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004855 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004856 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004857 array.ht = (x1node**)&(array.tbl[arrSize]);
4858 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004859 for(i=0; i<x1a->count; i++){
4860 x1node *oldnp, *newnp;
4861 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004862 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004863 newnp = &(array.tbl[i]);
4864 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4865 newnp->next = array.ht[h];
4866 newnp->data = oldnp->data;
4867 newnp->from = &(array.ht[h]);
4868 array.ht[h] = newnp;
4869 }
4870 free(x1a->tbl);
4871 *x1a = array;
4872 }
4873 /* Insert the new data */
4874 h = ph & (x1a->size-1);
4875 np = &(x1a->tbl[x1a->count++]);
4876 np->data = data;
4877 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4878 np->next = x1a->ht[h];
4879 x1a->ht[h] = np;
4880 np->from = &(x1a->ht[h]);
4881 return 1;
4882}
4883
4884/* Return a pointer to data assigned to the given key. Return NULL
4885** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004886const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004887{
drh01f75f22013-10-02 20:46:30 +00004888 unsigned h;
drh75897232000-05-29 14:26:00 +00004889 x1node *np;
4890
4891 if( x1a==0 ) return 0;
4892 h = strhash(key) & (x1a->size-1);
4893 np = x1a->ht[h];
4894 while( np ){
4895 if( strcmp(np->data,key)==0 ) break;
4896 np = np->next;
4897 }
4898 return np ? np->data : 0;
4899}
4900
4901/* Return a pointer to the (terminal or nonterminal) symbol "x".
4902** Create a new symbol if this is the first time "x" has been seen.
4903*/
icculus9e44cf12010-02-14 17:14:22 +00004904struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004905{
4906 struct symbol *sp;
4907
4908 sp = Symbol_find(x);
4909 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004910 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004911 MemoryCheck(sp);
4912 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004913 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004914 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004915 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004916 sp->prec = -1;
4917 sp->assoc = UNK;
4918 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004919 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004920 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004921 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004922 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004923 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004924 Symbol_insert(sp,sp->name);
4925 }
drhc4dd3fd2008-01-22 01:48:05 +00004926 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004927 return sp;
4928}
4929
drh61f92cd2014-01-11 03:06:18 +00004930/* Compare two symbols for sorting purposes. Return negative,
4931** zero, or positive if a is less then, equal to, or greater
4932** than b.
drh60d31652004-02-22 00:08:04 +00004933**
4934** Symbols that begin with upper case letters (terminals or tokens)
4935** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004936** (non-terminals). And MULTITERMINAL symbols (created using the
4937** %token_class directive) must sort at the very end. Other than
4938** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004939**
4940** We find experimentally that leaving the symbols in their original
4941** order (the order they appeared in the grammar file) gives the
4942** smallest parser tables in SQLite.
4943*/
icculus9e44cf12010-02-14 17:14:22 +00004944int Symbolcmpp(const void *_a, const void *_b)
4945{
drh61f92cd2014-01-11 03:06:18 +00004946 const struct symbol *a = *(const struct symbol **) _a;
4947 const struct symbol *b = *(const struct symbol **) _b;
4948 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4949 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4950 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004951}
4952
4953/* There is one instance of the following structure for each
4954** associative array of type "x2".
4955*/
4956struct s_x2 {
4957 int size; /* The number of available slots. */
4958 /* Must be a power of 2 greater than or */
4959 /* equal to 1 */
4960 int count; /* Number of currently slots filled */
4961 struct s_x2node *tbl; /* The data stored here */
4962 struct s_x2node **ht; /* Hash table for lookups */
4963};
4964
4965/* There is one instance of this structure for every data element
4966** in an associative array of type "x2".
4967*/
4968typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004969 struct symbol *data; /* The data */
4970 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004971 struct s_x2node *next; /* Next entry with the same hash */
4972 struct s_x2node **from; /* Previous link */
4973} x2node;
4974
4975/* There is only one instance of the array, which is the following */
4976static struct s_x2 *x2a;
4977
4978/* Allocate a new associative array */
4979void Symbol_init(){
4980 if( x2a ) return;
4981 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4982 if( x2a ){
4983 x2a->size = 128;
4984 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004985 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004986 if( x2a->tbl==0 ){
4987 free(x2a);
4988 x2a = 0;
4989 }else{
4990 int i;
4991 x2a->ht = (x2node**)&(x2a->tbl[128]);
4992 for(i=0; i<128; i++) x2a->ht[i] = 0;
4993 }
4994 }
4995}
4996/* Insert a new record into the array. Return TRUE if successful.
4997** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004998int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004999{
5000 x2node *np;
drh01f75f22013-10-02 20:46:30 +00005001 unsigned h;
5002 unsigned ph;
drh75897232000-05-29 14:26:00 +00005003
5004 if( x2a==0 ) return 0;
5005 ph = strhash(key);
5006 h = ph & (x2a->size-1);
5007 np = x2a->ht[h];
5008 while( np ){
5009 if( strcmp(np->key,key)==0 ){
5010 /* An existing entry with the same key is found. */
5011 /* Fail because overwrite is not allows. */
5012 return 0;
5013 }
5014 np = np->next;
5015 }
5016 if( x2a->count>=x2a->size ){
5017 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005018 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005019 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00005020 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00005021 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00005022 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00005023 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005024 array.ht = (x2node**)&(array.tbl[arrSize]);
5025 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005026 for(i=0; i<x2a->count; i++){
5027 x2node *oldnp, *newnp;
5028 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005029 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005030 newnp = &(array.tbl[i]);
5031 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5032 newnp->next = array.ht[h];
5033 newnp->key = oldnp->key;
5034 newnp->data = oldnp->data;
5035 newnp->from = &(array.ht[h]);
5036 array.ht[h] = newnp;
5037 }
5038 free(x2a->tbl);
5039 *x2a = array;
5040 }
5041 /* Insert the new data */
5042 h = ph & (x2a->size-1);
5043 np = &(x2a->tbl[x2a->count++]);
5044 np->key = key;
5045 np->data = data;
5046 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5047 np->next = x2a->ht[h];
5048 x2a->ht[h] = np;
5049 np->from = &(x2a->ht[h]);
5050 return 1;
5051}
5052
5053/* Return a pointer to data assigned to the given key. Return NULL
5054** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005055struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005056{
drh01f75f22013-10-02 20:46:30 +00005057 unsigned h;
drh75897232000-05-29 14:26:00 +00005058 x2node *np;
5059
5060 if( x2a==0 ) return 0;
5061 h = strhash(key) & (x2a->size-1);
5062 np = x2a->ht[h];
5063 while( np ){
5064 if( strcmp(np->key,key)==0 ) break;
5065 np = np->next;
5066 }
5067 return np ? np->data : 0;
5068}
5069
5070/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005071struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005072{
5073 struct symbol *data;
5074 if( x2a && n>0 && n<=x2a->count ){
5075 data = x2a->tbl[n-1].data;
5076 }else{
5077 data = 0;
5078 }
5079 return data;
5080}
5081
5082/* Return the size of the array */
5083int Symbol_count()
5084{
5085 return x2a ? x2a->count : 0;
5086}
5087
5088/* Return an array of pointers to all data in the table.
5089** The array is obtained from malloc. Return NULL if memory allocation
5090** problems, or if the array is empty. */
5091struct symbol **Symbol_arrayof()
5092{
5093 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005094 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005095 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005096 arrSize = x2a->count;
5097 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005098 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005099 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005100 }
5101 return array;
5102}
5103
5104/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005105int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005106{
icculus9e44cf12010-02-14 17:14:22 +00005107 const struct config *a = (struct config *) _a;
5108 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005109 int x;
5110 x = a->rp->index - b->rp->index;
5111 if( x==0 ) x = a->dot - b->dot;
5112 return x;
5113}
5114
5115/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005116PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005117{
5118 int rc;
5119 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5120 rc = a->rp->index - b->rp->index;
5121 if( rc==0 ) rc = a->dot - b->dot;
5122 }
5123 if( rc==0 ){
5124 if( a ) rc = 1;
5125 if( b ) rc = -1;
5126 }
5127 return rc;
5128}
5129
5130/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005131PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005132{
drh01f75f22013-10-02 20:46:30 +00005133 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005134 while( a ){
5135 h = h*571 + a->rp->index*37 + a->dot;
5136 a = a->bp;
5137 }
5138 return h;
5139}
5140
5141/* Allocate a new state structure */
5142struct state *State_new()
5143{
icculus9e44cf12010-02-14 17:14:22 +00005144 struct state *newstate;
5145 newstate = (struct state *)calloc(1, sizeof(struct state) );
5146 MemoryCheck(newstate);
5147 return newstate;
drh75897232000-05-29 14:26:00 +00005148}
5149
5150/* There is one instance of the following structure for each
5151** associative array of type "x3".
5152*/
5153struct s_x3 {
5154 int size; /* The number of available slots. */
5155 /* Must be a power of 2 greater than or */
5156 /* equal to 1 */
5157 int count; /* Number of currently slots filled */
5158 struct s_x3node *tbl; /* The data stored here */
5159 struct s_x3node **ht; /* Hash table for lookups */
5160};
5161
5162/* There is one instance of this structure for every data element
5163** in an associative array of type "x3".
5164*/
5165typedef struct s_x3node {
5166 struct state *data; /* The data */
5167 struct config *key; /* The key */
5168 struct s_x3node *next; /* Next entry with the same hash */
5169 struct s_x3node **from; /* Previous link */
5170} x3node;
5171
5172/* There is only one instance of the array, which is the following */
5173static struct s_x3 *x3a;
5174
5175/* Allocate a new associative array */
5176void State_init(){
5177 if( x3a ) return;
5178 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5179 if( x3a ){
5180 x3a->size = 128;
5181 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005182 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005183 if( x3a->tbl==0 ){
5184 free(x3a);
5185 x3a = 0;
5186 }else{
5187 int i;
5188 x3a->ht = (x3node**)&(x3a->tbl[128]);
5189 for(i=0; i<128; i++) x3a->ht[i] = 0;
5190 }
5191 }
5192}
5193/* Insert a new record into the array. Return TRUE if successful.
5194** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005195int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005196{
5197 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005198 unsigned h;
5199 unsigned ph;
drh75897232000-05-29 14:26:00 +00005200
5201 if( x3a==0 ) return 0;
5202 ph = statehash(key);
5203 h = ph & (x3a->size-1);
5204 np = x3a->ht[h];
5205 while( np ){
5206 if( statecmp(np->key,key)==0 ){
5207 /* An existing entry with the same key is found. */
5208 /* Fail because overwrite is not allows. */
5209 return 0;
5210 }
5211 np = np->next;
5212 }
5213 if( x3a->count>=x3a->size ){
5214 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005215 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005216 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005217 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005218 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005219 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005220 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005221 array.ht = (x3node**)&(array.tbl[arrSize]);
5222 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005223 for(i=0; i<x3a->count; i++){
5224 x3node *oldnp, *newnp;
5225 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005226 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005227 newnp = &(array.tbl[i]);
5228 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5229 newnp->next = array.ht[h];
5230 newnp->key = oldnp->key;
5231 newnp->data = oldnp->data;
5232 newnp->from = &(array.ht[h]);
5233 array.ht[h] = newnp;
5234 }
5235 free(x3a->tbl);
5236 *x3a = array;
5237 }
5238 /* Insert the new data */
5239 h = ph & (x3a->size-1);
5240 np = &(x3a->tbl[x3a->count++]);
5241 np->key = key;
5242 np->data = data;
5243 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5244 np->next = x3a->ht[h];
5245 x3a->ht[h] = np;
5246 np->from = &(x3a->ht[h]);
5247 return 1;
5248}
5249
5250/* Return a pointer to data assigned to the given key. Return NULL
5251** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005252struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005253{
drh01f75f22013-10-02 20:46:30 +00005254 unsigned h;
drh75897232000-05-29 14:26:00 +00005255 x3node *np;
5256
5257 if( x3a==0 ) return 0;
5258 h = statehash(key) & (x3a->size-1);
5259 np = x3a->ht[h];
5260 while( np ){
5261 if( statecmp(np->key,key)==0 ) break;
5262 np = np->next;
5263 }
5264 return np ? np->data : 0;
5265}
5266
5267/* Return an array of pointers to all data in the table.
5268** The array is obtained from malloc. Return NULL if memory allocation
5269** problems, or if the array is empty. */
5270struct state **State_arrayof()
5271{
5272 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005273 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005274 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005275 arrSize = x3a->count;
5276 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005277 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005278 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005279 }
5280 return array;
5281}
5282
5283/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005284PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005285{
drh01f75f22013-10-02 20:46:30 +00005286 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005287 h = h*571 + a->rp->index*37 + a->dot;
5288 return h;
5289}
5290
5291/* There is one instance of the following structure for each
5292** associative array of type "x4".
5293*/
5294struct s_x4 {
5295 int size; /* The number of available slots. */
5296 /* Must be a power of 2 greater than or */
5297 /* equal to 1 */
5298 int count; /* Number of currently slots filled */
5299 struct s_x4node *tbl; /* The data stored here */
5300 struct s_x4node **ht; /* Hash table for lookups */
5301};
5302
5303/* There is one instance of this structure for every data element
5304** in an associative array of type "x4".
5305*/
5306typedef struct s_x4node {
5307 struct config *data; /* The data */
5308 struct s_x4node *next; /* Next entry with the same hash */
5309 struct s_x4node **from; /* Previous link */
5310} x4node;
5311
5312/* There is only one instance of the array, which is the following */
5313static struct s_x4 *x4a;
5314
5315/* Allocate a new associative array */
5316void Configtable_init(){
5317 if( x4a ) return;
5318 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5319 if( x4a ){
5320 x4a->size = 64;
5321 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005322 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005323 if( x4a->tbl==0 ){
5324 free(x4a);
5325 x4a = 0;
5326 }else{
5327 int i;
5328 x4a->ht = (x4node**)&(x4a->tbl[64]);
5329 for(i=0; i<64; i++) x4a->ht[i] = 0;
5330 }
5331 }
5332}
5333/* Insert a new record into the array. Return TRUE if successful.
5334** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005335int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005336{
5337 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005338 unsigned h;
5339 unsigned ph;
drh75897232000-05-29 14:26:00 +00005340
5341 if( x4a==0 ) return 0;
5342 ph = confighash(data);
5343 h = ph & (x4a->size-1);
5344 np = x4a->ht[h];
5345 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005346 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005347 /* An existing entry with the same key is found. */
5348 /* Fail because overwrite is not allows. */
5349 return 0;
5350 }
5351 np = np->next;
5352 }
5353 if( x4a->count>=x4a->size ){
5354 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005355 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005356 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005357 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005358 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005359 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005360 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005361 array.ht = (x4node**)&(array.tbl[arrSize]);
5362 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005363 for(i=0; i<x4a->count; i++){
5364 x4node *oldnp, *newnp;
5365 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005366 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005367 newnp = &(array.tbl[i]);
5368 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5369 newnp->next = array.ht[h];
5370 newnp->data = oldnp->data;
5371 newnp->from = &(array.ht[h]);
5372 array.ht[h] = newnp;
5373 }
5374 free(x4a->tbl);
5375 *x4a = array;
5376 }
5377 /* Insert the new data */
5378 h = ph & (x4a->size-1);
5379 np = &(x4a->tbl[x4a->count++]);
5380 np->data = data;
5381 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5382 np->next = x4a->ht[h];
5383 x4a->ht[h] = np;
5384 np->from = &(x4a->ht[h]);
5385 return 1;
5386}
5387
5388/* Return a pointer to data assigned to the given key. Return NULL
5389** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005390struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005391{
5392 int h;
5393 x4node *np;
5394
5395 if( x4a==0 ) return 0;
5396 h = confighash(key) & (x4a->size-1);
5397 np = x4a->ht[h];
5398 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005399 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005400 np = np->next;
5401 }
5402 return np ? np->data : 0;
5403}
5404
5405/* Remove all data from the table. Pass each data to the function "f"
5406** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005407void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005408{
5409 int i;
5410 if( x4a==0 || x4a->count==0 ) return;
5411 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5412 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5413 x4a->count = 0;
5414 return;
5415}