blob: 01c8a1da96ed53775bc88d68d42a0aecc98fd61d [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 */
drh75897232000-05-29 14:26:00 +0000291 struct symbol *precsym; /* Precedence symbol for this rule */
292 int index; /* An index number for this rule */
drh4ef07702016-03-16 19:45:54 +0000293 int iRule; /* Rule number as used in the generated tables */
drh75897232000-05-29 14:26:00 +0000294 Boolean canReduce; /* True if this rule is ever reduced */
295 struct rule *nextlhs; /* Next rule with the same LHS */
296 struct rule *next; /* Next rule in the global list */
297};
298
299/* A configuration is a production rule of the grammar together with
300** a mark (dot) showing how much of that rule has been processed so far.
301** Configurations also contain a follow-set which is a list of terminal
302** symbols which are allowed to immediately follow the end of the rule.
303** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000304enum cfgstatus {
305 COMPLETE,
306 INCOMPLETE
307};
drh75897232000-05-29 14:26:00 +0000308struct config {
309 struct rule *rp; /* The rule upon which the configuration is based */
310 int dot; /* The parse point */
311 char *fws; /* Follow-set for this configuration only */
312 struct plink *fplp; /* Follow-set forward propagation links */
313 struct plink *bplp; /* Follow-set backwards propagation links */
314 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000315 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000316 struct config *next; /* Next configuration in the state */
317 struct config *bp; /* The next basis configuration */
318};
319
icculus9e44cf12010-02-14 17:14:22 +0000320enum e_action {
321 SHIFT,
322 ACCEPT,
323 REDUCE,
324 ERROR,
325 SSCONFLICT, /* A shift/shift conflict */
326 SRCONFLICT, /* Was a reduce, but part of a conflict */
327 RRCONFLICT, /* Was a reduce, but part of a conflict */
328 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
329 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000330 NOT_USED, /* Deleted by compression */
331 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000332};
333
drh75897232000-05-29 14:26:00 +0000334/* Every shift or reduce operation is stored as one of the following */
335struct action {
336 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000337 enum e_action type;
drh75897232000-05-29 14:26:00 +0000338 union {
339 struct state *stp; /* The new state, if a shift */
340 struct rule *rp; /* The rule, if a reduce */
341 } x;
342 struct action *next; /* Next action for this state */
343 struct action *collide; /* Next action with the same hash */
344};
345
346/* Each state of the generated parser's finite state machine
347** is encoded as an instance of the following structure. */
348struct state {
349 struct config *bp; /* The basis configurations for this state */
350 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000351 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000352 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000353 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
354 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000355 int iDfltReduce; /* Default action is to REDUCE by this rule */
356 struct rule *pDfltReduce;/* The default REDUCE rule. */
357 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000358};
drh8b582012003-10-21 13:16:03 +0000359#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000360
361/* A followset propagation link indicates that the contents of one
362** configuration followset should be propagated to another whenever
363** the first changes. */
364struct plink {
365 struct config *cfp; /* The configuration to which linked */
366 struct plink *next; /* The next propagate link */
367};
368
369/* The state vector for the entire parser generator is recorded as
370** follows. (LEMON uses no global variables and makes little use of
371** static variables. Fields in the following structure can be thought
372** of as begin global variables in the program.) */
373struct lemon {
374 struct state **sorted; /* Table of states sorted by state number */
375 struct rule *rule; /* List of all rules */
drh4ef07702016-03-16 19:45:54 +0000376 struct rule *startRule; /* First rule */
drh75897232000-05-29 14:26:00 +0000377 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000378 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000379 int nrule; /* Number of rules */
380 int nsymbol; /* Number of terminal and nonterminal symbols */
381 int nterminal; /* Number of terminal symbols */
382 struct symbol **symbols; /* Sorted array of pointers to symbols */
383 int errorcnt; /* Number of errors */
384 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000385 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000386 char *name; /* Name of the generated parser */
387 char *arg; /* Declaration of the 3th argument to parser */
388 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000389 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000390 char *start; /* Name of the start symbol for the grammar */
391 char *stacksize; /* Size of the parser stack */
392 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000393 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000394 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000395 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000396 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000397 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000398 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000399 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000400 char *filename; /* Name of the input file */
401 char *outname; /* Name of the current output file */
402 char *tokenprefix; /* A prefix added to token names in the .h file */
403 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000404 int nactiontab; /* Number of entries in the yy_action[] table */
405 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000406 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000407 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000408 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000409 char *argv0; /* Name of the program */
410};
411
412#define MemoryCheck(X) if((X)==0){ \
413 extern void memory_error(); \
414 memory_error(); \
415}
416
417/**************** From the file "table.h" *********************************/
418/*
419** All code in this file has been automatically generated
420** from a specification in the file
421** "table.q"
422** by the associative array code building program "aagen".
423** Do not edit this file! Instead, edit the specification
424** file, then rerun aagen.
425*/
426/*
427** Code for processing tables in the LEMON parser generator.
428*/
drh75897232000-05-29 14:26:00 +0000429/* Routines for handling a strings */
430
icculus9e44cf12010-02-14 17:14:22 +0000431const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000432
icculus9e44cf12010-02-14 17:14:22 +0000433void Strsafe_init(void);
434int Strsafe_insert(const char *);
435const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000436
437/* Routines for handling symbols of the grammar */
438
icculus9e44cf12010-02-14 17:14:22 +0000439struct symbol *Symbol_new(const char *);
440int Symbolcmpp(const void *, const void *);
441void Symbol_init(void);
442int Symbol_insert(struct symbol *, const char *);
443struct symbol *Symbol_find(const char *);
444struct symbol *Symbol_Nth(int);
445int Symbol_count(void);
446struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000447
448/* Routines to manage the state table */
449
icculus9e44cf12010-02-14 17:14:22 +0000450int Configcmp(const char *, const char *);
451struct state *State_new(void);
452void State_init(void);
453int State_insert(struct state *, struct config *);
454struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000455struct state **State_arrayof(/* */);
456
457/* Routines used for efficiency in Configlist_add */
458
icculus9e44cf12010-02-14 17:14:22 +0000459void Configtable_init(void);
460int Configtable_insert(struct config *);
461struct config *Configtable_find(struct config *);
462void Configtable_clear(int(*)(struct config *));
463
drh75897232000-05-29 14:26:00 +0000464/****************** From the file "action.c" *******************************/
465/*
466** Routines processing parser actions in the LEMON parser generator.
467*/
468
469/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000470static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000471 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000472 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000473
474 if( freelist==0 ){
475 int i;
476 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000477 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000478 if( freelist==0 ){
479 fprintf(stderr,"Unable to allocate memory for a new parser action.");
480 exit(1);
481 }
482 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
483 freelist[amt-1].next = 0;
484 }
icculus9e44cf12010-02-14 17:14:22 +0000485 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000486 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000487 return newaction;
drh75897232000-05-29 14:26:00 +0000488}
489
drhe9278182007-07-18 18:16:29 +0000490/* Compare two actions for sorting purposes. Return negative, zero, or
491** positive if the first action is less than, equal to, or greater than
492** the first
493*/
494static int actioncmp(
495 struct action *ap1,
496 struct action *ap2
497){
drh75897232000-05-29 14:26:00 +0000498 int rc;
499 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000500 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000501 rc = (int)ap1->type - (int)ap2->type;
502 }
drh3bd48ab2015-09-07 18:23:37 +0000503 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000504 rc = ap1->x.rp->index - ap2->x.rp->index;
505 }
drhe594bc32009-11-03 13:02:25 +0000506 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000507 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000508 }
drh75897232000-05-29 14:26:00 +0000509 return rc;
510}
511
512/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000513static struct action *Action_sort(
514 struct action *ap
515){
516 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
517 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000518 return ap;
519}
520
icculus9e44cf12010-02-14 17:14:22 +0000521void Action_add(
522 struct action **app,
523 enum e_action type,
524 struct symbol *sp,
525 char *arg
526){
527 struct action *newaction;
528 newaction = Action_new();
529 newaction->next = *app;
530 *app = newaction;
531 newaction->type = type;
532 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000533 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000534 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000535 }else{
icculus9e44cf12010-02-14 17:14:22 +0000536 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000537 }
538}
drh8b582012003-10-21 13:16:03 +0000539/********************** New code to implement the "acttab" module ***********/
540/*
541** This module implements routines use to construct the yy_action[] table.
542*/
543
544/*
545** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000546** the following structure.
547**
548** The yy_action table maps the pair (state_number, lookahead) into an
549** action_number. The table is an array of integers pairs. The state_number
550** determines an initial offset into the yy_action array. The lookahead
551** value is then added to this initial offset to get an index X into the
552** yy_action array. If the aAction[X].lookahead equals the value of the
553** of the lookahead input, then the value of the action_number output is
554** aAction[X].action. If the lookaheads do not match then the
555** default action for the state_number is returned.
556**
557** All actions associated with a single state_number are first entered
558** into aLookahead[] using multiple calls to acttab_action(). Then the
559** actions for that single state_number are placed into the aAction[]
560** array with a single call to acttab_insert(). The acttab_insert() call
561** also resets the aLookahead[] array in preparation for the next
562** state number.
drh8b582012003-10-21 13:16:03 +0000563*/
icculus9e44cf12010-02-14 17:14:22 +0000564struct lookahead_action {
565 int lookahead; /* Value of the lookahead token */
566 int action; /* Action to take on the given lookahead */
567};
drh8b582012003-10-21 13:16:03 +0000568typedef struct acttab acttab;
569struct acttab {
570 int nAction; /* Number of used slots in aAction[] */
571 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000572 struct lookahead_action
573 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000574 *aLookahead; /* A single new transaction set */
575 int mnLookahead; /* Minimum aLookahead[].lookahead */
576 int mnAction; /* Action associated with mnLookahead */
577 int mxLookahead; /* Maximum aLookahead[].lookahead */
578 int nLookahead; /* Used slots in aLookahead[] */
579 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
580};
581
582/* Return the number of entries in the yy_action table */
583#define acttab_size(X) ((X)->nAction)
584
585/* The value for the N-th entry in yy_action */
586#define acttab_yyaction(X,N) ((X)->aAction[N].action)
587
588/* The value for the N-th entry in yy_lookahead */
589#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
590
591/* Free all memory associated with the given acttab */
592void acttab_free(acttab *p){
593 free( p->aAction );
594 free( p->aLookahead );
595 free( p );
596}
597
598/* Allocate a new acttab structure */
599acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000600 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000601 if( p==0 ){
602 fprintf(stderr,"Unable to allocate memory for a new acttab.");
603 exit(1);
604 }
605 memset(p, 0, sizeof(*p));
606 return p;
607}
608
drh8dc3e8f2010-01-07 03:53:03 +0000609/* Add a new action to the current transaction set.
610**
611** This routine is called once for each lookahead for a particular
612** state.
drh8b582012003-10-21 13:16:03 +0000613*/
614void acttab_action(acttab *p, int lookahead, int action){
615 if( p->nLookahead>=p->nLookaheadAlloc ){
616 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000617 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000618 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
619 if( p->aLookahead==0 ){
620 fprintf(stderr,"malloc failed\n");
621 exit(1);
622 }
623 }
624 if( p->nLookahead==0 ){
625 p->mxLookahead = lookahead;
626 p->mnLookahead = lookahead;
627 p->mnAction = action;
628 }else{
629 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
630 if( p->mnLookahead>lookahead ){
631 p->mnLookahead = lookahead;
632 p->mnAction = action;
633 }
634 }
635 p->aLookahead[p->nLookahead].lookahead = lookahead;
636 p->aLookahead[p->nLookahead].action = action;
637 p->nLookahead++;
638}
639
640/*
641** Add the transaction set built up with prior calls to acttab_action()
642** into the current action table. Then reset the transaction set back
643** to an empty set in preparation for a new round of acttab_action() calls.
644**
645** Return the offset into the action table of the new transaction.
646*/
647int acttab_insert(acttab *p){
648 int i, j, k, n;
649 assert( p->nLookahead>0 );
650
651 /* Make sure we have enough space to hold the expanded action table
652 ** in the worst case. The worst case occurs if the transaction set
653 ** must be appended to the current action table
654 */
drh784d86f2004-02-19 18:41:53 +0000655 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000656 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000657 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000658 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000659 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000660 sizeof(p->aAction[0])*p->nActionAlloc);
661 if( p->aAction==0 ){
662 fprintf(stderr,"malloc failed\n");
663 exit(1);
664 }
drhfdbf9282003-10-21 16:34:41 +0000665 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000666 p->aAction[i].lookahead = -1;
667 p->aAction[i].action = -1;
668 }
669 }
670
drh8dc3e8f2010-01-07 03:53:03 +0000671 /* Scan the existing action table looking for an offset that is a
672 ** duplicate of the current transaction set. Fall out of the loop
673 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000674 **
675 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
676 */
drh8dc3e8f2010-01-07 03:53:03 +0000677 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000678 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000679 /* All lookaheads and actions in the aLookahead[] transaction
680 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000681 if( p->aAction[i].action!=p->mnAction ) continue;
682 for(j=0; j<p->nLookahead; j++){
683 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
684 if( k<0 || k>=p->nAction ) break;
685 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
686 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
687 }
688 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000689
690 /* No possible lookahead value that is not in the aLookahead[]
691 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000692 n = 0;
693 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000694 if( p->aAction[j].lookahead<0 ) continue;
695 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000696 }
drhfdbf9282003-10-21 16:34:41 +0000697 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000698 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000699 }
drh8b582012003-10-21 13:16:03 +0000700 }
701 }
drh8dc3e8f2010-01-07 03:53:03 +0000702
703 /* If no existing offsets exactly match the current transaction, find an
704 ** an empty offset in the aAction[] table in which we can add the
705 ** aLookahead[] transaction.
706 */
drhf16371d2009-11-03 19:18:31 +0000707 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000708 /* Look for holes in the aAction[] table that fit the current
709 ** aLookahead[] transaction. Leave i set to the offset of the hole.
710 ** If no holes are found, i is left at p->nAction, which means the
711 ** transaction will be appended. */
712 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000713 if( p->aAction[i].lookahead<0 ){
714 for(j=0; j<p->nLookahead; j++){
715 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
716 if( k<0 ) break;
717 if( p->aAction[k].lookahead>=0 ) break;
718 }
719 if( j<p->nLookahead ) continue;
720 for(j=0; j<p->nAction; j++){
721 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
722 }
723 if( j==p->nAction ){
724 break; /* Fits in empty slots */
725 }
726 }
727 }
728 }
drh8b582012003-10-21 13:16:03 +0000729 /* Insert transaction set at index i. */
730 for(j=0; j<p->nLookahead; j++){
731 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
732 p->aAction[k] = p->aLookahead[j];
733 if( k>=p->nAction ) p->nAction = k+1;
734 }
735 p->nLookahead = 0;
736
737 /* Return the offset that is added to the lookahead in order to get the
738 ** index into yy_action of the action */
739 return i - p->mnLookahead;
740}
741
drh75897232000-05-29 14:26:00 +0000742/********************** From the file "build.c" *****************************/
743/*
744** Routines to construction the finite state machine for the LEMON
745** parser generator.
746*/
747
748/* Find a precedence symbol of every rule in the grammar.
749**
750** Those rules which have a precedence symbol coded in the input
751** grammar using the "[symbol]" construct will already have the
752** rp->precsym field filled. Other rules take as their precedence
753** symbol the first RHS symbol with a defined precedence. If there
754** are not RHS symbols with a defined precedence, the precedence
755** symbol field is left blank.
756*/
icculus9e44cf12010-02-14 17:14:22 +0000757void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000758{
759 struct rule *rp;
760 for(rp=xp->rule; rp; rp=rp->next){
761 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000762 int i, j;
763 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
764 struct symbol *sp = rp->rhs[i];
765 if( sp->type==MULTITERMINAL ){
766 for(j=0; j<sp->nsubsym; j++){
767 if( sp->subsym[j]->prec>=0 ){
768 rp->precsym = sp->subsym[j];
769 break;
770 }
771 }
772 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000773 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000774 }
drh75897232000-05-29 14:26:00 +0000775 }
776 }
777 }
778 return;
779}
780
781/* Find all nonterminals which will generate the empty string.
782** Then go back and compute the first sets of every nonterminal.
783** The first set is the set of all terminal symbols which can begin
784** a string generated by that nonterminal.
785*/
icculus9e44cf12010-02-14 17:14:22 +0000786void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000787{
drhfd405312005-11-06 04:06:59 +0000788 int i, j;
drh75897232000-05-29 14:26:00 +0000789 struct rule *rp;
790 int progress;
791
792 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000793 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000794 }
795 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
796 lemp->symbols[i]->firstset = SetNew();
797 }
798
799 /* First compute all lambdas */
800 do{
801 progress = 0;
802 for(rp=lemp->rule; rp; rp=rp->next){
803 if( rp->lhs->lambda ) continue;
804 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000805 struct symbol *sp = rp->rhs[i];
806 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
807 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000808 }
809 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000810 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000811 progress = 1;
812 }
813 }
814 }while( progress );
815
816 /* Now compute all first sets */
817 do{
818 struct symbol *s1, *s2;
819 progress = 0;
820 for(rp=lemp->rule; rp; rp=rp->next){
821 s1 = rp->lhs;
822 for(i=0; i<rp->nrhs; i++){
823 s2 = rp->rhs[i];
824 if( s2->type==TERMINAL ){
825 progress += SetAdd(s1->firstset,s2->index);
826 break;
drhfd405312005-11-06 04:06:59 +0000827 }else if( s2->type==MULTITERMINAL ){
828 for(j=0; j<s2->nsubsym; j++){
829 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
830 }
831 break;
drhf2f105d2012-08-20 15:53:54 +0000832 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000833 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000834 }else{
drh75897232000-05-29 14:26:00 +0000835 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000836 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000837 }
drh75897232000-05-29 14:26:00 +0000838 }
839 }
840 }while( progress );
841 return;
842}
843
844/* Compute all LR(0) states for the grammar. Links
845** are added to between some states so that the LR(1) follow sets
846** can be computed later.
847*/
icculus9e44cf12010-02-14 17:14:22 +0000848PRIVATE struct state *getstate(struct lemon *); /* forward reference */
849void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000850{
851 struct symbol *sp;
852 struct rule *rp;
853
854 Configlist_init();
855
856 /* Find the start symbol */
857 if( lemp->start ){
858 sp = Symbol_find(lemp->start);
859 if( sp==0 ){
860 ErrorMsg(lemp->filename,0,
861"The specified start symbol \"%s\" is not \
862in a nonterminal of the grammar. \"%s\" will be used as the start \
drh4ef07702016-03-16 19:45:54 +0000863symbol instead.",lemp->start,lemp->startRule->lhs->name);
drh75897232000-05-29 14:26:00 +0000864 lemp->errorcnt++;
drh4ef07702016-03-16 19:45:54 +0000865 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000866 }
867 }else{
drh4ef07702016-03-16 19:45:54 +0000868 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +0000869 }
870
871 /* Make sure the start symbol doesn't occur on the right-hand side of
872 ** any rule. Report an error if it does. (YACC would generate a new
873 ** start symbol in this case.) */
874 for(rp=lemp->rule; rp; rp=rp->next){
875 int i;
876 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000877 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000878 ErrorMsg(lemp->filename,0,
879"The start symbol \"%s\" occurs on the \
880right-hand side of a rule. This will result in a parser which \
881does not work properly.",sp->name);
882 lemp->errorcnt++;
883 }
884 }
885 }
886
887 /* The basis configuration set for the first state
888 ** is all rules which have the start symbol as their
889 ** left-hand side */
890 for(rp=sp->rule; rp; rp=rp->nextlhs){
891 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000892 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000893 newcfp = Configlist_addbasis(rp,0);
894 SetAdd(newcfp->fws,0);
895 }
896
897 /* Compute the first state. All other states will be
898 ** computed automatically during the computation of the first one.
899 ** The returned pointer to the first state is not used. */
900 (void)getstate(lemp);
901 return;
902}
903
904/* Return a pointer to a state which is described by the configuration
905** list which has been built from calls to Configlist_add.
906*/
icculus9e44cf12010-02-14 17:14:22 +0000907PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
908PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000909{
910 struct config *cfp, *bp;
911 struct state *stp;
912
913 /* Extract the sorted basis of the new state. The basis was constructed
914 ** by prior calls to "Configlist_addbasis()". */
915 Configlist_sortbasis();
916 bp = Configlist_basis();
917
918 /* Get a state with the same basis */
919 stp = State_find(bp);
920 if( stp ){
921 /* A state with the same basis already exists! Copy all the follow-set
922 ** propagation links from the state under construction into the
923 ** preexisting state, then return a pointer to the preexisting state */
924 struct config *x, *y;
925 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
926 Plink_copy(&y->bplp,x->bplp);
927 Plink_delete(x->fplp);
928 x->fplp = x->bplp = 0;
929 }
930 cfp = Configlist_return();
931 Configlist_eat(cfp);
932 }else{
933 /* This really is a new state. Construct all the details */
934 Configlist_closure(lemp); /* Compute the configuration closure */
935 Configlist_sort(); /* Sort the configuration closure */
936 cfp = Configlist_return(); /* Get a pointer to the config list */
937 stp = State_new(); /* A new state structure */
938 MemoryCheck(stp);
939 stp->bp = bp; /* Remember the configuration basis */
940 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000941 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000942 stp->ap = 0; /* No actions, yet. */
943 State_insert(stp,stp->bp); /* Add to the state table */
944 buildshifts(lemp,stp); /* Recursively compute successor states */
945 }
946 return stp;
947}
948
drhfd405312005-11-06 04:06:59 +0000949/*
950** Return true if two symbols are the same.
951*/
icculus9e44cf12010-02-14 17:14:22 +0000952int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000953{
954 int i;
955 if( a==b ) return 1;
956 if( a->type!=MULTITERMINAL ) return 0;
957 if( b->type!=MULTITERMINAL ) return 0;
958 if( a->nsubsym!=b->nsubsym ) return 0;
959 for(i=0; i<a->nsubsym; i++){
960 if( a->subsym[i]!=b->subsym[i] ) return 0;
961 }
962 return 1;
963}
964
drh75897232000-05-29 14:26:00 +0000965/* Construct all successor states to the given state. A "successor"
966** state is any state which can be reached by a shift action.
967*/
icculus9e44cf12010-02-14 17:14:22 +0000968PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000969{
970 struct config *cfp; /* For looping thru the config closure of "stp" */
971 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000972 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000973 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
974 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
975 struct state *newstp; /* A pointer to a successor state */
976
977 /* Each configuration becomes complete after it contibutes to a successor
978 ** state. Initially, all configurations are incomplete */
979 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
980
981 /* Loop through all configurations of the state "stp" */
982 for(cfp=stp->cfp; cfp; cfp=cfp->next){
983 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
984 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
985 Configlist_reset(); /* Reset the new config set */
986 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
987
988 /* For every configuration in the state "stp" which has the symbol "sp"
989 ** following its dot, add the same configuration to the basis set under
990 ** construction but with the dot shifted one symbol to the right. */
991 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
992 if( bcfp->status==COMPLETE ) continue; /* Already used */
993 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
994 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000995 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000996 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000997 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
998 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000999 }
1000
1001 /* Get a pointer to the state described by the basis configuration set
1002 ** constructed in the preceding loop */
1003 newstp = getstate(lemp);
1004
1005 /* The state "newstp" is reached from the state "stp" by a shift action
1006 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001007 if( sp->type==MULTITERMINAL ){
1008 int i;
1009 for(i=0; i<sp->nsubsym; i++){
1010 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1011 }
1012 }else{
1013 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1014 }
drh75897232000-05-29 14:26:00 +00001015 }
1016}
1017
1018/*
1019** Construct the propagation links
1020*/
icculus9e44cf12010-02-14 17:14:22 +00001021void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001022{
1023 int i;
1024 struct config *cfp, *other;
1025 struct state *stp;
1026 struct plink *plp;
1027
1028 /* Housekeeping detail:
1029 ** Add to every propagate link a pointer back to the state to
1030 ** which the link is attached. */
1031 for(i=0; i<lemp->nstate; i++){
1032 stp = lemp->sorted[i];
1033 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1034 cfp->stp = stp;
1035 }
1036 }
1037
1038 /* Convert all backlinks into forward links. Only the forward
1039 ** links are used in the follow-set computation. */
1040 for(i=0; i<lemp->nstate; i++){
1041 stp = lemp->sorted[i];
1042 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1043 for(plp=cfp->bplp; plp; plp=plp->next){
1044 other = plp->cfp;
1045 Plink_add(&other->fplp,cfp);
1046 }
1047 }
1048 }
1049}
1050
1051/* Compute all followsets.
1052**
1053** A followset is the set of all symbols which can come immediately
1054** after a configuration.
1055*/
icculus9e44cf12010-02-14 17:14:22 +00001056void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001057{
1058 int i;
1059 struct config *cfp;
1060 struct plink *plp;
1061 int progress;
1062 int change;
1063
1064 for(i=0; i<lemp->nstate; i++){
1065 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1066 cfp->status = INCOMPLETE;
1067 }
1068 }
1069
1070 do{
1071 progress = 0;
1072 for(i=0; i<lemp->nstate; i++){
1073 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1074 if( cfp->status==COMPLETE ) continue;
1075 for(plp=cfp->fplp; plp; plp=plp->next){
1076 change = SetUnion(plp->cfp->fws,cfp->fws);
1077 if( change ){
1078 plp->cfp->status = INCOMPLETE;
1079 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001080 }
1081 }
drh75897232000-05-29 14:26:00 +00001082 cfp->status = COMPLETE;
1083 }
1084 }
1085 }while( progress );
1086}
1087
drh3cb2f6e2012-01-09 14:19:05 +00001088static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001089
1090/* Compute the reduce actions, and resolve conflicts.
1091*/
icculus9e44cf12010-02-14 17:14:22 +00001092void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001093{
1094 int i,j;
1095 struct config *cfp;
1096 struct state *stp;
1097 struct symbol *sp;
1098 struct rule *rp;
1099
1100 /* Add all of the reduce actions
1101 ** A reduce action is added for each element of the followset of
1102 ** a configuration which has its dot at the extreme right.
1103 */
1104 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1105 stp = lemp->sorted[i];
1106 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1107 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1108 for(j=0; j<lemp->nterminal; j++){
1109 if( SetFind(cfp->fws,j) ){
1110 /* Add a reduce action to the state "stp" which will reduce by the
1111 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001112 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001113 }
drhf2f105d2012-08-20 15:53:54 +00001114 }
drh75897232000-05-29 14:26:00 +00001115 }
1116 }
1117 }
1118
1119 /* Add the accepting token */
1120 if( lemp->start ){
1121 sp = Symbol_find(lemp->start);
drh4ef07702016-03-16 19:45:54 +00001122 if( sp==0 ) sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001123 }else{
drh4ef07702016-03-16 19:45:54 +00001124 sp = lemp->startRule->lhs;
drh75897232000-05-29 14:26:00 +00001125 }
1126 /* Add to the first state (which is always the starting state of the
1127 ** finite state machine) an action to ACCEPT if the lookahead is the
1128 ** start nonterminal. */
1129 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1130
1131 /* Resolve conflicts */
1132 for(i=0; i<lemp->nstate; i++){
1133 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001134 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001135 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001136 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001137 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001138 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1139 /* The two actions "ap" and "nap" have the same lookahead.
1140 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001141 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001142 }
1143 }
1144 }
1145
1146 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001147 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001148 for(i=0; i<lemp->nstate; i++){
1149 struct action *ap;
1150 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001151 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001152 }
1153 }
1154 for(rp=lemp->rule; rp; rp=rp->next){
1155 if( rp->canReduce ) continue;
1156 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1157 lemp->errorcnt++;
1158 }
1159}
1160
1161/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001162** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001163**
1164** NO LONGER TRUE:
1165** To resolve a conflict, first look to see if either action
1166** is on an error rule. In that case, take the action which
1167** is not associated with the error rule. If neither or both
1168** actions are associated with an error rule, then try to
1169** use precedence to resolve the conflict.
1170**
1171** If either action is a SHIFT, then it must be apx. This
1172** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1173*/
icculus9e44cf12010-02-14 17:14:22 +00001174static int resolve_conflict(
1175 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001176 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001177){
drh75897232000-05-29 14:26:00 +00001178 struct symbol *spx, *spy;
1179 int errcnt = 0;
1180 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001181 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001182 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001183 errcnt++;
1184 }
drh75897232000-05-29 14:26:00 +00001185 if( apx->type==SHIFT && apy->type==REDUCE ){
1186 spx = apx->sp;
1187 spy = apy->x.rp->precsym;
1188 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1189 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001190 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001191 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001192 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001193 apy->type = RD_RESOLVED;
1194 }else if( spx->prec<spy->prec ){
1195 apx->type = SH_RESOLVED;
1196 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1197 apy->type = RD_RESOLVED; /* associativity */
1198 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1199 apx->type = SH_RESOLVED;
1200 }else{
1201 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001202 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001203 }
1204 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1205 spx = apx->x.rp->precsym;
1206 spy = apy->x.rp->precsym;
1207 if( spx==0 || spy==0 || spx->prec<0 ||
1208 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001209 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001210 errcnt++;
1211 }else if( spx->prec>spy->prec ){
1212 apy->type = RD_RESOLVED;
1213 }else if( spx->prec<spy->prec ){
1214 apx->type = RD_RESOLVED;
1215 }
1216 }else{
drhb59499c2002-02-23 18:45:13 +00001217 assert(
1218 apx->type==SH_RESOLVED ||
1219 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001220 apx->type==SSCONFLICT ||
1221 apx->type==SRCONFLICT ||
1222 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001223 apy->type==SH_RESOLVED ||
1224 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001225 apy->type==SSCONFLICT ||
1226 apy->type==SRCONFLICT ||
1227 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001228 );
1229 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1230 ** REDUCEs on the list. If we reach this point it must be because
1231 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001232 }
1233 return errcnt;
1234}
1235/********************* From the file "configlist.c" *************************/
1236/*
1237** Routines to processing a configuration list and building a state
1238** in the LEMON parser generator.
1239*/
1240
1241static struct config *freelist = 0; /* List of free configurations */
1242static struct config *current = 0; /* Top of list of configurations */
1243static struct config **currentend = 0; /* Last on list of configs */
1244static struct config *basis = 0; /* Top of list of basis configs */
1245static struct config **basisend = 0; /* End of list of basis configs */
1246
1247/* Return a pointer to a new configuration */
1248PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001249 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001250 if( freelist==0 ){
1251 int i;
1252 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001253 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001254 if( freelist==0 ){
1255 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1256 exit(1);
1257 }
1258 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1259 freelist[amt-1].next = 0;
1260 }
icculus9e44cf12010-02-14 17:14:22 +00001261 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001262 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001263 return newcfg;
drh75897232000-05-29 14:26:00 +00001264}
1265
1266/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001267PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001268{
1269 old->next = freelist;
1270 freelist = old;
1271}
1272
1273/* Initialized the configuration list builder */
1274void Configlist_init(){
1275 current = 0;
1276 currentend = &current;
1277 basis = 0;
1278 basisend = &basis;
1279 Configtable_init();
1280 return;
1281}
1282
1283/* Initialized the configuration list builder */
1284void Configlist_reset(){
1285 current = 0;
1286 currentend = &current;
1287 basis = 0;
1288 basisend = &basis;
1289 Configtable_clear(0);
1290 return;
1291}
1292
1293/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001294struct config *Configlist_add(
1295 struct rule *rp, /* The rule */
1296 int dot /* Index into the RHS of the rule where the dot goes */
1297){
drh75897232000-05-29 14:26:00 +00001298 struct config *cfp, model;
1299
1300 assert( currentend!=0 );
1301 model.rp = rp;
1302 model.dot = dot;
1303 cfp = Configtable_find(&model);
1304 if( cfp==0 ){
1305 cfp = newconfig();
1306 cfp->rp = rp;
1307 cfp->dot = dot;
1308 cfp->fws = SetNew();
1309 cfp->stp = 0;
1310 cfp->fplp = cfp->bplp = 0;
1311 cfp->next = 0;
1312 cfp->bp = 0;
1313 *currentend = cfp;
1314 currentend = &cfp->next;
1315 Configtable_insert(cfp);
1316 }
1317 return cfp;
1318}
1319
1320/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001321struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001322{
1323 struct config *cfp, model;
1324
1325 assert( basisend!=0 );
1326 assert( currentend!=0 );
1327 model.rp = rp;
1328 model.dot = dot;
1329 cfp = Configtable_find(&model);
1330 if( cfp==0 ){
1331 cfp = newconfig();
1332 cfp->rp = rp;
1333 cfp->dot = dot;
1334 cfp->fws = SetNew();
1335 cfp->stp = 0;
1336 cfp->fplp = cfp->bplp = 0;
1337 cfp->next = 0;
1338 cfp->bp = 0;
1339 *currentend = cfp;
1340 currentend = &cfp->next;
1341 *basisend = cfp;
1342 basisend = &cfp->bp;
1343 Configtable_insert(cfp);
1344 }
1345 return cfp;
1346}
1347
1348/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001349void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001350{
1351 struct config *cfp, *newcfp;
1352 struct rule *rp, *newrp;
1353 struct symbol *sp, *xsp;
1354 int i, dot;
1355
1356 assert( currentend!=0 );
1357 for(cfp=current; cfp; cfp=cfp->next){
1358 rp = cfp->rp;
1359 dot = cfp->dot;
1360 if( dot>=rp->nrhs ) continue;
1361 sp = rp->rhs[dot];
1362 if( sp->type==NONTERMINAL ){
1363 if( sp->rule==0 && sp!=lemp->errsym ){
1364 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1365 sp->name);
1366 lemp->errorcnt++;
1367 }
1368 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1369 newcfp = Configlist_add(newrp,0);
1370 for(i=dot+1; i<rp->nrhs; i++){
1371 xsp = rp->rhs[i];
1372 if( xsp->type==TERMINAL ){
1373 SetAdd(newcfp->fws,xsp->index);
1374 break;
drhfd405312005-11-06 04:06:59 +00001375 }else if( xsp->type==MULTITERMINAL ){
1376 int k;
1377 for(k=0; k<xsp->nsubsym; k++){
1378 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1379 }
1380 break;
drhf2f105d2012-08-20 15:53:54 +00001381 }else{
drh75897232000-05-29 14:26:00 +00001382 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001383 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001384 }
1385 }
drh75897232000-05-29 14:26:00 +00001386 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1387 }
1388 }
1389 }
1390 return;
1391}
1392
1393/* Sort the configuration list */
1394void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001395 current = (struct config*)msort((char*)current,(char**)&(current->next),
1396 Configcmp);
drh75897232000-05-29 14:26:00 +00001397 currentend = 0;
1398 return;
1399}
1400
1401/* Sort the basis configuration list */
1402void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001403 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1404 Configcmp);
drh75897232000-05-29 14:26:00 +00001405 basisend = 0;
1406 return;
1407}
1408
1409/* Return a pointer to the head of the configuration list and
1410** reset the list */
1411struct config *Configlist_return(){
1412 struct config *old;
1413 old = current;
1414 current = 0;
1415 currentend = 0;
1416 return old;
1417}
1418
1419/* Return a pointer to the head of the configuration list and
1420** reset the list */
1421struct config *Configlist_basis(){
1422 struct config *old;
1423 old = basis;
1424 basis = 0;
1425 basisend = 0;
1426 return old;
1427}
1428
1429/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001430void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001431{
1432 struct config *nextcfp;
1433 for(; cfp; cfp=nextcfp){
1434 nextcfp = cfp->next;
1435 assert( cfp->fplp==0 );
1436 assert( cfp->bplp==0 );
1437 if( cfp->fws ) SetFree(cfp->fws);
1438 deleteconfig(cfp);
1439 }
1440 return;
1441}
1442/***************** From the file "error.c" *********************************/
1443/*
1444** Code for printing error message.
1445*/
1446
drhf9a2e7b2003-04-15 01:49:48 +00001447void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001448 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001449 fprintf(stderr, "%s:%d: ", filename, lineno);
1450 va_start(ap, format);
1451 vfprintf(stderr,format,ap);
1452 va_end(ap);
1453 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001454}
1455/**************** From the file "main.c" ************************************/
1456/*
1457** Main program file for the LEMON parser generator.
1458*/
1459
1460/* Report an out-of-memory condition and abort. This function
1461** is used mostly by the "MemoryCheck" macro in struct.h
1462*/
1463void memory_error(){
1464 fprintf(stderr,"Out of memory. Aborting...\n");
1465 exit(1);
1466}
1467
drh6d08b4d2004-07-20 12:45:22 +00001468static int nDefine = 0; /* Number of -D options on the command line */
1469static char **azDefine = 0; /* Name of the -D macros */
1470
1471/* This routine is called with the argument to each -D command-line option.
1472** Add the macro defined to the azDefine array.
1473*/
1474static void handle_D_option(char *z){
1475 char **paz;
1476 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001477 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001478 if( azDefine==0 ){
1479 fprintf(stderr,"out of memory\n");
1480 exit(1);
1481 }
1482 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001483 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001484 if( *paz==0 ){
1485 fprintf(stderr,"out of memory\n");
1486 exit(1);
1487 }
drh898799f2014-01-10 23:21:00 +00001488 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001489 for(z=*paz; *z && *z!='='; z++){}
1490 *z = 0;
1491}
1492
icculus3e143bd2010-02-14 00:48:49 +00001493static char *user_templatename = NULL;
1494static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001495 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001496 if( user_templatename==0 ){
1497 memory_error();
1498 }
drh898799f2014-01-10 23:21:00 +00001499 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001500}
drh75897232000-05-29 14:26:00 +00001501
drh4ef07702016-03-16 19:45:54 +00001502/* Merge together to lists of rules order by rule.iRule */
1503static struct rule *Rule_merge(struct rule *pA, struct rule *pB){
1504 struct rule *pFirst = 0;
1505 struct rule **ppPrev = &pFirst;
1506 while( pA && pB ){
1507 if( pA->iRule<pB->iRule ){
1508 *ppPrev = pA;
1509 ppPrev = &pA->next;
1510 pA = pA->next;
1511 }else{
1512 *ppPrev = pB;
1513 ppPrev = &pB->next;
1514 pB = pB->next;
1515 }
1516 }
1517 if( pA ){
1518 *ppPrev = pA;
1519 }else{
1520 *ppPrev = pB;
1521 }
1522 return pFirst;
1523}
1524
1525/*
1526** Sort a list of rules in order of increasing iRule value
1527*/
1528static struct rule *Rule_sort(struct rule *rp){
1529 int i;
1530 struct rule *pNext;
1531 struct rule *x[32];
1532 memset(x, 0, sizeof(x));
1533 while( rp ){
1534 pNext = rp->next;
1535 rp->next = 0;
1536 for(i=0; i<sizeof(x)/sizeof(x[0]) && x[i]; i++){
1537 rp = Rule_merge(x[i], rp);
1538 x[i] = 0;
1539 }
1540 x[i] = rp;
1541 rp = pNext;
1542 }
1543 rp = 0;
1544 for(i=0; i<sizeof(x)/sizeof(x[0]); i++){
1545 rp = Rule_merge(x[i], rp);
1546 }
1547 return rp;
1548}
1549
drhc75e0162015-09-07 02:23:02 +00001550/* forward reference */
1551static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1552
1553/* Print a single line of the "Parser Stats" output
1554*/
1555static void stats_line(const char *zLabel, int iValue){
1556 int nLabel = lemonStrlen(zLabel);
1557 printf(" %s%.*s %5d\n", zLabel,
1558 35-nLabel, "................................",
1559 iValue);
1560}
1561
drh75897232000-05-29 14:26:00 +00001562/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001563int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001564{
1565 static int version = 0;
1566 static int rpflag = 0;
1567 static int basisflag = 0;
1568 static int compress = 0;
1569 static int quiet = 0;
1570 static int statistics = 0;
1571 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001572 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001573 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001574 static struct s_options options[] = {
1575 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1576 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001577 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001578 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001579 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001580 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001581 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1582 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001583 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001584 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1585 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001586 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001587 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001588 {OPT_FLAG, "s", (char*)&statistics,
1589 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001590 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001591 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1592 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001593 {OPT_FLAG,0,0,0}
1594 };
1595 int i;
icculus42585cf2010-02-14 05:19:56 +00001596 int exitcode;
drh75897232000-05-29 14:26:00 +00001597 struct lemon lem;
drh4ef07702016-03-16 19:45:54 +00001598 struct rule *rp;
drh75897232000-05-29 14:26:00 +00001599
drhb0c86772000-06-02 23:21:26 +00001600 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001601 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001602 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001603 exit(0);
1604 }
drhb0c86772000-06-02 23:21:26 +00001605 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001606 fprintf(stderr,"Exactly one filename argument is required.\n");
1607 exit(1);
1608 }
drh954f6b42006-06-13 13:27:46 +00001609 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001610 lem.errorcnt = 0;
1611
1612 /* Initialize the machine */
1613 Strsafe_init();
1614 Symbol_init();
1615 State_init();
1616 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001617 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001618 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001619 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001620 Symbol_new("$");
1621 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001622 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001623
1624 /* Parse the input file */
1625 Parse(&lem);
1626 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001627 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001628 fprintf(stderr,"Empty grammar.\n");
1629 exit(1);
1630 }
1631
1632 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001633 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001634 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001635 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001636 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1637 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1638 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1639 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1640 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1641 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001642 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001643 lem.nterminal = i;
1644
drh4ef07702016-03-16 19:45:54 +00001645 /* Assign sequential rule numbers */
1646 for(i=0, rp=lem.rule; rp; rp=rp->next){
1647 rp->iRule = rp->code ? i++ : -1;
1648 }
1649 for(rp=lem.rule; rp; rp=rp->next){
1650 if( rp->iRule<0 ) rp->iRule = i++;
1651 }
1652 lem.startRule = lem.rule;
1653 lem.rule = Rule_sort(lem.rule);
1654
drh75897232000-05-29 14:26:00 +00001655 /* Generate a reprint of the grammar, if requested on the command line */
1656 if( rpflag ){
1657 Reprint(&lem);
1658 }else{
1659 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001660 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001661
1662 /* Find the precedence for every production rule (that has one) */
1663 FindRulePrecedences(&lem);
1664
1665 /* Compute the lambda-nonterminals and the first-sets for every
1666 ** nonterminal */
1667 FindFirstSets(&lem);
1668
1669 /* Compute all LR(0) states. Also record follow-set propagation
1670 ** links so that the follow-set can be computed later */
1671 lem.nstate = 0;
1672 FindStates(&lem);
1673 lem.sorted = State_arrayof();
1674
1675 /* Tie up loose ends on the propagation links */
1676 FindLinks(&lem);
1677
1678 /* Compute the follow set of every reducible configuration */
1679 FindFollowSets(&lem);
1680
1681 /* Compute the action tables */
1682 FindActions(&lem);
1683
1684 /* Compress the action tables */
1685 if( compress==0 ) CompressTables(&lem);
1686
drhada354d2005-11-05 15:03:59 +00001687 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001688 ** occur at the end. This is an optimization that helps make the
1689 ** generated parser tables smaller. */
1690 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001691
drh75897232000-05-29 14:26:00 +00001692 /* Generate a report of the parser generated. (the "y.output" file) */
1693 if( !quiet ) ReportOutput(&lem);
1694
1695 /* Generate the source code for the parser */
1696 ReportTable(&lem, mhflag);
1697
1698 /* Produce a header file for use by the scanner. (This step is
1699 ** omitted if the "-m" option is used because makeheaders will
1700 ** generate the file for us.) */
1701 if( !mhflag ) ReportHeader(&lem);
1702 }
1703 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001704 printf("Parser statistics:\n");
1705 stats_line("terminal symbols", lem.nterminal);
1706 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1707 stats_line("total symbols", lem.nsymbol);
1708 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001709 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001710 stats_line("conflicts", lem.nconflict);
1711 stats_line("action table entries", lem.nactiontab);
1712 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001713 }
icculus8e158022010-02-16 16:09:03 +00001714 if( lem.nconflict > 0 ){
1715 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001716 }
1717
1718 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001719 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001720 exit(exitcode);
1721 return (exitcode);
drh75897232000-05-29 14:26:00 +00001722}
1723/******************** From the file "msort.c" *******************************/
1724/*
1725** A generic merge-sort program.
1726**
1727** USAGE:
1728** Let "ptr" be a pointer to some structure which is at the head of
1729** a null-terminated list. Then to sort the list call:
1730**
1731** ptr = msort(ptr,&(ptr->next),cmpfnc);
1732**
1733** In the above, "cmpfnc" is a pointer to a function which compares
1734** two instances of the structure and returns an integer, as in
1735** strcmp. The second argument is a pointer to the pointer to the
1736** second element of the linked list. This address is used to compute
1737** the offset to the "next" field within the structure. The offset to
1738** the "next" field must be constant for all structures in the list.
1739**
1740** The function returns a new pointer which is the head of the list
1741** after sorting.
1742**
1743** ALGORITHM:
1744** Merge-sort.
1745*/
1746
1747/*
1748** Return a pointer to the next structure in the linked list.
1749*/
drhd25d6922012-04-18 09:59:56 +00001750#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001751
1752/*
1753** Inputs:
1754** a: A sorted, null-terminated linked list. (May be null).
1755** b: A sorted, null-terminated linked list. (May be null).
1756** cmp: A pointer to the comparison function.
1757** offset: Offset in the structure to the "next" field.
1758**
1759** Return Value:
1760** A pointer to the head of a sorted list containing the elements
1761** of both a and b.
1762**
1763** Side effects:
1764** The "next" pointers for elements in the lists a and b are
1765** changed.
1766*/
drhe9278182007-07-18 18:16:29 +00001767static char *merge(
1768 char *a,
1769 char *b,
1770 int (*cmp)(const char*,const char*),
1771 int offset
1772){
drh75897232000-05-29 14:26:00 +00001773 char *ptr, *head;
1774
1775 if( a==0 ){
1776 head = b;
1777 }else if( b==0 ){
1778 head = a;
1779 }else{
drhe594bc32009-11-03 13:02:25 +00001780 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001781 ptr = a;
1782 a = NEXT(a);
1783 }else{
1784 ptr = b;
1785 b = NEXT(b);
1786 }
1787 head = ptr;
1788 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001789 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001790 NEXT(ptr) = a;
1791 ptr = a;
1792 a = NEXT(a);
1793 }else{
1794 NEXT(ptr) = b;
1795 ptr = b;
1796 b = NEXT(b);
1797 }
1798 }
1799 if( a ) NEXT(ptr) = a;
1800 else NEXT(ptr) = b;
1801 }
1802 return head;
1803}
1804
1805/*
1806** Inputs:
1807** list: Pointer to a singly-linked list of structures.
1808** next: Pointer to pointer to the second element of the list.
1809** cmp: A comparison function.
1810**
1811** Return Value:
1812** A pointer to the head of a sorted list containing the elements
1813** orginally in list.
1814**
1815** Side effects:
1816** The "next" pointers for elements in list are changed.
1817*/
1818#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001819static char *msort(
1820 char *list,
1821 char **next,
1822 int (*cmp)(const char*,const char*)
1823){
drhba99af52001-10-25 20:37:16 +00001824 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001825 char *ep;
1826 char *set[LISTSIZE];
1827 int i;
drh1cc0d112015-03-31 15:15:48 +00001828 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001829 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1830 while( list ){
1831 ep = list;
1832 list = NEXT(list);
1833 NEXT(ep) = 0;
1834 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1835 ep = merge(ep,set[i],cmp,offset);
1836 set[i] = 0;
1837 }
1838 set[i] = ep;
1839 }
1840 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001841 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001842 return ep;
1843}
1844/************************ From the file "option.c" **************************/
1845static char **argv;
1846static struct s_options *op;
1847static FILE *errstream;
1848
1849#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1850
1851/*
1852** Print the command line with a carrot pointing to the k-th character
1853** of the n-th field.
1854*/
icculus9e44cf12010-02-14 17:14:22 +00001855static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001856{
1857 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001858 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001859 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001860 for(i=1; i<n && argv[i]; i++){
1861 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001862 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001863 }
1864 spcnt += k;
1865 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1866 if( spcnt<20 ){
1867 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1868 }else{
1869 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1870 }
1871}
1872
1873/*
1874** Return the index of the N-th non-switch argument. Return -1
1875** if N is out of range.
1876*/
icculus9e44cf12010-02-14 17:14:22 +00001877static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001878{
1879 int i;
1880 int dashdash = 0;
1881 if( argv!=0 && *argv!=0 ){
1882 for(i=1; argv[i]; i++){
1883 if( dashdash || !ISOPT(argv[i]) ){
1884 if( n==0 ) return i;
1885 n--;
1886 }
1887 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1888 }
1889 }
1890 return -1;
1891}
1892
1893static char emsg[] = "Command line syntax error: ";
1894
1895/*
1896** Process a flag command line argument.
1897*/
icculus9e44cf12010-02-14 17:14:22 +00001898static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001899{
1900 int v;
1901 int errcnt = 0;
1902 int j;
1903 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001904 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001905 }
1906 v = argv[i][0]=='-' ? 1 : 0;
1907 if( op[j].label==0 ){
1908 if( err ){
1909 fprintf(err,"%sundefined option.\n",emsg);
1910 errline(i,1,err);
1911 }
1912 errcnt++;
drh0325d392015-01-01 19:11:22 +00001913 }else if( op[j].arg==0 ){
1914 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001915 }else if( op[j].type==OPT_FLAG ){
1916 *((int*)op[j].arg) = v;
1917 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001918 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001919 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001920 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001921 }else{
1922 if( err ){
1923 fprintf(err,"%smissing argument on switch.\n",emsg);
1924 errline(i,1,err);
1925 }
1926 errcnt++;
1927 }
1928 return errcnt;
1929}
1930
1931/*
1932** Process a command line switch which has an argument.
1933*/
icculus9e44cf12010-02-14 17:14:22 +00001934static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001935{
1936 int lv = 0;
1937 double dv = 0.0;
1938 char *sv = 0, *end;
1939 char *cp;
1940 int j;
1941 int errcnt = 0;
1942 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001943 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001944 *cp = 0;
1945 for(j=0; op[j].label; j++){
1946 if( strcmp(argv[i],op[j].label)==0 ) break;
1947 }
1948 *cp = '=';
1949 if( op[j].label==0 ){
1950 if( err ){
1951 fprintf(err,"%sundefined option.\n",emsg);
1952 errline(i,0,err);
1953 }
1954 errcnt++;
1955 }else{
1956 cp++;
1957 switch( op[j].type ){
1958 case OPT_FLAG:
1959 case OPT_FFLAG:
1960 if( err ){
1961 fprintf(err,"%soption requires an argument.\n",emsg);
1962 errline(i,0,err);
1963 }
1964 errcnt++;
1965 break;
1966 case OPT_DBL:
1967 case OPT_FDBL:
1968 dv = strtod(cp,&end);
1969 if( *end ){
1970 if( err ){
drh25473362015-09-04 18:03:45 +00001971 fprintf(err,
1972 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001973 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001974 }
1975 errcnt++;
1976 }
1977 break;
1978 case OPT_INT:
1979 case OPT_FINT:
1980 lv = strtol(cp,&end,0);
1981 if( *end ){
1982 if( err ){
1983 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001984 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001985 }
1986 errcnt++;
1987 }
1988 break;
1989 case OPT_STR:
1990 case OPT_FSTR:
1991 sv = cp;
1992 break;
1993 }
1994 switch( op[j].type ){
1995 case OPT_FLAG:
1996 case OPT_FFLAG:
1997 break;
1998 case OPT_DBL:
1999 *(double*)(op[j].arg) = dv;
2000 break;
2001 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00002002 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00002003 break;
2004 case OPT_INT:
2005 *(int*)(op[j].arg) = lv;
2006 break;
2007 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00002008 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00002009 break;
2010 case OPT_STR:
2011 *(char**)(op[j].arg) = sv;
2012 break;
2013 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00002014 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00002015 break;
2016 }
2017 }
2018 return errcnt;
2019}
2020
icculus9e44cf12010-02-14 17:14:22 +00002021int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00002022{
2023 int errcnt = 0;
2024 argv = a;
2025 op = o;
2026 errstream = err;
2027 if( argv && *argv && op ){
2028 int i;
2029 for(i=1; argv[i]; i++){
2030 if( argv[i][0]=='+' || argv[i][0]=='-' ){
2031 errcnt += handleflags(i,err);
2032 }else if( strchr(argv[i],'=') ){
2033 errcnt += handleswitch(i,err);
2034 }
2035 }
2036 }
2037 if( errcnt>0 ){
2038 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00002039 OptPrint();
drh75897232000-05-29 14:26:00 +00002040 exit(1);
2041 }
2042 return 0;
2043}
2044
drhb0c86772000-06-02 23:21:26 +00002045int OptNArgs(){
drh75897232000-05-29 14:26:00 +00002046 int cnt = 0;
2047 int dashdash = 0;
2048 int i;
2049 if( argv!=0 && argv[0]!=0 ){
2050 for(i=1; argv[i]; i++){
2051 if( dashdash || !ISOPT(argv[i]) ) cnt++;
2052 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
2053 }
2054 }
2055 return cnt;
2056}
2057
icculus9e44cf12010-02-14 17:14:22 +00002058char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00002059{
2060 int i;
2061 i = argindex(n);
2062 return i>=0 ? argv[i] : 0;
2063}
2064
icculus9e44cf12010-02-14 17:14:22 +00002065void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002066{
2067 int i;
2068 i = argindex(n);
2069 if( i>=0 ) errline(i,0,errstream);
2070}
2071
drhb0c86772000-06-02 23:21:26 +00002072void OptPrint(){
drh75897232000-05-29 14:26:00 +00002073 int i;
2074 int max, len;
2075 max = 0;
2076 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002077 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002078 switch( op[i].type ){
2079 case OPT_FLAG:
2080 case OPT_FFLAG:
2081 break;
2082 case OPT_INT:
2083 case OPT_FINT:
2084 len += 9; /* length of "<integer>" */
2085 break;
2086 case OPT_DBL:
2087 case OPT_FDBL:
2088 len += 6; /* length of "<real>" */
2089 break;
2090 case OPT_STR:
2091 case OPT_FSTR:
2092 len += 8; /* length of "<string>" */
2093 break;
2094 }
2095 if( len>max ) max = len;
2096 }
2097 for(i=0; op[i].label; i++){
2098 switch( op[i].type ){
2099 case OPT_FLAG:
2100 case OPT_FFLAG:
2101 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2102 break;
2103 case OPT_INT:
2104 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002105 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002106 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002107 break;
2108 case OPT_DBL:
2109 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002110 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002111 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002112 break;
2113 case OPT_STR:
2114 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002115 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002116 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002117 break;
2118 }
2119 }
2120}
2121/*********************** From the file "parse.c" ****************************/
2122/*
2123** Input file parser for the LEMON parser generator.
2124*/
2125
2126/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002127enum e_state {
2128 INITIALIZE,
2129 WAITING_FOR_DECL_OR_RULE,
2130 WAITING_FOR_DECL_KEYWORD,
2131 WAITING_FOR_DECL_ARG,
2132 WAITING_FOR_PRECEDENCE_SYMBOL,
2133 WAITING_FOR_ARROW,
2134 IN_RHS,
2135 LHS_ALIAS_1,
2136 LHS_ALIAS_2,
2137 LHS_ALIAS_3,
2138 RHS_ALIAS_1,
2139 RHS_ALIAS_2,
2140 PRECEDENCE_MARK_1,
2141 PRECEDENCE_MARK_2,
2142 RESYNC_AFTER_RULE_ERROR,
2143 RESYNC_AFTER_DECL_ERROR,
2144 WAITING_FOR_DESTRUCTOR_SYMBOL,
2145 WAITING_FOR_DATATYPE_SYMBOL,
2146 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002147 WAITING_FOR_WILDCARD_ID,
2148 WAITING_FOR_CLASS_ID,
2149 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002150};
drh75897232000-05-29 14:26:00 +00002151struct pstate {
2152 char *filename; /* Name of the input file */
2153 int tokenlineno; /* Linenumber at which current token starts */
2154 int errorcnt; /* Number of errors so far */
2155 char *tokenstart; /* Text of current token */
2156 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002157 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002158 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002159 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002160 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002161 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002162 int nrhs; /* Number of right-hand side symbols seen */
2163 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002164 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002165 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002166 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002167 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002168 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002169 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002170 enum e_assoc declassoc; /* Assign this association to decl arguments */
2171 int preccounter; /* Assign this precedence to decl arguments */
2172 struct rule *firstrule; /* Pointer to first rule in the grammar */
2173 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2174};
2175
2176/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002177static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002178{
icculus9e44cf12010-02-14 17:14:22 +00002179 const char *x;
drh75897232000-05-29 14:26:00 +00002180 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2181#if 0
2182 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2183 x,psp->state);
2184#endif
2185 switch( psp->state ){
2186 case INITIALIZE:
2187 psp->prevrule = 0;
2188 psp->preccounter = 0;
2189 psp->firstrule = psp->lastrule = 0;
2190 psp->gp->nrule = 0;
2191 /* Fall thru to next case */
2192 case WAITING_FOR_DECL_OR_RULE:
2193 if( x[0]=='%' ){
2194 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002195 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002196 psp->lhs = Symbol_new(x);
2197 psp->nrhs = 0;
2198 psp->lhsalias = 0;
2199 psp->state = WAITING_FOR_ARROW;
2200 }else if( x[0]=='{' ){
2201 if( psp->prevrule==0 ){
2202 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002203"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002204fragment which begins on this line.");
2205 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002206 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002207 ErrorMsg(psp->filename,psp->tokenlineno,
2208"Code fragment beginning on this line is not the first \
2209to follow the previous rule.");
2210 psp->errorcnt++;
2211 }else{
2212 psp->prevrule->line = psp->tokenlineno;
2213 psp->prevrule->code = &x[1];
drhf2f105d2012-08-20 15:53:54 +00002214 }
drh75897232000-05-29 14:26:00 +00002215 }else if( x[0]=='[' ){
2216 psp->state = PRECEDENCE_MARK_1;
2217 }else{
2218 ErrorMsg(psp->filename,psp->tokenlineno,
2219 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2220 x);
2221 psp->errorcnt++;
2222 }
2223 break;
2224 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002225 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002226 ErrorMsg(psp->filename,psp->tokenlineno,
2227 "The precedence symbol must be a terminal.");
2228 psp->errorcnt++;
2229 }else if( psp->prevrule==0 ){
2230 ErrorMsg(psp->filename,psp->tokenlineno,
2231 "There is no prior rule to assign precedence \"[%s]\".",x);
2232 psp->errorcnt++;
2233 }else if( psp->prevrule->precsym!=0 ){
2234 ErrorMsg(psp->filename,psp->tokenlineno,
2235"Precedence mark on this line is not the first \
2236to follow the previous rule.");
2237 psp->errorcnt++;
2238 }else{
2239 psp->prevrule->precsym = Symbol_new(x);
2240 }
2241 psp->state = PRECEDENCE_MARK_2;
2242 break;
2243 case PRECEDENCE_MARK_2:
2244 if( x[0]!=']' ){
2245 ErrorMsg(psp->filename,psp->tokenlineno,
2246 "Missing \"]\" on precedence mark.");
2247 psp->errorcnt++;
2248 }
2249 psp->state = WAITING_FOR_DECL_OR_RULE;
2250 break;
2251 case WAITING_FOR_ARROW:
2252 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2253 psp->state = IN_RHS;
2254 }else if( x[0]=='(' ){
2255 psp->state = LHS_ALIAS_1;
2256 }else{
2257 ErrorMsg(psp->filename,psp->tokenlineno,
2258 "Expected to see a \":\" following the LHS symbol \"%s\".",
2259 psp->lhs->name);
2260 psp->errorcnt++;
2261 psp->state = RESYNC_AFTER_RULE_ERROR;
2262 }
2263 break;
2264 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002265 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002266 psp->lhsalias = x;
2267 psp->state = LHS_ALIAS_2;
2268 }else{
2269 ErrorMsg(psp->filename,psp->tokenlineno,
2270 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2271 x,psp->lhs->name);
2272 psp->errorcnt++;
2273 psp->state = RESYNC_AFTER_RULE_ERROR;
2274 }
2275 break;
2276 case LHS_ALIAS_2:
2277 if( x[0]==')' ){
2278 psp->state = LHS_ALIAS_3;
2279 }else{
2280 ErrorMsg(psp->filename,psp->tokenlineno,
2281 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2282 psp->errorcnt++;
2283 psp->state = RESYNC_AFTER_RULE_ERROR;
2284 }
2285 break;
2286 case LHS_ALIAS_3:
2287 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2288 psp->state = IN_RHS;
2289 }else{
2290 ErrorMsg(psp->filename,psp->tokenlineno,
2291 "Missing \"->\" following: \"%s(%s)\".",
2292 psp->lhs->name,psp->lhsalias);
2293 psp->errorcnt++;
2294 psp->state = RESYNC_AFTER_RULE_ERROR;
2295 }
2296 break;
2297 case IN_RHS:
2298 if( x[0]=='.' ){
2299 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002300 rp = (struct rule *)calloc( sizeof(struct rule) +
2301 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002302 if( rp==0 ){
2303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "Can't allocate enough memory for this rule.");
2305 psp->errorcnt++;
2306 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002307 }else{
drh75897232000-05-29 14:26:00 +00002308 int i;
2309 rp->ruleline = psp->tokenlineno;
2310 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002311 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002312 for(i=0; i<psp->nrhs; i++){
2313 rp->rhs[i] = psp->rhs[i];
2314 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002315 }
drh75897232000-05-29 14:26:00 +00002316 rp->lhs = psp->lhs;
2317 rp->lhsalias = psp->lhsalias;
2318 rp->nrhs = psp->nrhs;
2319 rp->code = 0;
2320 rp->precsym = 0;
2321 rp->index = psp->gp->nrule++;
2322 rp->nextlhs = rp->lhs->rule;
2323 rp->lhs->rule = rp;
2324 rp->next = 0;
2325 if( psp->firstrule==0 ){
2326 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002327 }else{
drh75897232000-05-29 14:26:00 +00002328 psp->lastrule->next = rp;
2329 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002330 }
drh75897232000-05-29 14:26:00 +00002331 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002332 }
drh75897232000-05-29 14:26:00 +00002333 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002334 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002335 if( psp->nrhs>=MAXRHS ){
2336 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002337 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002338 x);
2339 psp->errorcnt++;
2340 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002341 }else{
drh75897232000-05-29 14:26:00 +00002342 psp->rhs[psp->nrhs] = Symbol_new(x);
2343 psp->alias[psp->nrhs] = 0;
2344 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002345 }
drhfd405312005-11-06 04:06:59 +00002346 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2347 struct symbol *msp = psp->rhs[psp->nrhs-1];
2348 if( msp->type!=MULTITERMINAL ){
2349 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002350 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002351 memset(msp, 0, sizeof(*msp));
2352 msp->type = MULTITERMINAL;
2353 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002354 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002355 msp->subsym[0] = origsp;
2356 msp->name = origsp->name;
2357 psp->rhs[psp->nrhs-1] = msp;
2358 }
2359 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002360 msp->subsym = (struct symbol **) realloc(msp->subsym,
2361 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002362 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002363 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002364 ErrorMsg(psp->filename,psp->tokenlineno,
2365 "Cannot form a compound containing a non-terminal");
2366 psp->errorcnt++;
2367 }
drh75897232000-05-29 14:26:00 +00002368 }else if( x[0]=='(' && psp->nrhs>0 ){
2369 psp->state = RHS_ALIAS_1;
2370 }else{
2371 ErrorMsg(psp->filename,psp->tokenlineno,
2372 "Illegal character on RHS of rule: \"%s\".",x);
2373 psp->errorcnt++;
2374 psp->state = RESYNC_AFTER_RULE_ERROR;
2375 }
2376 break;
2377 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002378 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002379 psp->alias[psp->nrhs-1] = x;
2380 psp->state = RHS_ALIAS_2;
2381 }else{
2382 ErrorMsg(psp->filename,psp->tokenlineno,
2383 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2384 x,psp->rhs[psp->nrhs-1]->name);
2385 psp->errorcnt++;
2386 psp->state = RESYNC_AFTER_RULE_ERROR;
2387 }
2388 break;
2389 case RHS_ALIAS_2:
2390 if( x[0]==')' ){
2391 psp->state = IN_RHS;
2392 }else{
2393 ErrorMsg(psp->filename,psp->tokenlineno,
2394 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2395 psp->errorcnt++;
2396 psp->state = RESYNC_AFTER_RULE_ERROR;
2397 }
2398 break;
2399 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002400 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002401 psp->declkeyword = x;
2402 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002403 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002404 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002405 psp->state = WAITING_FOR_DECL_ARG;
2406 if( strcmp(x,"name")==0 ){
2407 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002408 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002409 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002410 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002411 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002412 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002413 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002414 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002415 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002416 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002417 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002418 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002419 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002420 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002421 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002422 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002423 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002424 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002425 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002426 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002427 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002428 }else if( strcmp(x,"extra_argument")==0 ){
2429 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002430 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002431 }else if( strcmp(x,"token_type")==0 ){
2432 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002433 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002434 }else if( strcmp(x,"default_type")==0 ){
2435 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002436 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002437 }else if( strcmp(x,"stack_size")==0 ){
2438 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002439 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002440 }else if( strcmp(x,"start_symbol")==0 ){
2441 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002442 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002443 }else if( strcmp(x,"left")==0 ){
2444 psp->preccounter++;
2445 psp->declassoc = LEFT;
2446 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2447 }else if( strcmp(x,"right")==0 ){
2448 psp->preccounter++;
2449 psp->declassoc = RIGHT;
2450 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2451 }else if( strcmp(x,"nonassoc")==0 ){
2452 psp->preccounter++;
2453 psp->declassoc = NONE;
2454 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002455 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002456 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002457 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002458 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002459 }else if( strcmp(x,"fallback")==0 ){
2460 psp->fallback = 0;
2461 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002462 }else if( strcmp(x,"wildcard")==0 ){
2463 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002464 }else if( strcmp(x,"token_class")==0 ){
2465 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002466 }else{
2467 ErrorMsg(psp->filename,psp->tokenlineno,
2468 "Unknown declaration keyword: \"%%%s\".",x);
2469 psp->errorcnt++;
2470 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002471 }
drh75897232000-05-29 14:26:00 +00002472 }else{
2473 ErrorMsg(psp->filename,psp->tokenlineno,
2474 "Illegal declaration keyword: \"%s\".",x);
2475 psp->errorcnt++;
2476 psp->state = RESYNC_AFTER_DECL_ERROR;
2477 }
2478 break;
2479 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002480 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002481 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002482 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002483 psp->errorcnt++;
2484 psp->state = RESYNC_AFTER_DECL_ERROR;
2485 }else{
icculusd286fa62010-03-03 17:06:32 +00002486 struct symbol *sp = Symbol_new(x);
2487 psp->declargslot = &sp->destructor;
2488 psp->decllinenoslot = &sp->destLineno;
2489 psp->insertLineMacro = 1;
2490 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002491 }
2492 break;
2493 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002494 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002495 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002496 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002497 psp->errorcnt++;
2498 psp->state = RESYNC_AFTER_DECL_ERROR;
2499 }else{
icculus866bf1e2010-02-17 20:31:32 +00002500 struct symbol *sp = Symbol_find(x);
2501 if((sp) && (sp->datatype)){
2502 ErrorMsg(psp->filename,psp->tokenlineno,
2503 "Symbol %%type \"%s\" already defined", x);
2504 psp->errorcnt++;
2505 psp->state = RESYNC_AFTER_DECL_ERROR;
2506 }else{
2507 if (!sp){
2508 sp = Symbol_new(x);
2509 }
2510 psp->declargslot = &sp->datatype;
2511 psp->insertLineMacro = 0;
2512 psp->state = WAITING_FOR_DECL_ARG;
2513 }
drh75897232000-05-29 14:26:00 +00002514 }
2515 break;
2516 case WAITING_FOR_PRECEDENCE_SYMBOL:
2517 if( x[0]=='.' ){
2518 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002519 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002520 struct symbol *sp;
2521 sp = Symbol_new(x);
2522 if( sp->prec>=0 ){
2523 ErrorMsg(psp->filename,psp->tokenlineno,
2524 "Symbol \"%s\" has already be given a precedence.",x);
2525 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002526 }else{
drh75897232000-05-29 14:26:00 +00002527 sp->prec = psp->preccounter;
2528 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002529 }
drh75897232000-05-29 14:26:00 +00002530 }else{
2531 ErrorMsg(psp->filename,psp->tokenlineno,
2532 "Can't assign a precedence to \"%s\".",x);
2533 psp->errorcnt++;
2534 }
2535 break;
2536 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002537 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002538 const char *zOld, *zNew;
2539 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002540 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002541 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002542 char zLine[50];
2543 zNew = x;
2544 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002545 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002546 if( *psp->declargslot ){
2547 zOld = *psp->declargslot;
2548 }else{
2549 zOld = "";
2550 }
drh87cf1372008-08-13 20:09:06 +00002551 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002552 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002553 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002554 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2555 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002556 for(z=psp->filename, nBack=0; *z; z++){
2557 if( *z=='\\' ) nBack++;
2558 }
drh898799f2014-01-10 23:21:00 +00002559 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002560 nLine = lemonStrlen(zLine);
2561 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002562 }
icculus9e44cf12010-02-14 17:14:22 +00002563 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2564 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002565 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002566 if( nOld && zBuf[-1]!='\n' ){
2567 *(zBuf++) = '\n';
2568 }
2569 memcpy(zBuf, zLine, nLine);
2570 zBuf += nLine;
2571 *(zBuf++) = '"';
2572 for(z=psp->filename; *z; z++){
2573 if( *z=='\\' ){
2574 *(zBuf++) = '\\';
2575 }
2576 *(zBuf++) = *z;
2577 }
2578 *(zBuf++) = '"';
2579 *(zBuf++) = '\n';
2580 }
drh4dc8ef52008-07-01 17:13:57 +00002581 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2582 psp->decllinenoslot[0] = psp->tokenlineno;
2583 }
drha5808f32008-04-27 22:19:44 +00002584 memcpy(zBuf, zNew, nNew);
2585 zBuf += nNew;
2586 *zBuf = 0;
2587 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002588 }else{
2589 ErrorMsg(psp->filename,psp->tokenlineno,
2590 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2591 psp->errorcnt++;
2592 psp->state = RESYNC_AFTER_DECL_ERROR;
2593 }
2594 break;
drh0bd1f4e2002-06-06 18:54:39 +00002595 case WAITING_FOR_FALLBACK_ID:
2596 if( x[0]=='.' ){
2597 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002598 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002599 ErrorMsg(psp->filename, psp->tokenlineno,
2600 "%%fallback argument \"%s\" should be a token", x);
2601 psp->errorcnt++;
2602 }else{
2603 struct symbol *sp = Symbol_new(x);
2604 if( psp->fallback==0 ){
2605 psp->fallback = sp;
2606 }else if( sp->fallback ){
2607 ErrorMsg(psp->filename, psp->tokenlineno,
2608 "More than one fallback assigned to token %s", x);
2609 psp->errorcnt++;
2610 }else{
2611 sp->fallback = psp->fallback;
2612 psp->gp->has_fallback = 1;
2613 }
2614 }
2615 break;
drhe09daa92006-06-10 13:29:31 +00002616 case WAITING_FOR_WILDCARD_ID:
2617 if( x[0]=='.' ){
2618 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002619 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002620 ErrorMsg(psp->filename, psp->tokenlineno,
2621 "%%wildcard argument \"%s\" should be a token", x);
2622 psp->errorcnt++;
2623 }else{
2624 struct symbol *sp = Symbol_new(x);
2625 if( psp->gp->wildcard==0 ){
2626 psp->gp->wildcard = sp;
2627 }else{
2628 ErrorMsg(psp->filename, psp->tokenlineno,
2629 "Extra wildcard to token: %s", x);
2630 psp->errorcnt++;
2631 }
2632 }
2633 break;
drh61f92cd2014-01-11 03:06:18 +00002634 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002635 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002636 ErrorMsg(psp->filename, psp->tokenlineno,
2637 "%%token_class must be followed by an identifier: ", x);
2638 psp->errorcnt++;
2639 psp->state = RESYNC_AFTER_DECL_ERROR;
2640 }else if( Symbol_find(x) ){
2641 ErrorMsg(psp->filename, psp->tokenlineno,
2642 "Symbol \"%s\" already used", x);
2643 psp->errorcnt++;
2644 psp->state = RESYNC_AFTER_DECL_ERROR;
2645 }else{
2646 psp->tkclass = Symbol_new(x);
2647 psp->tkclass->type = MULTITERMINAL;
2648 psp->state = WAITING_FOR_CLASS_TOKEN;
2649 }
2650 break;
2651 case WAITING_FOR_CLASS_TOKEN:
2652 if( x[0]=='.' ){
2653 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002654 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002655 struct symbol *msp = psp->tkclass;
2656 msp->nsubsym++;
2657 msp->subsym = (struct symbol **) realloc(msp->subsym,
2658 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002659 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002660 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2661 }else{
2662 ErrorMsg(psp->filename, psp->tokenlineno,
2663 "%%token_class argument \"%s\" should be a token", x);
2664 psp->errorcnt++;
2665 psp->state = RESYNC_AFTER_DECL_ERROR;
2666 }
2667 break;
drh75897232000-05-29 14:26:00 +00002668 case RESYNC_AFTER_RULE_ERROR:
2669/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2670** break; */
2671 case RESYNC_AFTER_DECL_ERROR:
2672 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2673 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2674 break;
2675 }
2676}
2677
drh34ff57b2008-07-14 12:27:51 +00002678/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002679** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2680** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2681** comments them out. Text in between is also commented out as appropriate.
2682*/
danielk1977940fac92005-01-23 22:41:37 +00002683static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002684 int i, j, k, n;
2685 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002686 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002687 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002688 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002689 for(i=0; z[i]; i++){
2690 if( z[i]=='\n' ) lineno++;
2691 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002692 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002693 if( exclude ){
2694 exclude--;
2695 if( exclude==0 ){
2696 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2697 }
2698 }
2699 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002700 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2701 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002702 if( exclude ){
2703 exclude++;
2704 }else{
drhc56fac72015-10-29 13:48:15 +00002705 for(j=i+7; ISSPACE(z[j]); j++){}
2706 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002707 exclude = 1;
2708 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002709 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002710 exclude = 0;
2711 break;
2712 }
2713 }
2714 if( z[i+3]=='n' ) exclude = !exclude;
2715 if( exclude ){
2716 start = i;
2717 start_lineno = lineno;
2718 }
2719 }
2720 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2721 }
2722 }
2723 if( exclude ){
2724 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2725 exit(1);
2726 }
2727}
2728
drh75897232000-05-29 14:26:00 +00002729/* In spite of its name, this function is really a scanner. It read
2730** in the entire input file (all at once) then tokenizes it. Each
2731** token is passed to the function "parseonetoken" which builds all
2732** the appropriate data structures in the global state vector "gp".
2733*/
icculus9e44cf12010-02-14 17:14:22 +00002734void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002735{
2736 struct pstate ps;
2737 FILE *fp;
2738 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002739 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002740 int lineno;
2741 int c;
2742 char *cp, *nextcp;
2743 int startline = 0;
2744
rse38514a92007-09-20 11:34:17 +00002745 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002746 ps.gp = gp;
2747 ps.filename = gp->filename;
2748 ps.errorcnt = 0;
2749 ps.state = INITIALIZE;
2750
2751 /* Begin by reading the input file */
2752 fp = fopen(ps.filename,"rb");
2753 if( fp==0 ){
2754 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2755 gp->errorcnt++;
2756 return;
2757 }
2758 fseek(fp,0,2);
2759 filesize = ftell(fp);
2760 rewind(fp);
2761 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002762 if( filesize>100000000 || filebuf==0 ){
2763 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002764 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002765 fclose(fp);
drh75897232000-05-29 14:26:00 +00002766 return;
2767 }
2768 if( fread(filebuf,1,filesize,fp)!=filesize ){
2769 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2770 filesize);
2771 free(filebuf);
2772 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002773 fclose(fp);
drh75897232000-05-29 14:26:00 +00002774 return;
2775 }
2776 fclose(fp);
2777 filebuf[filesize] = 0;
2778
drh6d08b4d2004-07-20 12:45:22 +00002779 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2780 preprocess_input(filebuf);
2781
drh75897232000-05-29 14:26:00 +00002782 /* Now scan the text of the input file */
2783 lineno = 1;
2784 for(cp=filebuf; (c= *cp)!=0; ){
2785 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002786 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002787 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2788 cp+=2;
2789 while( (c= *cp)!=0 && c!='\n' ) cp++;
2790 continue;
2791 }
2792 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2793 cp+=2;
2794 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2795 if( c=='\n' ) lineno++;
2796 cp++;
2797 }
2798 if( c ) cp++;
2799 continue;
2800 }
2801 ps.tokenstart = cp; /* Mark the beginning of the token */
2802 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2803 if( c=='\"' ){ /* String literals */
2804 cp++;
2805 while( (c= *cp)!=0 && c!='\"' ){
2806 if( c=='\n' ) lineno++;
2807 cp++;
2808 }
2809 if( c==0 ){
2810 ErrorMsg(ps.filename,startline,
2811"String starting on this line is not terminated before the end of the file.");
2812 ps.errorcnt++;
2813 nextcp = cp;
2814 }else{
2815 nextcp = cp+1;
2816 }
2817 }else if( c=='{' ){ /* A block of C code */
2818 int level;
2819 cp++;
2820 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2821 if( c=='\n' ) lineno++;
2822 else if( c=='{' ) level++;
2823 else if( c=='}' ) level--;
2824 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2825 int prevc;
2826 cp = &cp[2];
2827 prevc = 0;
2828 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2829 if( c=='\n' ) lineno++;
2830 prevc = c;
2831 cp++;
drhf2f105d2012-08-20 15:53:54 +00002832 }
2833 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002834 cp = &cp[2];
2835 while( (c= *cp)!=0 && c!='\n' ) cp++;
2836 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002837 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002838 int startchar, prevc;
2839 startchar = c;
2840 prevc = 0;
2841 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2842 if( c=='\n' ) lineno++;
2843 if( prevc=='\\' ) prevc = 0;
2844 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002845 }
2846 }
drh75897232000-05-29 14:26:00 +00002847 }
2848 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002849 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002850"C code starting on this line is not terminated before the end of the file.");
2851 ps.errorcnt++;
2852 nextcp = cp;
2853 }else{
2854 nextcp = cp+1;
2855 }
drhc56fac72015-10-29 13:48:15 +00002856 }else if( ISALNUM(c) ){ /* Identifiers */
2857 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002858 nextcp = cp;
2859 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2860 cp += 3;
2861 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002862 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002863 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002864 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002865 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002866 }else{ /* All other (one character) operators */
2867 cp++;
2868 nextcp = cp;
2869 }
2870 c = *cp;
2871 *cp = 0; /* Null terminate the token */
2872 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002873 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002874 cp = nextcp;
2875 }
2876 free(filebuf); /* Release the buffer after parsing */
2877 gp->rule = ps.firstrule;
2878 gp->errorcnt = ps.errorcnt;
2879}
2880/*************************** From the file "plink.c" *********************/
2881/*
2882** Routines processing configuration follow-set propagation links
2883** in the LEMON parser generator.
2884*/
2885static struct plink *plink_freelist = 0;
2886
2887/* Allocate a new plink */
2888struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002889 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002890
2891 if( plink_freelist==0 ){
2892 int i;
2893 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002894 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002895 if( plink_freelist==0 ){
2896 fprintf(stderr,
2897 "Unable to allocate memory for a new follow-set propagation link.\n");
2898 exit(1);
2899 }
2900 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2901 plink_freelist[amt-1].next = 0;
2902 }
icculus9e44cf12010-02-14 17:14:22 +00002903 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002904 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002905 return newlink;
drh75897232000-05-29 14:26:00 +00002906}
2907
2908/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002909void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002910{
icculus9e44cf12010-02-14 17:14:22 +00002911 struct plink *newlink;
2912 newlink = Plink_new();
2913 newlink->next = *plpp;
2914 *plpp = newlink;
2915 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002916}
2917
2918/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002919void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002920{
2921 struct plink *nextpl;
2922 while( from ){
2923 nextpl = from->next;
2924 from->next = *to;
2925 *to = from;
2926 from = nextpl;
2927 }
2928}
2929
2930/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002931void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002932{
2933 struct plink *nextpl;
2934
2935 while( plp ){
2936 nextpl = plp->next;
2937 plp->next = plink_freelist;
2938 plink_freelist = plp;
2939 plp = nextpl;
2940 }
2941}
2942/*********************** From the file "report.c" **************************/
2943/*
2944** Procedures for generating reports and tables in the LEMON parser generator.
2945*/
2946
2947/* Generate a filename with the given suffix. Space to hold the
2948** name comes from malloc() and must be freed by the calling
2949** function.
2950*/
icculus9e44cf12010-02-14 17:14:22 +00002951PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002952{
2953 char *name;
2954 char *cp;
2955
icculus9e44cf12010-02-14 17:14:22 +00002956 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002957 if( name==0 ){
2958 fprintf(stderr,"Can't allocate space for a filename.\n");
2959 exit(1);
2960 }
drh898799f2014-01-10 23:21:00 +00002961 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002962 cp = strrchr(name,'.');
2963 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002964 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002965 return name;
2966}
2967
2968/* Open a file with a name based on the name of the input file,
2969** but with a different (specified) suffix, and return a pointer
2970** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002971PRIVATE FILE *file_open(
2972 struct lemon *lemp,
2973 const char *suffix,
2974 const char *mode
2975){
drh75897232000-05-29 14:26:00 +00002976 FILE *fp;
2977
2978 if( lemp->outname ) free(lemp->outname);
2979 lemp->outname = file_makename(lemp, suffix);
2980 fp = fopen(lemp->outname,mode);
2981 if( fp==0 && *mode=='w' ){
2982 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2983 lemp->errorcnt++;
2984 return 0;
2985 }
2986 return fp;
2987}
2988
2989/* Duplicate the input file without comments and without actions
2990** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002991void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002992{
2993 struct rule *rp;
2994 struct symbol *sp;
2995 int i, j, maxlen, len, ncolumns, skip;
2996 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2997 maxlen = 10;
2998 for(i=0; i<lemp->nsymbol; i++){
2999 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00003000 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00003001 if( len>maxlen ) maxlen = len;
3002 }
3003 ncolumns = 76/(maxlen+5);
3004 if( ncolumns<1 ) ncolumns = 1;
3005 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
3006 for(i=0; i<skip; i++){
3007 printf("//");
3008 for(j=i; j<lemp->nsymbol; j+=skip){
3009 sp = lemp->symbols[j];
3010 assert( sp->index==j );
3011 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
3012 }
3013 printf("\n");
3014 }
3015 for(rp=lemp->rule; rp; rp=rp->next){
3016 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00003017 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00003018 printf(" ::=");
3019 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00003020 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003021 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003022 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003023 for(j=1; j<sp->nsubsym; j++){
3024 printf("|%s", sp->subsym[j]->name);
3025 }
drh61f92cd2014-01-11 03:06:18 +00003026 }else{
3027 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003028 }
3029 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00003030 }
3031 printf(".");
3032 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00003033 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00003034 printf("\n");
3035 }
3036}
3037
drh7e698e92015-09-07 14:22:24 +00003038/* Print a single rule.
3039*/
3040void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00003041 struct symbol *sp;
3042 int i, j;
drh75897232000-05-29 14:26:00 +00003043 fprintf(fp,"%s ::=",rp->lhs->name);
3044 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00003045 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00003046 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00003047 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00003048 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00003049 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00003050 for(j=1; j<sp->nsubsym; j++){
3051 fprintf(fp,"|%s",sp->subsym[j]->name);
3052 }
drh61f92cd2014-01-11 03:06:18 +00003053 }else{
3054 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00003055 }
drh75897232000-05-29 14:26:00 +00003056 }
3057}
3058
drh7e698e92015-09-07 14:22:24 +00003059/* Print the rule for a configuration.
3060*/
3061void ConfigPrint(FILE *fp, struct config *cfp){
3062 RulePrint(fp, cfp->rp, cfp->dot);
3063}
3064
drh75897232000-05-29 14:26:00 +00003065/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003066#if 0
drh75897232000-05-29 14:26:00 +00003067/* Print a set */
3068PRIVATE void SetPrint(out,set,lemp)
3069FILE *out;
3070char *set;
3071struct lemon *lemp;
3072{
3073 int i;
3074 char *spacer;
3075 spacer = "";
3076 fprintf(out,"%12s[","");
3077 for(i=0; i<lemp->nterminal; i++){
3078 if( SetFind(set,i) ){
3079 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3080 spacer = " ";
3081 }
3082 }
3083 fprintf(out,"]\n");
3084}
3085
3086/* Print a plink chain */
3087PRIVATE void PlinkPrint(out,plp,tag)
3088FILE *out;
3089struct plink *plp;
3090char *tag;
3091{
3092 while( plp ){
drhada354d2005-11-05 15:03:59 +00003093 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003094 ConfigPrint(out,plp->cfp);
3095 fprintf(out,"\n");
3096 plp = plp->next;
3097 }
3098}
3099#endif
3100
3101/* Print an action to the given file descriptor. Return FALSE if
3102** nothing was actually printed.
3103*/
drh7e698e92015-09-07 14:22:24 +00003104int PrintAction(
3105 struct action *ap, /* The action to print */
3106 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003107 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003108){
drh75897232000-05-29 14:26:00 +00003109 int result = 1;
3110 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003111 case SHIFT: {
3112 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003113 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003114 break;
drh7e698e92015-09-07 14:22:24 +00003115 }
3116 case REDUCE: {
3117 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003118 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003119 RulePrint(fp, rp, -1);
3120 break;
3121 }
3122 case SHIFTREDUCE: {
3123 struct rule *rp = ap->x.rp;
drh4ef07702016-03-16 19:45:54 +00003124 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->iRule);
drh3bd48ab2015-09-07 18:23:37 +00003125 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003126 break;
drh7e698e92015-09-07 14:22:24 +00003127 }
drh75897232000-05-29 14:26:00 +00003128 case ACCEPT:
3129 fprintf(fp,"%*s accept",indent,ap->sp->name);
3130 break;
3131 case ERROR:
3132 fprintf(fp,"%*s error",indent,ap->sp->name);
3133 break;
drh9892c5d2007-12-21 00:02:11 +00003134 case SRCONFLICT:
3135 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003136 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh4ef07702016-03-16 19:45:54 +00003137 indent,ap->sp->name,ap->x.rp->iRule);
drh75897232000-05-29 14:26:00 +00003138 break;
drh9892c5d2007-12-21 00:02:11 +00003139 case SSCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003140 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003141 indent,ap->sp->name,ap->x.stp->statenum);
3142 break;
drh75897232000-05-29 14:26:00 +00003143 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003144 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003145 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003146 indent,ap->sp->name,ap->x.stp->statenum);
3147 }else{
3148 result = 0;
3149 }
3150 break;
drh75897232000-05-29 14:26:00 +00003151 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003152 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003153 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drh4ef07702016-03-16 19:45:54 +00003154 indent,ap->sp->name,ap->x.rp->iRule);
drhf5c4e0f2010-07-18 11:35:53 +00003155 }else{
3156 result = 0;
3157 }
3158 break;
drh75897232000-05-29 14:26:00 +00003159 case NOT_USED:
3160 result = 0;
3161 break;
3162 }
3163 return result;
3164}
3165
drh3bd48ab2015-09-07 18:23:37 +00003166/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003167void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003168{
3169 int i;
3170 struct state *stp;
3171 struct config *cfp;
3172 struct action *ap;
3173 FILE *fp;
3174
drh2aa6ca42004-09-10 00:14:04 +00003175 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003176 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003177 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003178 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003179 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003180 if( lemp->basisflag ) cfp=stp->bp;
3181 else cfp=stp->cfp;
3182 while( cfp ){
3183 char buf[20];
3184 if( cfp->dot==cfp->rp->nrhs ){
drh4ef07702016-03-16 19:45:54 +00003185 lemon_sprintf(buf,"(%d)",cfp->rp->iRule);
drh75897232000-05-29 14:26:00 +00003186 fprintf(fp," %5s ",buf);
3187 }else{
3188 fprintf(fp," ");
3189 }
3190 ConfigPrint(fp,cfp);
3191 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003192#if 0
drh75897232000-05-29 14:26:00 +00003193 SetPrint(fp,cfp->fws,lemp);
3194 PlinkPrint(fp,cfp->fplp,"To ");
3195 PlinkPrint(fp,cfp->bplp,"From");
3196#endif
3197 if( lemp->basisflag ) cfp=cfp->bp;
3198 else cfp=cfp->next;
3199 }
3200 fprintf(fp,"\n");
3201 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003202 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003203 }
3204 fprintf(fp,"\n");
3205 }
drhe9278182007-07-18 18:16:29 +00003206 fprintf(fp, "----------------------------------------------------\n");
3207 fprintf(fp, "Symbols:\n");
3208 for(i=0; i<lemp->nsymbol; i++){
3209 int j;
3210 struct symbol *sp;
3211
3212 sp = lemp->symbols[i];
3213 fprintf(fp, " %3d: %s", i, sp->name);
3214 if( sp->type==NONTERMINAL ){
3215 fprintf(fp, ":");
3216 if( sp->lambda ){
3217 fprintf(fp, " <lambda>");
3218 }
3219 for(j=0; j<lemp->nterminal; j++){
3220 if( sp->firstset && SetFind(sp->firstset, j) ){
3221 fprintf(fp, " %s", lemp->symbols[j]->name);
3222 }
3223 }
3224 }
3225 fprintf(fp, "\n");
3226 }
drh75897232000-05-29 14:26:00 +00003227 fclose(fp);
3228 return;
3229}
3230
3231/* Search for the file "name" which is in the same directory as
3232** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003233PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003234{
icculus9e44cf12010-02-14 17:14:22 +00003235 const char *pathlist;
3236 char *pathbufptr;
3237 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003238 char *path,*cp;
3239 char c;
drh75897232000-05-29 14:26:00 +00003240
3241#ifdef __WIN32__
3242 cp = strrchr(argv0,'\\');
3243#else
3244 cp = strrchr(argv0,'/');
3245#endif
3246 if( cp ){
3247 c = *cp;
3248 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003249 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003250 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003251 *cp = c;
3252 }else{
drh75897232000-05-29 14:26:00 +00003253 pathlist = getenv("PATH");
3254 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003255 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003256 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003257 if( (pathbuf != 0) && (path!=0) ){
3258 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003259 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003260 while( *pathbuf ){
3261 cp = strchr(pathbuf,':');
3262 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003263 c = *cp;
3264 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003265 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003266 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003267 if( c==0 ) pathbuf[0] = 0;
3268 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003269 if( access(path,modemask)==0 ) break;
3270 }
icculus9e44cf12010-02-14 17:14:22 +00003271 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003272 }
3273 }
3274 return path;
3275}
3276
3277/* Given an action, compute the integer value for that action
3278** which is to be put in the action table of the generated machine.
3279** Return negative if no action should be generated.
3280*/
icculus9e44cf12010-02-14 17:14:22 +00003281PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003282{
3283 int act;
3284 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003285 case SHIFT: act = ap->x.stp->statenum; break;
drh4ef07702016-03-16 19:45:54 +00003286 case SHIFTREDUCE: act = ap->x.rp->iRule + lemp->nstate; break;
3287 case REDUCE: act = ap->x.rp->iRule + lemp->nstate+lemp->nrule; break;
drh3bd48ab2015-09-07 18:23:37 +00003288 case ERROR: act = lemp->nstate + lemp->nrule*2; break;
3289 case ACCEPT: act = lemp->nstate + lemp->nrule*2 + 1; break;
drh75897232000-05-29 14:26:00 +00003290 default: act = -1; break;
3291 }
3292 return act;
3293}
3294
3295#define LINESIZE 1000
3296/* The next cluster of routines are for reading the template file
3297** and writing the results to the generated parser */
3298/* The first function transfers data from "in" to "out" until
3299** a line is seen which begins with "%%". The line number is
3300** tracked.
3301**
3302** if name!=0, then any word that begin with "Parse" is changed to
3303** begin with *name instead.
3304*/
icculus9e44cf12010-02-14 17:14:22 +00003305PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003306{
3307 int i, iStart;
3308 char line[LINESIZE];
3309 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3310 (*lineno)++;
3311 iStart = 0;
3312 if( name ){
3313 for(i=0; line[i]; i++){
3314 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003315 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003316 ){
3317 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3318 fprintf(out,"%s",name);
3319 i += 4;
3320 iStart = i+1;
3321 }
3322 }
3323 }
3324 fprintf(out,"%s",&line[iStart]);
3325 }
3326}
3327
3328/* The next function finds the template file and opens it, returning
3329** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003330PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003331{
3332 static char templatename[] = "lempar.c";
3333 char buf[1000];
3334 FILE *in;
3335 char *tpltname;
3336 char *cp;
3337
icculus3e143bd2010-02-14 00:48:49 +00003338 /* first, see if user specified a template filename on the command line. */
3339 if (user_templatename != 0) {
3340 if( access(user_templatename,004)==-1 ){
3341 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3342 user_templatename);
3343 lemp->errorcnt++;
3344 return 0;
3345 }
3346 in = fopen(user_templatename,"rb");
3347 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003348 fprintf(stderr,"Can't open the template file \"%s\".\n",
3349 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003350 lemp->errorcnt++;
3351 return 0;
3352 }
3353 return in;
3354 }
3355
drh75897232000-05-29 14:26:00 +00003356 cp = strrchr(lemp->filename,'.');
3357 if( cp ){
drh898799f2014-01-10 23:21:00 +00003358 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003359 }else{
drh898799f2014-01-10 23:21:00 +00003360 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003361 }
3362 if( access(buf,004)==0 ){
3363 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003364 }else if( access(templatename,004)==0 ){
3365 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003366 }else{
3367 tpltname = pathsearch(lemp->argv0,templatename,0);
3368 }
3369 if( tpltname==0 ){
3370 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3371 templatename);
3372 lemp->errorcnt++;
3373 return 0;
3374 }
drh2aa6ca42004-09-10 00:14:04 +00003375 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003376 if( in==0 ){
3377 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3378 lemp->errorcnt++;
3379 return 0;
3380 }
3381 return in;
3382}
3383
drhaf805ca2004-09-07 11:28:25 +00003384/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003385PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003386{
3387 fprintf(out,"#line %d \"",lineno);
3388 while( *filename ){
3389 if( *filename == '\\' ) putc('\\',out);
3390 putc(*filename,out);
3391 filename++;
3392 }
3393 fprintf(out,"\"\n");
3394}
3395
drh75897232000-05-29 14:26:00 +00003396/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003397PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003398{
3399 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003400 while( *str ){
drh75897232000-05-29 14:26:00 +00003401 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003402 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003403 str++;
3404 }
drh9db55df2004-09-09 14:01:21 +00003405 if( str[-1]!='\n' ){
3406 putc('\n',out);
3407 (*lineno)++;
3408 }
shane58543932008-12-10 20:10:04 +00003409 if (!lemp->nolinenosflag) {
3410 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3411 }
drh75897232000-05-29 14:26:00 +00003412 return;
3413}
3414
3415/*
3416** The following routine emits code for the destructor for the
3417** symbol sp
3418*/
icculus9e44cf12010-02-14 17:14:22 +00003419void emit_destructor_code(
3420 FILE *out,
3421 struct symbol *sp,
3422 struct lemon *lemp,
3423 int *lineno
3424){
drhcc83b6e2004-04-23 23:38:42 +00003425 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003426
drh75897232000-05-29 14:26:00 +00003427 if( sp->type==TERMINAL ){
3428 cp = lemp->tokendest;
3429 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003430 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003431 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003432 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003433 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003434 if( !lemp->nolinenosflag ){
3435 (*lineno)++;
3436 tplt_linedir(out,sp->destLineno,lemp->filename);
3437 }
drh960e8c62001-04-03 16:53:21 +00003438 }else if( lemp->vardest ){
3439 cp = lemp->vardest;
3440 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003441 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003442 }else{
3443 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003444 }
3445 for(; *cp; cp++){
3446 if( *cp=='$' && cp[1]=='$' ){
3447 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3448 cp++;
3449 continue;
3450 }
shane58543932008-12-10 20:10:04 +00003451 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003452 fputc(*cp,out);
3453 }
shane58543932008-12-10 20:10:04 +00003454 fprintf(out,"\n"); (*lineno)++;
3455 if (!lemp->nolinenosflag) {
3456 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3457 }
3458 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003459 return;
3460}
3461
3462/*
drh960e8c62001-04-03 16:53:21 +00003463** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003464*/
icculus9e44cf12010-02-14 17:14:22 +00003465int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003466{
3467 int ret;
3468 if( sp->type==TERMINAL ){
3469 ret = lemp->tokendest!=0;
3470 }else{
drh960e8c62001-04-03 16:53:21 +00003471 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003472 }
3473 return ret;
3474}
3475
drh0bb132b2004-07-20 14:06:51 +00003476/*
3477** Append text to a dynamically allocated string. If zText is 0 then
3478** reset the string to be empty again. Always return the complete text
3479** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003480**
3481** n bytes of zText are stored. If n==0 then all of zText up to the first
3482** \000 terminator is stored. zText can contain up to two instances of
3483** %d. The values of p1 and p2 are written into the first and second
3484** %d.
3485**
3486** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003487*/
icculus9e44cf12010-02-14 17:14:22 +00003488PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3489 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003490 static char *z = 0;
3491 static int alloced = 0;
3492 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003493 int c;
drh0bb132b2004-07-20 14:06:51 +00003494 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003495 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003496 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003497 used = 0;
3498 return z;
3499 }
drh7ac25c72004-08-19 15:12:26 +00003500 if( n<=0 ){
3501 if( n<0 ){
3502 used += n;
3503 assert( used>=0 );
3504 }
drh87cf1372008-08-13 20:09:06 +00003505 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003506 }
drhdf609712010-11-23 20:55:27 +00003507 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003508 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003509 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003510 }
icculus9e44cf12010-02-14 17:14:22 +00003511 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003512 while( n-- > 0 ){
3513 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003514 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003515 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003516 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003517 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003518 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003519 zText++;
3520 n--;
3521 }else{
mistachkin2318d332015-01-12 18:02:52 +00003522 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003523 }
3524 }
3525 z[used] = 0;
3526 return z;
3527}
3528
3529/*
3530** zCode is a string that is the action associated with a rule. Expand
3531** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003532** stack.
drhdabd04c2016-02-17 01:46:19 +00003533**
3534** Return 1 if the expanded code requires that "yylhsminor" local variable
3535** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003536*/
drhdabd04c2016-02-17 01:46:19 +00003537PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003538 char *cp, *xp;
3539 int i;
drhcf82f0d2016-02-17 04:33:10 +00003540 int rc = 0; /* True if yylhsminor is used */
drh43303de2016-02-17 12:34:03 +00003541 int dontUseRhs0 = 0; /* If true, use of left-most RHS label is illegal */
drhcf82f0d2016-02-17 04:33:10 +00003542 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3543 char lhsused = 0; /* True if the LHS element has been used */
3544 char lhsdirect; /* True if LHS writes directly into stack */
3545 char used[MAXRHS]; /* True for each RHS element which is used */
3546 char zLhs[50]; /* Convert the LHS symbol into this string */
3547 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003548
3549 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3550 lhsused = 0;
3551
drh19c9e562007-03-29 20:13:53 +00003552 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003553 static char newlinestr[2] = { '\n', '\0' };
3554 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003555 rp->line = rp->ruleline;
3556 }
3557
drh4dd0d3f2016-02-17 01:18:33 +00003558
drh2e55b042016-04-30 17:19:30 +00003559 if( rp->nrhs==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003560 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3561 lhsdirect = 1;
3562 }else if( rp->rhsalias[0]==0 ){
drh2e55b042016-04-30 17:19:30 +00003563 /* The left-most RHS symbol has no value. LHS direct is ok. But
drh4dd0d3f2016-02-17 01:18:33 +00003564 ** we have to call the distructor on the RHS symbol first. */
3565 lhsdirect = 1;
3566 if( has_destructor(rp->rhs[0],lemp) ){
3567 append_str(0,0,0,0);
3568 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3569 rp->rhs[0]->index,1-rp->nrhs);
3570 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3571 }
drh2e55b042016-04-30 17:19:30 +00003572 }else if( rp->lhsalias==0 ){
3573 /* There is no LHS value symbol. */
3574 lhsdirect = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003575 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3576 /* The LHS symbol and the left-most RHS symbol are the same, so
3577 ** direct writing is allowed */
3578 lhsdirect = 1;
3579 lhsused = 1;
3580 used[0] = 1;
3581 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3582 ErrorMsg(lemp->filename,rp->ruleline,
3583 "%s(%s) and %s(%s) share the same label but have "
3584 "different datatypes.",
3585 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3586 lemp->errorcnt++;
3587 }
3588 }else{
drhcf82f0d2016-02-17 04:33:10 +00003589 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3590 rp->lhsalias, rp->rhsalias[0]);
3591 zSkip = strstr(rp->code, zOvwrt);
3592 if( zSkip!=0 ){
3593 /* The code contains a special comment that indicates that it is safe
3594 ** for the LHS label to overwrite left-most RHS label. */
3595 lhsdirect = 1;
3596 }else{
3597 lhsdirect = 0;
3598 }
drh4dd0d3f2016-02-17 01:18:33 +00003599 }
3600 if( lhsdirect ){
3601 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3602 }else{
drhdabd04c2016-02-17 01:46:19 +00003603 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003604 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3605 }
3606
drh0bb132b2004-07-20 14:06:51 +00003607 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003608
3609 /* This const cast is wrong but harmless, if we're careful. */
3610 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003611 if( cp==zSkip ){
3612 append_str(zOvwrt,0,0,0);
3613 cp += lemonStrlen(zOvwrt)-1;
drh43303de2016-02-17 12:34:03 +00003614 dontUseRhs0 = 1;
drhcf82f0d2016-02-17 04:33:10 +00003615 continue;
3616 }
drhc56fac72015-10-29 13:48:15 +00003617 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003618 char saved;
drhc56fac72015-10-29 13:48:15 +00003619 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003620 saved = *xp;
3621 *xp = 0;
3622 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003623 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003624 cp = xp;
3625 lhsused = 1;
3626 }else{
3627 for(i=0; i<rp->nrhs; i++){
3628 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh43303de2016-02-17 12:34:03 +00003629 if( i==0 && dontUseRhs0 ){
3630 ErrorMsg(lemp->filename,rp->ruleline,
3631 "Label %s used after '%s'.",
3632 rp->rhsalias[0], zOvwrt);
3633 lemp->errorcnt++;
3634 }else if( cp!=rp->code && cp[-1]=='@' ){
drh7ac25c72004-08-19 15:12:26 +00003635 /* If the argument is of the form @X then substituted
3636 ** the token number of X, not the value of X */
3637 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3638 }else{
drhfd405312005-11-06 04:06:59 +00003639 struct symbol *sp = rp->rhs[i];
3640 int dtnum;
3641 if( sp->type==MULTITERMINAL ){
3642 dtnum = sp->subsym[0]->dtnum;
3643 }else{
3644 dtnum = sp->dtnum;
3645 }
3646 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003647 }
drh0bb132b2004-07-20 14:06:51 +00003648 cp = xp;
3649 used[i] = 1;
3650 break;
3651 }
3652 }
3653 }
3654 *xp = saved;
3655 }
3656 append_str(cp, 1, 0, 0);
3657 } /* End loop */
3658
drh4dd0d3f2016-02-17 01:18:33 +00003659 /* Main code generation completed */
3660 cp = append_str(0,0,0,0);
3661 if( cp && cp[0] ) rp->code = Strsafe(cp);
3662 append_str(0,0,0,0);
3663
drh0bb132b2004-07-20 14:06:51 +00003664 /* Check to make sure the LHS has been used */
3665 if( rp->lhsalias && !lhsused ){
3666 ErrorMsg(lemp->filename,rp->ruleline,
3667 "Label \"%s\" for \"%s(%s)\" is never used.",
3668 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3669 lemp->errorcnt++;
3670 }
3671
drh4dd0d3f2016-02-17 01:18:33 +00003672 /* Generate destructor code for RHS minor values which are not referenced.
3673 ** Generate error messages for unused labels and duplicate labels.
3674 */
drh0bb132b2004-07-20 14:06:51 +00003675 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003676 if( rp->rhsalias[i] ){
3677 if( i>0 ){
3678 int j;
3679 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3680 ErrorMsg(lemp->filename,rp->ruleline,
3681 "%s(%s) has the same label as the LHS but is not the left-most "
3682 "symbol on the RHS.",
3683 rp->rhs[i]->name, rp->rhsalias);
3684 lemp->errorcnt++;
3685 }
3686 for(j=0; j<i; j++){
3687 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3688 ErrorMsg(lemp->filename,rp->ruleline,
3689 "Label %s used for multiple symbols on the RHS of a rule.",
3690 rp->rhsalias[i]);
3691 lemp->errorcnt++;
3692 break;
3693 }
3694 }
drh0bb132b2004-07-20 14:06:51 +00003695 }
drh4dd0d3f2016-02-17 01:18:33 +00003696 if( !used[i] ){
3697 ErrorMsg(lemp->filename,rp->ruleline,
3698 "Label %s for \"%s(%s)\" is never used.",
3699 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3700 lemp->errorcnt++;
3701 }
3702 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3703 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3704 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003705 }
3706 }
drh4dd0d3f2016-02-17 01:18:33 +00003707
3708 /* If unable to write LHS values directly into the stack, write the
3709 ** saved LHS value now. */
3710 if( lhsdirect==0 ){
3711 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3712 append_str(zLhs, 0, 0, 0);
3713 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003714 }
drh4dd0d3f2016-02-17 01:18:33 +00003715
3716 /* Suffix code generation complete */
3717 cp = append_str(0,0,0,0);
drh2e55b042016-04-30 17:19:30 +00003718 if( cp && cp[0] ) rp->codeSuffix = Strsafe(cp);
drhdabd04c2016-02-17 01:46:19 +00003719
3720 return rc;
drh0bb132b2004-07-20 14:06:51 +00003721}
3722
drh75897232000-05-29 14:26:00 +00003723/*
3724** Generate code which executes when the rule "rp" is reduced. Write
3725** the code to "out". Make sure lineno stays up-to-date.
3726*/
icculus9e44cf12010-02-14 17:14:22 +00003727PRIVATE void emit_code(
3728 FILE *out,
3729 struct rule *rp,
3730 struct lemon *lemp,
3731 int *lineno
3732){
3733 const char *cp;
drh75897232000-05-29 14:26:00 +00003734
drh4dd0d3f2016-02-17 01:18:33 +00003735 /* Setup code prior to the #line directive */
3736 if( rp->codePrefix && rp->codePrefix[0] ){
3737 fprintf(out, "{%s", rp->codePrefix);
3738 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3739 }
3740
drh75897232000-05-29 14:26:00 +00003741 /* Generate code to do the reduce action */
3742 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003743 if( !lemp->nolinenosflag ){
3744 (*lineno)++;
3745 tplt_linedir(out,rp->line,lemp->filename);
3746 }
drhaf805ca2004-09-07 11:28:25 +00003747 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003748 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003749 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003750 if( !lemp->nolinenosflag ){
3751 (*lineno)++;
3752 tplt_linedir(out,*lineno,lemp->outname);
3753 }
drh4dd0d3f2016-02-17 01:18:33 +00003754 }
3755
3756 /* Generate breakdown code that occurs after the #line directive */
3757 if( rp->codeSuffix && rp->codeSuffix[0] ){
3758 fprintf(out, "%s", rp->codeSuffix);
3759 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3760 }
3761
3762 if( rp->codePrefix ){
3763 fprintf(out, "}\n"); (*lineno)++;
3764 }
drh75897232000-05-29 14:26:00 +00003765
drh75897232000-05-29 14:26:00 +00003766 return;
3767}
3768
3769/*
3770** Print the definition of the union used for the parser's data stack.
3771** This union contains fields for every possible data type for tokens
3772** and nonterminals. In the process of computing and printing this
3773** union, also set the ".dtnum" field of every terminal and nonterminal
3774** symbol.
3775*/
icculus9e44cf12010-02-14 17:14:22 +00003776void print_stack_union(
3777 FILE *out, /* The output stream */
3778 struct lemon *lemp, /* The main info structure for this parser */
3779 int *plineno, /* Pointer to the line number */
3780 int mhflag /* True if generating makeheaders output */
3781){
drh75897232000-05-29 14:26:00 +00003782 int lineno = *plineno; /* The line number of the output */
3783 char **types; /* A hash table of datatypes */
3784 int arraysize; /* Size of the "types" array */
3785 int maxdtlength; /* Maximum length of any ".datatype" field. */
3786 char *stddt; /* Standardized name for a datatype */
3787 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003788 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003789 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003790
3791 /* Allocate and initialize types[] and allocate stddt[] */
3792 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003793 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003794 if( types==0 ){
3795 fprintf(stderr,"Out of memory.\n");
3796 exit(1);
3797 }
drh75897232000-05-29 14:26:00 +00003798 for(i=0; i<arraysize; i++) types[i] = 0;
3799 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003800 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003801 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003802 }
drh75897232000-05-29 14:26:00 +00003803 for(i=0; i<lemp->nsymbol; i++){
3804 int len;
3805 struct symbol *sp = lemp->symbols[i];
3806 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003807 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003808 if( len>maxdtlength ) maxdtlength = len;
3809 }
3810 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003811 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003812 fprintf(stderr,"Out of memory.\n");
3813 exit(1);
3814 }
3815
3816 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3817 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003818 ** used for terminal symbols. If there is no %default_type defined then
3819 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3820 ** a datatype using the %type directive.
3821 */
drh75897232000-05-29 14:26:00 +00003822 for(i=0; i<lemp->nsymbol; i++){
3823 struct symbol *sp = lemp->symbols[i];
3824 char *cp;
3825 if( sp==lemp->errsym ){
3826 sp->dtnum = arraysize+1;
3827 continue;
3828 }
drh960e8c62001-04-03 16:53:21 +00003829 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003830 sp->dtnum = 0;
3831 continue;
3832 }
3833 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003834 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003835 j = 0;
drhc56fac72015-10-29 13:48:15 +00003836 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003837 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003838 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003839 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003840 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003841 sp->dtnum = 0;
3842 continue;
3843 }
drh75897232000-05-29 14:26:00 +00003844 hash = 0;
3845 for(j=0; stddt[j]; j++){
3846 hash = hash*53 + stddt[j];
3847 }
drh3b2129c2003-05-13 00:34:21 +00003848 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003849 while( types[hash] ){
3850 if( strcmp(types[hash],stddt)==0 ){
3851 sp->dtnum = hash + 1;
3852 break;
3853 }
3854 hash++;
drh2b51f212013-10-11 23:01:02 +00003855 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003856 }
3857 if( types[hash]==0 ){
3858 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003859 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003860 if( types[hash]==0 ){
3861 fprintf(stderr,"Out of memory.\n");
3862 exit(1);
3863 }
drh898799f2014-01-10 23:21:00 +00003864 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003865 }
3866 }
3867
3868 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3869 name = lemp->name ? lemp->name : "Parse";
3870 lineno = *plineno;
3871 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3872 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3873 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3874 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3875 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003876 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003877 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3878 for(i=0; i<arraysize; i++){
3879 if( types[i]==0 ) continue;
3880 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3881 free(types[i]);
3882 }
drhc4dd3fd2008-01-22 01:48:05 +00003883 if( lemp->errsym->useCnt ){
3884 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3885 }
drh75897232000-05-29 14:26:00 +00003886 free(stddt);
3887 free(types);
3888 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3889 *plineno = lineno;
3890}
3891
drhb29b0a52002-02-23 19:39:46 +00003892/*
3893** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003894** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3895** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003896*/
drhc75e0162015-09-07 02:23:02 +00003897static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3898 const char *zType = "int";
3899 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003900 if( lwr>=0 ){
3901 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003902 zType = "unsigned char";
3903 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003904 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003905 zType = "unsigned short int";
3906 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003907 }else{
drhc75e0162015-09-07 02:23:02 +00003908 zType = "unsigned int";
3909 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003910 }
3911 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003912 zType = "signed char";
3913 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003914 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003915 zType = "short";
3916 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003917 }
drhc75e0162015-09-07 02:23:02 +00003918 if( pnByte ) *pnByte = nByte;
3919 return zType;
drhb29b0a52002-02-23 19:39:46 +00003920}
3921
drhfdbf9282003-10-21 16:34:41 +00003922/*
3923** Each state contains a set of token transaction and a set of
3924** nonterminal transactions. Each of these sets makes an instance
3925** of the following structure. An array of these structures is used
3926** to order the creation of entries in the yy_action[] table.
3927*/
3928struct axset {
3929 struct state *stp; /* A pointer to a state */
3930 int isTkn; /* True to use tokens. False for non-terminals */
3931 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003932 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003933};
3934
3935/*
3936** Compare to axset structures for sorting purposes
3937*/
3938static int axset_compare(const void *a, const void *b){
3939 struct axset *p1 = (struct axset*)a;
3940 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003941 int c;
3942 c = p2->nAction - p1->nAction;
3943 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003944 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003945 }
3946 assert( c!=0 || p1==p2 );
3947 return c;
drhfdbf9282003-10-21 16:34:41 +00003948}
3949
drhc4dd3fd2008-01-22 01:48:05 +00003950/*
3951** Write text on "out" that describes the rule "rp".
3952*/
3953static void writeRuleText(FILE *out, struct rule *rp){
3954 int j;
3955 fprintf(out,"%s ::=", rp->lhs->name);
3956 for(j=0; j<rp->nrhs; j++){
3957 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003958 if( sp->type!=MULTITERMINAL ){
3959 fprintf(out," %s", sp->name);
3960 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003961 int k;
drh61f92cd2014-01-11 03:06:18 +00003962 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003963 for(k=1; k<sp->nsubsym; k++){
3964 fprintf(out,"|%s",sp->subsym[k]->name);
3965 }
3966 }
3967 }
3968}
3969
3970
drh75897232000-05-29 14:26:00 +00003971/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003972void ReportTable(
3973 struct lemon *lemp,
3974 int mhflag /* Output in makeheaders format if true */
3975){
drh75897232000-05-29 14:26:00 +00003976 FILE *out, *in;
3977 char line[LINESIZE];
3978 int lineno;
3979 struct state *stp;
3980 struct action *ap;
3981 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003982 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003983 int i, j, n, sz;
3984 int szActionType; /* sizeof(YYACTIONTYPE) */
3985 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003986 const char *name;
drh8b582012003-10-21 13:16:03 +00003987 int mnTknOfst, mxTknOfst;
3988 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003989 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003990
3991 in = tplt_open(lemp);
3992 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003993 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003994 if( out==0 ){
3995 fclose(in);
3996 return;
3997 }
3998 lineno = 1;
3999 tplt_xfer(lemp->name,in,out,&lineno);
4000
4001 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00004002 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00004003 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00004004 char *incName = file_makename(lemp, ".h");
4005 fprintf(out,"#include \"%s\"\n", incName); lineno++;
4006 free(incName);
drh75897232000-05-29 14:26:00 +00004007 }
4008 tplt_xfer(lemp->name,in,out,&lineno);
4009
4010 /* Generate #defines for all tokens */
4011 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00004012 const char *prefix;
drh75897232000-05-29 14:26:00 +00004013 fprintf(out,"#if INTERFACE\n"); lineno++;
4014 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4015 else prefix = "";
4016 for(i=1; i<lemp->nterminal; i++){
4017 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4018 lineno++;
4019 }
4020 fprintf(out,"#endif\n"); lineno++;
4021 }
4022 tplt_xfer(lemp->name,in,out,&lineno);
4023
4024 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00004025 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00004026 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00004027 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
4028 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00004029 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00004030 if( lemp->wildcard ){
4031 fprintf(out,"#define YYWILDCARD %d\n",
4032 lemp->wildcard->index); lineno++;
4033 }
drh75897232000-05-29 14:26:00 +00004034 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00004035 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004036 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00004037 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
4038 }else{
4039 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
4040 }
drhca44b5a2007-02-22 23:06:58 +00004041 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004042 if( mhflag ){
4043 fprintf(out,"#if INTERFACE\n"); lineno++;
4044 }
4045 name = lemp->name ? lemp->name : "Parse";
4046 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00004047 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00004048 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
4049 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00004050 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
4051 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
4052 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
4053 name,lemp->arg,&lemp->arg[i]); lineno++;
4054 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
4055 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00004056 }else{
drh1f245e42002-03-11 13:55:50 +00004057 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
4058 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
4059 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
4060 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00004061 }
4062 if( mhflag ){
4063 fprintf(out,"#endif\n"); lineno++;
4064 }
drhc4dd3fd2008-01-22 01:48:05 +00004065 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00004066 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
4067 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004068 }
drh0bd1f4e2002-06-06 18:54:39 +00004069 if( lemp->has_fallback ){
4070 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4071 }
drh75897232000-05-29 14:26:00 +00004072
drh3bd48ab2015-09-07 18:23:37 +00004073 /* Compute the action table, but do not output it yet. The action
4074 ** table must be computed before generating the YYNSTATE macro because
4075 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004076 */
drh3bd48ab2015-09-07 18:23:37 +00004077 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004078 if( ax==0 ){
4079 fprintf(stderr,"malloc failed\n");
4080 exit(1);
4081 }
drh3bd48ab2015-09-07 18:23:37 +00004082 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004083 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004084 ax[i*2].stp = stp;
4085 ax[i*2].isTkn = 1;
4086 ax[i*2].nAction = stp->nTknAct;
4087 ax[i*2+1].stp = stp;
4088 ax[i*2+1].isTkn = 0;
4089 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004090 }
drh8b582012003-10-21 13:16:03 +00004091 mxTknOfst = mnTknOfst = 0;
4092 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004093 /* In an effort to minimize the action table size, use the heuristic
4094 ** of placing the largest action sets first */
4095 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4096 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004097 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004098 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004099 stp = ax[i].stp;
4100 if( ax[i].isTkn ){
4101 for(ap=stp->ap; ap; ap=ap->next){
4102 int action;
4103 if( ap->sp->index>=lemp->nterminal ) continue;
4104 action = compute_action(lemp, ap);
4105 if( action<0 ) continue;
4106 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004107 }
drhfdbf9282003-10-21 16:34:41 +00004108 stp->iTknOfst = acttab_insert(pActtab);
4109 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4110 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4111 }else{
4112 for(ap=stp->ap; ap; ap=ap->next){
4113 int action;
4114 if( ap->sp->index<lemp->nterminal ) continue;
4115 if( ap->sp->index==lemp->nsymbol ) continue;
4116 action = compute_action(lemp, ap);
4117 if( action<0 ) continue;
4118 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004119 }
drhfdbf9282003-10-21 16:34:41 +00004120 stp->iNtOfst = acttab_insert(pActtab);
4121 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4122 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004123 }
drh337cd0d2015-09-07 23:40:42 +00004124#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4125 { int jj, nn;
4126 for(jj=nn=0; jj<pActtab->nAction; jj++){
4127 if( pActtab->aAction[jj].action<0 ) nn++;
4128 }
4129 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4130 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4131 ax[i].nAction, pActtab->nAction, nn);
4132 }
4133#endif
drh8b582012003-10-21 13:16:03 +00004134 }
drhfdbf9282003-10-21 16:34:41 +00004135 free(ax);
drh8b582012003-10-21 13:16:03 +00004136
drh3bd48ab2015-09-07 18:23:37 +00004137 /* Finish rendering the constants now that the action table has
4138 ** been computed */
4139 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4140 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004141 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004142 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4143 i = lemp->nstate + lemp->nrule;
4144 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4145 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
4146 i = lemp->nstate + lemp->nrule*2;
4147 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4148 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
4149 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
4150 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
4151 tplt_xfer(lemp->name,in,out,&lineno);
4152
4153 /* Now output the action table and its associates:
4154 **
4155 ** yy_action[] A single table containing all actions.
4156 ** yy_lookahead[] A table containing the lookahead for each entry in
4157 ** yy_action. Used to detect hash collisions.
4158 ** yy_shift_ofst[] For each state, the offset into yy_action for
4159 ** shifting terminals.
4160 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4161 ** shifting non-terminals after a reduce.
4162 ** yy_default[] Default action for each state.
4163 */
4164
drh8b582012003-10-21 13:16:03 +00004165 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004166 lemp->nactiontab = n = acttab_size(pActtab);
4167 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004168 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4169 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004170 for(i=j=0; i<n; i++){
4171 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00004172 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00004173 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004174 fprintf(out, " %4d,", action);
4175 if( j==9 || i==n-1 ){
4176 fprintf(out, "\n"); lineno++;
4177 j = 0;
4178 }else{
4179 j++;
4180 }
4181 }
4182 fprintf(out, "};\n"); lineno++;
4183
4184 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004185 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004186 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004187 for(i=j=0; i<n; i++){
4188 int la = acttab_yylookahead(pActtab, i);
4189 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004190 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004191 fprintf(out, " %4d,", la);
4192 if( j==9 || i==n-1 ){
4193 fprintf(out, "\n"); lineno++;
4194 j = 0;
4195 }else{
4196 j++;
4197 }
4198 }
4199 fprintf(out, "};\n"); lineno++;
4200
4201 /* Output the yy_shift_ofst[] table */
4202 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004203 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004204 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004205 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4206 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4207 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004208 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004209 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4210 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004211 for(i=j=0; i<n; i++){
4212 int ofst;
4213 stp = lemp->sorted[i];
4214 ofst = stp->iTknOfst;
4215 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004216 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004217 fprintf(out, " %4d,", ofst);
4218 if( j==9 || i==n-1 ){
4219 fprintf(out, "\n"); lineno++;
4220 j = 0;
4221 }else{
4222 j++;
4223 }
4224 }
4225 fprintf(out, "};\n"); lineno++;
4226
4227 /* Output the yy_reduce_ofst[] table */
4228 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004229 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004230 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004231 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4232 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4233 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004234 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004235 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4236 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004237 for(i=j=0; i<n; i++){
4238 int ofst;
4239 stp = lemp->sorted[i];
4240 ofst = stp->iNtOfst;
4241 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004242 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004243 fprintf(out, " %4d,", ofst);
4244 if( j==9 || i==n-1 ){
4245 fprintf(out, "\n"); lineno++;
4246 j = 0;
4247 }else{
4248 j++;
4249 }
4250 }
4251 fprintf(out, "};\n"); lineno++;
4252
4253 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004254 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004255 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004256 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004257 for(i=j=0; i<n; i++){
4258 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004259 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004260 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004261 if( j==9 || i==n-1 ){
4262 fprintf(out, "\n"); lineno++;
4263 j = 0;
4264 }else{
4265 j++;
4266 }
4267 }
4268 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004269 tplt_xfer(lemp->name,in,out,&lineno);
4270
drh0bd1f4e2002-06-06 18:54:39 +00004271 /* Generate the table of fallback tokens.
4272 */
4273 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004274 int mx = lemp->nterminal - 1;
4275 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004276 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004277 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004278 struct symbol *p = lemp->symbols[i];
4279 if( p->fallback==0 ){
4280 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4281 }else{
4282 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4283 p->name, p->fallback->name);
4284 }
4285 lineno++;
4286 }
4287 }
4288 tplt_xfer(lemp->name, in, out, &lineno);
4289
4290 /* Generate a table containing the symbolic name of every symbol
4291 */
drh75897232000-05-29 14:26:00 +00004292 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004293 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004294 fprintf(out," %-15s",line);
4295 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4296 }
4297 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4298 tplt_xfer(lemp->name,in,out,&lineno);
4299
drh0bd1f4e2002-06-06 18:54:39 +00004300 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004301 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004302 ** when tracing REDUCE actions.
4303 */
4304 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
drh4ef07702016-03-16 19:45:54 +00004305 assert( rp->iRule==i );
drhc4dd3fd2008-01-22 01:48:05 +00004306 fprintf(out," /* %3d */ \"", i);
4307 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004308 fprintf(out,"\",\n"); lineno++;
4309 }
4310 tplt_xfer(lemp->name,in,out,&lineno);
4311
drh75897232000-05-29 14:26:00 +00004312 /* Generate code which executes every time a symbol is popped from
4313 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004314 ** (In other words, generate the %destructor actions)
4315 */
drh75897232000-05-29 14:26:00 +00004316 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004317 int once = 1;
drh75897232000-05-29 14:26:00 +00004318 for(i=0; i<lemp->nsymbol; i++){
4319 struct symbol *sp = lemp->symbols[i];
4320 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004321 if( once ){
4322 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4323 once = 0;
4324 }
drhc53eed12009-06-12 17:46:19 +00004325 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004326 }
4327 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4328 if( i<lemp->nsymbol ){
4329 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4330 fprintf(out," break;\n"); lineno++;
4331 }
4332 }
drh8d659732005-01-13 23:54:06 +00004333 if( lemp->vardest ){
4334 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004335 int once = 1;
drh8d659732005-01-13 23:54:06 +00004336 for(i=0; i<lemp->nsymbol; i++){
4337 struct symbol *sp = lemp->symbols[i];
4338 if( sp==0 || sp->type==TERMINAL ||
4339 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004340 if( once ){
4341 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4342 once = 0;
4343 }
drhc53eed12009-06-12 17:46:19 +00004344 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004345 dflt_sp = sp;
4346 }
4347 if( dflt_sp!=0 ){
4348 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004349 }
drh4dc8ef52008-07-01 17:13:57 +00004350 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004351 }
drh75897232000-05-29 14:26:00 +00004352 for(i=0; i<lemp->nsymbol; i++){
4353 struct symbol *sp = lemp->symbols[i];
4354 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004355 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004356
4357 /* Combine duplicate destructors into a single case */
4358 for(j=i+1; j<lemp->nsymbol; j++){
4359 struct symbol *sp2 = lemp->symbols[j];
4360 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4361 && sp2->dtnum==sp->dtnum
4362 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004363 fprintf(out," case %d: /* %s */\n",
4364 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004365 sp2->destructor = 0;
4366 }
4367 }
4368
drh75897232000-05-29 14:26:00 +00004369 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4370 fprintf(out," break;\n"); lineno++;
4371 }
drh75897232000-05-29 14:26:00 +00004372 tplt_xfer(lemp->name,in,out,&lineno);
4373
4374 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004375 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004376 tplt_xfer(lemp->name,in,out,&lineno);
4377
4378 /* Generate the table of rule information
4379 **
4380 ** Note: This code depends on the fact that rules are number
4381 ** sequentually beginning with 0.
4382 */
4383 for(rp=lemp->rule; rp; rp=rp->next){
4384 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4385 }
4386 tplt_xfer(lemp->name,in,out,&lineno);
4387
4388 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004389 i = 0;
drh75897232000-05-29 14:26:00 +00004390 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004391 i += translate_code(lemp, rp);
4392 }
4393 if( i ){
4394 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004395 }
drhc53eed12009-06-12 17:46:19 +00004396 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004397 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004398 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004399 if( rp->code==0 ) continue;
drh2e55b042016-04-30 17:19:30 +00004400 if( rp->code[0]=='\n'
4401 && rp->code[1]==0
4402 && rp->codePrefix==0
4403 && rp->codeSuffix==0
4404 ){
4405 /* No actions, so this will be part of the "default:" rule */
4406 continue;
4407 }
drh4ef07702016-03-16 19:45:54 +00004408 fprintf(out," case %d: /* ", rp->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004409 writeRuleText(out, rp);
4410 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004411 for(rp2=rp->next; rp2; rp2=rp2->next){
drhafb8cd92016-04-29 11:28:35 +00004412 if( rp2->code==rp->code && rp2->codePrefix==rp->codePrefix
4413 && rp2->codeSuffix==rp->codeSuffix ){
drh4ef07702016-03-16 19:45:54 +00004414 fprintf(out," case %d: /* ", rp2->iRule);
drhc4dd3fd2008-01-22 01:48:05 +00004415 writeRuleText(out, rp2);
drh4ef07702016-03-16 19:45:54 +00004416 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->iRule); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004417 rp2->code = 0;
4418 }
4419 }
drh75897232000-05-29 14:26:00 +00004420 emit_code(out,rp,lemp,&lineno);
4421 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004422 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004423 }
drhc53eed12009-06-12 17:46:19 +00004424 /* Finally, output the default: rule. We choose as the default: all
4425 ** empty actions. */
4426 fprintf(out," default:\n"); lineno++;
4427 for(rp=lemp->rule; rp; rp=rp->next){
4428 if( rp->code==0 ) continue;
4429 assert( rp->code[0]=='\n' && rp->code[1]==0 );
drh2e55b042016-04-30 17:19:30 +00004430 assert( rp->codePrefix==0 );
4431 assert( rp->codeSuffix==0 );
drh4ef07702016-03-16 19:45:54 +00004432 fprintf(out," /* (%d) ", rp->iRule);
drhc53eed12009-06-12 17:46:19 +00004433 writeRuleText(out, rp);
drh4ef07702016-03-16 19:45:54 +00004434 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->iRule); lineno++;
drhc53eed12009-06-12 17:46:19 +00004435 }
4436 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004437 tplt_xfer(lemp->name,in,out,&lineno);
4438
4439 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004440 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004441 tplt_xfer(lemp->name,in,out,&lineno);
4442
4443 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004444 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004445 tplt_xfer(lemp->name,in,out,&lineno);
4446
4447 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004448 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004449 tplt_xfer(lemp->name,in,out,&lineno);
4450
4451 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004452 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004453
4454 fclose(in);
4455 fclose(out);
4456 return;
4457}
4458
4459/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004460void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004461{
4462 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004463 const char *prefix;
drh75897232000-05-29 14:26:00 +00004464 char line[LINESIZE];
4465 char pattern[LINESIZE];
4466 int i;
4467
4468 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4469 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004470 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004471 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004472 int nextChar;
drh75897232000-05-29 14:26:00 +00004473 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004474 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4475 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004476 if( strcmp(line,pattern) ) break;
4477 }
drh8ba0d1c2012-06-16 15:26:31 +00004478 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004479 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004480 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004481 /* No change in the file. Don't rewrite it. */
4482 return;
4483 }
4484 }
drh2aa6ca42004-09-10 00:14:04 +00004485 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004486 if( out ){
4487 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004488 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004489 }
4490 fclose(out);
4491 }
4492 return;
4493}
4494
4495/* Reduce the size of the action tables, if possible, by making use
4496** of defaults.
4497**
drhb59499c2002-02-23 18:45:13 +00004498** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004499** it the default. Except, there is no default if the wildcard token
4500** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004501*/
icculus9e44cf12010-02-14 17:14:22 +00004502void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004503{
4504 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004505 struct action *ap, *ap2;
4506 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004507 int nbest, n;
drh75897232000-05-29 14:26:00 +00004508 int i;
drhe09daa92006-06-10 13:29:31 +00004509 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004510
4511 for(i=0; i<lemp->nstate; i++){
4512 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004513 nbest = 0;
4514 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004515 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004516
drhb59499c2002-02-23 18:45:13 +00004517 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004518 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4519 usesWildcard = 1;
4520 }
drhb59499c2002-02-23 18:45:13 +00004521 if( ap->type!=REDUCE ) continue;
4522 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004523 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004524 if( rp==rbest ) continue;
4525 n = 1;
4526 for(ap2=ap->next; ap2; ap2=ap2->next){
4527 if( ap2->type!=REDUCE ) continue;
4528 rp2 = ap2->x.rp;
4529 if( rp2==rbest ) continue;
4530 if( rp2==rp ) n++;
4531 }
4532 if( n>nbest ){
4533 nbest = n;
4534 rbest = rp;
drh75897232000-05-29 14:26:00 +00004535 }
4536 }
drhb59499c2002-02-23 18:45:13 +00004537
4538 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004539 ** is not at least 1 or if the wildcard token is a possible
4540 ** lookahead.
4541 */
4542 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004543
drhb59499c2002-02-23 18:45:13 +00004544
4545 /* Combine matching REDUCE actions into a single default */
4546 for(ap=stp->ap; ap; ap=ap->next){
4547 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4548 }
drh75897232000-05-29 14:26:00 +00004549 assert( ap );
4550 ap->sp = Symbol_new("{default}");
4551 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004552 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004553 }
4554 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004555
4556 for(ap=stp->ap; ap; ap=ap->next){
4557 if( ap->type==SHIFT ) break;
4558 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4559 }
4560 if( ap==0 ){
4561 stp->autoReduce = 1;
4562 stp->pDfltReduce = rbest;
4563 }
4564 }
4565
4566 /* Make a second pass over all states and actions. Convert
4567 ** every action that is a SHIFT to an autoReduce state into
4568 ** a SHIFTREDUCE action.
4569 */
4570 for(i=0; i<lemp->nstate; i++){
4571 stp = lemp->sorted[i];
4572 for(ap=stp->ap; ap; ap=ap->next){
4573 struct state *pNextState;
4574 if( ap->type!=SHIFT ) continue;
4575 pNextState = ap->x.stp;
4576 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4577 ap->type = SHIFTREDUCE;
4578 ap->x.rp = pNextState->pDfltReduce;
4579 }
4580 }
drh75897232000-05-29 14:26:00 +00004581 }
4582}
drhb59499c2002-02-23 18:45:13 +00004583
drhada354d2005-11-05 15:03:59 +00004584
4585/*
4586** Compare two states for sorting purposes. The smaller state is the
4587** one with the most non-terminal actions. If they have the same number
4588** of non-terminal actions, then the smaller is the one with the most
4589** token actions.
4590*/
4591static int stateResortCompare(const void *a, const void *b){
4592 const struct state *pA = *(const struct state**)a;
4593 const struct state *pB = *(const struct state**)b;
4594 int n;
4595
4596 n = pB->nNtAct - pA->nNtAct;
4597 if( n==0 ){
4598 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004599 if( n==0 ){
4600 n = pB->statenum - pA->statenum;
4601 }
drhada354d2005-11-05 15:03:59 +00004602 }
drhe594bc32009-11-03 13:02:25 +00004603 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004604 return n;
4605}
4606
4607
4608/*
4609** Renumber and resort states so that states with fewer choices
4610** occur at the end. Except, keep state 0 as the first state.
4611*/
icculus9e44cf12010-02-14 17:14:22 +00004612void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004613{
4614 int i;
4615 struct state *stp;
4616 struct action *ap;
4617
4618 for(i=0; i<lemp->nstate; i++){
4619 stp = lemp->sorted[i];
4620 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004621 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004622 stp->iTknOfst = NO_OFFSET;
4623 stp->iNtOfst = NO_OFFSET;
4624 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004625 int iAction = compute_action(lemp,ap);
4626 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004627 if( ap->sp->index<lemp->nterminal ){
4628 stp->nTknAct++;
4629 }else if( ap->sp->index<lemp->nsymbol ){
4630 stp->nNtAct++;
4631 }else{
drh3bd48ab2015-09-07 18:23:37 +00004632 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4633 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004634 }
4635 }
4636 }
4637 }
4638 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4639 stateResortCompare);
4640 for(i=0; i<lemp->nstate; i++){
4641 lemp->sorted[i]->statenum = i;
4642 }
drh3bd48ab2015-09-07 18:23:37 +00004643 lemp->nxstate = lemp->nstate;
4644 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4645 lemp->nxstate--;
4646 }
drhada354d2005-11-05 15:03:59 +00004647}
4648
4649
drh75897232000-05-29 14:26:00 +00004650/***************** From the file "set.c" ************************************/
4651/*
4652** Set manipulation routines for the LEMON parser generator.
4653*/
4654
4655static int size = 0;
4656
4657/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004658void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004659{
4660 size = n+1;
4661}
4662
4663/* Allocate a new set */
4664char *SetNew(){
4665 char *s;
drh9892c5d2007-12-21 00:02:11 +00004666 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004667 if( s==0 ){
4668 extern void memory_error();
4669 memory_error();
4670 }
drh75897232000-05-29 14:26:00 +00004671 return s;
4672}
4673
4674/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004675void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004676{
4677 free(s);
4678}
4679
4680/* Add a new element to the set. Return TRUE if the element was added
4681** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004682int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004683{
4684 int rv;
drh9892c5d2007-12-21 00:02:11 +00004685 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004686 rv = s[e];
4687 s[e] = 1;
4688 return !rv;
4689}
4690
4691/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004692int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004693{
4694 int i, progress;
4695 progress = 0;
4696 for(i=0; i<size; i++){
4697 if( s2[i]==0 ) continue;
4698 if( s1[i]==0 ){
4699 progress = 1;
4700 s1[i] = 1;
4701 }
4702 }
4703 return progress;
4704}
4705/********************** From the file "table.c" ****************************/
4706/*
4707** All code in this file has been automatically generated
4708** from a specification in the file
4709** "table.q"
4710** by the associative array code building program "aagen".
4711** Do not edit this file! Instead, edit the specification
4712** file, then rerun aagen.
4713*/
4714/*
4715** Code for processing tables in the LEMON parser generator.
4716*/
4717
drh01f75f22013-10-02 20:46:30 +00004718PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004719{
drh01f75f22013-10-02 20:46:30 +00004720 unsigned h = 0;
4721 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004722 return h;
4723}
4724
4725/* Works like strdup, sort of. Save a string in malloced memory, but
4726** keep strings in a table so that the same string is not in more
4727** than one place.
4728*/
icculus9e44cf12010-02-14 17:14:22 +00004729const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004730{
icculus9e44cf12010-02-14 17:14:22 +00004731 const char *z;
4732 char *cpy;
drh75897232000-05-29 14:26:00 +00004733
drh916f75f2006-07-17 00:19:39 +00004734 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004735 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004736 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004737 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004738 z = cpy;
drh75897232000-05-29 14:26:00 +00004739 Strsafe_insert(z);
4740 }
4741 MemoryCheck(z);
4742 return z;
4743}
4744
4745/* There is one instance of the following structure for each
4746** associative array of type "x1".
4747*/
4748struct s_x1 {
4749 int size; /* The number of available slots. */
4750 /* Must be a power of 2 greater than or */
4751 /* equal to 1 */
4752 int count; /* Number of currently slots filled */
4753 struct s_x1node *tbl; /* The data stored here */
4754 struct s_x1node **ht; /* Hash table for lookups */
4755};
4756
4757/* There is one instance of this structure for every data element
4758** in an associative array of type "x1".
4759*/
4760typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004761 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004762 struct s_x1node *next; /* Next entry with the same hash */
4763 struct s_x1node **from; /* Previous link */
4764} x1node;
4765
4766/* There is only one instance of the array, which is the following */
4767static struct s_x1 *x1a;
4768
4769/* Allocate a new associative array */
4770void Strsafe_init(){
4771 if( x1a ) return;
4772 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4773 if( x1a ){
4774 x1a->size = 1024;
4775 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004776 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004777 if( x1a->tbl==0 ){
4778 free(x1a);
4779 x1a = 0;
4780 }else{
4781 int i;
4782 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4783 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4784 }
4785 }
4786}
4787/* Insert a new record into the array. Return TRUE if successful.
4788** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004789int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004790{
4791 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004792 unsigned h;
4793 unsigned ph;
drh75897232000-05-29 14:26:00 +00004794
4795 if( x1a==0 ) return 0;
4796 ph = strhash(data);
4797 h = ph & (x1a->size-1);
4798 np = x1a->ht[h];
4799 while( np ){
4800 if( strcmp(np->data,data)==0 ){
4801 /* An existing entry with the same key is found. */
4802 /* Fail because overwrite is not allows. */
4803 return 0;
4804 }
4805 np = np->next;
4806 }
4807 if( x1a->count>=x1a->size ){
4808 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004809 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004810 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004811 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004812 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004813 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004814 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004815 array.ht = (x1node**)&(array.tbl[arrSize]);
4816 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004817 for(i=0; i<x1a->count; i++){
4818 x1node *oldnp, *newnp;
4819 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004820 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004821 newnp = &(array.tbl[i]);
4822 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4823 newnp->next = array.ht[h];
4824 newnp->data = oldnp->data;
4825 newnp->from = &(array.ht[h]);
4826 array.ht[h] = newnp;
4827 }
4828 free(x1a->tbl);
4829 *x1a = array;
4830 }
4831 /* Insert the new data */
4832 h = ph & (x1a->size-1);
4833 np = &(x1a->tbl[x1a->count++]);
4834 np->data = data;
4835 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4836 np->next = x1a->ht[h];
4837 x1a->ht[h] = np;
4838 np->from = &(x1a->ht[h]);
4839 return 1;
4840}
4841
4842/* Return a pointer to data assigned to the given key. Return NULL
4843** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004844const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004845{
drh01f75f22013-10-02 20:46:30 +00004846 unsigned h;
drh75897232000-05-29 14:26:00 +00004847 x1node *np;
4848
4849 if( x1a==0 ) return 0;
4850 h = strhash(key) & (x1a->size-1);
4851 np = x1a->ht[h];
4852 while( np ){
4853 if( strcmp(np->data,key)==0 ) break;
4854 np = np->next;
4855 }
4856 return np ? np->data : 0;
4857}
4858
4859/* Return a pointer to the (terminal or nonterminal) symbol "x".
4860** Create a new symbol if this is the first time "x" has been seen.
4861*/
icculus9e44cf12010-02-14 17:14:22 +00004862struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004863{
4864 struct symbol *sp;
4865
4866 sp = Symbol_find(x);
4867 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004868 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004869 MemoryCheck(sp);
4870 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004871 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004872 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004873 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004874 sp->prec = -1;
4875 sp->assoc = UNK;
4876 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004877 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004878 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004879 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004880 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004881 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004882 Symbol_insert(sp,sp->name);
4883 }
drhc4dd3fd2008-01-22 01:48:05 +00004884 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004885 return sp;
4886}
4887
drh61f92cd2014-01-11 03:06:18 +00004888/* Compare two symbols for sorting purposes. Return negative,
4889** zero, or positive if a is less then, equal to, or greater
4890** than b.
drh60d31652004-02-22 00:08:04 +00004891**
4892** Symbols that begin with upper case letters (terminals or tokens)
4893** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004894** (non-terminals). And MULTITERMINAL symbols (created using the
4895** %token_class directive) must sort at the very end. Other than
4896** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004897**
4898** We find experimentally that leaving the symbols in their original
4899** order (the order they appeared in the grammar file) gives the
4900** smallest parser tables in SQLite.
4901*/
icculus9e44cf12010-02-14 17:14:22 +00004902int Symbolcmpp(const void *_a, const void *_b)
4903{
drh61f92cd2014-01-11 03:06:18 +00004904 const struct symbol *a = *(const struct symbol **) _a;
4905 const struct symbol *b = *(const struct symbol **) _b;
4906 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4907 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4908 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004909}
4910
4911/* There is one instance of the following structure for each
4912** associative array of type "x2".
4913*/
4914struct s_x2 {
4915 int size; /* The number of available slots. */
4916 /* Must be a power of 2 greater than or */
4917 /* equal to 1 */
4918 int count; /* Number of currently slots filled */
4919 struct s_x2node *tbl; /* The data stored here */
4920 struct s_x2node **ht; /* Hash table for lookups */
4921};
4922
4923/* There is one instance of this structure for every data element
4924** in an associative array of type "x2".
4925*/
4926typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004927 struct symbol *data; /* The data */
4928 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004929 struct s_x2node *next; /* Next entry with the same hash */
4930 struct s_x2node **from; /* Previous link */
4931} x2node;
4932
4933/* There is only one instance of the array, which is the following */
4934static struct s_x2 *x2a;
4935
4936/* Allocate a new associative array */
4937void Symbol_init(){
4938 if( x2a ) return;
4939 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4940 if( x2a ){
4941 x2a->size = 128;
4942 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004943 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004944 if( x2a->tbl==0 ){
4945 free(x2a);
4946 x2a = 0;
4947 }else{
4948 int i;
4949 x2a->ht = (x2node**)&(x2a->tbl[128]);
4950 for(i=0; i<128; i++) x2a->ht[i] = 0;
4951 }
4952 }
4953}
4954/* Insert a new record into the array. Return TRUE if successful.
4955** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004956int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004957{
4958 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004959 unsigned h;
4960 unsigned ph;
drh75897232000-05-29 14:26:00 +00004961
4962 if( x2a==0 ) return 0;
4963 ph = strhash(key);
4964 h = ph & (x2a->size-1);
4965 np = x2a->ht[h];
4966 while( np ){
4967 if( strcmp(np->key,key)==0 ){
4968 /* An existing entry with the same key is found. */
4969 /* Fail because overwrite is not allows. */
4970 return 0;
4971 }
4972 np = np->next;
4973 }
4974 if( x2a->count>=x2a->size ){
4975 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004976 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004977 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004978 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004979 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004980 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004981 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004982 array.ht = (x2node**)&(array.tbl[arrSize]);
4983 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004984 for(i=0; i<x2a->count; i++){
4985 x2node *oldnp, *newnp;
4986 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004987 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004988 newnp = &(array.tbl[i]);
4989 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4990 newnp->next = array.ht[h];
4991 newnp->key = oldnp->key;
4992 newnp->data = oldnp->data;
4993 newnp->from = &(array.ht[h]);
4994 array.ht[h] = newnp;
4995 }
4996 free(x2a->tbl);
4997 *x2a = array;
4998 }
4999 /* Insert the new data */
5000 h = ph & (x2a->size-1);
5001 np = &(x2a->tbl[x2a->count++]);
5002 np->key = key;
5003 np->data = data;
5004 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
5005 np->next = x2a->ht[h];
5006 x2a->ht[h] = np;
5007 np->from = &(x2a->ht[h]);
5008 return 1;
5009}
5010
5011/* Return a pointer to data assigned to the given key. Return NULL
5012** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005013struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00005014{
drh01f75f22013-10-02 20:46:30 +00005015 unsigned h;
drh75897232000-05-29 14:26:00 +00005016 x2node *np;
5017
5018 if( x2a==0 ) return 0;
5019 h = strhash(key) & (x2a->size-1);
5020 np = x2a->ht[h];
5021 while( np ){
5022 if( strcmp(np->key,key)==0 ) break;
5023 np = np->next;
5024 }
5025 return np ? np->data : 0;
5026}
5027
5028/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00005029struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00005030{
5031 struct symbol *data;
5032 if( x2a && n>0 && n<=x2a->count ){
5033 data = x2a->tbl[n-1].data;
5034 }else{
5035 data = 0;
5036 }
5037 return data;
5038}
5039
5040/* Return the size of the array */
5041int Symbol_count()
5042{
5043 return x2a ? x2a->count : 0;
5044}
5045
5046/* Return an array of pointers to all data in the table.
5047** The array is obtained from malloc. Return NULL if memory allocation
5048** problems, or if the array is empty. */
5049struct symbol **Symbol_arrayof()
5050{
5051 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00005052 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005053 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005054 arrSize = x2a->count;
5055 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00005056 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005057 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005058 }
5059 return array;
5060}
5061
5062/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00005063int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00005064{
icculus9e44cf12010-02-14 17:14:22 +00005065 const struct config *a = (struct config *) _a;
5066 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00005067 int x;
5068 x = a->rp->index - b->rp->index;
5069 if( x==0 ) x = a->dot - b->dot;
5070 return x;
5071}
5072
5073/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00005074PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00005075{
5076 int rc;
5077 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5078 rc = a->rp->index - b->rp->index;
5079 if( rc==0 ) rc = a->dot - b->dot;
5080 }
5081 if( rc==0 ){
5082 if( a ) rc = 1;
5083 if( b ) rc = -1;
5084 }
5085 return rc;
5086}
5087
5088/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005089PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005090{
drh01f75f22013-10-02 20:46:30 +00005091 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005092 while( a ){
5093 h = h*571 + a->rp->index*37 + a->dot;
5094 a = a->bp;
5095 }
5096 return h;
5097}
5098
5099/* Allocate a new state structure */
5100struct state *State_new()
5101{
icculus9e44cf12010-02-14 17:14:22 +00005102 struct state *newstate;
5103 newstate = (struct state *)calloc(1, sizeof(struct state) );
5104 MemoryCheck(newstate);
5105 return newstate;
drh75897232000-05-29 14:26:00 +00005106}
5107
5108/* There is one instance of the following structure for each
5109** associative array of type "x3".
5110*/
5111struct s_x3 {
5112 int size; /* The number of available slots. */
5113 /* Must be a power of 2 greater than or */
5114 /* equal to 1 */
5115 int count; /* Number of currently slots filled */
5116 struct s_x3node *tbl; /* The data stored here */
5117 struct s_x3node **ht; /* Hash table for lookups */
5118};
5119
5120/* There is one instance of this structure for every data element
5121** in an associative array of type "x3".
5122*/
5123typedef struct s_x3node {
5124 struct state *data; /* The data */
5125 struct config *key; /* The key */
5126 struct s_x3node *next; /* Next entry with the same hash */
5127 struct s_x3node **from; /* Previous link */
5128} x3node;
5129
5130/* There is only one instance of the array, which is the following */
5131static struct s_x3 *x3a;
5132
5133/* Allocate a new associative array */
5134void State_init(){
5135 if( x3a ) return;
5136 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5137 if( x3a ){
5138 x3a->size = 128;
5139 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005140 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005141 if( x3a->tbl==0 ){
5142 free(x3a);
5143 x3a = 0;
5144 }else{
5145 int i;
5146 x3a->ht = (x3node**)&(x3a->tbl[128]);
5147 for(i=0; i<128; i++) x3a->ht[i] = 0;
5148 }
5149 }
5150}
5151/* Insert a new record into the array. Return TRUE if successful.
5152** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005153int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005154{
5155 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005156 unsigned h;
5157 unsigned ph;
drh75897232000-05-29 14:26:00 +00005158
5159 if( x3a==0 ) return 0;
5160 ph = statehash(key);
5161 h = ph & (x3a->size-1);
5162 np = x3a->ht[h];
5163 while( np ){
5164 if( statecmp(np->key,key)==0 ){
5165 /* An existing entry with the same key is found. */
5166 /* Fail because overwrite is not allows. */
5167 return 0;
5168 }
5169 np = np->next;
5170 }
5171 if( x3a->count>=x3a->size ){
5172 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005173 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005174 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005175 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005176 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005177 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005178 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005179 array.ht = (x3node**)&(array.tbl[arrSize]);
5180 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005181 for(i=0; i<x3a->count; i++){
5182 x3node *oldnp, *newnp;
5183 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005184 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005185 newnp = &(array.tbl[i]);
5186 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5187 newnp->next = array.ht[h];
5188 newnp->key = oldnp->key;
5189 newnp->data = oldnp->data;
5190 newnp->from = &(array.ht[h]);
5191 array.ht[h] = newnp;
5192 }
5193 free(x3a->tbl);
5194 *x3a = array;
5195 }
5196 /* Insert the new data */
5197 h = ph & (x3a->size-1);
5198 np = &(x3a->tbl[x3a->count++]);
5199 np->key = key;
5200 np->data = data;
5201 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5202 np->next = x3a->ht[h];
5203 x3a->ht[h] = np;
5204 np->from = &(x3a->ht[h]);
5205 return 1;
5206}
5207
5208/* Return a pointer to data assigned to the given key. Return NULL
5209** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005210struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005211{
drh01f75f22013-10-02 20:46:30 +00005212 unsigned h;
drh75897232000-05-29 14:26:00 +00005213 x3node *np;
5214
5215 if( x3a==0 ) return 0;
5216 h = statehash(key) & (x3a->size-1);
5217 np = x3a->ht[h];
5218 while( np ){
5219 if( statecmp(np->key,key)==0 ) break;
5220 np = np->next;
5221 }
5222 return np ? np->data : 0;
5223}
5224
5225/* Return an array of pointers to all data in the table.
5226** The array is obtained from malloc. Return NULL if memory allocation
5227** problems, or if the array is empty. */
5228struct state **State_arrayof()
5229{
5230 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005231 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005232 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005233 arrSize = x3a->count;
5234 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005235 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005236 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005237 }
5238 return array;
5239}
5240
5241/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005242PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005243{
drh01f75f22013-10-02 20:46:30 +00005244 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005245 h = h*571 + a->rp->index*37 + a->dot;
5246 return h;
5247}
5248
5249/* There is one instance of the following structure for each
5250** associative array of type "x4".
5251*/
5252struct s_x4 {
5253 int size; /* The number of available slots. */
5254 /* Must be a power of 2 greater than or */
5255 /* equal to 1 */
5256 int count; /* Number of currently slots filled */
5257 struct s_x4node *tbl; /* The data stored here */
5258 struct s_x4node **ht; /* Hash table for lookups */
5259};
5260
5261/* There is one instance of this structure for every data element
5262** in an associative array of type "x4".
5263*/
5264typedef struct s_x4node {
5265 struct config *data; /* The data */
5266 struct s_x4node *next; /* Next entry with the same hash */
5267 struct s_x4node **from; /* Previous link */
5268} x4node;
5269
5270/* There is only one instance of the array, which is the following */
5271static struct s_x4 *x4a;
5272
5273/* Allocate a new associative array */
5274void Configtable_init(){
5275 if( x4a ) return;
5276 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5277 if( x4a ){
5278 x4a->size = 64;
5279 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005280 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005281 if( x4a->tbl==0 ){
5282 free(x4a);
5283 x4a = 0;
5284 }else{
5285 int i;
5286 x4a->ht = (x4node**)&(x4a->tbl[64]);
5287 for(i=0; i<64; i++) x4a->ht[i] = 0;
5288 }
5289 }
5290}
5291/* Insert a new record into the array. Return TRUE if successful.
5292** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005293int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005294{
5295 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005296 unsigned h;
5297 unsigned ph;
drh75897232000-05-29 14:26:00 +00005298
5299 if( x4a==0 ) return 0;
5300 ph = confighash(data);
5301 h = ph & (x4a->size-1);
5302 np = x4a->ht[h];
5303 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005304 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005305 /* An existing entry with the same key is found. */
5306 /* Fail because overwrite is not allows. */
5307 return 0;
5308 }
5309 np = np->next;
5310 }
5311 if( x4a->count>=x4a->size ){
5312 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005313 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005314 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005315 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005316 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005317 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005318 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005319 array.ht = (x4node**)&(array.tbl[arrSize]);
5320 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005321 for(i=0; i<x4a->count; i++){
5322 x4node *oldnp, *newnp;
5323 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005324 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005325 newnp = &(array.tbl[i]);
5326 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5327 newnp->next = array.ht[h];
5328 newnp->data = oldnp->data;
5329 newnp->from = &(array.ht[h]);
5330 array.ht[h] = newnp;
5331 }
5332 free(x4a->tbl);
5333 *x4a = array;
5334 }
5335 /* Insert the new data */
5336 h = ph & (x4a->size-1);
5337 np = &(x4a->tbl[x4a->count++]);
5338 np->data = data;
5339 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5340 np->next = x4a->ht[h];
5341 x4a->ht[h] = np;
5342 np->from = &(x4a->ht[h]);
5343 return 1;
5344}
5345
5346/* Return a pointer to data assigned to the given key. Return NULL
5347** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005348struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005349{
5350 int h;
5351 x4node *np;
5352
5353 if( x4a==0 ) return 0;
5354 h = confighash(key) & (x4a->size-1);
5355 np = x4a->ht[h];
5356 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005357 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005358 np = np->next;
5359 }
5360 return np ? np->data : 0;
5361}
5362
5363/* Remove all data from the table. Pass each data to the function "f"
5364** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005365void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005366{
5367 int i;
5368 if( x4a==0 || x4a->count==0 ) return;
5369 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5370 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5371 x4a->count = 0;
5372 return;
5373}