blob: c678fa0da6daccceb9098f417de976ed249e7369 [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.
drh0bb132b2004-07-20 14:06:51 +00003472*/
drhaf805ca2004-09-07 11:28:25 +00003473PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003474 char *cp, *xp;
3475 int i;
3476 char lhsused = 0; /* True if the LHS element has been used */
drh4dd0d3f2016-02-17 01:18:33 +00003477 char lhsdirect; /* True if LHS writes directly into stack */
drh0bb132b2004-07-20 14:06:51 +00003478 char used[MAXRHS]; /* True for each RHS element which is used */
drh4dd0d3f2016-02-17 01:18:33 +00003479 char zLhs[50]; /* Convert the LHS symbol into this string */
drh0bb132b2004-07-20 14:06:51 +00003480
3481 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3482 lhsused = 0;
3483
drh19c9e562007-03-29 20:13:53 +00003484 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003485 static char newlinestr[2] = { '\n', '\0' };
3486 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003487 rp->line = rp->ruleline;
3488 }
3489
drh4dd0d3f2016-02-17 01:18:33 +00003490
3491 if( rp->lhsalias==0 ){
3492 /* There is no LHS value symbol. */
3493 lhsdirect = 1;
3494 }else if( rp->nrhs==0 ){
3495 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3496 lhsdirect = 1;
3497 }else if( rp->rhsalias[0]==0 ){
3498 /* The left-most RHS symbol has not value. LHS direct is ok. But
3499 ** we have to call the distructor on the RHS symbol first. */
3500 lhsdirect = 1;
3501 if( has_destructor(rp->rhs[0],lemp) ){
3502 append_str(0,0,0,0);
3503 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3504 rp->rhs[0]->index,1-rp->nrhs);
3505 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3506 }
3507 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3508 /* The LHS symbol and the left-most RHS symbol are the same, so
3509 ** direct writing is allowed */
3510 lhsdirect = 1;
3511 lhsused = 1;
3512 used[0] = 1;
3513 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3514 ErrorMsg(lemp->filename,rp->ruleline,
3515 "%s(%s) and %s(%s) share the same label but have "
3516 "different datatypes.",
3517 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3518 lemp->errorcnt++;
3519 }
3520 }else{
3521 lhsdirect = 0;
3522 }
3523 if( lhsdirect ){
3524 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3525 }else{
3526 append_str(0,0,0,0);
3527 append_str(" YYMINORTYPE yylhsminor;\n", 0, 0, 0);
3528 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3529 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3530 }
3531
drh0bb132b2004-07-20 14:06:51 +00003532 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003533
3534 /* This const cast is wrong but harmless, if we're careful. */
3535 for(cp=(char *)rp->code; *cp; cp++){
drhc56fac72015-10-29 13:48:15 +00003536 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003537 char saved;
drhc56fac72015-10-29 13:48:15 +00003538 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003539 saved = *xp;
3540 *xp = 0;
3541 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003542 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003543 cp = xp;
3544 lhsused = 1;
3545 }else{
3546 for(i=0; i<rp->nrhs; i++){
3547 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003548 if( cp!=rp->code && cp[-1]=='@' ){
3549 /* If the argument is of the form @X then substituted
3550 ** the token number of X, not the value of X */
3551 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3552 }else{
drhfd405312005-11-06 04:06:59 +00003553 struct symbol *sp = rp->rhs[i];
3554 int dtnum;
3555 if( sp->type==MULTITERMINAL ){
3556 dtnum = sp->subsym[0]->dtnum;
3557 }else{
3558 dtnum = sp->dtnum;
3559 }
3560 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003561 }
drh0bb132b2004-07-20 14:06:51 +00003562 cp = xp;
3563 used[i] = 1;
3564 break;
3565 }
3566 }
3567 }
3568 *xp = saved;
3569 }
3570 append_str(cp, 1, 0, 0);
3571 } /* End loop */
3572
drh4dd0d3f2016-02-17 01:18:33 +00003573 /* Main code generation completed */
3574 cp = append_str(0,0,0,0);
3575 if( cp && cp[0] ) rp->code = Strsafe(cp);
3576 append_str(0,0,0,0);
3577
drh0bb132b2004-07-20 14:06:51 +00003578 /* Check to make sure the LHS has been used */
3579 if( rp->lhsalias && !lhsused ){
3580 ErrorMsg(lemp->filename,rp->ruleline,
3581 "Label \"%s\" for \"%s(%s)\" is never used.",
3582 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3583 lemp->errorcnt++;
3584 }
3585
drh4dd0d3f2016-02-17 01:18:33 +00003586 /* Generate destructor code for RHS minor values which are not referenced.
3587 ** Generate error messages for unused labels and duplicate labels.
3588 */
drh0bb132b2004-07-20 14:06:51 +00003589 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003590 if( rp->rhsalias[i] ){
3591 if( i>0 ){
3592 int j;
3593 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3594 ErrorMsg(lemp->filename,rp->ruleline,
3595 "%s(%s) has the same label as the LHS but is not the left-most "
3596 "symbol on the RHS.",
3597 rp->rhs[i]->name, rp->rhsalias);
3598 lemp->errorcnt++;
3599 }
3600 for(j=0; j<i; j++){
3601 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3602 ErrorMsg(lemp->filename,rp->ruleline,
3603 "Label %s used for multiple symbols on the RHS of a rule.",
3604 rp->rhsalias[i]);
3605 lemp->errorcnt++;
3606 break;
3607 }
3608 }
drh0bb132b2004-07-20 14:06:51 +00003609 }
drh4dd0d3f2016-02-17 01:18:33 +00003610 if( !used[i] ){
3611 ErrorMsg(lemp->filename,rp->ruleline,
3612 "Label %s for \"%s(%s)\" is never used.",
3613 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3614 lemp->errorcnt++;
3615 }
3616 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3617 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3618 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003619 }
3620 }
drh4dd0d3f2016-02-17 01:18:33 +00003621
3622 /* If unable to write LHS values directly into the stack, write the
3623 ** saved LHS value now. */
3624 if( lhsdirect==0 ){
3625 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3626 append_str(zLhs, 0, 0, 0);
3627 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003628 }
drh4dd0d3f2016-02-17 01:18:33 +00003629
3630 /* Suffix code generation complete */
3631 cp = append_str(0,0,0,0);
3632 if( cp ) rp->codeSuffix = Strsafe(cp);
drh0bb132b2004-07-20 14:06:51 +00003633}
3634
drh75897232000-05-29 14:26:00 +00003635/*
3636** Generate code which executes when the rule "rp" is reduced. Write
3637** the code to "out". Make sure lineno stays up-to-date.
3638*/
icculus9e44cf12010-02-14 17:14:22 +00003639PRIVATE void emit_code(
3640 FILE *out,
3641 struct rule *rp,
3642 struct lemon *lemp,
3643 int *lineno
3644){
3645 const char *cp;
drh75897232000-05-29 14:26:00 +00003646
drh4dd0d3f2016-02-17 01:18:33 +00003647 /* Setup code prior to the #line directive */
3648 if( rp->codePrefix && rp->codePrefix[0] ){
3649 fprintf(out, "{%s", rp->codePrefix);
3650 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3651 }
3652
drh75897232000-05-29 14:26:00 +00003653 /* Generate code to do the reduce action */
3654 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003655 if( !lemp->nolinenosflag ){
3656 (*lineno)++;
3657 tplt_linedir(out,rp->line,lemp->filename);
3658 }
drhaf805ca2004-09-07 11:28:25 +00003659 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003660 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003661 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003662 if( !lemp->nolinenosflag ){
3663 (*lineno)++;
3664 tplt_linedir(out,*lineno,lemp->outname);
3665 }
drh4dd0d3f2016-02-17 01:18:33 +00003666 }
3667
3668 /* Generate breakdown code that occurs after the #line directive */
3669 if( rp->codeSuffix && rp->codeSuffix[0] ){
3670 fprintf(out, "%s", rp->codeSuffix);
3671 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3672 }
3673
3674 if( rp->codePrefix ){
3675 fprintf(out, "}\n"); (*lineno)++;
3676 }
drh75897232000-05-29 14:26:00 +00003677
drh75897232000-05-29 14:26:00 +00003678 return;
3679}
3680
3681/*
3682** Print the definition of the union used for the parser's data stack.
3683** This union contains fields for every possible data type for tokens
3684** and nonterminals. In the process of computing and printing this
3685** union, also set the ".dtnum" field of every terminal and nonterminal
3686** symbol.
3687*/
icculus9e44cf12010-02-14 17:14:22 +00003688void print_stack_union(
3689 FILE *out, /* The output stream */
3690 struct lemon *lemp, /* The main info structure for this parser */
3691 int *plineno, /* Pointer to the line number */
3692 int mhflag /* True if generating makeheaders output */
3693){
drh75897232000-05-29 14:26:00 +00003694 int lineno = *plineno; /* The line number of the output */
3695 char **types; /* A hash table of datatypes */
3696 int arraysize; /* Size of the "types" array */
3697 int maxdtlength; /* Maximum length of any ".datatype" field. */
3698 char *stddt; /* Standardized name for a datatype */
3699 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003700 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003701 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003702
3703 /* Allocate and initialize types[] and allocate stddt[] */
3704 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003705 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003706 if( types==0 ){
3707 fprintf(stderr,"Out of memory.\n");
3708 exit(1);
3709 }
drh75897232000-05-29 14:26:00 +00003710 for(i=0; i<arraysize; i++) types[i] = 0;
3711 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003712 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003713 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003714 }
drh75897232000-05-29 14:26:00 +00003715 for(i=0; i<lemp->nsymbol; i++){
3716 int len;
3717 struct symbol *sp = lemp->symbols[i];
3718 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003719 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003720 if( len>maxdtlength ) maxdtlength = len;
3721 }
3722 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003723 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003724 fprintf(stderr,"Out of memory.\n");
3725 exit(1);
3726 }
3727
3728 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3729 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003730 ** used for terminal symbols. If there is no %default_type defined then
3731 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3732 ** a datatype using the %type directive.
3733 */
drh75897232000-05-29 14:26:00 +00003734 for(i=0; i<lemp->nsymbol; i++){
3735 struct symbol *sp = lemp->symbols[i];
3736 char *cp;
3737 if( sp==lemp->errsym ){
3738 sp->dtnum = arraysize+1;
3739 continue;
3740 }
drh960e8c62001-04-03 16:53:21 +00003741 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003742 sp->dtnum = 0;
3743 continue;
3744 }
3745 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003746 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003747 j = 0;
drhc56fac72015-10-29 13:48:15 +00003748 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003749 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003750 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003751 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003752 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003753 sp->dtnum = 0;
3754 continue;
3755 }
drh75897232000-05-29 14:26:00 +00003756 hash = 0;
3757 for(j=0; stddt[j]; j++){
3758 hash = hash*53 + stddt[j];
3759 }
drh3b2129c2003-05-13 00:34:21 +00003760 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003761 while( types[hash] ){
3762 if( strcmp(types[hash],stddt)==0 ){
3763 sp->dtnum = hash + 1;
3764 break;
3765 }
3766 hash++;
drh2b51f212013-10-11 23:01:02 +00003767 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003768 }
3769 if( types[hash]==0 ){
3770 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003771 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003772 if( types[hash]==0 ){
3773 fprintf(stderr,"Out of memory.\n");
3774 exit(1);
3775 }
drh898799f2014-01-10 23:21:00 +00003776 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003777 }
3778 }
3779
3780 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3781 name = lemp->name ? lemp->name : "Parse";
3782 lineno = *plineno;
3783 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3784 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3785 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3786 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3787 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003788 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003789 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3790 for(i=0; i<arraysize; i++){
3791 if( types[i]==0 ) continue;
3792 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3793 free(types[i]);
3794 }
drhc4dd3fd2008-01-22 01:48:05 +00003795 if( lemp->errsym->useCnt ){
3796 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3797 }
drh75897232000-05-29 14:26:00 +00003798 free(stddt);
3799 free(types);
3800 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3801 *plineno = lineno;
3802}
3803
drhb29b0a52002-02-23 19:39:46 +00003804/*
3805** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003806** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3807** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003808*/
drhc75e0162015-09-07 02:23:02 +00003809static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3810 const char *zType = "int";
3811 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003812 if( lwr>=0 ){
3813 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003814 zType = "unsigned char";
3815 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003816 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003817 zType = "unsigned short int";
3818 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003819 }else{
drhc75e0162015-09-07 02:23:02 +00003820 zType = "unsigned int";
3821 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003822 }
3823 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003824 zType = "signed char";
3825 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003826 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003827 zType = "short";
3828 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003829 }
drhc75e0162015-09-07 02:23:02 +00003830 if( pnByte ) *pnByte = nByte;
3831 return zType;
drhb29b0a52002-02-23 19:39:46 +00003832}
3833
drhfdbf9282003-10-21 16:34:41 +00003834/*
3835** Each state contains a set of token transaction and a set of
3836** nonterminal transactions. Each of these sets makes an instance
3837** of the following structure. An array of these structures is used
3838** to order the creation of entries in the yy_action[] table.
3839*/
3840struct axset {
3841 struct state *stp; /* A pointer to a state */
3842 int isTkn; /* True to use tokens. False for non-terminals */
3843 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003844 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003845};
3846
3847/*
3848** Compare to axset structures for sorting purposes
3849*/
3850static int axset_compare(const void *a, const void *b){
3851 struct axset *p1 = (struct axset*)a;
3852 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003853 int c;
3854 c = p2->nAction - p1->nAction;
3855 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003856 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003857 }
3858 assert( c!=0 || p1==p2 );
3859 return c;
drhfdbf9282003-10-21 16:34:41 +00003860}
3861
drhc4dd3fd2008-01-22 01:48:05 +00003862/*
3863** Write text on "out" that describes the rule "rp".
3864*/
3865static void writeRuleText(FILE *out, struct rule *rp){
3866 int j;
3867 fprintf(out,"%s ::=", rp->lhs->name);
3868 for(j=0; j<rp->nrhs; j++){
3869 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003870 if( sp->type!=MULTITERMINAL ){
3871 fprintf(out," %s", sp->name);
3872 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003873 int k;
drh61f92cd2014-01-11 03:06:18 +00003874 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003875 for(k=1; k<sp->nsubsym; k++){
3876 fprintf(out,"|%s",sp->subsym[k]->name);
3877 }
3878 }
3879 }
3880}
3881
3882
drh75897232000-05-29 14:26:00 +00003883/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003884void ReportTable(
3885 struct lemon *lemp,
3886 int mhflag /* Output in makeheaders format if true */
3887){
drh75897232000-05-29 14:26:00 +00003888 FILE *out, *in;
3889 char line[LINESIZE];
3890 int lineno;
3891 struct state *stp;
3892 struct action *ap;
3893 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003894 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003895 int i, j, n, sz;
3896 int szActionType; /* sizeof(YYACTIONTYPE) */
3897 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003898 const char *name;
drh8b582012003-10-21 13:16:03 +00003899 int mnTknOfst, mxTknOfst;
3900 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003901 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003902
3903 in = tplt_open(lemp);
3904 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003905 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003906 if( out==0 ){
3907 fclose(in);
3908 return;
3909 }
3910 lineno = 1;
3911 tplt_xfer(lemp->name,in,out,&lineno);
3912
3913 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003914 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003915 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00003916 char *incName = file_makename(lemp, ".h");
3917 fprintf(out,"#include \"%s\"\n", incName); lineno++;
3918 free(incName);
drh75897232000-05-29 14:26:00 +00003919 }
3920 tplt_xfer(lemp->name,in,out,&lineno);
3921
3922 /* Generate #defines for all tokens */
3923 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003924 const char *prefix;
drh75897232000-05-29 14:26:00 +00003925 fprintf(out,"#if INTERFACE\n"); lineno++;
3926 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3927 else prefix = "";
3928 for(i=1; i<lemp->nterminal; i++){
3929 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3930 lineno++;
3931 }
3932 fprintf(out,"#endif\n"); lineno++;
3933 }
3934 tplt_xfer(lemp->name,in,out,&lineno);
3935
3936 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003937 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00003938 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00003939 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3940 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00003941 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003942 if( lemp->wildcard ){
3943 fprintf(out,"#define YYWILDCARD %d\n",
3944 lemp->wildcard->index); lineno++;
3945 }
drh75897232000-05-29 14:26:00 +00003946 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003947 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003948 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003949 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3950 }else{
3951 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3952 }
drhca44b5a2007-02-22 23:06:58 +00003953 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003954 if( mhflag ){
3955 fprintf(out,"#if INTERFACE\n"); lineno++;
3956 }
3957 name = lemp->name ? lemp->name : "Parse";
3958 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00003959 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00003960 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
3961 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003962 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3963 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3964 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3965 name,lemp->arg,&lemp->arg[i]); lineno++;
3966 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3967 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003968 }else{
drh1f245e42002-03-11 13:55:50 +00003969 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3970 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3971 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3972 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003973 }
3974 if( mhflag ){
3975 fprintf(out,"#endif\n"); lineno++;
3976 }
drhc4dd3fd2008-01-22 01:48:05 +00003977 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00003978 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3979 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003980 }
drh0bd1f4e2002-06-06 18:54:39 +00003981 if( lemp->has_fallback ){
3982 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3983 }
drh75897232000-05-29 14:26:00 +00003984
drh3bd48ab2015-09-07 18:23:37 +00003985 /* Compute the action table, but do not output it yet. The action
3986 ** table must be computed before generating the YYNSTATE macro because
3987 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00003988 */
drh3bd48ab2015-09-07 18:23:37 +00003989 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003990 if( ax==0 ){
3991 fprintf(stderr,"malloc failed\n");
3992 exit(1);
3993 }
drh3bd48ab2015-09-07 18:23:37 +00003994 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003995 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003996 ax[i*2].stp = stp;
3997 ax[i*2].isTkn = 1;
3998 ax[i*2].nAction = stp->nTknAct;
3999 ax[i*2+1].stp = stp;
4000 ax[i*2+1].isTkn = 0;
4001 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004002 }
drh8b582012003-10-21 13:16:03 +00004003 mxTknOfst = mnTknOfst = 0;
4004 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004005 /* In an effort to minimize the action table size, use the heuristic
4006 ** of placing the largest action sets first */
4007 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4008 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004009 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004010 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004011 stp = ax[i].stp;
4012 if( ax[i].isTkn ){
4013 for(ap=stp->ap; ap; ap=ap->next){
4014 int action;
4015 if( ap->sp->index>=lemp->nterminal ) continue;
4016 action = compute_action(lemp, ap);
4017 if( action<0 ) continue;
4018 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004019 }
drhfdbf9282003-10-21 16:34:41 +00004020 stp->iTknOfst = acttab_insert(pActtab);
4021 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4022 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4023 }else{
4024 for(ap=stp->ap; ap; ap=ap->next){
4025 int action;
4026 if( ap->sp->index<lemp->nterminal ) continue;
4027 if( ap->sp->index==lemp->nsymbol ) continue;
4028 action = compute_action(lemp, ap);
4029 if( action<0 ) continue;
4030 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004031 }
drhfdbf9282003-10-21 16:34:41 +00004032 stp->iNtOfst = acttab_insert(pActtab);
4033 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4034 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004035 }
drh337cd0d2015-09-07 23:40:42 +00004036#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4037 { int jj, nn;
4038 for(jj=nn=0; jj<pActtab->nAction; jj++){
4039 if( pActtab->aAction[jj].action<0 ) nn++;
4040 }
4041 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4042 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4043 ax[i].nAction, pActtab->nAction, nn);
4044 }
4045#endif
drh8b582012003-10-21 13:16:03 +00004046 }
drhfdbf9282003-10-21 16:34:41 +00004047 free(ax);
drh8b582012003-10-21 13:16:03 +00004048
drh3bd48ab2015-09-07 18:23:37 +00004049 /* Finish rendering the constants now that the action table has
4050 ** been computed */
4051 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4052 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004053 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004054 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4055 i = lemp->nstate + lemp->nrule;
4056 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4057 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
4058 i = lemp->nstate + lemp->nrule*2;
4059 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4060 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
4061 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
4062 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
4063 tplt_xfer(lemp->name,in,out,&lineno);
4064
4065 /* Now output the action table and its associates:
4066 **
4067 ** yy_action[] A single table containing all actions.
4068 ** yy_lookahead[] A table containing the lookahead for each entry in
4069 ** yy_action. Used to detect hash collisions.
4070 ** yy_shift_ofst[] For each state, the offset into yy_action for
4071 ** shifting terminals.
4072 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4073 ** shifting non-terminals after a reduce.
4074 ** yy_default[] Default action for each state.
4075 */
4076
drh8b582012003-10-21 13:16:03 +00004077 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004078 lemp->nactiontab = n = acttab_size(pActtab);
4079 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004080 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4081 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004082 for(i=j=0; i<n; i++){
4083 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00004084 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00004085 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004086 fprintf(out, " %4d,", action);
4087 if( j==9 || i==n-1 ){
4088 fprintf(out, "\n"); lineno++;
4089 j = 0;
4090 }else{
4091 j++;
4092 }
4093 }
4094 fprintf(out, "};\n"); lineno++;
4095
4096 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004097 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004098 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004099 for(i=j=0; i<n; i++){
4100 int la = acttab_yylookahead(pActtab, i);
4101 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004102 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004103 fprintf(out, " %4d,", la);
4104 if( j==9 || i==n-1 ){
4105 fprintf(out, "\n"); lineno++;
4106 j = 0;
4107 }else{
4108 j++;
4109 }
4110 }
4111 fprintf(out, "};\n"); lineno++;
4112
4113 /* Output the yy_shift_ofst[] table */
4114 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004115 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004116 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004117 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4118 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4119 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004120 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004121 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4122 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004123 for(i=j=0; i<n; i++){
4124 int ofst;
4125 stp = lemp->sorted[i];
4126 ofst = stp->iTknOfst;
4127 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004128 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004129 fprintf(out, " %4d,", ofst);
4130 if( j==9 || i==n-1 ){
4131 fprintf(out, "\n"); lineno++;
4132 j = 0;
4133 }else{
4134 j++;
4135 }
4136 }
4137 fprintf(out, "};\n"); lineno++;
4138
4139 /* Output the yy_reduce_ofst[] table */
4140 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004141 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004142 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004143 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4144 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4145 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004146 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004147 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4148 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004149 for(i=j=0; i<n; i++){
4150 int ofst;
4151 stp = lemp->sorted[i];
4152 ofst = stp->iNtOfst;
4153 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004154 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004155 fprintf(out, " %4d,", ofst);
4156 if( j==9 || i==n-1 ){
4157 fprintf(out, "\n"); lineno++;
4158 j = 0;
4159 }else{
4160 j++;
4161 }
4162 }
4163 fprintf(out, "};\n"); lineno++;
4164
4165 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004166 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004167 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004168 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004169 for(i=j=0; i<n; i++){
4170 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004171 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004172 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004173 if( j==9 || i==n-1 ){
4174 fprintf(out, "\n"); lineno++;
4175 j = 0;
4176 }else{
4177 j++;
4178 }
4179 }
4180 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004181 tplt_xfer(lemp->name,in,out,&lineno);
4182
drh0bd1f4e2002-06-06 18:54:39 +00004183 /* Generate the table of fallback tokens.
4184 */
4185 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004186 int mx = lemp->nterminal - 1;
4187 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004188 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004189 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004190 struct symbol *p = lemp->symbols[i];
4191 if( p->fallback==0 ){
4192 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4193 }else{
4194 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4195 p->name, p->fallback->name);
4196 }
4197 lineno++;
4198 }
4199 }
4200 tplt_xfer(lemp->name, in, out, &lineno);
4201
4202 /* Generate a table containing the symbolic name of every symbol
4203 */
drh75897232000-05-29 14:26:00 +00004204 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004205 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004206 fprintf(out," %-15s",line);
4207 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4208 }
4209 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4210 tplt_xfer(lemp->name,in,out,&lineno);
4211
drh0bd1f4e2002-06-06 18:54:39 +00004212 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004213 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004214 ** when tracing REDUCE actions.
4215 */
4216 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4217 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004218 fprintf(out," /* %3d */ \"", i);
4219 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004220 fprintf(out,"\",\n"); lineno++;
4221 }
4222 tplt_xfer(lemp->name,in,out,&lineno);
4223
drh75897232000-05-29 14:26:00 +00004224 /* Generate code which executes every time a symbol is popped from
4225 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004226 ** (In other words, generate the %destructor actions)
4227 */
drh75897232000-05-29 14:26:00 +00004228 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004229 int once = 1;
drh75897232000-05-29 14:26:00 +00004230 for(i=0; i<lemp->nsymbol; i++){
4231 struct symbol *sp = lemp->symbols[i];
4232 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004233 if( once ){
4234 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4235 once = 0;
4236 }
drhc53eed12009-06-12 17:46:19 +00004237 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004238 }
4239 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4240 if( i<lemp->nsymbol ){
4241 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4242 fprintf(out," break;\n"); lineno++;
4243 }
4244 }
drh8d659732005-01-13 23:54:06 +00004245 if( lemp->vardest ){
4246 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004247 int once = 1;
drh8d659732005-01-13 23:54:06 +00004248 for(i=0; i<lemp->nsymbol; i++){
4249 struct symbol *sp = lemp->symbols[i];
4250 if( sp==0 || sp->type==TERMINAL ||
4251 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004252 if( once ){
4253 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4254 once = 0;
4255 }
drhc53eed12009-06-12 17:46:19 +00004256 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004257 dflt_sp = sp;
4258 }
4259 if( dflt_sp!=0 ){
4260 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004261 }
drh4dc8ef52008-07-01 17:13:57 +00004262 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004263 }
drh75897232000-05-29 14:26:00 +00004264 for(i=0; i<lemp->nsymbol; i++){
4265 struct symbol *sp = lemp->symbols[i];
4266 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004267 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004268
4269 /* Combine duplicate destructors into a single case */
4270 for(j=i+1; j<lemp->nsymbol; j++){
4271 struct symbol *sp2 = lemp->symbols[j];
4272 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4273 && sp2->dtnum==sp->dtnum
4274 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004275 fprintf(out," case %d: /* %s */\n",
4276 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004277 sp2->destructor = 0;
4278 }
4279 }
4280
drh75897232000-05-29 14:26:00 +00004281 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4282 fprintf(out," break;\n"); lineno++;
4283 }
drh75897232000-05-29 14:26:00 +00004284 tplt_xfer(lemp->name,in,out,&lineno);
4285
4286 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004287 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004288 tplt_xfer(lemp->name,in,out,&lineno);
4289
4290 /* Generate the table of rule information
4291 **
4292 ** Note: This code depends on the fact that rules are number
4293 ** sequentually beginning with 0.
4294 */
4295 for(rp=lemp->rule; rp; rp=rp->next){
4296 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4297 }
4298 tplt_xfer(lemp->name,in,out,&lineno);
4299
4300 /* Generate code which execution during each REDUCE action */
4301 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004302 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004303 }
drhc53eed12009-06-12 17:46:19 +00004304 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004305 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004306 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004307 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004308 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004309 fprintf(out," case %d: /* ", rp->index);
4310 writeRuleText(out, rp);
4311 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004312 for(rp2=rp->next; rp2; rp2=rp2->next){
4313 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004314 fprintf(out," case %d: /* ", rp2->index);
4315 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004316 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004317 rp2->code = 0;
4318 }
4319 }
drh75897232000-05-29 14:26:00 +00004320 emit_code(out,rp,lemp,&lineno);
4321 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004322 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004323 }
drhc53eed12009-06-12 17:46:19 +00004324 /* Finally, output the default: rule. We choose as the default: all
4325 ** empty actions. */
4326 fprintf(out," default:\n"); lineno++;
4327 for(rp=lemp->rule; rp; rp=rp->next){
4328 if( rp->code==0 ) continue;
4329 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4330 fprintf(out," /* (%d) ", rp->index);
4331 writeRuleText(out, rp);
4332 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4333 }
4334 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004335 tplt_xfer(lemp->name,in,out,&lineno);
4336
4337 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004338 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004339 tplt_xfer(lemp->name,in,out,&lineno);
4340
4341 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004342 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004343 tplt_xfer(lemp->name,in,out,&lineno);
4344
4345 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004346 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004347 tplt_xfer(lemp->name,in,out,&lineno);
4348
4349 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004350 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004351
4352 fclose(in);
4353 fclose(out);
4354 return;
4355}
4356
4357/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004358void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004359{
4360 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004361 const char *prefix;
drh75897232000-05-29 14:26:00 +00004362 char line[LINESIZE];
4363 char pattern[LINESIZE];
4364 int i;
4365
4366 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4367 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004368 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004369 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004370 int nextChar;
drh75897232000-05-29 14:26:00 +00004371 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004372 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4373 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004374 if( strcmp(line,pattern) ) break;
4375 }
drh8ba0d1c2012-06-16 15:26:31 +00004376 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004377 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004378 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004379 /* No change in the file. Don't rewrite it. */
4380 return;
4381 }
4382 }
drh2aa6ca42004-09-10 00:14:04 +00004383 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004384 if( out ){
4385 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004386 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004387 }
4388 fclose(out);
4389 }
4390 return;
4391}
4392
4393/* Reduce the size of the action tables, if possible, by making use
4394** of defaults.
4395**
drhb59499c2002-02-23 18:45:13 +00004396** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004397** it the default. Except, there is no default if the wildcard token
4398** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004399*/
icculus9e44cf12010-02-14 17:14:22 +00004400void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004401{
4402 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004403 struct action *ap, *ap2;
4404 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004405 int nbest, n;
drh75897232000-05-29 14:26:00 +00004406 int i;
drhe09daa92006-06-10 13:29:31 +00004407 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004408
4409 for(i=0; i<lemp->nstate; i++){
4410 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004411 nbest = 0;
4412 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004413 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004414
drhb59499c2002-02-23 18:45:13 +00004415 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004416 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4417 usesWildcard = 1;
4418 }
drhb59499c2002-02-23 18:45:13 +00004419 if( ap->type!=REDUCE ) continue;
4420 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004421 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004422 if( rp==rbest ) continue;
4423 n = 1;
4424 for(ap2=ap->next; ap2; ap2=ap2->next){
4425 if( ap2->type!=REDUCE ) continue;
4426 rp2 = ap2->x.rp;
4427 if( rp2==rbest ) continue;
4428 if( rp2==rp ) n++;
4429 }
4430 if( n>nbest ){
4431 nbest = n;
4432 rbest = rp;
drh75897232000-05-29 14:26:00 +00004433 }
4434 }
drhb59499c2002-02-23 18:45:13 +00004435
4436 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004437 ** is not at least 1 or if the wildcard token is a possible
4438 ** lookahead.
4439 */
4440 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004441
drhb59499c2002-02-23 18:45:13 +00004442
4443 /* Combine matching REDUCE actions into a single default */
4444 for(ap=stp->ap; ap; ap=ap->next){
4445 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4446 }
drh75897232000-05-29 14:26:00 +00004447 assert( ap );
4448 ap->sp = Symbol_new("{default}");
4449 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004450 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004451 }
4452 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004453
4454 for(ap=stp->ap; ap; ap=ap->next){
4455 if( ap->type==SHIFT ) break;
4456 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4457 }
4458 if( ap==0 ){
4459 stp->autoReduce = 1;
4460 stp->pDfltReduce = rbest;
4461 }
4462 }
4463
4464 /* Make a second pass over all states and actions. Convert
4465 ** every action that is a SHIFT to an autoReduce state into
4466 ** a SHIFTREDUCE action.
4467 */
4468 for(i=0; i<lemp->nstate; i++){
4469 stp = lemp->sorted[i];
4470 for(ap=stp->ap; ap; ap=ap->next){
4471 struct state *pNextState;
4472 if( ap->type!=SHIFT ) continue;
4473 pNextState = ap->x.stp;
4474 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4475 ap->type = SHIFTREDUCE;
4476 ap->x.rp = pNextState->pDfltReduce;
4477 }
4478 }
drh75897232000-05-29 14:26:00 +00004479 }
4480}
drhb59499c2002-02-23 18:45:13 +00004481
drhada354d2005-11-05 15:03:59 +00004482
4483/*
4484** Compare two states for sorting purposes. The smaller state is the
4485** one with the most non-terminal actions. If they have the same number
4486** of non-terminal actions, then the smaller is the one with the most
4487** token actions.
4488*/
4489static int stateResortCompare(const void *a, const void *b){
4490 const struct state *pA = *(const struct state**)a;
4491 const struct state *pB = *(const struct state**)b;
4492 int n;
4493
4494 n = pB->nNtAct - pA->nNtAct;
4495 if( n==0 ){
4496 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004497 if( n==0 ){
4498 n = pB->statenum - pA->statenum;
4499 }
drhada354d2005-11-05 15:03:59 +00004500 }
drhe594bc32009-11-03 13:02:25 +00004501 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004502 return n;
4503}
4504
4505
4506/*
4507** Renumber and resort states so that states with fewer choices
4508** occur at the end. Except, keep state 0 as the first state.
4509*/
icculus9e44cf12010-02-14 17:14:22 +00004510void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004511{
4512 int i;
4513 struct state *stp;
4514 struct action *ap;
4515
4516 for(i=0; i<lemp->nstate; i++){
4517 stp = lemp->sorted[i];
4518 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004519 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004520 stp->iTknOfst = NO_OFFSET;
4521 stp->iNtOfst = NO_OFFSET;
4522 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004523 int iAction = compute_action(lemp,ap);
4524 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004525 if( ap->sp->index<lemp->nterminal ){
4526 stp->nTknAct++;
4527 }else if( ap->sp->index<lemp->nsymbol ){
4528 stp->nNtAct++;
4529 }else{
drh3bd48ab2015-09-07 18:23:37 +00004530 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4531 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004532 }
4533 }
4534 }
4535 }
4536 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4537 stateResortCompare);
4538 for(i=0; i<lemp->nstate; i++){
4539 lemp->sorted[i]->statenum = i;
4540 }
drh3bd48ab2015-09-07 18:23:37 +00004541 lemp->nxstate = lemp->nstate;
4542 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4543 lemp->nxstate--;
4544 }
drhada354d2005-11-05 15:03:59 +00004545}
4546
4547
drh75897232000-05-29 14:26:00 +00004548/***************** From the file "set.c" ************************************/
4549/*
4550** Set manipulation routines for the LEMON parser generator.
4551*/
4552
4553static int size = 0;
4554
4555/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004556void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004557{
4558 size = n+1;
4559}
4560
4561/* Allocate a new set */
4562char *SetNew(){
4563 char *s;
drh9892c5d2007-12-21 00:02:11 +00004564 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004565 if( s==0 ){
4566 extern void memory_error();
4567 memory_error();
4568 }
drh75897232000-05-29 14:26:00 +00004569 return s;
4570}
4571
4572/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004573void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004574{
4575 free(s);
4576}
4577
4578/* Add a new element to the set. Return TRUE if the element was added
4579** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004580int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004581{
4582 int rv;
drh9892c5d2007-12-21 00:02:11 +00004583 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004584 rv = s[e];
4585 s[e] = 1;
4586 return !rv;
4587}
4588
4589/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004590int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004591{
4592 int i, progress;
4593 progress = 0;
4594 for(i=0; i<size; i++){
4595 if( s2[i]==0 ) continue;
4596 if( s1[i]==0 ){
4597 progress = 1;
4598 s1[i] = 1;
4599 }
4600 }
4601 return progress;
4602}
4603/********************** From the file "table.c" ****************************/
4604/*
4605** All code in this file has been automatically generated
4606** from a specification in the file
4607** "table.q"
4608** by the associative array code building program "aagen".
4609** Do not edit this file! Instead, edit the specification
4610** file, then rerun aagen.
4611*/
4612/*
4613** Code for processing tables in the LEMON parser generator.
4614*/
4615
drh01f75f22013-10-02 20:46:30 +00004616PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004617{
drh01f75f22013-10-02 20:46:30 +00004618 unsigned h = 0;
4619 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004620 return h;
4621}
4622
4623/* Works like strdup, sort of. Save a string in malloced memory, but
4624** keep strings in a table so that the same string is not in more
4625** than one place.
4626*/
icculus9e44cf12010-02-14 17:14:22 +00004627const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004628{
icculus9e44cf12010-02-14 17:14:22 +00004629 const char *z;
4630 char *cpy;
drh75897232000-05-29 14:26:00 +00004631
drh916f75f2006-07-17 00:19:39 +00004632 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004633 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004634 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004635 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004636 z = cpy;
drh75897232000-05-29 14:26:00 +00004637 Strsafe_insert(z);
4638 }
4639 MemoryCheck(z);
4640 return z;
4641}
4642
4643/* There is one instance of the following structure for each
4644** associative array of type "x1".
4645*/
4646struct s_x1 {
4647 int size; /* The number of available slots. */
4648 /* Must be a power of 2 greater than or */
4649 /* equal to 1 */
4650 int count; /* Number of currently slots filled */
4651 struct s_x1node *tbl; /* The data stored here */
4652 struct s_x1node **ht; /* Hash table for lookups */
4653};
4654
4655/* There is one instance of this structure for every data element
4656** in an associative array of type "x1".
4657*/
4658typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004659 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004660 struct s_x1node *next; /* Next entry with the same hash */
4661 struct s_x1node **from; /* Previous link */
4662} x1node;
4663
4664/* There is only one instance of the array, which is the following */
4665static struct s_x1 *x1a;
4666
4667/* Allocate a new associative array */
4668void Strsafe_init(){
4669 if( x1a ) return;
4670 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4671 if( x1a ){
4672 x1a->size = 1024;
4673 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004674 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004675 if( x1a->tbl==0 ){
4676 free(x1a);
4677 x1a = 0;
4678 }else{
4679 int i;
4680 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4681 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4682 }
4683 }
4684}
4685/* Insert a new record into the array. Return TRUE if successful.
4686** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004687int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004688{
4689 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004690 unsigned h;
4691 unsigned ph;
drh75897232000-05-29 14:26:00 +00004692
4693 if( x1a==0 ) return 0;
4694 ph = strhash(data);
4695 h = ph & (x1a->size-1);
4696 np = x1a->ht[h];
4697 while( np ){
4698 if( strcmp(np->data,data)==0 ){
4699 /* An existing entry with the same key is found. */
4700 /* Fail because overwrite is not allows. */
4701 return 0;
4702 }
4703 np = np->next;
4704 }
4705 if( x1a->count>=x1a->size ){
4706 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004707 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004708 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004709 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004710 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004711 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004712 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004713 array.ht = (x1node**)&(array.tbl[arrSize]);
4714 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004715 for(i=0; i<x1a->count; i++){
4716 x1node *oldnp, *newnp;
4717 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004718 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004719 newnp = &(array.tbl[i]);
4720 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4721 newnp->next = array.ht[h];
4722 newnp->data = oldnp->data;
4723 newnp->from = &(array.ht[h]);
4724 array.ht[h] = newnp;
4725 }
4726 free(x1a->tbl);
4727 *x1a = array;
4728 }
4729 /* Insert the new data */
4730 h = ph & (x1a->size-1);
4731 np = &(x1a->tbl[x1a->count++]);
4732 np->data = data;
4733 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4734 np->next = x1a->ht[h];
4735 x1a->ht[h] = np;
4736 np->from = &(x1a->ht[h]);
4737 return 1;
4738}
4739
4740/* Return a pointer to data assigned to the given key. Return NULL
4741** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004742const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004743{
drh01f75f22013-10-02 20:46:30 +00004744 unsigned h;
drh75897232000-05-29 14:26:00 +00004745 x1node *np;
4746
4747 if( x1a==0 ) return 0;
4748 h = strhash(key) & (x1a->size-1);
4749 np = x1a->ht[h];
4750 while( np ){
4751 if( strcmp(np->data,key)==0 ) break;
4752 np = np->next;
4753 }
4754 return np ? np->data : 0;
4755}
4756
4757/* Return a pointer to the (terminal or nonterminal) symbol "x".
4758** Create a new symbol if this is the first time "x" has been seen.
4759*/
icculus9e44cf12010-02-14 17:14:22 +00004760struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004761{
4762 struct symbol *sp;
4763
4764 sp = Symbol_find(x);
4765 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004766 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004767 MemoryCheck(sp);
4768 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004769 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004770 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004771 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004772 sp->prec = -1;
4773 sp->assoc = UNK;
4774 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004775 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004776 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004777 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004778 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004779 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004780 Symbol_insert(sp,sp->name);
4781 }
drhc4dd3fd2008-01-22 01:48:05 +00004782 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004783 return sp;
4784}
4785
drh61f92cd2014-01-11 03:06:18 +00004786/* Compare two symbols for sorting purposes. Return negative,
4787** zero, or positive if a is less then, equal to, or greater
4788** than b.
drh60d31652004-02-22 00:08:04 +00004789**
4790** Symbols that begin with upper case letters (terminals or tokens)
4791** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004792** (non-terminals). And MULTITERMINAL symbols (created using the
4793** %token_class directive) must sort at the very end. Other than
4794** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004795**
4796** We find experimentally that leaving the symbols in their original
4797** order (the order they appeared in the grammar file) gives the
4798** smallest parser tables in SQLite.
4799*/
icculus9e44cf12010-02-14 17:14:22 +00004800int Symbolcmpp(const void *_a, const void *_b)
4801{
drh61f92cd2014-01-11 03:06:18 +00004802 const struct symbol *a = *(const struct symbol **) _a;
4803 const struct symbol *b = *(const struct symbol **) _b;
4804 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4805 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4806 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004807}
4808
4809/* There is one instance of the following structure for each
4810** associative array of type "x2".
4811*/
4812struct s_x2 {
4813 int size; /* The number of available slots. */
4814 /* Must be a power of 2 greater than or */
4815 /* equal to 1 */
4816 int count; /* Number of currently slots filled */
4817 struct s_x2node *tbl; /* The data stored here */
4818 struct s_x2node **ht; /* Hash table for lookups */
4819};
4820
4821/* There is one instance of this structure for every data element
4822** in an associative array of type "x2".
4823*/
4824typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004825 struct symbol *data; /* The data */
4826 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004827 struct s_x2node *next; /* Next entry with the same hash */
4828 struct s_x2node **from; /* Previous link */
4829} x2node;
4830
4831/* There is only one instance of the array, which is the following */
4832static struct s_x2 *x2a;
4833
4834/* Allocate a new associative array */
4835void Symbol_init(){
4836 if( x2a ) return;
4837 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4838 if( x2a ){
4839 x2a->size = 128;
4840 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004841 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004842 if( x2a->tbl==0 ){
4843 free(x2a);
4844 x2a = 0;
4845 }else{
4846 int i;
4847 x2a->ht = (x2node**)&(x2a->tbl[128]);
4848 for(i=0; i<128; i++) x2a->ht[i] = 0;
4849 }
4850 }
4851}
4852/* Insert a new record into the array. Return TRUE if successful.
4853** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004854int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004855{
4856 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004857 unsigned h;
4858 unsigned ph;
drh75897232000-05-29 14:26:00 +00004859
4860 if( x2a==0 ) return 0;
4861 ph = strhash(key);
4862 h = ph & (x2a->size-1);
4863 np = x2a->ht[h];
4864 while( np ){
4865 if( strcmp(np->key,key)==0 ){
4866 /* An existing entry with the same key is found. */
4867 /* Fail because overwrite is not allows. */
4868 return 0;
4869 }
4870 np = np->next;
4871 }
4872 if( x2a->count>=x2a->size ){
4873 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004874 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004875 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004876 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004877 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004878 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004879 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004880 array.ht = (x2node**)&(array.tbl[arrSize]);
4881 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004882 for(i=0; i<x2a->count; i++){
4883 x2node *oldnp, *newnp;
4884 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004885 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004886 newnp = &(array.tbl[i]);
4887 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4888 newnp->next = array.ht[h];
4889 newnp->key = oldnp->key;
4890 newnp->data = oldnp->data;
4891 newnp->from = &(array.ht[h]);
4892 array.ht[h] = newnp;
4893 }
4894 free(x2a->tbl);
4895 *x2a = array;
4896 }
4897 /* Insert the new data */
4898 h = ph & (x2a->size-1);
4899 np = &(x2a->tbl[x2a->count++]);
4900 np->key = key;
4901 np->data = data;
4902 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4903 np->next = x2a->ht[h];
4904 x2a->ht[h] = np;
4905 np->from = &(x2a->ht[h]);
4906 return 1;
4907}
4908
4909/* Return a pointer to data assigned to the given key. Return NULL
4910** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004911struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004912{
drh01f75f22013-10-02 20:46:30 +00004913 unsigned h;
drh75897232000-05-29 14:26:00 +00004914 x2node *np;
4915
4916 if( x2a==0 ) return 0;
4917 h = strhash(key) & (x2a->size-1);
4918 np = x2a->ht[h];
4919 while( np ){
4920 if( strcmp(np->key,key)==0 ) break;
4921 np = np->next;
4922 }
4923 return np ? np->data : 0;
4924}
4925
4926/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004927struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004928{
4929 struct symbol *data;
4930 if( x2a && n>0 && n<=x2a->count ){
4931 data = x2a->tbl[n-1].data;
4932 }else{
4933 data = 0;
4934 }
4935 return data;
4936}
4937
4938/* Return the size of the array */
4939int Symbol_count()
4940{
4941 return x2a ? x2a->count : 0;
4942}
4943
4944/* Return an array of pointers to all data in the table.
4945** The array is obtained from malloc. Return NULL if memory allocation
4946** problems, or if the array is empty. */
4947struct symbol **Symbol_arrayof()
4948{
4949 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00004950 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004951 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004952 arrSize = x2a->count;
4953 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004954 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004955 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004956 }
4957 return array;
4958}
4959
4960/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004961int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004962{
icculus9e44cf12010-02-14 17:14:22 +00004963 const struct config *a = (struct config *) _a;
4964 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004965 int x;
4966 x = a->rp->index - b->rp->index;
4967 if( x==0 ) x = a->dot - b->dot;
4968 return x;
4969}
4970
4971/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004972PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004973{
4974 int rc;
4975 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4976 rc = a->rp->index - b->rp->index;
4977 if( rc==0 ) rc = a->dot - b->dot;
4978 }
4979 if( rc==0 ){
4980 if( a ) rc = 1;
4981 if( b ) rc = -1;
4982 }
4983 return rc;
4984}
4985
4986/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00004987PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004988{
drh01f75f22013-10-02 20:46:30 +00004989 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004990 while( a ){
4991 h = h*571 + a->rp->index*37 + a->dot;
4992 a = a->bp;
4993 }
4994 return h;
4995}
4996
4997/* Allocate a new state structure */
4998struct state *State_new()
4999{
icculus9e44cf12010-02-14 17:14:22 +00005000 struct state *newstate;
5001 newstate = (struct state *)calloc(1, sizeof(struct state) );
5002 MemoryCheck(newstate);
5003 return newstate;
drh75897232000-05-29 14:26:00 +00005004}
5005
5006/* There is one instance of the following structure for each
5007** associative array of type "x3".
5008*/
5009struct s_x3 {
5010 int size; /* The number of available slots. */
5011 /* Must be a power of 2 greater than or */
5012 /* equal to 1 */
5013 int count; /* Number of currently slots filled */
5014 struct s_x3node *tbl; /* The data stored here */
5015 struct s_x3node **ht; /* Hash table for lookups */
5016};
5017
5018/* There is one instance of this structure for every data element
5019** in an associative array of type "x3".
5020*/
5021typedef struct s_x3node {
5022 struct state *data; /* The data */
5023 struct config *key; /* The key */
5024 struct s_x3node *next; /* Next entry with the same hash */
5025 struct s_x3node **from; /* Previous link */
5026} x3node;
5027
5028/* There is only one instance of the array, which is the following */
5029static struct s_x3 *x3a;
5030
5031/* Allocate a new associative array */
5032void State_init(){
5033 if( x3a ) return;
5034 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5035 if( x3a ){
5036 x3a->size = 128;
5037 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005038 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005039 if( x3a->tbl==0 ){
5040 free(x3a);
5041 x3a = 0;
5042 }else{
5043 int i;
5044 x3a->ht = (x3node**)&(x3a->tbl[128]);
5045 for(i=0; i<128; i++) x3a->ht[i] = 0;
5046 }
5047 }
5048}
5049/* Insert a new record into the array. Return TRUE if successful.
5050** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005051int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005052{
5053 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005054 unsigned h;
5055 unsigned ph;
drh75897232000-05-29 14:26:00 +00005056
5057 if( x3a==0 ) return 0;
5058 ph = statehash(key);
5059 h = ph & (x3a->size-1);
5060 np = x3a->ht[h];
5061 while( np ){
5062 if( statecmp(np->key,key)==0 ){
5063 /* An existing entry with the same key is found. */
5064 /* Fail because overwrite is not allows. */
5065 return 0;
5066 }
5067 np = np->next;
5068 }
5069 if( x3a->count>=x3a->size ){
5070 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005071 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005072 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005073 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005074 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005075 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005076 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005077 array.ht = (x3node**)&(array.tbl[arrSize]);
5078 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005079 for(i=0; i<x3a->count; i++){
5080 x3node *oldnp, *newnp;
5081 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005082 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005083 newnp = &(array.tbl[i]);
5084 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5085 newnp->next = array.ht[h];
5086 newnp->key = oldnp->key;
5087 newnp->data = oldnp->data;
5088 newnp->from = &(array.ht[h]);
5089 array.ht[h] = newnp;
5090 }
5091 free(x3a->tbl);
5092 *x3a = array;
5093 }
5094 /* Insert the new data */
5095 h = ph & (x3a->size-1);
5096 np = &(x3a->tbl[x3a->count++]);
5097 np->key = key;
5098 np->data = data;
5099 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5100 np->next = x3a->ht[h];
5101 x3a->ht[h] = np;
5102 np->from = &(x3a->ht[h]);
5103 return 1;
5104}
5105
5106/* Return a pointer to data assigned to the given key. Return NULL
5107** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005108struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005109{
drh01f75f22013-10-02 20:46:30 +00005110 unsigned h;
drh75897232000-05-29 14:26:00 +00005111 x3node *np;
5112
5113 if( x3a==0 ) return 0;
5114 h = statehash(key) & (x3a->size-1);
5115 np = x3a->ht[h];
5116 while( np ){
5117 if( statecmp(np->key,key)==0 ) break;
5118 np = np->next;
5119 }
5120 return np ? np->data : 0;
5121}
5122
5123/* Return an array of pointers to all data in the table.
5124** The array is obtained from malloc. Return NULL if memory allocation
5125** problems, or if the array is empty. */
5126struct state **State_arrayof()
5127{
5128 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005129 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005130 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005131 arrSize = x3a->count;
5132 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005133 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005134 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005135 }
5136 return array;
5137}
5138
5139/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005140PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005141{
drh01f75f22013-10-02 20:46:30 +00005142 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005143 h = h*571 + a->rp->index*37 + a->dot;
5144 return h;
5145}
5146
5147/* There is one instance of the following structure for each
5148** associative array of type "x4".
5149*/
5150struct s_x4 {
5151 int size; /* The number of available slots. */
5152 /* Must be a power of 2 greater than or */
5153 /* equal to 1 */
5154 int count; /* Number of currently slots filled */
5155 struct s_x4node *tbl; /* The data stored here */
5156 struct s_x4node **ht; /* Hash table for lookups */
5157};
5158
5159/* There is one instance of this structure for every data element
5160** in an associative array of type "x4".
5161*/
5162typedef struct s_x4node {
5163 struct config *data; /* The data */
5164 struct s_x4node *next; /* Next entry with the same hash */
5165 struct s_x4node **from; /* Previous link */
5166} x4node;
5167
5168/* There is only one instance of the array, which is the following */
5169static struct s_x4 *x4a;
5170
5171/* Allocate a new associative array */
5172void Configtable_init(){
5173 if( x4a ) return;
5174 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5175 if( x4a ){
5176 x4a->size = 64;
5177 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005178 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005179 if( x4a->tbl==0 ){
5180 free(x4a);
5181 x4a = 0;
5182 }else{
5183 int i;
5184 x4a->ht = (x4node**)&(x4a->tbl[64]);
5185 for(i=0; i<64; i++) x4a->ht[i] = 0;
5186 }
5187 }
5188}
5189/* Insert a new record into the array. Return TRUE if successful.
5190** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005191int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005192{
5193 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005194 unsigned h;
5195 unsigned ph;
drh75897232000-05-29 14:26:00 +00005196
5197 if( x4a==0 ) return 0;
5198 ph = confighash(data);
5199 h = ph & (x4a->size-1);
5200 np = x4a->ht[h];
5201 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005202 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005203 /* An existing entry with the same key is found. */
5204 /* Fail because overwrite is not allows. */
5205 return 0;
5206 }
5207 np = np->next;
5208 }
5209 if( x4a->count>=x4a->size ){
5210 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005211 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005212 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005213 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005214 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005215 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005216 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005217 array.ht = (x4node**)&(array.tbl[arrSize]);
5218 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005219 for(i=0; i<x4a->count; i++){
5220 x4node *oldnp, *newnp;
5221 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005222 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005223 newnp = &(array.tbl[i]);
5224 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5225 newnp->next = array.ht[h];
5226 newnp->data = oldnp->data;
5227 newnp->from = &(array.ht[h]);
5228 array.ht[h] = newnp;
5229 }
5230 free(x4a->tbl);
5231 *x4a = array;
5232 }
5233 /* Insert the new data */
5234 h = ph & (x4a->size-1);
5235 np = &(x4a->tbl[x4a->count++]);
5236 np->data = data;
5237 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5238 np->next = x4a->ht[h];
5239 x4a->ht[h] = np;
5240 np->from = &(x4a->ht[h]);
5241 return 1;
5242}
5243
5244/* Return a pointer to data assigned to the given key. Return NULL
5245** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005246struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005247{
5248 int h;
5249 x4node *np;
5250
5251 if( x4a==0 ) return 0;
5252 h = confighash(key) & (x4a->size-1);
5253 np = x4a->ht[h];
5254 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005255 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005256 np = np->next;
5257 }
5258 return np ? np->data : 0;
5259}
5260
5261/* Remove all data from the table. Pass each data to the function "f"
5262** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005263void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005264{
5265 int i;
5266 if( x4a==0 || x4a->count==0 ) return;
5267 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5268 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5269 x4a->count = 0;
5270 return;
5271}