blob: 1f81717c7c69580324f2c9e723512d45670df455 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
drhf9a2e7b2003-04-15 01:49:48 +000010#include <stdarg.h>
drh75897232000-05-29 14:26:00 +000011#include <string.h>
12#include <ctype.h>
drh8b582012003-10-21 13:16:03 +000013#include <stdlib.h>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drhc56fac72015-10-29 13:48:15 +000016#define ISSPACE(X) isspace((unsigned char)(X))
17#define ISDIGIT(X) isdigit((unsigned char)(X))
18#define ISALNUM(X) isalnum((unsigned char)(X))
19#define ISALPHA(X) isalpha((unsigned char)(X))
20#define ISUPPER(X) isupper((unsigned char)(X))
21#define ISLOWER(X) islower((unsigned char)(X))
22
23
drh75897232000-05-29 14:26:00 +000024#ifndef __WIN32__
25# if defined(_WIN32) || defined(WIN32)
drhf2f105d2012-08-20 15:53:54 +000026# define __WIN32__
drh75897232000-05-29 14:26:00 +000027# endif
28#endif
29
rse8f304482007-07-30 18:31:53 +000030#ifdef __WIN32__
drhdf609712010-11-23 20:55:27 +000031#ifdef __cplusplus
32extern "C" {
33#endif
34extern int access(const char *path, int mode);
35#ifdef __cplusplus
36}
37#endif
rse8f304482007-07-30 18:31:53 +000038#else
39#include <unistd.h>
40#endif
41
drh75897232000-05-29 14:26:00 +000042/* #define PRIVATE static */
43#define PRIVATE
44
45#ifdef TEST
46#define MAXRHS 5 /* Set low to exercise exception code */
47#else
48#define MAXRHS 1000
49#endif
50
drhf5c4e0f2010-07-18 11:35:53 +000051static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000052static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000053
drh87cf1372008-08-13 20:09:06 +000054/*
55** Compilers are getting increasingly pedantic about type conversions
56** as C evolves ever closer to Ada.... To work around the latest problems
57** we have to define the following variant of strlen().
58*/
59#define lemonStrlen(X) ((int)strlen(X))
60
drh898799f2014-01-10 23:21:00 +000061/*
62** Compilers are starting to complain about the use of sprintf() and strcpy(),
63** saying they are unsafe. So we define our own versions of those routines too.
64**
65** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
drh25473362015-09-04 18:03:45 +000066** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
drh898799f2014-01-10 23:21:00 +000067** The third is a helper routine for vsnprintf() that adds texts to the end of a
68** buffer, making sure the buffer is always zero-terminated.
69**
70** The string formatter is a minimal subset of stdlib sprintf() supporting only
71** a few simply conversions:
72**
73** %d
74** %s
75** %.*s
76**
77*/
78static void lemon_addtext(
79 char *zBuf, /* The buffer to which text is added */
80 int *pnUsed, /* Slots of the buffer used so far */
81 const char *zIn, /* Text to add */
drh61f92cd2014-01-11 03:06:18 +000082 int nIn, /* Bytes of text to add. -1 to use strlen() */
83 int iWidth /* Field width. Negative to left justify */
drh898799f2014-01-10 23:21:00 +000084){
85 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
drhecaa9d32014-01-11 03:27:37 +000086 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
drh898799f2014-01-10 23:21:00 +000087 if( nIn==0 ) return;
88 memcpy(&zBuf[*pnUsed], zIn, nIn);
89 *pnUsed += nIn;
drhecaa9d32014-01-11 03:27:37 +000090 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
drh898799f2014-01-10 23:21:00 +000091 zBuf[*pnUsed] = 0;
92}
93static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
mistachkin7a429652014-01-14 10:17:21 +000094 int i, j, k, c;
drh898799f2014-01-10 23:21:00 +000095 int nUsed = 0;
96 const char *z;
97 char zTemp[50];
98 str[0] = 0;
99 for(i=j=0; (c = zFormat[i])!=0; i++){
100 if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000101 int iWidth = 0;
102 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000103 c = zFormat[++i];
drhc56fac72015-10-29 13:48:15 +0000104 if( ISDIGIT(c) || (c=='-' && ISDIGIT(zFormat[i+1])) ){
drh61f92cd2014-01-11 03:06:18 +0000105 if( c=='-' ) i++;
drhc56fac72015-10-29 13:48:15 +0000106 while( ISDIGIT(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
drh61f92cd2014-01-11 03:06:18 +0000107 if( c=='-' ) iWidth = -iWidth;
108 c = zFormat[i];
109 }
drh898799f2014-01-10 23:21:00 +0000110 if( c=='d' ){
111 int v = va_arg(ap, int);
112 if( v<0 ){
drh61f92cd2014-01-11 03:06:18 +0000113 lemon_addtext(str, &nUsed, "-", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000114 v = -v;
115 }else if( v==0 ){
drh61f92cd2014-01-11 03:06:18 +0000116 lemon_addtext(str, &nUsed, "0", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000117 }
118 k = 0;
119 while( v>0 ){
120 k++;
121 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
122 v /= 10;
123 }
drh61f92cd2014-01-11 03:06:18 +0000124 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
drh898799f2014-01-10 23:21:00 +0000125 }else if( c=='s' ){
126 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000127 lemon_addtext(str, &nUsed, z, -1, iWidth);
drh898799f2014-01-10 23:21:00 +0000128 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
129 i += 2;
130 k = va_arg(ap, int);
131 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000132 lemon_addtext(str, &nUsed, z, k, iWidth);
drh898799f2014-01-10 23:21:00 +0000133 }else if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000134 lemon_addtext(str, &nUsed, "%", 1, 0);
drh898799f2014-01-10 23:21:00 +0000135 }else{
136 fprintf(stderr, "illegal format\n");
137 exit(1);
138 }
139 j = i+1;
140 }
141 }
drh61f92cd2014-01-11 03:06:18 +0000142 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000143 return nUsed;
144}
145static int lemon_sprintf(char *str, const char *format, ...){
146 va_list ap;
147 int rc;
148 va_start(ap, format);
149 rc = lemon_vsprintf(str, format, ap);
150 va_end(ap);
151 return rc;
152}
153static void lemon_strcpy(char *dest, const char *src){
154 while( (*(dest++) = *(src++))!=0 ){}
155}
156static void lemon_strcat(char *dest, const char *src){
157 while( *dest ) dest++;
158 lemon_strcpy(dest, src);
159}
160
161
icculus9e44cf12010-02-14 17:14:22 +0000162/* a few forward declarations... */
163struct rule;
164struct lemon;
165struct action;
166
drhe9278182007-07-18 18:16:29 +0000167static struct action *Action_new(void);
168static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +0000169
170/********** From the file "build.h" ************************************/
171void FindRulePrecedences();
172void FindFirstSets();
173void FindStates();
174void FindLinks();
175void FindFollowSets();
176void FindActions();
177
178/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +0000179void Configlist_init(void);
180struct config *Configlist_add(struct rule *, int);
181struct config *Configlist_addbasis(struct rule *, int);
182void Configlist_closure(struct lemon *);
183void Configlist_sort(void);
184void Configlist_sortbasis(void);
185struct config *Configlist_return(void);
186struct config *Configlist_basis(void);
187void Configlist_eat(struct config *);
188void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +0000189
190/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +0000191void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +0000192
193/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +0000194enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
195 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +0000196struct s_options {
icculus9e44cf12010-02-14 17:14:22 +0000197 enum option_type type;
198 const char *label;
drh75897232000-05-29 14:26:00 +0000199 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000200 const char *message;
drh75897232000-05-29 14:26:00 +0000201};
icculus9e44cf12010-02-14 17:14:22 +0000202int OptInit(char**,struct s_options*,FILE*);
203int OptNArgs(void);
204char *OptArg(int);
205void OptErr(int);
206void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000207
208/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000209void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000210
211/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000212struct plink *Plink_new(void);
213void Plink_add(struct plink **, struct config *);
214void Plink_copy(struct plink **, struct plink *);
215void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000216
217/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000218void Reprint(struct lemon *);
219void ReportOutput(struct lemon *);
220void ReportTable(struct lemon *, int);
221void ReportHeader(struct lemon *);
222void CompressTables(struct lemon *);
223void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000224
225/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000226void SetSize(int); /* All sets will be of size N */
227char *SetNew(void); /* A new set for element 0..N */
228void SetFree(char*); /* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +0000229int SetAdd(char*,int); /* Add element to a set */
230int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000231#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
232
233/********** From the file "struct.h" *************************************/
234/*
235** Principal data structures for the LEMON parser generator.
236*/
237
drhaa9f1122007-08-23 02:50:56 +0000238typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000239
240/* Symbols (terminals and nonterminals) of the grammar are stored
241** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000242enum symbol_type {
243 TERMINAL,
244 NONTERMINAL,
245 MULTITERMINAL
246};
247enum e_assoc {
drh75897232000-05-29 14:26:00 +0000248 LEFT,
249 RIGHT,
250 NONE,
251 UNK
icculus9e44cf12010-02-14 17:14:22 +0000252};
253struct symbol {
254 const char *name; /* Name of the symbol */
255 int index; /* Index number for this symbol */
256 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
257 struct rule *rule; /* Linked list of rules of this (if an NT) */
258 struct symbol *fallback; /* fallback token in case this token doesn't parse */
259 int prec; /* Precedence if defined (-1 otherwise) */
260 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000261 char *firstset; /* First-set for all rules of this symbol */
262 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000263 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000264 char *destructor; /* Code which executes whenever this symbol is
265 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000266 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000267 char *datatype; /* The data type of information held by this
268 ** object. Only used if type==NONTERMINAL */
269 int dtnum; /* The data type number. In the parser, the value
270 ** stack is a union. The .yy%d element of this
271 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000272 /* The following fields are used by MULTITERMINALs only */
273 int nsubsym; /* Number of constituent symbols in the MULTI */
274 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000275};
276
277/* Each production rule in the grammar is stored in the following
278** structure. */
279struct rule {
280 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000281 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000282 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000283 int ruleline; /* Line number for the rule */
284 int nrhs; /* Number of RHS symbols */
285 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000286 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000287 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000288 const char *code; /* The code executed when this rule is reduced */
drh4dd0d3f2016-02-17 01:18:33 +0000289 const char *codePrefix; /* Setup code before code[] above */
290 const char *codeSuffix; /* Breakdown code after code[] above */
drh75897232000-05-29 14:26:00 +0000291 struct symbol *precsym; /* Precedence symbol for this rule */
292 int index; /* An index number for this rule */
293 Boolean canReduce; /* True if this rule is ever reduced */
294 struct rule *nextlhs; /* Next rule with the same LHS */
295 struct rule *next; /* Next rule in the global list */
296};
297
298/* A configuration is a production rule of the grammar together with
299** a mark (dot) showing how much of that rule has been processed so far.
300** Configurations also contain a follow-set which is a list of terminal
301** symbols which are allowed to immediately follow the end of the rule.
302** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000303enum cfgstatus {
304 COMPLETE,
305 INCOMPLETE
306};
drh75897232000-05-29 14:26:00 +0000307struct config {
308 struct rule *rp; /* The rule upon which the configuration is based */
309 int dot; /* The parse point */
310 char *fws; /* Follow-set for this configuration only */
311 struct plink *fplp; /* Follow-set forward propagation links */
312 struct plink *bplp; /* Follow-set backwards propagation links */
313 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000314 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000315 struct config *next; /* Next configuration in the state */
316 struct config *bp; /* The next basis configuration */
317};
318
icculus9e44cf12010-02-14 17:14:22 +0000319enum e_action {
320 SHIFT,
321 ACCEPT,
322 REDUCE,
323 ERROR,
324 SSCONFLICT, /* A shift/shift conflict */
325 SRCONFLICT, /* Was a reduce, but part of a conflict */
326 RRCONFLICT, /* Was a reduce, but part of a conflict */
327 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
328 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
drh3bd48ab2015-09-07 18:23:37 +0000329 NOT_USED, /* Deleted by compression */
330 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000331};
332
drh75897232000-05-29 14:26:00 +0000333/* Every shift or reduce operation is stored as one of the following */
334struct action {
335 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000336 enum e_action type;
drh75897232000-05-29 14:26:00 +0000337 union {
338 struct state *stp; /* The new state, if a shift */
339 struct rule *rp; /* The rule, if a reduce */
340 } x;
341 struct action *next; /* Next action for this state */
342 struct action *collide; /* Next action with the same hash */
343};
344
345/* Each state of the generated parser's finite state machine
346** is encoded as an instance of the following structure. */
347struct state {
348 struct config *bp; /* The basis configurations for this state */
349 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000350 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000351 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000352 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
353 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000354 int iDfltReduce; /* Default action is to REDUCE by this rule */
355 struct rule *pDfltReduce;/* The default REDUCE rule. */
356 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000357};
drh8b582012003-10-21 13:16:03 +0000358#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000359
360/* A followset propagation link indicates that the contents of one
361** configuration followset should be propagated to another whenever
362** the first changes. */
363struct plink {
364 struct config *cfp; /* The configuration to which linked */
365 struct plink *next; /* The next propagate link */
366};
367
368/* The state vector for the entire parser generator is recorded as
369** follows. (LEMON uses no global variables and makes little use of
370** static variables. Fields in the following structure can be thought
371** of as begin global variables in the program.) */
372struct lemon {
373 struct state **sorted; /* Table of states sorted by state number */
374 struct rule *rule; /* List of all rules */
375 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000376 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000377 int nrule; /* Number of rules */
378 int nsymbol; /* Number of terminal and nonterminal symbols */
379 int nterminal; /* Number of terminal symbols */
380 struct symbol **symbols; /* Sorted array of pointers to symbols */
381 int errorcnt; /* Number of errors */
382 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000383 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000384 char *name; /* Name of the generated parser */
385 char *arg; /* Declaration of the 3th argument to parser */
386 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000387 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000388 char *start; /* Name of the start symbol for the grammar */
389 char *stacksize; /* Size of the parser stack */
390 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000391 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000392 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000393 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000394 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000395 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000396 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000397 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000398 char *filename; /* Name of the input file */
399 char *outname; /* Name of the current output file */
400 char *tokenprefix; /* A prefix added to token names in the .h file */
401 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000402 int nactiontab; /* Number of entries in the yy_action[] table */
403 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000404 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000405 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000406 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000407 char *argv0; /* Name of the program */
408};
409
410#define MemoryCheck(X) if((X)==0){ \
411 extern void memory_error(); \
412 memory_error(); \
413}
414
415/**************** From the file "table.h" *********************************/
416/*
417** All code in this file has been automatically generated
418** from a specification in the file
419** "table.q"
420** by the associative array code building program "aagen".
421** Do not edit this file! Instead, edit the specification
422** file, then rerun aagen.
423*/
424/*
425** Code for processing tables in the LEMON parser generator.
426*/
drh75897232000-05-29 14:26:00 +0000427/* Routines for handling a strings */
428
icculus9e44cf12010-02-14 17:14:22 +0000429const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000430
icculus9e44cf12010-02-14 17:14:22 +0000431void Strsafe_init(void);
432int Strsafe_insert(const char *);
433const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000434
435/* Routines for handling symbols of the grammar */
436
icculus9e44cf12010-02-14 17:14:22 +0000437struct symbol *Symbol_new(const char *);
438int Symbolcmpp(const void *, const void *);
439void Symbol_init(void);
440int Symbol_insert(struct symbol *, const char *);
441struct symbol *Symbol_find(const char *);
442struct symbol *Symbol_Nth(int);
443int Symbol_count(void);
444struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000445
446/* Routines to manage the state table */
447
icculus9e44cf12010-02-14 17:14:22 +0000448int Configcmp(const char *, const char *);
449struct state *State_new(void);
450void State_init(void);
451int State_insert(struct state *, struct config *);
452struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000453struct state **State_arrayof(/* */);
454
455/* Routines used for efficiency in Configlist_add */
456
icculus9e44cf12010-02-14 17:14:22 +0000457void Configtable_init(void);
458int Configtable_insert(struct config *);
459struct config *Configtable_find(struct config *);
460void Configtable_clear(int(*)(struct config *));
461
drh75897232000-05-29 14:26:00 +0000462/****************** From the file "action.c" *******************************/
463/*
464** Routines processing parser actions in the LEMON parser generator.
465*/
466
467/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000468static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000469 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000470 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000471
472 if( freelist==0 ){
473 int i;
474 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000475 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000476 if( freelist==0 ){
477 fprintf(stderr,"Unable to allocate memory for a new parser action.");
478 exit(1);
479 }
480 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
481 freelist[amt-1].next = 0;
482 }
icculus9e44cf12010-02-14 17:14:22 +0000483 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000484 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000485 return newaction;
drh75897232000-05-29 14:26:00 +0000486}
487
drhe9278182007-07-18 18:16:29 +0000488/* Compare two actions for sorting purposes. Return negative, zero, or
489** positive if the first action is less than, equal to, or greater than
490** the first
491*/
492static int actioncmp(
493 struct action *ap1,
494 struct action *ap2
495){
drh75897232000-05-29 14:26:00 +0000496 int rc;
497 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000498 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000499 rc = (int)ap1->type - (int)ap2->type;
500 }
drh3bd48ab2015-09-07 18:23:37 +0000501 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000502 rc = ap1->x.rp->index - ap2->x.rp->index;
503 }
drhe594bc32009-11-03 13:02:25 +0000504 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000505 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000506 }
drh75897232000-05-29 14:26:00 +0000507 return rc;
508}
509
510/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000511static struct action *Action_sort(
512 struct action *ap
513){
514 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
515 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000516 return ap;
517}
518
icculus9e44cf12010-02-14 17:14:22 +0000519void Action_add(
520 struct action **app,
521 enum e_action type,
522 struct symbol *sp,
523 char *arg
524){
525 struct action *newaction;
526 newaction = Action_new();
527 newaction->next = *app;
528 *app = newaction;
529 newaction->type = type;
530 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000531 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000532 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000533 }else{
icculus9e44cf12010-02-14 17:14:22 +0000534 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000535 }
536}
drh8b582012003-10-21 13:16:03 +0000537/********************** New code to implement the "acttab" module ***********/
538/*
539** This module implements routines use to construct the yy_action[] table.
540*/
541
542/*
543** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000544** the following structure.
545**
546** The yy_action table maps the pair (state_number, lookahead) into an
547** action_number. The table is an array of integers pairs. The state_number
548** determines an initial offset into the yy_action array. The lookahead
549** value is then added to this initial offset to get an index X into the
550** yy_action array. If the aAction[X].lookahead equals the value of the
551** of the lookahead input, then the value of the action_number output is
552** aAction[X].action. If the lookaheads do not match then the
553** default action for the state_number is returned.
554**
555** All actions associated with a single state_number are first entered
556** into aLookahead[] using multiple calls to acttab_action(). Then the
557** actions for that single state_number are placed into the aAction[]
558** array with a single call to acttab_insert(). The acttab_insert() call
559** also resets the aLookahead[] array in preparation for the next
560** state number.
drh8b582012003-10-21 13:16:03 +0000561*/
icculus9e44cf12010-02-14 17:14:22 +0000562struct lookahead_action {
563 int lookahead; /* Value of the lookahead token */
564 int action; /* Action to take on the given lookahead */
565};
drh8b582012003-10-21 13:16:03 +0000566typedef struct acttab acttab;
567struct acttab {
568 int nAction; /* Number of used slots in aAction[] */
569 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000570 struct lookahead_action
571 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000572 *aLookahead; /* A single new transaction set */
573 int mnLookahead; /* Minimum aLookahead[].lookahead */
574 int mnAction; /* Action associated with mnLookahead */
575 int mxLookahead; /* Maximum aLookahead[].lookahead */
576 int nLookahead; /* Used slots in aLookahead[] */
577 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
578};
579
580/* Return the number of entries in the yy_action table */
581#define acttab_size(X) ((X)->nAction)
582
583/* The value for the N-th entry in yy_action */
584#define acttab_yyaction(X,N) ((X)->aAction[N].action)
585
586/* The value for the N-th entry in yy_lookahead */
587#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
588
589/* Free all memory associated with the given acttab */
590void acttab_free(acttab *p){
591 free( p->aAction );
592 free( p->aLookahead );
593 free( p );
594}
595
596/* Allocate a new acttab structure */
597acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000598 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000599 if( p==0 ){
600 fprintf(stderr,"Unable to allocate memory for a new acttab.");
601 exit(1);
602 }
603 memset(p, 0, sizeof(*p));
604 return p;
605}
606
drh8dc3e8f2010-01-07 03:53:03 +0000607/* Add a new action to the current transaction set.
608**
609** This routine is called once for each lookahead for a particular
610** state.
drh8b582012003-10-21 13:16:03 +0000611*/
612void acttab_action(acttab *p, int lookahead, int action){
613 if( p->nLookahead>=p->nLookaheadAlloc ){
614 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000615 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000616 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
617 if( p->aLookahead==0 ){
618 fprintf(stderr,"malloc failed\n");
619 exit(1);
620 }
621 }
622 if( p->nLookahead==0 ){
623 p->mxLookahead = lookahead;
624 p->mnLookahead = lookahead;
625 p->mnAction = action;
626 }else{
627 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
628 if( p->mnLookahead>lookahead ){
629 p->mnLookahead = lookahead;
630 p->mnAction = action;
631 }
632 }
633 p->aLookahead[p->nLookahead].lookahead = lookahead;
634 p->aLookahead[p->nLookahead].action = action;
635 p->nLookahead++;
636}
637
638/*
639** Add the transaction set built up with prior calls to acttab_action()
640** into the current action table. Then reset the transaction set back
641** to an empty set in preparation for a new round of acttab_action() calls.
642**
643** Return the offset into the action table of the new transaction.
644*/
645int acttab_insert(acttab *p){
646 int i, j, k, n;
647 assert( p->nLookahead>0 );
648
649 /* Make sure we have enough space to hold the expanded action table
650 ** in the worst case. The worst case occurs if the transaction set
651 ** must be appended to the current action table
652 */
drh784d86f2004-02-19 18:41:53 +0000653 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000654 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000655 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000656 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000657 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000658 sizeof(p->aAction[0])*p->nActionAlloc);
659 if( p->aAction==0 ){
660 fprintf(stderr,"malloc failed\n");
661 exit(1);
662 }
drhfdbf9282003-10-21 16:34:41 +0000663 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000664 p->aAction[i].lookahead = -1;
665 p->aAction[i].action = -1;
666 }
667 }
668
drh8dc3e8f2010-01-07 03:53:03 +0000669 /* Scan the existing action table looking for an offset that is a
670 ** duplicate of the current transaction set. Fall out of the loop
671 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000672 **
673 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
674 */
drh8dc3e8f2010-01-07 03:53:03 +0000675 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000676 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000677 /* All lookaheads and actions in the aLookahead[] transaction
678 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000679 if( p->aAction[i].action!=p->mnAction ) continue;
680 for(j=0; j<p->nLookahead; j++){
681 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
682 if( k<0 || k>=p->nAction ) break;
683 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
684 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
685 }
686 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000687
688 /* No possible lookahead value that is not in the aLookahead[]
689 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000690 n = 0;
691 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000692 if( p->aAction[j].lookahead<0 ) continue;
693 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000694 }
drhfdbf9282003-10-21 16:34:41 +0000695 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000696 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000697 }
drh8b582012003-10-21 13:16:03 +0000698 }
699 }
drh8dc3e8f2010-01-07 03:53:03 +0000700
701 /* If no existing offsets exactly match the current transaction, find an
702 ** an empty offset in the aAction[] table in which we can add the
703 ** aLookahead[] transaction.
704 */
drhf16371d2009-11-03 19:18:31 +0000705 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000706 /* Look for holes in the aAction[] table that fit the current
707 ** aLookahead[] transaction. Leave i set to the offset of the hole.
708 ** If no holes are found, i is left at p->nAction, which means the
709 ** transaction will be appended. */
710 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000711 if( p->aAction[i].lookahead<0 ){
712 for(j=0; j<p->nLookahead; j++){
713 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
714 if( k<0 ) break;
715 if( p->aAction[k].lookahead>=0 ) break;
716 }
717 if( j<p->nLookahead ) continue;
718 for(j=0; j<p->nAction; j++){
719 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
720 }
721 if( j==p->nAction ){
722 break; /* Fits in empty slots */
723 }
724 }
725 }
726 }
drh8b582012003-10-21 13:16:03 +0000727 /* Insert transaction set at index i. */
728 for(j=0; j<p->nLookahead; j++){
729 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
730 p->aAction[k] = p->aLookahead[j];
731 if( k>=p->nAction ) p->nAction = k+1;
732 }
733 p->nLookahead = 0;
734
735 /* Return the offset that is added to the lookahead in order to get the
736 ** index into yy_action of the action */
737 return i - p->mnLookahead;
738}
739
drh75897232000-05-29 14:26:00 +0000740/********************** From the file "build.c" *****************************/
741/*
742** Routines to construction the finite state machine for the LEMON
743** parser generator.
744*/
745
746/* Find a precedence symbol of every rule in the grammar.
747**
748** Those rules which have a precedence symbol coded in the input
749** grammar using the "[symbol]" construct will already have the
750** rp->precsym field filled. Other rules take as their precedence
751** symbol the first RHS symbol with a defined precedence. If there
752** are not RHS symbols with a defined precedence, the precedence
753** symbol field is left blank.
754*/
icculus9e44cf12010-02-14 17:14:22 +0000755void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000756{
757 struct rule *rp;
758 for(rp=xp->rule; rp; rp=rp->next){
759 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000760 int i, j;
761 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
762 struct symbol *sp = rp->rhs[i];
763 if( sp->type==MULTITERMINAL ){
764 for(j=0; j<sp->nsubsym; j++){
765 if( sp->subsym[j]->prec>=0 ){
766 rp->precsym = sp->subsym[j];
767 break;
768 }
769 }
770 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000771 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000772 }
drh75897232000-05-29 14:26:00 +0000773 }
774 }
775 }
776 return;
777}
778
779/* Find all nonterminals which will generate the empty string.
780** Then go back and compute the first sets of every nonterminal.
781** The first set is the set of all terminal symbols which can begin
782** a string generated by that nonterminal.
783*/
icculus9e44cf12010-02-14 17:14:22 +0000784void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000785{
drhfd405312005-11-06 04:06:59 +0000786 int i, j;
drh75897232000-05-29 14:26:00 +0000787 struct rule *rp;
788 int progress;
789
790 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000791 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000792 }
793 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
794 lemp->symbols[i]->firstset = SetNew();
795 }
796
797 /* First compute all lambdas */
798 do{
799 progress = 0;
800 for(rp=lemp->rule; rp; rp=rp->next){
801 if( rp->lhs->lambda ) continue;
802 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000803 struct symbol *sp = rp->rhs[i];
804 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
805 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000806 }
807 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000808 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000809 progress = 1;
810 }
811 }
812 }while( progress );
813
814 /* Now compute all first sets */
815 do{
816 struct symbol *s1, *s2;
817 progress = 0;
818 for(rp=lemp->rule; rp; rp=rp->next){
819 s1 = rp->lhs;
820 for(i=0; i<rp->nrhs; i++){
821 s2 = rp->rhs[i];
822 if( s2->type==TERMINAL ){
823 progress += SetAdd(s1->firstset,s2->index);
824 break;
drhfd405312005-11-06 04:06:59 +0000825 }else if( s2->type==MULTITERMINAL ){
826 for(j=0; j<s2->nsubsym; j++){
827 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
828 }
829 break;
drhf2f105d2012-08-20 15:53:54 +0000830 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000831 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000832 }else{
drh75897232000-05-29 14:26:00 +0000833 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000834 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000835 }
drh75897232000-05-29 14:26:00 +0000836 }
837 }
838 }while( progress );
839 return;
840}
841
842/* Compute all LR(0) states for the grammar. Links
843** are added to between some states so that the LR(1) follow sets
844** can be computed later.
845*/
icculus9e44cf12010-02-14 17:14:22 +0000846PRIVATE struct state *getstate(struct lemon *); /* forward reference */
847void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000848{
849 struct symbol *sp;
850 struct rule *rp;
851
852 Configlist_init();
853
854 /* Find the start symbol */
855 if( lemp->start ){
856 sp = Symbol_find(lemp->start);
857 if( sp==0 ){
858 ErrorMsg(lemp->filename,0,
859"The specified start symbol \"%s\" is not \
860in a nonterminal of the grammar. \"%s\" will be used as the start \
861symbol instead.",lemp->start,lemp->rule->lhs->name);
862 lemp->errorcnt++;
863 sp = lemp->rule->lhs;
864 }
865 }else{
866 sp = lemp->rule->lhs;
867 }
868
869 /* Make sure the start symbol doesn't occur on the right-hand side of
870 ** any rule. Report an error if it does. (YACC would generate a new
871 ** start symbol in this case.) */
872 for(rp=lemp->rule; rp; rp=rp->next){
873 int i;
874 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000875 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000876 ErrorMsg(lemp->filename,0,
877"The start symbol \"%s\" occurs on the \
878right-hand side of a rule. This will result in a parser which \
879does not work properly.",sp->name);
880 lemp->errorcnt++;
881 }
882 }
883 }
884
885 /* The basis configuration set for the first state
886 ** is all rules which have the start symbol as their
887 ** left-hand side */
888 for(rp=sp->rule; rp; rp=rp->nextlhs){
889 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000890 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000891 newcfp = Configlist_addbasis(rp,0);
892 SetAdd(newcfp->fws,0);
893 }
894
895 /* Compute the first state. All other states will be
896 ** computed automatically during the computation of the first one.
897 ** The returned pointer to the first state is not used. */
898 (void)getstate(lemp);
899 return;
900}
901
902/* Return a pointer to a state which is described by the configuration
903** list which has been built from calls to Configlist_add.
904*/
icculus9e44cf12010-02-14 17:14:22 +0000905PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
906PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000907{
908 struct config *cfp, *bp;
909 struct state *stp;
910
911 /* Extract the sorted basis of the new state. The basis was constructed
912 ** by prior calls to "Configlist_addbasis()". */
913 Configlist_sortbasis();
914 bp = Configlist_basis();
915
916 /* Get a state with the same basis */
917 stp = State_find(bp);
918 if( stp ){
919 /* A state with the same basis already exists! Copy all the follow-set
920 ** propagation links from the state under construction into the
921 ** preexisting state, then return a pointer to the preexisting state */
922 struct config *x, *y;
923 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
924 Plink_copy(&y->bplp,x->bplp);
925 Plink_delete(x->fplp);
926 x->fplp = x->bplp = 0;
927 }
928 cfp = Configlist_return();
929 Configlist_eat(cfp);
930 }else{
931 /* This really is a new state. Construct all the details */
932 Configlist_closure(lemp); /* Compute the configuration closure */
933 Configlist_sort(); /* Sort the configuration closure */
934 cfp = Configlist_return(); /* Get a pointer to the config list */
935 stp = State_new(); /* A new state structure */
936 MemoryCheck(stp);
937 stp->bp = bp; /* Remember the configuration basis */
938 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000939 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000940 stp->ap = 0; /* No actions, yet. */
941 State_insert(stp,stp->bp); /* Add to the state table */
942 buildshifts(lemp,stp); /* Recursively compute successor states */
943 }
944 return stp;
945}
946
drhfd405312005-11-06 04:06:59 +0000947/*
948** Return true if two symbols are the same.
949*/
icculus9e44cf12010-02-14 17:14:22 +0000950int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000951{
952 int i;
953 if( a==b ) return 1;
954 if( a->type!=MULTITERMINAL ) return 0;
955 if( b->type!=MULTITERMINAL ) return 0;
956 if( a->nsubsym!=b->nsubsym ) return 0;
957 for(i=0; i<a->nsubsym; i++){
958 if( a->subsym[i]!=b->subsym[i] ) return 0;
959 }
960 return 1;
961}
962
drh75897232000-05-29 14:26:00 +0000963/* Construct all successor states to the given state. A "successor"
964** state is any state which can be reached by a shift action.
965*/
icculus9e44cf12010-02-14 17:14:22 +0000966PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000967{
968 struct config *cfp; /* For looping thru the config closure of "stp" */
969 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000970 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000971 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
972 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
973 struct state *newstp; /* A pointer to a successor state */
974
975 /* Each configuration becomes complete after it contibutes to a successor
976 ** state. Initially, all configurations are incomplete */
977 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
978
979 /* Loop through all configurations of the state "stp" */
980 for(cfp=stp->cfp; cfp; cfp=cfp->next){
981 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
982 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
983 Configlist_reset(); /* Reset the new config set */
984 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
985
986 /* For every configuration in the state "stp" which has the symbol "sp"
987 ** following its dot, add the same configuration to the basis set under
988 ** construction but with the dot shifted one symbol to the right. */
989 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
990 if( bcfp->status==COMPLETE ) continue; /* Already used */
991 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
992 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000993 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000994 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000995 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
996 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000997 }
998
999 /* Get a pointer to the state described by the basis configuration set
1000 ** constructed in the preceding loop */
1001 newstp = getstate(lemp);
1002
1003 /* The state "newstp" is reached from the state "stp" by a shift action
1004 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +00001005 if( sp->type==MULTITERMINAL ){
1006 int i;
1007 for(i=0; i<sp->nsubsym; i++){
1008 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
1009 }
1010 }else{
1011 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1012 }
drh75897232000-05-29 14:26:00 +00001013 }
1014}
1015
1016/*
1017** Construct the propagation links
1018*/
icculus9e44cf12010-02-14 17:14:22 +00001019void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001020{
1021 int i;
1022 struct config *cfp, *other;
1023 struct state *stp;
1024 struct plink *plp;
1025
1026 /* Housekeeping detail:
1027 ** Add to every propagate link a pointer back to the state to
1028 ** which the link is attached. */
1029 for(i=0; i<lemp->nstate; i++){
1030 stp = lemp->sorted[i];
1031 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1032 cfp->stp = stp;
1033 }
1034 }
1035
1036 /* Convert all backlinks into forward links. Only the forward
1037 ** links are used in the follow-set computation. */
1038 for(i=0; i<lemp->nstate; i++){
1039 stp = lemp->sorted[i];
1040 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1041 for(plp=cfp->bplp; plp; plp=plp->next){
1042 other = plp->cfp;
1043 Plink_add(&other->fplp,cfp);
1044 }
1045 }
1046 }
1047}
1048
1049/* Compute all followsets.
1050**
1051** A followset is the set of all symbols which can come immediately
1052** after a configuration.
1053*/
icculus9e44cf12010-02-14 17:14:22 +00001054void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001055{
1056 int i;
1057 struct config *cfp;
1058 struct plink *plp;
1059 int progress;
1060 int change;
1061
1062 for(i=0; i<lemp->nstate; i++){
1063 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1064 cfp->status = INCOMPLETE;
1065 }
1066 }
1067
1068 do{
1069 progress = 0;
1070 for(i=0; i<lemp->nstate; i++){
1071 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1072 if( cfp->status==COMPLETE ) continue;
1073 for(plp=cfp->fplp; plp; plp=plp->next){
1074 change = SetUnion(plp->cfp->fws,cfp->fws);
1075 if( change ){
1076 plp->cfp->status = INCOMPLETE;
1077 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001078 }
1079 }
drh75897232000-05-29 14:26:00 +00001080 cfp->status = COMPLETE;
1081 }
1082 }
1083 }while( progress );
1084}
1085
drh3cb2f6e2012-01-09 14:19:05 +00001086static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001087
1088/* Compute the reduce actions, and resolve conflicts.
1089*/
icculus9e44cf12010-02-14 17:14:22 +00001090void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001091{
1092 int i,j;
1093 struct config *cfp;
1094 struct state *stp;
1095 struct symbol *sp;
1096 struct rule *rp;
1097
1098 /* Add all of the reduce actions
1099 ** A reduce action is added for each element of the followset of
1100 ** a configuration which has its dot at the extreme right.
1101 */
1102 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1103 stp = lemp->sorted[i];
1104 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1105 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1106 for(j=0; j<lemp->nterminal; j++){
1107 if( SetFind(cfp->fws,j) ){
1108 /* Add a reduce action to the state "stp" which will reduce by the
1109 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001110 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001111 }
drhf2f105d2012-08-20 15:53:54 +00001112 }
drh75897232000-05-29 14:26:00 +00001113 }
1114 }
1115 }
1116
1117 /* Add the accepting token */
1118 if( lemp->start ){
1119 sp = Symbol_find(lemp->start);
1120 if( sp==0 ) sp = lemp->rule->lhs;
1121 }else{
1122 sp = lemp->rule->lhs;
1123 }
1124 /* Add to the first state (which is always the starting state of the
1125 ** finite state machine) an action to ACCEPT if the lookahead is the
1126 ** start nonterminal. */
1127 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1128
1129 /* Resolve conflicts */
1130 for(i=0; i<lemp->nstate; i++){
1131 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001132 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001133 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001134 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001135 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001136 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1137 /* The two actions "ap" and "nap" have the same lookahead.
1138 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001139 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001140 }
1141 }
1142 }
1143
1144 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001145 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001146 for(i=0; i<lemp->nstate; i++){
1147 struct action *ap;
1148 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001149 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001150 }
1151 }
1152 for(rp=lemp->rule; rp; rp=rp->next){
1153 if( rp->canReduce ) continue;
1154 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1155 lemp->errorcnt++;
1156 }
1157}
1158
1159/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001160** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001161**
1162** NO LONGER TRUE:
1163** To resolve a conflict, first look to see if either action
1164** is on an error rule. In that case, take the action which
1165** is not associated with the error rule. If neither or both
1166** actions are associated with an error rule, then try to
1167** use precedence to resolve the conflict.
1168**
1169** If either action is a SHIFT, then it must be apx. This
1170** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1171*/
icculus9e44cf12010-02-14 17:14:22 +00001172static int resolve_conflict(
1173 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001174 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001175){
drh75897232000-05-29 14:26:00 +00001176 struct symbol *spx, *spy;
1177 int errcnt = 0;
1178 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001179 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001180 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001181 errcnt++;
1182 }
drh75897232000-05-29 14:26:00 +00001183 if( apx->type==SHIFT && apy->type==REDUCE ){
1184 spx = apx->sp;
1185 spy = apy->x.rp->precsym;
1186 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1187 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001188 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001189 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001190 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001191 apy->type = RD_RESOLVED;
1192 }else if( spx->prec<spy->prec ){
1193 apx->type = SH_RESOLVED;
1194 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1195 apy->type = RD_RESOLVED; /* associativity */
1196 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1197 apx->type = SH_RESOLVED;
1198 }else{
1199 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001200 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001201 }
1202 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1203 spx = apx->x.rp->precsym;
1204 spy = apy->x.rp->precsym;
1205 if( spx==0 || spy==0 || spx->prec<0 ||
1206 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001207 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001208 errcnt++;
1209 }else if( spx->prec>spy->prec ){
1210 apy->type = RD_RESOLVED;
1211 }else if( spx->prec<spy->prec ){
1212 apx->type = RD_RESOLVED;
1213 }
1214 }else{
drhb59499c2002-02-23 18:45:13 +00001215 assert(
1216 apx->type==SH_RESOLVED ||
1217 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001218 apx->type==SSCONFLICT ||
1219 apx->type==SRCONFLICT ||
1220 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001221 apy->type==SH_RESOLVED ||
1222 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001223 apy->type==SSCONFLICT ||
1224 apy->type==SRCONFLICT ||
1225 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001226 );
1227 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1228 ** REDUCEs on the list. If we reach this point it must be because
1229 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001230 }
1231 return errcnt;
1232}
1233/********************* From the file "configlist.c" *************************/
1234/*
1235** Routines to processing a configuration list and building a state
1236** in the LEMON parser generator.
1237*/
1238
1239static struct config *freelist = 0; /* List of free configurations */
1240static struct config *current = 0; /* Top of list of configurations */
1241static struct config **currentend = 0; /* Last on list of configs */
1242static struct config *basis = 0; /* Top of list of basis configs */
1243static struct config **basisend = 0; /* End of list of basis configs */
1244
1245/* Return a pointer to a new configuration */
1246PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001247 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001248 if( freelist==0 ){
1249 int i;
1250 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001251 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001252 if( freelist==0 ){
1253 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1254 exit(1);
1255 }
1256 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1257 freelist[amt-1].next = 0;
1258 }
icculus9e44cf12010-02-14 17:14:22 +00001259 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001260 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001261 return newcfg;
drh75897232000-05-29 14:26:00 +00001262}
1263
1264/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001265PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001266{
1267 old->next = freelist;
1268 freelist = old;
1269}
1270
1271/* Initialized the configuration list builder */
1272void Configlist_init(){
1273 current = 0;
1274 currentend = &current;
1275 basis = 0;
1276 basisend = &basis;
1277 Configtable_init();
1278 return;
1279}
1280
1281/* Initialized the configuration list builder */
1282void Configlist_reset(){
1283 current = 0;
1284 currentend = &current;
1285 basis = 0;
1286 basisend = &basis;
1287 Configtable_clear(0);
1288 return;
1289}
1290
1291/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001292struct config *Configlist_add(
1293 struct rule *rp, /* The rule */
1294 int dot /* Index into the RHS of the rule where the dot goes */
1295){
drh75897232000-05-29 14:26:00 +00001296 struct config *cfp, model;
1297
1298 assert( currentend!=0 );
1299 model.rp = rp;
1300 model.dot = dot;
1301 cfp = Configtable_find(&model);
1302 if( cfp==0 ){
1303 cfp = newconfig();
1304 cfp->rp = rp;
1305 cfp->dot = dot;
1306 cfp->fws = SetNew();
1307 cfp->stp = 0;
1308 cfp->fplp = cfp->bplp = 0;
1309 cfp->next = 0;
1310 cfp->bp = 0;
1311 *currentend = cfp;
1312 currentend = &cfp->next;
1313 Configtable_insert(cfp);
1314 }
1315 return cfp;
1316}
1317
1318/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001319struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001320{
1321 struct config *cfp, model;
1322
1323 assert( basisend!=0 );
1324 assert( currentend!=0 );
1325 model.rp = rp;
1326 model.dot = dot;
1327 cfp = Configtable_find(&model);
1328 if( cfp==0 ){
1329 cfp = newconfig();
1330 cfp->rp = rp;
1331 cfp->dot = dot;
1332 cfp->fws = SetNew();
1333 cfp->stp = 0;
1334 cfp->fplp = cfp->bplp = 0;
1335 cfp->next = 0;
1336 cfp->bp = 0;
1337 *currentend = cfp;
1338 currentend = &cfp->next;
1339 *basisend = cfp;
1340 basisend = &cfp->bp;
1341 Configtable_insert(cfp);
1342 }
1343 return cfp;
1344}
1345
1346/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001347void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001348{
1349 struct config *cfp, *newcfp;
1350 struct rule *rp, *newrp;
1351 struct symbol *sp, *xsp;
1352 int i, dot;
1353
1354 assert( currentend!=0 );
1355 for(cfp=current; cfp; cfp=cfp->next){
1356 rp = cfp->rp;
1357 dot = cfp->dot;
1358 if( dot>=rp->nrhs ) continue;
1359 sp = rp->rhs[dot];
1360 if( sp->type==NONTERMINAL ){
1361 if( sp->rule==0 && sp!=lemp->errsym ){
1362 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1363 sp->name);
1364 lemp->errorcnt++;
1365 }
1366 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1367 newcfp = Configlist_add(newrp,0);
1368 for(i=dot+1; i<rp->nrhs; i++){
1369 xsp = rp->rhs[i];
1370 if( xsp->type==TERMINAL ){
1371 SetAdd(newcfp->fws,xsp->index);
1372 break;
drhfd405312005-11-06 04:06:59 +00001373 }else if( xsp->type==MULTITERMINAL ){
1374 int k;
1375 for(k=0; k<xsp->nsubsym; k++){
1376 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1377 }
1378 break;
drhf2f105d2012-08-20 15:53:54 +00001379 }else{
drh75897232000-05-29 14:26:00 +00001380 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001381 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001382 }
1383 }
drh75897232000-05-29 14:26:00 +00001384 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1385 }
1386 }
1387 }
1388 return;
1389}
1390
1391/* Sort the configuration list */
1392void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001393 current = (struct config*)msort((char*)current,(char**)&(current->next),
1394 Configcmp);
drh75897232000-05-29 14:26:00 +00001395 currentend = 0;
1396 return;
1397}
1398
1399/* Sort the basis configuration list */
1400void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001401 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1402 Configcmp);
drh75897232000-05-29 14:26:00 +00001403 basisend = 0;
1404 return;
1405}
1406
1407/* Return a pointer to the head of the configuration list and
1408** reset the list */
1409struct config *Configlist_return(){
1410 struct config *old;
1411 old = current;
1412 current = 0;
1413 currentend = 0;
1414 return old;
1415}
1416
1417/* Return a pointer to the head of the configuration list and
1418** reset the list */
1419struct config *Configlist_basis(){
1420 struct config *old;
1421 old = basis;
1422 basis = 0;
1423 basisend = 0;
1424 return old;
1425}
1426
1427/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001428void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001429{
1430 struct config *nextcfp;
1431 for(; cfp; cfp=nextcfp){
1432 nextcfp = cfp->next;
1433 assert( cfp->fplp==0 );
1434 assert( cfp->bplp==0 );
1435 if( cfp->fws ) SetFree(cfp->fws);
1436 deleteconfig(cfp);
1437 }
1438 return;
1439}
1440/***************** From the file "error.c" *********************************/
1441/*
1442** Code for printing error message.
1443*/
1444
drhf9a2e7b2003-04-15 01:49:48 +00001445void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001446 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001447 fprintf(stderr, "%s:%d: ", filename, lineno);
1448 va_start(ap, format);
1449 vfprintf(stderr,format,ap);
1450 va_end(ap);
1451 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001452}
1453/**************** From the file "main.c" ************************************/
1454/*
1455** Main program file for the LEMON parser generator.
1456*/
1457
1458/* Report an out-of-memory condition and abort. This function
1459** is used mostly by the "MemoryCheck" macro in struct.h
1460*/
1461void memory_error(){
1462 fprintf(stderr,"Out of memory. Aborting...\n");
1463 exit(1);
1464}
1465
drh6d08b4d2004-07-20 12:45:22 +00001466static int nDefine = 0; /* Number of -D options on the command line */
1467static char **azDefine = 0; /* Name of the -D macros */
1468
1469/* This routine is called with the argument to each -D command-line option.
1470** Add the macro defined to the azDefine array.
1471*/
1472static void handle_D_option(char *z){
1473 char **paz;
1474 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001475 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001476 if( azDefine==0 ){
1477 fprintf(stderr,"out of memory\n");
1478 exit(1);
1479 }
1480 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001481 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001482 if( *paz==0 ){
1483 fprintf(stderr,"out of memory\n");
1484 exit(1);
1485 }
drh898799f2014-01-10 23:21:00 +00001486 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001487 for(z=*paz; *z && *z!='='; z++){}
1488 *z = 0;
1489}
1490
icculus3e143bd2010-02-14 00:48:49 +00001491static char *user_templatename = NULL;
1492static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001493 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001494 if( user_templatename==0 ){
1495 memory_error();
1496 }
drh898799f2014-01-10 23:21:00 +00001497 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001498}
drh75897232000-05-29 14:26:00 +00001499
drhc75e0162015-09-07 02:23:02 +00001500/* forward reference */
1501static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1502
1503/* Print a single line of the "Parser Stats" output
1504*/
1505static void stats_line(const char *zLabel, int iValue){
1506 int nLabel = lemonStrlen(zLabel);
1507 printf(" %s%.*s %5d\n", zLabel,
1508 35-nLabel, "................................",
1509 iValue);
1510}
1511
drh75897232000-05-29 14:26:00 +00001512/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001513int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001514{
1515 static int version = 0;
1516 static int rpflag = 0;
1517 static int basisflag = 0;
1518 static int compress = 0;
1519 static int quiet = 0;
1520 static int statistics = 0;
1521 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001522 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001523 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001524 static struct s_options options[] = {
1525 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1526 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001527 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001528 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001529 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001530 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001531 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1532 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001533 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001534 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1535 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001536 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001537 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001538 {OPT_FLAG, "s", (char*)&statistics,
1539 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001540 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001541 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1542 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001543 {OPT_FLAG,0,0,0}
1544 };
1545 int i;
icculus42585cf2010-02-14 05:19:56 +00001546 int exitcode;
drh75897232000-05-29 14:26:00 +00001547 struct lemon lem;
1548
drhb0c86772000-06-02 23:21:26 +00001549 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001550 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001551 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001552 exit(0);
1553 }
drhb0c86772000-06-02 23:21:26 +00001554 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001555 fprintf(stderr,"Exactly one filename argument is required.\n");
1556 exit(1);
1557 }
drh954f6b42006-06-13 13:27:46 +00001558 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001559 lem.errorcnt = 0;
1560
1561 /* Initialize the machine */
1562 Strsafe_init();
1563 Symbol_init();
1564 State_init();
1565 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001566 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001567 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001568 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001569 Symbol_new("$");
1570 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001571 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001572
1573 /* Parse the input file */
1574 Parse(&lem);
1575 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001576 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001577 fprintf(stderr,"Empty grammar.\n");
1578 exit(1);
1579 }
1580
1581 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001582 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001583 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001584 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001585 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1586 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1587 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1588 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1589 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1590 lem.nsymbol = i - 1;
drhc56fac72015-10-29 13:48:15 +00001591 for(i=1; ISUPPER(lem.symbols[i]->name[0]); i++);
drh75897232000-05-29 14:26:00 +00001592 lem.nterminal = i;
1593
1594 /* Generate a reprint of the grammar, if requested on the command line */
1595 if( rpflag ){
1596 Reprint(&lem);
1597 }else{
1598 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001599 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001600
1601 /* Find the precedence for every production rule (that has one) */
1602 FindRulePrecedences(&lem);
1603
1604 /* Compute the lambda-nonterminals and the first-sets for every
1605 ** nonterminal */
1606 FindFirstSets(&lem);
1607
1608 /* Compute all LR(0) states. Also record follow-set propagation
1609 ** links so that the follow-set can be computed later */
1610 lem.nstate = 0;
1611 FindStates(&lem);
1612 lem.sorted = State_arrayof();
1613
1614 /* Tie up loose ends on the propagation links */
1615 FindLinks(&lem);
1616
1617 /* Compute the follow set of every reducible configuration */
1618 FindFollowSets(&lem);
1619
1620 /* Compute the action tables */
1621 FindActions(&lem);
1622
1623 /* Compress the action tables */
1624 if( compress==0 ) CompressTables(&lem);
1625
drhada354d2005-11-05 15:03:59 +00001626 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001627 ** occur at the end. This is an optimization that helps make the
1628 ** generated parser tables smaller. */
1629 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001630
drh75897232000-05-29 14:26:00 +00001631 /* Generate a report of the parser generated. (the "y.output" file) */
1632 if( !quiet ) ReportOutput(&lem);
1633
1634 /* Generate the source code for the parser */
1635 ReportTable(&lem, mhflag);
1636
1637 /* Produce a header file for use by the scanner. (This step is
1638 ** omitted if the "-m" option is used because makeheaders will
1639 ** generate the file for us.) */
1640 if( !mhflag ) ReportHeader(&lem);
1641 }
1642 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001643 printf("Parser statistics:\n");
1644 stats_line("terminal symbols", lem.nterminal);
1645 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1646 stats_line("total symbols", lem.nsymbol);
1647 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001648 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001649 stats_line("conflicts", lem.nconflict);
1650 stats_line("action table entries", lem.nactiontab);
1651 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001652 }
icculus8e158022010-02-16 16:09:03 +00001653 if( lem.nconflict > 0 ){
1654 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001655 }
1656
1657 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001658 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001659 exit(exitcode);
1660 return (exitcode);
drh75897232000-05-29 14:26:00 +00001661}
1662/******************** From the file "msort.c" *******************************/
1663/*
1664** A generic merge-sort program.
1665**
1666** USAGE:
1667** Let "ptr" be a pointer to some structure which is at the head of
1668** a null-terminated list. Then to sort the list call:
1669**
1670** ptr = msort(ptr,&(ptr->next),cmpfnc);
1671**
1672** In the above, "cmpfnc" is a pointer to a function which compares
1673** two instances of the structure and returns an integer, as in
1674** strcmp. The second argument is a pointer to the pointer to the
1675** second element of the linked list. This address is used to compute
1676** the offset to the "next" field within the structure. The offset to
1677** the "next" field must be constant for all structures in the list.
1678**
1679** The function returns a new pointer which is the head of the list
1680** after sorting.
1681**
1682** ALGORITHM:
1683** Merge-sort.
1684*/
1685
1686/*
1687** Return a pointer to the next structure in the linked list.
1688*/
drhd25d6922012-04-18 09:59:56 +00001689#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001690
1691/*
1692** Inputs:
1693** a: A sorted, null-terminated linked list. (May be null).
1694** b: A sorted, null-terminated linked list. (May be null).
1695** cmp: A pointer to the comparison function.
1696** offset: Offset in the structure to the "next" field.
1697**
1698** Return Value:
1699** A pointer to the head of a sorted list containing the elements
1700** of both a and b.
1701**
1702** Side effects:
1703** The "next" pointers for elements in the lists a and b are
1704** changed.
1705*/
drhe9278182007-07-18 18:16:29 +00001706static char *merge(
1707 char *a,
1708 char *b,
1709 int (*cmp)(const char*,const char*),
1710 int offset
1711){
drh75897232000-05-29 14:26:00 +00001712 char *ptr, *head;
1713
1714 if( a==0 ){
1715 head = b;
1716 }else if( b==0 ){
1717 head = a;
1718 }else{
drhe594bc32009-11-03 13:02:25 +00001719 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001720 ptr = a;
1721 a = NEXT(a);
1722 }else{
1723 ptr = b;
1724 b = NEXT(b);
1725 }
1726 head = ptr;
1727 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001728 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001729 NEXT(ptr) = a;
1730 ptr = a;
1731 a = NEXT(a);
1732 }else{
1733 NEXT(ptr) = b;
1734 ptr = b;
1735 b = NEXT(b);
1736 }
1737 }
1738 if( a ) NEXT(ptr) = a;
1739 else NEXT(ptr) = b;
1740 }
1741 return head;
1742}
1743
1744/*
1745** Inputs:
1746** list: Pointer to a singly-linked list of structures.
1747** next: Pointer to pointer to the second element of the list.
1748** cmp: A comparison function.
1749**
1750** Return Value:
1751** A pointer to the head of a sorted list containing the elements
1752** orginally in list.
1753**
1754** Side effects:
1755** The "next" pointers for elements in list are changed.
1756*/
1757#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001758static char *msort(
1759 char *list,
1760 char **next,
1761 int (*cmp)(const char*,const char*)
1762){
drhba99af52001-10-25 20:37:16 +00001763 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001764 char *ep;
1765 char *set[LISTSIZE];
1766 int i;
drh1cc0d112015-03-31 15:15:48 +00001767 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001768 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1769 while( list ){
1770 ep = list;
1771 list = NEXT(list);
1772 NEXT(ep) = 0;
1773 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1774 ep = merge(ep,set[i],cmp,offset);
1775 set[i] = 0;
1776 }
1777 set[i] = ep;
1778 }
1779 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001780 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001781 return ep;
1782}
1783/************************ From the file "option.c" **************************/
1784static char **argv;
1785static struct s_options *op;
1786static FILE *errstream;
1787
1788#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1789
1790/*
1791** Print the command line with a carrot pointing to the k-th character
1792** of the n-th field.
1793*/
icculus9e44cf12010-02-14 17:14:22 +00001794static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001795{
1796 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001797 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001798 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001799 for(i=1; i<n && argv[i]; i++){
1800 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001801 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001802 }
1803 spcnt += k;
1804 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1805 if( spcnt<20 ){
1806 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1807 }else{
1808 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1809 }
1810}
1811
1812/*
1813** Return the index of the N-th non-switch argument. Return -1
1814** if N is out of range.
1815*/
icculus9e44cf12010-02-14 17:14:22 +00001816static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001817{
1818 int i;
1819 int dashdash = 0;
1820 if( argv!=0 && *argv!=0 ){
1821 for(i=1; argv[i]; i++){
1822 if( dashdash || !ISOPT(argv[i]) ){
1823 if( n==0 ) return i;
1824 n--;
1825 }
1826 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1827 }
1828 }
1829 return -1;
1830}
1831
1832static char emsg[] = "Command line syntax error: ";
1833
1834/*
1835** Process a flag command line argument.
1836*/
icculus9e44cf12010-02-14 17:14:22 +00001837static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001838{
1839 int v;
1840 int errcnt = 0;
1841 int j;
1842 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001843 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001844 }
1845 v = argv[i][0]=='-' ? 1 : 0;
1846 if( op[j].label==0 ){
1847 if( err ){
1848 fprintf(err,"%sundefined option.\n",emsg);
1849 errline(i,1,err);
1850 }
1851 errcnt++;
drh0325d392015-01-01 19:11:22 +00001852 }else if( op[j].arg==0 ){
1853 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001854 }else if( op[j].type==OPT_FLAG ){
1855 *((int*)op[j].arg) = v;
1856 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001857 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001858 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001859 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001860 }else{
1861 if( err ){
1862 fprintf(err,"%smissing argument on switch.\n",emsg);
1863 errline(i,1,err);
1864 }
1865 errcnt++;
1866 }
1867 return errcnt;
1868}
1869
1870/*
1871** Process a command line switch which has an argument.
1872*/
icculus9e44cf12010-02-14 17:14:22 +00001873static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001874{
1875 int lv = 0;
1876 double dv = 0.0;
1877 char *sv = 0, *end;
1878 char *cp;
1879 int j;
1880 int errcnt = 0;
1881 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001882 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001883 *cp = 0;
1884 for(j=0; op[j].label; j++){
1885 if( strcmp(argv[i],op[j].label)==0 ) break;
1886 }
1887 *cp = '=';
1888 if( op[j].label==0 ){
1889 if( err ){
1890 fprintf(err,"%sundefined option.\n",emsg);
1891 errline(i,0,err);
1892 }
1893 errcnt++;
1894 }else{
1895 cp++;
1896 switch( op[j].type ){
1897 case OPT_FLAG:
1898 case OPT_FFLAG:
1899 if( err ){
1900 fprintf(err,"%soption requires an argument.\n",emsg);
1901 errline(i,0,err);
1902 }
1903 errcnt++;
1904 break;
1905 case OPT_DBL:
1906 case OPT_FDBL:
1907 dv = strtod(cp,&end);
1908 if( *end ){
1909 if( err ){
drh25473362015-09-04 18:03:45 +00001910 fprintf(err,
1911 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001912 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001913 }
1914 errcnt++;
1915 }
1916 break;
1917 case OPT_INT:
1918 case OPT_FINT:
1919 lv = strtol(cp,&end,0);
1920 if( *end ){
1921 if( err ){
1922 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001923 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001924 }
1925 errcnt++;
1926 }
1927 break;
1928 case OPT_STR:
1929 case OPT_FSTR:
1930 sv = cp;
1931 break;
1932 }
1933 switch( op[j].type ){
1934 case OPT_FLAG:
1935 case OPT_FFLAG:
1936 break;
1937 case OPT_DBL:
1938 *(double*)(op[j].arg) = dv;
1939 break;
1940 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001941 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001942 break;
1943 case OPT_INT:
1944 *(int*)(op[j].arg) = lv;
1945 break;
1946 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001947 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001948 break;
1949 case OPT_STR:
1950 *(char**)(op[j].arg) = sv;
1951 break;
1952 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001953 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001954 break;
1955 }
1956 }
1957 return errcnt;
1958}
1959
icculus9e44cf12010-02-14 17:14:22 +00001960int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001961{
1962 int errcnt = 0;
1963 argv = a;
1964 op = o;
1965 errstream = err;
1966 if( argv && *argv && op ){
1967 int i;
1968 for(i=1; argv[i]; i++){
1969 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1970 errcnt += handleflags(i,err);
1971 }else if( strchr(argv[i],'=') ){
1972 errcnt += handleswitch(i,err);
1973 }
1974 }
1975 }
1976 if( errcnt>0 ){
1977 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001978 OptPrint();
drh75897232000-05-29 14:26:00 +00001979 exit(1);
1980 }
1981 return 0;
1982}
1983
drhb0c86772000-06-02 23:21:26 +00001984int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001985 int cnt = 0;
1986 int dashdash = 0;
1987 int i;
1988 if( argv!=0 && argv[0]!=0 ){
1989 for(i=1; argv[i]; i++){
1990 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1991 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1992 }
1993 }
1994 return cnt;
1995}
1996
icculus9e44cf12010-02-14 17:14:22 +00001997char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001998{
1999 int i;
2000 i = argindex(n);
2001 return i>=0 ? argv[i] : 0;
2002}
2003
icculus9e44cf12010-02-14 17:14:22 +00002004void OptErr(int n)
drh75897232000-05-29 14:26:00 +00002005{
2006 int i;
2007 i = argindex(n);
2008 if( i>=0 ) errline(i,0,errstream);
2009}
2010
drhb0c86772000-06-02 23:21:26 +00002011void OptPrint(){
drh75897232000-05-29 14:26:00 +00002012 int i;
2013 int max, len;
2014 max = 0;
2015 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002016 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002017 switch( op[i].type ){
2018 case OPT_FLAG:
2019 case OPT_FFLAG:
2020 break;
2021 case OPT_INT:
2022 case OPT_FINT:
2023 len += 9; /* length of "<integer>" */
2024 break;
2025 case OPT_DBL:
2026 case OPT_FDBL:
2027 len += 6; /* length of "<real>" */
2028 break;
2029 case OPT_STR:
2030 case OPT_FSTR:
2031 len += 8; /* length of "<string>" */
2032 break;
2033 }
2034 if( len>max ) max = len;
2035 }
2036 for(i=0; op[i].label; i++){
2037 switch( op[i].type ){
2038 case OPT_FLAG:
2039 case OPT_FFLAG:
2040 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2041 break;
2042 case OPT_INT:
2043 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002044 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002045 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002046 break;
2047 case OPT_DBL:
2048 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002049 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002050 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002051 break;
2052 case OPT_STR:
2053 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002054 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002055 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002056 break;
2057 }
2058 }
2059}
2060/*********************** From the file "parse.c" ****************************/
2061/*
2062** Input file parser for the LEMON parser generator.
2063*/
2064
2065/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002066enum e_state {
2067 INITIALIZE,
2068 WAITING_FOR_DECL_OR_RULE,
2069 WAITING_FOR_DECL_KEYWORD,
2070 WAITING_FOR_DECL_ARG,
2071 WAITING_FOR_PRECEDENCE_SYMBOL,
2072 WAITING_FOR_ARROW,
2073 IN_RHS,
2074 LHS_ALIAS_1,
2075 LHS_ALIAS_2,
2076 LHS_ALIAS_3,
2077 RHS_ALIAS_1,
2078 RHS_ALIAS_2,
2079 PRECEDENCE_MARK_1,
2080 PRECEDENCE_MARK_2,
2081 RESYNC_AFTER_RULE_ERROR,
2082 RESYNC_AFTER_DECL_ERROR,
2083 WAITING_FOR_DESTRUCTOR_SYMBOL,
2084 WAITING_FOR_DATATYPE_SYMBOL,
2085 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002086 WAITING_FOR_WILDCARD_ID,
2087 WAITING_FOR_CLASS_ID,
2088 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002089};
drh75897232000-05-29 14:26:00 +00002090struct pstate {
2091 char *filename; /* Name of the input file */
2092 int tokenlineno; /* Linenumber at which current token starts */
2093 int errorcnt; /* Number of errors so far */
2094 char *tokenstart; /* Text of current token */
2095 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002096 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002097 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002098 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002099 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002100 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002101 int nrhs; /* Number of right-hand side symbols seen */
2102 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002103 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002104 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002105 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002106 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002107 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002108 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002109 enum e_assoc declassoc; /* Assign this association to decl arguments */
2110 int preccounter; /* Assign this precedence to decl arguments */
2111 struct rule *firstrule; /* Pointer to first rule in the grammar */
2112 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2113};
2114
2115/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002116static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002117{
icculus9e44cf12010-02-14 17:14:22 +00002118 const char *x;
drh75897232000-05-29 14:26:00 +00002119 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2120#if 0
2121 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2122 x,psp->state);
2123#endif
2124 switch( psp->state ){
2125 case INITIALIZE:
2126 psp->prevrule = 0;
2127 psp->preccounter = 0;
2128 psp->firstrule = psp->lastrule = 0;
2129 psp->gp->nrule = 0;
2130 /* Fall thru to next case */
2131 case WAITING_FOR_DECL_OR_RULE:
2132 if( x[0]=='%' ){
2133 psp->state = WAITING_FOR_DECL_KEYWORD;
drhc56fac72015-10-29 13:48:15 +00002134 }else if( ISLOWER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002135 psp->lhs = Symbol_new(x);
2136 psp->nrhs = 0;
2137 psp->lhsalias = 0;
2138 psp->state = WAITING_FOR_ARROW;
2139 }else if( x[0]=='{' ){
2140 if( psp->prevrule==0 ){
2141 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002142"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002143fragment which begins on this line.");
2144 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002145 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002146 ErrorMsg(psp->filename,psp->tokenlineno,
2147"Code fragment beginning on this line is not the first \
2148to follow the previous rule.");
2149 psp->errorcnt++;
2150 }else{
2151 psp->prevrule->line = psp->tokenlineno;
2152 psp->prevrule->code = &x[1];
drhf2f105d2012-08-20 15:53:54 +00002153 }
drh75897232000-05-29 14:26:00 +00002154 }else if( x[0]=='[' ){
2155 psp->state = PRECEDENCE_MARK_1;
2156 }else{
2157 ErrorMsg(psp->filename,psp->tokenlineno,
2158 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2159 x);
2160 psp->errorcnt++;
2161 }
2162 break;
2163 case PRECEDENCE_MARK_1:
drhc56fac72015-10-29 13:48:15 +00002164 if( !ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002165 ErrorMsg(psp->filename,psp->tokenlineno,
2166 "The precedence symbol must be a terminal.");
2167 psp->errorcnt++;
2168 }else if( psp->prevrule==0 ){
2169 ErrorMsg(psp->filename,psp->tokenlineno,
2170 "There is no prior rule to assign precedence \"[%s]\".",x);
2171 psp->errorcnt++;
2172 }else if( psp->prevrule->precsym!=0 ){
2173 ErrorMsg(psp->filename,psp->tokenlineno,
2174"Precedence mark on this line is not the first \
2175to follow the previous rule.");
2176 psp->errorcnt++;
2177 }else{
2178 psp->prevrule->precsym = Symbol_new(x);
2179 }
2180 psp->state = PRECEDENCE_MARK_2;
2181 break;
2182 case PRECEDENCE_MARK_2:
2183 if( x[0]!=']' ){
2184 ErrorMsg(psp->filename,psp->tokenlineno,
2185 "Missing \"]\" on precedence mark.");
2186 psp->errorcnt++;
2187 }
2188 psp->state = WAITING_FOR_DECL_OR_RULE;
2189 break;
2190 case WAITING_FOR_ARROW:
2191 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2192 psp->state = IN_RHS;
2193 }else if( x[0]=='(' ){
2194 psp->state = LHS_ALIAS_1;
2195 }else{
2196 ErrorMsg(psp->filename,psp->tokenlineno,
2197 "Expected to see a \":\" following the LHS symbol \"%s\".",
2198 psp->lhs->name);
2199 psp->errorcnt++;
2200 psp->state = RESYNC_AFTER_RULE_ERROR;
2201 }
2202 break;
2203 case LHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002204 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002205 psp->lhsalias = x;
2206 psp->state = LHS_ALIAS_2;
2207 }else{
2208 ErrorMsg(psp->filename,psp->tokenlineno,
2209 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2210 x,psp->lhs->name);
2211 psp->errorcnt++;
2212 psp->state = RESYNC_AFTER_RULE_ERROR;
2213 }
2214 break;
2215 case LHS_ALIAS_2:
2216 if( x[0]==')' ){
2217 psp->state = LHS_ALIAS_3;
2218 }else{
2219 ErrorMsg(psp->filename,psp->tokenlineno,
2220 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2221 psp->errorcnt++;
2222 psp->state = RESYNC_AFTER_RULE_ERROR;
2223 }
2224 break;
2225 case LHS_ALIAS_3:
2226 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2227 psp->state = IN_RHS;
2228 }else{
2229 ErrorMsg(psp->filename,psp->tokenlineno,
2230 "Missing \"->\" following: \"%s(%s)\".",
2231 psp->lhs->name,psp->lhsalias);
2232 psp->errorcnt++;
2233 psp->state = RESYNC_AFTER_RULE_ERROR;
2234 }
2235 break;
2236 case IN_RHS:
2237 if( x[0]=='.' ){
2238 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002239 rp = (struct rule *)calloc( sizeof(struct rule) +
2240 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002241 if( rp==0 ){
2242 ErrorMsg(psp->filename,psp->tokenlineno,
2243 "Can't allocate enough memory for this rule.");
2244 psp->errorcnt++;
2245 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002246 }else{
drh75897232000-05-29 14:26:00 +00002247 int i;
2248 rp->ruleline = psp->tokenlineno;
2249 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002250 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002251 for(i=0; i<psp->nrhs; i++){
2252 rp->rhs[i] = psp->rhs[i];
2253 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002254 }
drh75897232000-05-29 14:26:00 +00002255 rp->lhs = psp->lhs;
2256 rp->lhsalias = psp->lhsalias;
2257 rp->nrhs = psp->nrhs;
2258 rp->code = 0;
2259 rp->precsym = 0;
2260 rp->index = psp->gp->nrule++;
2261 rp->nextlhs = rp->lhs->rule;
2262 rp->lhs->rule = rp;
2263 rp->next = 0;
2264 if( psp->firstrule==0 ){
2265 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002266 }else{
drh75897232000-05-29 14:26:00 +00002267 psp->lastrule->next = rp;
2268 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002269 }
drh75897232000-05-29 14:26:00 +00002270 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002271 }
drh75897232000-05-29 14:26:00 +00002272 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002273 }else if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002274 if( psp->nrhs>=MAXRHS ){
2275 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002276 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002277 x);
2278 psp->errorcnt++;
2279 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002280 }else{
drh75897232000-05-29 14:26:00 +00002281 psp->rhs[psp->nrhs] = Symbol_new(x);
2282 psp->alias[psp->nrhs] = 0;
2283 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002284 }
drhfd405312005-11-06 04:06:59 +00002285 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2286 struct symbol *msp = psp->rhs[psp->nrhs-1];
2287 if( msp->type!=MULTITERMINAL ){
2288 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002289 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002290 memset(msp, 0, sizeof(*msp));
2291 msp->type = MULTITERMINAL;
2292 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002293 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002294 msp->subsym[0] = origsp;
2295 msp->name = origsp->name;
2296 psp->rhs[psp->nrhs-1] = msp;
2297 }
2298 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002299 msp->subsym = (struct symbol **) realloc(msp->subsym,
2300 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002301 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
drhc56fac72015-10-29 13:48:15 +00002302 if( ISLOWER(x[1]) || ISLOWER(msp->subsym[0]->name[0]) ){
drhfd405312005-11-06 04:06:59 +00002303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "Cannot form a compound containing a non-terminal");
2305 psp->errorcnt++;
2306 }
drh75897232000-05-29 14:26:00 +00002307 }else if( x[0]=='(' && psp->nrhs>0 ){
2308 psp->state = RHS_ALIAS_1;
2309 }else{
2310 ErrorMsg(psp->filename,psp->tokenlineno,
2311 "Illegal character on RHS of rule: \"%s\".",x);
2312 psp->errorcnt++;
2313 psp->state = RESYNC_AFTER_RULE_ERROR;
2314 }
2315 break;
2316 case RHS_ALIAS_1:
drhc56fac72015-10-29 13:48:15 +00002317 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002318 psp->alias[psp->nrhs-1] = x;
2319 psp->state = RHS_ALIAS_2;
2320 }else{
2321 ErrorMsg(psp->filename,psp->tokenlineno,
2322 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2323 x,psp->rhs[psp->nrhs-1]->name);
2324 psp->errorcnt++;
2325 psp->state = RESYNC_AFTER_RULE_ERROR;
2326 }
2327 break;
2328 case RHS_ALIAS_2:
2329 if( x[0]==')' ){
2330 psp->state = IN_RHS;
2331 }else{
2332 ErrorMsg(psp->filename,psp->tokenlineno,
2333 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2334 psp->errorcnt++;
2335 psp->state = RESYNC_AFTER_RULE_ERROR;
2336 }
2337 break;
2338 case WAITING_FOR_DECL_KEYWORD:
drhc56fac72015-10-29 13:48:15 +00002339 if( ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002340 psp->declkeyword = x;
2341 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002342 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002343 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002344 psp->state = WAITING_FOR_DECL_ARG;
2345 if( strcmp(x,"name")==0 ){
2346 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002347 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002348 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002349 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002350 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002351 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002352 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002353 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002354 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002355 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002356 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002357 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002358 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002359 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002360 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002361 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002362 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002363 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002364 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002365 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002366 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002367 }else if( strcmp(x,"extra_argument")==0 ){
2368 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002369 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002370 }else if( strcmp(x,"token_type")==0 ){
2371 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002372 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002373 }else if( strcmp(x,"default_type")==0 ){
2374 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002375 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002376 }else if( strcmp(x,"stack_size")==0 ){
2377 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002378 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002379 }else if( strcmp(x,"start_symbol")==0 ){
2380 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002381 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002382 }else if( strcmp(x,"left")==0 ){
2383 psp->preccounter++;
2384 psp->declassoc = LEFT;
2385 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2386 }else if( strcmp(x,"right")==0 ){
2387 psp->preccounter++;
2388 psp->declassoc = RIGHT;
2389 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2390 }else if( strcmp(x,"nonassoc")==0 ){
2391 psp->preccounter++;
2392 psp->declassoc = NONE;
2393 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002394 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002395 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002396 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002397 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002398 }else if( strcmp(x,"fallback")==0 ){
2399 psp->fallback = 0;
2400 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002401 }else if( strcmp(x,"wildcard")==0 ){
2402 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002403 }else if( strcmp(x,"token_class")==0 ){
2404 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002405 }else{
2406 ErrorMsg(psp->filename,psp->tokenlineno,
2407 "Unknown declaration keyword: \"%%%s\".",x);
2408 psp->errorcnt++;
2409 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002410 }
drh75897232000-05-29 14:26:00 +00002411 }else{
2412 ErrorMsg(psp->filename,psp->tokenlineno,
2413 "Illegal declaration keyword: \"%s\".",x);
2414 psp->errorcnt++;
2415 psp->state = RESYNC_AFTER_DECL_ERROR;
2416 }
2417 break;
2418 case WAITING_FOR_DESTRUCTOR_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002419 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002420 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002421 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002422 psp->errorcnt++;
2423 psp->state = RESYNC_AFTER_DECL_ERROR;
2424 }else{
icculusd286fa62010-03-03 17:06:32 +00002425 struct symbol *sp = Symbol_new(x);
2426 psp->declargslot = &sp->destructor;
2427 psp->decllinenoslot = &sp->destLineno;
2428 psp->insertLineMacro = 1;
2429 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002430 }
2431 break;
2432 case WAITING_FOR_DATATYPE_SYMBOL:
drhc56fac72015-10-29 13:48:15 +00002433 if( !ISALPHA(x[0]) ){
drh75897232000-05-29 14:26:00 +00002434 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002435 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002436 psp->errorcnt++;
2437 psp->state = RESYNC_AFTER_DECL_ERROR;
2438 }else{
icculus866bf1e2010-02-17 20:31:32 +00002439 struct symbol *sp = Symbol_find(x);
2440 if((sp) && (sp->datatype)){
2441 ErrorMsg(psp->filename,psp->tokenlineno,
2442 "Symbol %%type \"%s\" already defined", x);
2443 psp->errorcnt++;
2444 psp->state = RESYNC_AFTER_DECL_ERROR;
2445 }else{
2446 if (!sp){
2447 sp = Symbol_new(x);
2448 }
2449 psp->declargslot = &sp->datatype;
2450 psp->insertLineMacro = 0;
2451 psp->state = WAITING_FOR_DECL_ARG;
2452 }
drh75897232000-05-29 14:26:00 +00002453 }
2454 break;
2455 case WAITING_FOR_PRECEDENCE_SYMBOL:
2456 if( x[0]=='.' ){
2457 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002458 }else if( ISUPPER(x[0]) ){
drh75897232000-05-29 14:26:00 +00002459 struct symbol *sp;
2460 sp = Symbol_new(x);
2461 if( sp->prec>=0 ){
2462 ErrorMsg(psp->filename,psp->tokenlineno,
2463 "Symbol \"%s\" has already be given a precedence.",x);
2464 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002465 }else{
drh75897232000-05-29 14:26:00 +00002466 sp->prec = psp->preccounter;
2467 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002468 }
drh75897232000-05-29 14:26:00 +00002469 }else{
2470 ErrorMsg(psp->filename,psp->tokenlineno,
2471 "Can't assign a precedence to \"%s\".",x);
2472 psp->errorcnt++;
2473 }
2474 break;
2475 case WAITING_FOR_DECL_ARG:
drhc56fac72015-10-29 13:48:15 +00002476 if( x[0]=='{' || x[0]=='\"' || ISALNUM(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002477 const char *zOld, *zNew;
2478 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002479 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002480 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002481 char zLine[50];
2482 zNew = x;
2483 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002484 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002485 if( *psp->declargslot ){
2486 zOld = *psp->declargslot;
2487 }else{
2488 zOld = "";
2489 }
drh87cf1372008-08-13 20:09:06 +00002490 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002491 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002492 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002493 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2494 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002495 for(z=psp->filename, nBack=0; *z; z++){
2496 if( *z=='\\' ) nBack++;
2497 }
drh898799f2014-01-10 23:21:00 +00002498 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002499 nLine = lemonStrlen(zLine);
2500 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002501 }
icculus9e44cf12010-02-14 17:14:22 +00002502 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2503 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002504 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002505 if( nOld && zBuf[-1]!='\n' ){
2506 *(zBuf++) = '\n';
2507 }
2508 memcpy(zBuf, zLine, nLine);
2509 zBuf += nLine;
2510 *(zBuf++) = '"';
2511 for(z=psp->filename; *z; z++){
2512 if( *z=='\\' ){
2513 *(zBuf++) = '\\';
2514 }
2515 *(zBuf++) = *z;
2516 }
2517 *(zBuf++) = '"';
2518 *(zBuf++) = '\n';
2519 }
drh4dc8ef52008-07-01 17:13:57 +00002520 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2521 psp->decllinenoslot[0] = psp->tokenlineno;
2522 }
drha5808f32008-04-27 22:19:44 +00002523 memcpy(zBuf, zNew, nNew);
2524 zBuf += nNew;
2525 *zBuf = 0;
2526 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002527 }else{
2528 ErrorMsg(psp->filename,psp->tokenlineno,
2529 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2530 psp->errorcnt++;
2531 psp->state = RESYNC_AFTER_DECL_ERROR;
2532 }
2533 break;
drh0bd1f4e2002-06-06 18:54:39 +00002534 case WAITING_FOR_FALLBACK_ID:
2535 if( x[0]=='.' ){
2536 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002537 }else if( !ISUPPER(x[0]) ){
drh0bd1f4e2002-06-06 18:54:39 +00002538 ErrorMsg(psp->filename, psp->tokenlineno,
2539 "%%fallback argument \"%s\" should be a token", x);
2540 psp->errorcnt++;
2541 }else{
2542 struct symbol *sp = Symbol_new(x);
2543 if( psp->fallback==0 ){
2544 psp->fallback = sp;
2545 }else if( sp->fallback ){
2546 ErrorMsg(psp->filename, psp->tokenlineno,
2547 "More than one fallback assigned to token %s", x);
2548 psp->errorcnt++;
2549 }else{
2550 sp->fallback = psp->fallback;
2551 psp->gp->has_fallback = 1;
2552 }
2553 }
2554 break;
drhe09daa92006-06-10 13:29:31 +00002555 case WAITING_FOR_WILDCARD_ID:
2556 if( x[0]=='.' ){
2557 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002558 }else if( !ISUPPER(x[0]) ){
drhe09daa92006-06-10 13:29:31 +00002559 ErrorMsg(psp->filename, psp->tokenlineno,
2560 "%%wildcard argument \"%s\" should be a token", x);
2561 psp->errorcnt++;
2562 }else{
2563 struct symbol *sp = Symbol_new(x);
2564 if( psp->gp->wildcard==0 ){
2565 psp->gp->wildcard = sp;
2566 }else{
2567 ErrorMsg(psp->filename, psp->tokenlineno,
2568 "Extra wildcard to token: %s", x);
2569 psp->errorcnt++;
2570 }
2571 }
2572 break;
drh61f92cd2014-01-11 03:06:18 +00002573 case WAITING_FOR_CLASS_ID:
drhc56fac72015-10-29 13:48:15 +00002574 if( !ISLOWER(x[0]) ){
drh61f92cd2014-01-11 03:06:18 +00002575 ErrorMsg(psp->filename, psp->tokenlineno,
2576 "%%token_class must be followed by an identifier: ", x);
2577 psp->errorcnt++;
2578 psp->state = RESYNC_AFTER_DECL_ERROR;
2579 }else if( Symbol_find(x) ){
2580 ErrorMsg(psp->filename, psp->tokenlineno,
2581 "Symbol \"%s\" already used", x);
2582 psp->errorcnt++;
2583 psp->state = RESYNC_AFTER_DECL_ERROR;
2584 }else{
2585 psp->tkclass = Symbol_new(x);
2586 psp->tkclass->type = MULTITERMINAL;
2587 psp->state = WAITING_FOR_CLASS_TOKEN;
2588 }
2589 break;
2590 case WAITING_FOR_CLASS_TOKEN:
2591 if( x[0]=='.' ){
2592 psp->state = WAITING_FOR_DECL_OR_RULE;
drhc56fac72015-10-29 13:48:15 +00002593 }else if( ISUPPER(x[0]) || ((x[0]=='|' || x[0]=='/') && ISUPPER(x[1])) ){
drh61f92cd2014-01-11 03:06:18 +00002594 struct symbol *msp = psp->tkclass;
2595 msp->nsubsym++;
2596 msp->subsym = (struct symbol **) realloc(msp->subsym,
2597 sizeof(struct symbol*)*msp->nsubsym);
drhc56fac72015-10-29 13:48:15 +00002598 if( !ISUPPER(x[0]) ) x++;
drh61f92cd2014-01-11 03:06:18 +00002599 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2600 }else{
2601 ErrorMsg(psp->filename, psp->tokenlineno,
2602 "%%token_class argument \"%s\" should be a token", x);
2603 psp->errorcnt++;
2604 psp->state = RESYNC_AFTER_DECL_ERROR;
2605 }
2606 break;
drh75897232000-05-29 14:26:00 +00002607 case RESYNC_AFTER_RULE_ERROR:
2608/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2609** break; */
2610 case RESYNC_AFTER_DECL_ERROR:
2611 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2612 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2613 break;
2614 }
2615}
2616
drh34ff57b2008-07-14 12:27:51 +00002617/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002618** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2619** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2620** comments them out. Text in between is also commented out as appropriate.
2621*/
danielk1977940fac92005-01-23 22:41:37 +00002622static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002623 int i, j, k, n;
2624 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002625 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002626 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002627 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002628 for(i=0; z[i]; i++){
2629 if( z[i]=='\n' ) lineno++;
2630 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
drhc56fac72015-10-29 13:48:15 +00002631 if( strncmp(&z[i],"%endif",6)==0 && ISSPACE(z[i+6]) ){
drh6d08b4d2004-07-20 12:45:22 +00002632 if( exclude ){
2633 exclude--;
2634 if( exclude==0 ){
2635 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2636 }
2637 }
2638 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
drhc56fac72015-10-29 13:48:15 +00002639 }else if( (strncmp(&z[i],"%ifdef",6)==0 && ISSPACE(z[i+6]))
2640 || (strncmp(&z[i],"%ifndef",7)==0 && ISSPACE(z[i+7])) ){
drh6d08b4d2004-07-20 12:45:22 +00002641 if( exclude ){
2642 exclude++;
2643 }else{
drhc56fac72015-10-29 13:48:15 +00002644 for(j=i+7; ISSPACE(z[j]); j++){}
2645 for(n=0; z[j+n] && !ISSPACE(z[j+n]); n++){}
drh6d08b4d2004-07-20 12:45:22 +00002646 exclude = 1;
2647 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002648 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002649 exclude = 0;
2650 break;
2651 }
2652 }
2653 if( z[i+3]=='n' ) exclude = !exclude;
2654 if( exclude ){
2655 start = i;
2656 start_lineno = lineno;
2657 }
2658 }
2659 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2660 }
2661 }
2662 if( exclude ){
2663 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2664 exit(1);
2665 }
2666}
2667
drh75897232000-05-29 14:26:00 +00002668/* In spite of its name, this function is really a scanner. It read
2669** in the entire input file (all at once) then tokenizes it. Each
2670** token is passed to the function "parseonetoken" which builds all
2671** the appropriate data structures in the global state vector "gp".
2672*/
icculus9e44cf12010-02-14 17:14:22 +00002673void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002674{
2675 struct pstate ps;
2676 FILE *fp;
2677 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002678 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002679 int lineno;
2680 int c;
2681 char *cp, *nextcp;
2682 int startline = 0;
2683
rse38514a92007-09-20 11:34:17 +00002684 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002685 ps.gp = gp;
2686 ps.filename = gp->filename;
2687 ps.errorcnt = 0;
2688 ps.state = INITIALIZE;
2689
2690 /* Begin by reading the input file */
2691 fp = fopen(ps.filename,"rb");
2692 if( fp==0 ){
2693 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2694 gp->errorcnt++;
2695 return;
2696 }
2697 fseek(fp,0,2);
2698 filesize = ftell(fp);
2699 rewind(fp);
2700 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002701 if( filesize>100000000 || filebuf==0 ){
2702 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002703 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002704 fclose(fp);
drh75897232000-05-29 14:26:00 +00002705 return;
2706 }
2707 if( fread(filebuf,1,filesize,fp)!=filesize ){
2708 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2709 filesize);
2710 free(filebuf);
2711 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002712 fclose(fp);
drh75897232000-05-29 14:26:00 +00002713 return;
2714 }
2715 fclose(fp);
2716 filebuf[filesize] = 0;
2717
drh6d08b4d2004-07-20 12:45:22 +00002718 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2719 preprocess_input(filebuf);
2720
drh75897232000-05-29 14:26:00 +00002721 /* Now scan the text of the input file */
2722 lineno = 1;
2723 for(cp=filebuf; (c= *cp)!=0; ){
2724 if( c=='\n' ) lineno++; /* Keep track of the line number */
drhc56fac72015-10-29 13:48:15 +00002725 if( ISSPACE(c) ){ cp++; continue; } /* Skip all white space */
drh75897232000-05-29 14:26:00 +00002726 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2727 cp+=2;
2728 while( (c= *cp)!=0 && c!='\n' ) cp++;
2729 continue;
2730 }
2731 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2732 cp+=2;
2733 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2734 if( c=='\n' ) lineno++;
2735 cp++;
2736 }
2737 if( c ) cp++;
2738 continue;
2739 }
2740 ps.tokenstart = cp; /* Mark the beginning of the token */
2741 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2742 if( c=='\"' ){ /* String literals */
2743 cp++;
2744 while( (c= *cp)!=0 && c!='\"' ){
2745 if( c=='\n' ) lineno++;
2746 cp++;
2747 }
2748 if( c==0 ){
2749 ErrorMsg(ps.filename,startline,
2750"String starting on this line is not terminated before the end of the file.");
2751 ps.errorcnt++;
2752 nextcp = cp;
2753 }else{
2754 nextcp = cp+1;
2755 }
2756 }else if( c=='{' ){ /* A block of C code */
2757 int level;
2758 cp++;
2759 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2760 if( c=='\n' ) lineno++;
2761 else if( c=='{' ) level++;
2762 else if( c=='}' ) level--;
2763 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2764 int prevc;
2765 cp = &cp[2];
2766 prevc = 0;
2767 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2768 if( c=='\n' ) lineno++;
2769 prevc = c;
2770 cp++;
drhf2f105d2012-08-20 15:53:54 +00002771 }
2772 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002773 cp = &cp[2];
2774 while( (c= *cp)!=0 && c!='\n' ) cp++;
2775 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002776 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002777 int startchar, prevc;
2778 startchar = c;
2779 prevc = 0;
2780 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2781 if( c=='\n' ) lineno++;
2782 if( prevc=='\\' ) prevc = 0;
2783 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002784 }
2785 }
drh75897232000-05-29 14:26:00 +00002786 }
2787 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002788 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002789"C code starting on this line is not terminated before the end of the file.");
2790 ps.errorcnt++;
2791 nextcp = cp;
2792 }else{
2793 nextcp = cp+1;
2794 }
drhc56fac72015-10-29 13:48:15 +00002795 }else if( ISALNUM(c) ){ /* Identifiers */
2796 while( (c= *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drh75897232000-05-29 14:26:00 +00002797 nextcp = cp;
2798 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2799 cp += 3;
2800 nextcp = cp;
drhc56fac72015-10-29 13:48:15 +00002801 }else if( (c=='/' || c=='|') && ISALPHA(cp[1]) ){
drhfd405312005-11-06 04:06:59 +00002802 cp += 2;
drhc56fac72015-10-29 13:48:15 +00002803 while( (c = *cp)!=0 && (ISALNUM(c) || c=='_') ) cp++;
drhfd405312005-11-06 04:06:59 +00002804 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002805 }else{ /* All other (one character) operators */
2806 cp++;
2807 nextcp = cp;
2808 }
2809 c = *cp;
2810 *cp = 0; /* Null terminate the token */
2811 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002812 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002813 cp = nextcp;
2814 }
2815 free(filebuf); /* Release the buffer after parsing */
2816 gp->rule = ps.firstrule;
2817 gp->errorcnt = ps.errorcnt;
2818}
2819/*************************** From the file "plink.c" *********************/
2820/*
2821** Routines processing configuration follow-set propagation links
2822** in the LEMON parser generator.
2823*/
2824static struct plink *plink_freelist = 0;
2825
2826/* Allocate a new plink */
2827struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002828 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002829
2830 if( plink_freelist==0 ){
2831 int i;
2832 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002833 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002834 if( plink_freelist==0 ){
2835 fprintf(stderr,
2836 "Unable to allocate memory for a new follow-set propagation link.\n");
2837 exit(1);
2838 }
2839 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2840 plink_freelist[amt-1].next = 0;
2841 }
icculus9e44cf12010-02-14 17:14:22 +00002842 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002843 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002844 return newlink;
drh75897232000-05-29 14:26:00 +00002845}
2846
2847/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002848void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002849{
icculus9e44cf12010-02-14 17:14:22 +00002850 struct plink *newlink;
2851 newlink = Plink_new();
2852 newlink->next = *plpp;
2853 *plpp = newlink;
2854 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002855}
2856
2857/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002858void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002859{
2860 struct plink *nextpl;
2861 while( from ){
2862 nextpl = from->next;
2863 from->next = *to;
2864 *to = from;
2865 from = nextpl;
2866 }
2867}
2868
2869/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002870void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002871{
2872 struct plink *nextpl;
2873
2874 while( plp ){
2875 nextpl = plp->next;
2876 plp->next = plink_freelist;
2877 plink_freelist = plp;
2878 plp = nextpl;
2879 }
2880}
2881/*********************** From the file "report.c" **************************/
2882/*
2883** Procedures for generating reports and tables in the LEMON parser generator.
2884*/
2885
2886/* Generate a filename with the given suffix. Space to hold the
2887** name comes from malloc() and must be freed by the calling
2888** function.
2889*/
icculus9e44cf12010-02-14 17:14:22 +00002890PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002891{
2892 char *name;
2893 char *cp;
2894
icculus9e44cf12010-02-14 17:14:22 +00002895 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002896 if( name==0 ){
2897 fprintf(stderr,"Can't allocate space for a filename.\n");
2898 exit(1);
2899 }
drh898799f2014-01-10 23:21:00 +00002900 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002901 cp = strrchr(name,'.');
2902 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002903 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002904 return name;
2905}
2906
2907/* Open a file with a name based on the name of the input file,
2908** but with a different (specified) suffix, and return a pointer
2909** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002910PRIVATE FILE *file_open(
2911 struct lemon *lemp,
2912 const char *suffix,
2913 const char *mode
2914){
drh75897232000-05-29 14:26:00 +00002915 FILE *fp;
2916
2917 if( lemp->outname ) free(lemp->outname);
2918 lemp->outname = file_makename(lemp, suffix);
2919 fp = fopen(lemp->outname,mode);
2920 if( fp==0 && *mode=='w' ){
2921 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2922 lemp->errorcnt++;
2923 return 0;
2924 }
2925 return fp;
2926}
2927
2928/* Duplicate the input file without comments and without actions
2929** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002930void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002931{
2932 struct rule *rp;
2933 struct symbol *sp;
2934 int i, j, maxlen, len, ncolumns, skip;
2935 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2936 maxlen = 10;
2937 for(i=0; i<lemp->nsymbol; i++){
2938 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002939 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002940 if( len>maxlen ) maxlen = len;
2941 }
2942 ncolumns = 76/(maxlen+5);
2943 if( ncolumns<1 ) ncolumns = 1;
2944 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2945 for(i=0; i<skip; i++){
2946 printf("//");
2947 for(j=i; j<lemp->nsymbol; j+=skip){
2948 sp = lemp->symbols[j];
2949 assert( sp->index==j );
2950 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2951 }
2952 printf("\n");
2953 }
2954 for(rp=lemp->rule; rp; rp=rp->next){
2955 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002956 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002957 printf(" ::=");
2958 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002959 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002960 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002961 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002962 for(j=1; j<sp->nsubsym; j++){
2963 printf("|%s", sp->subsym[j]->name);
2964 }
drh61f92cd2014-01-11 03:06:18 +00002965 }else{
2966 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002967 }
2968 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002969 }
2970 printf(".");
2971 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002972 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002973 printf("\n");
2974 }
2975}
2976
drh7e698e92015-09-07 14:22:24 +00002977/* Print a single rule.
2978*/
2979void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00002980 struct symbol *sp;
2981 int i, j;
drh75897232000-05-29 14:26:00 +00002982 fprintf(fp,"%s ::=",rp->lhs->name);
2983 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00002984 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00002985 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002986 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002987 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002988 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002989 for(j=1; j<sp->nsubsym; j++){
2990 fprintf(fp,"|%s",sp->subsym[j]->name);
2991 }
drh61f92cd2014-01-11 03:06:18 +00002992 }else{
2993 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002994 }
drh75897232000-05-29 14:26:00 +00002995 }
2996}
2997
drh7e698e92015-09-07 14:22:24 +00002998/* Print the rule for a configuration.
2999*/
3000void ConfigPrint(FILE *fp, struct config *cfp){
3001 RulePrint(fp, cfp->rp, cfp->dot);
3002}
3003
drh75897232000-05-29 14:26:00 +00003004/* #define TEST */
drhfd405312005-11-06 04:06:59 +00003005#if 0
drh75897232000-05-29 14:26:00 +00003006/* Print a set */
3007PRIVATE void SetPrint(out,set,lemp)
3008FILE *out;
3009char *set;
3010struct lemon *lemp;
3011{
3012 int i;
3013 char *spacer;
3014 spacer = "";
3015 fprintf(out,"%12s[","");
3016 for(i=0; i<lemp->nterminal; i++){
3017 if( SetFind(set,i) ){
3018 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3019 spacer = " ";
3020 }
3021 }
3022 fprintf(out,"]\n");
3023}
3024
3025/* Print a plink chain */
3026PRIVATE void PlinkPrint(out,plp,tag)
3027FILE *out;
3028struct plink *plp;
3029char *tag;
3030{
3031 while( plp ){
drhada354d2005-11-05 15:03:59 +00003032 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003033 ConfigPrint(out,plp->cfp);
3034 fprintf(out,"\n");
3035 plp = plp->next;
3036 }
3037}
3038#endif
3039
3040/* Print an action to the given file descriptor. Return FALSE if
3041** nothing was actually printed.
3042*/
drh7e698e92015-09-07 14:22:24 +00003043int PrintAction(
3044 struct action *ap, /* The action to print */
3045 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003046 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003047){
drh75897232000-05-29 14:26:00 +00003048 int result = 1;
3049 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003050 case SHIFT: {
3051 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003052 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003053 break;
drh7e698e92015-09-07 14:22:24 +00003054 }
3055 case REDUCE: {
3056 struct rule *rp = ap->x.rp;
drh3bd48ab2015-09-07 18:23:37 +00003057 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->index);
3058 RulePrint(fp, rp, -1);
3059 break;
3060 }
3061 case SHIFTREDUCE: {
3062 struct rule *rp = ap->x.rp;
3063 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->index);
3064 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003065 break;
drh7e698e92015-09-07 14:22:24 +00003066 }
drh75897232000-05-29 14:26:00 +00003067 case ACCEPT:
3068 fprintf(fp,"%*s accept",indent,ap->sp->name);
3069 break;
3070 case ERROR:
3071 fprintf(fp,"%*s error",indent,ap->sp->name);
3072 break;
drh9892c5d2007-12-21 00:02:11 +00003073 case SRCONFLICT:
3074 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003075 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh75897232000-05-29 14:26:00 +00003076 indent,ap->sp->name,ap->x.rp->index);
3077 break;
drh9892c5d2007-12-21 00:02:11 +00003078 case SSCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003079 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003080 indent,ap->sp->name,ap->x.stp->statenum);
3081 break;
drh75897232000-05-29 14:26:00 +00003082 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003083 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003084 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003085 indent,ap->sp->name,ap->x.stp->statenum);
3086 }else{
3087 result = 0;
3088 }
3089 break;
drh75897232000-05-29 14:26:00 +00003090 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003091 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003092 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003093 indent,ap->sp->name,ap->x.rp->index);
3094 }else{
3095 result = 0;
3096 }
3097 break;
drh75897232000-05-29 14:26:00 +00003098 case NOT_USED:
3099 result = 0;
3100 break;
3101 }
3102 return result;
3103}
3104
drh3bd48ab2015-09-07 18:23:37 +00003105/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003106void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003107{
3108 int i;
3109 struct state *stp;
3110 struct config *cfp;
3111 struct action *ap;
3112 FILE *fp;
3113
drh2aa6ca42004-09-10 00:14:04 +00003114 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003115 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003116 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003117 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003118 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003119 if( lemp->basisflag ) cfp=stp->bp;
3120 else cfp=stp->cfp;
3121 while( cfp ){
3122 char buf[20];
3123 if( cfp->dot==cfp->rp->nrhs ){
drh898799f2014-01-10 23:21:00 +00003124 lemon_sprintf(buf,"(%d)",cfp->rp->index);
drh75897232000-05-29 14:26:00 +00003125 fprintf(fp," %5s ",buf);
3126 }else{
3127 fprintf(fp," ");
3128 }
3129 ConfigPrint(fp,cfp);
3130 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003131#if 0
drh75897232000-05-29 14:26:00 +00003132 SetPrint(fp,cfp->fws,lemp);
3133 PlinkPrint(fp,cfp->fplp,"To ");
3134 PlinkPrint(fp,cfp->bplp,"From");
3135#endif
3136 if( lemp->basisflag ) cfp=cfp->bp;
3137 else cfp=cfp->next;
3138 }
3139 fprintf(fp,"\n");
3140 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003141 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003142 }
3143 fprintf(fp,"\n");
3144 }
drhe9278182007-07-18 18:16:29 +00003145 fprintf(fp, "----------------------------------------------------\n");
3146 fprintf(fp, "Symbols:\n");
3147 for(i=0; i<lemp->nsymbol; i++){
3148 int j;
3149 struct symbol *sp;
3150
3151 sp = lemp->symbols[i];
3152 fprintf(fp, " %3d: %s", i, sp->name);
3153 if( sp->type==NONTERMINAL ){
3154 fprintf(fp, ":");
3155 if( sp->lambda ){
3156 fprintf(fp, " <lambda>");
3157 }
3158 for(j=0; j<lemp->nterminal; j++){
3159 if( sp->firstset && SetFind(sp->firstset, j) ){
3160 fprintf(fp, " %s", lemp->symbols[j]->name);
3161 }
3162 }
3163 }
3164 fprintf(fp, "\n");
3165 }
drh75897232000-05-29 14:26:00 +00003166 fclose(fp);
3167 return;
3168}
3169
3170/* Search for the file "name" which is in the same directory as
3171** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003172PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003173{
icculus9e44cf12010-02-14 17:14:22 +00003174 const char *pathlist;
3175 char *pathbufptr;
3176 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003177 char *path,*cp;
3178 char c;
drh75897232000-05-29 14:26:00 +00003179
3180#ifdef __WIN32__
3181 cp = strrchr(argv0,'\\');
3182#else
3183 cp = strrchr(argv0,'/');
3184#endif
3185 if( cp ){
3186 c = *cp;
3187 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003188 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003189 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003190 *cp = c;
3191 }else{
drh75897232000-05-29 14:26:00 +00003192 pathlist = getenv("PATH");
3193 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003194 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003195 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003196 if( (pathbuf != 0) && (path!=0) ){
3197 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003198 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003199 while( *pathbuf ){
3200 cp = strchr(pathbuf,':');
3201 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003202 c = *cp;
3203 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003204 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003205 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003206 if( c==0 ) pathbuf[0] = 0;
3207 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003208 if( access(path,modemask)==0 ) break;
3209 }
icculus9e44cf12010-02-14 17:14:22 +00003210 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003211 }
3212 }
3213 return path;
3214}
3215
3216/* Given an action, compute the integer value for that action
3217** which is to be put in the action table of the generated machine.
3218** Return negative if no action should be generated.
3219*/
icculus9e44cf12010-02-14 17:14:22 +00003220PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003221{
3222 int act;
3223 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003224 case SHIFT: act = ap->x.stp->statenum; break;
3225 case SHIFTREDUCE: act = ap->x.rp->index + lemp->nstate; break;
3226 case REDUCE: act = ap->x.rp->index + lemp->nstate+lemp->nrule; break;
3227 case ERROR: act = lemp->nstate + lemp->nrule*2; break;
3228 case ACCEPT: act = lemp->nstate + lemp->nrule*2 + 1; break;
drh75897232000-05-29 14:26:00 +00003229 default: act = -1; break;
3230 }
3231 return act;
3232}
3233
3234#define LINESIZE 1000
3235/* The next cluster of routines are for reading the template file
3236** and writing the results to the generated parser */
3237/* The first function transfers data from "in" to "out" until
3238** a line is seen which begins with "%%". The line number is
3239** tracked.
3240**
3241** if name!=0, then any word that begin with "Parse" is changed to
3242** begin with *name instead.
3243*/
icculus9e44cf12010-02-14 17:14:22 +00003244PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003245{
3246 int i, iStart;
3247 char line[LINESIZE];
3248 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3249 (*lineno)++;
3250 iStart = 0;
3251 if( name ){
3252 for(i=0; line[i]; i++){
3253 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
drhc56fac72015-10-29 13:48:15 +00003254 && (i==0 || !ISALPHA(line[i-1]))
drh75897232000-05-29 14:26:00 +00003255 ){
3256 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3257 fprintf(out,"%s",name);
3258 i += 4;
3259 iStart = i+1;
3260 }
3261 }
3262 }
3263 fprintf(out,"%s",&line[iStart]);
3264 }
3265}
3266
3267/* The next function finds the template file and opens it, returning
3268** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003269PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003270{
3271 static char templatename[] = "lempar.c";
3272 char buf[1000];
3273 FILE *in;
3274 char *tpltname;
3275 char *cp;
3276
icculus3e143bd2010-02-14 00:48:49 +00003277 /* first, see if user specified a template filename on the command line. */
3278 if (user_templatename != 0) {
3279 if( access(user_templatename,004)==-1 ){
3280 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3281 user_templatename);
3282 lemp->errorcnt++;
3283 return 0;
3284 }
3285 in = fopen(user_templatename,"rb");
3286 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003287 fprintf(stderr,"Can't open the template file \"%s\".\n",
3288 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003289 lemp->errorcnt++;
3290 return 0;
3291 }
3292 return in;
3293 }
3294
drh75897232000-05-29 14:26:00 +00003295 cp = strrchr(lemp->filename,'.');
3296 if( cp ){
drh898799f2014-01-10 23:21:00 +00003297 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003298 }else{
drh898799f2014-01-10 23:21:00 +00003299 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003300 }
3301 if( access(buf,004)==0 ){
3302 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003303 }else if( access(templatename,004)==0 ){
3304 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003305 }else{
3306 tpltname = pathsearch(lemp->argv0,templatename,0);
3307 }
3308 if( tpltname==0 ){
3309 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3310 templatename);
3311 lemp->errorcnt++;
3312 return 0;
3313 }
drh2aa6ca42004-09-10 00:14:04 +00003314 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003315 if( in==0 ){
3316 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3317 lemp->errorcnt++;
3318 return 0;
3319 }
3320 return in;
3321}
3322
drhaf805ca2004-09-07 11:28:25 +00003323/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003324PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003325{
3326 fprintf(out,"#line %d \"",lineno);
3327 while( *filename ){
3328 if( *filename == '\\' ) putc('\\',out);
3329 putc(*filename,out);
3330 filename++;
3331 }
3332 fprintf(out,"\"\n");
3333}
3334
drh75897232000-05-29 14:26:00 +00003335/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003336PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003337{
3338 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003339 while( *str ){
drh75897232000-05-29 14:26:00 +00003340 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003341 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003342 str++;
3343 }
drh9db55df2004-09-09 14:01:21 +00003344 if( str[-1]!='\n' ){
3345 putc('\n',out);
3346 (*lineno)++;
3347 }
shane58543932008-12-10 20:10:04 +00003348 if (!lemp->nolinenosflag) {
3349 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3350 }
drh75897232000-05-29 14:26:00 +00003351 return;
3352}
3353
3354/*
3355** The following routine emits code for the destructor for the
3356** symbol sp
3357*/
icculus9e44cf12010-02-14 17:14:22 +00003358void emit_destructor_code(
3359 FILE *out,
3360 struct symbol *sp,
3361 struct lemon *lemp,
3362 int *lineno
3363){
drhcc83b6e2004-04-23 23:38:42 +00003364 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003365
drh75897232000-05-29 14:26:00 +00003366 if( sp->type==TERMINAL ){
3367 cp = lemp->tokendest;
3368 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003369 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003370 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003371 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003372 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003373 if( !lemp->nolinenosflag ){
3374 (*lineno)++;
3375 tplt_linedir(out,sp->destLineno,lemp->filename);
3376 }
drh960e8c62001-04-03 16:53:21 +00003377 }else if( lemp->vardest ){
3378 cp = lemp->vardest;
3379 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003380 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003381 }else{
3382 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003383 }
3384 for(; *cp; cp++){
3385 if( *cp=='$' && cp[1]=='$' ){
3386 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3387 cp++;
3388 continue;
3389 }
shane58543932008-12-10 20:10:04 +00003390 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003391 fputc(*cp,out);
3392 }
shane58543932008-12-10 20:10:04 +00003393 fprintf(out,"\n"); (*lineno)++;
3394 if (!lemp->nolinenosflag) {
3395 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3396 }
3397 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003398 return;
3399}
3400
3401/*
drh960e8c62001-04-03 16:53:21 +00003402** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003403*/
icculus9e44cf12010-02-14 17:14:22 +00003404int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003405{
3406 int ret;
3407 if( sp->type==TERMINAL ){
3408 ret = lemp->tokendest!=0;
3409 }else{
drh960e8c62001-04-03 16:53:21 +00003410 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003411 }
3412 return ret;
3413}
3414
drh0bb132b2004-07-20 14:06:51 +00003415/*
3416** Append text to a dynamically allocated string. If zText is 0 then
3417** reset the string to be empty again. Always return the complete text
3418** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003419**
3420** n bytes of zText are stored. If n==0 then all of zText up to the first
3421** \000 terminator is stored. zText can contain up to two instances of
3422** %d. The values of p1 and p2 are written into the first and second
3423** %d.
3424**
3425** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003426*/
icculus9e44cf12010-02-14 17:14:22 +00003427PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3428 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003429 static char *z = 0;
3430 static int alloced = 0;
3431 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003432 int c;
drh0bb132b2004-07-20 14:06:51 +00003433 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003434 if( zText==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003435 if( used==0 && z!=0 ) z[0] = 0;
drh0bb132b2004-07-20 14:06:51 +00003436 used = 0;
3437 return z;
3438 }
drh7ac25c72004-08-19 15:12:26 +00003439 if( n<=0 ){
3440 if( n<0 ){
3441 used += n;
3442 assert( used>=0 );
3443 }
drh87cf1372008-08-13 20:09:06 +00003444 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003445 }
drhdf609712010-11-23 20:55:27 +00003446 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003447 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003448 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003449 }
icculus9e44cf12010-02-14 17:14:22 +00003450 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003451 while( n-- > 0 ){
3452 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003453 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003454 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003455 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003456 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003457 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003458 zText++;
3459 n--;
3460 }else{
mistachkin2318d332015-01-12 18:02:52 +00003461 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003462 }
3463 }
3464 z[used] = 0;
3465 return z;
3466}
3467
3468/*
3469** zCode is a string that is the action associated with a rule. Expand
3470** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003471** stack.
drhdabd04c2016-02-17 01:46:19 +00003472**
3473** Return 1 if the expanded code requires that "yylhsminor" local variable
3474** to be defined.
drh0bb132b2004-07-20 14:06:51 +00003475*/
drhdabd04c2016-02-17 01:46:19 +00003476PRIVATE int translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003477 char *cp, *xp;
3478 int i;
drhdabd04c2016-02-17 01:46:19 +00003479 int rc = 0; /* True if yylhsminor is used */
drh0bb132b2004-07-20 14:06:51 +00003480 char lhsused = 0; /* True if the LHS element has been used */
drh4dd0d3f2016-02-17 01:18:33 +00003481 char lhsdirect; /* True if LHS writes directly into stack */
drh0bb132b2004-07-20 14:06:51 +00003482 char used[MAXRHS]; /* True for each RHS element which is used */
drh4dd0d3f2016-02-17 01:18:33 +00003483 char zLhs[50]; /* Convert the LHS symbol into this string */
drh0bb132b2004-07-20 14:06:51 +00003484
3485 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3486 lhsused = 0;
3487
drh19c9e562007-03-29 20:13:53 +00003488 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003489 static char newlinestr[2] = { '\n', '\0' };
3490 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003491 rp->line = rp->ruleline;
3492 }
3493
drh4dd0d3f2016-02-17 01:18:33 +00003494
3495 if( rp->lhsalias==0 ){
3496 /* There is no LHS value symbol. */
3497 lhsdirect = 1;
3498 }else if( rp->nrhs==0 ){
3499 /* If there are no RHS symbols, then writing directly to the LHS is ok */
3500 lhsdirect = 1;
3501 }else if( rp->rhsalias[0]==0 ){
3502 /* The left-most RHS symbol has not value. LHS direct is ok. But
3503 ** we have to call the distructor on the RHS symbol first. */
3504 lhsdirect = 1;
3505 if( has_destructor(rp->rhs[0],lemp) ){
3506 append_str(0,0,0,0);
3507 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3508 rp->rhs[0]->index,1-rp->nrhs);
3509 rp->codePrefix = Strsafe(append_str(0,0,0,0));
3510 }
3511 }else if( strcmp(rp->lhsalias,rp->rhsalias[0])==0 ){
3512 /* The LHS symbol and the left-most RHS symbol are the same, so
3513 ** direct writing is allowed */
3514 lhsdirect = 1;
3515 lhsused = 1;
3516 used[0] = 1;
3517 if( rp->lhs->dtnum!=rp->rhs[0]->dtnum ){
3518 ErrorMsg(lemp->filename,rp->ruleline,
3519 "%s(%s) and %s(%s) share the same label but have "
3520 "different datatypes.",
3521 rp->lhs->name, rp->lhsalias, rp->rhs[0]->name, rp->rhsalias[0]);
3522 lemp->errorcnt++;
3523 }
3524 }else{
3525 lhsdirect = 0;
3526 }
3527 if( lhsdirect ){
3528 sprintf(zLhs, "yymsp[%d].minor.yy%d",1-rp->nrhs,rp->lhs->dtnum);
3529 }else{
drhdabd04c2016-02-17 01:46:19 +00003530 rc = 1;
drh4dd0d3f2016-02-17 01:18:33 +00003531 sprintf(zLhs, "yylhsminor.yy%d",rp->lhs->dtnum);
3532 }
3533
drh0bb132b2004-07-20 14:06:51 +00003534 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003535
3536 /* This const cast is wrong but harmless, if we're careful. */
3537 for(cp=(char *)rp->code; *cp; cp++){
drhc56fac72015-10-29 13:48:15 +00003538 if( ISALPHA(*cp) && (cp==rp->code || (!ISALNUM(cp[-1]) && cp[-1]!='_')) ){
drh0bb132b2004-07-20 14:06:51 +00003539 char saved;
drhc56fac72015-10-29 13:48:15 +00003540 for(xp= &cp[1]; ISALNUM(*xp) || *xp=='_'; xp++);
drh0bb132b2004-07-20 14:06:51 +00003541 saved = *xp;
3542 *xp = 0;
3543 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh4dd0d3f2016-02-17 01:18:33 +00003544 append_str(zLhs,0,0,0);
drh0bb132b2004-07-20 14:06:51 +00003545 cp = xp;
3546 lhsused = 1;
3547 }else{
3548 for(i=0; i<rp->nrhs; i++){
3549 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003550 if( cp!=rp->code && cp[-1]=='@' ){
3551 /* If the argument is of the form @X then substituted
3552 ** the token number of X, not the value of X */
3553 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3554 }else{
drhfd405312005-11-06 04:06:59 +00003555 struct symbol *sp = rp->rhs[i];
3556 int dtnum;
3557 if( sp->type==MULTITERMINAL ){
3558 dtnum = sp->subsym[0]->dtnum;
3559 }else{
3560 dtnum = sp->dtnum;
3561 }
3562 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003563 }
drh0bb132b2004-07-20 14:06:51 +00003564 cp = xp;
3565 used[i] = 1;
3566 break;
3567 }
3568 }
3569 }
3570 *xp = saved;
3571 }
3572 append_str(cp, 1, 0, 0);
3573 } /* End loop */
3574
drh4dd0d3f2016-02-17 01:18:33 +00003575 /* Main code generation completed */
3576 cp = append_str(0,0,0,0);
3577 if( cp && cp[0] ) rp->code = Strsafe(cp);
3578 append_str(0,0,0,0);
3579
drh0bb132b2004-07-20 14:06:51 +00003580 /* Check to make sure the LHS has been used */
3581 if( rp->lhsalias && !lhsused ){
3582 ErrorMsg(lemp->filename,rp->ruleline,
3583 "Label \"%s\" for \"%s(%s)\" is never used.",
3584 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3585 lemp->errorcnt++;
3586 }
3587
drh4dd0d3f2016-02-17 01:18:33 +00003588 /* Generate destructor code for RHS minor values which are not referenced.
3589 ** Generate error messages for unused labels and duplicate labels.
3590 */
drh0bb132b2004-07-20 14:06:51 +00003591 for(i=0; i<rp->nrhs; i++){
drh4dd0d3f2016-02-17 01:18:33 +00003592 if( rp->rhsalias[i] ){
3593 if( i>0 ){
3594 int j;
3595 if( rp->lhsalias && strcmp(rp->lhsalias,rp->rhsalias[i])==0 ){
3596 ErrorMsg(lemp->filename,rp->ruleline,
3597 "%s(%s) has the same label as the LHS but is not the left-most "
3598 "symbol on the RHS.",
3599 rp->rhs[i]->name, rp->rhsalias);
3600 lemp->errorcnt++;
3601 }
3602 for(j=0; j<i; j++){
3603 if( rp->rhsalias[j] && strcmp(rp->rhsalias[j],rp->rhsalias[i])==0 ){
3604 ErrorMsg(lemp->filename,rp->ruleline,
3605 "Label %s used for multiple symbols on the RHS of a rule.",
3606 rp->rhsalias[i]);
3607 lemp->errorcnt++;
3608 break;
3609 }
3610 }
drh0bb132b2004-07-20 14:06:51 +00003611 }
drh4dd0d3f2016-02-17 01:18:33 +00003612 if( !used[i] ){
3613 ErrorMsg(lemp->filename,rp->ruleline,
3614 "Label %s for \"%s(%s)\" is never used.",
3615 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3616 lemp->errorcnt++;
3617 }
3618 }else if( i>0 && has_destructor(rp->rhs[i],lemp) ){
3619 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
3620 rp->rhs[i]->index,i-rp->nrhs+1);
drh0bb132b2004-07-20 14:06:51 +00003621 }
3622 }
drh4dd0d3f2016-02-17 01:18:33 +00003623
3624 /* If unable to write LHS values directly into the stack, write the
3625 ** saved LHS value now. */
3626 if( lhsdirect==0 ){
3627 append_str(" yymsp[%d].minor.yy%d = ", 0, 1-rp->nrhs, rp->lhs->dtnum);
3628 append_str(zLhs, 0, 0, 0);
3629 append_str(";\n", 0, 0, 0);
drh61e339a2007-01-16 03:09:02 +00003630 }
drh4dd0d3f2016-02-17 01:18:33 +00003631
3632 /* Suffix code generation complete */
3633 cp = append_str(0,0,0,0);
3634 if( cp ) rp->codeSuffix = Strsafe(cp);
drhdabd04c2016-02-17 01:46:19 +00003635
3636 return rc;
drh0bb132b2004-07-20 14:06:51 +00003637}
3638
drh75897232000-05-29 14:26:00 +00003639/*
3640** Generate code which executes when the rule "rp" is reduced. Write
3641** the code to "out". Make sure lineno stays up-to-date.
3642*/
icculus9e44cf12010-02-14 17:14:22 +00003643PRIVATE void emit_code(
3644 FILE *out,
3645 struct rule *rp,
3646 struct lemon *lemp,
3647 int *lineno
3648){
3649 const char *cp;
drh75897232000-05-29 14:26:00 +00003650
drh4dd0d3f2016-02-17 01:18:33 +00003651 /* Setup code prior to the #line directive */
3652 if( rp->codePrefix && rp->codePrefix[0] ){
3653 fprintf(out, "{%s", rp->codePrefix);
3654 for(cp=rp->codePrefix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3655 }
3656
drh75897232000-05-29 14:26:00 +00003657 /* Generate code to do the reduce action */
3658 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003659 if( !lemp->nolinenosflag ){
3660 (*lineno)++;
3661 tplt_linedir(out,rp->line,lemp->filename);
3662 }
drhaf805ca2004-09-07 11:28:25 +00003663 fprintf(out,"{%s",rp->code);
drh4dd0d3f2016-02-17 01:18:33 +00003664 for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
shane58543932008-12-10 20:10:04 +00003665 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003666 if( !lemp->nolinenosflag ){
3667 (*lineno)++;
3668 tplt_linedir(out,*lineno,lemp->outname);
3669 }
drh4dd0d3f2016-02-17 01:18:33 +00003670 }
3671
3672 /* Generate breakdown code that occurs after the #line directive */
3673 if( rp->codeSuffix && rp->codeSuffix[0] ){
3674 fprintf(out, "%s", rp->codeSuffix);
3675 for(cp=rp->codeSuffix; *cp; cp++){ if( *cp=='\n' ) (*lineno)++; }
3676 }
3677
3678 if( rp->codePrefix ){
3679 fprintf(out, "}\n"); (*lineno)++;
3680 }
drh75897232000-05-29 14:26:00 +00003681
drh75897232000-05-29 14:26:00 +00003682 return;
3683}
3684
3685/*
3686** Print the definition of the union used for the parser's data stack.
3687** This union contains fields for every possible data type for tokens
3688** and nonterminals. In the process of computing and printing this
3689** union, also set the ".dtnum" field of every terminal and nonterminal
3690** symbol.
3691*/
icculus9e44cf12010-02-14 17:14:22 +00003692void print_stack_union(
3693 FILE *out, /* The output stream */
3694 struct lemon *lemp, /* The main info structure for this parser */
3695 int *plineno, /* Pointer to the line number */
3696 int mhflag /* True if generating makeheaders output */
3697){
drh75897232000-05-29 14:26:00 +00003698 int lineno = *plineno; /* The line number of the output */
3699 char **types; /* A hash table of datatypes */
3700 int arraysize; /* Size of the "types" array */
3701 int maxdtlength; /* Maximum length of any ".datatype" field. */
3702 char *stddt; /* Standardized name for a datatype */
3703 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003704 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003705 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003706
3707 /* Allocate and initialize types[] and allocate stddt[] */
3708 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003709 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003710 if( types==0 ){
3711 fprintf(stderr,"Out of memory.\n");
3712 exit(1);
3713 }
drh75897232000-05-29 14:26:00 +00003714 for(i=0; i<arraysize; i++) types[i] = 0;
3715 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003716 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003717 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003718 }
drh75897232000-05-29 14:26:00 +00003719 for(i=0; i<lemp->nsymbol; i++){
3720 int len;
3721 struct symbol *sp = lemp->symbols[i];
3722 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003723 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003724 if( len>maxdtlength ) maxdtlength = len;
3725 }
3726 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003727 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003728 fprintf(stderr,"Out of memory.\n");
3729 exit(1);
3730 }
3731
3732 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3733 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003734 ** used for terminal symbols. If there is no %default_type defined then
3735 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3736 ** a datatype using the %type directive.
3737 */
drh75897232000-05-29 14:26:00 +00003738 for(i=0; i<lemp->nsymbol; i++){
3739 struct symbol *sp = lemp->symbols[i];
3740 char *cp;
3741 if( sp==lemp->errsym ){
3742 sp->dtnum = arraysize+1;
3743 continue;
3744 }
drh960e8c62001-04-03 16:53:21 +00003745 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003746 sp->dtnum = 0;
3747 continue;
3748 }
3749 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003750 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003751 j = 0;
drhc56fac72015-10-29 13:48:15 +00003752 while( ISSPACE(*cp) ) cp++;
drh75897232000-05-29 14:26:00 +00003753 while( *cp ) stddt[j++] = *cp++;
drhc56fac72015-10-29 13:48:15 +00003754 while( j>0 && ISSPACE(stddt[j-1]) ) j--;
drh75897232000-05-29 14:26:00 +00003755 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003756 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003757 sp->dtnum = 0;
3758 continue;
3759 }
drh75897232000-05-29 14:26:00 +00003760 hash = 0;
3761 for(j=0; stddt[j]; j++){
3762 hash = hash*53 + stddt[j];
3763 }
drh3b2129c2003-05-13 00:34:21 +00003764 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003765 while( types[hash] ){
3766 if( strcmp(types[hash],stddt)==0 ){
3767 sp->dtnum = hash + 1;
3768 break;
3769 }
3770 hash++;
drh2b51f212013-10-11 23:01:02 +00003771 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003772 }
3773 if( types[hash]==0 ){
3774 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003775 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003776 if( types[hash]==0 ){
3777 fprintf(stderr,"Out of memory.\n");
3778 exit(1);
3779 }
drh898799f2014-01-10 23:21:00 +00003780 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003781 }
3782 }
3783
3784 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3785 name = lemp->name ? lemp->name : "Parse";
3786 lineno = *plineno;
3787 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3788 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3789 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3790 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3791 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003792 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003793 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3794 for(i=0; i<arraysize; i++){
3795 if( types[i]==0 ) continue;
3796 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3797 free(types[i]);
3798 }
drhc4dd3fd2008-01-22 01:48:05 +00003799 if( lemp->errsym->useCnt ){
3800 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3801 }
drh75897232000-05-29 14:26:00 +00003802 free(stddt);
3803 free(types);
3804 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3805 *plineno = lineno;
3806}
3807
drhb29b0a52002-02-23 19:39:46 +00003808/*
3809** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003810** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3811** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003812*/
drhc75e0162015-09-07 02:23:02 +00003813static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3814 const char *zType = "int";
3815 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003816 if( lwr>=0 ){
3817 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003818 zType = "unsigned char";
3819 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003820 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003821 zType = "unsigned short int";
3822 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003823 }else{
drhc75e0162015-09-07 02:23:02 +00003824 zType = "unsigned int";
3825 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003826 }
3827 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003828 zType = "signed char";
3829 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003830 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003831 zType = "short";
3832 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003833 }
drhc75e0162015-09-07 02:23:02 +00003834 if( pnByte ) *pnByte = nByte;
3835 return zType;
drhb29b0a52002-02-23 19:39:46 +00003836}
3837
drhfdbf9282003-10-21 16:34:41 +00003838/*
3839** Each state contains a set of token transaction and a set of
3840** nonterminal transactions. Each of these sets makes an instance
3841** of the following structure. An array of these structures is used
3842** to order the creation of entries in the yy_action[] table.
3843*/
3844struct axset {
3845 struct state *stp; /* A pointer to a state */
3846 int isTkn; /* True to use tokens. False for non-terminals */
3847 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003848 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003849};
3850
3851/*
3852** Compare to axset structures for sorting purposes
3853*/
3854static int axset_compare(const void *a, const void *b){
3855 struct axset *p1 = (struct axset*)a;
3856 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003857 int c;
3858 c = p2->nAction - p1->nAction;
3859 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003860 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003861 }
3862 assert( c!=0 || p1==p2 );
3863 return c;
drhfdbf9282003-10-21 16:34:41 +00003864}
3865
drhc4dd3fd2008-01-22 01:48:05 +00003866/*
3867** Write text on "out" that describes the rule "rp".
3868*/
3869static void writeRuleText(FILE *out, struct rule *rp){
3870 int j;
3871 fprintf(out,"%s ::=", rp->lhs->name);
3872 for(j=0; j<rp->nrhs; j++){
3873 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003874 if( sp->type!=MULTITERMINAL ){
3875 fprintf(out," %s", sp->name);
3876 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003877 int k;
drh61f92cd2014-01-11 03:06:18 +00003878 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003879 for(k=1; k<sp->nsubsym; k++){
3880 fprintf(out,"|%s",sp->subsym[k]->name);
3881 }
3882 }
3883 }
3884}
3885
3886
drh75897232000-05-29 14:26:00 +00003887/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003888void ReportTable(
3889 struct lemon *lemp,
3890 int mhflag /* Output in makeheaders format if true */
3891){
drh75897232000-05-29 14:26:00 +00003892 FILE *out, *in;
3893 char line[LINESIZE];
3894 int lineno;
3895 struct state *stp;
3896 struct action *ap;
3897 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003898 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003899 int i, j, n, sz;
3900 int szActionType; /* sizeof(YYACTIONTYPE) */
3901 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003902 const char *name;
drh8b582012003-10-21 13:16:03 +00003903 int mnTknOfst, mxTknOfst;
3904 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003905 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003906
3907 in = tplt_open(lemp);
3908 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003909 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003910 if( out==0 ){
3911 fclose(in);
3912 return;
3913 }
3914 lineno = 1;
3915 tplt_xfer(lemp->name,in,out,&lineno);
3916
3917 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003918 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003919 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00003920 char *incName = file_makename(lemp, ".h");
3921 fprintf(out,"#include \"%s\"\n", incName); lineno++;
3922 free(incName);
drh75897232000-05-29 14:26:00 +00003923 }
3924 tplt_xfer(lemp->name,in,out,&lineno);
3925
3926 /* Generate #defines for all tokens */
3927 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003928 const char *prefix;
drh75897232000-05-29 14:26:00 +00003929 fprintf(out,"#if INTERFACE\n"); lineno++;
3930 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3931 else prefix = "";
3932 for(i=1; i<lemp->nterminal; i++){
3933 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3934 lineno++;
3935 }
3936 fprintf(out,"#endif\n"); lineno++;
3937 }
3938 tplt_xfer(lemp->name,in,out,&lineno);
3939
3940 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003941 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00003942 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00003943 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3944 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00003945 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003946 if( lemp->wildcard ){
3947 fprintf(out,"#define YYWILDCARD %d\n",
3948 lemp->wildcard->index); lineno++;
3949 }
drh75897232000-05-29 14:26:00 +00003950 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003951 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003952 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003953 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3954 }else{
3955 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3956 }
drhca44b5a2007-02-22 23:06:58 +00003957 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003958 if( mhflag ){
3959 fprintf(out,"#if INTERFACE\n"); lineno++;
3960 }
3961 name = lemp->name ? lemp->name : "Parse";
3962 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00003963 i = lemonStrlen(lemp->arg);
drhc56fac72015-10-29 13:48:15 +00003964 while( i>=1 && ISSPACE(lemp->arg[i-1]) ) i--;
3965 while( i>=1 && (ISALNUM(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003966 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3967 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3968 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3969 name,lemp->arg,&lemp->arg[i]); lineno++;
3970 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3971 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003972 }else{
drh1f245e42002-03-11 13:55:50 +00003973 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3974 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3975 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3976 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003977 }
3978 if( mhflag ){
3979 fprintf(out,"#endif\n"); lineno++;
3980 }
drhc4dd3fd2008-01-22 01:48:05 +00003981 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00003982 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3983 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003984 }
drh0bd1f4e2002-06-06 18:54:39 +00003985 if( lemp->has_fallback ){
3986 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3987 }
drh75897232000-05-29 14:26:00 +00003988
drh3bd48ab2015-09-07 18:23:37 +00003989 /* Compute the action table, but do not output it yet. The action
3990 ** table must be computed before generating the YYNSTATE macro because
3991 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00003992 */
drh3bd48ab2015-09-07 18:23:37 +00003993 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003994 if( ax==0 ){
3995 fprintf(stderr,"malloc failed\n");
3996 exit(1);
3997 }
drh3bd48ab2015-09-07 18:23:37 +00003998 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003999 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004000 ax[i*2].stp = stp;
4001 ax[i*2].isTkn = 1;
4002 ax[i*2].nAction = stp->nTknAct;
4003 ax[i*2+1].stp = stp;
4004 ax[i*2+1].isTkn = 0;
4005 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00004006 }
drh8b582012003-10-21 13:16:03 +00004007 mxTknOfst = mnTknOfst = 0;
4008 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00004009 /* In an effort to minimize the action table size, use the heuristic
4010 ** of placing the largest action sets first */
4011 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
4012 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00004013 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00004014 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00004015 stp = ax[i].stp;
4016 if( ax[i].isTkn ){
4017 for(ap=stp->ap; ap; ap=ap->next){
4018 int action;
4019 if( ap->sp->index>=lemp->nterminal ) continue;
4020 action = compute_action(lemp, ap);
4021 if( action<0 ) continue;
4022 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004023 }
drhfdbf9282003-10-21 16:34:41 +00004024 stp->iTknOfst = acttab_insert(pActtab);
4025 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
4026 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
4027 }else{
4028 for(ap=stp->ap; ap; ap=ap->next){
4029 int action;
4030 if( ap->sp->index<lemp->nterminal ) continue;
4031 if( ap->sp->index==lemp->nsymbol ) continue;
4032 action = compute_action(lemp, ap);
4033 if( action<0 ) continue;
4034 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00004035 }
drhfdbf9282003-10-21 16:34:41 +00004036 stp->iNtOfst = acttab_insert(pActtab);
4037 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
4038 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00004039 }
drh337cd0d2015-09-07 23:40:42 +00004040#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
4041 { int jj, nn;
4042 for(jj=nn=0; jj<pActtab->nAction; jj++){
4043 if( pActtab->aAction[jj].action<0 ) nn++;
4044 }
4045 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
4046 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
4047 ax[i].nAction, pActtab->nAction, nn);
4048 }
4049#endif
drh8b582012003-10-21 13:16:03 +00004050 }
drhfdbf9282003-10-21 16:34:41 +00004051 free(ax);
drh8b582012003-10-21 13:16:03 +00004052
drh3bd48ab2015-09-07 18:23:37 +00004053 /* Finish rendering the constants now that the action table has
4054 ** been computed */
4055 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
4056 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00004057 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004058 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
4059 i = lemp->nstate + lemp->nrule;
4060 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
4061 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
4062 i = lemp->nstate + lemp->nrule*2;
4063 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
4064 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
4065 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
4066 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
4067 tplt_xfer(lemp->name,in,out,&lineno);
4068
4069 /* Now output the action table and its associates:
4070 **
4071 ** yy_action[] A single table containing all actions.
4072 ** yy_lookahead[] A table containing the lookahead for each entry in
4073 ** yy_action. Used to detect hash collisions.
4074 ** yy_shift_ofst[] For each state, the offset into yy_action for
4075 ** shifting terminals.
4076 ** yy_reduce_ofst[] For each state, the offset into yy_action for
4077 ** shifting non-terminals after a reduce.
4078 ** yy_default[] Default action for each state.
4079 */
4080
drh8b582012003-10-21 13:16:03 +00004081 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00004082 lemp->nactiontab = n = acttab_size(pActtab);
4083 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00004084 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
4085 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004086 for(i=j=0; i<n; i++){
4087 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00004088 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00004089 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004090 fprintf(out, " %4d,", action);
4091 if( j==9 || i==n-1 ){
4092 fprintf(out, "\n"); lineno++;
4093 j = 0;
4094 }else{
4095 j++;
4096 }
4097 }
4098 fprintf(out, "};\n"); lineno++;
4099
4100 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00004101 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00004102 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00004103 for(i=j=0; i<n; i++){
4104 int la = acttab_yylookahead(pActtab, i);
4105 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004106 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004107 fprintf(out, " %4d,", la);
4108 if( j==9 || i==n-1 ){
4109 fprintf(out, "\n"); lineno++;
4110 j = 0;
4111 }else{
4112 j++;
4113 }
4114 }
4115 fprintf(out, "};\n"); lineno++;
4116
4117 /* Output the yy_shift_ofst[] table */
4118 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004119 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004120 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004121 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4122 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4123 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004124 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004125 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4126 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004127 for(i=j=0; i<n; i++){
4128 int ofst;
4129 stp = lemp->sorted[i];
4130 ofst = stp->iTknOfst;
4131 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004132 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004133 fprintf(out, " %4d,", ofst);
4134 if( j==9 || i==n-1 ){
4135 fprintf(out, "\n"); lineno++;
4136 j = 0;
4137 }else{
4138 j++;
4139 }
4140 }
4141 fprintf(out, "};\n"); lineno++;
4142
4143 /* Output the yy_reduce_ofst[] table */
4144 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004145 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004146 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004147 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4148 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4149 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004150 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004151 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4152 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004153 for(i=j=0; i<n; i++){
4154 int ofst;
4155 stp = lemp->sorted[i];
4156 ofst = stp->iNtOfst;
4157 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004158 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004159 fprintf(out, " %4d,", ofst);
4160 if( j==9 || i==n-1 ){
4161 fprintf(out, "\n"); lineno++;
4162 j = 0;
4163 }else{
4164 j++;
4165 }
4166 }
4167 fprintf(out, "};\n"); lineno++;
4168
4169 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004170 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004171 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004172 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004173 for(i=j=0; i<n; i++){
4174 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004175 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004176 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004177 if( j==9 || i==n-1 ){
4178 fprintf(out, "\n"); lineno++;
4179 j = 0;
4180 }else{
4181 j++;
4182 }
4183 }
4184 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004185 tplt_xfer(lemp->name,in,out,&lineno);
4186
drh0bd1f4e2002-06-06 18:54:39 +00004187 /* Generate the table of fallback tokens.
4188 */
4189 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004190 int mx = lemp->nterminal - 1;
4191 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004192 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004193 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004194 struct symbol *p = lemp->symbols[i];
4195 if( p->fallback==0 ){
4196 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4197 }else{
4198 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4199 p->name, p->fallback->name);
4200 }
4201 lineno++;
4202 }
4203 }
4204 tplt_xfer(lemp->name, in, out, &lineno);
4205
4206 /* Generate a table containing the symbolic name of every symbol
4207 */
drh75897232000-05-29 14:26:00 +00004208 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004209 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004210 fprintf(out," %-15s",line);
4211 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4212 }
4213 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4214 tplt_xfer(lemp->name,in,out,&lineno);
4215
drh0bd1f4e2002-06-06 18:54:39 +00004216 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004217 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004218 ** when tracing REDUCE actions.
4219 */
4220 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4221 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004222 fprintf(out," /* %3d */ \"", i);
4223 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004224 fprintf(out,"\",\n"); lineno++;
4225 }
4226 tplt_xfer(lemp->name,in,out,&lineno);
4227
drh75897232000-05-29 14:26:00 +00004228 /* Generate code which executes every time a symbol is popped from
4229 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004230 ** (In other words, generate the %destructor actions)
4231 */
drh75897232000-05-29 14:26:00 +00004232 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004233 int once = 1;
drh75897232000-05-29 14:26:00 +00004234 for(i=0; i<lemp->nsymbol; i++){
4235 struct symbol *sp = lemp->symbols[i];
4236 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004237 if( once ){
4238 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4239 once = 0;
4240 }
drhc53eed12009-06-12 17:46:19 +00004241 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004242 }
4243 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4244 if( i<lemp->nsymbol ){
4245 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4246 fprintf(out," break;\n"); lineno++;
4247 }
4248 }
drh8d659732005-01-13 23:54:06 +00004249 if( lemp->vardest ){
4250 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004251 int once = 1;
drh8d659732005-01-13 23:54:06 +00004252 for(i=0; i<lemp->nsymbol; i++){
4253 struct symbol *sp = lemp->symbols[i];
4254 if( sp==0 || sp->type==TERMINAL ||
4255 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004256 if( once ){
4257 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4258 once = 0;
4259 }
drhc53eed12009-06-12 17:46:19 +00004260 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004261 dflt_sp = sp;
4262 }
4263 if( dflt_sp!=0 ){
4264 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004265 }
drh4dc8ef52008-07-01 17:13:57 +00004266 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004267 }
drh75897232000-05-29 14:26:00 +00004268 for(i=0; i<lemp->nsymbol; i++){
4269 struct symbol *sp = lemp->symbols[i];
4270 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004271 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004272
4273 /* Combine duplicate destructors into a single case */
4274 for(j=i+1; j<lemp->nsymbol; j++){
4275 struct symbol *sp2 = lemp->symbols[j];
4276 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4277 && sp2->dtnum==sp->dtnum
4278 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004279 fprintf(out," case %d: /* %s */\n",
4280 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004281 sp2->destructor = 0;
4282 }
4283 }
4284
drh75897232000-05-29 14:26:00 +00004285 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4286 fprintf(out," break;\n"); lineno++;
4287 }
drh75897232000-05-29 14:26:00 +00004288 tplt_xfer(lemp->name,in,out,&lineno);
4289
4290 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004291 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004292 tplt_xfer(lemp->name,in,out,&lineno);
4293
4294 /* Generate the table of rule information
4295 **
4296 ** Note: This code depends on the fact that rules are number
4297 ** sequentually beginning with 0.
4298 */
4299 for(rp=lemp->rule; rp; rp=rp->next){
4300 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4301 }
4302 tplt_xfer(lemp->name,in,out,&lineno);
4303
4304 /* Generate code which execution during each REDUCE action */
drhdabd04c2016-02-17 01:46:19 +00004305 i = 0;
drh75897232000-05-29 14:26:00 +00004306 for(rp=lemp->rule; rp; rp=rp->next){
drhdabd04c2016-02-17 01:46:19 +00004307 i += translate_code(lemp, rp);
4308 }
4309 if( i ){
4310 fprintf(out," YYMINORTYPE yylhsminor;\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004311 }
drhc53eed12009-06-12 17:46:19 +00004312 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004313 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004314 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004315 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004316 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004317 fprintf(out," case %d: /* ", rp->index);
4318 writeRuleText(out, rp);
4319 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004320 for(rp2=rp->next; rp2; rp2=rp2->next){
4321 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004322 fprintf(out," case %d: /* ", rp2->index);
4323 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004324 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004325 rp2->code = 0;
4326 }
4327 }
drh75897232000-05-29 14:26:00 +00004328 emit_code(out,rp,lemp,&lineno);
4329 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004330 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004331 }
drhc53eed12009-06-12 17:46:19 +00004332 /* Finally, output the default: rule. We choose as the default: all
4333 ** empty actions. */
4334 fprintf(out," default:\n"); lineno++;
4335 for(rp=lemp->rule; rp; rp=rp->next){
4336 if( rp->code==0 ) continue;
4337 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4338 fprintf(out," /* (%d) ", rp->index);
4339 writeRuleText(out, rp);
4340 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4341 }
4342 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004343 tplt_xfer(lemp->name,in,out,&lineno);
4344
4345 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004346 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004347 tplt_xfer(lemp->name,in,out,&lineno);
4348
4349 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004350 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004351 tplt_xfer(lemp->name,in,out,&lineno);
4352
4353 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004354 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004355 tplt_xfer(lemp->name,in,out,&lineno);
4356
4357 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004358 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004359
4360 fclose(in);
4361 fclose(out);
4362 return;
4363}
4364
4365/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004366void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004367{
4368 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004369 const char *prefix;
drh75897232000-05-29 14:26:00 +00004370 char line[LINESIZE];
4371 char pattern[LINESIZE];
4372 int i;
4373
4374 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4375 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004376 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004377 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004378 int nextChar;
drh75897232000-05-29 14:26:00 +00004379 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004380 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4381 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004382 if( strcmp(line,pattern) ) break;
4383 }
drh8ba0d1c2012-06-16 15:26:31 +00004384 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004385 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004386 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004387 /* No change in the file. Don't rewrite it. */
4388 return;
4389 }
4390 }
drh2aa6ca42004-09-10 00:14:04 +00004391 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004392 if( out ){
4393 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004394 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004395 }
4396 fclose(out);
4397 }
4398 return;
4399}
4400
4401/* Reduce the size of the action tables, if possible, by making use
4402** of defaults.
4403**
drhb59499c2002-02-23 18:45:13 +00004404** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004405** it the default. Except, there is no default if the wildcard token
4406** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004407*/
icculus9e44cf12010-02-14 17:14:22 +00004408void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004409{
4410 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004411 struct action *ap, *ap2;
4412 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004413 int nbest, n;
drh75897232000-05-29 14:26:00 +00004414 int i;
drhe09daa92006-06-10 13:29:31 +00004415 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004416
4417 for(i=0; i<lemp->nstate; i++){
4418 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004419 nbest = 0;
4420 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004421 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004422
drhb59499c2002-02-23 18:45:13 +00004423 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004424 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4425 usesWildcard = 1;
4426 }
drhb59499c2002-02-23 18:45:13 +00004427 if( ap->type!=REDUCE ) continue;
4428 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004429 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004430 if( rp==rbest ) continue;
4431 n = 1;
4432 for(ap2=ap->next; ap2; ap2=ap2->next){
4433 if( ap2->type!=REDUCE ) continue;
4434 rp2 = ap2->x.rp;
4435 if( rp2==rbest ) continue;
4436 if( rp2==rp ) n++;
4437 }
4438 if( n>nbest ){
4439 nbest = n;
4440 rbest = rp;
drh75897232000-05-29 14:26:00 +00004441 }
4442 }
drhb59499c2002-02-23 18:45:13 +00004443
4444 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004445 ** is not at least 1 or if the wildcard token is a possible
4446 ** lookahead.
4447 */
4448 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004449
drhb59499c2002-02-23 18:45:13 +00004450
4451 /* Combine matching REDUCE actions into a single default */
4452 for(ap=stp->ap; ap; ap=ap->next){
4453 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4454 }
drh75897232000-05-29 14:26:00 +00004455 assert( ap );
4456 ap->sp = Symbol_new("{default}");
4457 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004458 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004459 }
4460 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004461
4462 for(ap=stp->ap; ap; ap=ap->next){
4463 if( ap->type==SHIFT ) break;
4464 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4465 }
4466 if( ap==0 ){
4467 stp->autoReduce = 1;
4468 stp->pDfltReduce = rbest;
4469 }
4470 }
4471
4472 /* Make a second pass over all states and actions. Convert
4473 ** every action that is a SHIFT to an autoReduce state into
4474 ** a SHIFTREDUCE action.
4475 */
4476 for(i=0; i<lemp->nstate; i++){
4477 stp = lemp->sorted[i];
4478 for(ap=stp->ap; ap; ap=ap->next){
4479 struct state *pNextState;
4480 if( ap->type!=SHIFT ) continue;
4481 pNextState = ap->x.stp;
4482 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4483 ap->type = SHIFTREDUCE;
4484 ap->x.rp = pNextState->pDfltReduce;
4485 }
4486 }
drh75897232000-05-29 14:26:00 +00004487 }
4488}
drhb59499c2002-02-23 18:45:13 +00004489
drhada354d2005-11-05 15:03:59 +00004490
4491/*
4492** Compare two states for sorting purposes. The smaller state is the
4493** one with the most non-terminal actions. If they have the same number
4494** of non-terminal actions, then the smaller is the one with the most
4495** token actions.
4496*/
4497static int stateResortCompare(const void *a, const void *b){
4498 const struct state *pA = *(const struct state**)a;
4499 const struct state *pB = *(const struct state**)b;
4500 int n;
4501
4502 n = pB->nNtAct - pA->nNtAct;
4503 if( n==0 ){
4504 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004505 if( n==0 ){
4506 n = pB->statenum - pA->statenum;
4507 }
drhada354d2005-11-05 15:03:59 +00004508 }
drhe594bc32009-11-03 13:02:25 +00004509 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004510 return n;
4511}
4512
4513
4514/*
4515** Renumber and resort states so that states with fewer choices
4516** occur at the end. Except, keep state 0 as the first state.
4517*/
icculus9e44cf12010-02-14 17:14:22 +00004518void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004519{
4520 int i;
4521 struct state *stp;
4522 struct action *ap;
4523
4524 for(i=0; i<lemp->nstate; i++){
4525 stp = lemp->sorted[i];
4526 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004527 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004528 stp->iTknOfst = NO_OFFSET;
4529 stp->iNtOfst = NO_OFFSET;
4530 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004531 int iAction = compute_action(lemp,ap);
4532 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004533 if( ap->sp->index<lemp->nterminal ){
4534 stp->nTknAct++;
4535 }else if( ap->sp->index<lemp->nsymbol ){
4536 stp->nNtAct++;
4537 }else{
drh3bd48ab2015-09-07 18:23:37 +00004538 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4539 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004540 }
4541 }
4542 }
4543 }
4544 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4545 stateResortCompare);
4546 for(i=0; i<lemp->nstate; i++){
4547 lemp->sorted[i]->statenum = i;
4548 }
drh3bd48ab2015-09-07 18:23:37 +00004549 lemp->nxstate = lemp->nstate;
4550 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4551 lemp->nxstate--;
4552 }
drhada354d2005-11-05 15:03:59 +00004553}
4554
4555
drh75897232000-05-29 14:26:00 +00004556/***************** From the file "set.c" ************************************/
4557/*
4558** Set manipulation routines for the LEMON parser generator.
4559*/
4560
4561static int size = 0;
4562
4563/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004564void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004565{
4566 size = n+1;
4567}
4568
4569/* Allocate a new set */
4570char *SetNew(){
4571 char *s;
drh9892c5d2007-12-21 00:02:11 +00004572 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004573 if( s==0 ){
4574 extern void memory_error();
4575 memory_error();
4576 }
drh75897232000-05-29 14:26:00 +00004577 return s;
4578}
4579
4580/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004581void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004582{
4583 free(s);
4584}
4585
4586/* Add a new element to the set. Return TRUE if the element was added
4587** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004588int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004589{
4590 int rv;
drh9892c5d2007-12-21 00:02:11 +00004591 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004592 rv = s[e];
4593 s[e] = 1;
4594 return !rv;
4595}
4596
4597/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004598int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004599{
4600 int i, progress;
4601 progress = 0;
4602 for(i=0; i<size; i++){
4603 if( s2[i]==0 ) continue;
4604 if( s1[i]==0 ){
4605 progress = 1;
4606 s1[i] = 1;
4607 }
4608 }
4609 return progress;
4610}
4611/********************** From the file "table.c" ****************************/
4612/*
4613** All code in this file has been automatically generated
4614** from a specification in the file
4615** "table.q"
4616** by the associative array code building program "aagen".
4617** Do not edit this file! Instead, edit the specification
4618** file, then rerun aagen.
4619*/
4620/*
4621** Code for processing tables in the LEMON parser generator.
4622*/
4623
drh01f75f22013-10-02 20:46:30 +00004624PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004625{
drh01f75f22013-10-02 20:46:30 +00004626 unsigned h = 0;
4627 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004628 return h;
4629}
4630
4631/* Works like strdup, sort of. Save a string in malloced memory, but
4632** keep strings in a table so that the same string is not in more
4633** than one place.
4634*/
icculus9e44cf12010-02-14 17:14:22 +00004635const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004636{
icculus9e44cf12010-02-14 17:14:22 +00004637 const char *z;
4638 char *cpy;
drh75897232000-05-29 14:26:00 +00004639
drh916f75f2006-07-17 00:19:39 +00004640 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004641 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004642 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004643 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004644 z = cpy;
drh75897232000-05-29 14:26:00 +00004645 Strsafe_insert(z);
4646 }
4647 MemoryCheck(z);
4648 return z;
4649}
4650
4651/* There is one instance of the following structure for each
4652** associative array of type "x1".
4653*/
4654struct s_x1 {
4655 int size; /* The number of available slots. */
4656 /* Must be a power of 2 greater than or */
4657 /* equal to 1 */
4658 int count; /* Number of currently slots filled */
4659 struct s_x1node *tbl; /* The data stored here */
4660 struct s_x1node **ht; /* Hash table for lookups */
4661};
4662
4663/* There is one instance of this structure for every data element
4664** in an associative array of type "x1".
4665*/
4666typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004667 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004668 struct s_x1node *next; /* Next entry with the same hash */
4669 struct s_x1node **from; /* Previous link */
4670} x1node;
4671
4672/* There is only one instance of the array, which is the following */
4673static struct s_x1 *x1a;
4674
4675/* Allocate a new associative array */
4676void Strsafe_init(){
4677 if( x1a ) return;
4678 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4679 if( x1a ){
4680 x1a->size = 1024;
4681 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004682 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004683 if( x1a->tbl==0 ){
4684 free(x1a);
4685 x1a = 0;
4686 }else{
4687 int i;
4688 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4689 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4690 }
4691 }
4692}
4693/* Insert a new record into the array. Return TRUE if successful.
4694** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004695int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004696{
4697 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004698 unsigned h;
4699 unsigned ph;
drh75897232000-05-29 14:26:00 +00004700
4701 if( x1a==0 ) return 0;
4702 ph = strhash(data);
4703 h = ph & (x1a->size-1);
4704 np = x1a->ht[h];
4705 while( np ){
4706 if( strcmp(np->data,data)==0 ){
4707 /* An existing entry with the same key is found. */
4708 /* Fail because overwrite is not allows. */
4709 return 0;
4710 }
4711 np = np->next;
4712 }
4713 if( x1a->count>=x1a->size ){
4714 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004715 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004716 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004717 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004718 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004719 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004720 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004721 array.ht = (x1node**)&(array.tbl[arrSize]);
4722 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004723 for(i=0; i<x1a->count; i++){
4724 x1node *oldnp, *newnp;
4725 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004726 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004727 newnp = &(array.tbl[i]);
4728 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4729 newnp->next = array.ht[h];
4730 newnp->data = oldnp->data;
4731 newnp->from = &(array.ht[h]);
4732 array.ht[h] = newnp;
4733 }
4734 free(x1a->tbl);
4735 *x1a = array;
4736 }
4737 /* Insert the new data */
4738 h = ph & (x1a->size-1);
4739 np = &(x1a->tbl[x1a->count++]);
4740 np->data = data;
4741 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4742 np->next = x1a->ht[h];
4743 x1a->ht[h] = np;
4744 np->from = &(x1a->ht[h]);
4745 return 1;
4746}
4747
4748/* Return a pointer to data assigned to the given key. Return NULL
4749** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004750const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004751{
drh01f75f22013-10-02 20:46:30 +00004752 unsigned h;
drh75897232000-05-29 14:26:00 +00004753 x1node *np;
4754
4755 if( x1a==0 ) return 0;
4756 h = strhash(key) & (x1a->size-1);
4757 np = x1a->ht[h];
4758 while( np ){
4759 if( strcmp(np->data,key)==0 ) break;
4760 np = np->next;
4761 }
4762 return np ? np->data : 0;
4763}
4764
4765/* Return a pointer to the (terminal or nonterminal) symbol "x".
4766** Create a new symbol if this is the first time "x" has been seen.
4767*/
icculus9e44cf12010-02-14 17:14:22 +00004768struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004769{
4770 struct symbol *sp;
4771
4772 sp = Symbol_find(x);
4773 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004774 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004775 MemoryCheck(sp);
4776 sp->name = Strsafe(x);
drhc56fac72015-10-29 13:48:15 +00004777 sp->type = ISUPPER(*x) ? TERMINAL : NONTERMINAL;
drh75897232000-05-29 14:26:00 +00004778 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004779 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004780 sp->prec = -1;
4781 sp->assoc = UNK;
4782 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004783 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004784 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004785 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004786 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004787 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004788 Symbol_insert(sp,sp->name);
4789 }
drhc4dd3fd2008-01-22 01:48:05 +00004790 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004791 return sp;
4792}
4793
drh61f92cd2014-01-11 03:06:18 +00004794/* Compare two symbols for sorting purposes. Return negative,
4795** zero, or positive if a is less then, equal to, or greater
4796** than b.
drh60d31652004-02-22 00:08:04 +00004797**
4798** Symbols that begin with upper case letters (terminals or tokens)
4799** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004800** (non-terminals). And MULTITERMINAL symbols (created using the
4801** %token_class directive) must sort at the very end. Other than
4802** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004803**
4804** We find experimentally that leaving the symbols in their original
4805** order (the order they appeared in the grammar file) gives the
4806** smallest parser tables in SQLite.
4807*/
icculus9e44cf12010-02-14 17:14:22 +00004808int Symbolcmpp(const void *_a, const void *_b)
4809{
drh61f92cd2014-01-11 03:06:18 +00004810 const struct symbol *a = *(const struct symbol **) _a;
4811 const struct symbol *b = *(const struct symbol **) _b;
4812 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4813 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4814 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004815}
4816
4817/* There is one instance of the following structure for each
4818** associative array of type "x2".
4819*/
4820struct s_x2 {
4821 int size; /* The number of available slots. */
4822 /* Must be a power of 2 greater than or */
4823 /* equal to 1 */
4824 int count; /* Number of currently slots filled */
4825 struct s_x2node *tbl; /* The data stored here */
4826 struct s_x2node **ht; /* Hash table for lookups */
4827};
4828
4829/* There is one instance of this structure for every data element
4830** in an associative array of type "x2".
4831*/
4832typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004833 struct symbol *data; /* The data */
4834 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004835 struct s_x2node *next; /* Next entry with the same hash */
4836 struct s_x2node **from; /* Previous link */
4837} x2node;
4838
4839/* There is only one instance of the array, which is the following */
4840static struct s_x2 *x2a;
4841
4842/* Allocate a new associative array */
4843void Symbol_init(){
4844 if( x2a ) return;
4845 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4846 if( x2a ){
4847 x2a->size = 128;
4848 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004849 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004850 if( x2a->tbl==0 ){
4851 free(x2a);
4852 x2a = 0;
4853 }else{
4854 int i;
4855 x2a->ht = (x2node**)&(x2a->tbl[128]);
4856 for(i=0; i<128; i++) x2a->ht[i] = 0;
4857 }
4858 }
4859}
4860/* Insert a new record into the array. Return TRUE if successful.
4861** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004862int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004863{
4864 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004865 unsigned h;
4866 unsigned ph;
drh75897232000-05-29 14:26:00 +00004867
4868 if( x2a==0 ) return 0;
4869 ph = strhash(key);
4870 h = ph & (x2a->size-1);
4871 np = x2a->ht[h];
4872 while( np ){
4873 if( strcmp(np->key,key)==0 ){
4874 /* An existing entry with the same key is found. */
4875 /* Fail because overwrite is not allows. */
4876 return 0;
4877 }
4878 np = np->next;
4879 }
4880 if( x2a->count>=x2a->size ){
4881 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004882 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004883 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004884 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004885 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004886 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004887 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004888 array.ht = (x2node**)&(array.tbl[arrSize]);
4889 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004890 for(i=0; i<x2a->count; i++){
4891 x2node *oldnp, *newnp;
4892 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004893 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004894 newnp = &(array.tbl[i]);
4895 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4896 newnp->next = array.ht[h];
4897 newnp->key = oldnp->key;
4898 newnp->data = oldnp->data;
4899 newnp->from = &(array.ht[h]);
4900 array.ht[h] = newnp;
4901 }
4902 free(x2a->tbl);
4903 *x2a = array;
4904 }
4905 /* Insert the new data */
4906 h = ph & (x2a->size-1);
4907 np = &(x2a->tbl[x2a->count++]);
4908 np->key = key;
4909 np->data = data;
4910 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4911 np->next = x2a->ht[h];
4912 x2a->ht[h] = np;
4913 np->from = &(x2a->ht[h]);
4914 return 1;
4915}
4916
4917/* Return a pointer to data assigned to the given key. Return NULL
4918** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004919struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004920{
drh01f75f22013-10-02 20:46:30 +00004921 unsigned h;
drh75897232000-05-29 14:26:00 +00004922 x2node *np;
4923
4924 if( x2a==0 ) return 0;
4925 h = strhash(key) & (x2a->size-1);
4926 np = x2a->ht[h];
4927 while( np ){
4928 if( strcmp(np->key,key)==0 ) break;
4929 np = np->next;
4930 }
4931 return np ? np->data : 0;
4932}
4933
4934/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004935struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004936{
4937 struct symbol *data;
4938 if( x2a && n>0 && n<=x2a->count ){
4939 data = x2a->tbl[n-1].data;
4940 }else{
4941 data = 0;
4942 }
4943 return data;
4944}
4945
4946/* Return the size of the array */
4947int Symbol_count()
4948{
4949 return x2a ? x2a->count : 0;
4950}
4951
4952/* Return an array of pointers to all data in the table.
4953** The array is obtained from malloc. Return NULL if memory allocation
4954** problems, or if the array is empty. */
4955struct symbol **Symbol_arrayof()
4956{
4957 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00004958 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004959 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004960 arrSize = x2a->count;
4961 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004962 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004963 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004964 }
4965 return array;
4966}
4967
4968/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004969int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004970{
icculus9e44cf12010-02-14 17:14:22 +00004971 const struct config *a = (struct config *) _a;
4972 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004973 int x;
4974 x = a->rp->index - b->rp->index;
4975 if( x==0 ) x = a->dot - b->dot;
4976 return x;
4977}
4978
4979/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004980PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004981{
4982 int rc;
4983 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4984 rc = a->rp->index - b->rp->index;
4985 if( rc==0 ) rc = a->dot - b->dot;
4986 }
4987 if( rc==0 ){
4988 if( a ) rc = 1;
4989 if( b ) rc = -1;
4990 }
4991 return rc;
4992}
4993
4994/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00004995PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004996{
drh01f75f22013-10-02 20:46:30 +00004997 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004998 while( a ){
4999 h = h*571 + a->rp->index*37 + a->dot;
5000 a = a->bp;
5001 }
5002 return h;
5003}
5004
5005/* Allocate a new state structure */
5006struct state *State_new()
5007{
icculus9e44cf12010-02-14 17:14:22 +00005008 struct state *newstate;
5009 newstate = (struct state *)calloc(1, sizeof(struct state) );
5010 MemoryCheck(newstate);
5011 return newstate;
drh75897232000-05-29 14:26:00 +00005012}
5013
5014/* There is one instance of the following structure for each
5015** associative array of type "x3".
5016*/
5017struct s_x3 {
5018 int size; /* The number of available slots. */
5019 /* Must be a power of 2 greater than or */
5020 /* equal to 1 */
5021 int count; /* Number of currently slots filled */
5022 struct s_x3node *tbl; /* The data stored here */
5023 struct s_x3node **ht; /* Hash table for lookups */
5024};
5025
5026/* There is one instance of this structure for every data element
5027** in an associative array of type "x3".
5028*/
5029typedef struct s_x3node {
5030 struct state *data; /* The data */
5031 struct config *key; /* The key */
5032 struct s_x3node *next; /* Next entry with the same hash */
5033 struct s_x3node **from; /* Previous link */
5034} x3node;
5035
5036/* There is only one instance of the array, which is the following */
5037static struct s_x3 *x3a;
5038
5039/* Allocate a new associative array */
5040void State_init(){
5041 if( x3a ) return;
5042 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
5043 if( x3a ){
5044 x3a->size = 128;
5045 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005046 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005047 if( x3a->tbl==0 ){
5048 free(x3a);
5049 x3a = 0;
5050 }else{
5051 int i;
5052 x3a->ht = (x3node**)&(x3a->tbl[128]);
5053 for(i=0; i<128; i++) x3a->ht[i] = 0;
5054 }
5055 }
5056}
5057/* Insert a new record into the array. Return TRUE if successful.
5058** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005059int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00005060{
5061 x3node *np;
drh01f75f22013-10-02 20:46:30 +00005062 unsigned h;
5063 unsigned ph;
drh75897232000-05-29 14:26:00 +00005064
5065 if( x3a==0 ) return 0;
5066 ph = statehash(key);
5067 h = ph & (x3a->size-1);
5068 np = x3a->ht[h];
5069 while( np ){
5070 if( statecmp(np->key,key)==0 ){
5071 /* An existing entry with the same key is found. */
5072 /* Fail because overwrite is not allows. */
5073 return 0;
5074 }
5075 np = np->next;
5076 }
5077 if( x3a->count>=x3a->size ){
5078 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005079 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005080 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00005081 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00005082 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00005083 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00005084 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005085 array.ht = (x3node**)&(array.tbl[arrSize]);
5086 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005087 for(i=0; i<x3a->count; i++){
5088 x3node *oldnp, *newnp;
5089 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005090 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005091 newnp = &(array.tbl[i]);
5092 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5093 newnp->next = array.ht[h];
5094 newnp->key = oldnp->key;
5095 newnp->data = oldnp->data;
5096 newnp->from = &(array.ht[h]);
5097 array.ht[h] = newnp;
5098 }
5099 free(x3a->tbl);
5100 *x3a = array;
5101 }
5102 /* Insert the new data */
5103 h = ph & (x3a->size-1);
5104 np = &(x3a->tbl[x3a->count++]);
5105 np->key = key;
5106 np->data = data;
5107 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5108 np->next = x3a->ht[h];
5109 x3a->ht[h] = np;
5110 np->from = &(x3a->ht[h]);
5111 return 1;
5112}
5113
5114/* Return a pointer to data assigned to the given key. Return NULL
5115** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005116struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005117{
drh01f75f22013-10-02 20:46:30 +00005118 unsigned h;
drh75897232000-05-29 14:26:00 +00005119 x3node *np;
5120
5121 if( x3a==0 ) return 0;
5122 h = statehash(key) & (x3a->size-1);
5123 np = x3a->ht[h];
5124 while( np ){
5125 if( statecmp(np->key,key)==0 ) break;
5126 np = np->next;
5127 }
5128 return np ? np->data : 0;
5129}
5130
5131/* Return an array of pointers to all data in the table.
5132** The array is obtained from malloc. Return NULL if memory allocation
5133** problems, or if the array is empty. */
5134struct state **State_arrayof()
5135{
5136 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005137 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005138 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005139 arrSize = x3a->count;
5140 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005141 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005142 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005143 }
5144 return array;
5145}
5146
5147/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005148PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005149{
drh01f75f22013-10-02 20:46:30 +00005150 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005151 h = h*571 + a->rp->index*37 + a->dot;
5152 return h;
5153}
5154
5155/* There is one instance of the following structure for each
5156** associative array of type "x4".
5157*/
5158struct s_x4 {
5159 int size; /* The number of available slots. */
5160 /* Must be a power of 2 greater than or */
5161 /* equal to 1 */
5162 int count; /* Number of currently slots filled */
5163 struct s_x4node *tbl; /* The data stored here */
5164 struct s_x4node **ht; /* Hash table for lookups */
5165};
5166
5167/* There is one instance of this structure for every data element
5168** in an associative array of type "x4".
5169*/
5170typedef struct s_x4node {
5171 struct config *data; /* The data */
5172 struct s_x4node *next; /* Next entry with the same hash */
5173 struct s_x4node **from; /* Previous link */
5174} x4node;
5175
5176/* There is only one instance of the array, which is the following */
5177static struct s_x4 *x4a;
5178
5179/* Allocate a new associative array */
5180void Configtable_init(){
5181 if( x4a ) return;
5182 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5183 if( x4a ){
5184 x4a->size = 64;
5185 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005186 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005187 if( x4a->tbl==0 ){
5188 free(x4a);
5189 x4a = 0;
5190 }else{
5191 int i;
5192 x4a->ht = (x4node**)&(x4a->tbl[64]);
5193 for(i=0; i<64; i++) x4a->ht[i] = 0;
5194 }
5195 }
5196}
5197/* Insert a new record into the array. Return TRUE if successful.
5198** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005199int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005200{
5201 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005202 unsigned h;
5203 unsigned ph;
drh75897232000-05-29 14:26:00 +00005204
5205 if( x4a==0 ) return 0;
5206 ph = confighash(data);
5207 h = ph & (x4a->size-1);
5208 np = x4a->ht[h];
5209 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005210 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005211 /* An existing entry with the same key is found. */
5212 /* Fail because overwrite is not allows. */
5213 return 0;
5214 }
5215 np = np->next;
5216 }
5217 if( x4a->count>=x4a->size ){
5218 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005219 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005220 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005221 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005222 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005223 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005224 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005225 array.ht = (x4node**)&(array.tbl[arrSize]);
5226 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005227 for(i=0; i<x4a->count; i++){
5228 x4node *oldnp, *newnp;
5229 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005230 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005231 newnp = &(array.tbl[i]);
5232 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5233 newnp->next = array.ht[h];
5234 newnp->data = oldnp->data;
5235 newnp->from = &(array.ht[h]);
5236 array.ht[h] = newnp;
5237 }
5238 free(x4a->tbl);
5239 *x4a = array;
5240 }
5241 /* Insert the new data */
5242 h = ph & (x4a->size-1);
5243 np = &(x4a->tbl[x4a->count++]);
5244 np->data = data;
5245 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5246 np->next = x4a->ht[h];
5247 x4a->ht[h] = np;
5248 np->from = &(x4a->ht[h]);
5249 return 1;
5250}
5251
5252/* Return a pointer to data assigned to the given key. Return NULL
5253** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005254struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005255{
5256 int h;
5257 x4node *np;
5258
5259 if( x4a==0 ) return 0;
5260 h = confighash(key) & (x4a->size-1);
5261 np = x4a->ht[h];
5262 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005263 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005264 np = np->next;
5265 }
5266 return np ? np->data : 0;
5267}
5268
5269/* Remove all data from the table. Pass each data to the function "f"
5270** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005271void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005272{
5273 int i;
5274 if( x4a==0 || x4a->count==0 ) return;
5275 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5276 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5277 x4a->count = 0;
5278 return;
5279}