blob: 1058d14ae6354c9b0e9e76625140e6a1f07f38c4 [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 */
293 Boolean canReduce; /* True if this rule is ever reduced */
294 struct rule *nextlhs; /* Next rule with the same LHS */
295 struct rule *next; /* Next rule in the global list */
296};
297
298/* A configuration is a production rule of the grammar together with
299** a mark (dot) showing how much of that rule has been processed so far.
300** Configurations also contain a follow-set which is a list of terminal
301** symbols which are allowed to immediately follow the end of the rule.
302** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000303enum cfgstatus {
304 COMPLETE,
305 INCOMPLETE
306};
drh75897232000-05-29 14:26:00 +0000307struct config {
308 struct rule *rp; /* The rule upon which the configuration is based */
309 int dot; /* The parse point */
310 char *fws; /* Follow-set for this configuration only */
311 struct plink *fplp; /* Follow-set forward propagation links */
312 struct plink *bplp; /* Follow-set backwards propagation links */
313 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000314 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000315 struct config *next; /* Next configuration in the state */
316 struct config *bp; /* The next basis configuration */
317};
318
icculus9e44cf12010-02-14 17:14:22 +0000319enum e_action {
320 SHIFT,
321 ACCEPT,
322 REDUCE,
323 ERROR,
324 SSCONFLICT, /* A shift/shift conflict */
325 SRCONFLICT, /* Was a reduce, but part of a conflict */
326 RRCONFLICT, /* Was a reduce, but part of a conflict */
327 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
328 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000329 NOT_USED, /* Deleted by compression */
330 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000331};
332
drh75897232000-05-29 14:26:00 +0000333/* Every shift or reduce operation is stored as one of the following */
334struct action {
335 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000336 enum e_action type;
drh75897232000-05-29 14:26:00 +0000337 union {
338 struct state *stp; /* The new state, if a shift */
339 struct rule *rp; /* The rule, if a reduce */
340 } x;
341 struct action *next; /* Next action for this state */
342 struct action *collide; /* Next action with the same hash */
343};
344
345/* Each state of the generated parser's finite state machine
346** is encoded as an instance of the following structure. */
347struct state {
348 struct config *bp; /* The basis configurations for this state */
349 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000350 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000351 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000352 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
353 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000354 int iDfltReduce; /* Default action is to REDUCE by this rule */
355 struct rule *pDfltReduce;/* The default REDUCE rule. */
356 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000357};
drh8b582012003-10-21 13:16:03 +0000358#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000359
360/* A followset propagation link indicates that the contents of one
361** configuration followset should be propagated to another whenever
362** the first changes. */
363struct plink {
364 struct config *cfp; /* The configuration to which linked */
365 struct plink *next; /* The next propagate link */
366};
367
368/* The state vector for the entire parser generator is recorded as
369** follows. (LEMON uses no global variables and makes little use of
370** static variables. Fields in the following structure can be thought
371** of as begin global variables in the program.) */
372struct lemon {
373 struct state **sorted; /* Table of states sorted by state number */
374 struct rule *rule; /* List of all rules */
375 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000376 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000377 int nrule; /* Number of rules */
378 int nsymbol; /* Number of terminal and nonterminal symbols */
379 int nterminal; /* Number of terminal symbols */
380 struct symbol **symbols; /* Sorted array of pointers to symbols */
381 int errorcnt; /* Number of errors */
382 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000383 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000384 char *name; /* Name of the generated parser */
385 char *arg; /* Declaration of the 3th argument to parser */
386 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000387 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000388 char *start; /* Name of the start symbol for the grammar */
389 char *stacksize; /* Size of the parser stack */
390 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000391 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000392 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000393 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000394 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000395 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000396 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000397 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000398 char *filename; /* Name of the input file */
399 char *outname; /* Name of the current output file */
400 char *tokenprefix; /* A prefix added to token names in the .h file */
401 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000402 int nactiontab; /* Number of entries in the yy_action[] table */
403 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000404 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000405 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000406 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000407 char *argv0; /* Name of the program */
408};
409
410#define MemoryCheck(X) if((X)==0){ \
411 extern void memory_error(); \
412 memory_error(); \
413}
414
415/**************** From the file "table.h" *********************************/
416/*
417** All code in this file has been automatically generated
418** from a specification in the file
419** "table.q"
420** by the associative array code building program "aagen".
421** Do not edit this file! Instead, edit the specification
422** file, then rerun aagen.
423*/
424/*
425** Code for processing tables in the LEMON parser generator.
426*/
drh75897232000-05-29 14:26:00 +0000427/* Routines for handling a strings */
428
icculus9e44cf12010-02-14 17:14:22 +0000429const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000430
icculus9e44cf12010-02-14 17:14:22 +0000431void Strsafe_init(void);
432int Strsafe_insert(const char *);
433const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000434
435/* Routines for handling symbols of the grammar */
436
icculus9e44cf12010-02-14 17:14:22 +0000437struct symbol *Symbol_new(const char *);
438int Symbolcmpp(const void *, const void *);
439void Symbol_init(void);
440int Symbol_insert(struct symbol *, const char *);
441struct symbol *Symbol_find(const char *);
442struct symbol *Symbol_Nth(int);
443int Symbol_count(void);
444struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000445
446/* Routines to manage the state table */
447
icculus9e44cf12010-02-14 17:14:22 +0000448int Configcmp(const char *, const char *);
449struct state *State_new(void);
450void State_init(void);
451int State_insert(struct state *, struct config *);
452struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000453struct state **State_arrayof(/* */);
454
455/* Routines used for efficiency in Configlist_add */
456
icculus9e44cf12010-02-14 17:14:22 +0000457void Configtable_init(void);
458int Configtable_insert(struct config *);
459struct config *Configtable_find(struct config *);
460void Configtable_clear(int(*)(struct config *));
461
drh75897232000-05-29 14:26:00 +0000462/****************** From the file "action.c" *******************************/
463/*
464** Routines processing parser actions in the LEMON parser generator.
465*/
466
467/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000468static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000469 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000470 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000471
472 if( freelist==0 ){
473 int i;
474 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000475 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000476 if( freelist==0 ){
477 fprintf(stderr,"Unable to allocate memory for a new parser action.");
478 exit(1);
479 }
480 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
481 freelist[amt-1].next = 0;
482 }
icculus9e44cf12010-02-14 17:14:22 +0000483 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000484 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000485 return newaction;
drh75897232000-05-29 14:26:00 +0000486}
487
drhe9278182007-07-18 18:16:29 +0000488/* Compare two actions for sorting purposes. Return negative, zero, or
489** positive if the first action is less than, equal to, or greater than
490** the first
491*/
492static int actioncmp(
493 struct action *ap1,
494 struct action *ap2
495){
drh75897232000-05-29 14:26:00 +0000496 int rc;
497 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000498 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000499 rc = (int)ap1->type - (int)ap2->type;
500 }
drh3bd48ab2015-09-07 18:23:37 +0000501 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000502 rc = ap1->x.rp->index - ap2->x.rp->index;
503 }
drhe594bc32009-11-03 13:02:25 +0000504 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000505 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000506 }
drh75897232000-05-29 14:26:00 +0000507 return rc;
508}
509
510/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000511static struct action *Action_sort(
512 struct action *ap
513){
514 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
515 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000516 return ap;
517}
518
icculus9e44cf12010-02-14 17:14:22 +0000519void Action_add(
520 struct action **app,
521 enum e_action type,
522 struct symbol *sp,
523 char *arg
524){
525 struct action *newaction;
526 newaction = Action_new();
527 newaction->next = *app;
528 *app = newaction;
529 newaction->type = type;
530 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000531 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000532 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000533 }else{
icculus9e44cf12010-02-14 17:14:22 +0000534 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000535 }
536}
drh8b582012003-10-21 13:16:03 +0000537/********************** New code to implement the "acttab" module ***********/
538/*
539** This module implements routines use to construct the yy_action[] table.
540*/
541
542/*
543** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000544** the following structure.
545**
546** The yy_action table maps the pair (state_number, lookahead) into an
547** action_number. The table is an array of integers pairs. The state_number
548** determines an initial offset into the yy_action array. The lookahead
549** value is then added to this initial offset to get an index X into the
550** yy_action array. If the aAction[X].lookahead equals the value of the
551** of the lookahead input, then the value of the action_number output is
552** aAction[X].action. If the lookaheads do not match then the
553** default action for the state_number is returned.
554**
555** All actions associated with a single state_number are first entered
556** into aLookahead[] using multiple calls to acttab_action(). Then the
557** actions for that single state_number are placed into the aAction[]
558** array with a single call to acttab_insert(). The acttab_insert() call
559** also resets the aLookahead[] array in preparation for the next
560** state number.
drh8b582012003-10-21 13:16:03 +0000561*/
icculus9e44cf12010-02-14 17:14:22 +0000562struct lookahead_action {
563 int lookahead; /* Value of the lookahead token */
564 int action; /* Action to take on the given lookahead */
565};
drh8b582012003-10-21 13:16:03 +0000566typedef struct acttab acttab;
567struct acttab {
568 int nAction; /* Number of used slots in aAction[] */
569 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000570 struct lookahead_action
571 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000572 *aLookahead; /* A single new transaction set */
573 int mnLookahead; /* Minimum aLookahead[].lookahead */
574 int mnAction; /* Action associated with mnLookahead */
575 int mxLookahead; /* Maximum aLookahead[].lookahead */
576 int nLookahead; /* Used slots in aLookahead[] */
577 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
578};
579
580/* Return the number of entries in the yy_action table */
581#define acttab_size(X) ((X)->nAction)
582
583/* The value for the N-th entry in yy_action */
584#define acttab_yyaction(X,N) ((X)->aAction[N].action)
585
586/* The value for the N-th entry in yy_lookahead */
587#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
588
589/* Free all memory associated with the given acttab */
590void acttab_free(acttab *p){
591 free( p->aAction );
592 free( p->aLookahead );
593 free( p );
594}
595
596/* Allocate a new acttab structure */
597acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000598 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000599 if( p==0 ){
600 fprintf(stderr,"Unable to allocate memory for a new acttab.");
601 exit(1);
602 }
603 memset(p, 0, sizeof(*p));
604 return p;
605}
606
drh8dc3e8f2010-01-07 03:53:03 +0000607/* Add a new action to the current transaction set.
608**
609** This routine is called once for each lookahead for a particular
610** state.
drh8b582012003-10-21 13:16:03 +0000611*/
612void acttab_action(acttab *p, int lookahead, int action){
613 if( p->nLookahead>=p->nLookaheadAlloc ){
614 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000615 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000616 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
617 if( p->aLookahead==0 ){
618 fprintf(stderr,"malloc failed\n");
619 exit(1);
620 }
621 }
622 if( p->nLookahead==0 ){
623 p->mxLookahead = lookahead;
624 p->mnLookahead = lookahead;
625 p->mnAction = action;
626 }else{
627 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
628 if( p->mnLookahead>lookahead ){
629 p->mnLookahead = lookahead;
630 p->mnAction = action;
631 }
632 }
633 p->aLookahead[p->nLookahead].lookahead = lookahead;
634 p->aLookahead[p->nLookahead].action = action;
635 p->nLookahead++;
636}
637
638/*
639** Add the transaction set built up with prior calls to acttab_action()
640** into the current action table. Then reset the transaction set back
641** to an empty set in preparation for a new round of acttab_action() calls.
642**
643** Return the offset into the action table of the new transaction.
644*/
645int acttab_insert(acttab *p){
646 int i, j, k, n;
647 assert( p->nLookahead>0 );
648
649 /* Make sure we have enough space to hold the expanded action table
650 ** in the worst case. The worst case occurs if the transaction set
651 ** must be appended to the current action table
652 */
drh784d86f2004-02-19 18:41:53 +0000653 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000654 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000655 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000656 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000657 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000658 sizeof(p->aAction[0])*p->nActionAlloc);
659 if( p->aAction==0 ){
660 fprintf(stderr,"malloc failed\n");
661 exit(1);
662 }
drhfdbf9282003-10-21 16:34:41 +0000663 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000664 p->aAction[i].lookahead = -1;
665 p->aAction[i].action = -1;
666 }
667 }
668
drh8dc3e8f2010-01-07 03:53:03 +0000669 /* Scan the existing action table looking for an offset that is a
670 ** duplicate of the current transaction set. Fall out of the loop
671 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000672 **
673 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
674 */
drh8dc3e8f2010-01-07 03:53:03 +0000675 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000676 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000677 /* All lookaheads and actions in the aLookahead[] transaction
678 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000679 if( p->aAction[i].action!=p->mnAction ) continue;
680 for(j=0; j<p->nLookahead; j++){
681 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
682 if( k<0 || k>=p->nAction ) break;
683 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
684 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
685 }
686 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000687
688 /* No possible lookahead value that is not in the aLookahead[]
689 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000690 n = 0;
691 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000692 if( p->aAction[j].lookahead<0 ) continue;
693 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000694 }
drhfdbf9282003-10-21 16:34:41 +0000695 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000696 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000697 }
drh8b582012003-10-21 13:16:03 +0000698 }
699 }
drh8dc3e8f2010-01-07 03:53:03 +0000700
701 /* If no existing offsets exactly match the current transaction, find an
702 ** an empty offset in the aAction[] table in which we can add the
703 ** aLookahead[] transaction.
704 */
drhf16371d2009-11-03 19:18:31 +0000705 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000706 /* Look for holes in the aAction[] table that fit the current
707 ** aLookahead[] transaction. Leave i set to the offset of the hole.
708 ** If no holes are found, i is left at p->nAction, which means the
709 ** transaction will be appended. */
710 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000711 if( p->aAction[i].lookahead<0 ){
712 for(j=0; j<p->nLookahead; j++){
713 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
714 if( k<0 ) break;
715 if( p->aAction[k].lookahead>=0 ) break;
716 }
717 if( j<p->nLookahead ) continue;
718 for(j=0; j<p->nAction; j++){
719 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
720 }
721 if( j==p->nAction ){
722 break; /* Fits in empty slots */
723 }
724 }
725 }
726 }
drh8b582012003-10-21 13:16:03 +0000727 /* Insert transaction set at index i. */
728 for(j=0; j<p->nLookahead; j++){
729 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
730 p->aAction[k] = p->aLookahead[j];
731 if( k>=p->nAction ) p->nAction = k+1;
732 }
733 p->nLookahead = 0;
734
735 /* Return the offset that is added to the lookahead in order to get the
736 ** index into yy_action of the action */
737 return i - p->mnLookahead;
738}
739
drh75897232000-05-29 14:26:00 +0000740/********************** From the file "build.c" *****************************/
741/*
742** Routines to construction the finite state machine for the LEMON
743** parser generator.
744*/
745
746/* Find a precedence symbol of every rule in the grammar.
747**
748** Those rules which have a precedence symbol coded in the input
749** grammar using the "[symbol]" construct will already have the
750** rp->precsym field filled. Other rules take as their precedence
751** symbol the first RHS symbol with a defined precedence. If there
752** are not RHS symbols with a defined precedence, the precedence
753** symbol field is left blank.
754*/
icculus9e44cf12010-02-14 17:14:22 +0000755void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000756{
757 struct rule *rp;
758 for(rp=xp->rule; rp; rp=rp->next){
759 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000760 int i, j;
761 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
762 struct symbol *sp = rp->rhs[i];
763 if( sp->type==MULTITERMINAL ){
764 for(j=0; j<sp->nsubsym; j++){
765 if( sp->subsym[j]->prec>=0 ){
766 rp->precsym = sp->subsym[j];
767 break;
768 }
769 }
770 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000771 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000772 }
drh75897232000-05-29 14:26:00 +0000773 }
774 }
775 }
776 return;
777}
778
779/* Find all nonterminals which will generate the empty string.
780** Then go back and compute the first sets of every nonterminal.
781** The first set is the set of all terminal symbols which can begin
782** a string generated by that nonterminal.
783*/
icculus9e44cf12010-02-14 17:14:22 +0000784void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000785{
drhfd405312005-11-06 04:06:59 +0000786 int i, j;
drh75897232000-05-29 14:26:00 +0000787 struct rule *rp;
788 int progress;
789
790 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000791 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000792 }
793 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
794 lemp->symbols[i]->firstset = SetNew();
795 }
796
797 /* First compute all lambdas */
798 do{
799 progress = 0;
800 for(rp=lemp->rule; rp; rp=rp->next){
801 if( rp->lhs->lambda ) continue;
802 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000803 struct symbol *sp = rp->rhs[i];
804 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
805 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000806 }
807 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000808 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000809 progress = 1;
810 }
811 }
812 }while( progress );
813
814 /* Now compute all first sets */
815 do{
816 struct symbol *s1, *s2;
817 progress = 0;
818 for(rp=lemp->rule; rp; rp=rp->next){
819 s1 = rp->lhs;
820 for(i=0; i<rp->nrhs; i++){
821 s2 = rp->rhs[i];
822 if( s2->type==TERMINAL ){
823 progress += SetAdd(s1->firstset,s2->index);
824 break;
drhfd405312005-11-06 04:06:59 +0000825 }else if( s2->type==MULTITERMINAL ){
826 for(j=0; j<s2->nsubsym; j++){
827 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
828 }
829 break;
drhf2f105d2012-08-20 15:53:54 +0000830 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000831 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000832 }else{
drh75897232000-05-29 14:26:00 +0000833 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000834 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000835 }
drh75897232000-05-29 14:26:00 +0000836 }
837 }
838 }while( progress );
839 return;
840}
841
842/* Compute all LR(0) states for the grammar. Links
843** are added to between some states so that the LR(1) follow sets
844** can be computed later.
845*/
icculus9e44cf12010-02-14 17:14:22 +0000846PRIVATE struct state *getstate(struct lemon *); /* forward reference */
847void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000848{
849 struct symbol *sp;
850 struct rule *rp;
851
852 Configlist_init();
853
854 /* Find the start symbol */
855 if( lemp->start ){
856 sp = Symbol_find(lemp->start);
857 if( sp==0 ){
858 ErrorMsg(lemp->filename,0,
859"The specified start symbol \"%s\" is not \
860in a nonterminal of the grammar. \"%s\" will be used as the start \
861symbol instead.",lemp->start,lemp->rule->lhs->name);
862 lemp->errorcnt++;
863 sp = lemp->rule->lhs;
864 }
865 }else{
866 sp = lemp->rule->lhs;
867 }
868
869 /* Make sure the start symbol doesn't occur on the right-hand side of
870 ** any rule. Report an error if it does. (YACC would generate a new
871 ** start symbol in this case.) */
872 for(rp=lemp->rule; rp; rp=rp->next){
873 int i;
874 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000875 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000876 ErrorMsg(lemp->filename,0,
877"The start symbol \"%s\" occurs on the \
878right-hand side of a rule. This will result in a parser which \
879does not work properly.",sp->name);
880 lemp->errorcnt++;
881 }
882 }
883 }
884
885 /* The basis configuration set for the first state
886 ** is all rules which have the start symbol as their
887 ** left-hand side */
888 for(rp=sp->rule; rp; rp=rp->nextlhs){
889 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000890 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000891 newcfp = Configlist_addbasis(rp,0);
892 SetAdd(newcfp->fws,0);
893 }
894
895 /* Compute the first state. All other states will be
896 ** computed automatically during the computation of the first one.
897 ** The returned pointer to the first state is not used. */
898 (void)getstate(lemp);
899 return;
900}
901
902/* Return a pointer to a state which is described by the configuration
903** list which has been built from calls to Configlist_add.
904*/
icculus9e44cf12010-02-14 17:14:22 +0000905PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
906PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000907{
908 struct config *cfp, *bp;
909 struct state *stp;
910
911 /* Extract the sorted basis of the new state. The basis was constructed
912 ** by prior calls to "Configlist_addbasis()". */
913 Configlist_sortbasis();
914 bp = Configlist_basis();
915
916 /* Get a state with the same basis */
917 stp = State_find(bp);
918 if( stp ){
919 /* A state with the same basis already exists! Copy all the follow-set
920 ** propagation links from the state under construction into the
921 ** preexisting state, then return a pointer to the preexisting state */
922 struct config *x, *y;
923 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
924 Plink_copy(&y->bplp,x->bplp);
925 Plink_delete(x->fplp);
926 x->fplp = x->bplp = 0;
927 }
928 cfp = Configlist_return();
929 Configlist_eat(cfp);
930 }else{
931 /* This really is a new state. Construct all the details */
932 Configlist_closure(lemp); /* Compute the configuration closure */
933 Configlist_sort(); /* Sort the configuration closure */
934 cfp = Configlist_return(); /* Get a pointer to the config list */
935 stp = State_new(); /* A new state structure */
936 MemoryCheck(stp);
937 stp->bp = bp; /* Remember the configuration basis */
938 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000939 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000940 stp->ap = 0; /* No actions, yet. */
941 State_insert(stp,stp->bp); /* Add to the state table */
942 buildshifts(lemp,stp); /* Recursively compute successor states */
943 }
944 return stp;
945}
946
drhfd405312005-11-06 04:06:59 +0000947/*
948** Return true if two symbols are the same.
949*/
icculus9e44cf12010-02-14 17:14:22 +0000950int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000951{
952 int i;
953 if( a==b ) return 1;
954 if( a->type!=MULTITERMINAL ) return 0;
955 if( b->type!=MULTITERMINAL ) return 0;
956 if( a->nsubsym!=b->nsubsym ) return 0;
957 for(i=0; i<a->nsubsym; i++){
958 if( a->subsym[i]!=b->subsym[i] ) return 0;
959 }
960 return 1;
961}
962
drh75897232000-05-29 14:26:00 +0000963/* Construct all successor states to the given state. A "successor"
964** state is any state which can be reached by a shift action.
965*/
icculus9e44cf12010-02-14 17:14:22 +0000966PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000967{
968 struct config *cfp; /* For looping thru the config closure of "stp" */
969 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000970 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000971 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
972 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
973 struct state *newstp; /* A pointer to a successor state */
974
975 /* Each configuration becomes complete after it contibutes to a successor
976 ** state. Initially, all configurations are incomplete */
977 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
978
979 /* Loop through all configurations of the state "stp" */
980 for(cfp=stp->cfp; cfp; cfp=cfp->next){
981 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
982 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
983 Configlist_reset(); /* Reset the new config set */
984 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
985
986 /* For every configuration in the state "stp" which has the symbol "sp"
987 ** following its dot, add the same configuration to the basis set under
988 ** construction but with the dot shifted one symbol to the right. */
989 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
990 if( bcfp->status==COMPLETE ) continue; /* Already used */
991 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
992 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000993 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000994 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000995 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
996 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000997 }
998
999 /* Get a pointer to the state described by the basis configuration set
1000 ** constructed in the preceding loop */
1001 newstp = getstate(lemp);
1002
1003 /* The state "newstp" is reached from the state "stp" by a shift action
1004 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001005 if( sp->type==MULTITERMINAL ){
1006 int i;
1007 for(i=0; i<sp->nsubsym; i++){
1008 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1009 }
1010 }else{
1011 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1012 }
drh75897232000-05-29 14:26:00 +00001013 }
1014}
1015
1016/*
1017** Construct the propagation links
1018*/
icculus9e44cf12010-02-14 17:14:22 +00001019void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001020{
1021 int i;
1022 struct config *cfp, *other;
1023 struct state *stp;
1024 struct plink *plp;
1025
1026 /* Housekeeping detail:
1027 ** Add to every propagate link a pointer back to the state to
1028 ** which the link is attached. */
1029 for(i=0; i<lemp->nstate; i++){
1030 stp = lemp->sorted[i];
1031 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1032 cfp->stp = stp;
1033 }
1034 }
1035
1036 /* Convert all backlinks into forward links. Only the forward
1037 ** links are used in the follow-set computation. */
1038 for(i=0; i<lemp->nstate; i++){
1039 stp = lemp->sorted[i];
1040 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1041 for(plp=cfp->bplp; plp; plp=plp->next){
1042 other = plp->cfp;
1043 Plink_add(&other->fplp,cfp);
1044 }
1045 }
1046 }
1047}
1048
1049/* Compute all followsets.
1050**
1051** A followset is the set of all symbols which can come immediately
1052** after a configuration.
1053*/
icculus9e44cf12010-02-14 17:14:22 +00001054void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001055{
1056 int i;
1057 struct config *cfp;
1058 struct plink *plp;
1059 int progress;
1060 int change;
1061
1062 for(i=0; i<lemp->nstate; i++){
1063 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1064 cfp->status = INCOMPLETE;
1065 }
1066 }
1067
1068 do{
1069 progress = 0;
1070 for(i=0; i<lemp->nstate; i++){
1071 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1072 if( cfp->status==COMPLETE ) continue;
1073 for(plp=cfp->fplp; plp; plp=plp->next){
1074 change = SetUnion(plp->cfp->fws,cfp->fws);
1075 if( change ){
1076 plp->cfp->status = INCOMPLETE;
1077 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001078 }
1079 }
drh75897232000-05-29 14:26:00 +00001080 cfp->status = COMPLETE;
1081 }
1082 }
1083 }while( progress );
1084}
1085
drh3cb2f6e2012-01-09 14:19:05 +00001086static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001087
1088/* Compute the reduce actions, and resolve conflicts.
1089*/
icculus9e44cf12010-02-14 17:14:22 +00001090void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001091{
1092 int i,j;
1093 struct config *cfp;
1094 struct state *stp;
1095 struct symbol *sp;
1096 struct rule *rp;
1097
1098 /* Add all of the reduce actions
1099 ** A reduce action is added for each element of the followset of
1100 ** a configuration which has its dot at the extreme right.
1101 */
1102 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1103 stp = lemp->sorted[i];
1104 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1105 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1106 for(j=0; j<lemp->nterminal; j++){
1107 if( SetFind(cfp->fws,j) ){
1108 /* Add a reduce action to the state "stp" which will reduce by the
1109 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001110 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001111 }
drhf2f105d2012-08-20 15:53:54 +00001112 }
drh75897232000-05-29 14:26:00 +00001113 }
1114 }
1115 }
1116
1117 /* Add the accepting token */
1118 if( lemp->start ){
1119 sp = Symbol_find(lemp->start);
1120 if( sp==0 ) sp = lemp->rule->lhs;
1121 }else{
1122 sp = lemp->rule->lhs;
1123 }
1124 /* Add to the first state (which is always the starting state of the
1125 ** finite state machine) an action to ACCEPT if the lookahead is the
1126 ** start nonterminal. */
1127 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1128
1129 /* Resolve conflicts */
1130 for(i=0; i<lemp->nstate; i++){
1131 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001132 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001133 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001134 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001135 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001136 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1137 /* The two actions "ap" and "nap" have the same lookahead.
1138 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001139 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001140 }
1141 }
1142 }
1143
1144 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001145 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001146 for(i=0; i<lemp->nstate; i++){
1147 struct action *ap;
1148 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001149 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001150 }
1151 }
1152 for(rp=lemp->rule; rp; rp=rp->next){
1153 if( rp->canReduce ) continue;
1154 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1155 lemp->errorcnt++;
1156 }
1157}
1158
1159/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001160** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001161**
1162** NO LONGER TRUE:
1163** To resolve a conflict, first look to see if either action
1164** is on an error rule. In that case, take the action which
1165** is not associated with the error rule. If neither or both
1166** actions are associated with an error rule, then try to
1167** use precedence to resolve the conflict.
1168**
1169** If either action is a SHIFT, then it must be apx. This
1170** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1171*/
icculus9e44cf12010-02-14 17:14:22 +00001172static int resolve_conflict(
1173 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001174 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001175){
drh75897232000-05-29 14:26:00 +00001176 struct symbol *spx, *spy;
1177 int errcnt = 0;
1178 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001179 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001180 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001181 errcnt++;
1182 }
drh75897232000-05-29 14:26:00 +00001183 if( apx->type==SHIFT && apy->type==REDUCE ){
1184 spx = apx->sp;
1185 spy = apy->x.rp->precsym;
1186 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1187 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001188 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001189 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001190 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001191 apy->type = RD_RESOLVED;
1192 }else if( spx->prec<spy->prec ){
1193 apx->type = SH_RESOLVED;
1194 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1195 apy->type = RD_RESOLVED; /* associativity */
1196 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1197 apx->type = SH_RESOLVED;
1198 }else{
1199 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001200 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001201 }
1202 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1203 spx = apx->x.rp->precsym;
1204 spy = apy->x.rp->precsym;
1205 if( spx==0 || spy==0 || spx->prec<0 ||
1206 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001207 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001208 errcnt++;
1209 }else if( spx->prec>spy->prec ){
1210 apy->type = RD_RESOLVED;
1211 }else if( spx->prec<spy->prec ){
1212 apx->type = RD_RESOLVED;
1213 }
1214 }else{
drhb59499c2002-02-23 18:45:13 +00001215 assert(
1216 apx->type==SH_RESOLVED ||
1217 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001218 apx->type==SSCONFLICT ||
1219 apx->type==SRCONFLICT ||
1220 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001221 apy->type==SH_RESOLVED ||
1222 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001223 apy->type==SSCONFLICT ||
1224 apy->type==SRCONFLICT ||
1225 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001226 );
1227 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1228 ** REDUCEs on the list. If we reach this point it must be because
1229 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001230 }
1231 return errcnt;
1232}
1233/********************* From the file "configlist.c" *************************/
1234/*
1235** Routines to processing a configuration list and building a state
1236** in the LEMON parser generator.
1237*/
1238
1239static struct config *freelist = 0; /* List of free configurations */
1240static struct config *current = 0; /* Top of list of configurations */
1241static struct config **currentend = 0; /* Last on list of configs */
1242static struct config *basis = 0; /* Top of list of basis configs */
1243static struct config **basisend = 0; /* End of list of basis configs */
1244
1245/* Return a pointer to a new configuration */
1246PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001247 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001248 if( freelist==0 ){
1249 int i;
1250 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001251 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001252 if( freelist==0 ){
1253 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1254 exit(1);
1255 }
1256 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1257 freelist[amt-1].next = 0;
1258 }
icculus9e44cf12010-02-14 17:14:22 +00001259 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001260 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001261 return newcfg;
drh75897232000-05-29 14:26:00 +00001262}
1263
1264/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001265PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001266{
1267 old->next = freelist;
1268 freelist = old;
1269}
1270
1271/* Initialized the configuration list builder */
1272void Configlist_init(){
1273 current = 0;
1274 currentend = &current;
1275 basis = 0;
1276 basisend = &basis;
1277 Configtable_init();
1278 return;
1279}
1280
1281/* Initialized the configuration list builder */
1282void Configlist_reset(){
1283 current = 0;
1284 currentend = &current;
1285 basis = 0;
1286 basisend = &basis;
1287 Configtable_clear(0);
1288 return;
1289}
1290
1291/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001292struct config *Configlist_add(
1293 struct rule *rp, /* The rule */
1294 int dot /* Index into the RHS of the rule where the dot goes */
1295){
drh75897232000-05-29 14:26:00 +00001296 struct config *cfp, model;
1297
1298 assert( currentend!=0 );
1299 model.rp = rp;
1300 model.dot = dot;
1301 cfp = Configtable_find(&model);
1302 if( cfp==0 ){
1303 cfp = newconfig();
1304 cfp->rp = rp;
1305 cfp->dot = dot;
1306 cfp->fws = SetNew();
1307 cfp->stp = 0;
1308 cfp->fplp = cfp->bplp = 0;
1309 cfp->next = 0;
1310 cfp->bp = 0;
1311 *currentend = cfp;
1312 currentend = &cfp->next;
1313 Configtable_insert(cfp);
1314 }
1315 return cfp;
1316}
1317
1318/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001319struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001320{
1321 struct config *cfp, model;
1322
1323 assert( basisend!=0 );
1324 assert( currentend!=0 );
1325 model.rp = rp;
1326 model.dot = dot;
1327 cfp = Configtable_find(&model);
1328 if( cfp==0 ){
1329 cfp = newconfig();
1330 cfp->rp = rp;
1331 cfp->dot = dot;
1332 cfp->fws = SetNew();
1333 cfp->stp = 0;
1334 cfp->fplp = cfp->bplp = 0;
1335 cfp->next = 0;
1336 cfp->bp = 0;
1337 *currentend = cfp;
1338 currentend = &cfp->next;
1339 *basisend = cfp;
1340 basisend = &cfp->bp;
1341 Configtable_insert(cfp);
1342 }
1343 return cfp;
1344}
1345
1346/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001347void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001348{
1349 struct config *cfp, *newcfp;
1350 struct rule *rp, *newrp;
1351 struct symbol *sp, *xsp;
1352 int i, dot;
1353
1354 assert( currentend!=0 );
1355 for(cfp=current; cfp; cfp=cfp->next){
1356 rp = cfp->rp;
1357 dot = cfp->dot;
1358 if( dot>=rp->nrhs ) continue;
1359 sp = rp->rhs[dot];
1360 if( sp->type==NONTERMINAL ){
1361 if( sp->rule==0 && sp!=lemp->errsym ){
1362 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1363 sp->name);
1364 lemp->errorcnt++;
1365 }
1366 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1367 newcfp = Configlist_add(newrp,0);
1368 for(i=dot+1; i<rp->nrhs; i++){
1369 xsp = rp->rhs[i];
1370 if( xsp->type==TERMINAL ){
1371 SetAdd(newcfp->fws,xsp->index);
1372 break;
drhfd405312005-11-06 04:06:59 +00001373 }else if( xsp->type==MULTITERMINAL ){
1374 int k;
1375 for(k=0; k<xsp->nsubsym; k++){
1376 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1377 }
1378 break;
drhf2f105d2012-08-20 15:53:54 +00001379 }else{
drh75897232000-05-29 14:26:00 +00001380 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001381 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001382 }
1383 }
drh75897232000-05-29 14:26:00 +00001384 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1385 }
1386 }
1387 }
1388 return;
1389}
1390
1391/* Sort the configuration list */
1392void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001393 current = (struct config*)msort((char*)current,(char**)&(current->next),
1394 Configcmp);
drh75897232000-05-29 14:26:00 +00001395 currentend = 0;
1396 return;
1397}
1398
1399/* Sort the basis configuration list */
1400void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001401 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1402 Configcmp);
drh75897232000-05-29 14:26:00 +00001403 basisend = 0;
1404 return;
1405}
1406
1407/* Return a pointer to the head of the configuration list and
1408** reset the list */
1409struct config *Configlist_return(){
1410 struct config *old;
1411 old = current;
1412 current = 0;
1413 currentend = 0;
1414 return old;
1415}
1416
1417/* Return a pointer to the head of the configuration list and
1418** reset the list */
1419struct config *Configlist_basis(){
1420 struct config *old;
1421 old = basis;
1422 basis = 0;
1423 basisend = 0;
1424 return old;
1425}
1426
1427/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001428void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001429{
1430 struct config *nextcfp;
1431 for(; cfp; cfp=nextcfp){
1432 nextcfp = cfp->next;
1433 assert( cfp->fplp==0 );
1434 assert( cfp->bplp==0 );
1435 if( cfp->fws ) SetFree(cfp->fws);
1436 deleteconfig(cfp);
1437 }
1438 return;
1439}
1440/***************** From the file "error.c" *********************************/
1441/*
1442** Code for printing error message.
1443*/
1444
drhf9a2e7b2003-04-15 01:49:48 +00001445void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001446 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001447 fprintf(stderr, "%s:%d: ", filename, lineno);
1448 va_start(ap, format);
1449 vfprintf(stderr,format,ap);
1450 va_end(ap);
1451 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001452}
1453/**************** From the file "main.c" ************************************/
1454/*
1455** Main program file for the LEMON parser generator.
1456*/
1457
1458/* Report an out-of-memory condition and abort. This function
1459** is used mostly by the "MemoryCheck" macro in struct.h
1460*/
1461void memory_error(){
1462 fprintf(stderr,"Out of memory. Aborting...\n");
1463 exit(1);
1464}
1465
drh6d08b4d2004-07-20 12:45:22 +00001466static int nDefine = 0; /* Number of -D options on the command line */
1467static char **azDefine = 0; /* Name of the -D macros */
1468
1469/* This routine is called with the argument to each -D command-line option.
1470** Add the macro defined to the azDefine array.
1471*/
1472static void handle_D_option(char *z){
1473 char **paz;
1474 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001475 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001476 if( azDefine==0 ){
1477 fprintf(stderr,"out of memory\n");
1478 exit(1);
1479 }
1480 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001481 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001482 if( *paz==0 ){
1483 fprintf(stderr,"out of memory\n");
1484 exit(1);
1485 }
drh898799f2014-01-10 23:21:00 +00001486 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001487 for(z=*paz; *z && *z!='='; z++){}
1488 *z = 0;
1489}
1490
icculus3e143bd2010-02-14 00:48:49 +00001491static char *user_templatename = NULL;
1492static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001493 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001494 if( user_templatename==0 ){
1495 memory_error();
1496 }
drh898799f2014-01-10 23:21:00 +00001497 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001498}
drh75897232000-05-29 14:26:00 +00001499
drhc75e0162015-09-07 02:23:02 +00001500/* forward reference */
1501static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1502
1503/* Print a single line of the "Parser Stats" output
1504*/
1505static void stats_line(const char *zLabel, int iValue){
1506 int nLabel = lemonStrlen(zLabel);
1507 printf(" %s%.*s %5d\n", zLabel,
1508 35-nLabel, "................................",
1509 iValue);
1510}
1511
drh75897232000-05-29 14:26:00 +00001512/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001513int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001514{
1515 static int version = 0;
1516 static int rpflag = 0;
1517 static int basisflag = 0;
1518 static int compress = 0;
1519 static int quiet = 0;
1520 static int statistics = 0;
1521 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001522 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001523 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001524 static struct s_options options[] = {
1525 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1526 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001527 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001528 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001529 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001530 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001531 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1532 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001533 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001534 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1535 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001536 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001537 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001538 {OPT_FLAG, "s", (char*)&statistics,
1539 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001540 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001541 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1542 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001543 {OPT_FLAG,0,0,0}
1544 };
1545 int i;
icculus42585cf2010-02-14 05:19:56 +00001546 int exitcode;
drh75897232000-05-29 14:26:00 +00001547 struct lemon lem;
1548
drhb0c86772000-06-02 23:21:26 +00001549 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001550 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001551 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001552 exit(0);
1553 }
drhb0c86772000-06-02 23:21:26 +00001554 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001555 fprintf(stderr,"Exactly one filename argument is required.\n");
1556 exit(1);
1557 }
drh954f6b42006-06-13 13:27:46 +00001558 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001559 lem.errorcnt = 0;
1560
1561 /* Initialize the machine */
1562 Strsafe_init();
1563 Symbol_init();
1564 State_init();
1565 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001566 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001567 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001568 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001569 Symbol_new("$");
1570 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001571 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001572
1573 /* Parse the input file */
1574 Parse(&lem);
1575 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001576 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001577 fprintf(stderr,"Empty grammar.\n");
1578 exit(1);
1579 }
1580
1581 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001582 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001583 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001584 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001585 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1586 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1587 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1588 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1589 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1590 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001591 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001592 lem.nterminal = i;
1593
1594 /* Generate a reprint of the grammar, if requested on the command line */
1595 if( rpflag ){
1596 Reprint(&lem);
1597 }else{
1598 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001599 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001600
1601 /* Find the precedence for every production rule (that has one) */
1602 FindRulePrecedences(&lem);
1603
1604 /* Compute the lambda-nonterminals and the first-sets for every
1605 ** nonterminal */
1606 FindFirstSets(&lem);
1607
1608 /* Compute all LR(0) states. Also record follow-set propagation
1609 ** links so that the follow-set can be computed later */
1610 lem.nstate = 0;
1611 FindStates(&lem);
1612 lem.sorted = State_arrayof();
1613
1614 /* Tie up loose ends on the propagation links */
1615 FindLinks(&lem);
1616
1617 /* Compute the follow set of every reducible configuration */
1618 FindFollowSets(&lem);
1619
1620 /* Compute the action tables */
1621 FindActions(&lem);
1622
1623 /* Compress the action tables */
1624 if( compress==0 ) CompressTables(&lem);
1625
drhada354d2005-11-05 15:03:59 +00001626 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001627 ** occur at the end. This is an optimization that helps make the
1628 ** generated parser tables smaller. */
1629 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001630
drh75897232000-05-29 14:26:00 +00001631 /* Generate a report of the parser generated. (the "y.output" file) */
1632 if( !quiet ) ReportOutput(&lem);
1633
1634 /* Generate the source code for the parser */
1635 ReportTable(&lem, mhflag);
1636
1637 /* Produce a header file for use by the scanner. (This step is
1638 ** omitted if the "-m" option is used because makeheaders will
1639 ** generate the file for us.) */
1640 if( !mhflag ) ReportHeader(&lem);
1641 }
1642 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001643 printf("Parser statistics:\n");
1644 stats_line("terminal symbols", lem.nterminal);
1645 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1646 stats_line("total symbols", lem.nsymbol);
1647 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001648 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001649 stats_line("conflicts", lem.nconflict);
1650 stats_line("action table entries", lem.nactiontab);
1651 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001652 }
icculus8e158022010-02-16 16:09:03 +00001653 if( lem.nconflict > 0 ){
1654 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001655 }
1656
1657 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001658 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001659 exit(exitcode);
1660 return (exitcode);
drh75897232000-05-29 14:26:00 +00001661}
1662/******************** From the file "msort.c" *******************************/
1663/*
1664** A generic merge-sort program.
1665**
1666** USAGE:
1667** Let "ptr" be a pointer to some structure which is at the head of
1668** a null-terminated list. Then to sort the list call:
1669**
1670** ptr = msort(ptr,&(ptr->next),cmpfnc);
1671**
1672** In the above, "cmpfnc" is a pointer to a function which compares
1673** two instances of the structure and returns an integer, as in
1674** strcmp. The second argument is a pointer to the pointer to the
1675** second element of the linked list. This address is used to compute
1676** the offset to the "next" field within the structure. The offset to
1677** the "next" field must be constant for all structures in the list.
1678**
1679** The function returns a new pointer which is the head of the list
1680** after sorting.
1681**
1682** ALGORITHM:
1683** Merge-sort.
1684*/
1685
1686/*
1687** Return a pointer to the next structure in the linked list.
1688*/
drhd25d6922012-04-18 09:59:56 +00001689#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001690
1691/*
1692** Inputs:
1693** a: A sorted, null-terminated linked list. (May be null).
1694** b: A sorted, null-terminated linked list. (May be null).
1695** cmp: A pointer to the comparison function.
1696** offset: Offset in the structure to the "next" field.
1697**
1698** Return Value:
1699** A pointer to the head of a sorted list containing the elements
1700** of both a and b.
1701**
1702** Side effects:
1703** The "next" pointers for elements in the lists a and b are
1704** changed.
1705*/
drhe9278182007-07-18 18:16:29 +00001706static char *merge(
1707 char *a,
1708 char *b,
1709 int (*cmp)(const char*,const char*),
1710 int offset
1711){
drh75897232000-05-29 14:26:00 +00001712 char *ptr, *head;
1713
1714 if( a==0 ){
1715 head = b;
1716 }else if( b==0 ){
1717 head = a;
1718 }else{
drhe594bc32009-11-03 13:02:25 +00001719 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001720 ptr = a;
1721 a = NEXT(a);
1722 }else{
1723 ptr = b;
1724 b = NEXT(b);
1725 }
1726 head = ptr;
1727 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001728 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001729 NEXT(ptr) = a;
1730 ptr = a;
1731 a = NEXT(a);
1732 }else{
1733 NEXT(ptr) = b;
1734 ptr = b;
1735 b = NEXT(b);
1736 }
1737 }
1738 if( a ) NEXT(ptr) = a;
1739 else NEXT(ptr) = b;
1740 }
1741 return head;
1742}
1743
1744/*
1745** Inputs:
1746** list: Pointer to a singly-linked list of structures.
1747** next: Pointer to pointer to the second element of the list.
1748** cmp: A comparison function.
1749**
1750** Return Value:
1751** A pointer to the head of a sorted list containing the elements
1752** orginally in list.
1753**
1754** Side effects:
1755** The "next" pointers for elements in list are changed.
1756*/
1757#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001758static char *msort(
1759 char *list,
1760 char **next,
1761 int (*cmp)(const char*,const char*)
1762){
drhba99af52001-10-25 20:37:16 +00001763 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001764 char *ep;
1765 char *set[LISTSIZE];
1766 int i;
drh1cc0d112015-03-31 15:15:48 +00001767 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001768 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1769 while( list ){
1770 ep = list;
1771 list = NEXT(list);
1772 NEXT(ep) = 0;
1773 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1774 ep = merge(ep,set[i],cmp,offset);
1775 set[i] = 0;
1776 }
1777 set[i] = ep;
1778 }
1779 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001780 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001781 return ep;
1782}
1783/************************ From the file "option.c" **************************/
1784static char **argv;
1785static struct s_options *op;
1786static FILE *errstream;
1787
1788#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1789
1790/*
1791** Print the command line with a carrot pointing to the k-th character
1792** of the n-th field.
1793*/
icculus9e44cf12010-02-14 17:14:22 +00001794static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001795{
1796 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001797 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001798 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001799 for(i=1; i<n && argv[i]; i++){
1800 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001801 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001802 }
1803 spcnt += k;
1804 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1805 if( spcnt<20 ){
1806 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1807 }else{
1808 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1809 }
1810}
1811
1812/*
1813** Return the index of the N-th non-switch argument. Return -1
1814** if N is out of range.
1815*/
icculus9e44cf12010-02-14 17:14:22 +00001816static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001817{
1818 int i;
1819 int dashdash = 0;
1820 if( argv!=0 && *argv!=0 ){
1821 for(i=1; argv[i]; i++){
1822 if( dashdash || !ISOPT(argv[i]) ){
1823 if( n==0 ) return i;
1824 n--;
1825 }
1826 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1827 }
1828 }
1829 return -1;
1830}
1831
1832static char emsg[] = "Command line syntax error: ";
1833
1834/*
1835** Process a flag command line argument.
1836*/
icculus9e44cf12010-02-14 17:14:22 +00001837static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001838{
1839 int v;
1840 int errcnt = 0;
1841 int j;
1842 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001843 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001844 }
1845 v = argv[i][0]=='-' ? 1 : 0;
1846 if( op[j].label==0 ){
1847 if( err ){
1848 fprintf(err,"%sundefined option.\n",emsg);
1849 errline(i,1,err);
1850 }
1851 errcnt++;
drh0325d392015-01-01 19:11:22 +00001852 }else if( op[j].arg==0 ){
1853 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001854 }else if( op[j].type==OPT_FLAG ){
1855 *((int*)op[j].arg) = v;
1856 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001857 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001858 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001859 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001860 }else{
1861 if( err ){
1862 fprintf(err,"%smissing argument on switch.\n",emsg);
1863 errline(i,1,err);
1864 }
1865 errcnt++;
1866 }
1867 return errcnt;
1868}
1869
1870/*
1871** Process a command line switch which has an argument.
1872*/
icculus9e44cf12010-02-14 17:14:22 +00001873static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001874{
1875 int lv = 0;
1876 double dv = 0.0;
1877 char *sv = 0, *end;
1878 char *cp;
1879 int j;
1880 int errcnt = 0;
1881 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001882 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001883 *cp = 0;
1884 for(j=0; op[j].label; j++){
1885 if( strcmp(argv[i],op[j].label)==0 ) break;
1886 }
1887 *cp = '=';
1888 if( op[j].label==0 ){
1889 if( err ){
1890 fprintf(err,"%sundefined option.\n",emsg);
1891 errline(i,0,err);
1892 }
1893 errcnt++;
1894 }else{
1895 cp++;
1896 switch( op[j].type ){
1897 case OPT_FLAG:
1898 case OPT_FFLAG:
1899 if( err ){
1900 fprintf(err,"%soption requires an argument.\n",emsg);
1901 errline(i,0,err);
1902 }
1903 errcnt++;
1904 break;
1905 case OPT_DBL:
1906 case OPT_FDBL:
1907 dv = strtod(cp,&end);
1908 if( *end ){
1909 if( err ){
drh25473362015-09-04 18:03:45 +00001910 fprintf(err,
1911 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001912 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001913 }
1914 errcnt++;
1915 }
1916 break;
1917 case OPT_INT:
1918 case OPT_FINT:
1919 lv = strtol(cp,&end,0);
1920 if( *end ){
1921 if( err ){
1922 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001923 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001924 }
1925 errcnt++;
1926 }
1927 break;
1928 case OPT_STR:
1929 case OPT_FSTR:
1930 sv = cp;
1931 break;
1932 }
1933 switch( op[j].type ){
1934 case OPT_FLAG:
1935 case OPT_FFLAG:
1936 break;
1937 case OPT_DBL:
1938 *(double*)(op[j].arg) = dv;
1939 break;
1940 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001941 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001942 break;
1943 case OPT_INT:
1944 *(int*)(op[j].arg) = lv;
1945 break;
1946 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001947 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001948 break;
1949 case OPT_STR:
1950 *(char**)(op[j].arg) = sv;
1951 break;
1952 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001953 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001954 break;
1955 }
1956 }
1957 return errcnt;
1958}
1959
icculus9e44cf12010-02-14 17:14:22 +00001960int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001961{
1962 int errcnt = 0;
1963 argv = a;
1964 op = o;
1965 errstream = err;
1966 if( argv && *argv && op ){
1967 int i;
1968 for(i=1; argv[i]; i++){
1969 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1970 errcnt += handleflags(i,err);
1971 }else if( strchr(argv[i],'=') ){
1972 errcnt += handleswitch(i,err);
1973 }
1974 }
1975 }
1976 if( errcnt>0 ){
1977 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001978 OptPrint();
drh75897232000-05-29 14:26:00 +00001979 exit(1);
1980 }
1981 return 0;
1982}
1983
drhb0c86772000-06-02 23:21:26 +00001984int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001985 int cnt = 0;
1986 int dashdash = 0;
1987 int i;
1988 if( argv!=0 && argv[0]!=0 ){
1989 for(i=1; argv[i]; i++){
1990 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1991 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1992 }
1993 }
1994 return cnt;
1995}
1996
icculus9e44cf12010-02-14 17:14:22 +00001997char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001998{
1999 int i;
2000 i = argindex(n);
2001 return i>=0 ? argv[i] : 0;
2002}
2003
icculus9e44cf12010-02-14 17:14:22 +00002004void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002005{
2006 int i;
2007 i = argindex(n);
2008 if( i>=0 ) errline(i,0,errstream);
2009}
2010
drhb0c86772000-06-02 23:21:26 +00002011void OptPrint(){
drh75897232000-05-29 14:26:00 +00002012 int i;
2013 int max, len;
2014 max = 0;
2015 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002016 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002017 switch( op[i].type ){
2018 case OPT_FLAG:
2019 case OPT_FFLAG:
2020 break;
2021 case OPT_INT:
2022 case OPT_FINT:
2023 len += 9; /* length of "<integer>" */
2024 break;
2025 case OPT_DBL:
2026 case OPT_FDBL:
2027 len += 6; /* length of "<real>" */
2028 break;
2029 case OPT_STR:
2030 case OPT_FSTR:
2031 len += 8; /* length of "<string>" */
2032 break;
2033 }
2034 if( len>max ) max = len;
2035 }
2036 for(i=0; op[i].label; i++){
2037 switch( op[i].type ){
2038 case OPT_FLAG:
2039 case OPT_FFLAG:
2040 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2041 break;
2042 case OPT_INT:
2043 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002044 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002045 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002046 break;
2047 case OPT_DBL:
2048 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002049 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002050 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002051 break;
2052 case OPT_STR:
2053 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002054 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002055 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002056 break;
2057 }
2058 }
2059}
2060/*********************** From the file "parse.c" ****************************/
2061/*
2062** Input file parser for the LEMON parser generator.
2063*/
2064
2065/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002066enum e_state {
2067 INITIALIZE,
2068 WAITING_FOR_DECL_OR_RULE,
2069 WAITING_FOR_DECL_KEYWORD,
2070 WAITING_FOR_DECL_ARG,
2071 WAITING_FOR_PRECEDENCE_SYMBOL,
2072 WAITING_FOR_ARROW,
2073 IN_RHS,
2074 LHS_ALIAS_1,
2075 LHS_ALIAS_2,
2076 LHS_ALIAS_3,
2077 RHS_ALIAS_1,
2078 RHS_ALIAS_2,
2079 PRECEDENCE_MARK_1,
2080 PRECEDENCE_MARK_2,
2081 RESYNC_AFTER_RULE_ERROR,
2082 RESYNC_AFTER_DECL_ERROR,
2083 WAITING_FOR_DESTRUCTOR_SYMBOL,
2084 WAITING_FOR_DATATYPE_SYMBOL,
2085 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002086 WAITING_FOR_WILDCARD_ID,
2087 WAITING_FOR_CLASS_ID,
2088 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002089};
drh75897232000-05-29 14:26:00 +00002090struct pstate {
2091 char *filename; /* Name of the input file */
2092 int tokenlineno; /* Linenumber at which current token starts */
2093 int errorcnt; /* Number of errors so far */
2094 char *tokenstart; /* Text of current token */
2095 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002096 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002097 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002098 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002099 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002100 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002101 int nrhs; /* Number of right-hand side symbols seen */
2102 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002103 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002104 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002105 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002106 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002107 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002108 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002109 enum e_assoc declassoc; /* Assign this association to decl arguments */
2110 int preccounter; /* Assign this precedence to decl arguments */
2111 struct rule *firstrule; /* Pointer to first rule in the grammar */
2112 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2113};
2114
2115/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002116static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002117{
icculus9e44cf12010-02-14 17:14:22 +00002118 const char *x;
drh75897232000-05-29 14:26:00 +00002119 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2120#if 0
2121 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2122 x,psp->state);
2123#endif
2124 switch( psp->state ){
2125 case INITIALIZE:
2126 psp->prevrule = 0;
2127 psp->preccounter = 0;
2128 psp->firstrule = psp->lastrule = 0;
2129 psp->gp->nrule = 0;
2130 /* Fall thru to next case */
2131 case WAITING_FOR_DECL_OR_RULE:
2132 if( x[0]=='%' ){
2133 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002134 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002135 psp->lhs = Symbol_new(x);
2136 psp->nrhs = 0;
2137 psp->lhsalias = 0;
2138 psp->state = WAITING_FOR_ARROW;
2139 }else if( x[0]=='{' ){
2140 if( psp->prevrule==0 ){
2141 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002142"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002143fragment which begins on this line.");
2144 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002145 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002146 ErrorMsg(psp->filename,psp->tokenlineno,
2147"Code fragment beginning on this line is not the first \
2148to follow the previous rule.");
2149 psp->errorcnt++;
2150 }else{
2151 psp->prevrule->line = psp->tokenlineno;
2152 psp->prevrule->code = &x[1];
drhf2f105d2012-08-20 15:53:54 +00002153 }
drh75897232000-05-29 14:26:00 +00002154 }else if( x[0]=='[' ){
2155 psp->state = PRECEDENCE_MARK_1;
2156 }else{
2157 ErrorMsg(psp->filename,psp->tokenlineno,
2158 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2159 x);
2160 psp->errorcnt++;
2161 }
2162 break;
2163 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002164 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002165 ErrorMsg(psp->filename,psp->tokenlineno,
2166 "The precedence symbol must be a terminal.");
2167 psp->errorcnt++;
2168 }else if( psp->prevrule==0 ){
2169 ErrorMsg(psp->filename,psp->tokenlineno,
2170 "There is no prior rule to assign precedence \"[%s]\".",x);
2171 psp->errorcnt++;
2172 }else if( psp->prevrule->precsym!=0 ){
2173 ErrorMsg(psp->filename,psp->tokenlineno,
2174"Precedence mark on this line is not the first \
2175to follow the previous rule.");
2176 psp->errorcnt++;
2177 }else{
2178 psp->prevrule->precsym = Symbol_new(x);
2179 }
2180 psp->state = PRECEDENCE_MARK_2;
2181 break;
2182 case PRECEDENCE_MARK_2:
2183 if( x[0]!=']' ){
2184 ErrorMsg(psp->filename,psp->tokenlineno,
2185 "Missing \"]\" on precedence mark.");
2186 psp->errorcnt++;
2187 }
2188 psp->state = WAITING_FOR_DECL_OR_RULE;
2189 break;
2190 case WAITING_FOR_ARROW:
2191 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2192 psp->state = IN_RHS;
2193 }else if( x[0]=='(' ){
2194 psp->state = LHS_ALIAS_1;
2195 }else{
2196 ErrorMsg(psp->filename,psp->tokenlineno,
2197 "Expected to see a \":\" following the LHS symbol \"%s\".",
2198 psp->lhs->name);
2199 psp->errorcnt++;
2200 psp->state = RESYNC_AFTER_RULE_ERROR;
2201 }
2202 break;
2203 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002204 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002205 psp->lhsalias = x;
2206 psp->state = LHS_ALIAS_2;
2207 }else{
2208 ErrorMsg(psp->filename,psp->tokenlineno,
2209 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2210 x,psp->lhs->name);
2211 psp->errorcnt++;
2212 psp->state = RESYNC_AFTER_RULE_ERROR;
2213 }
2214 break;
2215 case LHS_ALIAS_2:
2216 if( x[0]==')' ){
2217 psp->state = LHS_ALIAS_3;
2218 }else{
2219 ErrorMsg(psp->filename,psp->tokenlineno,
2220 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2221 psp->errorcnt++;
2222 psp->state = RESYNC_AFTER_RULE_ERROR;
2223 }
2224 break;
2225 case LHS_ALIAS_3:
2226 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2227 psp->state = IN_RHS;
2228 }else{
2229 ErrorMsg(psp->filename,psp->tokenlineno,
2230 "Missing \"->\" following: \"%s(%s)\".",
2231 psp->lhs->name,psp->lhsalias);
2232 psp->errorcnt++;
2233 psp->state = RESYNC_AFTER_RULE_ERROR;
2234 }
2235 break;
2236 case IN_RHS:
2237 if( x[0]=='.' ){
2238 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002239 rp = (struct rule *)calloc( sizeof(struct rule) +
2240 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002241 if( rp==0 ){
2242 ErrorMsg(psp->filename,psp->tokenlineno,
2243 "Can't allocate enough memory for this rule.");
2244 psp->errorcnt++;
2245 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002246 }else{
drh75897232000-05-29 14:26:00 +00002247 int i;
2248 rp->ruleline = psp->tokenlineno;
2249 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002250 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002251 for(i=0; i<psp->nrhs; i++){
2252 rp->rhs[i] = psp->rhs[i];
2253 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002254 }
drh75897232000-05-29 14:26:00 +00002255 rp->lhs = psp->lhs;
2256 rp->lhsalias = psp->lhsalias;
2257 rp->nrhs = psp->nrhs;
2258 rp->code = 0;
2259 rp->precsym = 0;
2260 rp->index = psp->gp->nrule++;
2261 rp->nextlhs = rp->lhs->rule;
2262 rp->lhs->rule = rp;
2263 rp->next = 0;
2264 if( psp->firstrule==0 ){
2265 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002266 }else{
drh75897232000-05-29 14:26:00 +00002267 psp->lastrule->next = rp;
2268 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002269 }
drh75897232000-05-29 14:26:00 +00002270 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002271 }
drh75897232000-05-29 14:26:00 +00002272 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002273 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002274 if( psp->nrhs>=MAXRHS ){
2275 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002276 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002277 x);
2278 psp->errorcnt++;
2279 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002280 }else{
drh75897232000-05-29 14:26:00 +00002281 psp->rhs[psp->nrhs] = Symbol_new(x);
2282 psp->alias[psp->nrhs] = 0;
2283 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002284 }
drhfd405312005-11-06 04:06:59 +00002285 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2286 struct symbol *msp = psp->rhs[psp->nrhs-1];
2287 if( msp->type!=MULTITERMINAL ){
2288 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002289 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002290 memset(msp, 0, sizeof(*msp));
2291 msp->type = MULTITERMINAL;
2292 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002293 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002294 msp->subsym[0] = origsp;
2295 msp->name = origsp->name;
2296 psp->rhs[psp->nrhs-1] = msp;
2297 }
2298 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002299 msp->subsym = (struct symbol **) realloc(msp->subsym,
2300 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002301 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002302 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "Cannot form a compound containing a non-terminal");
2305 psp->errorcnt++;
2306 }
drh75897232000-05-29 14:26:00 +00002307 }else if( x[0]=='(' && psp->nrhs>0 ){
2308 psp->state = RHS_ALIAS_1;
2309 }else{
2310 ErrorMsg(psp->filename,psp->tokenlineno,
2311 "Illegal character on RHS of rule: \"%s\".",x);
2312 psp->errorcnt++;
2313 psp->state = RESYNC_AFTER_RULE_ERROR;
2314 }
2315 break;
2316 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002317 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002318 psp->alias[psp->nrhs-1] = x;
2319 psp->state = RHS_ALIAS_2;
2320 }else{
2321 ErrorMsg(psp->filename,psp->tokenlineno,
2322 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2323 x,psp->rhs[psp->nrhs-1]->name);
2324 psp->errorcnt++;
2325 psp->state = RESYNC_AFTER_RULE_ERROR;
2326 }
2327 break;
2328 case RHS_ALIAS_2:
2329 if( x[0]==')' ){
2330 psp->state = IN_RHS;
2331 }else{
2332 ErrorMsg(psp->filename,psp->tokenlineno,
2333 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2334 psp->errorcnt++;
2335 psp->state = RESYNC_AFTER_RULE_ERROR;
2336 }
2337 break;
2338 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002339 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002340 psp->declkeyword = x;
2341 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002342 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002343 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002344 psp->state = WAITING_FOR_DECL_ARG;
2345 if( strcmp(x,"name")==0 ){
2346 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002347 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002348 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002349 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002350 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002351 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002352 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002353 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002354 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002355 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002356 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002357 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002358 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002359 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002360 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002361 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002362 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002363 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002364 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002365 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002366 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002367 }else if( strcmp(x,"extra_argument")==0 ){
2368 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002369 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002370 }else if( strcmp(x,"token_type")==0 ){
2371 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002372 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002373 }else if( strcmp(x,"default_type")==0 ){
2374 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002375 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002376 }else if( strcmp(x,"stack_size")==0 ){
2377 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002378 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002379 }else if( strcmp(x,"start_symbol")==0 ){
2380 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002381 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002382 }else if( strcmp(x,"left")==0 ){
2383 psp->preccounter++;
2384 psp->declassoc = LEFT;
2385 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2386 }else if( strcmp(x,"right")==0 ){
2387 psp->preccounter++;
2388 psp->declassoc = RIGHT;
2389 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2390 }else if( strcmp(x,"nonassoc")==0 ){
2391 psp->preccounter++;
2392 psp->declassoc = NONE;
2393 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002394 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002395 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002396 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002397 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002398 }else if( strcmp(x,"fallback")==0 ){
2399 psp->fallback = 0;
2400 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002401 }else if( strcmp(x,"wildcard")==0 ){
2402 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002403 }else if( strcmp(x,"token_class")==0 ){
2404 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002405 }else{
2406 ErrorMsg(psp->filename,psp->tokenlineno,
2407 "Unknown declaration keyword: \"%%%s\".",x);
2408 psp->errorcnt++;
2409 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002410 }
drh75897232000-05-29 14:26:00 +00002411 }else{
2412 ErrorMsg(psp->filename,psp->tokenlineno,
2413 "Illegal declaration keyword: \"%s\".",x);
2414 psp->errorcnt++;
2415 psp->state = RESYNC_AFTER_DECL_ERROR;
2416 }
2417 break;
2418 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002419 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002420 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002421 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002422 psp->errorcnt++;
2423 psp->state = RESYNC_AFTER_DECL_ERROR;
2424 }else{
icculusd286fa62010-03-03 17:06:32 +00002425 struct symbol *sp = Symbol_new(x);
2426 psp->declargslot = &sp->destructor;
2427 psp->decllinenoslot = &sp->destLineno;
2428 psp->insertLineMacro = 1;
2429 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002430 }
2431 break;
2432 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002433 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002434 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002435 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002436 psp->errorcnt++;
2437 psp->state = RESYNC_AFTER_DECL_ERROR;
2438 }else{
icculus866bf1e2010-02-17 20:31:32 +00002439 struct symbol *sp = Symbol_find(x);
2440 if((sp) && (sp->datatype)){
2441 ErrorMsg(psp->filename,psp->tokenlineno,
2442 "Symbol %%type \"%s\" already defined", x);
2443 psp->errorcnt++;
2444 psp->state = RESYNC_AFTER_DECL_ERROR;
2445 }else{
2446 if (!sp){
2447 sp = Symbol_new(x);
2448 }
2449 psp->declargslot = &sp->datatype;
2450 psp->insertLineMacro = 0;
2451 psp->state = WAITING_FOR_DECL_ARG;
2452 }
drh75897232000-05-29 14:26:00 +00002453 }
2454 break;
2455 case WAITING_FOR_PRECEDENCE_SYMBOL:
2456 if( x[0]=='.' ){
2457 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002458 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002459 struct symbol *sp;
2460 sp = Symbol_new(x);
2461 if( sp->prec>=0 ){
2462 ErrorMsg(psp->filename,psp->tokenlineno,
2463 "Symbol \"%s\" has already be given a precedence.",x);
2464 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002465 }else{
drh75897232000-05-29 14:26:00 +00002466 sp->prec = psp->preccounter;
2467 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002468 }
drh75897232000-05-29 14:26:00 +00002469 }else{
2470 ErrorMsg(psp->filename,psp->tokenlineno,
2471 "Can't assign a precedence to \"%s\".",x);
2472 psp->errorcnt++;
2473 }
2474 break;
2475 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002476 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002477 const char *zOld, *zNew;
2478 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002479 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002480 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002481 char zLine[50];
2482 zNew = x;
2483 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002484 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002485 if( *psp->declargslot ){
2486 zOld = *psp->declargslot;
2487 }else{
2488 zOld = "";
2489 }
drh87cf1372008-08-13 20:09:06 +00002490 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002491 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002492 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002493 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2494 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002495 for(z=psp->filename, nBack=0; *z; z++){
2496 if( *z=='\\' ) nBack++;
2497 }
drh898799f2014-01-10 23:21:00 +00002498 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002499 nLine = lemonStrlen(zLine);
2500 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002501 }
icculus9e44cf12010-02-14 17:14:22 +00002502 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2503 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002504 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002505 if( nOld && zBuf[-1]!='\n' ){
2506 *(zBuf++) = '\n';
2507 }
2508 memcpy(zBuf, zLine, nLine);
2509 zBuf += nLine;
2510 *(zBuf++) = '"';
2511 for(z=psp->filename; *z; z++){
2512 if( *z=='\\' ){
2513 *(zBuf++) = '\\';
2514 }
2515 *(zBuf++) = *z;
2516 }
2517 *(zBuf++) = '"';
2518 *(zBuf++) = '\n';
2519 }
drh4dc8ef52008-07-01 17:13:57 +00002520 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2521 psp->decllinenoslot[0] = psp->tokenlineno;
2522 }
drha5808f32008-04-27 22:19:44 +00002523 memcpy(zBuf, zNew, nNew);
2524 zBuf += nNew;
2525 *zBuf = 0;
2526 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002527 }else{
2528 ErrorMsg(psp->filename,psp->tokenlineno,
2529 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2530 psp->errorcnt++;
2531 psp->state = RESYNC_AFTER_DECL_ERROR;
2532 }
2533 break;
drh0bd1f4e2002-06-06 18:54:39 +00002534 case WAITING_FOR_FALLBACK_ID:
2535 if( x[0]=='.' ){
2536 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002537 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002538 ErrorMsg(psp->filename, psp->tokenlineno,
2539 "%%fallback argument \"%s\" should be a token", x);
2540 psp->errorcnt++;
2541 }else{
2542 struct symbol *sp = Symbol_new(x);
2543 if( psp->fallback==0 ){
2544 psp->fallback = sp;
2545 }else if( sp->fallback ){
2546 ErrorMsg(psp->filename, psp->tokenlineno,
2547 "More than one fallback assigned to token %s", x);
2548 psp->errorcnt++;
2549 }else{
2550 sp->fallback = psp->fallback;
2551 psp->gp->has_fallback = 1;
2552 }
2553 }
2554 break;
drhe09daa92006-06-10 13:29:31 +00002555 case WAITING_FOR_WILDCARD_ID:
2556 if( x[0]=='.' ){
2557 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002558 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002559 ErrorMsg(psp->filename, psp->tokenlineno,
2560 "%%wildcard argument \"%s\" should be a token", x);
2561 psp->errorcnt++;
2562 }else{
2563 struct symbol *sp = Symbol_new(x);
2564 if( psp->gp->wildcard==0 ){
2565 psp->gp->wildcard = sp;
2566 }else{
2567 ErrorMsg(psp->filename, psp->tokenlineno,
2568 "Extra wildcard to token: %s", x);
2569 psp->errorcnt++;
2570 }
2571 }
2572 break;
drh61f92cd2014-01-11 03:06:18 +00002573 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002574 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002575 ErrorMsg(psp->filename, psp->tokenlineno,
2576 "%%token_class must be followed by an identifier: ", x);
2577 psp->errorcnt++;
2578 psp->state = RESYNC_AFTER_DECL_ERROR;
2579 }else if( Symbol_find(x) ){
2580 ErrorMsg(psp->filename, psp->tokenlineno,
2581 "Symbol \"%s\" already used", x);
2582 psp->errorcnt++;
2583 psp->state = RESYNC_AFTER_DECL_ERROR;
2584 }else{
2585 psp->tkclass = Symbol_new(x);
2586 psp->tkclass->type = MULTITERMINAL;
2587 psp->state = WAITING_FOR_CLASS_TOKEN;
2588 }
2589 break;
2590 case WAITING_FOR_CLASS_TOKEN:
2591 if( x[0]=='.' ){
2592 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002593 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002594 struct symbol *msp = psp->tkclass;
2595 msp->nsubsym++;
2596 msp->subsym = (struct symbol **) realloc(msp->subsym,
2597 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002598 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002599 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2600 }else{
2601 ErrorMsg(psp->filename, psp->tokenlineno,
2602 "%%token_class argument \"%s\" should be a token", x);
2603 psp->errorcnt++;
2604 psp->state = RESYNC_AFTER_DECL_ERROR;
2605 }
2606 break;
drh75897232000-05-29 14:26:00 +00002607 case RESYNC_AFTER_RULE_ERROR:
2608/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2609** break; */
2610 case RESYNC_AFTER_DECL_ERROR:
2611 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2612 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2613 break;
2614 }
2615}
2616
drh34ff57b2008-07-14 12:27:51 +00002617/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002618** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2619** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2620** comments them out. Text in between is also commented out as appropriate.
2621*/
danielk1977940fac92005-01-23 22:41:37 +00002622static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002623 int i, j, k, n;
2624 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002625 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002626 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002627 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002628 for(i=0; z[i]; i++){
2629 if( z[i]=='\n' ) lineno++;
2630 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002631 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002632 if( exclude ){
2633 exclude--;
2634 if( exclude==0 ){
2635 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2636 }
2637 }
2638 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002639 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2640 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002641 if( exclude ){
2642 exclude++;
2643 }else{
drhc56fac72015-10-29 13:48:15 +00002644 for(j=i+7; ISSPACE(z[j]); j++){}
2645 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002646 exclude = 1;
2647 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002648 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002649 exclude = 0;
2650 break;
2651 }
2652 }
2653 if( z[i+3]=='n' ) exclude = !exclude;
2654 if( exclude ){
2655 start = i;
2656 start_lineno = lineno;
2657 }
2658 }
2659 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2660 }
2661 }
2662 if( exclude ){
2663 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2664 exit(1);
2665 }
2666}
2667
drh75897232000-05-29 14:26:00 +00002668/* In spite of its name, this function is really a scanner. It read
2669** in the entire input file (all at once) then tokenizes it. Each
2670** token is passed to the function "parseonetoken" which builds all
2671** the appropriate data structures in the global state vector "gp".
2672*/
icculus9e44cf12010-02-14 17:14:22 +00002673void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002674{
2675 struct pstate ps;
2676 FILE *fp;
2677 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002678 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002679 int lineno;
2680 int c;
2681 char *cp, *nextcp;
2682 int startline = 0;
2683
rse38514a92007-09-20 11:34:17 +00002684 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002685 ps.gp = gp;
2686 ps.filename = gp->filename;
2687 ps.errorcnt = 0;
2688 ps.state = INITIALIZE;
2689
2690 /* Begin by reading the input file */
2691 fp = fopen(ps.filename,"rb");
2692 if( fp==0 ){
2693 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2694 gp->errorcnt++;
2695 return;
2696 }
2697 fseek(fp,0,2);
2698 filesize = ftell(fp);
2699 rewind(fp);
2700 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002701 if( filesize>100000000 || filebuf==0 ){
2702 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002703 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002704 fclose(fp);
drh75897232000-05-29 14:26:00 +00002705 return;
2706 }
2707 if( fread(filebuf,1,filesize,fp)!=filesize ){
2708 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2709 filesize);
2710 free(filebuf);
2711 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002712 fclose(fp);
drh75897232000-05-29 14:26:00 +00002713 return;
2714 }
2715 fclose(fp);
2716 filebuf[filesize] = 0;
2717
drh6d08b4d2004-07-20 12:45:22 +00002718 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2719 preprocess_input(filebuf);
2720
drh75897232000-05-29 14:26:00 +00002721 /* Now scan the text of the input file */
2722 lineno = 1;
2723 for(cp=filebuf; (c= *cp)!=0; ){
2724 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002725 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002726 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2727 cp+=2;
2728 while( (c= *cp)!=0 && c!='\n' ) cp++;
2729 continue;
2730 }
2731 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2732 cp+=2;
2733 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2734 if( c=='\n' ) lineno++;
2735 cp++;
2736 }
2737 if( c ) cp++;
2738 continue;
2739 }
2740 ps.tokenstart = cp; /* Mark the beginning of the token */
2741 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2742 if( c=='\"' ){ /* String literals */
2743 cp++;
2744 while( (c= *cp)!=0 && c!='\"' ){
2745 if( c=='\n' ) lineno++;
2746 cp++;
2747 }
2748 if( c==0 ){
2749 ErrorMsg(ps.filename,startline,
2750"String starting on this line is not terminated before the end of the file.");
2751 ps.errorcnt++;
2752 nextcp = cp;
2753 }else{
2754 nextcp = cp+1;
2755 }
2756 }else if( c=='{' ){ /* A block of C code */
2757 int level;
2758 cp++;
2759 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2760 if( c=='\n' ) lineno++;
2761 else if( c=='{' ) level++;
2762 else if( c=='}' ) level--;
2763 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2764 int prevc;
2765 cp = &cp[2];
2766 prevc = 0;
2767 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2768 if( c=='\n' ) lineno++;
2769 prevc = c;
2770 cp++;
drhf2f105d2012-08-20 15:53:54 +00002771 }
2772 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002773 cp = &cp[2];
2774 while( (c= *cp)!=0 && c!='\n' ) cp++;
2775 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002776 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002777 int startchar, prevc;
2778 startchar = c;
2779 prevc = 0;
2780 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2781 if( c=='\n' ) lineno++;
2782 if( prevc=='\\' ) prevc = 0;
2783 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002784 }
2785 }
drh75897232000-05-29 14:26:00 +00002786 }
2787 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002788 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002789"C code starting on this line is not terminated before the end of the file.");
2790 ps.errorcnt++;
2791 nextcp = cp;
2792 }else{
2793 nextcp = cp+1;
2794 }
drhc56fac72015-10-29 13:48:15 +00002795 }else if( ISALNUM(c) ){ /* Identifiers */
2796 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002797 nextcp = cp;
2798 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2799 cp += 3;
2800 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002801 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002802 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002803 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002804 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002805 }else{ /* All other (one character) operators */
2806 cp++;
2807 nextcp = cp;
2808 }
2809 c = *cp;
2810 *cp = 0; /* Null terminate the token */
2811 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002812 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002813 cp = nextcp;
2814 }
2815 free(filebuf); /* Release the buffer after parsing */
2816 gp->rule = ps.firstrule;
2817 gp->errorcnt = ps.errorcnt;
2818}
2819/*************************** From the file "plink.c" *********************/
2820/*
2821** Routines processing configuration follow-set propagation links
2822** in the LEMON parser generator.
2823*/
2824static struct plink *plink_freelist = 0;
2825
2826/* Allocate a new plink */
2827struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002828 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002829
2830 if( plink_freelist==0 ){
2831 int i;
2832 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002833 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002834 if( plink_freelist==0 ){
2835 fprintf(stderr,
2836 "Unable to allocate memory for a new follow-set propagation link.\n");
2837 exit(1);
2838 }
2839 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2840 plink_freelist[amt-1].next = 0;
2841 }
icculus9e44cf12010-02-14 17:14:22 +00002842 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002843 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002844 return newlink;
drh75897232000-05-29 14:26:00 +00002845}
2846
2847/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002848void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002849{
icculus9e44cf12010-02-14 17:14:22 +00002850 struct plink *newlink;
2851 newlink = Plink_new();
2852 newlink->next = *plpp;
2853 *plpp = newlink;
2854 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002855}
2856
2857/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002858void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002859{
2860 struct plink *nextpl;
2861 while( from ){
2862 nextpl = from->next;
2863 from->next = *to;
2864 *to = from;
2865 from = nextpl;
2866 }
2867}
2868
2869/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002870void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002871{
2872 struct plink *nextpl;
2873
2874 while( plp ){
2875 nextpl = plp->next;
2876 plp->next = plink_freelist;
2877 plink_freelist = plp;
2878 plp = nextpl;
2879 }
2880}
2881/*********************** From the file "report.c" **************************/
2882/*
2883** Procedures for generating reports and tables in the LEMON parser generator.
2884*/
2885
2886/* Generate a filename with the given suffix. Space to hold the
2887** name comes from malloc() and must be freed by the calling
2888** function.
2889*/
icculus9e44cf12010-02-14 17:14:22 +00002890PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002891{
2892 char *name;
2893 char *cp;
2894
icculus9e44cf12010-02-14 17:14:22 +00002895 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002896 if( name==0 ){
2897 fprintf(stderr,"Can't allocate space for a filename.\n");
2898 exit(1);
2899 }
drh898799f2014-01-10 23:21:00 +00002900 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002901 cp = strrchr(name,'.');
2902 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002903 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002904 return name;
2905}
2906
2907/* Open a file with a name based on the name of the input file,
2908** but with a different (specified) suffix, and return a pointer
2909** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002910PRIVATE FILE *file_open(
2911 struct lemon *lemp,
2912 const char *suffix,
2913 const char *mode
2914){
drh75897232000-05-29 14:26:00 +00002915 FILE *fp;
2916
2917 if( lemp->outname ) free(lemp->outname);
2918 lemp->outname = file_makename(lemp, suffix);
2919 fp = fopen(lemp->outname,mode);
2920 if( fp==0 && *mode=='w' ){
2921 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2922 lemp->errorcnt++;
2923 return 0;
2924 }
2925 return fp;
2926}
2927
2928/* Duplicate the input file without comments and without actions
2929** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002930void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002931{
2932 struct rule *rp;
2933 struct symbol *sp;
2934 int i, j, maxlen, len, ncolumns, skip;
2935 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2936 maxlen = 10;
2937 for(i=0; i<lemp->nsymbol; i++){
2938 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002939 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002940 if( len>maxlen ) maxlen = len;
2941 }
2942 ncolumns = 76/(maxlen+5);
2943 if( ncolumns<1 ) ncolumns = 1;
2944 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2945 for(i=0; i<skip; i++){
2946 printf("//");
2947 for(j=i; j<lemp->nsymbol; j+=skip){
2948 sp = lemp->symbols[j];
2949 assert( sp->index==j );
2950 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2951 }
2952 printf("\n");
2953 }
2954 for(rp=lemp->rule; rp; rp=rp->next){
2955 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002956 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002957 printf(" ::=");
2958 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002959 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002960 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002961 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002962 for(j=1; j<sp->nsubsym; j++){
2963 printf("|%s", sp->subsym[j]->name);
2964 }
drh61f92cd2014-01-11 03:06:18 +00002965 }else{
2966 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002967 }
2968 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002969 }
2970 printf(".");
2971 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002972 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002973 printf("\n");
2974 }
2975}
2976
drh7e698e92015-09-07 14:22:24 +00002977/* Print a single rule.
2978*/
2979void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00002980 struct symbol *sp;
2981 int i, j;
drh75897232000-05-29 14:26:00 +00002982 fprintf(fp,"%s ::=",rp->lhs->name);
2983 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00002984 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00002985 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002986 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002987 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002988 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002989 for(j=1; j<sp->nsubsym; j++){
2990 fprintf(fp,"|%s",sp->subsym[j]->name);
2991 }
drh61f92cd2014-01-11 03:06:18 +00002992 }else{
2993 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002994 }
drh75897232000-05-29 14:26:00 +00002995 }
2996}
2997
drh7e698e92015-09-07 14:22:24 +00002998/* Print the rule for a configuration.
2999*/
3000void ConfigPrint(FILE *fp, struct config *cfp){
3001 RulePrint(fp, cfp->rp, cfp->dot);
3002}
3003
drh75897232000-05-29 14:26:00 +00003004/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003005#if 0
drh75897232000-05-29 14:26:00 +00003006/* Print a set */
3007PRIVATE void SetPrint(out,set,lemp)
3008FILE *out;
3009char *set;
3010struct lemon *lemp;
3011{
3012 int i;
3013 char *spacer;
3014 spacer = "";
3015 fprintf(out,"%12s[","");
3016 for(i=0; i<lemp->nterminal; i++){
3017 if( SetFind(set,i) ){
3018 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3019 spacer = " ";
3020 }
3021 }
3022 fprintf(out,"]\n");
3023}
3024
3025/* Print a plink chain */
3026PRIVATE void PlinkPrint(out,plp,tag)
3027FILE *out;
3028struct plink *plp;
3029char *tag;
3030{
3031 while( plp ){
drhada354d2005-11-05 15:03:59 +00003032 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003033 ConfigPrint(out,plp->cfp);
3034 fprintf(out,"\n");
3035 plp = plp->next;
3036 }
3037}
3038#endif
3039
3040/* Print an action to the given file descriptor. Return FALSE if
3041** nothing was actually printed.
3042*/
drh7e698e92015-09-07 14:22:24 +00003043int PrintAction(
3044 struct action *ap, /* The action to print */
3045 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003046 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003047){
drh75897232000-05-29 14:26:00 +00003048 int result = 1;
3049 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003050 case SHIFT: {
3051 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003052 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003053 break;
drh7e698e92015-09-07 14:22:24 +00003054 }
3055 case REDUCE: {
3056 struct rule *rp = ap->x.rp;
drh3bd48ab2015-09-07 18:23:37 +00003057 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->index);
3058 RulePrint(fp, rp, -1);
3059 break;
3060 }
3061 case SHIFTREDUCE: {
3062 struct rule *rp = ap->x.rp;
3063 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->index);
3064 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003065 break;
drh7e698e92015-09-07 14:22:24 +00003066 }
drh75897232000-05-29 14:26:00 +00003067 case ACCEPT:
3068 fprintf(fp,"%*s accept",indent,ap->sp->name);
3069 break;
3070 case ERROR:
3071 fprintf(fp,"%*s error",indent,ap->sp->name);
3072 break;
drh9892c5d2007-12-21 00:02:11 +00003073 case SRCONFLICT:
3074 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003075 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh75897232000-05-29 14:26:00 +00003076 indent,ap->sp->name,ap->x.rp->index);
3077 break;
drh9892c5d2007-12-21 00:02:11 +00003078 case SSCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003079 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003080 indent,ap->sp->name,ap->x.stp->statenum);
3081 break;
drh75897232000-05-29 14:26:00 +00003082 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003083 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003084 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003085 indent,ap->sp->name,ap->x.stp->statenum);
3086 }else{
3087 result = 0;
3088 }
3089 break;
drh75897232000-05-29 14:26:00 +00003090 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003091 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003092 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003093 indent,ap->sp->name,ap->x.rp->index);
3094 }else{
3095 result = 0;
3096 }
3097 break;
drh75897232000-05-29 14:26:00 +00003098 case NOT_USED:
3099 result = 0;
3100 break;
3101 }
3102 return result;
3103}
3104
drh3bd48ab2015-09-07 18:23:37 +00003105/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003106void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003107{
3108 int i;
3109 struct state *stp;
3110 struct config *cfp;
3111 struct action *ap;
3112 FILE *fp;
3113
drh2aa6ca42004-09-10 00:14:04 +00003114 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003115 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003116 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003117 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003118 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003119 if( lemp->basisflag ) cfp=stp->bp;
3120 else cfp=stp->cfp;
3121 while( cfp ){
3122 char buf[20];
3123 if( cfp->dot==cfp->rp->nrhs ){
drh898799f2014-01-10 23:21:00 +00003124 lemon_sprintf(buf,"(%d)",cfp->rp->index);
drh75897232000-05-29 14:26:00 +00003125 fprintf(fp," %5s ",buf);
3126 }else{
3127 fprintf(fp," ");
3128 }
3129 ConfigPrint(fp,cfp);
3130 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003131#if 0
drh75897232000-05-29 14:26:00 +00003132 SetPrint(fp,cfp->fws,lemp);
3133 PlinkPrint(fp,cfp->fplp,"To ");
3134 PlinkPrint(fp,cfp->bplp,"From");
3135#endif
3136 if( lemp->basisflag ) cfp=cfp->bp;
3137 else cfp=cfp->next;
3138 }
3139 fprintf(fp,"\n");
3140 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003141 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003142 }
3143 fprintf(fp,"\n");
3144 }
drhe9278182007-07-18 18:16:29 +00003145 fprintf(fp, "----------------------------------------------------\n");
3146 fprintf(fp, "Symbols:\n");
3147 for(i=0; i<lemp->nsymbol; i++){
3148 int j;
3149 struct symbol *sp;
3150
3151 sp = lemp->symbols[i];
3152 fprintf(fp, " %3d: %s", i, sp->name);
3153 if( sp->type==NONTERMINAL ){
3154 fprintf(fp, ":");
3155 if( sp->lambda ){
3156 fprintf(fp, " <lambda>");
3157 }
3158 for(j=0; j<lemp->nterminal; j++){
3159 if( sp->firstset && SetFind(sp->firstset, j) ){
3160 fprintf(fp, " %s", lemp->symbols[j]->name);
3161 }
3162 }
3163 }
3164 fprintf(fp, "\n");
3165 }
drh75897232000-05-29 14:26:00 +00003166 fclose(fp);
3167 return;
3168}
3169
3170/* Search for the file "name" which is in the same directory as
3171** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003172PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003173{
icculus9e44cf12010-02-14 17:14:22 +00003174 const char *pathlist;
3175 char *pathbufptr;
3176 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003177 char *path,*cp;
3178 char c;
drh75897232000-05-29 14:26:00 +00003179
3180#ifdef __WIN32__
3181 cp = strrchr(argv0,'\\');
3182#else
3183 cp = strrchr(argv0,'/');
3184#endif
3185 if( cp ){
3186 c = *cp;
3187 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003188 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003189 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003190 *cp = c;
3191 }else{
drh75897232000-05-29 14:26:00 +00003192 pathlist = getenv("PATH");
3193 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003194 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003195 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003196 if( (pathbuf != 0) && (path!=0) ){
3197 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003198 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003199 while( *pathbuf ){
3200 cp = strchr(pathbuf,':');
3201 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003202 c = *cp;
3203 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003204 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003205 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003206 if( c==0 ) pathbuf[0] = 0;
3207 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003208 if( access(path,modemask)==0 ) break;
3209 }
icculus9e44cf12010-02-14 17:14:22 +00003210 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003211 }
3212 }
3213 return path;
3214}
3215
3216/* Given an action, compute the integer value for that action
3217** which is to be put in the action table of the generated machine.
3218** Return negative if no action should be generated.
3219*/
icculus9e44cf12010-02-14 17:14:22 +00003220PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003221{
3222 int act;
3223 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003224 case SHIFT: act = ap->x.stp->statenum; break;
3225 case SHIFTREDUCE: act = ap->x.rp->index + lemp->nstate; break;
3226 case REDUCE: act = ap->x.rp->index + lemp->nstate+lemp->nrule; break;
3227 case ERROR: act = lemp->nstate + lemp->nrule*2; break;
3228 case ACCEPT: act = lemp->nstate + lemp->nrule*2 + 1; break;
drh75897232000-05-29 14:26:00 +00003229 default: act = -1; break;
3230 }
3231 return act;
3232}
3233
3234#define LINESIZE 1000
3235/* The next cluster of routines are for reading the template file
3236** and writing the results to the generated parser */
3237/* The first function transfers data from "in" to "out" until
3238** a line is seen which begins with "%%". The line number is
3239** tracked.
3240**
3241** if name!=0, then any word that begin with "Parse" is changed to
3242** begin with *name instead.
3243*/
icculus9e44cf12010-02-14 17:14:22 +00003244PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003245{
3246 int i, iStart;
3247 char line[LINESIZE];
3248 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3249 (*lineno)++;
3250 iStart = 0;
3251 if( name ){
3252 for(i=0; line[i]; i++){
3253 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003254 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003255 ){
3256 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3257 fprintf(out,"%s",name);
3258 i += 4;
3259 iStart = i+1;
3260 }
3261 }
3262 }
3263 fprintf(out,"%s",&line[iStart]);
3264 }
3265}
3266
3267/* The next function finds the template file and opens it, returning
3268** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003269PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003270{
3271 static char templatename[] = "lempar.c";
3272 char buf[1000];
3273 FILE *in;
3274 char *tpltname;
3275 char *cp;
3276
icculus3e143bd2010-02-14 00:48:49 +00003277 /* first, see if user specified a template filename on the command line. */
3278 if (user_templatename != 0) {
3279 if( access(user_templatename,004)==-1 ){
3280 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3281 user_templatename);
3282 lemp->errorcnt++;
3283 return 0;
3284 }
3285 in = fopen(user_templatename,"rb");
3286 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003287 fprintf(stderr,"Can't open the template file \"%s\".\n",
3288 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003289 lemp->errorcnt++;
3290 return 0;
3291 }
3292 return in;
3293 }
3294
drh75897232000-05-29 14:26:00 +00003295 cp = strrchr(lemp->filename,'.');
3296 if( cp ){
drh898799f2014-01-10 23:21:00 +00003297 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003298 }else{
drh898799f2014-01-10 23:21:00 +00003299 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003300 }
3301 if( access(buf,004)==0 ){
3302 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003303 }else if( access(templatename,004)==0 ){
3304 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003305 }else{
3306 tpltname = pathsearch(lemp->argv0,templatename,0);
3307 }
3308 if( tpltname==0 ){
3309 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3310 templatename);
3311 lemp->errorcnt++;
3312 return 0;
3313 }
drh2aa6ca42004-09-10 00:14:04 +00003314 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003315 if( in==0 ){
3316 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3317 lemp->errorcnt++;
3318 return 0;
3319 }
3320 return in;
3321}
3322
drhaf805ca2004-09-07 11:28:25 +00003323/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003324PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003325{
3326 fprintf(out,"#line %d \"",lineno);
3327 while( *filename ){
3328 if( *filename == '\\' ) putc('\\',out);
3329 putc(*filename,out);
3330 filename++;
3331 }
3332 fprintf(out,"\"\n");
3333}
3334
drh75897232000-05-29 14:26:00 +00003335/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003336PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003337{
3338 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003339 while( *str ){
drh75897232000-05-29 14:26:00 +00003340 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003341 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003342 str++;
3343 }
drh9db55df2004-09-09 14:01:21 +00003344 if( str[-1]!='\n' ){
3345 putc('\n',out);
3346 (*lineno)++;
3347 }
shane58543932008-12-10 20:10:04 +00003348 if (!lemp->nolinenosflag) {
3349 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3350 }
drh75897232000-05-29 14:26:00 +00003351 return;
3352}
3353
3354/*
3355** The following routine emits code for the destructor for the
3356** symbol sp
3357*/
icculus9e44cf12010-02-14 17:14:22 +00003358void emit_destructor_code(
3359 FILE *out,
3360 struct symbol *sp,
3361 struct lemon *lemp,
3362 int *lineno
3363){
drhcc83b6e2004-04-23 23:38:42 +00003364 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003365
drh75897232000-05-29 14:26:00 +00003366 if( sp->type==TERMINAL ){
3367 cp = lemp->tokendest;
3368 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003369 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003370 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003371 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003372 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003373 if( !lemp->nolinenosflag ){
3374 (*lineno)++;
3375 tplt_linedir(out,sp->destLineno,lemp->filename);
3376 }
drh960e8c62001-04-03 16:53:21 +00003377 }else if( lemp->vardest ){
3378 cp = lemp->vardest;
3379 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003380 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003381 }else{
3382 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003383 }
3384 for(; *cp; cp++){
3385 if( *cp=='$' && cp[1]=='$' ){
3386 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3387 cp++;
3388 continue;
3389 }
shane58543932008-12-10 20:10:04 +00003390 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003391 fputc(*cp,out);
3392 }
shane58543932008-12-10 20:10:04 +00003393 fprintf(out,"\n"); (*lineno)++;
3394 if (!lemp->nolinenosflag) {
3395 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3396 }
3397 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003398 return;
3399}
3400
3401/*
drh960e8c62001-04-03 16:53:21 +00003402** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003403*/
icculus9e44cf12010-02-14 17:14:22 +00003404int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003405{
3406 int ret;
3407 if( sp->type==TERMINAL ){
3408 ret = lemp->tokendest!=0;
3409 }else{
drh960e8c62001-04-03 16:53:21 +00003410 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003411 }
3412 return ret;
3413}
3414
drh0bb132b2004-07-20 14:06:51 +00003415/*
3416** Append text to a dynamically allocated string. If zText is 0 then
3417** reset the string to be empty again. Always return the complete text
3418** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003419**
3420** n bytes of zText are stored. If n==0 then all of zText up to the first
3421** \000 terminator is stored. zText can contain up to two instances of
3422** %d. The values of p1 and p2 are written into the first and second
3423** %d.
3424**
3425** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003426*/
icculus9e44cf12010-02-14 17:14:22 +00003427PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3428 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003429 static char *z = 0;
3430 static int alloced = 0;
3431 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003432 int c;
drh0bb132b2004-07-20 14:06:51 +00003433 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003434 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003435 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003436 used = 0;
3437 return z;
3438 }
drh7ac25c72004-08-19 15:12:26 +00003439 if( n<=0 ){
3440 if( n<0 ){
3441 used += n;
3442 assert( used>=0 );
3443 }
drh87cf1372008-08-13 20:09:06 +00003444 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003445 }
drhdf609712010-11-23 20:55:27 +00003446 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003447 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003448 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003449 }
icculus9e44cf12010-02-14 17:14:22 +00003450 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003451 while( n-- > 0 ){
3452 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003453 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003454 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003455 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003456 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003457 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003458 zText++;
3459 n--;
3460 }else{
mistachkin2318d332015-01-12 18:02:52 +00003461 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003462 }
3463 }
3464 z[used] = 0;
3465 return z;
3466}
3467
3468/*
3469** zCode is a string that is the action associated with a rule. Expand
3470** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003471** stack.
drhdabd04c2016-02-17 01:46:19 +00003472**
3473** Return 1 if the expanded code requires that "yylhsminor" local variable
3474** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003475*/
drhdabd04c2016-02-17 01:46:19 +00003476PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003477 char *cp, *xp;
3478 int i;
drhcf82f0d2016-02-17 04:33:10 +00003479 int rc = 0; /* True if yylhsminor is used */
3480 const char *zSkip = 0; /* The zOvwrt comment within rp->code, or NULL */
3481 char lhsused = 0; /* True if the LHS element has been used */
3482 char lhsdirect; /* True if LHS writes directly into stack */
3483 char used[MAXRHS]; /* True for each RHS element which is used */
3484 char zLhs[50]; /* Convert the LHS symbol into this string */
3485 char zOvwrt[900]; /* Comment that to allow LHS to overwrite RHS */
drh0bb132b2004-07-20 14:06:51 +00003486
3487 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3488 lhsused = 0;
3489
drh19c9e562007-03-29 20:13:53 +00003490 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003491 static char newlinestr[2] = { '\n', '\0' };
3492 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003493 rp->line = rp->ruleline;
3494 }
3495
drh4dd0d3f2016-02-17 01:18:33 +00003496
3497 if( rp->lhsalias==0 ){
3498 /* There is no LHS value symbol. */
3499 lhsdirect = 1;
3500 }else if( rp->nrhs==0 ){
3501 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3502 lhsdirect = 1;
3503 }else if( rp->rhsalias[0]==0 ){
3504 /* The left-most RHS symbol has not value. LHS direct is ok. But
3505 ** we have to call the distructor on the RHS symbol first. */
3506 lhsdirect = 1;
3507 if( has_destructor(rp->rhs[0],lemp) ){
3508 append_str(0,0,0,0);
3509 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3510 rp->rhs[0]->index,1-rp->nrhs);
3511 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3512 }
3513 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3514 /* The LHS symbol and the left-most RHS symbol are the same, so
3515 ** direct writing is allowed */
3516 lhsdirect = 1;
3517 lhsused = 1;
3518 used[0] = 1;
3519 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3520 ErrorMsg(lemp->filename,rp->ruleline,
3521 "%s(%s) and %s(%s) share the same label but have "
3522 "different datatypes.",
3523 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3524 lemp->errorcnt++;
3525 }
3526 }else{
drhcf82f0d2016-02-17 04:33:10 +00003527 lemon_sprintf(zOvwrt, "/*%s-overwrites-%s*/",
3528 rp->lhsalias, rp->rhsalias[0]);
3529 zSkip = strstr(rp->code, zOvwrt);
3530 if( zSkip!=0 ){
3531 /* The code contains a special comment that indicates that it is safe
3532 ** for the LHS label to overwrite left-most RHS label. */
3533 lhsdirect = 1;
3534 }else{
3535 lhsdirect = 0;
3536 }
drh4dd0d3f2016-02-17 01:18:33 +00003537 }
3538 if( lhsdirect ){
3539 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3540 }else{
drhdabd04c2016-02-17 01:46:19 +00003541 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003542 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3543 }
3544
drh0bb132b2004-07-20 14:06:51 +00003545 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003546
3547 /* This const cast is wrong but harmless, if we're careful. */
3548 for(cp=(char *)rp->code; *cp; cp++){
drhcf82f0d2016-02-17 04:33:10 +00003549 if( cp==zSkip ){
3550 append_str(zOvwrt,0,0,0);
3551 cp += lemonStrlen(zOvwrt)-1;
3552 continue;
3553 }
drhc56fac72015-10-29 13:48:15 +00003554 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003555 char saved;
drhc56fac72015-10-29 13:48:15 +00003556 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003557 saved = *xp;
3558 *xp = 0;
3559 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003560 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003561 cp = xp;
3562 lhsused = 1;
3563 }else{
3564 for(i=0; i<rp->nrhs; i++){
3565 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003566 if( cp!=rp->code && cp[-1]=='@' ){
3567 /* If the argument is of the form @X then substituted
3568 ** the token number of X, not the value of X */
3569 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3570 }else{
drhfd405312005-11-06 04:06:59 +00003571 struct symbol *sp = rp->rhs[i];
3572 int dtnum;
3573 if( sp->type==MULTITERMINAL ){
3574 dtnum = sp->subsym[0]->dtnum;
3575 }else{
3576 dtnum = sp->dtnum;
3577 }
3578 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003579 }
drh0bb132b2004-07-20 14:06:51 +00003580 cp = xp;
3581 used[i] = 1;
3582 break;
3583 }
3584 }
3585 }
3586 *xp = saved;
3587 }
3588 append_str(cp, 1, 0, 0);
3589 } /* End loop */
3590
drh4dd0d3f2016-02-17 01:18:33 +00003591 /* Main code generation completed */
3592 cp = append_str(0,0,0,0);
3593 if( cp && cp[0] ) rp->code = Strsafe(cp);
3594 append_str(0,0,0,0);
3595
drh0bb132b2004-07-20 14:06:51 +00003596 /* Check to make sure the LHS has been used */
3597 if( rp->lhsalias && !lhsused ){
3598 ErrorMsg(lemp->filename,rp->ruleline,
3599 "Label \"%s\" for \"%s(%s)\" is never used.",
3600 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3601 lemp->errorcnt++;
3602 }
3603
drh4dd0d3f2016-02-17 01:18:33 +00003604 /* Generate destructor code for RHS minor values which are not referenced.
3605 ** Generate error messages for unused labels and duplicate labels.
3606 */
drh0bb132b2004-07-20 14:06:51 +00003607 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003608 if( rp->rhsalias[i] ){
3609 if( i>0 ){
3610 int j;
3611 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3612 ErrorMsg(lemp->filename,rp->ruleline,
3613 "%s(%s) has the same label as the LHS but is not the left-most "
3614 "symbol on the RHS.",
3615 rp->rhs[i]->name, rp->rhsalias);
3616 lemp->errorcnt++;
3617 }
3618 for(j=0; j<i; j++){
3619 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3620 ErrorMsg(lemp->filename,rp->ruleline,
3621 "Label %s used for multiple symbols on the RHS of a rule.",
3622 rp->rhsalias[i]);
3623 lemp->errorcnt++;
3624 break;
3625 }
3626 }
drh0bb132b2004-07-20 14:06:51 +00003627 }
drh4dd0d3f2016-02-17 01:18:33 +00003628 if( !used[i] ){
3629 ErrorMsg(lemp->filename,rp->ruleline,
3630 "Label %s for \"%s(%s)\" is never used.",
3631 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3632 lemp->errorcnt++;
3633 }
3634 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3635 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3636 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003637 }
3638 }
drh4dd0d3f2016-02-17 01:18:33 +00003639
3640 /* If unable to write LHS values directly into the stack, write the
3641 ** saved LHS value now. */
3642 if( lhsdirect==0 ){
3643 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3644 append_str(zLhs, 0, 0, 0);
3645 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003646 }
drh4dd0d3f2016-02-17 01:18:33 +00003647
3648 /* Suffix code generation complete */
3649 cp = append_str(0,0,0,0);
3650 if( cp ) rp->codeSuffix = Strsafe(cp);
drhdabd04c2016-02-17 01:46:19 +00003651
3652 return rc;
drh0bb132b2004-07-20 14:06:51 +00003653}
3654
drh75897232000-05-29 14:26:00 +00003655/*
3656** Generate code which executes when the rule "rp" is reduced. Write
3657** the code to "out". Make sure lineno stays up-to-date.
3658*/
icculus9e44cf12010-02-14 17:14:22 +00003659PRIVATE void emit_code(
3660 FILE *out,
3661 struct rule *rp,
3662 struct lemon *lemp,
3663 int *lineno
3664){
3665 const char *cp;
drh75897232000-05-29 14:26:00 +00003666
drh4dd0d3f2016-02-17 01:18:33 +00003667 /* Setup code prior to the #line directive */
3668 if( rp->codePrefix && rp->codePrefix[0] ){
3669 fprintf(out, "{%s", rp->codePrefix);
3670 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3671 }
3672
drh75897232000-05-29 14:26:00 +00003673 /* Generate code to do the reduce action */
3674 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003675 if( !lemp->nolinenosflag ){
3676 (*lineno)++;
3677 tplt_linedir(out,rp->line,lemp->filename);
3678 }
drhaf805ca2004-09-07 11:28:25 +00003679 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003680 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003681 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003682 if( !lemp->nolinenosflag ){
3683 (*lineno)++;
3684 tplt_linedir(out,*lineno,lemp->outname);
3685 }
drh4dd0d3f2016-02-17 01:18:33 +00003686 }
3687
3688 /* Generate breakdown code that occurs after the #line directive */
3689 if( rp->codeSuffix && rp->codeSuffix[0] ){
3690 fprintf(out, "%s", rp->codeSuffix);
3691 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3692 }
3693
3694 if( rp->codePrefix ){
3695 fprintf(out, "}\n"); (*lineno)++;
3696 }
drh75897232000-05-29 14:26:00 +00003697
drh75897232000-05-29 14:26:00 +00003698 return;
3699}
3700
3701/*
3702** Print the definition of the union used for the parser's data stack.
3703** This union contains fields for every possible data type for tokens
3704** and nonterminals. In the process of computing and printing this
3705** union, also set the ".dtnum" field of every terminal and nonterminal
3706** symbol.
3707*/
icculus9e44cf12010-02-14 17:14:22 +00003708void print_stack_union(
3709 FILE *out, /* The output stream */
3710 struct lemon *lemp, /* The main info structure for this parser */
3711 int *plineno, /* Pointer to the line number */
3712 int mhflag /* True if generating makeheaders output */
3713){
drh75897232000-05-29 14:26:00 +00003714 int lineno = *plineno; /* The line number of the output */
3715 char **types; /* A hash table of datatypes */
3716 int arraysize; /* Size of the "types" array */
3717 int maxdtlength; /* Maximum length of any ".datatype" field. */
3718 char *stddt; /* Standardized name for a datatype */
3719 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003720 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003721 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003722
3723 /* Allocate and initialize types[] and allocate stddt[] */
3724 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003725 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003726 if( types==0 ){
3727 fprintf(stderr,"Out of memory.\n");
3728 exit(1);
3729 }
drh75897232000-05-29 14:26:00 +00003730 for(i=0; i<arraysize; i++) types[i] = 0;
3731 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003732 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003733 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003734 }
drh75897232000-05-29 14:26:00 +00003735 for(i=0; i<lemp->nsymbol; i++){
3736 int len;
3737 struct symbol *sp = lemp->symbols[i];
3738 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003739 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003740 if( len>maxdtlength ) maxdtlength = len;
3741 }
3742 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003743 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003744 fprintf(stderr,"Out of memory.\n");
3745 exit(1);
3746 }
3747
3748 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3749 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003750 ** used for terminal symbols. If there is no %default_type defined then
3751 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3752 ** a datatype using the %type directive.
3753 */
drh75897232000-05-29 14:26:00 +00003754 for(i=0; i<lemp->nsymbol; i++){
3755 struct symbol *sp = lemp->symbols[i];
3756 char *cp;
3757 if( sp==lemp->errsym ){
3758 sp->dtnum = arraysize+1;
3759 continue;
3760 }
drh960e8c62001-04-03 16:53:21 +00003761 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003762 sp->dtnum = 0;
3763 continue;
3764 }
3765 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003766 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003767 j = 0;
drhc56fac72015-10-29 13:48:15 +00003768 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003769 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003770 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003771 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003772 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003773 sp->dtnum = 0;
3774 continue;
3775 }
drh75897232000-05-29 14:26:00 +00003776 hash = 0;
3777 for(j=0; stddt[j]; j++){
3778 hash = hash*53 + stddt[j];
3779 }
drh3b2129c2003-05-13 00:34:21 +00003780 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003781 while( types[hash] ){
3782 if( strcmp(types[hash],stddt)==0 ){
3783 sp->dtnum = hash + 1;
3784 break;
3785 }
3786 hash++;
drh2b51f212013-10-11 23:01:02 +00003787 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003788 }
3789 if( types[hash]==0 ){
3790 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003791 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003792 if( types[hash]==0 ){
3793 fprintf(stderr,"Out of memory.\n");
3794 exit(1);
3795 }
drh898799f2014-01-10 23:21:00 +00003796 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003797 }
3798 }
3799
3800 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3801 name = lemp->name ? lemp->name : "Parse";
3802 lineno = *plineno;
3803 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3804 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3805 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3806 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3807 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003808 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003809 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3810 for(i=0; i<arraysize; i++){
3811 if( types[i]==0 ) continue;
3812 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3813 free(types[i]);
3814 }
drhc4dd3fd2008-01-22 01:48:05 +00003815 if( lemp->errsym->useCnt ){
3816 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3817 }
drh75897232000-05-29 14:26:00 +00003818 free(stddt);
3819 free(types);
3820 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3821 *plineno = lineno;
3822}
3823
drhb29b0a52002-02-23 19:39:46 +00003824/*
3825** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003826** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3827** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003828*/
drhc75e0162015-09-07 02:23:02 +00003829static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3830 const char *zType = "int";
3831 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003832 if( lwr>=0 ){
3833 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003834 zType = "unsigned char";
3835 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003836 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003837 zType = "unsigned short int";
3838 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003839 }else{
drhc75e0162015-09-07 02:23:02 +00003840 zType = "unsigned int";
3841 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003842 }
3843 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003844 zType = "signed char";
3845 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003846 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003847 zType = "short";
3848 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003849 }
drhc75e0162015-09-07 02:23:02 +00003850 if( pnByte ) *pnByte = nByte;
3851 return zType;
drhb29b0a52002-02-23 19:39:46 +00003852}
3853
drhfdbf9282003-10-21 16:34:41 +00003854/*
3855** Each state contains a set of token transaction and a set of
3856** nonterminal transactions. Each of these sets makes an instance
3857** of the following structure. An array of these structures is used
3858** to order the creation of entries in the yy_action[] table.
3859*/
3860struct axset {
3861 struct state *stp; /* A pointer to a state */
3862 int isTkn; /* True to use tokens. False for non-terminals */
3863 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003864 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003865};
3866
3867/*
3868** Compare to axset structures for sorting purposes
3869*/
3870static int axset_compare(const void *a, const void *b){
3871 struct axset *p1 = (struct axset*)a;
3872 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003873 int c;
3874 c = p2->nAction - p1->nAction;
3875 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003876 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003877 }
3878 assert( c!=0 || p1==p2 );
3879 return c;
drhfdbf9282003-10-21 16:34:41 +00003880}
3881
drhc4dd3fd2008-01-22 01:48:05 +00003882/*
3883** Write text on "out" that describes the rule "rp".
3884*/
3885static void writeRuleText(FILE *out, struct rule *rp){
3886 int j;
3887 fprintf(out,"%s ::=", rp->lhs->name);
3888 for(j=0; j<rp->nrhs; j++){
3889 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003890 if( sp->type!=MULTITERMINAL ){
3891 fprintf(out," %s", sp->name);
3892 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003893 int k;
drh61f92cd2014-01-11 03:06:18 +00003894 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003895 for(k=1; k<sp->nsubsym; k++){
3896 fprintf(out,"|%s",sp->subsym[k]->name);
3897 }
3898 }
3899 }
3900}
3901
3902
drh75897232000-05-29 14:26:00 +00003903/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003904void ReportTable(
3905 struct lemon *lemp,
3906 int mhflag /* Output in makeheaders format if true */
3907){
drh75897232000-05-29 14:26:00 +00003908 FILE *out, *in;
3909 char line[LINESIZE];
3910 int lineno;
3911 struct state *stp;
3912 struct action *ap;
3913 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003914 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003915 int i, j, n, sz;
3916 int szActionType; /* sizeof(YYACTIONTYPE) */
3917 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003918 const char *name;
drh8b582012003-10-21 13:16:03 +00003919 int mnTknOfst, mxTknOfst;
3920 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003921 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003922
3923 in = tplt_open(lemp);
3924 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003925 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003926 if( out==0 ){
3927 fclose(in);
3928 return;
3929 }
3930 lineno = 1;
3931 tplt_xfer(lemp->name,in,out,&lineno);
3932
3933 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003934 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003935 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00003936 char *incName = file_makename(lemp, ".h");
3937 fprintf(out,"#include \"%s\"\n", incName); lineno++;
3938 free(incName);
drh75897232000-05-29 14:26:00 +00003939 }
3940 tplt_xfer(lemp->name,in,out,&lineno);
3941
3942 /* Generate #defines for all tokens */
3943 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003944 const char *prefix;
drh75897232000-05-29 14:26:00 +00003945 fprintf(out,"#if INTERFACE\n"); lineno++;
3946 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3947 else prefix = "";
3948 for(i=1; i<lemp->nterminal; i++){
3949 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3950 lineno++;
3951 }
3952 fprintf(out,"#endif\n"); lineno++;
3953 }
3954 tplt_xfer(lemp->name,in,out,&lineno);
3955
3956 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003957 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00003958 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00003959 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3960 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00003961 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003962 if( lemp->wildcard ){
3963 fprintf(out,"#define YYWILDCARD %d\n",
3964 lemp->wildcard->index); lineno++;
3965 }
drh75897232000-05-29 14:26:00 +00003966 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003967 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003968 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003969 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3970 }else{
3971 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3972 }
drhca44b5a2007-02-22 23:06:58 +00003973 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003974 if( mhflag ){
3975 fprintf(out,"#if INTERFACE\n"); lineno++;
3976 }
3977 name = lemp->name ? lemp->name : "Parse";
3978 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00003979 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00003980 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
3981 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003982 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3983 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3984 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3985 name,lemp->arg,&lemp->arg[i]); lineno++;
3986 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3987 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003988 }else{
drh1f245e42002-03-11 13:55:50 +00003989 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3990 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3991 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3992 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003993 }
3994 if( mhflag ){
3995 fprintf(out,"#endif\n"); lineno++;
3996 }
drhc4dd3fd2008-01-22 01:48:05 +00003997 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00003998 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3999 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00004000 }
drh0bd1f4e2002-06-06 18:54:39 +00004001 if( lemp->has_fallback ){
4002 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
4003 }
drh75897232000-05-29 14:26:00 +00004004
drh3bd48ab2015-09-07 18:23:37 +00004005 /* Compute the action table, but do not output it yet. The action
4006 ** table must be computed before generating the YYNSTATE macro because
4007 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00004008 */
drh3bd48ab2015-09-07 18:23:37 +00004009 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00004010 if( ax==0 ){
4011 fprintf(stderr,"malloc failed\n");
4012 exit(1);
4013 }
drh3bd48ab2015-09-07 18:23:37 +00004014 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00004015 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004016 ax[i*2].stp = stp;
4017 ax[i*2].isTkn = 1;
4018 ax[i*2].nAction = stp->nTknAct;
4019 ax[i*2+1].stp = stp;
4020 ax[i*2+1].isTkn = 0;
4021 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004022 }
drh8b582012003-10-21 13:16:03 +00004023 mxTknOfst = mnTknOfst = 0;
4024 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004025 /* In an effort to minimize the action table size, use the heuristic
4026 ** of placing the largest action sets first */
4027 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4028 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004029 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004030 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004031 stp = ax[i].stp;
4032 if( ax[i].isTkn ){
4033 for(ap=stp->ap; ap; ap=ap->next){
4034 int action;
4035 if( ap->sp->index>=lemp->nterminal ) continue;
4036 action = compute_action(lemp, ap);
4037 if( action<0 ) continue;
4038 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004039 }
drhfdbf9282003-10-21 16:34:41 +00004040 stp->iTknOfst = acttab_insert(pActtab);
4041 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4042 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4043 }else{
4044 for(ap=stp->ap; ap; ap=ap->next){
4045 int action;
4046 if( ap->sp->index<lemp->nterminal ) continue;
4047 if( ap->sp->index==lemp->nsymbol ) continue;
4048 action = compute_action(lemp, ap);
4049 if( action<0 ) continue;
4050 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004051 }
drhfdbf9282003-10-21 16:34:41 +00004052 stp->iNtOfst = acttab_insert(pActtab);
4053 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4054 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004055 }
drh337cd0d2015-09-07 23:40:42 +00004056#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4057 { int jj, nn;
4058 for(jj=nn=0; jj<pActtab->nAction; jj++){
4059 if( pActtab->aAction[jj].action<0 ) nn++;
4060 }
4061 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4062 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4063 ax[i].nAction, pActtab->nAction, nn);
4064 }
4065#endif
drh8b582012003-10-21 13:16:03 +00004066 }
drhfdbf9282003-10-21 16:34:41 +00004067 free(ax);
drh8b582012003-10-21 13:16:03 +00004068
drh3bd48ab2015-09-07 18:23:37 +00004069 /* Finish rendering the constants now that the action table has
4070 ** been computed */
4071 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4072 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004073 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004074 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4075 i = lemp->nstate + lemp->nrule;
4076 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4077 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
4078 i = lemp->nstate + lemp->nrule*2;
4079 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4080 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
4081 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
4082 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
4083 tplt_xfer(lemp->name,in,out,&lineno);
4084
4085 /* Now output the action table and its associates:
4086 **
4087 ** yy_action[] A single table containing all actions.
4088 ** yy_lookahead[] A table containing the lookahead for each entry in
4089 ** yy_action. Used to detect hash collisions.
4090 ** yy_shift_ofst[] For each state, the offset into yy_action for
4091 ** shifting terminals.
4092 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4093 ** shifting non-terminals after a reduce.
4094 ** yy_default[] Default action for each state.
4095 */
4096
drh8b582012003-10-21 13:16:03 +00004097 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004098 lemp->nactiontab = n = acttab_size(pActtab);
4099 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004100 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4101 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004102 for(i=j=0; i<n; i++){
4103 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00004104 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00004105 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004106 fprintf(out, " %4d,", action);
4107 if( j==9 || i==n-1 ){
4108 fprintf(out, "\n"); lineno++;
4109 j = 0;
4110 }else{
4111 j++;
4112 }
4113 }
4114 fprintf(out, "};\n"); lineno++;
4115
4116 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004117 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004118 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004119 for(i=j=0; i<n; i++){
4120 int la = acttab_yylookahead(pActtab, i);
4121 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004122 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004123 fprintf(out, " %4d,", la);
4124 if( j==9 || i==n-1 ){
4125 fprintf(out, "\n"); lineno++;
4126 j = 0;
4127 }else{
4128 j++;
4129 }
4130 }
4131 fprintf(out, "};\n"); lineno++;
4132
4133 /* Output the yy_shift_ofst[] table */
4134 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004135 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004136 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004137 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4138 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4139 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004140 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004141 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4142 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004143 for(i=j=0; i<n; i++){
4144 int ofst;
4145 stp = lemp->sorted[i];
4146 ofst = stp->iTknOfst;
4147 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004148 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004149 fprintf(out, " %4d,", ofst);
4150 if( j==9 || i==n-1 ){
4151 fprintf(out, "\n"); lineno++;
4152 j = 0;
4153 }else{
4154 j++;
4155 }
4156 }
4157 fprintf(out, "};\n"); lineno++;
4158
4159 /* Output the yy_reduce_ofst[] table */
4160 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004161 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004162 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004163 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4164 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4165 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004166 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004167 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4168 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004169 for(i=j=0; i<n; i++){
4170 int ofst;
4171 stp = lemp->sorted[i];
4172 ofst = stp->iNtOfst;
4173 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004174 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004175 fprintf(out, " %4d,", ofst);
4176 if( j==9 || i==n-1 ){
4177 fprintf(out, "\n"); lineno++;
4178 j = 0;
4179 }else{
4180 j++;
4181 }
4182 }
4183 fprintf(out, "};\n"); lineno++;
4184
4185 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004186 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004187 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004188 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004189 for(i=j=0; i<n; i++){
4190 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004191 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004192 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004193 if( j==9 || i==n-1 ){
4194 fprintf(out, "\n"); lineno++;
4195 j = 0;
4196 }else{
4197 j++;
4198 }
4199 }
4200 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004201 tplt_xfer(lemp->name,in,out,&lineno);
4202
drh0bd1f4e2002-06-06 18:54:39 +00004203 /* Generate the table of fallback tokens.
4204 */
4205 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004206 int mx = lemp->nterminal - 1;
4207 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004208 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004209 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004210 struct symbol *p = lemp->symbols[i];
4211 if( p->fallback==0 ){
4212 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4213 }else{
4214 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4215 p->name, p->fallback->name);
4216 }
4217 lineno++;
4218 }
4219 }
4220 tplt_xfer(lemp->name, in, out, &lineno);
4221
4222 /* Generate a table containing the symbolic name of every symbol
4223 */
drh75897232000-05-29 14:26:00 +00004224 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004225 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004226 fprintf(out," %-15s",line);
4227 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4228 }
4229 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4230 tplt_xfer(lemp->name,in,out,&lineno);
4231
drh0bd1f4e2002-06-06 18:54:39 +00004232 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004233 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004234 ** when tracing REDUCE actions.
4235 */
4236 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4237 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004238 fprintf(out," /* %3d */ \"", i);
4239 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004240 fprintf(out,"\",\n"); lineno++;
4241 }
4242 tplt_xfer(lemp->name,in,out,&lineno);
4243
drh75897232000-05-29 14:26:00 +00004244 /* Generate code which executes every time a symbol is popped from
4245 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004246 ** (In other words, generate the %destructor actions)
4247 */
drh75897232000-05-29 14:26:00 +00004248 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004249 int once = 1;
drh75897232000-05-29 14:26:00 +00004250 for(i=0; i<lemp->nsymbol; i++){
4251 struct symbol *sp = lemp->symbols[i];
4252 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004253 if( once ){
4254 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4255 once = 0;
4256 }
drhc53eed12009-06-12 17:46:19 +00004257 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004258 }
4259 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4260 if( i<lemp->nsymbol ){
4261 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4262 fprintf(out," break;\n"); lineno++;
4263 }
4264 }
drh8d659732005-01-13 23:54:06 +00004265 if( lemp->vardest ){
4266 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004267 int once = 1;
drh8d659732005-01-13 23:54:06 +00004268 for(i=0; i<lemp->nsymbol; i++){
4269 struct symbol *sp = lemp->symbols[i];
4270 if( sp==0 || sp->type==TERMINAL ||
4271 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004272 if( once ){
4273 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4274 once = 0;
4275 }
drhc53eed12009-06-12 17:46:19 +00004276 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004277 dflt_sp = sp;
4278 }
4279 if( dflt_sp!=0 ){
4280 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004281 }
drh4dc8ef52008-07-01 17:13:57 +00004282 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004283 }
drh75897232000-05-29 14:26:00 +00004284 for(i=0; i<lemp->nsymbol; i++){
4285 struct symbol *sp = lemp->symbols[i];
4286 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004287 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004288
4289 /* Combine duplicate destructors into a single case */
4290 for(j=i+1; j<lemp->nsymbol; j++){
4291 struct symbol *sp2 = lemp->symbols[j];
4292 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4293 && sp2->dtnum==sp->dtnum
4294 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004295 fprintf(out," case %d: /* %s */\n",
4296 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004297 sp2->destructor = 0;
4298 }
4299 }
4300
drh75897232000-05-29 14:26:00 +00004301 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4302 fprintf(out," break;\n"); lineno++;
4303 }
drh75897232000-05-29 14:26:00 +00004304 tplt_xfer(lemp->name,in,out,&lineno);
4305
4306 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004307 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004308 tplt_xfer(lemp->name,in,out,&lineno);
4309
4310 /* Generate the table of rule information
4311 **
4312 ** Note: This code depends on the fact that rules are number
4313 ** sequentually beginning with 0.
4314 */
4315 for(rp=lemp->rule; rp; rp=rp->next){
4316 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4317 }
4318 tplt_xfer(lemp->name,in,out,&lineno);
4319
4320 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004321 i = 0;
drh75897232000-05-29 14:26:00 +00004322 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004323 i += translate_code(lemp, rp);
4324 }
4325 if( i ){
4326 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004327 }
drhc53eed12009-06-12 17:46:19 +00004328 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004329 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004330 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004331 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004332 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004333 fprintf(out," case %d: /* ", rp->index);
4334 writeRuleText(out, rp);
4335 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004336 for(rp2=rp->next; rp2; rp2=rp2->next){
4337 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004338 fprintf(out," case %d: /* ", rp2->index);
4339 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004340 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004341 rp2->code = 0;
4342 }
4343 }
drh75897232000-05-29 14:26:00 +00004344 emit_code(out,rp,lemp,&lineno);
4345 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004346 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004347 }
drhc53eed12009-06-12 17:46:19 +00004348 /* Finally, output the default: rule. We choose as the default: all
4349 ** empty actions. */
4350 fprintf(out," default:\n"); lineno++;
4351 for(rp=lemp->rule; rp; rp=rp->next){
4352 if( rp->code==0 ) continue;
4353 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4354 fprintf(out," /* (%d) ", rp->index);
4355 writeRuleText(out, rp);
4356 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4357 }
4358 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004359 tplt_xfer(lemp->name,in,out,&lineno);
4360
4361 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004362 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004363 tplt_xfer(lemp->name,in,out,&lineno);
4364
4365 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004366 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004367 tplt_xfer(lemp->name,in,out,&lineno);
4368
4369 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004370 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004371 tplt_xfer(lemp->name,in,out,&lineno);
4372
4373 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004374 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004375
4376 fclose(in);
4377 fclose(out);
4378 return;
4379}
4380
4381/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004382void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004383{
4384 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004385 const char *prefix;
drh75897232000-05-29 14:26:00 +00004386 char line[LINESIZE];
4387 char pattern[LINESIZE];
4388 int i;
4389
4390 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4391 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004392 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004393 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004394 int nextChar;
drh75897232000-05-29 14:26:00 +00004395 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004396 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4397 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004398 if( strcmp(line,pattern) ) break;
4399 }
drh8ba0d1c2012-06-16 15:26:31 +00004400 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004401 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004402 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004403 /* No change in the file. Don't rewrite it. */
4404 return;
4405 }
4406 }
drh2aa6ca42004-09-10 00:14:04 +00004407 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004408 if( out ){
4409 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004410 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004411 }
4412 fclose(out);
4413 }
4414 return;
4415}
4416
4417/* Reduce the size of the action tables, if possible, by making use
4418** of defaults.
4419**
drhb59499c2002-02-23 18:45:13 +00004420** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004421** it the default. Except, there is no default if the wildcard token
4422** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004423*/
icculus9e44cf12010-02-14 17:14:22 +00004424void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004425{
4426 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004427 struct action *ap, *ap2;
4428 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004429 int nbest, n;
drh75897232000-05-29 14:26:00 +00004430 int i;
drhe09daa92006-06-10 13:29:31 +00004431 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004432
4433 for(i=0; i<lemp->nstate; i++){
4434 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004435 nbest = 0;
4436 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004437 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004438
drhb59499c2002-02-23 18:45:13 +00004439 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004440 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4441 usesWildcard = 1;
4442 }
drhb59499c2002-02-23 18:45:13 +00004443 if( ap->type!=REDUCE ) continue;
4444 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004445 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004446 if( rp==rbest ) continue;
4447 n = 1;
4448 for(ap2=ap->next; ap2; ap2=ap2->next){
4449 if( ap2->type!=REDUCE ) continue;
4450 rp2 = ap2->x.rp;
4451 if( rp2==rbest ) continue;
4452 if( rp2==rp ) n++;
4453 }
4454 if( n>nbest ){
4455 nbest = n;
4456 rbest = rp;
drh75897232000-05-29 14:26:00 +00004457 }
4458 }
drhb59499c2002-02-23 18:45:13 +00004459
4460 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004461 ** is not at least 1 or if the wildcard token is a possible
4462 ** lookahead.
4463 */
4464 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004465
drhb59499c2002-02-23 18:45:13 +00004466
4467 /* Combine matching REDUCE actions into a single default */
4468 for(ap=stp->ap; ap; ap=ap->next){
4469 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4470 }
drh75897232000-05-29 14:26:00 +00004471 assert( ap );
4472 ap->sp = Symbol_new("{default}");
4473 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004474 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004475 }
4476 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004477
4478 for(ap=stp->ap; ap; ap=ap->next){
4479 if( ap->type==SHIFT ) break;
4480 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4481 }
4482 if( ap==0 ){
4483 stp->autoReduce = 1;
4484 stp->pDfltReduce = rbest;
4485 }
4486 }
4487
4488 /* Make a second pass over all states and actions. Convert
4489 ** every action that is a SHIFT to an autoReduce state into
4490 ** a SHIFTREDUCE action.
4491 */
4492 for(i=0; i<lemp->nstate; i++){
4493 stp = lemp->sorted[i];
4494 for(ap=stp->ap; ap; ap=ap->next){
4495 struct state *pNextState;
4496 if( ap->type!=SHIFT ) continue;
4497 pNextState = ap->x.stp;
4498 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4499 ap->type = SHIFTREDUCE;
4500 ap->x.rp = pNextState->pDfltReduce;
4501 }
4502 }
drh75897232000-05-29 14:26:00 +00004503 }
4504}
drhb59499c2002-02-23 18:45:13 +00004505
drhada354d2005-11-05 15:03:59 +00004506
4507/*
4508** Compare two states for sorting purposes. The smaller state is the
4509** one with the most non-terminal actions. If they have the same number
4510** of non-terminal actions, then the smaller is the one with the most
4511** token actions.
4512*/
4513static int stateResortCompare(const void *a, const void *b){
4514 const struct state *pA = *(const struct state**)a;
4515 const struct state *pB = *(const struct state**)b;
4516 int n;
4517
4518 n = pB->nNtAct - pA->nNtAct;
4519 if( n==0 ){
4520 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004521 if( n==0 ){
4522 n = pB->statenum - pA->statenum;
4523 }
drhada354d2005-11-05 15:03:59 +00004524 }
drhe594bc32009-11-03 13:02:25 +00004525 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004526 return n;
4527}
4528
4529
4530/*
4531** Renumber and resort states so that states with fewer choices
4532** occur at the end. Except, keep state 0 as the first state.
4533*/
icculus9e44cf12010-02-14 17:14:22 +00004534void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004535{
4536 int i;
4537 struct state *stp;
4538 struct action *ap;
4539
4540 for(i=0; i<lemp->nstate; i++){
4541 stp = lemp->sorted[i];
4542 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004543 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004544 stp->iTknOfst = NO_OFFSET;
4545 stp->iNtOfst = NO_OFFSET;
4546 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004547 int iAction = compute_action(lemp,ap);
4548 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004549 if( ap->sp->index<lemp->nterminal ){
4550 stp->nTknAct++;
4551 }else if( ap->sp->index<lemp->nsymbol ){
4552 stp->nNtAct++;
4553 }else{
drh3bd48ab2015-09-07 18:23:37 +00004554 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4555 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004556 }
4557 }
4558 }
4559 }
4560 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4561 stateResortCompare);
4562 for(i=0; i<lemp->nstate; i++){
4563 lemp->sorted[i]->statenum = i;
4564 }
drh3bd48ab2015-09-07 18:23:37 +00004565 lemp->nxstate = lemp->nstate;
4566 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4567 lemp->nxstate--;
4568 }
drhada354d2005-11-05 15:03:59 +00004569}
4570
4571
drh75897232000-05-29 14:26:00 +00004572/***************** From the file "set.c" ************************************/
4573/*
4574** Set manipulation routines for the LEMON parser generator.
4575*/
4576
4577static int size = 0;
4578
4579/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004580void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004581{
4582 size = n+1;
4583}
4584
4585/* Allocate a new set */
4586char *SetNew(){
4587 char *s;
drh9892c5d2007-12-21 00:02:11 +00004588 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004589 if( s==0 ){
4590 extern void memory_error();
4591 memory_error();
4592 }
drh75897232000-05-29 14:26:00 +00004593 return s;
4594}
4595
4596/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004597void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004598{
4599 free(s);
4600}
4601
4602/* Add a new element to the set. Return TRUE if the element was added
4603** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004604int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004605{
4606 int rv;
drh9892c5d2007-12-21 00:02:11 +00004607 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004608 rv = s[e];
4609 s[e] = 1;
4610 return !rv;
4611}
4612
4613/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004614int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004615{
4616 int i, progress;
4617 progress = 0;
4618 for(i=0; i<size; i++){
4619 if( s2[i]==0 ) continue;
4620 if( s1[i]==0 ){
4621 progress = 1;
4622 s1[i] = 1;
4623 }
4624 }
4625 return progress;
4626}
4627/********************** From the file "table.c" ****************************/
4628/*
4629** All code in this file has been automatically generated
4630** from a specification in the file
4631** "table.q"
4632** by the associative array code building program "aagen".
4633** Do not edit this file! Instead, edit the specification
4634** file, then rerun aagen.
4635*/
4636/*
4637** Code for processing tables in the LEMON parser generator.
4638*/
4639
drh01f75f22013-10-02 20:46:30 +00004640PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004641{
drh01f75f22013-10-02 20:46:30 +00004642 unsigned h = 0;
4643 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004644 return h;
4645}
4646
4647/* Works like strdup, sort of. Save a string in malloced memory, but
4648** keep strings in a table so that the same string is not in more
4649** than one place.
4650*/
icculus9e44cf12010-02-14 17:14:22 +00004651const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004652{
icculus9e44cf12010-02-14 17:14:22 +00004653 const char *z;
4654 char *cpy;
drh75897232000-05-29 14:26:00 +00004655
drh916f75f2006-07-17 00:19:39 +00004656 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004657 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004658 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004659 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004660 z = cpy;
drh75897232000-05-29 14:26:00 +00004661 Strsafe_insert(z);
4662 }
4663 MemoryCheck(z);
4664 return z;
4665}
4666
4667/* There is one instance of the following structure for each
4668** associative array of type "x1".
4669*/
4670struct s_x1 {
4671 int size; /* The number of available slots. */
4672 /* Must be a power of 2 greater than or */
4673 /* equal to 1 */
4674 int count; /* Number of currently slots filled */
4675 struct s_x1node *tbl; /* The data stored here */
4676 struct s_x1node **ht; /* Hash table for lookups */
4677};
4678
4679/* There is one instance of this structure for every data element
4680** in an associative array of type "x1".
4681*/
4682typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004683 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004684 struct s_x1node *next; /* Next entry with the same hash */
4685 struct s_x1node **from; /* Previous link */
4686} x1node;
4687
4688/* There is only one instance of the array, which is the following */
4689static struct s_x1 *x1a;
4690
4691/* Allocate a new associative array */
4692void Strsafe_init(){
4693 if( x1a ) return;
4694 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4695 if( x1a ){
4696 x1a->size = 1024;
4697 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004698 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004699 if( x1a->tbl==0 ){
4700 free(x1a);
4701 x1a = 0;
4702 }else{
4703 int i;
4704 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4705 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4706 }
4707 }
4708}
4709/* Insert a new record into the array. Return TRUE if successful.
4710** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004711int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004712{
4713 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004714 unsigned h;
4715 unsigned ph;
drh75897232000-05-29 14:26:00 +00004716
4717 if( x1a==0 ) return 0;
4718 ph = strhash(data);
4719 h = ph & (x1a->size-1);
4720 np = x1a->ht[h];
4721 while( np ){
4722 if( strcmp(np->data,data)==0 ){
4723 /* An existing entry with the same key is found. */
4724 /* Fail because overwrite is not allows. */
4725 return 0;
4726 }
4727 np = np->next;
4728 }
4729 if( x1a->count>=x1a->size ){
4730 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004731 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004732 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004733 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004734 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004735 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004736 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004737 array.ht = (x1node**)&(array.tbl[arrSize]);
4738 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004739 for(i=0; i<x1a->count; i++){
4740 x1node *oldnp, *newnp;
4741 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004742 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004743 newnp = &(array.tbl[i]);
4744 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4745 newnp->next = array.ht[h];
4746 newnp->data = oldnp->data;
4747 newnp->from = &(array.ht[h]);
4748 array.ht[h] = newnp;
4749 }
4750 free(x1a->tbl);
4751 *x1a = array;
4752 }
4753 /* Insert the new data */
4754 h = ph & (x1a->size-1);
4755 np = &(x1a->tbl[x1a->count++]);
4756 np->data = data;
4757 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4758 np->next = x1a->ht[h];
4759 x1a->ht[h] = np;
4760 np->from = &(x1a->ht[h]);
4761 return 1;
4762}
4763
4764/* Return a pointer to data assigned to the given key. Return NULL
4765** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004766const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004767{
drh01f75f22013-10-02 20:46:30 +00004768 unsigned h;
drh75897232000-05-29 14:26:00 +00004769 x1node *np;
4770
4771 if( x1a==0 ) return 0;
4772 h = strhash(key) & (x1a->size-1);
4773 np = x1a->ht[h];
4774 while( np ){
4775 if( strcmp(np->data,key)==0 ) break;
4776 np = np->next;
4777 }
4778 return np ? np->data : 0;
4779}
4780
4781/* Return a pointer to the (terminal or nonterminal) symbol "x".
4782** Create a new symbol if this is the first time "x" has been seen.
4783*/
icculus9e44cf12010-02-14 17:14:22 +00004784struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004785{
4786 struct symbol *sp;
4787
4788 sp = Symbol_find(x);
4789 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004790 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004791 MemoryCheck(sp);
4792 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004793 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004794 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004795 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004796 sp->prec = -1;
4797 sp->assoc = UNK;
4798 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004799 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004800 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004801 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004802 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004803 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004804 Symbol_insert(sp,sp->name);
4805 }
drhc4dd3fd2008-01-22 01:48:05 +00004806 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004807 return sp;
4808}
4809
drh61f92cd2014-01-11 03:06:18 +00004810/* Compare two symbols for sorting purposes. Return negative,
4811** zero, or positive if a is less then, equal to, or greater
4812** than b.
drh60d31652004-02-22 00:08:04 +00004813**
4814** Symbols that begin with upper case letters (terminals or tokens)
4815** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004816** (non-terminals). And MULTITERMINAL symbols (created using the
4817** %token_class directive) must sort at the very end. Other than
4818** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004819**
4820** We find experimentally that leaving the symbols in their original
4821** order (the order they appeared in the grammar file) gives the
4822** smallest parser tables in SQLite.
4823*/
icculus9e44cf12010-02-14 17:14:22 +00004824int Symbolcmpp(const void *_a, const void *_b)
4825{
drh61f92cd2014-01-11 03:06:18 +00004826 const struct symbol *a = *(const struct symbol **) _a;
4827 const struct symbol *b = *(const struct symbol **) _b;
4828 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4829 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4830 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004831}
4832
4833/* There is one instance of the following structure for each
4834** associative array of type "x2".
4835*/
4836struct s_x2 {
4837 int size; /* The number of available slots. */
4838 /* Must be a power of 2 greater than or */
4839 /* equal to 1 */
4840 int count; /* Number of currently slots filled */
4841 struct s_x2node *tbl; /* The data stored here */
4842 struct s_x2node **ht; /* Hash table for lookups */
4843};
4844
4845/* There is one instance of this structure for every data element
4846** in an associative array of type "x2".
4847*/
4848typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004849 struct symbol *data; /* The data */
4850 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004851 struct s_x2node *next; /* Next entry with the same hash */
4852 struct s_x2node **from; /* Previous link */
4853} x2node;
4854
4855/* There is only one instance of the array, which is the following */
4856static struct s_x2 *x2a;
4857
4858/* Allocate a new associative array */
4859void Symbol_init(){
4860 if( x2a ) return;
4861 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4862 if( x2a ){
4863 x2a->size = 128;
4864 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004865 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004866 if( x2a->tbl==0 ){
4867 free(x2a);
4868 x2a = 0;
4869 }else{
4870 int i;
4871 x2a->ht = (x2node**)&(x2a->tbl[128]);
4872 for(i=0; i<128; i++) x2a->ht[i] = 0;
4873 }
4874 }
4875}
4876/* Insert a new record into the array. Return TRUE if successful.
4877** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004878int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004879{
4880 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004881 unsigned h;
4882 unsigned ph;
drh75897232000-05-29 14:26:00 +00004883
4884 if( x2a==0 ) return 0;
4885 ph = strhash(key);
4886 h = ph & (x2a->size-1);
4887 np = x2a->ht[h];
4888 while( np ){
4889 if( strcmp(np->key,key)==0 ){
4890 /* An existing entry with the same key is found. */
4891 /* Fail because overwrite is not allows. */
4892 return 0;
4893 }
4894 np = np->next;
4895 }
4896 if( x2a->count>=x2a->size ){
4897 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004898 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004899 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004900 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004901 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004902 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004903 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004904 array.ht = (x2node**)&(array.tbl[arrSize]);
4905 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004906 for(i=0; i<x2a->count; i++){
4907 x2node *oldnp, *newnp;
4908 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004909 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004910 newnp = &(array.tbl[i]);
4911 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4912 newnp->next = array.ht[h];
4913 newnp->key = oldnp->key;
4914 newnp->data = oldnp->data;
4915 newnp->from = &(array.ht[h]);
4916 array.ht[h] = newnp;
4917 }
4918 free(x2a->tbl);
4919 *x2a = array;
4920 }
4921 /* Insert the new data */
4922 h = ph & (x2a->size-1);
4923 np = &(x2a->tbl[x2a->count++]);
4924 np->key = key;
4925 np->data = data;
4926 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4927 np->next = x2a->ht[h];
4928 x2a->ht[h] = np;
4929 np->from = &(x2a->ht[h]);
4930 return 1;
4931}
4932
4933/* Return a pointer to data assigned to the given key. Return NULL
4934** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004935struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004936{
drh01f75f22013-10-02 20:46:30 +00004937 unsigned h;
drh75897232000-05-29 14:26:00 +00004938 x2node *np;
4939
4940 if( x2a==0 ) return 0;
4941 h = strhash(key) & (x2a->size-1);
4942 np = x2a->ht[h];
4943 while( np ){
4944 if( strcmp(np->key,key)==0 ) break;
4945 np = np->next;
4946 }
4947 return np ? np->data : 0;
4948}
4949
4950/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004951struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004952{
4953 struct symbol *data;
4954 if( x2a && n>0 && n<=x2a->count ){
4955 data = x2a->tbl[n-1].data;
4956 }else{
4957 data = 0;
4958 }
4959 return data;
4960}
4961
4962/* Return the size of the array */
4963int Symbol_count()
4964{
4965 return x2a ? x2a->count : 0;
4966}
4967
4968/* Return an array of pointers to all data in the table.
4969** The array is obtained from malloc. Return NULL if memory allocation
4970** problems, or if the array is empty. */
4971struct symbol **Symbol_arrayof()
4972{
4973 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00004974 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004975 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004976 arrSize = x2a->count;
4977 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004978 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004979 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004980 }
4981 return array;
4982}
4983
4984/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004985int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004986{
icculus9e44cf12010-02-14 17:14:22 +00004987 const struct config *a = (struct config *) _a;
4988 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004989 int x;
4990 x = a->rp->index - b->rp->index;
4991 if( x==0 ) x = a->dot - b->dot;
4992 return x;
4993}
4994
4995/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004996PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004997{
4998 int rc;
4999 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
5000 rc = a->rp->index - b->rp->index;
5001 if( rc==0 ) rc = a->dot - b->dot;
5002 }
5003 if( rc==0 ){
5004 if( a ) rc = 1;
5005 if( b ) rc = -1;
5006 }
5007 return rc;
5008}
5009
5010/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00005011PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00005012{
drh01f75f22013-10-02 20:46:30 +00005013 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005014 while( a ){
5015 h = h*571 + a->rp->index*37 + a->dot;
5016 a = a->bp;
5017 }
5018 return h;
5019}
5020
5021/* Allocate a new state structure */
5022struct state *State_new()
5023{
icculus9e44cf12010-02-14 17:14:22 +00005024 struct state *newstate;
5025 newstate = (struct state *)calloc(1, sizeof(struct state) );
5026 MemoryCheck(newstate);
5027 return newstate;
drh75897232000-05-29 14:26:00 +00005028}
5029
5030/* There is one instance of the following structure for each
5031** associative array of type "x3".
5032*/
5033struct s_x3 {
5034 int size; /* The number of available slots. */
5035 /* Must be a power of 2 greater than or */
5036 /* equal to 1 */
5037 int count; /* Number of currently slots filled */
5038 struct s_x3node *tbl; /* The data stored here */
5039 struct s_x3node **ht; /* Hash table for lookups */
5040};
5041
5042/* There is one instance of this structure for every data element
5043** in an associative array of type "x3".
5044*/
5045typedef struct s_x3node {
5046 struct state *data; /* The data */
5047 struct config *key; /* The key */
5048 struct s_x3node *next; /* Next entry with the same hash */
5049 struct s_x3node **from; /* Previous link */
5050} x3node;
5051
5052/* There is only one instance of the array, which is the following */
5053static struct s_x3 *x3a;
5054
5055/* Allocate a new associative array */
5056void State_init(){
5057 if( x3a ) return;
5058 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5059 if( x3a ){
5060 x3a->size = 128;
5061 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005062 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005063 if( x3a->tbl==0 ){
5064 free(x3a);
5065 x3a = 0;
5066 }else{
5067 int i;
5068 x3a->ht = (x3node**)&(x3a->tbl[128]);
5069 for(i=0; i<128; i++) x3a->ht[i] = 0;
5070 }
5071 }
5072}
5073/* Insert a new record into the array. Return TRUE if successful.
5074** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005075int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005076{
5077 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005078 unsigned h;
5079 unsigned ph;
drh75897232000-05-29 14:26:00 +00005080
5081 if( x3a==0 ) return 0;
5082 ph = statehash(key);
5083 h = ph & (x3a->size-1);
5084 np = x3a->ht[h];
5085 while( np ){
5086 if( statecmp(np->key,key)==0 ){
5087 /* An existing entry with the same key is found. */
5088 /* Fail because overwrite is not allows. */
5089 return 0;
5090 }
5091 np = np->next;
5092 }
5093 if( x3a->count>=x3a->size ){
5094 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005095 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005096 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005097 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005098 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005099 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005100 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005101 array.ht = (x3node**)&(array.tbl[arrSize]);
5102 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005103 for(i=0; i<x3a->count; i++){
5104 x3node *oldnp, *newnp;
5105 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005106 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005107 newnp = &(array.tbl[i]);
5108 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5109 newnp->next = array.ht[h];
5110 newnp->key = oldnp->key;
5111 newnp->data = oldnp->data;
5112 newnp->from = &(array.ht[h]);
5113 array.ht[h] = newnp;
5114 }
5115 free(x3a->tbl);
5116 *x3a = array;
5117 }
5118 /* Insert the new data */
5119 h = ph & (x3a->size-1);
5120 np = &(x3a->tbl[x3a->count++]);
5121 np->key = key;
5122 np->data = data;
5123 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5124 np->next = x3a->ht[h];
5125 x3a->ht[h] = np;
5126 np->from = &(x3a->ht[h]);
5127 return 1;
5128}
5129
5130/* Return a pointer to data assigned to the given key. Return NULL
5131** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005132struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005133{
drh01f75f22013-10-02 20:46:30 +00005134 unsigned h;
drh75897232000-05-29 14:26:00 +00005135 x3node *np;
5136
5137 if( x3a==0 ) return 0;
5138 h = statehash(key) & (x3a->size-1);
5139 np = x3a->ht[h];
5140 while( np ){
5141 if( statecmp(np->key,key)==0 ) break;
5142 np = np->next;
5143 }
5144 return np ? np->data : 0;
5145}
5146
5147/* Return an array of pointers to all data in the table.
5148** The array is obtained from malloc. Return NULL if memory allocation
5149** problems, or if the array is empty. */
5150struct state **State_arrayof()
5151{
5152 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005153 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005154 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005155 arrSize = x3a->count;
5156 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005157 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005158 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005159 }
5160 return array;
5161}
5162
5163/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005164PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005165{
drh01f75f22013-10-02 20:46:30 +00005166 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005167 h = h*571 + a->rp->index*37 + a->dot;
5168 return h;
5169}
5170
5171/* There is one instance of the following structure for each
5172** associative array of type "x4".
5173*/
5174struct s_x4 {
5175 int size; /* The number of available slots. */
5176 /* Must be a power of 2 greater than or */
5177 /* equal to 1 */
5178 int count; /* Number of currently slots filled */
5179 struct s_x4node *tbl; /* The data stored here */
5180 struct s_x4node **ht; /* Hash table for lookups */
5181};
5182
5183/* There is one instance of this structure for every data element
5184** in an associative array of type "x4".
5185*/
5186typedef struct s_x4node {
5187 struct config *data; /* The data */
5188 struct s_x4node *next; /* Next entry with the same hash */
5189 struct s_x4node **from; /* Previous link */
5190} x4node;
5191
5192/* There is only one instance of the array, which is the following */
5193static struct s_x4 *x4a;
5194
5195/* Allocate a new associative array */
5196void Configtable_init(){
5197 if( x4a ) return;
5198 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5199 if( x4a ){
5200 x4a->size = 64;
5201 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005202 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005203 if( x4a->tbl==0 ){
5204 free(x4a);
5205 x4a = 0;
5206 }else{
5207 int i;
5208 x4a->ht = (x4node**)&(x4a->tbl[64]);
5209 for(i=0; i<64; i++) x4a->ht[i] = 0;
5210 }
5211 }
5212}
5213/* Insert a new record into the array. Return TRUE if successful.
5214** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005215int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005216{
5217 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005218 unsigned h;
5219 unsigned ph;
drh75897232000-05-29 14:26:00 +00005220
5221 if( x4a==0 ) return 0;
5222 ph = confighash(data);
5223 h = ph & (x4a->size-1);
5224 np = x4a->ht[h];
5225 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005226 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005227 /* An existing entry with the same key is found. */
5228 /* Fail because overwrite is not allows. */
5229 return 0;
5230 }
5231 np = np->next;
5232 }
5233 if( x4a->count>=x4a->size ){
5234 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005235 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005236 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005237 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005238 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005239 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005240 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005241 array.ht = (x4node**)&(array.tbl[arrSize]);
5242 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005243 for(i=0; i<x4a->count; i++){
5244 x4node *oldnp, *newnp;
5245 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005246 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005247 newnp = &(array.tbl[i]);
5248 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5249 newnp->next = array.ht[h];
5250 newnp->data = oldnp->data;
5251 newnp->from = &(array.ht[h]);
5252 array.ht[h] = newnp;
5253 }
5254 free(x4a->tbl);
5255 *x4a = array;
5256 }
5257 /* Insert the new data */
5258 h = ph & (x4a->size-1);
5259 np = &(x4a->tbl[x4a->count++]);
5260 np->data = data;
5261 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5262 np->next = x4a->ht[h];
5263 x4a->ht[h] = np;
5264 np->from = &(x4a->ht[h]);
5265 return 1;
5266}
5267
5268/* Return a pointer to data assigned to the given key. Return NULL
5269** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005270struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005271{
5272 int h;
5273 x4node *np;
5274
5275 if( x4a==0 ) return 0;
5276 h = confighash(key) & (x4a->size-1);
5277 np = x4a->ht[h];
5278 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005279 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005280 np = np->next;
5281 }
5282 return np ? np->data : 0;
5283}
5284
5285/* Remove all data from the table. Pass each data to the function "f"
5286** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005287void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005288{
5289 int i;
5290 if( x4a==0 || x4a->count==0 ) return;
5291 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5292 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5293 x4a->count = 0;
5294 return;
5295}