blob: 2ad36eec4a195005eba192bc322d79ab2815746e [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;
344 struct action *next; /* Next action for this state */
345 struct action *collide; /* Next action with the same hash */
346};
347
348/* Each state of the generated parser's finite state machine
349** is encoded as an instance of the following structure. */
350struct state {
351 struct config *bp; /* The basis configurations for this state */
352 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000353 int statenum; /* Sequential number for this state */
drh711c9812016-05-23 14:24:31 +0000354 struct action *ap; /* List of actions for this state */
drh8b582012003-10-21 13:16:03 +0000355 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
356 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000357 int iDfltReduce; /* Default action is to REDUCE by this rule */
358 struct rule *pDfltReduce;/* The default REDUCE rule. */
359 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000360};
drh8b582012003-10-21 13:16:03 +0000361#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000362
363/* A followset propagation link indicates that the contents of one
364** configuration followset should be propagated to another whenever
365** the first changes. */
366struct plink {
367 struct config *cfp; /* The configuration to which linked */
368 struct plink *next; /* The next propagate link */
369};
370
371/* The state vector for the entire parser generator is recorded as
372** follows. (LEMON uses no global variables and makes little use of
373** static variables. Fields in the following structure can be thought
374** of as begin global variables in the program.) */
375struct lemon {
376 struct state **sorted; /* Table of states sorted by state number */
377 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000378 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000379 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000380 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000381 int nrule; /* Number of rules */
382 int nsymbol; /* Number of terminal and nonterminal symbols */
383 int nterminal; /* Number of terminal symbols */
384 struct symbol **symbols; /* Sorted array of pointers to symbols */
385 int errorcnt; /* Number of errors */
386 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000387 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000388 char *name; /* Name of the generated parser */
389 char *arg; /* Declaration of the 3th argument to parser */
390 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000391 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000392 char *start; /* Name of the start symbol for the grammar */
393 char *stacksize; /* Size of the parser stack */
394 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000395 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000396 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000397 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000398 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000399 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000400 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000401 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000402 char *filename; /* Name of the input file */
403 char *outname; /* Name of the current output file */
404 char *tokenprefix; /* A prefix added to token names in the .h file */
405 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000406 int nactiontab; /* Number of entries in the yy_action[] table */
407 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000408 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000409 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000410 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000411 char *argv0; /* Name of the program */
412};
413
414#define MemoryCheck(X) if((X)==0){ \
415 extern void memory_error(); \
416 memory_error(); \
417}
418
419/**************** From the file "table.h" *********************************/
420/*
421** All code in this file has been automatically generated
422** from a specification in the file
423** "table.q"
424** by the associative array code building program "aagen".
425** Do not edit this file! Instead, edit the specification
426** file, then rerun aagen.
427*/
428/*
429** Code for processing tables in the LEMON parser generator.
430*/
drh75897232000-05-29 14:26:00 +0000431/* Routines for handling a strings */
432
icculus9e44cf12010-02-14 17:14:22 +0000433const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000434
icculus9e44cf12010-02-14 17:14:22 +0000435void Strsafe_init(void);
436int Strsafe_insert(const char *);
437const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000438
439/* Routines for handling symbols of the grammar */
440
icculus9e44cf12010-02-14 17:14:22 +0000441struct symbol *Symbol_new(const char *);
442int Symbolcmpp(const void *, const void *);
443void Symbol_init(void);
444int Symbol_insert(struct symbol *, const char *);
445struct symbol *Symbol_find(const char *);
446struct symbol *Symbol_Nth(int);
447int Symbol_count(void);
448struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000449
450/* Routines to manage the state table */
451
icculus9e44cf12010-02-14 17:14:22 +0000452int Configcmp(const char *, const char *);
453struct state *State_new(void);
454void State_init(void);
455int State_insert(struct state *, struct config *);
456struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000457struct state **State_arrayof(/* */);
458
459/* Routines used for efficiency in Configlist_add */
460
icculus9e44cf12010-02-14 17:14:22 +0000461void Configtable_init(void);
462int Configtable_insert(struct config *);
463struct config *Configtable_find(struct config *);
464void Configtable_clear(int(*)(struct config *));
465
drh75897232000-05-29 14:26:00 +0000466/****************** From the file "action.c" *******************************/
467/*
468** Routines processing parser actions in the LEMON parser generator.
469*/
470
471/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000472static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000473 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000474 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000475
476 if( freelist==0 ){
477 int i;
478 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000479 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000480 if( freelist==0 ){
481 fprintf(stderr,"Unable to allocate memory for a new parser action.");
482 exit(1);
483 }
484 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
485 freelist[amt-1].next = 0;
486 }
icculus9e44cf12010-02-14 17:14:22 +0000487 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000488 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000489 return newaction;
drh75897232000-05-29 14:26:00 +0000490}
491
drhe9278182007-07-18 18:16:29 +0000492/* Compare two actions for sorting purposes. Return negative, zero, or
493** positive if the first action is less than, equal to, or greater than
494** the first
495*/
496static int actioncmp(
497 struct action *ap1,
498 struct action *ap2
499){
drh75897232000-05-29 14:26:00 +0000500 int rc;
501 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000502 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000503 rc = (int)ap1->type - (int)ap2->type;
504 }
drh3bd48ab2015-09-07 18:23:37 +0000505 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000506 rc = ap1->x.rp->index - ap2->x.rp->index;
507 }
drhe594bc32009-11-03 13:02:25 +0000508 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000509 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000510 }
drh75897232000-05-29 14:26:00 +0000511 return rc;
512}
513
514/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000515static struct action *Action_sort(
516 struct action *ap
517){
518 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
519 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000520 return ap;
521}
522
icculus9e44cf12010-02-14 17:14:22 +0000523void Action_add(
524 struct action **app,
525 enum e_action type,
526 struct symbol *sp,
527 char *arg
528){
529 struct action *newaction;
530 newaction = Action_new();
531 newaction->next = *app;
532 *app = newaction;
533 newaction->type = type;
534 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000535 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000536 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000537 }else{
icculus9e44cf12010-02-14 17:14:22 +0000538 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000539 }
540}
drh8b582012003-10-21 13:16:03 +0000541/********************** New code to implement the "acttab" module ***********/
542/*
543** This module implements routines use to construct the yy_action[] table.
544*/
545
546/*
547** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000548** the following structure.
549**
550** The yy_action table maps the pair (state_number, lookahead) into an
551** action_number. The table is an array of integers pairs. The state_number
552** determines an initial offset into the yy_action array. The lookahead
553** value is then added to this initial offset to get an index X into the
554** yy_action array. If the aAction[X].lookahead equals the value of the
555** of the lookahead input, then the value of the action_number output is
556** aAction[X].action. If the lookaheads do not match then the
557** default action for the state_number is returned.
558**
559** All actions associated with a single state_number are first entered
560** into aLookahead[] using multiple calls to acttab_action(). Then the
561** actions for that single state_number are placed into the aAction[]
562** array with a single call to acttab_insert(). The acttab_insert() call
563** also resets the aLookahead[] array in preparation for the next
564** state number.
drh8b582012003-10-21 13:16:03 +0000565*/
icculus9e44cf12010-02-14 17:14:22 +0000566struct lookahead_action {
567 int lookahead; /* Value of the lookahead token */
568 int action; /* Action to take on the given lookahead */
569};
drh8b582012003-10-21 13:16:03 +0000570typedef struct acttab acttab;
571struct acttab {
572 int nAction; /* Number of used slots in aAction[] */
573 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000574 struct lookahead_action
575 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000576 *aLookahead; /* A single new transaction set */
577 int mnLookahead; /* Minimum aLookahead[].lookahead */
578 int mnAction; /* Action associated with mnLookahead */
579 int mxLookahead; /* Maximum aLookahead[].lookahead */
580 int nLookahead; /* Used slots in aLookahead[] */
581 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
582};
583
584/* Return the number of entries in the yy_action table */
585#define acttab_size(X) ((X)->nAction)
586
587/* The value for the N-th entry in yy_action */
588#define acttab_yyaction(X,N) ((X)->aAction[N].action)
589
590/* The value for the N-th entry in yy_lookahead */
591#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
592
593/* Free all memory associated with the given acttab */
594void acttab_free(acttab *p){
595 free( p->aAction );
596 free( p->aLookahead );
597 free( p );
598}
599
600/* Allocate a new acttab structure */
601acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000602 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000603 if( p==0 ){
604 fprintf(stderr,"Unable to allocate memory for a new acttab.");
605 exit(1);
606 }
607 memset(p, 0, sizeof(*p));
608 return p;
609}
610
drh8dc3e8f2010-01-07 03:53:03 +0000611/* Add a new action to the current transaction set.
612**
613** This routine is called once for each lookahead for a particular
614** state.
drh8b582012003-10-21 13:16:03 +0000615*/
616void acttab_action(acttab *p, int lookahead, int action){
617 if( p->nLookahead>=p->nLookaheadAlloc ){
618 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000619 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000620 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
621 if( p->aLookahead==0 ){
622 fprintf(stderr,"malloc failed\n");
623 exit(1);
624 }
625 }
626 if( p->nLookahead==0 ){
627 p->mxLookahead = lookahead;
628 p->mnLookahead = lookahead;
629 p->mnAction = action;
630 }else{
631 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
632 if( p->mnLookahead>lookahead ){
633 p->mnLookahead = lookahead;
634 p->mnAction = action;
635 }
636 }
637 p->aLookahead[p->nLookahead].lookahead = lookahead;
638 p->aLookahead[p->nLookahead].action = action;
639 p->nLookahead++;
640}
641
642/*
643** Add the transaction set built up with prior calls to acttab_action()
644** into the current action table. Then reset the transaction set back
645** to an empty set in preparation for a new round of acttab_action() calls.
646**
647** Return the offset into the action table of the new transaction.
648*/
649int acttab_insert(acttab *p){
650 int i, j, k, n;
651 assert( p->nLookahead>0 );
652
653 /* Make sure we have enough space to hold the expanded action table
654 ** in the worst case. The worst case occurs if the transaction set
655 ** must be appended to the current action table
656 */
drh784d86f2004-02-19 18:41:53 +0000657 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000658 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000659 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000660 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000661 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000662 sizeof(p->aAction[0])*p->nActionAlloc);
663 if( p->aAction==0 ){
664 fprintf(stderr,"malloc failed\n");
665 exit(1);
666 }
drhfdbf9282003-10-21 16:34:41 +0000667 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000668 p->aAction[i].lookahead = -1;
669 p->aAction[i].action = -1;
670 }
671 }
672
drh8dc3e8f2010-01-07 03:53:03 +0000673 /* Scan the existing action table looking for an offset that is a
674 ** duplicate of the current transaction set. Fall out of the loop
675 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000676 **
677 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
678 */
drh8dc3e8f2010-01-07 03:53:03 +0000679 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000680 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000681 /* All lookaheads and actions in the aLookahead[] transaction
682 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000683 if( p->aAction[i].action!=p->mnAction ) continue;
684 for(j=0; j<p->nLookahead; j++){
685 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
686 if( k<0 || k>=p->nAction ) break;
687 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
688 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
689 }
690 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000691
692 /* No possible lookahead value that is not in the aLookahead[]
693 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000694 n = 0;
695 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000696 if( p->aAction[j].lookahead<0 ) continue;
697 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000698 }
drhfdbf9282003-10-21 16:34:41 +0000699 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000700 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000701 }
drh8b582012003-10-21 13:16:03 +0000702 }
703 }
drh8dc3e8f2010-01-07 03:53:03 +0000704
705 /* If no existing offsets exactly match the current transaction, find an
706 ** an empty offset in the aAction[] table in which we can add the
707 ** aLookahead[] transaction.
708 */
drhf16371d2009-11-03 19:18:31 +0000709 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000710 /* Look for holes in the aAction[] table that fit the current
711 ** aLookahead[] transaction. Leave i set to the offset of the hole.
712 ** If no holes are found, i is left at p->nAction, which means the
713 ** transaction will be appended. */
714 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000715 if( p->aAction[i].lookahead<0 ){
716 for(j=0; j<p->nLookahead; j++){
717 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
718 if( k<0 ) break;
719 if( p->aAction[k].lookahead>=0 ) break;
720 }
721 if( j<p->nLookahead ) continue;
722 for(j=0; j<p->nAction; j++){
723 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
724 }
725 if( j==p->nAction ){
726 break; /* Fits in empty slots */
727 }
728 }
729 }
730 }
drh8b582012003-10-21 13:16:03 +0000731 /* Insert transaction set at index i. */
732 for(j=0; j<p->nLookahead; j++){
733 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
734 p->aAction[k] = p->aLookahead[j];
735 if( k>=p->nAction ) p->nAction = k+1;
736 }
737 p->nLookahead = 0;
738
739 /* Return the offset that is added to the lookahead in order to get the
740 ** index into yy_action of the action */
741 return i - p->mnLookahead;
742}
743
drh75897232000-05-29 14:26:00 +0000744/********************** From the file "build.c" *****************************/
745/*
746** Routines to construction the finite state machine for the LEMON
747** parser generator.
748*/
749
750/* Find a precedence symbol of every rule in the grammar.
751**
752** Those rules which have a precedence symbol coded in the input
753** grammar using the "[symbol]" construct will already have the
754** rp->precsym field filled. Other rules take as their precedence
755** symbol the first RHS symbol with a defined precedence. If there
756** are not RHS symbols with a defined precedence, the precedence
757** symbol field is left blank.
758*/
icculus9e44cf12010-02-14 17:14:22 +0000759void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000760{
761 struct rule *rp;
762 for(rp=xp->rule; rp; rp=rp->next){
763 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000764 int i, j;
765 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
766 struct symbol *sp = rp->rhs[i];
767 if( sp->type==MULTITERMINAL ){
768 for(j=0; j<sp->nsubsym; j++){
769 if( sp->subsym[j]->prec>=0 ){
770 rp->precsym = sp->subsym[j];
771 break;
772 }
773 }
774 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000775 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000776 }
drh75897232000-05-29 14:26:00 +0000777 }
778 }
779 }
780 return;
781}
782
783/* Find all nonterminals which will generate the empty string.
784** Then go back and compute the first sets of every nonterminal.
785** The first set is the set of all terminal symbols which can begin
786** a string generated by that nonterminal.
787*/
icculus9e44cf12010-02-14 17:14:22 +0000788void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000789{
drhfd405312005-11-06 04:06:59 +0000790 int i, j;
drh75897232000-05-29 14:26:00 +0000791 struct rule *rp;
792 int progress;
793
794 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000795 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000796 }
797 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
798 lemp->symbols[i]->firstset = SetNew();
799 }
800
801 /* First compute all lambdas */
802 do{
803 progress = 0;
804 for(rp=lemp->rule; rp; rp=rp->next){
805 if( rp->lhs->lambda ) continue;
806 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000807 struct symbol *sp = rp->rhs[i];
808 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
809 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000810 }
811 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000812 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000813 progress = 1;
814 }
815 }
816 }while( progress );
817
818 /* Now compute all first sets */
819 do{
820 struct symbol *s1, *s2;
821 progress = 0;
822 for(rp=lemp->rule; rp; rp=rp->next){
823 s1 = rp->lhs;
824 for(i=0; i<rp->nrhs; i++){
825 s2 = rp->rhs[i];
826 if( s2->type==TERMINAL ){
827 progress += SetAdd(s1->firstset,s2->index);
828 break;
drhfd405312005-11-06 04:06:59 +0000829 }else if( s2->type==MULTITERMINAL ){
830 for(j=0; j<s2->nsubsym; j++){
831 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
832 }
833 break;
drhf2f105d2012-08-20 15:53:54 +0000834 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000835 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000836 }else{
drh75897232000-05-29 14:26:00 +0000837 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000838 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000839 }
drh75897232000-05-29 14:26:00 +0000840 }
841 }
842 }while( progress );
843 return;
844}
845
846/* Compute all LR(0) states for the grammar. Links
847** are added to between some states so that the LR(1) follow sets
848** can be computed later.
849*/
icculus9e44cf12010-02-14 17:14:22 +0000850PRIVATE struct state *getstate(struct lemon *); /* forward reference */
851void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000852{
853 struct symbol *sp;
854 struct rule *rp;
855
856 Configlist_init();
857
858 /* Find the start symbol */
859 if( lemp->start ){
860 sp = Symbol_find(lemp->start);
861 if( sp==0 ){
862 ErrorMsg(lemp->filename,0,
863"The specified start symbol \"%s\" is not \
864in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000865symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000866 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000867 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000868 }
869 }else{
drh4ef07702016-03-16 19:45:54 +0000870 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000871 }
872
873 /* Make sure the start symbol doesn't occur on the right-hand side of
874 ** any rule. Report an error if it does. (YACC would generate a new
875 ** start symbol in this case.) */
876 for(rp=lemp->rule; rp; rp=rp->next){
877 int i;
878 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000879 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000880 ErrorMsg(lemp->filename,0,
881"The start symbol \"%s\" occurs on the \
882right-hand side of a rule. This will result in a parser which \
883does not work properly.",sp->name);
884 lemp->errorcnt++;
885 }
886 }
887 }
888
889 /* The basis configuration set for the first state
890 ** is all rules which have the start symbol as their
891 ** left-hand side */
892 for(rp=sp->rule; rp; rp=rp->nextlhs){
893 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000894 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000895 newcfp = Configlist_addbasis(rp,0);
896 SetAdd(newcfp->fws,0);
897 }
898
899 /* Compute the first state. All other states will be
900 ** computed automatically during the computation of the first one.
901 ** The returned pointer to the first state is not used. */
902 (void)getstate(lemp);
903 return;
904}
905
906/* Return a pointer to a state which is described by the configuration
907** list which has been built from calls to Configlist_add.
908*/
icculus9e44cf12010-02-14 17:14:22 +0000909PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
910PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000911{
912 struct config *cfp, *bp;
913 struct state *stp;
914
915 /* Extract the sorted basis of the new state. The basis was constructed
916 ** by prior calls to "Configlist_addbasis()". */
917 Configlist_sortbasis();
918 bp = Configlist_basis();
919
920 /* Get a state with the same basis */
921 stp = State_find(bp);
922 if( stp ){
923 /* A state with the same basis already exists! Copy all the follow-set
924 ** propagation links from the state under construction into the
925 ** preexisting state, then return a pointer to the preexisting state */
926 struct config *x, *y;
927 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
928 Plink_copy(&y->bplp,x->bplp);
929 Plink_delete(x->fplp);
930 x->fplp = x->bplp = 0;
931 }
932 cfp = Configlist_return();
933 Configlist_eat(cfp);
934 }else{
935 /* This really is a new state. Construct all the details */
936 Configlist_closure(lemp); /* Compute the configuration closure */
937 Configlist_sort(); /* Sort the configuration closure */
938 cfp = Configlist_return(); /* Get a pointer to the config list */
939 stp = State_new(); /* A new state structure */
940 MemoryCheck(stp);
941 stp->bp = bp; /* Remember the configuration basis */
942 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000943 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000944 stp->ap = 0; /* No actions, yet. */
945 State_insert(stp,stp->bp); /* Add to the state table */
946 buildshifts(lemp,stp); /* Recursively compute successor states */
947 }
948 return stp;
949}
950
drhfd405312005-11-06 04:06:59 +0000951/*
952** Return true if two symbols are the same.
953*/
icculus9e44cf12010-02-14 17:14:22 +0000954int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000955{
956 int i;
957 if( a==b ) return 1;
958 if( a->type!=MULTITERMINAL ) return 0;
959 if( b->type!=MULTITERMINAL ) return 0;
960 if( a->nsubsym!=b->nsubsym ) return 0;
961 for(i=0; i<a->nsubsym; i++){
962 if( a->subsym[i]!=b->subsym[i] ) return 0;
963 }
964 return 1;
965}
966
drh75897232000-05-29 14:26:00 +0000967/* Construct all successor states to the given state. A "successor"
968** state is any state which can be reached by a shift action.
969*/
icculus9e44cf12010-02-14 17:14:22 +0000970PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000971{
972 struct config *cfp; /* For looping thru the config closure of "stp" */
973 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000974 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000975 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
976 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
977 struct state *newstp; /* A pointer to a successor state */
978
979 /* Each configuration becomes complete after it contibutes to a successor
980 ** state. Initially, all configurations are incomplete */
981 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
982
983 /* Loop through all configurations of the state "stp" */
984 for(cfp=stp->cfp; cfp; cfp=cfp->next){
985 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
986 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
987 Configlist_reset(); /* Reset the new config set */
988 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
989
990 /* For every configuration in the state "stp" which has the symbol "sp"
991 ** following its dot, add the same configuration to the basis set under
992 ** construction but with the dot shifted one symbol to the right. */
993 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
994 if( bcfp->status==COMPLETE ) continue; /* Already used */
995 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
996 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000997 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000998 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000999 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
1000 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +00001001 }
1002
1003 /* Get a pointer to the state described by the basis configuration set
1004 ** constructed in the preceding loop */
1005 newstp = getstate(lemp);
1006
1007 /* The state "newstp" is reached from the state "stp" by a shift action
1008 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001009 if( sp->type==MULTITERMINAL ){
1010 int i;
1011 for(i=0; i<sp->nsubsym; i++){
1012 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1013 }
1014 }else{
1015 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1016 }
drh75897232000-05-29 14:26:00 +00001017 }
1018}
1019
1020/*
1021** Construct the propagation links
1022*/
icculus9e44cf12010-02-14 17:14:22 +00001023void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001024{
1025 int i;
1026 struct config *cfp, *other;
1027 struct state *stp;
1028 struct plink *plp;
1029
1030 /* Housekeeping detail:
1031 ** Add to every propagate link a pointer back to the state to
1032 ** which the link is attached. */
1033 for(i=0; i<lemp->nstate; i++){
1034 stp = lemp->sorted[i];
1035 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1036 cfp->stp = stp;
1037 }
1038 }
1039
1040 /* Convert all backlinks into forward links. Only the forward
1041 ** links are used in the follow-set computation. */
1042 for(i=0; i<lemp->nstate; i++){
1043 stp = lemp->sorted[i];
1044 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1045 for(plp=cfp->bplp; plp; plp=plp->next){
1046 other = plp->cfp;
1047 Plink_add(&other->fplp,cfp);
1048 }
1049 }
1050 }
1051}
1052
1053/* Compute all followsets.
1054**
1055** A followset is the set of all symbols which can come immediately
1056** after a configuration.
1057*/
icculus9e44cf12010-02-14 17:14:22 +00001058void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001059{
1060 int i;
1061 struct config *cfp;
1062 struct plink *plp;
1063 int progress;
1064 int change;
1065
1066 for(i=0; i<lemp->nstate; i++){
1067 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1068 cfp->status = INCOMPLETE;
1069 }
1070 }
1071
1072 do{
1073 progress = 0;
1074 for(i=0; i<lemp->nstate; i++){
1075 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1076 if( cfp->status==COMPLETE ) continue;
1077 for(plp=cfp->fplp; plp; plp=plp->next){
1078 change = SetUnion(plp->cfp->fws,cfp->fws);
1079 if( change ){
1080 plp->cfp->status = INCOMPLETE;
1081 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001082 }
1083 }
drh75897232000-05-29 14:26:00 +00001084 cfp->status = COMPLETE;
1085 }
1086 }
1087 }while( progress );
1088}
1089
drh3cb2f6e2012-01-09 14:19:05 +00001090static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001091
1092/* Compute the reduce actions, and resolve conflicts.
1093*/
icculus9e44cf12010-02-14 17:14:22 +00001094void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001095{
1096 int i,j;
1097 struct config *cfp;
1098 struct state *stp;
1099 struct symbol *sp;
1100 struct rule *rp;
1101
1102 /* Add all of the reduce actions
1103 ** A reduce action is added for each element of the followset of
1104 ** a configuration which has its dot at the extreme right.
1105 */
1106 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1107 stp = lemp->sorted[i];
1108 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1109 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1110 for(j=0; j<lemp->nterminal; j++){
1111 if( SetFind(cfp->fws,j) ){
1112 /* Add a reduce action to the state "stp" which will reduce by the
1113 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001114 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001115 }
drhf2f105d2012-08-20 15:53:54 +00001116 }
drh75897232000-05-29 14:26:00 +00001117 }
1118 }
1119 }
1120
1121 /* Add the accepting token */
1122 if( lemp->start ){
1123 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001124 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001125 }else{
drh4ef07702016-03-16 19:45:54 +00001126 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001127 }
1128 /* Add to the first state (which is always the starting state of the
1129 ** finite state machine) an action to ACCEPT if the lookahead is the
1130 ** start nonterminal. */
1131 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1132
1133 /* Resolve conflicts */
1134 for(i=0; i<lemp->nstate; i++){
1135 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001136 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001137 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001138 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001139 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001140 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1141 /* The two actions "ap" and "nap" have the same lookahead.
1142 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001143 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001144 }
1145 }
1146 }
1147
1148 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001149 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001150 for(i=0; i<lemp->nstate; i++){
1151 struct action *ap;
1152 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001153 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001154 }
1155 }
1156 for(rp=lemp->rule; rp; rp=rp->next){
1157 if( rp->canReduce ) continue;
1158 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1159 lemp->errorcnt++;
1160 }
1161}
1162
1163/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001164** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001165**
1166** NO LONGER TRUE:
1167** To resolve a conflict, first look to see if either action
1168** is on an error rule. In that case, take the action which
1169** is not associated with the error rule. If neither or both
1170** actions are associated with an error rule, then try to
1171** use precedence to resolve the conflict.
1172**
1173** If either action is a SHIFT, then it must be apx. This
1174** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1175*/
icculus9e44cf12010-02-14 17:14:22 +00001176static int resolve_conflict(
1177 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001178 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001179){
drh75897232000-05-29 14:26:00 +00001180 struct symbol *spx, *spy;
1181 int errcnt = 0;
1182 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001183 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001184 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001185 errcnt++;
1186 }
drh75897232000-05-29 14:26:00 +00001187 if( apx->type==SHIFT && apy->type==REDUCE ){
1188 spx = apx->sp;
1189 spy = apy->x.rp->precsym;
1190 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1191 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001192 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001193 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001194 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001195 apy->type = RD_RESOLVED;
1196 }else if( spx->prec<spy->prec ){
1197 apx->type = SH_RESOLVED;
1198 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1199 apy->type = RD_RESOLVED; /* associativity */
1200 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1201 apx->type = SH_RESOLVED;
1202 }else{
1203 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001204 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001205 }
1206 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1207 spx = apx->x.rp->precsym;
1208 spy = apy->x.rp->precsym;
1209 if( spx==0 || spy==0 || spx->prec<0 ||
1210 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001211 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001212 errcnt++;
1213 }else if( spx->prec>spy->prec ){
1214 apy->type = RD_RESOLVED;
1215 }else if( spx->prec<spy->prec ){
1216 apx->type = RD_RESOLVED;
1217 }
1218 }else{
drhb59499c2002-02-23 18:45:13 +00001219 assert(
1220 apx->type==SH_RESOLVED ||
1221 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001222 apx->type==SSCONFLICT ||
1223 apx->type==SRCONFLICT ||
1224 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001225 apy->type==SH_RESOLVED ||
1226 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001227 apy->type==SSCONFLICT ||
1228 apy->type==SRCONFLICT ||
1229 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001230 );
1231 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1232 ** REDUCEs on the list. If we reach this point it must be because
1233 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001234 }
1235 return errcnt;
1236}
1237/********************* From the file "configlist.c" *************************/
1238/*
1239** Routines to processing a configuration list and building a state
1240** in the LEMON parser generator.
1241*/
1242
1243static struct config *freelist = 0; /* List of free configurations */
1244static struct config *current = 0; /* Top of list of configurations */
1245static struct config **currentend = 0; /* Last on list of configs */
1246static struct config *basis = 0; /* Top of list of basis configs */
1247static struct config **basisend = 0; /* End of list of basis configs */
1248
1249/* Return a pointer to a new configuration */
1250PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001251 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001252 if( freelist==0 ){
1253 int i;
1254 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001255 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001256 if( freelist==0 ){
1257 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1258 exit(1);
1259 }
1260 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1261 freelist[amt-1].next = 0;
1262 }
icculus9e44cf12010-02-14 17:14:22 +00001263 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001264 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001265 return newcfg;
drh75897232000-05-29 14:26:00 +00001266}
1267
1268/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001269PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001270{
1271 old->next = freelist;
1272 freelist = old;
1273}
1274
1275/* Initialized the configuration list builder */
1276void Configlist_init(){
1277 current = 0;
1278 currentend = &current;
1279 basis = 0;
1280 basisend = &basis;
1281 Configtable_init();
1282 return;
1283}
1284
1285/* Initialized the configuration list builder */
1286void Configlist_reset(){
1287 current = 0;
1288 currentend = &current;
1289 basis = 0;
1290 basisend = &basis;
1291 Configtable_clear(0);
1292 return;
1293}
1294
1295/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001296struct config *Configlist_add(
1297 struct rule *rp, /* The rule */
1298 int dot /* Index into the RHS of the rule where the dot goes */
1299){
drh75897232000-05-29 14:26:00 +00001300 struct config *cfp, model;
1301
1302 assert( currentend!=0 );
1303 model.rp = rp;
1304 model.dot = dot;
1305 cfp = Configtable_find(&model);
1306 if( cfp==0 ){
1307 cfp = newconfig();
1308 cfp->rp = rp;
1309 cfp->dot = dot;
1310 cfp->fws = SetNew();
1311 cfp->stp = 0;
1312 cfp->fplp = cfp->bplp = 0;
1313 cfp->next = 0;
1314 cfp->bp = 0;
1315 *currentend = cfp;
1316 currentend = &cfp->next;
1317 Configtable_insert(cfp);
1318 }
1319 return cfp;
1320}
1321
1322/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001323struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001324{
1325 struct config *cfp, model;
1326
1327 assert( basisend!=0 );
1328 assert( currentend!=0 );
1329 model.rp = rp;
1330 model.dot = dot;
1331 cfp = Configtable_find(&model);
1332 if( cfp==0 ){
1333 cfp = newconfig();
1334 cfp->rp = rp;
1335 cfp->dot = dot;
1336 cfp->fws = SetNew();
1337 cfp->stp = 0;
1338 cfp->fplp = cfp->bplp = 0;
1339 cfp->next = 0;
1340 cfp->bp = 0;
1341 *currentend = cfp;
1342 currentend = &cfp->next;
1343 *basisend = cfp;
1344 basisend = &cfp->bp;
1345 Configtable_insert(cfp);
1346 }
1347 return cfp;
1348}
1349
1350/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001351void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001352{
1353 struct config *cfp, *newcfp;
1354 struct rule *rp, *newrp;
1355 struct symbol *sp, *xsp;
1356 int i, dot;
1357
1358 assert( currentend!=0 );
1359 for(cfp=current; cfp; cfp=cfp->next){
1360 rp = cfp->rp;
1361 dot = cfp->dot;
1362 if( dot>=rp->nrhs ) continue;
1363 sp = rp->rhs[dot];
1364 if( sp->type==NONTERMINAL ){
1365 if( sp->rule==0 && sp!=lemp->errsym ){
1366 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1367 sp->name);
1368 lemp->errorcnt++;
1369 }
1370 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1371 newcfp = Configlist_add(newrp,0);
1372 for(i=dot+1; i<rp->nrhs; i++){
1373 xsp = rp->rhs[i];
1374 if( xsp->type==TERMINAL ){
1375 SetAdd(newcfp->fws,xsp->index);
1376 break;
drhfd405312005-11-06 04:06:59 +00001377 }else if( xsp->type==MULTITERMINAL ){
1378 int k;
1379 for(k=0; k<xsp->nsubsym; k++){
1380 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1381 }
1382 break;
drhf2f105d2012-08-20 15:53:54 +00001383 }else{
drh75897232000-05-29 14:26:00 +00001384 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001385 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001386 }
1387 }
drh75897232000-05-29 14:26:00 +00001388 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1389 }
1390 }
1391 }
1392 return;
1393}
1394
1395/* Sort the configuration list */
1396void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001397 current = (struct config*)msort((char*)current,(char**)&(current->next),
1398 Configcmp);
drh75897232000-05-29 14:26:00 +00001399 currentend = 0;
1400 return;
1401}
1402
1403/* Sort the basis configuration list */
1404void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001405 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1406 Configcmp);
drh75897232000-05-29 14:26:00 +00001407 basisend = 0;
1408 return;
1409}
1410
1411/* Return a pointer to the head of the configuration list and
1412** reset the list */
1413struct config *Configlist_return(){
1414 struct config *old;
1415 old = current;
1416 current = 0;
1417 currentend = 0;
1418 return old;
1419}
1420
1421/* Return a pointer to the head of the configuration list and
1422** reset the list */
1423struct config *Configlist_basis(){
1424 struct config *old;
1425 old = basis;
1426 basis = 0;
1427 basisend = 0;
1428 return old;
1429}
1430
1431/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001432void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001433{
1434 struct config *nextcfp;
1435 for(; cfp; cfp=nextcfp){
1436 nextcfp = cfp->next;
1437 assert( cfp->fplp==0 );
1438 assert( cfp->bplp==0 );
1439 if( cfp->fws ) SetFree(cfp->fws);
1440 deleteconfig(cfp);
1441 }
1442 return;
1443}
1444/***************** From the file "error.c" *********************************/
1445/*
1446** Code for printing error message.
1447*/
1448
drhf9a2e7b2003-04-15 01:49:48 +00001449void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001450 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001451 fprintf(stderr, "%s:%d: ", filename, lineno);
1452 va_start(ap, format);
1453 vfprintf(stderr,format,ap);
1454 va_end(ap);
1455 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001456}
1457/**************** From the file "main.c" ************************************/
1458/*
1459** Main program file for the LEMON parser generator.
1460*/
1461
1462/* Report an out-of-memory condition and abort. This function
1463** is used mostly by the "MemoryCheck" macro in struct.h
1464*/
1465void memory_error(){
1466 fprintf(stderr,"Out of memory. Aborting...\n");
1467 exit(1);
1468}
1469
drh6d08b4d2004-07-20 12:45:22 +00001470static int nDefine = 0; /* Number of -D options on the command line */
1471static char **azDefine = 0; /* Name of the -D macros */
1472
1473/* This routine is called with the argument to each -D command-line option.
1474** Add the macro defined to the azDefine array.
1475*/
1476static void handle_D_option(char *z){
1477 char **paz;
1478 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001479 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001480 if( azDefine==0 ){
1481 fprintf(stderr,"out of memory\n");
1482 exit(1);
1483 }
1484 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001485 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001486 if( *paz==0 ){
1487 fprintf(stderr,"out of memory\n");
1488 exit(1);
1489 }
drh898799f2014-01-10 23:21:00 +00001490 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001491 for(z=*paz; *z && *z!='='; z++){}
1492 *z = 0;
1493}
1494
icculus3e143bd2010-02-14 00:48:49 +00001495static char *user_templatename = NULL;
1496static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001497 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001498 if( user_templatename==0 ){
1499 memory_error();
1500 }
drh898799f2014-01-10 23:21:00 +00001501 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001502}
drh75897232000-05-29 14:26:00 +00001503
drh711c9812016-05-23 14:24:31 +00001504/* Merge together to lists of rules ordered by rule.iRule */
drh4ef07702016-03-16 19:45:54 +00001505static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1506 struct rule *pFirst = 0;
1507 struct rule **ppPrev = &pFirst;
1508 while( pA && pB ){
1509 if( pA->iRule<pB->iRule ){
1510 *ppPrev = pA;
1511 ppPrev = &pA->next;
1512 pA = pA->next;
1513 }else{
1514 *ppPrev = pB;
1515 ppPrev = &pB->next;
1516 pB = pB->next;
1517 }
1518 }
1519 if( pA ){
1520 *ppPrev = pA;
1521 }else{
1522 *ppPrev = pB;
1523 }
1524 return pFirst;
1525}
1526
1527/*
1528** Sort a list of rules in order of increasing iRule value
1529*/
1530static struct rule *Rule_sort(struct rule *rp){
1531 int i;
1532 struct rule *pNext;
1533 struct rule *x[32];
1534 memset(x, 0, sizeof(x));
1535 while( rp ){
1536 pNext = rp->next;
1537 rp->next = 0;
1538 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1539 rp = Rule_merge(x[i], rp);
1540 x[i] = 0;
1541 }
1542 x[i] = rp;
1543 rp = pNext;
1544 }
1545 rp = 0;
1546 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1547 rp = Rule_merge(x[i], rp);
1548 }
1549 return rp;
1550}
1551
drhc75e0162015-09-07 02:23:02 +00001552/* forward reference */
1553static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1554
1555/* Print a single line of the "Parser Stats" output
1556*/
1557static void stats_line(const char *zLabel, int iValue){
1558 int nLabel = lemonStrlen(zLabel);
1559 printf(" %s%.*s %5d\n", zLabel,
1560 35-nLabel, "................................",
1561 iValue);
1562}
1563
drh75897232000-05-29 14:26:00 +00001564/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001565int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001566{
1567 static int version = 0;
1568 static int rpflag = 0;
1569 static int basisflag = 0;
1570 static int compress = 0;
1571 static int quiet = 0;
1572 static int statistics = 0;
1573 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001574 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001575 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001576 static struct s_options options[] = {
1577 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1578 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001579 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001580 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001581 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001582 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001583 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1584 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001585 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001586 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1587 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001588 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001589 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001590 {OPT_FLAG, "s", (char*)&statistics,
1591 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001592 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001593 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1594 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001595 {OPT_FLAG,0,0,0}
1596 };
1597 int i;
icculus42585cf2010-02-14 05:19:56 +00001598 int exitcode;
drh75897232000-05-29 14:26:00 +00001599 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001600 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001601
drhb0c86772000-06-02 23:21:26 +00001602 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001603 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001604 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001605 exit(0);
1606 }
drhb0c86772000-06-02 23:21:26 +00001607 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001608 fprintf(stderr,"Exactly one filename argument is required.\n");
1609 exit(1);
1610 }
drh954f6b42006-06-13 13:27:46 +00001611 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001612 lem.errorcnt = 0;
1613
1614 /* Initialize the machine */
1615 Strsafe_init();
1616 Symbol_init();
1617 State_init();
1618 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001619 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001620 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001621 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001622 Symbol_new("$");
1623 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001624 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001625
1626 /* Parse the input file */
1627 Parse(&lem);
1628 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001629 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001630 fprintf(stderr,"Empty grammar.\n");
1631 exit(1);
1632 }
1633
1634 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001635 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001636 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001637 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001638 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1639 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1640 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1641 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1642 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1643 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001644 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001645 lem.nterminal = i;
1646
drh711c9812016-05-23 14:24:31 +00001647 /* Assign sequential rule numbers. Start with 0. Put rules that have no
1648 ** reduce action C-code associated with them last, so that the switch()
1649 ** statement that selects reduction actions will have a smaller jump table.
1650 */
drh4ef07702016-03-16 19:45:54 +00001651 for(i=0, rp=lem.rule; rp; rp=rp->next){
1652 rp->iRule = rp->code ? i++ : -1;
1653 }
1654 for(rp=lem.rule; rp; rp=rp->next){
1655 if( rp->iRule<0 ) rp->iRule = i++;
1656 }
1657 lem.startRule = lem.rule;
1658 lem.rule = Rule_sort(lem.rule);
1659
drh75897232000-05-29 14:26:00 +00001660 /* Generate a reprint of the grammar, if requested on the command line */
1661 if( rpflag ){
1662 Reprint(&lem);
1663 }else{
1664 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001665 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001666
1667 /* Find the precedence for every production rule (that has one) */
1668 FindRulePrecedences(&lem);
1669
1670 /* Compute the lambda-nonterminals and the first-sets for every
1671 ** nonterminal */
1672 FindFirstSets(&lem);
1673
1674 /* Compute all LR(0) states. Also record follow-set propagation
1675 ** links so that the follow-set can be computed later */
1676 lem.nstate = 0;
1677 FindStates(&lem);
1678 lem.sorted = State_arrayof();
1679
1680 /* Tie up loose ends on the propagation links */
1681 FindLinks(&lem);
1682
1683 /* Compute the follow set of every reducible configuration */
1684 FindFollowSets(&lem);
1685
1686 /* Compute the action tables */
1687 FindActions(&lem);
1688
1689 /* Compress the action tables */
1690 if( compress==0 ) CompressTables(&lem);
1691
drhada354d2005-11-05 15:03:59 +00001692 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001693 ** occur at the end. This is an optimization that helps make the
1694 ** generated parser tables smaller. */
1695 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001696
drh75897232000-05-29 14:26:00 +00001697 /* Generate a report of the parser generated. (the "y.output" file) */
1698 if( !quiet ) ReportOutput(&lem);
1699
1700 /* Generate the source code for the parser */
1701 ReportTable(&lem, mhflag);
1702
1703 /* Produce a header file for use by the scanner. (This step is
1704 ** omitted if the "-m" option is used because makeheaders will
1705 ** generate the file for us.) */
1706 if( !mhflag ) ReportHeader(&lem);
1707 }
1708 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001709 printf("Parser statistics:\n");
1710 stats_line("terminal symbols", lem.nterminal);
1711 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1712 stats_line("total symbols", lem.nsymbol);
1713 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001714 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001715 stats_line("conflicts", lem.nconflict);
1716 stats_line("action table entries", lem.nactiontab);
1717 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001718 }
icculus8e158022010-02-16 16:09:03 +00001719 if( lem.nconflict > 0 ){
1720 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001721 }
1722
1723 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001724 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001725 exit(exitcode);
1726 return (exitcode);
drh75897232000-05-29 14:26:00 +00001727}
1728/******************** From the file "msort.c" *******************************/
1729/*
1730** A generic merge-sort program.
1731**
1732** USAGE:
1733** Let "ptr" be a pointer to some structure which is at the head of
1734** a null-terminated list. Then to sort the list call:
1735**
1736** ptr = msort(ptr,&(ptr->next),cmpfnc);
1737**
1738** In the above, "cmpfnc" is a pointer to a function which compares
1739** two instances of the structure and returns an integer, as in
1740** strcmp. The second argument is a pointer to the pointer to the
1741** second element of the linked list. This address is used to compute
1742** the offset to the "next" field within the structure. The offset to
1743** the "next" field must be constant for all structures in the list.
1744**
1745** The function returns a new pointer which is the head of the list
1746** after sorting.
1747**
1748** ALGORITHM:
1749** Merge-sort.
1750*/
1751
1752/*
1753** Return a pointer to the next structure in the linked list.
1754*/
drhd25d6922012-04-18 09:59:56 +00001755#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001756
1757/*
1758** Inputs:
1759** a: A sorted, null-terminated linked list. (May be null).
1760** b: A sorted, null-terminated linked list. (May be null).
1761** cmp: A pointer to the comparison function.
1762** offset: Offset in the structure to the "next" field.
1763**
1764** Return Value:
1765** A pointer to the head of a sorted list containing the elements
1766** of both a and b.
1767**
1768** Side effects:
1769** The "next" pointers for elements in the lists a and b are
1770** changed.
1771*/
drhe9278182007-07-18 18:16:29 +00001772static char *merge(
1773 char *a,
1774 char *b,
1775 int (*cmp)(const char*,const char*),
1776 int offset
1777){
drh75897232000-05-29 14:26:00 +00001778 char *ptr, *head;
1779
1780 if( a==0 ){
1781 head = b;
1782 }else if( b==0 ){
1783 head = a;
1784 }else{
drhe594bc32009-11-03 13:02:25 +00001785 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001786 ptr = a;
1787 a = NEXT(a);
1788 }else{
1789 ptr = b;
1790 b = NEXT(b);
1791 }
1792 head = ptr;
1793 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001794 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001795 NEXT(ptr) = a;
1796 ptr = a;
1797 a = NEXT(a);
1798 }else{
1799 NEXT(ptr) = b;
1800 ptr = b;
1801 b = NEXT(b);
1802 }
1803 }
1804 if( a ) NEXT(ptr) = a;
1805 else NEXT(ptr) = b;
1806 }
1807 return head;
1808}
1809
1810/*
1811** Inputs:
1812** list: Pointer to a singly-linked list of structures.
1813** next: Pointer to pointer to the second element of the list.
1814** cmp: A comparison function.
1815**
1816** Return Value:
1817** A pointer to the head of a sorted list containing the elements
1818** orginally in list.
1819**
1820** Side effects:
1821** The "next" pointers for elements in list are changed.
1822*/
1823#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001824static char *msort(
1825 char *list,
1826 char **next,
1827 int (*cmp)(const char*,const char*)
1828){
drhba99af52001-10-25 20:37:16 +00001829 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001830 char *ep;
1831 char *set[LISTSIZE];
1832 int i;
drh1cc0d112015-03-31 15:15:48 +00001833 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001834 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1835 while( list ){
1836 ep = list;
1837 list = NEXT(list);
1838 NEXT(ep) = 0;
1839 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1840 ep = merge(ep,set[i],cmp,offset);
1841 set[i] = 0;
1842 }
1843 set[i] = ep;
1844 }
1845 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001846 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001847 return ep;
1848}
1849/************************ From the file "option.c" **************************/
1850static char **argv;
1851static struct s_options *op;
1852static FILE *errstream;
1853
1854#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1855
1856/*
1857** Print the command line with a carrot pointing to the k-th character
1858** of the n-th field.
1859*/
icculus9e44cf12010-02-14 17:14:22 +00001860static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001861{
1862 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001863 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001864 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001865 for(i=1; i<n && argv[i]; i++){
1866 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001867 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001868 }
1869 spcnt += k;
1870 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1871 if( spcnt<20 ){
1872 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1873 }else{
1874 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1875 }
1876}
1877
1878/*
1879** Return the index of the N-th non-switch argument. Return -1
1880** if N is out of range.
1881*/
icculus9e44cf12010-02-14 17:14:22 +00001882static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001883{
1884 int i;
1885 int dashdash = 0;
1886 if( argv!=0 && *argv!=0 ){
1887 for(i=1; argv[i]; i++){
1888 if( dashdash || !ISOPT(argv[i]) ){
1889 if( n==0 ) return i;
1890 n--;
1891 }
1892 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1893 }
1894 }
1895 return -1;
1896}
1897
1898static char emsg[] = "Command line syntax error: ";
1899
1900/*
1901** Process a flag command line argument.
1902*/
icculus9e44cf12010-02-14 17:14:22 +00001903static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001904{
1905 int v;
1906 int errcnt = 0;
1907 int j;
1908 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001909 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001910 }
1911 v = argv[i][0]=='-' ? 1 : 0;
1912 if( op[j].label==0 ){
1913 if( err ){
1914 fprintf(err,"%sundefined option.\n",emsg);
1915 errline(i,1,err);
1916 }
1917 errcnt++;
drh0325d392015-01-01 19:11:22 +00001918 }else if( op[j].arg==0 ){
1919 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001920 }else if( op[j].type==OPT_FLAG ){
1921 *((int*)op[j].arg) = v;
1922 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001923 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001924 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001925 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001926 }else{
1927 if( err ){
1928 fprintf(err,"%smissing argument on switch.\n",emsg);
1929 errline(i,1,err);
1930 }
1931 errcnt++;
1932 }
1933 return errcnt;
1934}
1935
1936/*
1937** Process a command line switch which has an argument.
1938*/
icculus9e44cf12010-02-14 17:14:22 +00001939static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001940{
1941 int lv = 0;
1942 double dv = 0.0;
1943 char *sv = 0, *end;
1944 char *cp;
1945 int j;
1946 int errcnt = 0;
1947 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001948 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001949 *cp = 0;
1950 for(j=0; op[j].label; j++){
1951 if( strcmp(argv[i],op[j].label)==0 ) break;
1952 }
1953 *cp = '=';
1954 if( op[j].label==0 ){
1955 if( err ){
1956 fprintf(err,"%sundefined option.\n",emsg);
1957 errline(i,0,err);
1958 }
1959 errcnt++;
1960 }else{
1961 cp++;
1962 switch( op[j].type ){
1963 case OPT_FLAG:
1964 case OPT_FFLAG:
1965 if( err ){
1966 fprintf(err,"%soption requires an argument.\n",emsg);
1967 errline(i,0,err);
1968 }
1969 errcnt++;
1970 break;
1971 case OPT_DBL:
1972 case OPT_FDBL:
1973 dv = strtod(cp,&end);
1974 if( *end ){
1975 if( err ){
drh25473362015-09-04 18:03:45 +00001976 fprintf(err,
1977 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001978 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001979 }
1980 errcnt++;
1981 }
1982 break;
1983 case OPT_INT:
1984 case OPT_FINT:
1985 lv = strtol(cp,&end,0);
1986 if( *end ){
1987 if( err ){
1988 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001989 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001990 }
1991 errcnt++;
1992 }
1993 break;
1994 case OPT_STR:
1995 case OPT_FSTR:
1996 sv = cp;
1997 break;
1998 }
1999 switch( op[j].type ){
2000 case OPT_FLAG:
2001 case OPT_FFLAG:
2002 break;
2003 case OPT_DBL:
2004 *(double*)(op[j].arg) = dv;
2005 break;
2006 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002007 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002008 break;
2009 case OPT_INT:
2010 *(int*)(op[j].arg) = lv;
2011 break;
2012 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002013 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002014 break;
2015 case OPT_STR:
2016 *(char**)(op[j].arg) = sv;
2017 break;
2018 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002019 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002020 break;
2021 }
2022 }
2023 return errcnt;
2024}
2025
icculus9e44cf12010-02-14 17:14:22 +00002026int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002027{
2028 int errcnt = 0;
2029 argv = a;
2030 op = o;
2031 errstream = err;
2032 if( argv && *argv && op ){
2033 int i;
2034 for(i=1; argv[i]; i++){
2035 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2036 errcnt += handleflags(i,err);
2037 }else if( strchr(argv[i],'=') ){
2038 errcnt += handleswitch(i,err);
2039 }
2040 }
2041 }
2042 if( errcnt>0 ){
2043 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002044 OptPrint();
drh75897232000-05-29 14:26:00 +00002045 exit(1);
2046 }
2047 return 0;
2048}
2049
drhb0c86772000-06-02 23:21:26 +00002050int OptNArgs(){
drh75897232000-05-29 14:26:00 +00002051 int cnt = 0;
2052 int dashdash = 0;
2053 int i;
2054 if( argv!=0 && argv[0]!=0 ){
2055 for(i=1; argv[i]; i++){
2056 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2057 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2058 }
2059 }
2060 return cnt;
2061}
2062
icculus9e44cf12010-02-14 17:14:22 +00002063char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002064{
2065 int i;
2066 i = argindex(n);
2067 return i>=0 ? argv[i] : 0;
2068}
2069
icculus9e44cf12010-02-14 17:14:22 +00002070void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002071{
2072 int i;
2073 i = argindex(n);
2074 if( i>=0 ) errline(i,0,errstream);
2075}
2076
drhb0c86772000-06-02 23:21:26 +00002077void OptPrint(){
drh75897232000-05-29 14:26:00 +00002078 int i;
2079 int max, len;
2080 max = 0;
2081 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002082 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002083 switch( op[i].type ){
2084 case OPT_FLAG:
2085 case OPT_FFLAG:
2086 break;
2087 case OPT_INT:
2088 case OPT_FINT:
2089 len += 9; /* length of "<integer>" */
2090 break;
2091 case OPT_DBL:
2092 case OPT_FDBL:
2093 len += 6; /* length of "<real>" */
2094 break;
2095 case OPT_STR:
2096 case OPT_FSTR:
2097 len += 8; /* length of "<string>" */
2098 break;
2099 }
2100 if( len>max ) max = len;
2101 }
2102 for(i=0; op[i].label; i++){
2103 switch( op[i].type ){
2104 case OPT_FLAG:
2105 case OPT_FFLAG:
2106 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2107 break;
2108 case OPT_INT:
2109 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002110 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002111 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002112 break;
2113 case OPT_DBL:
2114 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002115 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002116 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002117 break;
2118 case OPT_STR:
2119 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002120 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002121 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002122 break;
2123 }
2124 }
2125}
2126/*********************** From the file "parse.c" ****************************/
2127/*
2128** Input file parser for the LEMON parser generator.
2129*/
2130
2131/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002132enum e_state {
2133 INITIALIZE,
2134 WAITING_FOR_DECL_OR_RULE,
2135 WAITING_FOR_DECL_KEYWORD,
2136 WAITING_FOR_DECL_ARG,
2137 WAITING_FOR_PRECEDENCE_SYMBOL,
2138 WAITING_FOR_ARROW,
2139 IN_RHS,
2140 LHS_ALIAS_1,
2141 LHS_ALIAS_2,
2142 LHS_ALIAS_3,
2143 RHS_ALIAS_1,
2144 RHS_ALIAS_2,
2145 PRECEDENCE_MARK_1,
2146 PRECEDENCE_MARK_2,
2147 RESYNC_AFTER_RULE_ERROR,
2148 RESYNC_AFTER_DECL_ERROR,
2149 WAITING_FOR_DESTRUCTOR_SYMBOL,
2150 WAITING_FOR_DATATYPE_SYMBOL,
2151 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002152 WAITING_FOR_WILDCARD_ID,
2153 WAITING_FOR_CLASS_ID,
2154 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002155};
drh75897232000-05-29 14:26:00 +00002156struct pstate {
2157 char *filename; /* Name of the input file */
2158 int tokenlineno; /* Linenumber at which current token starts */
2159 int errorcnt; /* Number of errors so far */
2160 char *tokenstart; /* Text of current token */
2161 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002162 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002163 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002164 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002165 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002166 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002167 int nrhs; /* Number of right-hand side symbols seen */
2168 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002169 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002170 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002171 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002172 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002173 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002174 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002175 enum e_assoc declassoc; /* Assign this association to decl arguments */
2176 int preccounter; /* Assign this precedence to decl arguments */
2177 struct rule *firstrule; /* Pointer to first rule in the grammar */
2178 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2179};
2180
2181/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002182static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002183{
icculus9e44cf12010-02-14 17:14:22 +00002184 const char *x;
drh75897232000-05-29 14:26:00 +00002185 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2186#if 0
2187 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2188 x,psp->state);
2189#endif
2190 switch( psp->state ){
2191 case INITIALIZE:
2192 psp->prevrule = 0;
2193 psp->preccounter = 0;
2194 psp->firstrule = psp->lastrule = 0;
2195 psp->gp->nrule = 0;
2196 /* Fall thru to next case */
2197 case WAITING_FOR_DECL_OR_RULE:
2198 if( x[0]=='%' ){
2199 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002200 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002201 psp->lhs = Symbol_new(x);
2202 psp->nrhs = 0;
2203 psp->lhsalias = 0;
2204 psp->state = WAITING_FOR_ARROW;
2205 }else if( x[0]=='{' ){
2206 if( psp->prevrule==0 ){
2207 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002208"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002209fragment which begins on this line.");
2210 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002211 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002212 ErrorMsg(psp->filename,psp->tokenlineno,
2213"Code fragment beginning on this line is not the first \
2214to follow the previous rule.");
2215 psp->errorcnt++;
2216 }else{
2217 psp->prevrule->line = psp->tokenlineno;
2218 psp->prevrule->code = &x[1];
drh711c9812016-05-23 14:24:31 +00002219 psp->prevrule->noCode = 0;
drhf2f105d2012-08-20 15:53:54 +00002220 }
drh75897232000-05-29 14:26:00 +00002221 }else if( x[0]=='[' ){
2222 psp->state = PRECEDENCE_MARK_1;
2223 }else{
2224 ErrorMsg(psp->filename,psp->tokenlineno,
2225 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2226 x);
2227 psp->errorcnt++;
2228 }
2229 break;
2230 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002231 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002232 ErrorMsg(psp->filename,psp->tokenlineno,
2233 "The precedence symbol must be a terminal.");
2234 psp->errorcnt++;
2235 }else if( psp->prevrule==0 ){
2236 ErrorMsg(psp->filename,psp->tokenlineno,
2237 "There is no prior rule to assign precedence \"[%s]\".",x);
2238 psp->errorcnt++;
2239 }else if( psp->prevrule->precsym!=0 ){
2240 ErrorMsg(psp->filename,psp->tokenlineno,
2241"Precedence mark on this line is not the first \
2242to follow the previous rule.");
2243 psp->errorcnt++;
2244 }else{
2245 psp->prevrule->precsym = Symbol_new(x);
2246 }
2247 psp->state = PRECEDENCE_MARK_2;
2248 break;
2249 case PRECEDENCE_MARK_2:
2250 if( x[0]!=']' ){
2251 ErrorMsg(psp->filename,psp->tokenlineno,
2252 "Missing \"]\" on precedence mark.");
2253 psp->errorcnt++;
2254 }
2255 psp->state = WAITING_FOR_DECL_OR_RULE;
2256 break;
2257 case WAITING_FOR_ARROW:
2258 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2259 psp->state = IN_RHS;
2260 }else if( x[0]=='(' ){
2261 psp->state = LHS_ALIAS_1;
2262 }else{
2263 ErrorMsg(psp->filename,psp->tokenlineno,
2264 "Expected to see a \":\" following the LHS symbol \"%s\".",
2265 psp->lhs->name);
2266 psp->errorcnt++;
2267 psp->state = RESYNC_AFTER_RULE_ERROR;
2268 }
2269 break;
2270 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002271 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002272 psp->lhsalias = x;
2273 psp->state = LHS_ALIAS_2;
2274 }else{
2275 ErrorMsg(psp->filename,psp->tokenlineno,
2276 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2277 x,psp->lhs->name);
2278 psp->errorcnt++;
2279 psp->state = RESYNC_AFTER_RULE_ERROR;
2280 }
2281 break;
2282 case LHS_ALIAS_2:
2283 if( x[0]==')' ){
2284 psp->state = LHS_ALIAS_3;
2285 }else{
2286 ErrorMsg(psp->filename,psp->tokenlineno,
2287 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2288 psp->errorcnt++;
2289 psp->state = RESYNC_AFTER_RULE_ERROR;
2290 }
2291 break;
2292 case LHS_ALIAS_3:
2293 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2294 psp->state = IN_RHS;
2295 }else{
2296 ErrorMsg(psp->filename,psp->tokenlineno,
2297 "Missing \"->\" following: \"%s(%s)\".",
2298 psp->lhs->name,psp->lhsalias);
2299 psp->errorcnt++;
2300 psp->state = RESYNC_AFTER_RULE_ERROR;
2301 }
2302 break;
2303 case IN_RHS:
2304 if( x[0]=='.' ){
2305 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002306 rp = (struct rule *)calloc( sizeof(struct rule) +
2307 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002308 if( rp==0 ){
2309 ErrorMsg(psp->filename,psp->tokenlineno,
2310 "Can't allocate enough memory for this rule.");
2311 psp->errorcnt++;
2312 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002313 }else{
drh75897232000-05-29 14:26:00 +00002314 int i;
2315 rp->ruleline = psp->tokenlineno;
2316 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002317 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002318 for(i=0; i<psp->nrhs; i++){
2319 rp->rhs[i] = psp->rhs[i];
2320 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002321 }
drh75897232000-05-29 14:26:00 +00002322 rp->lhs = psp->lhs;
2323 rp->lhsalias = psp->lhsalias;
2324 rp->nrhs = psp->nrhs;
2325 rp->code = 0;
drh711c9812016-05-23 14:24:31 +00002326 rp->noCode = 1;
drh75897232000-05-29 14:26:00 +00002327 rp->precsym = 0;
2328 rp->index = psp->gp->nrule++;
2329 rp->nextlhs = rp->lhs->rule;
2330 rp->lhs->rule = rp;
2331 rp->next = 0;
2332 if( psp->firstrule==0 ){
2333 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002334 }else{
drh75897232000-05-29 14:26:00 +00002335 psp->lastrule->next = rp;
2336 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002337 }
drh75897232000-05-29 14:26:00 +00002338 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002339 }
drh75897232000-05-29 14:26:00 +00002340 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002341 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002342 if( psp->nrhs>=MAXRHS ){
2343 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002344 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002345 x);
2346 psp->errorcnt++;
2347 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002348 }else{
drh75897232000-05-29 14:26:00 +00002349 psp->rhs[psp->nrhs] = Symbol_new(x);
2350 psp->alias[psp->nrhs] = 0;
2351 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002352 }
drhfd405312005-11-06 04:06:59 +00002353 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2354 struct symbol *msp = psp->rhs[psp->nrhs-1];
2355 if( msp->type!=MULTITERMINAL ){
2356 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002357 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002358 memset(msp, 0, sizeof(*msp));
2359 msp->type = MULTITERMINAL;
2360 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002361 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002362 msp->subsym[0] = origsp;
2363 msp->name = origsp->name;
2364 psp->rhs[psp->nrhs-1] = msp;
2365 }
2366 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002367 msp->subsym = (struct symbol **) realloc(msp->subsym,
2368 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002369 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002370 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002371 ErrorMsg(psp->filename,psp->tokenlineno,
2372 "Cannot form a compound containing a non-terminal");
2373 psp->errorcnt++;
2374 }
drh75897232000-05-29 14:26:00 +00002375 }else if( x[0]=='(' && psp->nrhs>0 ){
2376 psp->state = RHS_ALIAS_1;
2377 }else{
2378 ErrorMsg(psp->filename,psp->tokenlineno,
2379 "Illegal character on RHS of rule: \"%s\".",x);
2380 psp->errorcnt++;
2381 psp->state = RESYNC_AFTER_RULE_ERROR;
2382 }
2383 break;
2384 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002385 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002386 psp->alias[psp->nrhs-1] = x;
2387 psp->state = RHS_ALIAS_2;
2388 }else{
2389 ErrorMsg(psp->filename,psp->tokenlineno,
2390 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2391 x,psp->rhs[psp->nrhs-1]->name);
2392 psp->errorcnt++;
2393 psp->state = RESYNC_AFTER_RULE_ERROR;
2394 }
2395 break;
2396 case RHS_ALIAS_2:
2397 if( x[0]==')' ){
2398 psp->state = IN_RHS;
2399 }else{
2400 ErrorMsg(psp->filename,psp->tokenlineno,
2401 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2402 psp->errorcnt++;
2403 psp->state = RESYNC_AFTER_RULE_ERROR;
2404 }
2405 break;
2406 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002407 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002408 psp->declkeyword = x;
2409 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002410 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002411 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002412 psp->state = WAITING_FOR_DECL_ARG;
2413 if( strcmp(x,"name")==0 ){
2414 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002415 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002416 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002417 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002418 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002419 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002420 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002421 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002422 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002423 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002424 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002425 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002426 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002427 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002428 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002429 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002430 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002431 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002432 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002433 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002434 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002435 }else if( strcmp(x,"extra_argument")==0 ){
2436 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002437 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002438 }else if( strcmp(x,"token_type")==0 ){
2439 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002440 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002441 }else if( strcmp(x,"default_type")==0 ){
2442 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002443 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002444 }else if( strcmp(x,"stack_size")==0 ){
2445 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002446 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002447 }else if( strcmp(x,"start_symbol")==0 ){
2448 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002449 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002450 }else if( strcmp(x,"left")==0 ){
2451 psp->preccounter++;
2452 psp->declassoc = LEFT;
2453 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2454 }else if( strcmp(x,"right")==0 ){
2455 psp->preccounter++;
2456 psp->declassoc = RIGHT;
2457 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2458 }else if( strcmp(x,"nonassoc")==0 ){
2459 psp->preccounter++;
2460 psp->declassoc = NONE;
2461 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002462 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002463 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002464 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002465 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002466 }else if( strcmp(x,"fallback")==0 ){
2467 psp->fallback = 0;
2468 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002469 }else if( strcmp(x,"wildcard")==0 ){
2470 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002471 }else if( strcmp(x,"token_class")==0 ){
2472 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002473 }else{
2474 ErrorMsg(psp->filename,psp->tokenlineno,
2475 "Unknown declaration keyword: \"%%%s\".",x);
2476 psp->errorcnt++;
2477 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002478 }
drh75897232000-05-29 14:26:00 +00002479 }else{
2480 ErrorMsg(psp->filename,psp->tokenlineno,
2481 "Illegal declaration keyword: \"%s\".",x);
2482 psp->errorcnt++;
2483 psp->state = RESYNC_AFTER_DECL_ERROR;
2484 }
2485 break;
2486 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002487 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002488 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002489 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002490 psp->errorcnt++;
2491 psp->state = RESYNC_AFTER_DECL_ERROR;
2492 }else{
icculusd286fa62010-03-03 17:06:32 +00002493 struct symbol *sp = Symbol_new(x);
2494 psp->declargslot = &sp->destructor;
2495 psp->decllinenoslot = &sp->destLineno;
2496 psp->insertLineMacro = 1;
2497 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002498 }
2499 break;
2500 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002501 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002502 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002503 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002504 psp->errorcnt++;
2505 psp->state = RESYNC_AFTER_DECL_ERROR;
2506 }else{
icculus866bf1e2010-02-17 20:31:32 +00002507 struct symbol *sp = Symbol_find(x);
2508 if((sp) && (sp->datatype)){
2509 ErrorMsg(psp->filename,psp->tokenlineno,
2510 "Symbol %%type \"%s\" already defined", x);
2511 psp->errorcnt++;
2512 psp->state = RESYNC_AFTER_DECL_ERROR;
2513 }else{
2514 if (!sp){
2515 sp = Symbol_new(x);
2516 }
2517 psp->declargslot = &sp->datatype;
2518 psp->insertLineMacro = 0;
2519 psp->state = WAITING_FOR_DECL_ARG;
2520 }
drh75897232000-05-29 14:26:00 +00002521 }
2522 break;
2523 case WAITING_FOR_PRECEDENCE_SYMBOL:
2524 if( x[0]=='.' ){
2525 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002526 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002527 struct symbol *sp;
2528 sp = Symbol_new(x);
2529 if( sp->prec>=0 ){
2530 ErrorMsg(psp->filename,psp->tokenlineno,
2531 "Symbol \"%s\" has already be given a precedence.",x);
2532 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002533 }else{
drh75897232000-05-29 14:26:00 +00002534 sp->prec = psp->preccounter;
2535 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002536 }
drh75897232000-05-29 14:26:00 +00002537 }else{
2538 ErrorMsg(psp->filename,psp->tokenlineno,
2539 "Can't assign a precedence to \"%s\".",x);
2540 psp->errorcnt++;
2541 }
2542 break;
2543 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002544 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002545 const char *zOld, *zNew;
2546 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002547 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002548 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002549 char zLine[50];
2550 zNew = x;
2551 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002552 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002553 if( *psp->declargslot ){
2554 zOld = *psp->declargslot;
2555 }else{
2556 zOld = "";
2557 }
drh87cf1372008-08-13 20:09:06 +00002558 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002559 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002560 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002561 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2562 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002563 for(z=psp->filename, nBack=0; *z; z++){
2564 if( *z=='\\' ) nBack++;
2565 }
drh898799f2014-01-10 23:21:00 +00002566 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002567 nLine = lemonStrlen(zLine);
2568 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002569 }
icculus9e44cf12010-02-14 17:14:22 +00002570 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2571 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002572 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002573 if( nOld && zBuf[-1]!='\n' ){
2574 *(zBuf++) = '\n';
2575 }
2576 memcpy(zBuf, zLine, nLine);
2577 zBuf += nLine;
2578 *(zBuf++) = '"';
2579 for(z=psp->filename; *z; z++){
2580 if( *z=='\\' ){
2581 *(zBuf++) = '\\';
2582 }
2583 *(zBuf++) = *z;
2584 }
2585 *(zBuf++) = '"';
2586 *(zBuf++) = '\n';
2587 }
drh4dc8ef52008-07-01 17:13:57 +00002588 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2589 psp->decllinenoslot[0] = psp->tokenlineno;
2590 }
drha5808f32008-04-27 22:19:44 +00002591 memcpy(zBuf, zNew, nNew);
2592 zBuf += nNew;
2593 *zBuf = 0;
2594 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002595 }else{
2596 ErrorMsg(psp->filename,psp->tokenlineno,
2597 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2598 psp->errorcnt++;
2599 psp->state = RESYNC_AFTER_DECL_ERROR;
2600 }
2601 break;
drh0bd1f4e2002-06-06 18:54:39 +00002602 case WAITING_FOR_FALLBACK_ID:
2603 if( x[0]=='.' ){
2604 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002605 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002606 ErrorMsg(psp->filename, psp->tokenlineno,
2607 "%%fallback argument \"%s\" should be a token", x);
2608 psp->errorcnt++;
2609 }else{
2610 struct symbol *sp = Symbol_new(x);
2611 if( psp->fallback==0 ){
2612 psp->fallback = sp;
2613 }else if( sp->fallback ){
2614 ErrorMsg(psp->filename, psp->tokenlineno,
2615 "More than one fallback assigned to token %s", x);
2616 psp->errorcnt++;
2617 }else{
2618 sp->fallback = psp->fallback;
2619 psp->gp->has_fallback = 1;
2620 }
2621 }
2622 break;
drhe09daa92006-06-10 13:29:31 +00002623 case WAITING_FOR_WILDCARD_ID:
2624 if( x[0]=='.' ){
2625 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002626 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002627 ErrorMsg(psp->filename, psp->tokenlineno,
2628 "%%wildcard argument \"%s\" should be a token", x);
2629 psp->errorcnt++;
2630 }else{
2631 struct symbol *sp = Symbol_new(x);
2632 if( psp->gp->wildcard==0 ){
2633 psp->gp->wildcard = sp;
2634 }else{
2635 ErrorMsg(psp->filename, psp->tokenlineno,
2636 "Extra wildcard to token: %s", x);
2637 psp->errorcnt++;
2638 }
2639 }
2640 break;
drh61f92cd2014-01-11 03:06:18 +00002641 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002642 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002643 ErrorMsg(psp->filename, psp->tokenlineno,
2644 "%%token_class must be followed by an identifier: ", x);
2645 psp->errorcnt++;
2646 psp->state = RESYNC_AFTER_DECL_ERROR;
2647 }else if( Symbol_find(x) ){
2648 ErrorMsg(psp->filename, psp->tokenlineno,
2649 "Symbol \"%s\" already used", x);
2650 psp->errorcnt++;
2651 psp->state = RESYNC_AFTER_DECL_ERROR;
2652 }else{
2653 psp->tkclass = Symbol_new(x);
2654 psp->tkclass->type = MULTITERMINAL;
2655 psp->state = WAITING_FOR_CLASS_TOKEN;
2656 }
2657 break;
2658 case WAITING_FOR_CLASS_TOKEN:
2659 if( x[0]=='.' ){
2660 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002661 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002662 struct symbol *msp = psp->tkclass;
2663 msp->nsubsym++;
2664 msp->subsym = (struct symbol **) realloc(msp->subsym,
2665 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002666 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002667 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2668 }else{
2669 ErrorMsg(psp->filename, psp->tokenlineno,
2670 "%%token_class argument \"%s\" should be a token", x);
2671 psp->errorcnt++;
2672 psp->state = RESYNC_AFTER_DECL_ERROR;
2673 }
2674 break;
drh75897232000-05-29 14:26:00 +00002675 case RESYNC_AFTER_RULE_ERROR:
2676/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2677** break; */
2678 case RESYNC_AFTER_DECL_ERROR:
2679 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2680 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2681 break;
2682 }
2683}
2684
drh34ff57b2008-07-14 12:27:51 +00002685/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002686** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2687** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2688** comments them out. Text in between is also commented out as appropriate.
2689*/
danielk1977940fac92005-01-23 22:41:37 +00002690static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002691 int i, j, k, n;
2692 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002693 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002694 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002695 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002696 for(i=0; z[i]; i++){
2697 if( z[i]=='\n' ) lineno++;
2698 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002699 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002700 if( exclude ){
2701 exclude--;
2702 if( exclude==0 ){
2703 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2704 }
2705 }
2706 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002707 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2708 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002709 if( exclude ){
2710 exclude++;
2711 }else{
drhc56fac72015-10-29 13:48:15 +00002712 for(j=i+7; ISSPACE(z[j]); j++){}
2713 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002714 exclude = 1;
2715 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002716 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002717 exclude = 0;
2718 break;
2719 }
2720 }
2721 if( z[i+3]=='n' ) exclude = !exclude;
2722 if( exclude ){
2723 start = i;
2724 start_lineno = lineno;
2725 }
2726 }
2727 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2728 }
2729 }
2730 if( exclude ){
2731 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2732 exit(1);
2733 }
2734}
2735
drh75897232000-05-29 14:26:00 +00002736/* In spite of its name, this function is really a scanner. It read
2737** in the entire input file (all at once) then tokenizes it. Each
2738** token is passed to the function "parseonetoken" which builds all
2739** the appropriate data structures in the global state vector "gp".
2740*/
icculus9e44cf12010-02-14 17:14:22 +00002741void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002742{
2743 struct pstate ps;
2744 FILE *fp;
2745 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002746 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002747 int lineno;
2748 int c;
2749 char *cp, *nextcp;
2750 int startline = 0;
2751
rse38514a92007-09-20 11:34:17 +00002752 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002753 ps.gp = gp;
2754 ps.filename = gp->filename;
2755 ps.errorcnt = 0;
2756 ps.state = INITIALIZE;
2757
2758 /* Begin by reading the input file */
2759 fp = fopen(ps.filename,"rb");
2760 if( fp==0 ){
2761 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2762 gp->errorcnt++;
2763 return;
2764 }
2765 fseek(fp,0,2);
2766 filesize = ftell(fp);
2767 rewind(fp);
2768 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002769 if( filesize>100000000 || filebuf==0 ){
2770 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002771 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002772 fclose(fp);
drh75897232000-05-29 14:26:00 +00002773 return;
2774 }
2775 if( fread(filebuf,1,filesize,fp)!=filesize ){
2776 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2777 filesize);
2778 free(filebuf);
2779 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002780 fclose(fp);
drh75897232000-05-29 14:26:00 +00002781 return;
2782 }
2783 fclose(fp);
2784 filebuf[filesize] = 0;
2785
drh6d08b4d2004-07-20 12:45:22 +00002786 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2787 preprocess_input(filebuf);
2788
drh75897232000-05-29 14:26:00 +00002789 /* Now scan the text of the input file */
2790 lineno = 1;
2791 for(cp=filebuf; (c= *cp)!=0; ){
2792 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002793 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002794 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2795 cp+=2;
2796 while( (c= *cp)!=0 && c!='\n' ) cp++;
2797 continue;
2798 }
2799 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2800 cp+=2;
2801 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2802 if( c=='\n' ) lineno++;
2803 cp++;
2804 }
2805 if( c ) cp++;
2806 continue;
2807 }
2808 ps.tokenstart = cp; /* Mark the beginning of the token */
2809 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2810 if( c=='\"' ){ /* String literals */
2811 cp++;
2812 while( (c= *cp)!=0 && c!='\"' ){
2813 if( c=='\n' ) lineno++;
2814 cp++;
2815 }
2816 if( c==0 ){
2817 ErrorMsg(ps.filename,startline,
2818"String starting on this line is not terminated before the end of the file.");
2819 ps.errorcnt++;
2820 nextcp = cp;
2821 }else{
2822 nextcp = cp+1;
2823 }
2824 }else if( c=='{' ){ /* A block of C code */
2825 int level;
2826 cp++;
2827 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2828 if( c=='\n' ) lineno++;
2829 else if( c=='{' ) level++;
2830 else if( c=='}' ) level--;
2831 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2832 int prevc;
2833 cp = &cp[2];
2834 prevc = 0;
2835 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2836 if( c=='\n' ) lineno++;
2837 prevc = c;
2838 cp++;
drhf2f105d2012-08-20 15:53:54 +00002839 }
2840 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002841 cp = &cp[2];
2842 while( (c= *cp)!=0 && c!='\n' ) cp++;
2843 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002844 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002845 int startchar, prevc;
2846 startchar = c;
2847 prevc = 0;
2848 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2849 if( c=='\n' ) lineno++;
2850 if( prevc=='\\' ) prevc = 0;
2851 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002852 }
2853 }
drh75897232000-05-29 14:26:00 +00002854 }
2855 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002856 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002857"C code starting on this line is not terminated before the end of the file.");
2858 ps.errorcnt++;
2859 nextcp = cp;
2860 }else{
2861 nextcp = cp+1;
2862 }
drhc56fac72015-10-29 13:48:15 +00002863 }else if( ISALNUM(c) ){ /* Identifiers */
2864 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002865 nextcp = cp;
2866 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2867 cp += 3;
2868 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002869 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002870 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002871 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002872 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002873 }else{ /* All other (one character) operators */
2874 cp++;
2875 nextcp = cp;
2876 }
2877 c = *cp;
2878 *cp = 0; /* Null terminate the token */
2879 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002880 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002881 cp = nextcp;
2882 }
2883 free(filebuf); /* Release the buffer after parsing */
2884 gp->rule = ps.firstrule;
2885 gp->errorcnt = ps.errorcnt;
2886}
2887/*************************** From the file "plink.c" *********************/
2888/*
2889** Routines processing configuration follow-set propagation links
2890** in the LEMON parser generator.
2891*/
2892static struct plink *plink_freelist = 0;
2893
2894/* Allocate a new plink */
2895struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002896 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002897
2898 if( plink_freelist==0 ){
2899 int i;
2900 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002901 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002902 if( plink_freelist==0 ){
2903 fprintf(stderr,
2904 "Unable to allocate memory for a new follow-set propagation link.\n");
2905 exit(1);
2906 }
2907 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2908 plink_freelist[amt-1].next = 0;
2909 }
icculus9e44cf12010-02-14 17:14:22 +00002910 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002911 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002912 return newlink;
drh75897232000-05-29 14:26:00 +00002913}
2914
2915/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002916void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002917{
icculus9e44cf12010-02-14 17:14:22 +00002918 struct plink *newlink;
2919 newlink = Plink_new();
2920 newlink->next = *plpp;
2921 *plpp = newlink;
2922 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002923}
2924
2925/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002926void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002927{
2928 struct plink *nextpl;
2929 while( from ){
2930 nextpl = from->next;
2931 from->next = *to;
2932 *to = from;
2933 from = nextpl;
2934 }
2935}
2936
2937/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002938void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002939{
2940 struct plink *nextpl;
2941
2942 while( plp ){
2943 nextpl = plp->next;
2944 plp->next = plink_freelist;
2945 plink_freelist = plp;
2946 plp = nextpl;
2947 }
2948}
2949/*********************** From the file "report.c" **************************/
2950/*
2951** Procedures for generating reports and tables in the LEMON parser generator.
2952*/
2953
2954/* Generate a filename with the given suffix. Space to hold the
2955** name comes from malloc() and must be freed by the calling
2956** function.
2957*/
icculus9e44cf12010-02-14 17:14:22 +00002958PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002959{
2960 char *name;
2961 char *cp;
2962
icculus9e44cf12010-02-14 17:14:22 +00002963 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002964 if( name==0 ){
2965 fprintf(stderr,"Can't allocate space for a filename.\n");
2966 exit(1);
2967 }
drh898799f2014-01-10 23:21:00 +00002968 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002969 cp = strrchr(name,'.');
2970 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002971 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002972 return name;
2973}
2974
2975/* Open a file with a name based on the name of the input file,
2976** but with a different (specified) suffix, and return a pointer
2977** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002978PRIVATE FILE *file_open(
2979 struct lemon *lemp,
2980 const char *suffix,
2981 const char *mode
2982){
drh75897232000-05-29 14:26:00 +00002983 FILE *fp;
2984
2985 if( lemp->outname ) free(lemp->outname);
2986 lemp->outname = file_makename(lemp, suffix);
2987 fp = fopen(lemp->outname,mode);
2988 if( fp==0 && *mode=='w' ){
2989 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2990 lemp->errorcnt++;
2991 return 0;
2992 }
2993 return fp;
2994}
2995
2996/* Duplicate the input file without comments and without actions
2997** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002998void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002999{
3000 struct rule *rp;
3001 struct symbol *sp;
3002 int i, j, maxlen, len, ncolumns, skip;
3003 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
3004 maxlen = 10;
3005 for(i=0; i<lemp->nsymbol; i++){
3006 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003007 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003008 if( len>maxlen ) maxlen = len;
3009 }
3010 ncolumns = 76/(maxlen+5);
3011 if( ncolumns<1 ) ncolumns = 1;
3012 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3013 for(i=0; i<skip; i++){
3014 printf("//");
3015 for(j=i; j<lemp->nsymbol; j+=skip){
3016 sp = lemp->symbols[j];
3017 assert( sp->index==j );
3018 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3019 }
3020 printf("\n");
3021 }
3022 for(rp=lemp->rule; rp; rp=rp->next){
3023 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00003024 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00003025 printf(" ::=");
3026 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00003027 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003028 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003029 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003030 for(j=1; j<sp->nsubsym; j++){
3031 printf("|%s", sp->subsym[j]->name);
3032 }
drh61f92cd2014-01-11 03:06:18 +00003033 }else{
3034 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003035 }
3036 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00003037 }
3038 printf(".");
3039 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003040 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003041 printf("\n");
3042 }
3043}
3044
drh7e698e92015-09-07 14:22:24 +00003045/* Print a single rule.
3046*/
3047void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003048 struct symbol *sp;
3049 int i, j;
drh75897232000-05-29 14:26:00 +00003050 fprintf(fp,"%s ::=",rp->lhs->name);
3051 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003052 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003053 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003054 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003055 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003056 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003057 for(j=1; j<sp->nsubsym; j++){
3058 fprintf(fp,"|%s",sp->subsym[j]->name);
3059 }
drh61f92cd2014-01-11 03:06:18 +00003060 }else{
3061 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003062 }
drh75897232000-05-29 14:26:00 +00003063 }
3064}
3065
drh7e698e92015-09-07 14:22:24 +00003066/* Print the rule for a configuration.
3067*/
3068void ConfigPrint(FILE *fp, struct config *cfp){
3069 RulePrint(fp, cfp->rp, cfp->dot);
3070}
3071
drh75897232000-05-29 14:26:00 +00003072/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003073#if 0
drh75897232000-05-29 14:26:00 +00003074/* Print a set */
3075PRIVATE void SetPrint(out,set,lemp)
3076FILE *out;
3077char *set;
3078struct lemon *lemp;
3079{
3080 int i;
3081 char *spacer;
3082 spacer = "";
3083 fprintf(out,"%12s[","");
3084 for(i=0; i<lemp->nterminal; i++){
3085 if( SetFind(set,i) ){
3086 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3087 spacer = " ";
3088 }
3089 }
3090 fprintf(out,"]\n");
3091}
3092
3093/* Print a plink chain */
3094PRIVATE void PlinkPrint(out,plp,tag)
3095FILE *out;
3096struct plink *plp;
3097char *tag;
3098{
3099 while( plp ){
drhada354d2005-11-05 15:03:59 +00003100 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003101 ConfigPrint(out,plp->cfp);
3102 fprintf(out,"\n");
3103 plp = plp->next;
3104 }
3105}
3106#endif
3107
3108/* Print an action to the given file descriptor. Return FALSE if
3109** nothing was actually printed.
3110*/
drh7e698e92015-09-07 14:22:24 +00003111int PrintAction(
3112 struct action *ap, /* The action to print */
3113 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003114 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003115){
drh75897232000-05-29 14:26:00 +00003116 int result = 1;
3117 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003118 case SHIFT: {
3119 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003120 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003121 break;
drh7e698e92015-09-07 14:22:24 +00003122 }
3123 case REDUCE: {
3124 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003125 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003126 RulePrint(fp, rp, -1);
3127 break;
3128 }
3129 case SHIFTREDUCE: {
3130 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003131 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003132 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003133 break;
drh7e698e92015-09-07 14:22:24 +00003134 }
drh75897232000-05-29 14:26:00 +00003135 case ACCEPT:
3136 fprintf(fp,"%*s accept",indent,ap->sp->name);
3137 break;
3138 case ERROR:
3139 fprintf(fp,"%*s error",indent,ap->sp->name);
3140 break;
drh9892c5d2007-12-21 00:02:11 +00003141 case SRCONFLICT:
3142 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003143 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003144 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003145 break;
drh9892c5d2007-12-21 00:02:11 +00003146 case SSCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003147 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003148 indent,ap->sp->name,ap->x.stp->statenum);
3149 break;
drh75897232000-05-29 14:26:00 +00003150 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003151 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003152 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003153 indent,ap->sp->name,ap->x.stp->statenum);
3154 }else{
3155 result = 0;
3156 }
3157 break;
drh75897232000-05-29 14:26:00 +00003158 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003159 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003160 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003161 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003162 }else{
3163 result = 0;
3164 }
3165 break;
drh75897232000-05-29 14:26:00 +00003166 case NOT_USED:
3167 result = 0;
3168 break;
3169 }
3170 return result;
3171}
3172
drh3bd48ab2015-09-07 18:23:37 +00003173/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003174void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003175{
3176 int i;
3177 struct state *stp;
3178 struct config *cfp;
3179 struct action *ap;
3180 FILE *fp;
3181
drh2aa6ca42004-09-10 00:14:04 +00003182 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003183 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003184 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003185 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003186 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003187 if( lemp->basisflag ) cfp=stp->bp;
3188 else cfp=stp->cfp;
3189 while( cfp ){
3190 char buf[20];
3191 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003192 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003193 fprintf(fp," %5s ",buf);
3194 }else{
3195 fprintf(fp," ");
3196 }
3197 ConfigPrint(fp,cfp);
3198 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003199#if 0
drh75897232000-05-29 14:26:00 +00003200 SetPrint(fp,cfp->fws,lemp);
3201 PlinkPrint(fp,cfp->fplp,"To ");
3202 PlinkPrint(fp,cfp->bplp,"From");
3203#endif
3204 if( lemp->basisflag ) cfp=cfp->bp;
3205 else cfp=cfp->next;
3206 }
3207 fprintf(fp,"\n");
3208 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003209 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003210 }
3211 fprintf(fp,"\n");
3212 }
drhe9278182007-07-18 18:16:29 +00003213 fprintf(fp, "----------------------------------------------------\n");
3214 fprintf(fp, "Symbols:\n");
3215 for(i=0; i<lemp->nsymbol; i++){
3216 int j;
3217 struct symbol *sp;
3218
3219 sp = lemp->symbols[i];
3220 fprintf(fp, " %3d: %s", i, sp->name);
3221 if( sp->type==NONTERMINAL ){
3222 fprintf(fp, ":");
3223 if( sp->lambda ){
3224 fprintf(fp, " <lambda>");
3225 }
3226 for(j=0; j<lemp->nterminal; j++){
3227 if( sp->firstset && SetFind(sp->firstset, j) ){
3228 fprintf(fp, " %s", lemp->symbols[j]->name);
3229 }
3230 }
3231 }
3232 fprintf(fp, "\n");
3233 }
drh75897232000-05-29 14:26:00 +00003234 fclose(fp);
3235 return;
3236}
3237
3238/* Search for the file "name" which is in the same directory as
3239** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003240PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003241{
icculus9e44cf12010-02-14 17:14:22 +00003242 const char *pathlist;
3243 char *pathbufptr;
3244 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003245 char *path,*cp;
3246 char c;
drh75897232000-05-29 14:26:00 +00003247
3248#ifdef __WIN32__
3249 cp = strrchr(argv0,'\\');
3250#else
3251 cp = strrchr(argv0,'/');
3252#endif
3253 if( cp ){
3254 c = *cp;
3255 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003256 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003257 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003258 *cp = c;
3259 }else{
drh75897232000-05-29 14:26:00 +00003260 pathlist = getenv("PATH");
3261 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003262 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003263 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003264 if( (pathbuf != 0) && (path!=0) ){
3265 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003266 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003267 while( *pathbuf ){
3268 cp = strchr(pathbuf,':');
3269 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003270 c = *cp;
3271 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003272 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003273 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003274 if( c==0 ) pathbuf[0] = 0;
3275 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003276 if( access(path,modemask)==0 ) break;
3277 }
icculus9e44cf12010-02-14 17:14:22 +00003278 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003279 }
3280 }
3281 return path;
3282}
3283
3284/* Given an action, compute the integer value for that action
3285** which is to be put in the action table of the generated machine.
3286** Return negative if no action should be generated.
3287*/
icculus9e44cf12010-02-14 17:14:22 +00003288PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003289{
3290 int act;
3291 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003292 case SHIFT: act = ap->x.stp->statenum; break;
drh4ef07702016-03-16 19:45:54 +00003293 case SHIFTREDUCE: act = ap->x.rp->iRule + lemp->nstate; break;
3294 case REDUCE: act = ap->x.rp->iRule + lemp->nstate+lemp->nrule; break;
drh3bd48ab2015-09-07 18:23:37 +00003295 case ERROR: act = lemp->nstate + lemp->nrule*2; break;
3296 case ACCEPT: act = lemp->nstate + lemp->nrule*2 + 1; break;
drh75897232000-05-29 14:26:00 +00003297 default: act = -1; break;
3298 }
3299 return act;
3300}
3301
3302#define LINESIZE 1000
3303/* The next cluster of routines are for reading the template file
3304** and writing the results to the generated parser */
3305/* The first function transfers data from "in" to "out" until
3306** a line is seen which begins with "%%". The line number is
3307** tracked.
3308**
3309** if name!=0, then any word that begin with "Parse" is changed to
3310** begin with *name instead.
3311*/
icculus9e44cf12010-02-14 17:14:22 +00003312PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003313{
3314 int i, iStart;
3315 char line[LINESIZE];
3316 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3317 (*lineno)++;
3318 iStart = 0;
3319 if( name ){
3320 for(i=0; line[i]; i++){
3321 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003322 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003323 ){
3324 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3325 fprintf(out,"%s",name);
3326 i += 4;
3327 iStart = i+1;
3328 }
3329 }
3330 }
3331 fprintf(out,"%s",&line[iStart]);
3332 }
3333}
3334
3335/* The next function finds the template file and opens it, returning
3336** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003337PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003338{
3339 static char templatename[] = "lempar.c";
3340 char buf[1000];
3341 FILE *in;
3342 char *tpltname;
3343 char *cp;
3344
icculus3e143bd2010-02-14 00:48:49 +00003345 /* first, see if user specified a template filename on the command line. */
3346 if (user_templatename != 0) {
3347 if( access(user_templatename,004)==-1 ){
3348 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3349 user_templatename);
3350 lemp->errorcnt++;
3351 return 0;
3352 }
3353 in = fopen(user_templatename,"rb");
3354 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003355 fprintf(stderr,"Can't open the template file \"%s\".\n",
3356 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003357 lemp->errorcnt++;
3358 return 0;
3359 }
3360 return in;
3361 }
3362
drh75897232000-05-29 14:26:00 +00003363 cp = strrchr(lemp->filename,'.');
3364 if( cp ){
drh898799f2014-01-10 23:21:00 +00003365 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003366 }else{
drh898799f2014-01-10 23:21:00 +00003367 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003368 }
3369 if( access(buf,004)==0 ){
3370 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003371 }else if( access(templatename,004)==0 ){
3372 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003373 }else{
3374 tpltname = pathsearch(lemp->argv0,templatename,0);
3375 }
3376 if( tpltname==0 ){
3377 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3378 templatename);
3379 lemp->errorcnt++;
3380 return 0;
3381 }
drh2aa6ca42004-09-10 00:14:04 +00003382 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003383 if( in==0 ){
3384 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3385 lemp->errorcnt++;
3386 return 0;
3387 }
3388 return in;
3389}
3390
drhaf805ca2004-09-07 11:28:25 +00003391/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003392PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003393{
3394 fprintf(out,"#line %d \"",lineno);
3395 while( *filename ){
3396 if( *filename == '\\' ) putc('\\',out);
3397 putc(*filename,out);
3398 filename++;
3399 }
3400 fprintf(out,"\"\n");
3401}
3402
drh75897232000-05-29 14:26:00 +00003403/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003404PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003405{
3406 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003407 while( *str ){
drh75897232000-05-29 14:26:00 +00003408 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003409 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003410 str++;
3411 }
drh9db55df2004-09-09 14:01:21 +00003412 if( str[-1]!='\n' ){
3413 putc('\n',out);
3414 (*lineno)++;
3415 }
shane58543932008-12-10 20:10:04 +00003416 if (!lemp->nolinenosflag) {
3417 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3418 }
drh75897232000-05-29 14:26:00 +00003419 return;
3420}
3421
3422/*
3423** The following routine emits code for the destructor for the
3424** symbol sp
3425*/
icculus9e44cf12010-02-14 17:14:22 +00003426void emit_destructor_code(
3427 FILE *out,
3428 struct symbol *sp,
3429 struct lemon *lemp,
3430 int *lineno
3431){
drhcc83b6e2004-04-23 23:38:42 +00003432 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003433
drh75897232000-05-29 14:26:00 +00003434 if( sp->type==TERMINAL ){
3435 cp = lemp->tokendest;
3436 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003437 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003438 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003439 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003440 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003441 if( !lemp->nolinenosflag ){
3442 (*lineno)++;
3443 tplt_linedir(out,sp->destLineno,lemp->filename);
3444 }
drh960e8c62001-04-03 16:53:21 +00003445 }else if( lemp->vardest ){
3446 cp = lemp->vardest;
3447 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003448 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003449 }else{
3450 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003451 }
3452 for(; *cp; cp++){
3453 if( *cp=='$' && cp[1]=='$' ){
3454 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3455 cp++;
3456 continue;
3457 }
shane58543932008-12-10 20:10:04 +00003458 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003459 fputc(*cp,out);
3460 }
shane58543932008-12-10 20:10:04 +00003461 fprintf(out,"\n"); (*lineno)++;
3462 if (!lemp->nolinenosflag) {
3463 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3464 }
3465 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003466 return;
3467}
3468
3469/*
drh960e8c62001-04-03 16:53:21 +00003470** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003471*/
icculus9e44cf12010-02-14 17:14:22 +00003472int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003473{
3474 int ret;
3475 if( sp->type==TERMINAL ){
3476 ret = lemp->tokendest!=0;
3477 }else{
drh960e8c62001-04-03 16:53:21 +00003478 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003479 }
3480 return ret;
3481}
3482
drh0bb132b2004-07-20 14:06:51 +00003483/*
3484** Append text to a dynamically allocated string. If zText is 0 then
3485** reset the string to be empty again. Always return the complete text
3486** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003487**
3488** n bytes of zText are stored. If n==0 then all of zText up to the first
3489** \000 terminator is stored. zText can contain up to two instances of
3490** %d. The values of p1 and p2 are written into the first and second
3491** %d.
3492**
3493** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003494*/
icculus9e44cf12010-02-14 17:14:22 +00003495PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3496 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003497 static char *z = 0;
3498 static int alloced = 0;
3499 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003500 int c;
drh0bb132b2004-07-20 14:06:51 +00003501 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003502 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003503 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003504 used = 0;
3505 return z;
3506 }
drh7ac25c72004-08-19 15:12:26 +00003507 if( n<=0 ){
3508 if( n<0 ){
3509 used += n;
3510 assert( used>=0 );
3511 }
drh87cf1372008-08-13 20:09:06 +00003512 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003513 }
drhdf609712010-11-23 20:55:27 +00003514 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003515 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003516 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003517 }
icculus9e44cf12010-02-14 17:14:22 +00003518 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003519 while( n-- > 0 ){
3520 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003521 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003522 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003523 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003524 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003525 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003526 zText++;
3527 n--;
3528 }else{
mistachkin2318d332015-01-12 18:02:52 +00003529 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003530 }
3531 }
3532 z[used] = 0;
3533 return z;
3534}
3535
3536/*
drh711c9812016-05-23 14:24:31 +00003537** Write and transform the rp->code string so that symbols are expanded.
3538** Populate the rp->codePrefix and rp->codeSuffix strings, as appropriate.
drhdabd04c2016-02-17 01:46:19 +00003539**
3540** Return 1 if the expanded code requires that "yylhsminor" local variable
3541** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003542*/
drhdabd04c2016-02-17 01:46:19 +00003543PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003544 char *cp, *xp;
3545 int i;
drhcf82f0d2016-02-17 04:33:10 +00003546 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003547 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003548 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3549 char lhsused = 0; /* True if the LHS element has been used */
3550 char lhsdirect; /* True if LHS writes directly into stack */
3551 char used[MAXRHS]; /* True for each RHS element which is used */
3552 char zLhs[50]; /* Convert the LHS symbol into this string */
3553 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003554
3555 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3556 lhsused = 0;
3557
drh19c9e562007-03-29 20:13:53 +00003558 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003559 static char newlinestr[2] = { '\n', '\0' };
3560 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003561 rp->line = rp->ruleline;
drh711c9812016-05-23 14:24:31 +00003562 rp->noCode = 1;
3563 }else{
3564 rp->noCode = 0;
drh19c9e562007-03-29 20:13:53 +00003565 }
3566
drh4dd0d3f2016-02-17 01:18:33 +00003567
drh2e55b042016-04-30 17:19:30 +00003568 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003569 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3570 lhsdirect = 1;
3571 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003572 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003573 ** we have to call the distructor on the RHS symbol first. */
3574 lhsdirect = 1;
3575 if( has_destructor(rp->rhs[0],lemp) ){
3576 append_str(0,0,0,0);
3577 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3578 rp->rhs[0]->index,1-rp->nrhs);
3579 rp->codePrefix = Strsafe(append_str(0,0,0,0));
drh711c9812016-05-23 14:24:31 +00003580 rp->noCode = 0;
drh4dd0d3f2016-02-17 01:18:33 +00003581 }
drh2e55b042016-04-30 17:19:30 +00003582 }else if( rp->lhsalias==0 ){
3583 /* There is no LHS value symbol. */
3584 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003585 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3586 /* The LHS symbol and the left-most RHS symbol are the same, so
3587 ** direct writing is allowed */
3588 lhsdirect = 1;
3589 lhsused = 1;
3590 used[0] = 1;
3591 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3592 ErrorMsg(lemp->filename,rp->ruleline,
3593 "%s(%s) and %s(%s) share the same label but have "
3594 "different datatypes.",
3595 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3596 lemp->errorcnt++;
3597 }
3598 }else{
drhcf82f0d2016-02-17 04:33:10 +00003599 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3600 rp->lhsalias, rp->rhsalias[0]);
3601 zSkip = strstr(rp->code, zOvwrt);
3602 if( zSkip!=0 ){
3603 /* The code contains a special comment that indicates that it is safe
3604 ** for the LHS label to overwrite left-most RHS label. */
3605 lhsdirect = 1;
3606 }else{
3607 lhsdirect = 0;
3608 }
drh4dd0d3f2016-02-17 01:18:33 +00003609 }
3610 if( lhsdirect ){
3611 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3612 }else{
drhdabd04c2016-02-17 01:46:19 +00003613 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003614 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3615 }
3616
drh0bb132b2004-07-20 14:06:51 +00003617 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003618
3619 /* This const cast is wrong but harmless, if we're careful. */
3620 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003621 if( cp==zSkip ){
3622 append_str(zOvwrt,0,0,0);
3623 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003624 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003625 continue;
3626 }
drhc56fac72015-10-29 13:48:15 +00003627 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003628 char saved;
drhc56fac72015-10-29 13:48:15 +00003629 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003630 saved = *xp;
3631 *xp = 0;
3632 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003633 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003634 cp = xp;
3635 lhsused = 1;
3636 }else{
3637 for(i=0; i<rp->nrhs; i++){
3638 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003639 if( i==0 && dontUseRhs0 ){
3640 ErrorMsg(lemp->filename,rp->ruleline,
3641 "Label %s used after '%s'.",
3642 rp->rhsalias[0], zOvwrt);
3643 lemp->errorcnt++;
3644 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003645 /* If the argument is of the form @X then substituted
3646 ** the token number of X, not the value of X */
3647 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3648 }else{
drhfd405312005-11-06 04:06:59 +00003649 struct symbol *sp = rp->rhs[i];
3650 int dtnum;
3651 if( sp->type==MULTITERMINAL ){
3652 dtnum = sp->subsym[0]->dtnum;
3653 }else{
3654 dtnum = sp->dtnum;
3655 }
3656 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003657 }
drh0bb132b2004-07-20 14:06:51 +00003658 cp = xp;
3659 used[i] = 1;
3660 break;
3661 }
3662 }
3663 }
3664 *xp = saved;
3665 }
3666 append_str(cp, 1, 0, 0);
3667 } /* End loop */
3668
drh4dd0d3f2016-02-17 01:18:33 +00003669 /* Main code generation completed */
3670 cp = append_str(0,0,0,0);
3671 if( cp && cp[0] ) rp->code = Strsafe(cp);
3672 append_str(0,0,0,0);
3673
drh0bb132b2004-07-20 14:06:51 +00003674 /* Check to make sure the LHS has been used */
3675 if( rp->lhsalias && !lhsused ){
3676 ErrorMsg(lemp->filename,rp->ruleline,
3677 "Label \"%s\" for \"%s(%s)\" is never used.",
3678 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3679 lemp->errorcnt++;
3680 }
3681
drh4dd0d3f2016-02-17 01:18:33 +00003682 /* Generate destructor code for RHS minor values which are not referenced.
3683 ** Generate error messages for unused labels and duplicate labels.
3684 */
drh0bb132b2004-07-20 14:06:51 +00003685 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003686 if( rp->rhsalias[i] ){
3687 if( i>0 ){
3688 int j;
3689 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3690 ErrorMsg(lemp->filename,rp->ruleline,
3691 "%s(%s) has the same label as the LHS but is not the left-most "
3692 "symbol on the RHS.",
3693 rp->rhs[i]->name, rp->rhsalias);
3694 lemp->errorcnt++;
3695 }
3696 for(j=0; j<i; j++){
3697 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3698 ErrorMsg(lemp->filename,rp->ruleline,
3699 "Label %s used for multiple symbols on the RHS of a rule.",
3700 rp->rhsalias[i]);
3701 lemp->errorcnt++;
3702 break;
3703 }
3704 }
drh0bb132b2004-07-20 14:06:51 +00003705 }
drh4dd0d3f2016-02-17 01:18:33 +00003706 if( !used[i] ){
3707 ErrorMsg(lemp->filename,rp->ruleline,
3708 "Label %s for \"%s(%s)\" is never used.",
3709 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3710 lemp->errorcnt++;
3711 }
3712 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3713 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3714 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003715 }
3716 }
drh4dd0d3f2016-02-17 01:18:33 +00003717
3718 /* If unable to write LHS values directly into the stack, write the
3719 ** saved LHS value now. */
3720 if( lhsdirect==0 ){
3721 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3722 append_str(zLhs, 0, 0, 0);
3723 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003724 }
drh4dd0d3f2016-02-17 01:18:33 +00003725
3726 /* Suffix code generation complete */
3727 cp = append_str(0,0,0,0);
drh711c9812016-05-23 14:24:31 +00003728 if( cp && cp[0] ){
3729 rp->codeSuffix = Strsafe(cp);
3730 rp->noCode = 0;
3731 }
drhdabd04c2016-02-17 01:46:19 +00003732
3733 return rc;
drh0bb132b2004-07-20 14:06:51 +00003734}
3735
drh75897232000-05-29 14:26:00 +00003736/*
3737** Generate code which executes when the rule "rp" is reduced. Write
3738** the code to "out". Make sure lineno stays up-to-date.
3739*/
icculus9e44cf12010-02-14 17:14:22 +00003740PRIVATE void emit_code(
3741 FILE *out,
3742 struct rule *rp,
3743 struct lemon *lemp,
3744 int *lineno
3745){
3746 const char *cp;
drh75897232000-05-29 14:26:00 +00003747
drh4dd0d3f2016-02-17 01:18:33 +00003748 /* Setup code prior to the #line directive */
3749 if( rp->codePrefix && rp->codePrefix[0] ){
3750 fprintf(out, "{%s", rp->codePrefix);
3751 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3752 }
3753
drh75897232000-05-29 14:26:00 +00003754 /* Generate code to do the reduce action */
3755 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003756 if( !lemp->nolinenosflag ){
3757 (*lineno)++;
3758 tplt_linedir(out,rp->line,lemp->filename);
3759 }
drhaf805ca2004-09-07 11:28:25 +00003760 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003761 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003762 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003763 if( !lemp->nolinenosflag ){
3764 (*lineno)++;
3765 tplt_linedir(out,*lineno,lemp->outname);
3766 }
drh4dd0d3f2016-02-17 01:18:33 +00003767 }
3768
3769 /* Generate breakdown code that occurs after the #line directive */
3770 if( rp->codeSuffix && rp->codeSuffix[0] ){
3771 fprintf(out, "%s", rp->codeSuffix);
3772 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3773 }
3774
3775 if( rp->codePrefix ){
3776 fprintf(out, "}\n"); (*lineno)++;
3777 }
drh75897232000-05-29 14:26:00 +00003778
drh75897232000-05-29 14:26:00 +00003779 return;
3780}
3781
3782/*
3783** Print the definition of the union used for the parser's data stack.
3784** This union contains fields for every possible data type for tokens
3785** and nonterminals. In the process of computing and printing this
3786** union, also set the ".dtnum" field of every terminal and nonterminal
3787** symbol.
3788*/
icculus9e44cf12010-02-14 17:14:22 +00003789void print_stack_union(
3790 FILE *out, /* The output stream */
3791 struct lemon *lemp, /* The main info structure for this parser */
3792 int *plineno, /* Pointer to the line number */
3793 int mhflag /* True if generating makeheaders output */
3794){
drh75897232000-05-29 14:26:00 +00003795 int lineno = *plineno; /* The line number of the output */
3796 char **types; /* A hash table of datatypes */
3797 int arraysize; /* Size of the "types" array */
3798 int maxdtlength; /* Maximum length of any ".datatype" field. */
3799 char *stddt; /* Standardized name for a datatype */
3800 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003801 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003802 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003803
3804 /* Allocate and initialize types[] and allocate stddt[] */
3805 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003806 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003807 if( types==0 ){
3808 fprintf(stderr,"Out of memory.\n");
3809 exit(1);
3810 }
drh75897232000-05-29 14:26:00 +00003811 for(i=0; i<arraysize; i++) types[i] = 0;
3812 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003813 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003814 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003815 }
drh75897232000-05-29 14:26:00 +00003816 for(i=0; i<lemp->nsymbol; i++){
3817 int len;
3818 struct symbol *sp = lemp->symbols[i];
3819 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003820 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003821 if( len>maxdtlength ) maxdtlength = len;
3822 }
3823 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003824 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003825 fprintf(stderr,"Out of memory.\n");
3826 exit(1);
3827 }
3828
3829 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3830 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003831 ** used for terminal symbols. If there is no %default_type defined then
3832 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3833 ** a datatype using the %type directive.
3834 */
drh75897232000-05-29 14:26:00 +00003835 for(i=0; i<lemp->nsymbol; i++){
3836 struct symbol *sp = lemp->symbols[i];
3837 char *cp;
3838 if( sp==lemp->errsym ){
3839 sp->dtnum = arraysize+1;
3840 continue;
3841 }
drh960e8c62001-04-03 16:53:21 +00003842 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003843 sp->dtnum = 0;
3844 continue;
3845 }
3846 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003847 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003848 j = 0;
drhc56fac72015-10-29 13:48:15 +00003849 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003850 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003851 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003852 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003853 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003854 sp->dtnum = 0;
3855 continue;
3856 }
drh75897232000-05-29 14:26:00 +00003857 hash = 0;
3858 for(j=0; stddt[j]; j++){
3859 hash = hash*53 + stddt[j];
3860 }
drh3b2129c2003-05-13 00:34:21 +00003861 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003862 while( types[hash] ){
3863 if( strcmp(types[hash],stddt)==0 ){
3864 sp->dtnum = hash + 1;
3865 break;
3866 }
3867 hash++;
drh2b51f212013-10-11 23:01:02 +00003868 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003869 }
3870 if( types[hash]==0 ){
3871 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003872 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003873 if( types[hash]==0 ){
3874 fprintf(stderr,"Out of memory.\n");
3875 exit(1);
3876 }
drh898799f2014-01-10 23:21:00 +00003877 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003878 }
3879 }
3880
3881 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3882 name = lemp->name ? lemp->name : "Parse";
3883 lineno = *plineno;
3884 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3885 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3886 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3887 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3888 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003889 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003890 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3891 for(i=0; i<arraysize; i++){
3892 if( types[i]==0 ) continue;
3893 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3894 free(types[i]);
3895 }
drhc4dd3fd2008-01-22 01:48:05 +00003896 if( lemp->errsym->useCnt ){
3897 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3898 }
drh75897232000-05-29 14:26:00 +00003899 free(stddt);
3900 free(types);
3901 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3902 *plineno = lineno;
3903}
3904
drhb29b0a52002-02-23 19:39:46 +00003905/*
3906** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003907** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3908** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003909*/
drhc75e0162015-09-07 02:23:02 +00003910static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3911 const char *zType = "int";
3912 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003913 if( lwr>=0 ){
3914 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003915 zType = "unsigned char";
3916 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003917 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003918 zType = "unsigned short int";
3919 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003920 }else{
drhc75e0162015-09-07 02:23:02 +00003921 zType = "unsigned int";
3922 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003923 }
3924 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003925 zType = "signed char";
3926 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003927 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003928 zType = "short";
3929 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003930 }
drhc75e0162015-09-07 02:23:02 +00003931 if( pnByte ) *pnByte = nByte;
3932 return zType;
drhb29b0a52002-02-23 19:39:46 +00003933}
3934
drhfdbf9282003-10-21 16:34:41 +00003935/*
3936** Each state contains a set of token transaction and a set of
3937** nonterminal transactions. Each of these sets makes an instance
3938** of the following structure. An array of these structures is used
3939** to order the creation of entries in the yy_action[] table.
3940*/
3941struct axset {
3942 struct state *stp; /* A pointer to a state */
3943 int isTkn; /* True to use tokens. False for non-terminals */
3944 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003945 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003946};
3947
3948/*
3949** Compare to axset structures for sorting purposes
3950*/
3951static int axset_compare(const void *a, const void *b){
3952 struct axset *p1 = (struct axset*)a;
3953 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003954 int c;
3955 c = p2->nAction - p1->nAction;
3956 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003957 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003958 }
3959 assert( c!=0 || p1==p2 );
3960 return c;
drhfdbf9282003-10-21 16:34:41 +00003961}
3962
drhc4dd3fd2008-01-22 01:48:05 +00003963/*
3964** Write text on "out" that describes the rule "rp".
3965*/
3966static void writeRuleText(FILE *out, struct rule *rp){
3967 int j;
3968 fprintf(out,"%s ::=", rp->lhs->name);
3969 for(j=0; j<rp->nrhs; j++){
3970 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003971 if( sp->type!=MULTITERMINAL ){
3972 fprintf(out," %s", sp->name);
3973 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003974 int k;
drh61f92cd2014-01-11 03:06:18 +00003975 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003976 for(k=1; k<sp->nsubsym; k++){
3977 fprintf(out,"|%s",sp->subsym[k]->name);
3978 }
3979 }
3980 }
3981}
3982
3983
drh75897232000-05-29 14:26:00 +00003984/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003985void ReportTable(
3986 struct lemon *lemp,
3987 int mhflag /* Output in makeheaders format if true */
3988){
drh75897232000-05-29 14:26:00 +00003989 FILE *out, *in;
3990 char line[LINESIZE];
3991 int lineno;
3992 struct state *stp;
3993 struct action *ap;
3994 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003995 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003996 int i, j, n, sz;
3997 int szActionType; /* sizeof(YYACTIONTYPE) */
3998 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003999 const char *name;
drh8b582012003-10-21 13:16:03 +00004000 int mnTknOfst, mxTknOfst;
4001 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00004002 struct axset *ax;
drh75897232000-05-29 14:26:00 +00004003
4004 in = tplt_open(lemp);
4005 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00004006 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00004007 if( out==0 ){
4008 fclose(in);
4009 return;
4010 }
4011 lineno = 1;
4012 tplt_xfer(lemp->name,in,out,&lineno);
4013
4014 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004015 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004016 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004017 char *incName = file_makename(lemp, ".h");
4018 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4019 free(incName);
drh75897232000-05-29 14:26:00 +00004020 }
4021 tplt_xfer(lemp->name,in,out,&lineno);
4022
4023 /* Generate #defines for all tokens */
4024 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004025 const char *prefix;
drh75897232000-05-29 14:26:00 +00004026 fprintf(out,"#if INTERFACE\n"); lineno++;
4027 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4028 else prefix = "";
4029 for(i=1; i<lemp->nterminal; i++){
4030 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4031 lineno++;
4032 }
4033 fprintf(out,"#endif\n"); lineno++;
4034 }
4035 tplt_xfer(lemp->name,in,out,&lineno);
4036
4037 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004038 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00004039 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00004040 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
4041 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00004042 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004043 if( lemp->wildcard ){
4044 fprintf(out,"#define YYWILDCARD %d\n",
4045 lemp->wildcard->index); lineno++;
4046 }
drh75897232000-05-29 14:26:00 +00004047 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004048 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004049 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004050 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4051 }else{
4052 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4053 }
drhca44b5a2007-02-22 23:06:58 +00004054 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004055 if( mhflag ){
4056 fprintf(out,"#if INTERFACE\n"); lineno++;
4057 }
4058 name = lemp->name ? lemp->name : "Parse";
4059 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004060 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004061 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4062 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004063 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4064 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4065 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
4066 name,lemp->arg,&lemp->arg[i]); lineno++;
4067 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
4068 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004069 }else{
drh1f245e42002-03-11 13:55:50 +00004070 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4071 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4072 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4073 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004074 }
4075 if( mhflag ){
4076 fprintf(out,"#endif\n"); lineno++;
4077 }
drhc4dd3fd2008-01-22 01:48:05 +00004078 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004079 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4080 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004081 }
drh0bd1f4e2002-06-06 18:54:39 +00004082 if( lemp->has_fallback ){
4083 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4084 }
drh75897232000-05-29 14:26:00 +00004085
drh3bd48ab2015-09-07 18:23:37 +00004086 /* Compute the action table, but do not output it yet. The action
4087 ** table must be computed before generating the YYNSTATE macro because
4088 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004089 */
drh3bd48ab2015-09-07 18:23:37 +00004090 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004091 if( ax==0 ){
4092 fprintf(stderr,"malloc failed\n");
4093 exit(1);
4094 }
drh3bd48ab2015-09-07 18:23:37 +00004095 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004096 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004097 ax[i*2].stp = stp;
4098 ax[i*2].isTkn = 1;
4099 ax[i*2].nAction = stp->nTknAct;
4100 ax[i*2+1].stp = stp;
4101 ax[i*2+1].isTkn = 0;
4102 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004103 }
drh8b582012003-10-21 13:16:03 +00004104 mxTknOfst = mnTknOfst = 0;
4105 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004106 /* In an effort to minimize the action table size, use the heuristic
4107 ** of placing the largest action sets first */
4108 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4109 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004110 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004111 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004112 stp = ax[i].stp;
4113 if( ax[i].isTkn ){
4114 for(ap=stp->ap; ap; ap=ap->next){
4115 int action;
4116 if( ap->sp->index>=lemp->nterminal ) continue;
4117 action = compute_action(lemp, ap);
4118 if( action<0 ) continue;
4119 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004120 }
drhfdbf9282003-10-21 16:34:41 +00004121 stp->iTknOfst = acttab_insert(pActtab);
4122 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4123 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4124 }else{
4125 for(ap=stp->ap; ap; ap=ap->next){
4126 int action;
4127 if( ap->sp->index<lemp->nterminal ) continue;
4128 if( ap->sp->index==lemp->nsymbol ) continue;
4129 action = compute_action(lemp, ap);
4130 if( action<0 ) continue;
4131 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004132 }
drhfdbf9282003-10-21 16:34:41 +00004133 stp->iNtOfst = acttab_insert(pActtab);
4134 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4135 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004136 }
drh337cd0d2015-09-07 23:40:42 +00004137#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4138 { int jj, nn;
4139 for(jj=nn=0; jj<pActtab->nAction; jj++){
4140 if( pActtab->aAction[jj].action<0 ) nn++;
4141 }
4142 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4143 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4144 ax[i].nAction, pActtab->nAction, nn);
4145 }
4146#endif
drh8b582012003-10-21 13:16:03 +00004147 }
drhfdbf9282003-10-21 16:34:41 +00004148 free(ax);
drh8b582012003-10-21 13:16:03 +00004149
drh3bd48ab2015-09-07 18:23:37 +00004150 /* Finish rendering the constants now that the action table has
4151 ** been computed */
4152 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4153 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004154 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004155 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4156 i = lemp->nstate + lemp->nrule;
4157 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4158 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
4159 i = lemp->nstate + lemp->nrule*2;
4160 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4161 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
4162 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
4163 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
4164 tplt_xfer(lemp->name,in,out,&lineno);
4165
4166 /* Now output the action table and its associates:
4167 **
4168 ** yy_action[] A single table containing all actions.
4169 ** yy_lookahead[] A table containing the lookahead for each entry in
4170 ** yy_action. Used to detect hash collisions.
4171 ** yy_shift_ofst[] For each state, the offset into yy_action for
4172 ** shifting terminals.
4173 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4174 ** shifting non-terminals after a reduce.
4175 ** yy_default[] Default action for each state.
4176 */
4177
drh8b582012003-10-21 13:16:03 +00004178 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004179 lemp->nactiontab = n = acttab_size(pActtab);
4180 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004181 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4182 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004183 for(i=j=0; i<n; i++){
4184 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00004185 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00004186 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004187 fprintf(out, " %4d,", action);
4188 if( j==9 || i==n-1 ){
4189 fprintf(out, "\n"); lineno++;
4190 j = 0;
4191 }else{
4192 j++;
4193 }
4194 }
4195 fprintf(out, "};\n"); lineno++;
4196
4197 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004198 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004199 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004200 for(i=j=0; i<n; i++){
4201 int la = acttab_yylookahead(pActtab, i);
4202 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004203 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004204 fprintf(out, " %4d,", la);
4205 if( j==9 || i==n-1 ){
4206 fprintf(out, "\n"); lineno++;
4207 j = 0;
4208 }else{
4209 j++;
4210 }
4211 }
4212 fprintf(out, "};\n"); lineno++;
4213
4214 /* Output the yy_shift_ofst[] table */
4215 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004216 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004217 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004218 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4219 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4220 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004221 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004222 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4223 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004224 for(i=j=0; i<n; i++){
4225 int ofst;
4226 stp = lemp->sorted[i];
4227 ofst = stp->iTknOfst;
4228 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004229 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004230 fprintf(out, " %4d,", ofst);
4231 if( j==9 || i==n-1 ){
4232 fprintf(out, "\n"); lineno++;
4233 j = 0;
4234 }else{
4235 j++;
4236 }
4237 }
4238 fprintf(out, "};\n"); lineno++;
4239
4240 /* Output the yy_reduce_ofst[] table */
4241 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004242 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004243 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004244 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4245 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4246 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004247 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004248 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4249 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004250 for(i=j=0; i<n; i++){
4251 int ofst;
4252 stp = lemp->sorted[i];
4253 ofst = stp->iNtOfst;
4254 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004255 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004256 fprintf(out, " %4d,", ofst);
4257 if( j==9 || i==n-1 ){
4258 fprintf(out, "\n"); lineno++;
4259 j = 0;
4260 }else{
4261 j++;
4262 }
4263 }
4264 fprintf(out, "};\n"); lineno++;
4265
4266 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004267 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004268 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004269 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004270 for(i=j=0; i<n; i++){
4271 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004272 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004273 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004274 if( j==9 || i==n-1 ){
4275 fprintf(out, "\n"); lineno++;
4276 j = 0;
4277 }else{
4278 j++;
4279 }
4280 }
4281 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004282 tplt_xfer(lemp->name,in,out,&lineno);
4283
drh0bd1f4e2002-06-06 18:54:39 +00004284 /* Generate the table of fallback tokens.
4285 */
4286 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004287 int mx = lemp->nterminal - 1;
4288 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004289 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004290 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004291 struct symbol *p = lemp->symbols[i];
4292 if( p->fallback==0 ){
4293 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4294 }else{
4295 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4296 p->name, p->fallback->name);
4297 }
4298 lineno++;
4299 }
4300 }
4301 tplt_xfer(lemp->name, in, out, &lineno);
4302
4303 /* Generate a table containing the symbolic name of every symbol
4304 */
drh75897232000-05-29 14:26:00 +00004305 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004306 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004307 fprintf(out," %-15s",line);
4308 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4309 }
4310 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4311 tplt_xfer(lemp->name,in,out,&lineno);
4312
drh0bd1f4e2002-06-06 18:54:39 +00004313 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004314 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004315 ** when tracing REDUCE actions.
4316 */
4317 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004318 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004319 fprintf(out," /* %3d */ \"", i);
4320 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004321 fprintf(out,"\",\n"); lineno++;
4322 }
4323 tplt_xfer(lemp->name,in,out,&lineno);
4324
drh75897232000-05-29 14:26:00 +00004325 /* Generate code which executes every time a symbol is popped from
4326 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004327 ** (In other words, generate the %destructor actions)
4328 */
drh75897232000-05-29 14:26:00 +00004329 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004330 int once = 1;
drh75897232000-05-29 14:26:00 +00004331 for(i=0; i<lemp->nsymbol; i++){
4332 struct symbol *sp = lemp->symbols[i];
4333 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004334 if( once ){
4335 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4336 once = 0;
4337 }
drhc53eed12009-06-12 17:46:19 +00004338 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004339 }
4340 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4341 if( i<lemp->nsymbol ){
4342 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4343 fprintf(out," break;\n"); lineno++;
4344 }
4345 }
drh8d659732005-01-13 23:54:06 +00004346 if( lemp->vardest ){
4347 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004348 int once = 1;
drh8d659732005-01-13 23:54:06 +00004349 for(i=0; i<lemp->nsymbol; i++){
4350 struct symbol *sp = lemp->symbols[i];
4351 if( sp==0 || sp->type==TERMINAL ||
4352 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004353 if( once ){
4354 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4355 once = 0;
4356 }
drhc53eed12009-06-12 17:46:19 +00004357 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004358 dflt_sp = sp;
4359 }
4360 if( dflt_sp!=0 ){
4361 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004362 }
drh4dc8ef52008-07-01 17:13:57 +00004363 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004364 }
drh75897232000-05-29 14:26:00 +00004365 for(i=0; i<lemp->nsymbol; i++){
4366 struct symbol *sp = lemp->symbols[i];
4367 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004368 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004369
4370 /* Combine duplicate destructors into a single case */
4371 for(j=i+1; j<lemp->nsymbol; j++){
4372 struct symbol *sp2 = lemp->symbols[j];
4373 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4374 && sp2->dtnum==sp->dtnum
4375 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004376 fprintf(out," case %d: /* %s */\n",
4377 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004378 sp2->destructor = 0;
4379 }
4380 }
4381
drh75897232000-05-29 14:26:00 +00004382 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4383 fprintf(out," break;\n"); lineno++;
4384 }
drh75897232000-05-29 14:26:00 +00004385 tplt_xfer(lemp->name,in,out,&lineno);
4386
4387 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004388 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004389 tplt_xfer(lemp->name,in,out,&lineno);
4390
4391 /* Generate the table of rule information
4392 **
4393 ** Note: This code depends on the fact that rules are number
4394 ** sequentually beginning with 0.
4395 */
4396 for(rp=lemp->rule; rp; rp=rp->next){
4397 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4398 }
4399 tplt_xfer(lemp->name,in,out,&lineno);
4400
4401 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004402 i = 0;
drh75897232000-05-29 14:26:00 +00004403 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004404 i += translate_code(lemp, rp);
4405 }
4406 if( i ){
4407 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004408 }
drhc53eed12009-06-12 17:46:19 +00004409 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004410 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004411 struct rule *rp2; /* Other rules with the same action */
drh711c9812016-05-23 14:24:31 +00004412 if( rp->codeEmitted ) continue;
4413 if( rp->noCode ){
4414 /* No C code actions, so this will be part of the "default:" rule */
drh2e55b042016-04-30 17:19:30 +00004415 continue;
4416 }
drh4ef07702016-03-16 19:45:54 +00004417 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004418 writeRuleText(out, rp);
4419 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004420 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004421 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4422 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004423 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004424 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004425 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh711c9812016-05-23 14:24:31 +00004426 rp2->codeEmitted = 1;
drh0bb132b2004-07-20 14:06:51 +00004427 }
4428 }
drh75897232000-05-29 14:26:00 +00004429 emit_code(out,rp,lemp,&lineno);
4430 fprintf(out," break;\n"); lineno++;
drh711c9812016-05-23 14:24:31 +00004431 rp->codeEmitted = 1;
drh75897232000-05-29 14:26:00 +00004432 }
drhc53eed12009-06-12 17:46:19 +00004433 /* Finally, output the default: rule. We choose as the default: all
4434 ** empty actions. */
4435 fprintf(out," default:\n"); lineno++;
4436 for(rp=lemp->rule; rp; rp=rp->next){
drh711c9812016-05-23 14:24:31 +00004437 if( rp->codeEmitted ) continue;
4438 assert( rp->noCode );
drh4ef07702016-03-16 19:45:54 +00004439 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004440 writeRuleText(out, rp);
drh4ef07702016-03-16 19:45:54 +00004441 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
drhc53eed12009-06-12 17:46:19 +00004442 }
4443 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004444 tplt_xfer(lemp->name,in,out,&lineno);
4445
4446 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004447 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004448 tplt_xfer(lemp->name,in,out,&lineno);
4449
4450 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004451 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004452 tplt_xfer(lemp->name,in,out,&lineno);
4453
4454 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004455 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004456 tplt_xfer(lemp->name,in,out,&lineno);
4457
4458 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004459 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004460
4461 fclose(in);
4462 fclose(out);
4463 return;
4464}
4465
4466/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004467void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004468{
4469 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004470 const char *prefix;
drh75897232000-05-29 14:26:00 +00004471 char line[LINESIZE];
4472 char pattern[LINESIZE];
4473 int i;
4474
4475 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4476 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004477 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004478 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004479 int nextChar;
drh75897232000-05-29 14:26:00 +00004480 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004481 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4482 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004483 if( strcmp(line,pattern) ) break;
4484 }
drh8ba0d1c2012-06-16 15:26:31 +00004485 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004486 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004487 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004488 /* No change in the file. Don't rewrite it. */
4489 return;
4490 }
4491 }
drh2aa6ca42004-09-10 00:14:04 +00004492 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004493 if( out ){
4494 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004495 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004496 }
4497 fclose(out);
4498 }
4499 return;
4500}
4501
4502/* Reduce the size of the action tables, if possible, by making use
4503** of defaults.
4504**
drhb59499c2002-02-23 18:45:13 +00004505** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004506** it the default. Except, there is no default if the wildcard token
4507** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004508*/
icculus9e44cf12010-02-14 17:14:22 +00004509void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004510{
4511 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004512 struct action *ap, *ap2;
4513 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004514 int nbest, n;
drh75897232000-05-29 14:26:00 +00004515 int i;
drhe09daa92006-06-10 13:29:31 +00004516 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004517
4518 for(i=0; i<lemp->nstate; i++){
4519 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004520 nbest = 0;
4521 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004522 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004523
drhb59499c2002-02-23 18:45:13 +00004524 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004525 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4526 usesWildcard = 1;
4527 }
drhb59499c2002-02-23 18:45:13 +00004528 if( ap->type!=REDUCE ) continue;
4529 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004530 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004531 if( rp==rbest ) continue;
4532 n = 1;
4533 for(ap2=ap->next; ap2; ap2=ap2->next){
4534 if( ap2->type!=REDUCE ) continue;
4535 rp2 = ap2->x.rp;
4536 if( rp2==rbest ) continue;
4537 if( rp2==rp ) n++;
4538 }
4539 if( n>nbest ){
4540 nbest = n;
4541 rbest = rp;
drh75897232000-05-29 14:26:00 +00004542 }
4543 }
drhb59499c2002-02-23 18:45:13 +00004544
4545 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004546 ** is not at least 1 or if the wildcard token is a possible
4547 ** lookahead.
4548 */
4549 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004550
drhb59499c2002-02-23 18:45:13 +00004551
4552 /* Combine matching REDUCE actions into a single default */
4553 for(ap=stp->ap; ap; ap=ap->next){
4554 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4555 }
drh75897232000-05-29 14:26:00 +00004556 assert( ap );
4557 ap->sp = Symbol_new("{default}");
4558 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004559 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004560 }
4561 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004562
4563 for(ap=stp->ap; ap; ap=ap->next){
4564 if( ap->type==SHIFT ) break;
4565 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4566 }
4567 if( ap==0 ){
4568 stp->autoReduce = 1;
4569 stp->pDfltReduce = rbest;
4570 }
4571 }
4572
4573 /* Make a second pass over all states and actions. Convert
4574 ** every action that is a SHIFT to an autoReduce state into
4575 ** a SHIFTREDUCE action.
4576 */
4577 for(i=0; i<lemp->nstate; i++){
4578 stp = lemp->sorted[i];
4579 for(ap=stp->ap; ap; ap=ap->next){
4580 struct state *pNextState;
4581 if( ap->type!=SHIFT ) continue;
4582 pNextState = ap->x.stp;
4583 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4584 ap->type = SHIFTREDUCE;
4585 ap->x.rp = pNextState->pDfltReduce;
4586 }
4587 }
drh75897232000-05-29 14:26:00 +00004588 }
4589}
drhb59499c2002-02-23 18:45:13 +00004590
drhada354d2005-11-05 15:03:59 +00004591
4592/*
4593** Compare two states for sorting purposes. The smaller state is the
4594** one with the most non-terminal actions. If they have the same number
4595** of non-terminal actions, then the smaller is the one with the most
4596** token actions.
4597*/
4598static int stateResortCompare(const void *a, const void *b){
4599 const struct state *pA = *(const struct state**)a;
4600 const struct state *pB = *(const struct state**)b;
4601 int n;
4602
4603 n = pB->nNtAct - pA->nNtAct;
4604 if( n==0 ){
4605 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004606 if( n==0 ){
4607 n = pB->statenum - pA->statenum;
4608 }
drhada354d2005-11-05 15:03:59 +00004609 }
drhe594bc32009-11-03 13:02:25 +00004610 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004611 return n;
4612}
4613
4614
4615/*
4616** Renumber and resort states so that states with fewer choices
4617** occur at the end. Except, keep state 0 as the first state.
4618*/
icculus9e44cf12010-02-14 17:14:22 +00004619void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004620{
4621 int i;
4622 struct state *stp;
4623 struct action *ap;
4624
4625 for(i=0; i<lemp->nstate; i++){
4626 stp = lemp->sorted[i];
4627 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004628 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004629 stp->iTknOfst = NO_OFFSET;
4630 stp->iNtOfst = NO_OFFSET;
4631 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004632 int iAction = compute_action(lemp,ap);
4633 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004634 if( ap->sp->index<lemp->nterminal ){
4635 stp->nTknAct++;
4636 }else if( ap->sp->index<lemp->nsymbol ){
4637 stp->nNtAct++;
4638 }else{
drh3bd48ab2015-09-07 18:23:37 +00004639 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4640 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004641 }
4642 }
4643 }
4644 }
4645 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4646 stateResortCompare);
4647 for(i=0; i<lemp->nstate; i++){
4648 lemp->sorted[i]->statenum = i;
4649 }
drh3bd48ab2015-09-07 18:23:37 +00004650 lemp->nxstate = lemp->nstate;
4651 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4652 lemp->nxstate--;
4653 }
drhada354d2005-11-05 15:03:59 +00004654}
4655
4656
drh75897232000-05-29 14:26:00 +00004657/***************** From the file "set.c" ************************************/
4658/*
4659** Set manipulation routines for the LEMON parser generator.
4660*/
4661
4662static int size = 0;
4663
4664/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004665void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004666{
4667 size = n+1;
4668}
4669
4670/* Allocate a new set */
4671char *SetNew(){
4672 char *s;
drh9892c5d2007-12-21 00:02:11 +00004673 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004674 if( s==0 ){
4675 extern void memory_error();
4676 memory_error();
4677 }
drh75897232000-05-29 14:26:00 +00004678 return s;
4679}
4680
4681/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004682void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004683{
4684 free(s);
4685}
4686
4687/* Add a new element to the set. Return TRUE if the element was added
4688** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004689int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004690{
4691 int rv;
drh9892c5d2007-12-21 00:02:11 +00004692 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004693 rv = s[e];
4694 s[e] = 1;
4695 return !rv;
4696}
4697
4698/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004699int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004700{
4701 int i, progress;
4702 progress = 0;
4703 for(i=0; i<size; i++){
4704 if( s2[i]==0 ) continue;
4705 if( s1[i]==0 ){
4706 progress = 1;
4707 s1[i] = 1;
4708 }
4709 }
4710 return progress;
4711}
4712/********************** From the file "table.c" ****************************/
4713/*
4714** All code in this file has been automatically generated
4715** from a specification in the file
4716** "table.q"
4717** by the associative array code building program "aagen".
4718** Do not edit this file! Instead, edit the specification
4719** file, then rerun aagen.
4720*/
4721/*
4722** Code for processing tables in the LEMON parser generator.
4723*/
4724
drh01f75f22013-10-02 20:46:30 +00004725PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004726{
drh01f75f22013-10-02 20:46:30 +00004727 unsigned h = 0;
4728 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004729 return h;
4730}
4731
4732/* Works like strdup, sort of. Save a string in malloced memory, but
4733** keep strings in a table so that the same string is not in more
4734** than one place.
4735*/
icculus9e44cf12010-02-14 17:14:22 +00004736const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004737{
icculus9e44cf12010-02-14 17:14:22 +00004738 const char *z;
4739 char *cpy;
drh75897232000-05-29 14:26:00 +00004740
drh916f75f2006-07-17 00:19:39 +00004741 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004742 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004743 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004744 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004745 z = cpy;
drh75897232000-05-29 14:26:00 +00004746 Strsafe_insert(z);
4747 }
4748 MemoryCheck(z);
4749 return z;
4750}
4751
4752/* There is one instance of the following structure for each
4753** associative array of type "x1".
4754*/
4755struct s_x1 {
4756 int size; /* The number of available slots. */
4757 /* Must be a power of 2 greater than or */
4758 /* equal to 1 */
4759 int count; /* Number of currently slots filled */
4760 struct s_x1node *tbl; /* The data stored here */
4761 struct s_x1node **ht; /* Hash table for lookups */
4762};
4763
4764/* There is one instance of this structure for every data element
4765** in an associative array of type "x1".
4766*/
4767typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004768 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004769 struct s_x1node *next; /* Next entry with the same hash */
4770 struct s_x1node **from; /* Previous link */
4771} x1node;
4772
4773/* There is only one instance of the array, which is the following */
4774static struct s_x1 *x1a;
4775
4776/* Allocate a new associative array */
4777void Strsafe_init(){
4778 if( x1a ) return;
4779 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4780 if( x1a ){
4781 x1a->size = 1024;
4782 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004783 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004784 if( x1a->tbl==0 ){
4785 free(x1a);
4786 x1a = 0;
4787 }else{
4788 int i;
4789 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4790 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4791 }
4792 }
4793}
4794/* Insert a new record into the array. Return TRUE if successful.
4795** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004796int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004797{
4798 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004799 unsigned h;
4800 unsigned ph;
drh75897232000-05-29 14:26:00 +00004801
4802 if( x1a==0 ) return 0;
4803 ph = strhash(data);
4804 h = ph & (x1a->size-1);
4805 np = x1a->ht[h];
4806 while( np ){
4807 if( strcmp(np->data,data)==0 ){
4808 /* An existing entry with the same key is found. */
4809 /* Fail because overwrite is not allows. */
4810 return 0;
4811 }
4812 np = np->next;
4813 }
4814 if( x1a->count>=x1a->size ){
4815 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004816 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004817 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004818 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004819 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004820 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004821 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004822 array.ht = (x1node**)&(array.tbl[arrSize]);
4823 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004824 for(i=0; i<x1a->count; i++){
4825 x1node *oldnp, *newnp;
4826 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004827 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004828 newnp = &(array.tbl[i]);
4829 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4830 newnp->next = array.ht[h];
4831 newnp->data = oldnp->data;
4832 newnp->from = &(array.ht[h]);
4833 array.ht[h] = newnp;
4834 }
4835 free(x1a->tbl);
4836 *x1a = array;
4837 }
4838 /* Insert the new data */
4839 h = ph & (x1a->size-1);
4840 np = &(x1a->tbl[x1a->count++]);
4841 np->data = data;
4842 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4843 np->next = x1a->ht[h];
4844 x1a->ht[h] = np;
4845 np->from = &(x1a->ht[h]);
4846 return 1;
4847}
4848
4849/* Return a pointer to data assigned to the given key. Return NULL
4850** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004851const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004852{
drh01f75f22013-10-02 20:46:30 +00004853 unsigned h;
drh75897232000-05-29 14:26:00 +00004854 x1node *np;
4855
4856 if( x1a==0 ) return 0;
4857 h = strhash(key) & (x1a->size-1);
4858 np = x1a->ht[h];
4859 while( np ){
4860 if( strcmp(np->data,key)==0 ) break;
4861 np = np->next;
4862 }
4863 return np ? np->data : 0;
4864}
4865
4866/* Return a pointer to the (terminal or nonterminal) symbol "x".
4867** Create a new symbol if this is the first time "x" has been seen.
4868*/
icculus9e44cf12010-02-14 17:14:22 +00004869struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004870{
4871 struct symbol *sp;
4872
4873 sp = Symbol_find(x);
4874 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004875 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004876 MemoryCheck(sp);
4877 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004878 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004879 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004880 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004881 sp->prec = -1;
4882 sp->assoc = UNK;
4883 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004884 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004885 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004886 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004887 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004888 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004889 Symbol_insert(sp,sp->name);
4890 }
drhc4dd3fd2008-01-22 01:48:05 +00004891 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004892 return sp;
4893}
4894
drh61f92cd2014-01-11 03:06:18 +00004895/* Compare two symbols for sorting purposes. Return negative,
4896** zero, or positive if a is less then, equal to, or greater
4897** than b.
drh60d31652004-02-22 00:08:04 +00004898**
4899** Symbols that begin with upper case letters (terminals or tokens)
4900** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004901** (non-terminals). And MULTITERMINAL symbols (created using the
4902** %token_class directive) must sort at the very end. Other than
4903** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004904**
4905** We find experimentally that leaving the symbols in their original
4906** order (the order they appeared in the grammar file) gives the
4907** smallest parser tables in SQLite.
4908*/
icculus9e44cf12010-02-14 17:14:22 +00004909int Symbolcmpp(const void *_a, const void *_b)
4910{
drh61f92cd2014-01-11 03:06:18 +00004911 const struct symbol *a = *(const struct symbol **) _a;
4912 const struct symbol *b = *(const struct symbol **) _b;
4913 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4914 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4915 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004916}
4917
4918/* There is one instance of the following structure for each
4919** associative array of type "x2".
4920*/
4921struct s_x2 {
4922 int size; /* The number of available slots. */
4923 /* Must be a power of 2 greater than or */
4924 /* equal to 1 */
4925 int count; /* Number of currently slots filled */
4926 struct s_x2node *tbl; /* The data stored here */
4927 struct s_x2node **ht; /* Hash table for lookups */
4928};
4929
4930/* There is one instance of this structure for every data element
4931** in an associative array of type "x2".
4932*/
4933typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004934 struct symbol *data; /* The data */
4935 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004936 struct s_x2node *next; /* Next entry with the same hash */
4937 struct s_x2node **from; /* Previous link */
4938} x2node;
4939
4940/* There is only one instance of the array, which is the following */
4941static struct s_x2 *x2a;
4942
4943/* Allocate a new associative array */
4944void Symbol_init(){
4945 if( x2a ) return;
4946 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4947 if( x2a ){
4948 x2a->size = 128;
4949 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004950 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004951 if( x2a->tbl==0 ){
4952 free(x2a);
4953 x2a = 0;
4954 }else{
4955 int i;
4956 x2a->ht = (x2node**)&(x2a->tbl[128]);
4957 for(i=0; i<128; i++) x2a->ht[i] = 0;
4958 }
4959 }
4960}
4961/* Insert a new record into the array. Return TRUE if successful.
4962** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004963int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004964{
4965 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004966 unsigned h;
4967 unsigned ph;
drh75897232000-05-29 14:26:00 +00004968
4969 if( x2a==0 ) return 0;
4970 ph = strhash(key);
4971 h = ph & (x2a->size-1);
4972 np = x2a->ht[h];
4973 while( np ){
4974 if( strcmp(np->key,key)==0 ){
4975 /* An existing entry with the same key is found. */
4976 /* Fail because overwrite is not allows. */
4977 return 0;
4978 }
4979 np = np->next;
4980 }
4981 if( x2a->count>=x2a->size ){
4982 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004983 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004984 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004985 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004986 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004987 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004988 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004989 array.ht = (x2node**)&(array.tbl[arrSize]);
4990 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004991 for(i=0; i<x2a->count; i++){
4992 x2node *oldnp, *newnp;
4993 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004994 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004995 newnp = &(array.tbl[i]);
4996 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4997 newnp->next = array.ht[h];
4998 newnp->key = oldnp->key;
4999 newnp->data = oldnp->data;
5000 newnp->from = &(array.ht[h]);
5001 array.ht[h] = newnp;
5002 }
5003 free(x2a->tbl);
5004 *x2a = array;
5005 }
5006 /* Insert the new data */
5007 h = ph & (x2a->size-1);
5008 np = &(x2a->tbl[x2a->count++]);
5009 np->key = key;
5010 np->data = data;
5011 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5012 np->next = x2a->ht[h];
5013 x2a->ht[h] = np;
5014 np->from = &(x2a->ht[h]);
5015 return 1;
5016}
5017
5018/* Return a pointer to data assigned to the given key. Return NULL
5019** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005020struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005021{
drh01f75f22013-10-02 20:46:30 +00005022 unsigned h;
drh75897232000-05-29 14:26:00 +00005023 x2node *np;
5024
5025 if( x2a==0 ) return 0;
5026 h = strhash(key) & (x2a->size-1);
5027 np = x2a->ht[h];
5028 while( np ){
5029 if( strcmp(np->key,key)==0 ) break;
5030 np = np->next;
5031 }
5032 return np ? np->data : 0;
5033}
5034
5035/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005036struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005037{
5038 struct symbol *data;
5039 if( x2a && n>0 && n<=x2a->count ){
5040 data = x2a->tbl[n-1].data;
5041 }else{
5042 data = 0;
5043 }
5044 return data;
5045}
5046
5047/* Return the size of the array */
5048int Symbol_count()
5049{
5050 return x2a ? x2a->count : 0;
5051}
5052
5053/* Return an array of pointers to all data in the table.
5054** The array is obtained from malloc. Return NULL if memory allocation
5055** problems, or if the array is empty. */
5056struct symbol **Symbol_arrayof()
5057{
5058 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005059 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005060 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005061 arrSize = x2a->count;
5062 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005063 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005064 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005065 }
5066 return array;
5067}
5068
5069/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005070int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005071{
icculus9e44cf12010-02-14 17:14:22 +00005072 const struct config *a = (struct config *) _a;
5073 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005074 int x;
5075 x = a->rp->index - b->rp->index;
5076 if( x==0 ) x = a->dot - b->dot;
5077 return x;
5078}
5079
5080/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005081PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005082{
5083 int rc;
5084 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5085 rc = a->rp->index - b->rp->index;
5086 if( rc==0 ) rc = a->dot - b->dot;
5087 }
5088 if( rc==0 ){
5089 if( a ) rc = 1;
5090 if( b ) rc = -1;
5091 }
5092 return rc;
5093}
5094
5095/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005096PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005097{
drh01f75f22013-10-02 20:46:30 +00005098 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005099 while( a ){
5100 h = h*571 + a->rp->index*37 + a->dot;
5101 a = a->bp;
5102 }
5103 return h;
5104}
5105
5106/* Allocate a new state structure */
5107struct state *State_new()
5108{
icculus9e44cf12010-02-14 17:14:22 +00005109 struct state *newstate;
5110 newstate = (struct state *)calloc(1, sizeof(struct state) );
5111 MemoryCheck(newstate);
5112 return newstate;
drh75897232000-05-29 14:26:00 +00005113}
5114
5115/* There is one instance of the following structure for each
5116** associative array of type "x3".
5117*/
5118struct s_x3 {
5119 int size; /* The number of available slots. */
5120 /* Must be a power of 2 greater than or */
5121 /* equal to 1 */
5122 int count; /* Number of currently slots filled */
5123 struct s_x3node *tbl; /* The data stored here */
5124 struct s_x3node **ht; /* Hash table for lookups */
5125};
5126
5127/* There is one instance of this structure for every data element
5128** in an associative array of type "x3".
5129*/
5130typedef struct s_x3node {
5131 struct state *data; /* The data */
5132 struct config *key; /* The key */
5133 struct s_x3node *next; /* Next entry with the same hash */
5134 struct s_x3node **from; /* Previous link */
5135} x3node;
5136
5137/* There is only one instance of the array, which is the following */
5138static struct s_x3 *x3a;
5139
5140/* Allocate a new associative array */
5141void State_init(){
5142 if( x3a ) return;
5143 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5144 if( x3a ){
5145 x3a->size = 128;
5146 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005147 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005148 if( x3a->tbl==0 ){
5149 free(x3a);
5150 x3a = 0;
5151 }else{
5152 int i;
5153 x3a->ht = (x3node**)&(x3a->tbl[128]);
5154 for(i=0; i<128; i++) x3a->ht[i] = 0;
5155 }
5156 }
5157}
5158/* Insert a new record into the array. Return TRUE if successful.
5159** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005160int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005161{
5162 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005163 unsigned h;
5164 unsigned ph;
drh75897232000-05-29 14:26:00 +00005165
5166 if( x3a==0 ) return 0;
5167 ph = statehash(key);
5168 h = ph & (x3a->size-1);
5169 np = x3a->ht[h];
5170 while( np ){
5171 if( statecmp(np->key,key)==0 ){
5172 /* An existing entry with the same key is found. */
5173 /* Fail because overwrite is not allows. */
5174 return 0;
5175 }
5176 np = np->next;
5177 }
5178 if( x3a->count>=x3a->size ){
5179 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005180 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005181 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005182 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005183 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005184 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005185 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005186 array.ht = (x3node**)&(array.tbl[arrSize]);
5187 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005188 for(i=0; i<x3a->count; i++){
5189 x3node *oldnp, *newnp;
5190 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005191 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005192 newnp = &(array.tbl[i]);
5193 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5194 newnp->next = array.ht[h];
5195 newnp->key = oldnp->key;
5196 newnp->data = oldnp->data;
5197 newnp->from = &(array.ht[h]);
5198 array.ht[h] = newnp;
5199 }
5200 free(x3a->tbl);
5201 *x3a = array;
5202 }
5203 /* Insert the new data */
5204 h = ph & (x3a->size-1);
5205 np = &(x3a->tbl[x3a->count++]);
5206 np->key = key;
5207 np->data = data;
5208 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5209 np->next = x3a->ht[h];
5210 x3a->ht[h] = np;
5211 np->from = &(x3a->ht[h]);
5212 return 1;
5213}
5214
5215/* Return a pointer to data assigned to the given key. Return NULL
5216** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005217struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005218{
drh01f75f22013-10-02 20:46:30 +00005219 unsigned h;
drh75897232000-05-29 14:26:00 +00005220 x3node *np;
5221
5222 if( x3a==0 ) return 0;
5223 h = statehash(key) & (x3a->size-1);
5224 np = x3a->ht[h];
5225 while( np ){
5226 if( statecmp(np->key,key)==0 ) break;
5227 np = np->next;
5228 }
5229 return np ? np->data : 0;
5230}
5231
5232/* Return an array of pointers to all data in the table.
5233** The array is obtained from malloc. Return NULL if memory allocation
5234** problems, or if the array is empty. */
5235struct state **State_arrayof()
5236{
5237 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005238 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005239 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005240 arrSize = x3a->count;
5241 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005242 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005243 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005244 }
5245 return array;
5246}
5247
5248/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005249PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005250{
drh01f75f22013-10-02 20:46:30 +00005251 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005252 h = h*571 + a->rp->index*37 + a->dot;
5253 return h;
5254}
5255
5256/* There is one instance of the following structure for each
5257** associative array of type "x4".
5258*/
5259struct s_x4 {
5260 int size; /* The number of available slots. */
5261 /* Must be a power of 2 greater than or */
5262 /* equal to 1 */
5263 int count; /* Number of currently slots filled */
5264 struct s_x4node *tbl; /* The data stored here */
5265 struct s_x4node **ht; /* Hash table for lookups */
5266};
5267
5268/* There is one instance of this structure for every data element
5269** in an associative array of type "x4".
5270*/
5271typedef struct s_x4node {
5272 struct config *data; /* The data */
5273 struct s_x4node *next; /* Next entry with the same hash */
5274 struct s_x4node **from; /* Previous link */
5275} x4node;
5276
5277/* There is only one instance of the array, which is the following */
5278static struct s_x4 *x4a;
5279
5280/* Allocate a new associative array */
5281void Configtable_init(){
5282 if( x4a ) return;
5283 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5284 if( x4a ){
5285 x4a->size = 64;
5286 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005287 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005288 if( x4a->tbl==0 ){
5289 free(x4a);
5290 x4a = 0;
5291 }else{
5292 int i;
5293 x4a->ht = (x4node**)&(x4a->tbl[64]);
5294 for(i=0; i<64; i++) x4a->ht[i] = 0;
5295 }
5296 }
5297}
5298/* Insert a new record into the array. Return TRUE if successful.
5299** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005300int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005301{
5302 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005303 unsigned h;
5304 unsigned ph;
drh75897232000-05-29 14:26:00 +00005305
5306 if( x4a==0 ) return 0;
5307 ph = confighash(data);
5308 h = ph & (x4a->size-1);
5309 np = x4a->ht[h];
5310 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005311 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005312 /* An existing entry with the same key is found. */
5313 /* Fail because overwrite is not allows. */
5314 return 0;
5315 }
5316 np = np->next;
5317 }
5318 if( x4a->count>=x4a->size ){
5319 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005320 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005321 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005322 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005323 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005324 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005325 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005326 array.ht = (x4node**)&(array.tbl[arrSize]);
5327 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005328 for(i=0; i<x4a->count; i++){
5329 x4node *oldnp, *newnp;
5330 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005331 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005332 newnp = &(array.tbl[i]);
5333 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5334 newnp->next = array.ht[h];
5335 newnp->data = oldnp->data;
5336 newnp->from = &(array.ht[h]);
5337 array.ht[h] = newnp;
5338 }
5339 free(x4a->tbl);
5340 *x4a = array;
5341 }
5342 /* Insert the new data */
5343 h = ph & (x4a->size-1);
5344 np = &(x4a->tbl[x4a->count++]);
5345 np->data = data;
5346 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5347 np->next = x4a->ht[h];
5348 x4a->ht[h] = np;
5349 np->from = &(x4a->ht[h]);
5350 return 1;
5351}
5352
5353/* Return a pointer to data assigned to the given key. Return NULL
5354** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005355struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005356{
5357 int h;
5358 x4node *np;
5359
5360 if( x4a==0 ) return 0;
5361 h = confighash(key) & (x4a->size-1);
5362 np = x4a->ht[h];
5363 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005364 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005365 np = np->next;
5366 }
5367 return np ? np->data : 0;
5368}
5369
5370/* Remove all data from the table. Pass each data to the function "f"
5371** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005372void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005373{
5374 int i;
5375 if( x4a==0 || x4a->count==0 ) return;
5376 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5377 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5378 x4a->count = 0;
5379 return;
5380}