blob: 89d992c37ec8075da5a7b6983d8a0bcda2200b48 [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
drh75897232000-05-29 14:26:00 +000016#ifndef __WIN32__
17# if defined(_WIN32) || defined(WIN32)
drhf2f105d2012-08-20 15:53:54 +000018# define __WIN32__
drh75897232000-05-29 14:26:00 +000019# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
drhdf609712010-11-23 20:55:27 +000023#ifdef __cplusplus
24extern "C" {
25#endif
26extern int access(const char *path, int mode);
27#ifdef __cplusplus
28}
29#endif
rse8f304482007-07-30 18:31:53 +000030#else
31#include <unistd.h>
32#endif
33
drh75897232000-05-29 14:26:00 +000034/* #define PRIVATE static */
35#define PRIVATE
36
37#ifdef TEST
38#define MAXRHS 5 /* Set low to exercise exception code */
39#else
40#define MAXRHS 1000
41#endif
42
drhf5c4e0f2010-07-18 11:35:53 +000043static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000044static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000045
drh87cf1372008-08-13 20:09:06 +000046/*
47** Compilers are getting increasingly pedantic about type conversions
48** as C evolves ever closer to Ada.... To work around the latest problems
49** we have to define the following variant of strlen().
50*/
51#define lemonStrlen(X) ((int)strlen(X))
52
drh898799f2014-01-10 23:21:00 +000053/*
54** Compilers are starting to complain about the use of sprintf() and strcpy(),
55** saying they are unsafe. So we define our own versions of those routines too.
56**
57** There are three routines here: lemon_sprintf(), lemon_vsprintf(), and
58** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
59** The third is a helper routine for vsnprintf() that adds texts to the end of a
60** buffer, making sure the buffer is always zero-terminated.
61**
62** The string formatter is a minimal subset of stdlib sprintf() supporting only
63** a few simply conversions:
64**
65** %d
66** %s
67** %.*s
68**
69*/
70static void lemon_addtext(
71 char *zBuf, /* The buffer to which text is added */
72 int *pnUsed, /* Slots of the buffer used so far */
73 const char *zIn, /* Text to add */
drh61f92cd2014-01-11 03:06:18 +000074 int nIn, /* Bytes of text to add. -1 to use strlen() */
75 int iWidth /* Field width. Negative to left justify */
drh898799f2014-01-10 23:21:00 +000076){
77 if( nIn<0 ) for(nIn=0; zIn[nIn]; nIn++){}
drhecaa9d32014-01-11 03:27:37 +000078 while( iWidth>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth--; }
drh898799f2014-01-10 23:21:00 +000079 if( nIn==0 ) return;
80 memcpy(&zBuf[*pnUsed], zIn, nIn);
81 *pnUsed += nIn;
drhecaa9d32014-01-11 03:27:37 +000082 while( (-iWidth)>nIn ){ zBuf[(*pnUsed)++] = ' '; iWidth++; }
drh898799f2014-01-10 23:21:00 +000083 zBuf[*pnUsed] = 0;
84}
85static int lemon_vsprintf(char *str, const char *zFormat, va_list ap){
mistachkin7a429652014-01-14 10:17:21 +000086 int i, j, k, c;
drh898799f2014-01-10 23:21:00 +000087 int nUsed = 0;
88 const char *z;
89 char zTemp[50];
90 str[0] = 0;
91 for(i=j=0; (c = zFormat[i])!=0; i++){
92 if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +000093 int iWidth = 0;
94 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +000095 c = zFormat[++i];
drh61f92cd2014-01-11 03:06:18 +000096 if( isdigit(c) || (c=='-' && isdigit(zFormat[i+1])) ){
97 if( c=='-' ) i++;
98 while( isdigit(zFormat[i]) ) iWidth = iWidth*10 + zFormat[i++] - '0';
99 if( c=='-' ) iWidth = -iWidth;
100 c = zFormat[i];
101 }
drh898799f2014-01-10 23:21:00 +0000102 if( c=='d' ){
103 int v = va_arg(ap, int);
104 if( v<0 ){
drh61f92cd2014-01-11 03:06:18 +0000105 lemon_addtext(str, &nUsed, "-", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000106 v = -v;
107 }else if( v==0 ){
drh61f92cd2014-01-11 03:06:18 +0000108 lemon_addtext(str, &nUsed, "0", 1, iWidth);
drh898799f2014-01-10 23:21:00 +0000109 }
110 k = 0;
111 while( v>0 ){
112 k++;
113 zTemp[sizeof(zTemp)-k] = (v%10) + '0';
114 v /= 10;
115 }
drh61f92cd2014-01-11 03:06:18 +0000116 lemon_addtext(str, &nUsed, &zTemp[sizeof(zTemp)-k], k, iWidth);
drh898799f2014-01-10 23:21:00 +0000117 }else if( c=='s' ){
118 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000119 lemon_addtext(str, &nUsed, z, -1, iWidth);
drh898799f2014-01-10 23:21:00 +0000120 }else if( c=='.' && memcmp(&zFormat[i], ".*s", 3)==0 ){
121 i += 2;
122 k = va_arg(ap, int);
123 z = va_arg(ap, const char*);
drh61f92cd2014-01-11 03:06:18 +0000124 lemon_addtext(str, &nUsed, z, k, iWidth);
drh898799f2014-01-10 23:21:00 +0000125 }else if( c=='%' ){
drh61f92cd2014-01-11 03:06:18 +0000126 lemon_addtext(str, &nUsed, "%", 1, 0);
drh898799f2014-01-10 23:21:00 +0000127 }else{
128 fprintf(stderr, "illegal format\n");
129 exit(1);
130 }
131 j = i+1;
132 }
133 }
drh61f92cd2014-01-11 03:06:18 +0000134 lemon_addtext(str, &nUsed, &zFormat[j], i-j, 0);
drh898799f2014-01-10 23:21:00 +0000135 return nUsed;
136}
137static int lemon_sprintf(char *str, const char *format, ...){
138 va_list ap;
139 int rc;
140 va_start(ap, format);
141 rc = lemon_vsprintf(str, format, ap);
142 va_end(ap);
143 return rc;
144}
145static void lemon_strcpy(char *dest, const char *src){
146 while( (*(dest++) = *(src++))!=0 ){}
147}
148static void lemon_strcat(char *dest, const char *src){
149 while( *dest ) dest++;
150 lemon_strcpy(dest, src);
151}
152
153
icculus9e44cf12010-02-14 17:14:22 +0000154/* a few forward declarations... */
155struct rule;
156struct lemon;
157struct action;
158
drhe9278182007-07-18 18:16:29 +0000159static struct action *Action_new(void);
160static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +0000161
162/********** From the file "build.h" ************************************/
163void FindRulePrecedences();
164void FindFirstSets();
165void FindStates();
166void FindLinks();
167void FindFollowSets();
168void FindActions();
169
170/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +0000171void Configlist_init(void);
172struct config *Configlist_add(struct rule *, int);
173struct config *Configlist_addbasis(struct rule *, int);
174void Configlist_closure(struct lemon *);
175void Configlist_sort(void);
176void Configlist_sortbasis(void);
177struct config *Configlist_return(void);
178struct config *Configlist_basis(void);
179void Configlist_eat(struct config *);
180void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +0000181
182/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +0000183void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +0000184
185/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +0000186enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
187 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +0000188struct s_options {
icculus9e44cf12010-02-14 17:14:22 +0000189 enum option_type type;
190 const char *label;
drh75897232000-05-29 14:26:00 +0000191 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000192 const char *message;
drh75897232000-05-29 14:26:00 +0000193};
icculus9e44cf12010-02-14 17:14:22 +0000194int OptInit(char**,struct s_options*,FILE*);
195int OptNArgs(void);
196char *OptArg(int);
197void OptErr(int);
198void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000199
200/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000201void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000202
203/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000204struct plink *Plink_new(void);
205void Plink_add(struct plink **, struct config *);
206void Plink_copy(struct plink **, struct plink *);
207void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000208
209/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000210void Reprint(struct lemon *);
211void ReportOutput(struct lemon *);
212void ReportTable(struct lemon *, int);
213void ReportHeader(struct lemon *);
214void CompressTables(struct lemon *);
215void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000216
217/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000218void SetSize(int); /* All sets will be of size N */
219char *SetNew(void); /* A new set for element 0..N */
220void SetFree(char*); /* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +0000221int SetAdd(char*,int); /* Add element to a set */
222int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000223#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
224
225/********** From the file "struct.h" *************************************/
226/*
227** Principal data structures for the LEMON parser generator.
228*/
229
drhaa9f1122007-08-23 02:50:56 +0000230typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000231
232/* Symbols (terminals and nonterminals) of the grammar are stored
233** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000234enum symbol_type {
235 TERMINAL,
236 NONTERMINAL,
237 MULTITERMINAL
238};
239enum e_assoc {
drh75897232000-05-29 14:26:00 +0000240 LEFT,
241 RIGHT,
242 NONE,
243 UNK
icculus9e44cf12010-02-14 17:14:22 +0000244};
245struct symbol {
246 const char *name; /* Name of the symbol */
247 int index; /* Index number for this symbol */
248 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
249 struct rule *rule; /* Linked list of rules of this (if an NT) */
250 struct symbol *fallback; /* fallback token in case this token doesn't parse */
251 int prec; /* Precedence if defined (-1 otherwise) */
252 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000253 char *firstset; /* First-set for all rules of this symbol */
254 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000255 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000256 char *destructor; /* Code which executes whenever this symbol is
257 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000258 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000259 char *datatype; /* The data type of information held by this
260 ** object. Only used if type==NONTERMINAL */
261 int dtnum; /* The data type number. In the parser, the value
262 ** stack is a union. The .yy%d element of this
263 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000264 /* The following fields are used by MULTITERMINALs only */
265 int nsubsym; /* Number of constituent symbols in the MULTI */
266 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000267};
268
269/* Each production rule in the grammar is stored in the following
270** structure. */
271struct rule {
272 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000273 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000274 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000275 int ruleline; /* Line number for the rule */
276 int nrhs; /* Number of RHS symbols */
277 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000278 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000279 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000280 const char *code; /* The code executed when this rule is reduced */
drh75897232000-05-29 14:26:00 +0000281 struct symbol *precsym; /* Precedence symbol for this rule */
282 int index; /* An index number for this rule */
283 Boolean canReduce; /* True if this rule is ever reduced */
284 struct rule *nextlhs; /* Next rule with the same LHS */
285 struct rule *next; /* Next rule in the global list */
286};
287
288/* A configuration is a production rule of the grammar together with
289** a mark (dot) showing how much of that rule has been processed so far.
290** Configurations also contain a follow-set which is a list of terminal
291** symbols which are allowed to immediately follow the end of the rule.
292** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000293enum cfgstatus {
294 COMPLETE,
295 INCOMPLETE
296};
drh75897232000-05-29 14:26:00 +0000297struct config {
298 struct rule *rp; /* The rule upon which the configuration is based */
299 int dot; /* The parse point */
300 char *fws; /* Follow-set for this configuration only */
301 struct plink *fplp; /* Follow-set forward propagation links */
302 struct plink *bplp; /* Follow-set backwards propagation links */
303 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000304 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000305 struct config *next; /* Next configuration in the state */
306 struct config *bp; /* The next basis configuration */
307};
308
icculus9e44cf12010-02-14 17:14:22 +0000309enum e_action {
310 SHIFT,
311 ACCEPT,
312 REDUCE,
313 ERROR,
314 SSCONFLICT, /* A shift/shift conflict */
315 SRCONFLICT, /* Was a reduce, but part of a conflict */
316 RRCONFLICT, /* Was a reduce, but part of a conflict */
317 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
318 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
319 NOT_USED /* Deleted by compression */
320};
321
drh75897232000-05-29 14:26:00 +0000322/* Every shift or reduce operation is stored as one of the following */
323struct action {
324 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000325 enum e_action type;
drh75897232000-05-29 14:26:00 +0000326 union {
327 struct state *stp; /* The new state, if a shift */
328 struct rule *rp; /* The rule, if a reduce */
329 } x;
330 struct action *next; /* Next action for this state */
331 struct action *collide; /* Next action with the same hash */
332};
333
334/* Each state of the generated parser's finite state machine
335** is encoded as an instance of the following structure. */
336struct state {
337 struct config *bp; /* The basis configurations for this state */
338 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000339 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000340 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000341 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
342 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
343 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000344};
drh8b582012003-10-21 13:16:03 +0000345#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000346
347/* A followset propagation link indicates that the contents of one
348** configuration followset should be propagated to another whenever
349** the first changes. */
350struct plink {
351 struct config *cfp; /* The configuration to which linked */
352 struct plink *next; /* The next propagate link */
353};
354
355/* The state vector for the entire parser generator is recorded as
356** follows. (LEMON uses no global variables and makes little use of
357** static variables. Fields in the following structure can be thought
358** of as begin global variables in the program.) */
359struct lemon {
360 struct state **sorted; /* Table of states sorted by state number */
361 struct rule *rule; /* List of all rules */
362 int nstate; /* Number of states */
363 int nrule; /* Number of rules */
364 int nsymbol; /* Number of terminal and nonterminal symbols */
365 int nterminal; /* Number of terminal symbols */
366 struct symbol **symbols; /* Sorted array of pointers to symbols */
367 int errorcnt; /* Number of errors */
368 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000369 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000370 char *name; /* Name of the generated parser */
371 char *arg; /* Declaration of the 3th argument to parser */
372 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000373 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000374 char *start; /* Name of the start symbol for the grammar */
375 char *stacksize; /* Size of the parser stack */
376 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000377 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000378 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000379 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000380 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000381 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000382 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000383 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000384 char *filename; /* Name of the input file */
385 char *outname; /* Name of the current output file */
386 char *tokenprefix; /* A prefix added to token names in the .h file */
387 int nconflict; /* Number of parsing conflicts */
388 int tablesize; /* Size of the parse tables */
389 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000390 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000391 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000392 char *argv0; /* Name of the program */
393};
394
395#define MemoryCheck(X) if((X)==0){ \
396 extern void memory_error(); \
397 memory_error(); \
398}
399
400/**************** From the file "table.h" *********************************/
401/*
402** All code in this file has been automatically generated
403** from a specification in the file
404** "table.q"
405** by the associative array code building program "aagen".
406** Do not edit this file! Instead, edit the specification
407** file, then rerun aagen.
408*/
409/*
410** Code for processing tables in the LEMON parser generator.
411*/
drh75897232000-05-29 14:26:00 +0000412/* Routines for handling a strings */
413
icculus9e44cf12010-02-14 17:14:22 +0000414const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000415
icculus9e44cf12010-02-14 17:14:22 +0000416void Strsafe_init(void);
417int Strsafe_insert(const char *);
418const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000419
420/* Routines for handling symbols of the grammar */
421
icculus9e44cf12010-02-14 17:14:22 +0000422struct symbol *Symbol_new(const char *);
423int Symbolcmpp(const void *, const void *);
424void Symbol_init(void);
425int Symbol_insert(struct symbol *, const char *);
426struct symbol *Symbol_find(const char *);
427struct symbol *Symbol_Nth(int);
428int Symbol_count(void);
429struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000430
431/* Routines to manage the state table */
432
icculus9e44cf12010-02-14 17:14:22 +0000433int Configcmp(const char *, const char *);
434struct state *State_new(void);
435void State_init(void);
436int State_insert(struct state *, struct config *);
437struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000438struct state **State_arrayof(/* */);
439
440/* Routines used for efficiency in Configlist_add */
441
icculus9e44cf12010-02-14 17:14:22 +0000442void Configtable_init(void);
443int Configtable_insert(struct config *);
444struct config *Configtable_find(struct config *);
445void Configtable_clear(int(*)(struct config *));
446
drh75897232000-05-29 14:26:00 +0000447/****************** From the file "action.c" *******************************/
448/*
449** Routines processing parser actions in the LEMON parser generator.
450*/
451
452/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000453static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000454 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000455 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000456
457 if( freelist==0 ){
458 int i;
459 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000460 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000461 if( freelist==0 ){
462 fprintf(stderr,"Unable to allocate memory for a new parser action.");
463 exit(1);
464 }
465 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
466 freelist[amt-1].next = 0;
467 }
icculus9e44cf12010-02-14 17:14:22 +0000468 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000469 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000470 return newaction;
drh75897232000-05-29 14:26:00 +0000471}
472
drhe9278182007-07-18 18:16:29 +0000473/* Compare two actions for sorting purposes. Return negative, zero, or
474** positive if the first action is less than, equal to, or greater than
475** the first
476*/
477static int actioncmp(
478 struct action *ap1,
479 struct action *ap2
480){
drh75897232000-05-29 14:26:00 +0000481 int rc;
482 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000483 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000484 rc = (int)ap1->type - (int)ap2->type;
485 }
486 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000487 rc = ap1->x.rp->index - ap2->x.rp->index;
488 }
drhe594bc32009-11-03 13:02:25 +0000489 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000490 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000491 }
drh75897232000-05-29 14:26:00 +0000492 return rc;
493}
494
495/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000496static struct action *Action_sort(
497 struct action *ap
498){
499 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
500 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000501 return ap;
502}
503
icculus9e44cf12010-02-14 17:14:22 +0000504void Action_add(
505 struct action **app,
506 enum e_action type,
507 struct symbol *sp,
508 char *arg
509){
510 struct action *newaction;
511 newaction = Action_new();
512 newaction->next = *app;
513 *app = newaction;
514 newaction->type = type;
515 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000516 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000517 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000518 }else{
icculus9e44cf12010-02-14 17:14:22 +0000519 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000520 }
521}
drh8b582012003-10-21 13:16:03 +0000522/********************** New code to implement the "acttab" module ***********/
523/*
524** This module implements routines use to construct the yy_action[] table.
525*/
526
527/*
528** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000529** the following structure.
530**
531** The yy_action table maps the pair (state_number, lookahead) into an
532** action_number. The table is an array of integers pairs. The state_number
533** determines an initial offset into the yy_action array. The lookahead
534** value is then added to this initial offset to get an index X into the
535** yy_action array. If the aAction[X].lookahead equals the value of the
536** of the lookahead input, then the value of the action_number output is
537** aAction[X].action. If the lookaheads do not match then the
538** default action for the state_number is returned.
539**
540** All actions associated with a single state_number are first entered
541** into aLookahead[] using multiple calls to acttab_action(). Then the
542** actions for that single state_number are placed into the aAction[]
543** array with a single call to acttab_insert(). The acttab_insert() call
544** also resets the aLookahead[] array in preparation for the next
545** state number.
drh8b582012003-10-21 13:16:03 +0000546*/
icculus9e44cf12010-02-14 17:14:22 +0000547struct lookahead_action {
548 int lookahead; /* Value of the lookahead token */
549 int action; /* Action to take on the given lookahead */
550};
drh8b582012003-10-21 13:16:03 +0000551typedef struct acttab acttab;
552struct acttab {
553 int nAction; /* Number of used slots in aAction[] */
554 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000555 struct lookahead_action
556 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000557 *aLookahead; /* A single new transaction set */
558 int mnLookahead; /* Minimum aLookahead[].lookahead */
559 int mnAction; /* Action associated with mnLookahead */
560 int mxLookahead; /* Maximum aLookahead[].lookahead */
561 int nLookahead; /* Used slots in aLookahead[] */
562 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
563};
564
565/* Return the number of entries in the yy_action table */
566#define acttab_size(X) ((X)->nAction)
567
568/* The value for the N-th entry in yy_action */
569#define acttab_yyaction(X,N) ((X)->aAction[N].action)
570
571/* The value for the N-th entry in yy_lookahead */
572#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
573
574/* Free all memory associated with the given acttab */
575void acttab_free(acttab *p){
576 free( p->aAction );
577 free( p->aLookahead );
578 free( p );
579}
580
581/* Allocate a new acttab structure */
582acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000583 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000584 if( p==0 ){
585 fprintf(stderr,"Unable to allocate memory for a new acttab.");
586 exit(1);
587 }
588 memset(p, 0, sizeof(*p));
589 return p;
590}
591
drh8dc3e8f2010-01-07 03:53:03 +0000592/* Add a new action to the current transaction set.
593**
594** This routine is called once for each lookahead for a particular
595** state.
drh8b582012003-10-21 13:16:03 +0000596*/
597void acttab_action(acttab *p, int lookahead, int action){
598 if( p->nLookahead>=p->nLookaheadAlloc ){
599 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000600 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000601 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
602 if( p->aLookahead==0 ){
603 fprintf(stderr,"malloc failed\n");
604 exit(1);
605 }
606 }
607 if( p->nLookahead==0 ){
608 p->mxLookahead = lookahead;
609 p->mnLookahead = lookahead;
610 p->mnAction = action;
611 }else{
612 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
613 if( p->mnLookahead>lookahead ){
614 p->mnLookahead = lookahead;
615 p->mnAction = action;
616 }
617 }
618 p->aLookahead[p->nLookahead].lookahead = lookahead;
619 p->aLookahead[p->nLookahead].action = action;
620 p->nLookahead++;
621}
622
623/*
624** Add the transaction set built up with prior calls to acttab_action()
625** into the current action table. Then reset the transaction set back
626** to an empty set in preparation for a new round of acttab_action() calls.
627**
628** Return the offset into the action table of the new transaction.
629*/
630int acttab_insert(acttab *p){
631 int i, j, k, n;
632 assert( p->nLookahead>0 );
633
634 /* Make sure we have enough space to hold the expanded action table
635 ** in the worst case. The worst case occurs if the transaction set
636 ** must be appended to the current action table
637 */
drh784d86f2004-02-19 18:41:53 +0000638 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000639 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000640 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000641 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000642 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000643 sizeof(p->aAction[0])*p->nActionAlloc);
644 if( p->aAction==0 ){
645 fprintf(stderr,"malloc failed\n");
646 exit(1);
647 }
drhfdbf9282003-10-21 16:34:41 +0000648 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000649 p->aAction[i].lookahead = -1;
650 p->aAction[i].action = -1;
651 }
652 }
653
drh8dc3e8f2010-01-07 03:53:03 +0000654 /* Scan the existing action table looking for an offset that is a
655 ** duplicate of the current transaction set. Fall out of the loop
656 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000657 **
658 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
659 */
drh8dc3e8f2010-01-07 03:53:03 +0000660 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000661 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000662 /* All lookaheads and actions in the aLookahead[] transaction
663 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000664 if( p->aAction[i].action!=p->mnAction ) continue;
665 for(j=0; j<p->nLookahead; j++){
666 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
667 if( k<0 || k>=p->nAction ) break;
668 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
669 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
670 }
671 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000672
673 /* No possible lookahead value that is not in the aLookahead[]
674 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000675 n = 0;
676 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000677 if( p->aAction[j].lookahead<0 ) continue;
678 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000679 }
drhfdbf9282003-10-21 16:34:41 +0000680 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000681 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000682 }
drh8b582012003-10-21 13:16:03 +0000683 }
684 }
drh8dc3e8f2010-01-07 03:53:03 +0000685
686 /* If no existing offsets exactly match the current transaction, find an
687 ** an empty offset in the aAction[] table in which we can add the
688 ** aLookahead[] transaction.
689 */
drhf16371d2009-11-03 19:18:31 +0000690 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000691 /* Look for holes in the aAction[] table that fit the current
692 ** aLookahead[] transaction. Leave i set to the offset of the hole.
693 ** If no holes are found, i is left at p->nAction, which means the
694 ** transaction will be appended. */
695 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000696 if( p->aAction[i].lookahead<0 ){
697 for(j=0; j<p->nLookahead; j++){
698 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
699 if( k<0 ) break;
700 if( p->aAction[k].lookahead>=0 ) break;
701 }
702 if( j<p->nLookahead ) continue;
703 for(j=0; j<p->nAction; j++){
704 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
705 }
706 if( j==p->nAction ){
707 break; /* Fits in empty slots */
708 }
709 }
710 }
711 }
drh8b582012003-10-21 13:16:03 +0000712 /* Insert transaction set at index i. */
713 for(j=0; j<p->nLookahead; j++){
714 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
715 p->aAction[k] = p->aLookahead[j];
716 if( k>=p->nAction ) p->nAction = k+1;
717 }
718 p->nLookahead = 0;
719
720 /* Return the offset that is added to the lookahead in order to get the
721 ** index into yy_action of the action */
722 return i - p->mnLookahead;
723}
724
drh75897232000-05-29 14:26:00 +0000725/********************** From the file "build.c" *****************************/
726/*
727** Routines to construction the finite state machine for the LEMON
728** parser generator.
729*/
730
731/* Find a precedence symbol of every rule in the grammar.
732**
733** Those rules which have a precedence symbol coded in the input
734** grammar using the "[symbol]" construct will already have the
735** rp->precsym field filled. Other rules take as their precedence
736** symbol the first RHS symbol with a defined precedence. If there
737** are not RHS symbols with a defined precedence, the precedence
738** symbol field is left blank.
739*/
icculus9e44cf12010-02-14 17:14:22 +0000740void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000741{
742 struct rule *rp;
743 for(rp=xp->rule; rp; rp=rp->next){
744 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000745 int i, j;
746 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
747 struct symbol *sp = rp->rhs[i];
748 if( sp->type==MULTITERMINAL ){
749 for(j=0; j<sp->nsubsym; j++){
750 if( sp->subsym[j]->prec>=0 ){
751 rp->precsym = sp->subsym[j];
752 break;
753 }
754 }
755 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000756 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000757 }
drh75897232000-05-29 14:26:00 +0000758 }
759 }
760 }
761 return;
762}
763
764/* Find all nonterminals which will generate the empty string.
765** Then go back and compute the first sets of every nonterminal.
766** The first set is the set of all terminal symbols which can begin
767** a string generated by that nonterminal.
768*/
icculus9e44cf12010-02-14 17:14:22 +0000769void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000770{
drhfd405312005-11-06 04:06:59 +0000771 int i, j;
drh75897232000-05-29 14:26:00 +0000772 struct rule *rp;
773 int progress;
774
775 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000776 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000777 }
778 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
779 lemp->symbols[i]->firstset = SetNew();
780 }
781
782 /* First compute all lambdas */
783 do{
784 progress = 0;
785 for(rp=lemp->rule; rp; rp=rp->next){
786 if( rp->lhs->lambda ) continue;
787 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000788 struct symbol *sp = rp->rhs[i];
789 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
790 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000791 }
792 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000793 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000794 progress = 1;
795 }
796 }
797 }while( progress );
798
799 /* Now compute all first sets */
800 do{
801 struct symbol *s1, *s2;
802 progress = 0;
803 for(rp=lemp->rule; rp; rp=rp->next){
804 s1 = rp->lhs;
805 for(i=0; i<rp->nrhs; i++){
806 s2 = rp->rhs[i];
807 if( s2->type==TERMINAL ){
808 progress += SetAdd(s1->firstset,s2->index);
809 break;
drhfd405312005-11-06 04:06:59 +0000810 }else if( s2->type==MULTITERMINAL ){
811 for(j=0; j<s2->nsubsym; j++){
812 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
813 }
814 break;
drhf2f105d2012-08-20 15:53:54 +0000815 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000816 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000817 }else{
drh75897232000-05-29 14:26:00 +0000818 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000819 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000820 }
drh75897232000-05-29 14:26:00 +0000821 }
822 }
823 }while( progress );
824 return;
825}
826
827/* Compute all LR(0) states for the grammar. Links
828** are added to between some states so that the LR(1) follow sets
829** can be computed later.
830*/
icculus9e44cf12010-02-14 17:14:22 +0000831PRIVATE struct state *getstate(struct lemon *); /* forward reference */
832void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000833{
834 struct symbol *sp;
835 struct rule *rp;
836
837 Configlist_init();
838
839 /* Find the start symbol */
840 if( lemp->start ){
841 sp = Symbol_find(lemp->start);
842 if( sp==0 ){
843 ErrorMsg(lemp->filename,0,
844"The specified start symbol \"%s\" is not \
845in a nonterminal of the grammar. \"%s\" will be used as the start \
846symbol instead.",lemp->start,lemp->rule->lhs->name);
847 lemp->errorcnt++;
848 sp = lemp->rule->lhs;
849 }
850 }else{
851 sp = lemp->rule->lhs;
852 }
853
854 /* Make sure the start symbol doesn't occur on the right-hand side of
855 ** any rule. Report an error if it does. (YACC would generate a new
856 ** start symbol in this case.) */
857 for(rp=lemp->rule; rp; rp=rp->next){
858 int i;
859 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000860 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000861 ErrorMsg(lemp->filename,0,
862"The start symbol \"%s\" occurs on the \
863right-hand side of a rule. This will result in a parser which \
864does not work properly.",sp->name);
865 lemp->errorcnt++;
866 }
867 }
868 }
869
870 /* The basis configuration set for the first state
871 ** is all rules which have the start symbol as their
872 ** left-hand side */
873 for(rp=sp->rule; rp; rp=rp->nextlhs){
874 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000875 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000876 newcfp = Configlist_addbasis(rp,0);
877 SetAdd(newcfp->fws,0);
878 }
879
880 /* Compute the first state. All other states will be
881 ** computed automatically during the computation of the first one.
882 ** The returned pointer to the first state is not used. */
883 (void)getstate(lemp);
884 return;
885}
886
887/* Return a pointer to a state which is described by the configuration
888** list which has been built from calls to Configlist_add.
889*/
icculus9e44cf12010-02-14 17:14:22 +0000890PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
891PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000892{
893 struct config *cfp, *bp;
894 struct state *stp;
895
896 /* Extract the sorted basis of the new state. The basis was constructed
897 ** by prior calls to "Configlist_addbasis()". */
898 Configlist_sortbasis();
899 bp = Configlist_basis();
900
901 /* Get a state with the same basis */
902 stp = State_find(bp);
903 if( stp ){
904 /* A state with the same basis already exists! Copy all the follow-set
905 ** propagation links from the state under construction into the
906 ** preexisting state, then return a pointer to the preexisting state */
907 struct config *x, *y;
908 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
909 Plink_copy(&y->bplp,x->bplp);
910 Plink_delete(x->fplp);
911 x->fplp = x->bplp = 0;
912 }
913 cfp = Configlist_return();
914 Configlist_eat(cfp);
915 }else{
916 /* This really is a new state. Construct all the details */
917 Configlist_closure(lemp); /* Compute the configuration closure */
918 Configlist_sort(); /* Sort the configuration closure */
919 cfp = Configlist_return(); /* Get a pointer to the config list */
920 stp = State_new(); /* A new state structure */
921 MemoryCheck(stp);
922 stp->bp = bp; /* Remember the configuration basis */
923 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000924 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000925 stp->ap = 0; /* No actions, yet. */
926 State_insert(stp,stp->bp); /* Add to the state table */
927 buildshifts(lemp,stp); /* Recursively compute successor states */
928 }
929 return stp;
930}
931
drhfd405312005-11-06 04:06:59 +0000932/*
933** Return true if two symbols are the same.
934*/
icculus9e44cf12010-02-14 17:14:22 +0000935int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000936{
937 int i;
938 if( a==b ) return 1;
939 if( a->type!=MULTITERMINAL ) return 0;
940 if( b->type!=MULTITERMINAL ) return 0;
941 if( a->nsubsym!=b->nsubsym ) return 0;
942 for(i=0; i<a->nsubsym; i++){
943 if( a->subsym[i]!=b->subsym[i] ) return 0;
944 }
945 return 1;
946}
947
drh75897232000-05-29 14:26:00 +0000948/* Construct all successor states to the given state. A "successor"
949** state is any state which can be reached by a shift action.
950*/
icculus9e44cf12010-02-14 17:14:22 +0000951PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000952{
953 struct config *cfp; /* For looping thru the config closure of "stp" */
954 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000955 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000956 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
957 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
958 struct state *newstp; /* A pointer to a successor state */
959
960 /* Each configuration becomes complete after it contibutes to a successor
961 ** state. Initially, all configurations are incomplete */
962 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
963
964 /* Loop through all configurations of the state "stp" */
965 for(cfp=stp->cfp; cfp; cfp=cfp->next){
966 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
967 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
968 Configlist_reset(); /* Reset the new config set */
969 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
970
971 /* For every configuration in the state "stp" which has the symbol "sp"
972 ** following its dot, add the same configuration to the basis set under
973 ** construction but with the dot shifted one symbol to the right. */
974 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
975 if( bcfp->status==COMPLETE ) continue; /* Already used */
976 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
977 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000978 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000979 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000980 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
981 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000982 }
983
984 /* Get a pointer to the state described by the basis configuration set
985 ** constructed in the preceding loop */
986 newstp = getstate(lemp);
987
988 /* The state "newstp" is reached from the state "stp" by a shift action
989 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000990 if( sp->type==MULTITERMINAL ){
991 int i;
992 for(i=0; i<sp->nsubsym; i++){
993 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
994 }
995 }else{
996 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
997 }
drh75897232000-05-29 14:26:00 +0000998 }
999}
1000
1001/*
1002** Construct the propagation links
1003*/
icculus9e44cf12010-02-14 17:14:22 +00001004void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001005{
1006 int i;
1007 struct config *cfp, *other;
1008 struct state *stp;
1009 struct plink *plp;
1010
1011 /* Housekeeping detail:
1012 ** Add to every propagate link a pointer back to the state to
1013 ** which the link is attached. */
1014 for(i=0; i<lemp->nstate; i++){
1015 stp = lemp->sorted[i];
1016 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1017 cfp->stp = stp;
1018 }
1019 }
1020
1021 /* Convert all backlinks into forward links. Only the forward
1022 ** links are used in the follow-set computation. */
1023 for(i=0; i<lemp->nstate; i++){
1024 stp = lemp->sorted[i];
1025 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1026 for(plp=cfp->bplp; plp; plp=plp->next){
1027 other = plp->cfp;
1028 Plink_add(&other->fplp,cfp);
1029 }
1030 }
1031 }
1032}
1033
1034/* Compute all followsets.
1035**
1036** A followset is the set of all symbols which can come immediately
1037** after a configuration.
1038*/
icculus9e44cf12010-02-14 17:14:22 +00001039void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001040{
1041 int i;
1042 struct config *cfp;
1043 struct plink *plp;
1044 int progress;
1045 int change;
1046
1047 for(i=0; i<lemp->nstate; i++){
1048 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1049 cfp->status = INCOMPLETE;
1050 }
1051 }
1052
1053 do{
1054 progress = 0;
1055 for(i=0; i<lemp->nstate; i++){
1056 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1057 if( cfp->status==COMPLETE ) continue;
1058 for(plp=cfp->fplp; plp; plp=plp->next){
1059 change = SetUnion(plp->cfp->fws,cfp->fws);
1060 if( change ){
1061 plp->cfp->status = INCOMPLETE;
1062 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001063 }
1064 }
drh75897232000-05-29 14:26:00 +00001065 cfp->status = COMPLETE;
1066 }
1067 }
1068 }while( progress );
1069}
1070
drh3cb2f6e2012-01-09 14:19:05 +00001071static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001072
1073/* Compute the reduce actions, and resolve conflicts.
1074*/
icculus9e44cf12010-02-14 17:14:22 +00001075void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001076{
1077 int i,j;
1078 struct config *cfp;
1079 struct state *stp;
1080 struct symbol *sp;
1081 struct rule *rp;
1082
1083 /* Add all of the reduce actions
1084 ** A reduce action is added for each element of the followset of
1085 ** a configuration which has its dot at the extreme right.
1086 */
1087 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1088 stp = lemp->sorted[i];
1089 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1090 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1091 for(j=0; j<lemp->nterminal; j++){
1092 if( SetFind(cfp->fws,j) ){
1093 /* Add a reduce action to the state "stp" which will reduce by the
1094 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001095 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001096 }
drhf2f105d2012-08-20 15:53:54 +00001097 }
drh75897232000-05-29 14:26:00 +00001098 }
1099 }
1100 }
1101
1102 /* Add the accepting token */
1103 if( lemp->start ){
1104 sp = Symbol_find(lemp->start);
1105 if( sp==0 ) sp = lemp->rule->lhs;
1106 }else{
1107 sp = lemp->rule->lhs;
1108 }
1109 /* Add to the first state (which is always the starting state of the
1110 ** finite state machine) an action to ACCEPT if the lookahead is the
1111 ** start nonterminal. */
1112 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1113
1114 /* Resolve conflicts */
1115 for(i=0; i<lemp->nstate; i++){
1116 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001117 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001118 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001119 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001120 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001121 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1122 /* The two actions "ap" and "nap" have the same lookahead.
1123 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001124 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001125 }
1126 }
1127 }
1128
1129 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001130 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001131 for(i=0; i<lemp->nstate; i++){
1132 struct action *ap;
1133 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001134 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001135 }
1136 }
1137 for(rp=lemp->rule; rp; rp=rp->next){
1138 if( rp->canReduce ) continue;
1139 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1140 lemp->errorcnt++;
1141 }
1142}
1143
1144/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001145** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001146**
1147** NO LONGER TRUE:
1148** To resolve a conflict, first look to see if either action
1149** is on an error rule. In that case, take the action which
1150** is not associated with the error rule. If neither or both
1151** actions are associated with an error rule, then try to
1152** use precedence to resolve the conflict.
1153**
1154** If either action is a SHIFT, then it must be apx. This
1155** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1156*/
icculus9e44cf12010-02-14 17:14:22 +00001157static int resolve_conflict(
1158 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001159 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001160){
drh75897232000-05-29 14:26:00 +00001161 struct symbol *spx, *spy;
1162 int errcnt = 0;
1163 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001164 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001165 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001166 errcnt++;
1167 }
drh75897232000-05-29 14:26:00 +00001168 if( apx->type==SHIFT && apy->type==REDUCE ){
1169 spx = apx->sp;
1170 spy = apy->x.rp->precsym;
1171 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1172 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001173 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001174 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001175 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001176 apy->type = RD_RESOLVED;
1177 }else if( spx->prec<spy->prec ){
1178 apx->type = SH_RESOLVED;
1179 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1180 apy->type = RD_RESOLVED; /* associativity */
1181 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1182 apx->type = SH_RESOLVED;
1183 }else{
1184 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001185 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001186 }
1187 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1188 spx = apx->x.rp->precsym;
1189 spy = apy->x.rp->precsym;
1190 if( spx==0 || spy==0 || spx->prec<0 ||
1191 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001192 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001193 errcnt++;
1194 }else if( spx->prec>spy->prec ){
1195 apy->type = RD_RESOLVED;
1196 }else if( spx->prec<spy->prec ){
1197 apx->type = RD_RESOLVED;
1198 }
1199 }else{
drhb59499c2002-02-23 18:45:13 +00001200 assert(
1201 apx->type==SH_RESOLVED ||
1202 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001203 apx->type==SSCONFLICT ||
1204 apx->type==SRCONFLICT ||
1205 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001206 apy->type==SH_RESOLVED ||
1207 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001208 apy->type==SSCONFLICT ||
1209 apy->type==SRCONFLICT ||
1210 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001211 );
1212 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1213 ** REDUCEs on the list. If we reach this point it must be because
1214 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001215 }
1216 return errcnt;
1217}
1218/********************* From the file "configlist.c" *************************/
1219/*
1220** Routines to processing a configuration list and building a state
1221** in the LEMON parser generator.
1222*/
1223
1224static struct config *freelist = 0; /* List of free configurations */
1225static struct config *current = 0; /* Top of list of configurations */
1226static struct config **currentend = 0; /* Last on list of configs */
1227static struct config *basis = 0; /* Top of list of basis configs */
1228static struct config **basisend = 0; /* End of list of basis configs */
1229
1230/* Return a pointer to a new configuration */
1231PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001232 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001233 if( freelist==0 ){
1234 int i;
1235 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001236 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001237 if( freelist==0 ){
1238 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1239 exit(1);
1240 }
1241 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1242 freelist[amt-1].next = 0;
1243 }
icculus9e44cf12010-02-14 17:14:22 +00001244 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001245 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001246 return newcfg;
drh75897232000-05-29 14:26:00 +00001247}
1248
1249/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001250PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001251{
1252 old->next = freelist;
1253 freelist = old;
1254}
1255
1256/* Initialized the configuration list builder */
1257void Configlist_init(){
1258 current = 0;
1259 currentend = &current;
1260 basis = 0;
1261 basisend = &basis;
1262 Configtable_init();
1263 return;
1264}
1265
1266/* Initialized the configuration list builder */
1267void Configlist_reset(){
1268 current = 0;
1269 currentend = &current;
1270 basis = 0;
1271 basisend = &basis;
1272 Configtable_clear(0);
1273 return;
1274}
1275
1276/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001277struct config *Configlist_add(
1278 struct rule *rp, /* The rule */
1279 int dot /* Index into the RHS of the rule where the dot goes */
1280){
drh75897232000-05-29 14:26:00 +00001281 struct config *cfp, model;
1282
1283 assert( currentend!=0 );
1284 model.rp = rp;
1285 model.dot = dot;
1286 cfp = Configtable_find(&model);
1287 if( cfp==0 ){
1288 cfp = newconfig();
1289 cfp->rp = rp;
1290 cfp->dot = dot;
1291 cfp->fws = SetNew();
1292 cfp->stp = 0;
1293 cfp->fplp = cfp->bplp = 0;
1294 cfp->next = 0;
1295 cfp->bp = 0;
1296 *currentend = cfp;
1297 currentend = &cfp->next;
1298 Configtable_insert(cfp);
1299 }
1300 return cfp;
1301}
1302
1303/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001304struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001305{
1306 struct config *cfp, model;
1307
1308 assert( basisend!=0 );
1309 assert( currentend!=0 );
1310 model.rp = rp;
1311 model.dot = dot;
1312 cfp = Configtable_find(&model);
1313 if( cfp==0 ){
1314 cfp = newconfig();
1315 cfp->rp = rp;
1316 cfp->dot = dot;
1317 cfp->fws = SetNew();
1318 cfp->stp = 0;
1319 cfp->fplp = cfp->bplp = 0;
1320 cfp->next = 0;
1321 cfp->bp = 0;
1322 *currentend = cfp;
1323 currentend = &cfp->next;
1324 *basisend = cfp;
1325 basisend = &cfp->bp;
1326 Configtable_insert(cfp);
1327 }
1328 return cfp;
1329}
1330
1331/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001332void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001333{
1334 struct config *cfp, *newcfp;
1335 struct rule *rp, *newrp;
1336 struct symbol *sp, *xsp;
1337 int i, dot;
1338
1339 assert( currentend!=0 );
1340 for(cfp=current; cfp; cfp=cfp->next){
1341 rp = cfp->rp;
1342 dot = cfp->dot;
1343 if( dot>=rp->nrhs ) continue;
1344 sp = rp->rhs[dot];
1345 if( sp->type==NONTERMINAL ){
1346 if( sp->rule==0 && sp!=lemp->errsym ){
1347 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1348 sp->name);
1349 lemp->errorcnt++;
1350 }
1351 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1352 newcfp = Configlist_add(newrp,0);
1353 for(i=dot+1; i<rp->nrhs; i++){
1354 xsp = rp->rhs[i];
1355 if( xsp->type==TERMINAL ){
1356 SetAdd(newcfp->fws,xsp->index);
1357 break;
drhfd405312005-11-06 04:06:59 +00001358 }else if( xsp->type==MULTITERMINAL ){
1359 int k;
1360 for(k=0; k<xsp->nsubsym; k++){
1361 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1362 }
1363 break;
drhf2f105d2012-08-20 15:53:54 +00001364 }else{
drh75897232000-05-29 14:26:00 +00001365 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001366 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001367 }
1368 }
drh75897232000-05-29 14:26:00 +00001369 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1370 }
1371 }
1372 }
1373 return;
1374}
1375
1376/* Sort the configuration list */
1377void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001378 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001379 currentend = 0;
1380 return;
1381}
1382
1383/* Sort the basis configuration list */
1384void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001385 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001386 basisend = 0;
1387 return;
1388}
1389
1390/* Return a pointer to the head of the configuration list and
1391** reset the list */
1392struct config *Configlist_return(){
1393 struct config *old;
1394 old = current;
1395 current = 0;
1396 currentend = 0;
1397 return old;
1398}
1399
1400/* Return a pointer to the head of the configuration list and
1401** reset the list */
1402struct config *Configlist_basis(){
1403 struct config *old;
1404 old = basis;
1405 basis = 0;
1406 basisend = 0;
1407 return old;
1408}
1409
1410/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001411void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001412{
1413 struct config *nextcfp;
1414 for(; cfp; cfp=nextcfp){
1415 nextcfp = cfp->next;
1416 assert( cfp->fplp==0 );
1417 assert( cfp->bplp==0 );
1418 if( cfp->fws ) SetFree(cfp->fws);
1419 deleteconfig(cfp);
1420 }
1421 return;
1422}
1423/***************** From the file "error.c" *********************************/
1424/*
1425** Code for printing error message.
1426*/
1427
drhf9a2e7b2003-04-15 01:49:48 +00001428void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001429 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001430 fprintf(stderr, "%s:%d: ", filename, lineno);
1431 va_start(ap, format);
1432 vfprintf(stderr,format,ap);
1433 va_end(ap);
1434 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001435}
1436/**************** From the file "main.c" ************************************/
1437/*
1438** Main program file for the LEMON parser generator.
1439*/
1440
1441/* Report an out-of-memory condition and abort. This function
1442** is used mostly by the "MemoryCheck" macro in struct.h
1443*/
1444void memory_error(){
1445 fprintf(stderr,"Out of memory. Aborting...\n");
1446 exit(1);
1447}
1448
drh6d08b4d2004-07-20 12:45:22 +00001449static int nDefine = 0; /* Number of -D options on the command line */
1450static char **azDefine = 0; /* Name of the -D macros */
1451
1452/* This routine is called with the argument to each -D command-line option.
1453** Add the macro defined to the azDefine array.
1454*/
1455static void handle_D_option(char *z){
1456 char **paz;
1457 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001458 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001459 if( azDefine==0 ){
1460 fprintf(stderr,"out of memory\n");
1461 exit(1);
1462 }
1463 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001464 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001465 if( *paz==0 ){
1466 fprintf(stderr,"out of memory\n");
1467 exit(1);
1468 }
drh898799f2014-01-10 23:21:00 +00001469 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001470 for(z=*paz; *z && *z!='='; z++){}
1471 *z = 0;
1472}
1473
icculus3e143bd2010-02-14 00:48:49 +00001474static char *user_templatename = NULL;
1475static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001476 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001477 if( user_templatename==0 ){
1478 memory_error();
1479 }
drh898799f2014-01-10 23:21:00 +00001480 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001481}
drh75897232000-05-29 14:26:00 +00001482
1483/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001484int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001485{
1486 static int version = 0;
1487 static int rpflag = 0;
1488 static int basisflag = 0;
1489 static int compress = 0;
1490 static int quiet = 0;
1491 static int statistics = 0;
1492 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001493 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001494 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001495 static struct s_options options[] = {
1496 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1497 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001498 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001499 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001500 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001501 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001502 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1503 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001504 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001505 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1506 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001507 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001508 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001509 {OPT_FLAG, "s", (char*)&statistics,
1510 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001511 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001512 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1513 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001514 {OPT_FLAG,0,0,0}
1515 };
1516 int i;
icculus42585cf2010-02-14 05:19:56 +00001517 int exitcode;
drh75897232000-05-29 14:26:00 +00001518 struct lemon lem;
1519
drhb0c86772000-06-02 23:21:26 +00001520 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001521 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001522 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001523 exit(0);
1524 }
drhb0c86772000-06-02 23:21:26 +00001525 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001526 fprintf(stderr,"Exactly one filename argument is required.\n");
1527 exit(1);
1528 }
drh954f6b42006-06-13 13:27:46 +00001529 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001530 lem.errorcnt = 0;
1531
1532 /* Initialize the machine */
1533 Strsafe_init();
1534 Symbol_init();
1535 State_init();
1536 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001537 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001538 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001539 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001540 Symbol_new("$");
1541 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001542 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001543
1544 /* Parse the input file */
1545 Parse(&lem);
1546 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001547 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001548 fprintf(stderr,"Empty grammar.\n");
1549 exit(1);
1550 }
1551
1552 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001553 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001554 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001555 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001556 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1557 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1558 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1559 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1560 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1561 lem.nsymbol = i - 1;
drh75897232000-05-29 14:26:00 +00001562 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1563 lem.nterminal = i;
1564
1565 /* Generate a reprint of the grammar, if requested on the command line */
1566 if( rpflag ){
1567 Reprint(&lem);
1568 }else{
1569 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001570 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001571
1572 /* Find the precedence for every production rule (that has one) */
1573 FindRulePrecedences(&lem);
1574
1575 /* Compute the lambda-nonterminals and the first-sets for every
1576 ** nonterminal */
1577 FindFirstSets(&lem);
1578
1579 /* Compute all LR(0) states. Also record follow-set propagation
1580 ** links so that the follow-set can be computed later */
1581 lem.nstate = 0;
1582 FindStates(&lem);
1583 lem.sorted = State_arrayof();
1584
1585 /* Tie up loose ends on the propagation links */
1586 FindLinks(&lem);
1587
1588 /* Compute the follow set of every reducible configuration */
1589 FindFollowSets(&lem);
1590
1591 /* Compute the action tables */
1592 FindActions(&lem);
1593
1594 /* Compress the action tables */
1595 if( compress==0 ) CompressTables(&lem);
1596
drhada354d2005-11-05 15:03:59 +00001597 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001598 ** occur at the end. This is an optimization that helps make the
1599 ** generated parser tables smaller. */
1600 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001601
drh75897232000-05-29 14:26:00 +00001602 /* Generate a report of the parser generated. (the "y.output" file) */
1603 if( !quiet ) ReportOutput(&lem);
1604
1605 /* Generate the source code for the parser */
1606 ReportTable(&lem, mhflag);
1607
1608 /* Produce a header file for use by the scanner. (This step is
1609 ** omitted if the "-m" option is used because makeheaders will
1610 ** generate the file for us.) */
1611 if( !mhflag ) ReportHeader(&lem);
1612 }
1613 if( statistics ){
1614 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1615 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1616 printf(" %d states, %d parser table entries, %d conflicts\n",
1617 lem.nstate, lem.tablesize, lem.nconflict);
1618 }
icculus8e158022010-02-16 16:09:03 +00001619 if( lem.nconflict > 0 ){
1620 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001621 }
1622
1623 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001624 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001625 exit(exitcode);
1626 return (exitcode);
drh75897232000-05-29 14:26:00 +00001627}
1628/******************** From the file "msort.c" *******************************/
1629/*
1630** A generic merge-sort program.
1631**
1632** USAGE:
1633** Let "ptr" be a pointer to some structure which is at the head of
1634** a null-terminated list. Then to sort the list call:
1635**
1636** ptr = msort(ptr,&(ptr->next),cmpfnc);
1637**
1638** In the above, "cmpfnc" is a pointer to a function which compares
1639** two instances of the structure and returns an integer, as in
1640** strcmp. The second argument is a pointer to the pointer to the
1641** second element of the linked list. This address is used to compute
1642** the offset to the "next" field within the structure. The offset to
1643** the "next" field must be constant for all structures in the list.
1644**
1645** The function returns a new pointer which is the head of the list
1646** after sorting.
1647**
1648** ALGORITHM:
1649** Merge-sort.
1650*/
1651
1652/*
1653** Return a pointer to the next structure in the linked list.
1654*/
drhd25d6922012-04-18 09:59:56 +00001655#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001656
1657/*
1658** Inputs:
1659** a: A sorted, null-terminated linked list. (May be null).
1660** b: A sorted, null-terminated linked list. (May be null).
1661** cmp: A pointer to the comparison function.
1662** offset: Offset in the structure to the "next" field.
1663**
1664** Return Value:
1665** A pointer to the head of a sorted list containing the elements
1666** of both a and b.
1667**
1668** Side effects:
1669** The "next" pointers for elements in the lists a and b are
1670** changed.
1671*/
drhe9278182007-07-18 18:16:29 +00001672static char *merge(
1673 char *a,
1674 char *b,
1675 int (*cmp)(const char*,const char*),
1676 int offset
1677){
drh75897232000-05-29 14:26:00 +00001678 char *ptr, *head;
1679
1680 if( a==0 ){
1681 head = b;
1682 }else if( b==0 ){
1683 head = a;
1684 }else{
drhe594bc32009-11-03 13:02:25 +00001685 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001686 ptr = a;
1687 a = NEXT(a);
1688 }else{
1689 ptr = b;
1690 b = NEXT(b);
1691 }
1692 head = ptr;
1693 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001694 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001695 NEXT(ptr) = a;
1696 ptr = a;
1697 a = NEXT(a);
1698 }else{
1699 NEXT(ptr) = b;
1700 ptr = b;
1701 b = NEXT(b);
1702 }
1703 }
1704 if( a ) NEXT(ptr) = a;
1705 else NEXT(ptr) = b;
1706 }
1707 return head;
1708}
1709
1710/*
1711** Inputs:
1712** list: Pointer to a singly-linked list of structures.
1713** next: Pointer to pointer to the second element of the list.
1714** cmp: A comparison function.
1715**
1716** Return Value:
1717** A pointer to the head of a sorted list containing the elements
1718** orginally in list.
1719**
1720** Side effects:
1721** The "next" pointers for elements in list are changed.
1722*/
1723#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001724static char *msort(
1725 char *list,
1726 char **next,
1727 int (*cmp)(const char*,const char*)
1728){
drhba99af52001-10-25 20:37:16 +00001729 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001730 char *ep;
1731 char *set[LISTSIZE];
1732 int i;
drh1cc0d112015-03-31 15:15:48 +00001733 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001734 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1735 while( list ){
1736 ep = list;
1737 list = NEXT(list);
1738 NEXT(ep) = 0;
1739 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1740 ep = merge(ep,set[i],cmp,offset);
1741 set[i] = 0;
1742 }
1743 set[i] = ep;
1744 }
1745 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001746 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001747 return ep;
1748}
1749/************************ From the file "option.c" **************************/
1750static char **argv;
1751static struct s_options *op;
1752static FILE *errstream;
1753
1754#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1755
1756/*
1757** Print the command line with a carrot pointing to the k-th character
1758** of the n-th field.
1759*/
icculus9e44cf12010-02-14 17:14:22 +00001760static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001761{
1762 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001763 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001764 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001765 for(i=1; i<n && argv[i]; i++){
1766 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001767 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001768 }
1769 spcnt += k;
1770 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1771 if( spcnt<20 ){
1772 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1773 }else{
1774 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1775 }
1776}
1777
1778/*
1779** Return the index of the N-th non-switch argument. Return -1
1780** if N is out of range.
1781*/
icculus9e44cf12010-02-14 17:14:22 +00001782static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001783{
1784 int i;
1785 int dashdash = 0;
1786 if( argv!=0 && *argv!=0 ){
1787 for(i=1; argv[i]; i++){
1788 if( dashdash || !ISOPT(argv[i]) ){
1789 if( n==0 ) return i;
1790 n--;
1791 }
1792 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1793 }
1794 }
1795 return -1;
1796}
1797
1798static char emsg[] = "Command line syntax error: ";
1799
1800/*
1801** Process a flag command line argument.
1802*/
icculus9e44cf12010-02-14 17:14:22 +00001803static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001804{
1805 int v;
1806 int errcnt = 0;
1807 int j;
1808 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001809 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001810 }
1811 v = argv[i][0]=='-' ? 1 : 0;
1812 if( op[j].label==0 ){
1813 if( err ){
1814 fprintf(err,"%sundefined option.\n",emsg);
1815 errline(i,1,err);
1816 }
1817 errcnt++;
drh0325d392015-01-01 19:11:22 +00001818 }else if( op[j].arg==0 ){
1819 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001820 }else if( op[j].type==OPT_FLAG ){
1821 *((int*)op[j].arg) = v;
1822 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001823 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001824 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001825 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001826 }else{
1827 if( err ){
1828 fprintf(err,"%smissing argument on switch.\n",emsg);
1829 errline(i,1,err);
1830 }
1831 errcnt++;
1832 }
1833 return errcnt;
1834}
1835
1836/*
1837** Process a command line switch which has an argument.
1838*/
icculus9e44cf12010-02-14 17:14:22 +00001839static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001840{
1841 int lv = 0;
1842 double dv = 0.0;
1843 char *sv = 0, *end;
1844 char *cp;
1845 int j;
1846 int errcnt = 0;
1847 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001848 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001849 *cp = 0;
1850 for(j=0; op[j].label; j++){
1851 if( strcmp(argv[i],op[j].label)==0 ) break;
1852 }
1853 *cp = '=';
1854 if( op[j].label==0 ){
1855 if( err ){
1856 fprintf(err,"%sundefined option.\n",emsg);
1857 errline(i,0,err);
1858 }
1859 errcnt++;
1860 }else{
1861 cp++;
1862 switch( op[j].type ){
1863 case OPT_FLAG:
1864 case OPT_FFLAG:
1865 if( err ){
1866 fprintf(err,"%soption requires an argument.\n",emsg);
1867 errline(i,0,err);
1868 }
1869 errcnt++;
1870 break;
1871 case OPT_DBL:
1872 case OPT_FDBL:
1873 dv = strtod(cp,&end);
1874 if( *end ){
1875 if( err ){
1876 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001877 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001878 }
1879 errcnt++;
1880 }
1881 break;
1882 case OPT_INT:
1883 case OPT_FINT:
1884 lv = strtol(cp,&end,0);
1885 if( *end ){
1886 if( err ){
1887 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001888 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001889 }
1890 errcnt++;
1891 }
1892 break;
1893 case OPT_STR:
1894 case OPT_FSTR:
1895 sv = cp;
1896 break;
1897 }
1898 switch( op[j].type ){
1899 case OPT_FLAG:
1900 case OPT_FFLAG:
1901 break;
1902 case OPT_DBL:
1903 *(double*)(op[j].arg) = dv;
1904 break;
1905 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001906 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001907 break;
1908 case OPT_INT:
1909 *(int*)(op[j].arg) = lv;
1910 break;
1911 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001912 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001913 break;
1914 case OPT_STR:
1915 *(char**)(op[j].arg) = sv;
1916 break;
1917 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001918 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001919 break;
1920 }
1921 }
1922 return errcnt;
1923}
1924
icculus9e44cf12010-02-14 17:14:22 +00001925int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001926{
1927 int errcnt = 0;
1928 argv = a;
1929 op = o;
1930 errstream = err;
1931 if( argv && *argv && op ){
1932 int i;
1933 for(i=1; argv[i]; i++){
1934 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1935 errcnt += handleflags(i,err);
1936 }else if( strchr(argv[i],'=') ){
1937 errcnt += handleswitch(i,err);
1938 }
1939 }
1940 }
1941 if( errcnt>0 ){
1942 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001943 OptPrint();
drh75897232000-05-29 14:26:00 +00001944 exit(1);
1945 }
1946 return 0;
1947}
1948
drhb0c86772000-06-02 23:21:26 +00001949int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001950 int cnt = 0;
1951 int dashdash = 0;
1952 int i;
1953 if( argv!=0 && argv[0]!=0 ){
1954 for(i=1; argv[i]; i++){
1955 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1956 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1957 }
1958 }
1959 return cnt;
1960}
1961
icculus9e44cf12010-02-14 17:14:22 +00001962char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001963{
1964 int i;
1965 i = argindex(n);
1966 return i>=0 ? argv[i] : 0;
1967}
1968
icculus9e44cf12010-02-14 17:14:22 +00001969void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001970{
1971 int i;
1972 i = argindex(n);
1973 if( i>=0 ) errline(i,0,errstream);
1974}
1975
drhb0c86772000-06-02 23:21:26 +00001976void OptPrint(){
drh75897232000-05-29 14:26:00 +00001977 int i;
1978 int max, len;
1979 max = 0;
1980 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001981 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001982 switch( op[i].type ){
1983 case OPT_FLAG:
1984 case OPT_FFLAG:
1985 break;
1986 case OPT_INT:
1987 case OPT_FINT:
1988 len += 9; /* length of "<integer>" */
1989 break;
1990 case OPT_DBL:
1991 case OPT_FDBL:
1992 len += 6; /* length of "<real>" */
1993 break;
1994 case OPT_STR:
1995 case OPT_FSTR:
1996 len += 8; /* length of "<string>" */
1997 break;
1998 }
1999 if( len>max ) max = len;
2000 }
2001 for(i=0; op[i].label; i++){
2002 switch( op[i].type ){
2003 case OPT_FLAG:
2004 case OPT_FFLAG:
2005 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2006 break;
2007 case OPT_INT:
2008 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002009 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002010 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002011 break;
2012 case OPT_DBL:
2013 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002014 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002015 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002016 break;
2017 case OPT_STR:
2018 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002019 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002020 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002021 break;
2022 }
2023 }
2024}
2025/*********************** From the file "parse.c" ****************************/
2026/*
2027** Input file parser for the LEMON parser generator.
2028*/
2029
2030/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002031enum e_state {
2032 INITIALIZE,
2033 WAITING_FOR_DECL_OR_RULE,
2034 WAITING_FOR_DECL_KEYWORD,
2035 WAITING_FOR_DECL_ARG,
2036 WAITING_FOR_PRECEDENCE_SYMBOL,
2037 WAITING_FOR_ARROW,
2038 IN_RHS,
2039 LHS_ALIAS_1,
2040 LHS_ALIAS_2,
2041 LHS_ALIAS_3,
2042 RHS_ALIAS_1,
2043 RHS_ALIAS_2,
2044 PRECEDENCE_MARK_1,
2045 PRECEDENCE_MARK_2,
2046 RESYNC_AFTER_RULE_ERROR,
2047 RESYNC_AFTER_DECL_ERROR,
2048 WAITING_FOR_DESTRUCTOR_SYMBOL,
2049 WAITING_FOR_DATATYPE_SYMBOL,
2050 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002051 WAITING_FOR_WILDCARD_ID,
2052 WAITING_FOR_CLASS_ID,
2053 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002054};
drh75897232000-05-29 14:26:00 +00002055struct pstate {
2056 char *filename; /* Name of the input file */
2057 int tokenlineno; /* Linenumber at which current token starts */
2058 int errorcnt; /* Number of errors so far */
2059 char *tokenstart; /* Text of current token */
2060 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002061 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002062 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002063 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002064 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002065 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002066 int nrhs; /* Number of right-hand side symbols seen */
2067 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002068 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002069 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002070 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002071 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002072 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002073 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002074 enum e_assoc declassoc; /* Assign this association to decl arguments */
2075 int preccounter; /* Assign this precedence to decl arguments */
2076 struct rule *firstrule; /* Pointer to first rule in the grammar */
2077 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2078};
2079
2080/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002081static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002082{
icculus9e44cf12010-02-14 17:14:22 +00002083 const char *x;
drh75897232000-05-29 14:26:00 +00002084 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2085#if 0
2086 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2087 x,psp->state);
2088#endif
2089 switch( psp->state ){
2090 case INITIALIZE:
2091 psp->prevrule = 0;
2092 psp->preccounter = 0;
2093 psp->firstrule = psp->lastrule = 0;
2094 psp->gp->nrule = 0;
2095 /* Fall thru to next case */
2096 case WAITING_FOR_DECL_OR_RULE:
2097 if( x[0]=='%' ){
2098 psp->state = WAITING_FOR_DECL_KEYWORD;
2099 }else if( islower(x[0]) ){
2100 psp->lhs = Symbol_new(x);
2101 psp->nrhs = 0;
2102 psp->lhsalias = 0;
2103 psp->state = WAITING_FOR_ARROW;
2104 }else if( x[0]=='{' ){
2105 if( psp->prevrule==0 ){
2106 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002107"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002108fragment which begins on this line.");
2109 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002110 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002111 ErrorMsg(psp->filename,psp->tokenlineno,
2112"Code fragment beginning on this line is not the first \
2113to follow the previous rule.");
2114 psp->errorcnt++;
2115 }else{
2116 psp->prevrule->line = psp->tokenlineno;
2117 psp->prevrule->code = &x[1];
drhf2f105d2012-08-20 15:53:54 +00002118 }
drh75897232000-05-29 14:26:00 +00002119 }else if( x[0]=='[' ){
2120 psp->state = PRECEDENCE_MARK_1;
2121 }else{
2122 ErrorMsg(psp->filename,psp->tokenlineno,
2123 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2124 x);
2125 psp->errorcnt++;
2126 }
2127 break;
2128 case PRECEDENCE_MARK_1:
2129 if( !isupper(x[0]) ){
2130 ErrorMsg(psp->filename,psp->tokenlineno,
2131 "The precedence symbol must be a terminal.");
2132 psp->errorcnt++;
2133 }else if( psp->prevrule==0 ){
2134 ErrorMsg(psp->filename,psp->tokenlineno,
2135 "There is no prior rule to assign precedence \"[%s]\".",x);
2136 psp->errorcnt++;
2137 }else if( psp->prevrule->precsym!=0 ){
2138 ErrorMsg(psp->filename,psp->tokenlineno,
2139"Precedence mark on this line is not the first \
2140to follow the previous rule.");
2141 psp->errorcnt++;
2142 }else{
2143 psp->prevrule->precsym = Symbol_new(x);
2144 }
2145 psp->state = PRECEDENCE_MARK_2;
2146 break;
2147 case PRECEDENCE_MARK_2:
2148 if( x[0]!=']' ){
2149 ErrorMsg(psp->filename,psp->tokenlineno,
2150 "Missing \"]\" on precedence mark.");
2151 psp->errorcnt++;
2152 }
2153 psp->state = WAITING_FOR_DECL_OR_RULE;
2154 break;
2155 case WAITING_FOR_ARROW:
2156 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2157 psp->state = IN_RHS;
2158 }else if( x[0]=='(' ){
2159 psp->state = LHS_ALIAS_1;
2160 }else{
2161 ErrorMsg(psp->filename,psp->tokenlineno,
2162 "Expected to see a \":\" following the LHS symbol \"%s\".",
2163 psp->lhs->name);
2164 psp->errorcnt++;
2165 psp->state = RESYNC_AFTER_RULE_ERROR;
2166 }
2167 break;
2168 case LHS_ALIAS_1:
2169 if( isalpha(x[0]) ){
2170 psp->lhsalias = x;
2171 psp->state = LHS_ALIAS_2;
2172 }else{
2173 ErrorMsg(psp->filename,psp->tokenlineno,
2174 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2175 x,psp->lhs->name);
2176 psp->errorcnt++;
2177 psp->state = RESYNC_AFTER_RULE_ERROR;
2178 }
2179 break;
2180 case LHS_ALIAS_2:
2181 if( x[0]==')' ){
2182 psp->state = LHS_ALIAS_3;
2183 }else{
2184 ErrorMsg(psp->filename,psp->tokenlineno,
2185 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2186 psp->errorcnt++;
2187 psp->state = RESYNC_AFTER_RULE_ERROR;
2188 }
2189 break;
2190 case LHS_ALIAS_3:
2191 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2192 psp->state = IN_RHS;
2193 }else{
2194 ErrorMsg(psp->filename,psp->tokenlineno,
2195 "Missing \"->\" following: \"%s(%s)\".",
2196 psp->lhs->name,psp->lhsalias);
2197 psp->errorcnt++;
2198 psp->state = RESYNC_AFTER_RULE_ERROR;
2199 }
2200 break;
2201 case IN_RHS:
2202 if( x[0]=='.' ){
2203 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002204 rp = (struct rule *)calloc( sizeof(struct rule) +
2205 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002206 if( rp==0 ){
2207 ErrorMsg(psp->filename,psp->tokenlineno,
2208 "Can't allocate enough memory for this rule.");
2209 psp->errorcnt++;
2210 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002211 }else{
drh75897232000-05-29 14:26:00 +00002212 int i;
2213 rp->ruleline = psp->tokenlineno;
2214 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002215 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002216 for(i=0; i<psp->nrhs; i++){
2217 rp->rhs[i] = psp->rhs[i];
2218 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002219 }
drh75897232000-05-29 14:26:00 +00002220 rp->lhs = psp->lhs;
2221 rp->lhsalias = psp->lhsalias;
2222 rp->nrhs = psp->nrhs;
2223 rp->code = 0;
2224 rp->precsym = 0;
2225 rp->index = psp->gp->nrule++;
2226 rp->nextlhs = rp->lhs->rule;
2227 rp->lhs->rule = rp;
2228 rp->next = 0;
2229 if( psp->firstrule==0 ){
2230 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002231 }else{
drh75897232000-05-29 14:26:00 +00002232 psp->lastrule->next = rp;
2233 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002234 }
drh75897232000-05-29 14:26:00 +00002235 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002236 }
drh75897232000-05-29 14:26:00 +00002237 psp->state = WAITING_FOR_DECL_OR_RULE;
2238 }else if( isalpha(x[0]) ){
2239 if( psp->nrhs>=MAXRHS ){
2240 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002241 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002242 x);
2243 psp->errorcnt++;
2244 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002245 }else{
drh75897232000-05-29 14:26:00 +00002246 psp->rhs[psp->nrhs] = Symbol_new(x);
2247 psp->alias[psp->nrhs] = 0;
2248 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002249 }
drhfd405312005-11-06 04:06:59 +00002250 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2251 struct symbol *msp = psp->rhs[psp->nrhs-1];
2252 if( msp->type!=MULTITERMINAL ){
2253 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002254 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002255 memset(msp, 0, sizeof(*msp));
2256 msp->type = MULTITERMINAL;
2257 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002258 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002259 msp->subsym[0] = origsp;
2260 msp->name = origsp->name;
2261 psp->rhs[psp->nrhs-1] = msp;
2262 }
2263 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002264 msp->subsym = (struct symbol **) realloc(msp->subsym,
2265 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002266 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2267 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2268 ErrorMsg(psp->filename,psp->tokenlineno,
2269 "Cannot form a compound containing a non-terminal");
2270 psp->errorcnt++;
2271 }
drh75897232000-05-29 14:26:00 +00002272 }else if( x[0]=='(' && psp->nrhs>0 ){
2273 psp->state = RHS_ALIAS_1;
2274 }else{
2275 ErrorMsg(psp->filename,psp->tokenlineno,
2276 "Illegal character on RHS of rule: \"%s\".",x);
2277 psp->errorcnt++;
2278 psp->state = RESYNC_AFTER_RULE_ERROR;
2279 }
2280 break;
2281 case RHS_ALIAS_1:
2282 if( isalpha(x[0]) ){
2283 psp->alias[psp->nrhs-1] = x;
2284 psp->state = RHS_ALIAS_2;
2285 }else{
2286 ErrorMsg(psp->filename,psp->tokenlineno,
2287 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2288 x,psp->rhs[psp->nrhs-1]->name);
2289 psp->errorcnt++;
2290 psp->state = RESYNC_AFTER_RULE_ERROR;
2291 }
2292 break;
2293 case RHS_ALIAS_2:
2294 if( x[0]==')' ){
2295 psp->state = IN_RHS;
2296 }else{
2297 ErrorMsg(psp->filename,psp->tokenlineno,
2298 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2299 psp->errorcnt++;
2300 psp->state = RESYNC_AFTER_RULE_ERROR;
2301 }
2302 break;
2303 case WAITING_FOR_DECL_KEYWORD:
2304 if( isalpha(x[0]) ){
2305 psp->declkeyword = x;
2306 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002307 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002308 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002309 psp->state = WAITING_FOR_DECL_ARG;
2310 if( strcmp(x,"name")==0 ){
2311 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002312 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002313 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002314 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002315 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002316 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002317 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002318 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002319 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002320 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002321 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002322 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002323 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002324 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002325 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002326 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002327 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002328 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002329 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002330 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002331 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002332 }else if( strcmp(x,"extra_argument")==0 ){
2333 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002334 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002335 }else if( strcmp(x,"token_type")==0 ){
2336 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002337 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002338 }else if( strcmp(x,"default_type")==0 ){
2339 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002340 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002341 }else if( strcmp(x,"stack_size")==0 ){
2342 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002343 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002344 }else if( strcmp(x,"start_symbol")==0 ){
2345 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002346 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002347 }else if( strcmp(x,"left")==0 ){
2348 psp->preccounter++;
2349 psp->declassoc = LEFT;
2350 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2351 }else if( strcmp(x,"right")==0 ){
2352 psp->preccounter++;
2353 psp->declassoc = RIGHT;
2354 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2355 }else if( strcmp(x,"nonassoc")==0 ){
2356 psp->preccounter++;
2357 psp->declassoc = NONE;
2358 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002359 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002360 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002361 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002362 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002363 }else if( strcmp(x,"fallback")==0 ){
2364 psp->fallback = 0;
2365 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002366 }else if( strcmp(x,"wildcard")==0 ){
2367 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002368 }else if( strcmp(x,"token_class")==0 ){
2369 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002370 }else{
2371 ErrorMsg(psp->filename,psp->tokenlineno,
2372 "Unknown declaration keyword: \"%%%s\".",x);
2373 psp->errorcnt++;
2374 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002375 }
drh75897232000-05-29 14:26:00 +00002376 }else{
2377 ErrorMsg(psp->filename,psp->tokenlineno,
2378 "Illegal declaration keyword: \"%s\".",x);
2379 psp->errorcnt++;
2380 psp->state = RESYNC_AFTER_DECL_ERROR;
2381 }
2382 break;
2383 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2384 if( !isalpha(x[0]) ){
2385 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002386 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002387 psp->errorcnt++;
2388 psp->state = RESYNC_AFTER_DECL_ERROR;
2389 }else{
icculusd286fa62010-03-03 17:06:32 +00002390 struct symbol *sp = Symbol_new(x);
2391 psp->declargslot = &sp->destructor;
2392 psp->decllinenoslot = &sp->destLineno;
2393 psp->insertLineMacro = 1;
2394 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002395 }
2396 break;
2397 case WAITING_FOR_DATATYPE_SYMBOL:
2398 if( !isalpha(x[0]) ){
2399 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002400 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002401 psp->errorcnt++;
2402 psp->state = RESYNC_AFTER_DECL_ERROR;
2403 }else{
icculus866bf1e2010-02-17 20:31:32 +00002404 struct symbol *sp = Symbol_find(x);
2405 if((sp) && (sp->datatype)){
2406 ErrorMsg(psp->filename,psp->tokenlineno,
2407 "Symbol %%type \"%s\" already defined", x);
2408 psp->errorcnt++;
2409 psp->state = RESYNC_AFTER_DECL_ERROR;
2410 }else{
2411 if (!sp){
2412 sp = Symbol_new(x);
2413 }
2414 psp->declargslot = &sp->datatype;
2415 psp->insertLineMacro = 0;
2416 psp->state = WAITING_FOR_DECL_ARG;
2417 }
drh75897232000-05-29 14:26:00 +00002418 }
2419 break;
2420 case WAITING_FOR_PRECEDENCE_SYMBOL:
2421 if( x[0]=='.' ){
2422 psp->state = WAITING_FOR_DECL_OR_RULE;
2423 }else if( isupper(x[0]) ){
2424 struct symbol *sp;
2425 sp = Symbol_new(x);
2426 if( sp->prec>=0 ){
2427 ErrorMsg(psp->filename,psp->tokenlineno,
2428 "Symbol \"%s\" has already be given a precedence.",x);
2429 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002430 }else{
drh75897232000-05-29 14:26:00 +00002431 sp->prec = psp->preccounter;
2432 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002433 }
drh75897232000-05-29 14:26:00 +00002434 }else{
2435 ErrorMsg(psp->filename,psp->tokenlineno,
2436 "Can't assign a precedence to \"%s\".",x);
2437 psp->errorcnt++;
2438 }
2439 break;
2440 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002441 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002442 const char *zOld, *zNew;
2443 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002444 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002445 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002446 char zLine[50];
2447 zNew = x;
2448 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002449 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002450 if( *psp->declargslot ){
2451 zOld = *psp->declargslot;
2452 }else{
2453 zOld = "";
2454 }
drh87cf1372008-08-13 20:09:06 +00002455 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002456 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002457 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002458 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2459 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002460 for(z=psp->filename, nBack=0; *z; z++){
2461 if( *z=='\\' ) nBack++;
2462 }
drh898799f2014-01-10 23:21:00 +00002463 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002464 nLine = lemonStrlen(zLine);
2465 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002466 }
icculus9e44cf12010-02-14 17:14:22 +00002467 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2468 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002469 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002470 if( nOld && zBuf[-1]!='\n' ){
2471 *(zBuf++) = '\n';
2472 }
2473 memcpy(zBuf, zLine, nLine);
2474 zBuf += nLine;
2475 *(zBuf++) = '"';
2476 for(z=psp->filename; *z; z++){
2477 if( *z=='\\' ){
2478 *(zBuf++) = '\\';
2479 }
2480 *(zBuf++) = *z;
2481 }
2482 *(zBuf++) = '"';
2483 *(zBuf++) = '\n';
2484 }
drh4dc8ef52008-07-01 17:13:57 +00002485 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2486 psp->decllinenoslot[0] = psp->tokenlineno;
2487 }
drha5808f32008-04-27 22:19:44 +00002488 memcpy(zBuf, zNew, nNew);
2489 zBuf += nNew;
2490 *zBuf = 0;
2491 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002492 }else{
2493 ErrorMsg(psp->filename,psp->tokenlineno,
2494 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2495 psp->errorcnt++;
2496 psp->state = RESYNC_AFTER_DECL_ERROR;
2497 }
2498 break;
drh0bd1f4e2002-06-06 18:54:39 +00002499 case WAITING_FOR_FALLBACK_ID:
2500 if( x[0]=='.' ){
2501 psp->state = WAITING_FOR_DECL_OR_RULE;
2502 }else if( !isupper(x[0]) ){
2503 ErrorMsg(psp->filename, psp->tokenlineno,
2504 "%%fallback argument \"%s\" should be a token", x);
2505 psp->errorcnt++;
2506 }else{
2507 struct symbol *sp = Symbol_new(x);
2508 if( psp->fallback==0 ){
2509 psp->fallback = sp;
2510 }else if( sp->fallback ){
2511 ErrorMsg(psp->filename, psp->tokenlineno,
2512 "More than one fallback assigned to token %s", x);
2513 psp->errorcnt++;
2514 }else{
2515 sp->fallback = psp->fallback;
2516 psp->gp->has_fallback = 1;
2517 }
2518 }
2519 break;
drhe09daa92006-06-10 13:29:31 +00002520 case WAITING_FOR_WILDCARD_ID:
2521 if( x[0]=='.' ){
2522 psp->state = WAITING_FOR_DECL_OR_RULE;
2523 }else if( !isupper(x[0]) ){
2524 ErrorMsg(psp->filename, psp->tokenlineno,
2525 "%%wildcard argument \"%s\" should be a token", x);
2526 psp->errorcnt++;
2527 }else{
2528 struct symbol *sp = Symbol_new(x);
2529 if( psp->gp->wildcard==0 ){
2530 psp->gp->wildcard = sp;
2531 }else{
2532 ErrorMsg(psp->filename, psp->tokenlineno,
2533 "Extra wildcard to token: %s", x);
2534 psp->errorcnt++;
2535 }
2536 }
2537 break;
drh61f92cd2014-01-11 03:06:18 +00002538 case WAITING_FOR_CLASS_ID:
2539 if( !islower(x[0]) ){
2540 ErrorMsg(psp->filename, psp->tokenlineno,
2541 "%%token_class must be followed by an identifier: ", x);
2542 psp->errorcnt++;
2543 psp->state = RESYNC_AFTER_DECL_ERROR;
2544 }else if( Symbol_find(x) ){
2545 ErrorMsg(psp->filename, psp->tokenlineno,
2546 "Symbol \"%s\" already used", x);
2547 psp->errorcnt++;
2548 psp->state = RESYNC_AFTER_DECL_ERROR;
2549 }else{
2550 psp->tkclass = Symbol_new(x);
2551 psp->tkclass->type = MULTITERMINAL;
2552 psp->state = WAITING_FOR_CLASS_TOKEN;
2553 }
2554 break;
2555 case WAITING_FOR_CLASS_TOKEN:
2556 if( x[0]=='.' ){
2557 psp->state = WAITING_FOR_DECL_OR_RULE;
2558 }else if( isupper(x[0]) || ((x[0]=='|' || x[0]=='/') && isupper(x[1])) ){
2559 struct symbol *msp = psp->tkclass;
2560 msp->nsubsym++;
2561 msp->subsym = (struct symbol **) realloc(msp->subsym,
2562 sizeof(struct symbol*)*msp->nsubsym);
2563 if( !isupper(x[0]) ) x++;
2564 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2565 }else{
2566 ErrorMsg(psp->filename, psp->tokenlineno,
2567 "%%token_class argument \"%s\" should be a token", x);
2568 psp->errorcnt++;
2569 psp->state = RESYNC_AFTER_DECL_ERROR;
2570 }
2571 break;
drh75897232000-05-29 14:26:00 +00002572 case RESYNC_AFTER_RULE_ERROR:
2573/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2574** break; */
2575 case RESYNC_AFTER_DECL_ERROR:
2576 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2577 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2578 break;
2579 }
2580}
2581
drh34ff57b2008-07-14 12:27:51 +00002582/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002583** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2584** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2585** comments them out. Text in between is also commented out as appropriate.
2586*/
danielk1977940fac92005-01-23 22:41:37 +00002587static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002588 int i, j, k, n;
2589 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002590 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002591 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002592 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002593 for(i=0; z[i]; i++){
2594 if( z[i]=='\n' ) lineno++;
2595 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2596 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2597 if( exclude ){
2598 exclude--;
2599 if( exclude==0 ){
2600 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2601 }
2602 }
2603 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2604 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2605 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2606 if( exclude ){
2607 exclude++;
2608 }else{
2609 for(j=i+7; isspace(z[j]); j++){}
2610 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2611 exclude = 1;
2612 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002613 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002614 exclude = 0;
2615 break;
2616 }
2617 }
2618 if( z[i+3]=='n' ) exclude = !exclude;
2619 if( exclude ){
2620 start = i;
2621 start_lineno = lineno;
2622 }
2623 }
2624 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2625 }
2626 }
2627 if( exclude ){
2628 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2629 exit(1);
2630 }
2631}
2632
drh75897232000-05-29 14:26:00 +00002633/* In spite of its name, this function is really a scanner. It read
2634** in the entire input file (all at once) then tokenizes it. Each
2635** token is passed to the function "parseonetoken" which builds all
2636** the appropriate data structures in the global state vector "gp".
2637*/
icculus9e44cf12010-02-14 17:14:22 +00002638void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002639{
2640 struct pstate ps;
2641 FILE *fp;
2642 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002643 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002644 int lineno;
2645 int c;
2646 char *cp, *nextcp;
2647 int startline = 0;
2648
rse38514a92007-09-20 11:34:17 +00002649 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002650 ps.gp = gp;
2651 ps.filename = gp->filename;
2652 ps.errorcnt = 0;
2653 ps.state = INITIALIZE;
2654
2655 /* Begin by reading the input file */
2656 fp = fopen(ps.filename,"rb");
2657 if( fp==0 ){
2658 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2659 gp->errorcnt++;
2660 return;
2661 }
2662 fseek(fp,0,2);
2663 filesize = ftell(fp);
2664 rewind(fp);
2665 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002666 if( filesize>100000000 || filebuf==0 ){
2667 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002668 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002669 fclose(fp);
drh75897232000-05-29 14:26:00 +00002670 return;
2671 }
2672 if( fread(filebuf,1,filesize,fp)!=filesize ){
2673 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2674 filesize);
2675 free(filebuf);
2676 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002677 fclose(fp);
drh75897232000-05-29 14:26:00 +00002678 return;
2679 }
2680 fclose(fp);
2681 filebuf[filesize] = 0;
2682
drh6d08b4d2004-07-20 12:45:22 +00002683 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2684 preprocess_input(filebuf);
2685
drh75897232000-05-29 14:26:00 +00002686 /* Now scan the text of the input file */
2687 lineno = 1;
2688 for(cp=filebuf; (c= *cp)!=0; ){
2689 if( c=='\n' ) lineno++; /* Keep track of the line number */
2690 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2691 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2692 cp+=2;
2693 while( (c= *cp)!=0 && c!='\n' ) cp++;
2694 continue;
2695 }
2696 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2697 cp+=2;
2698 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2699 if( c=='\n' ) lineno++;
2700 cp++;
2701 }
2702 if( c ) cp++;
2703 continue;
2704 }
2705 ps.tokenstart = cp; /* Mark the beginning of the token */
2706 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2707 if( c=='\"' ){ /* String literals */
2708 cp++;
2709 while( (c= *cp)!=0 && c!='\"' ){
2710 if( c=='\n' ) lineno++;
2711 cp++;
2712 }
2713 if( c==0 ){
2714 ErrorMsg(ps.filename,startline,
2715"String starting on this line is not terminated before the end of the file.");
2716 ps.errorcnt++;
2717 nextcp = cp;
2718 }else{
2719 nextcp = cp+1;
2720 }
2721 }else if( c=='{' ){ /* A block of C code */
2722 int level;
2723 cp++;
2724 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2725 if( c=='\n' ) lineno++;
2726 else if( c=='{' ) level++;
2727 else if( c=='}' ) level--;
2728 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2729 int prevc;
2730 cp = &cp[2];
2731 prevc = 0;
2732 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2733 if( c=='\n' ) lineno++;
2734 prevc = c;
2735 cp++;
drhf2f105d2012-08-20 15:53:54 +00002736 }
2737 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002738 cp = &cp[2];
2739 while( (c= *cp)!=0 && c!='\n' ) cp++;
2740 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002741 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002742 int startchar, prevc;
2743 startchar = c;
2744 prevc = 0;
2745 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2746 if( c=='\n' ) lineno++;
2747 if( prevc=='\\' ) prevc = 0;
2748 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002749 }
2750 }
drh75897232000-05-29 14:26:00 +00002751 }
2752 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002753 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002754"C code starting on this line is not terminated before the end of the file.");
2755 ps.errorcnt++;
2756 nextcp = cp;
2757 }else{
2758 nextcp = cp+1;
2759 }
2760 }else if( isalnum(c) ){ /* Identifiers */
2761 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2762 nextcp = cp;
2763 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2764 cp += 3;
2765 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002766 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2767 cp += 2;
2768 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2769 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002770 }else{ /* All other (one character) operators */
2771 cp++;
2772 nextcp = cp;
2773 }
2774 c = *cp;
2775 *cp = 0; /* Null terminate the token */
2776 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002777 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002778 cp = nextcp;
2779 }
2780 free(filebuf); /* Release the buffer after parsing */
2781 gp->rule = ps.firstrule;
2782 gp->errorcnt = ps.errorcnt;
2783}
2784/*************************** From the file "plink.c" *********************/
2785/*
2786** Routines processing configuration follow-set propagation links
2787** in the LEMON parser generator.
2788*/
2789static struct plink *plink_freelist = 0;
2790
2791/* Allocate a new plink */
2792struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002793 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002794
2795 if( plink_freelist==0 ){
2796 int i;
2797 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002798 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002799 if( plink_freelist==0 ){
2800 fprintf(stderr,
2801 "Unable to allocate memory for a new follow-set propagation link.\n");
2802 exit(1);
2803 }
2804 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2805 plink_freelist[amt-1].next = 0;
2806 }
icculus9e44cf12010-02-14 17:14:22 +00002807 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002808 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002809 return newlink;
drh75897232000-05-29 14:26:00 +00002810}
2811
2812/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002813void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002814{
icculus9e44cf12010-02-14 17:14:22 +00002815 struct plink *newlink;
2816 newlink = Plink_new();
2817 newlink->next = *plpp;
2818 *plpp = newlink;
2819 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002820}
2821
2822/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002823void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002824{
2825 struct plink *nextpl;
2826 while( from ){
2827 nextpl = from->next;
2828 from->next = *to;
2829 *to = from;
2830 from = nextpl;
2831 }
2832}
2833
2834/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002835void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002836{
2837 struct plink *nextpl;
2838
2839 while( plp ){
2840 nextpl = plp->next;
2841 plp->next = plink_freelist;
2842 plink_freelist = plp;
2843 plp = nextpl;
2844 }
2845}
2846/*********************** From the file "report.c" **************************/
2847/*
2848** Procedures for generating reports and tables in the LEMON parser generator.
2849*/
2850
2851/* Generate a filename with the given suffix. Space to hold the
2852** name comes from malloc() and must be freed by the calling
2853** function.
2854*/
icculus9e44cf12010-02-14 17:14:22 +00002855PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002856{
2857 char *name;
2858 char *cp;
2859
icculus9e44cf12010-02-14 17:14:22 +00002860 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002861 if( name==0 ){
2862 fprintf(stderr,"Can't allocate space for a filename.\n");
2863 exit(1);
2864 }
drh898799f2014-01-10 23:21:00 +00002865 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002866 cp = strrchr(name,'.');
2867 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002868 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002869 return name;
2870}
2871
2872/* Open a file with a name based on the name of the input file,
2873** but with a different (specified) suffix, and return a pointer
2874** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002875PRIVATE FILE *file_open(
2876 struct lemon *lemp,
2877 const char *suffix,
2878 const char *mode
2879){
drh75897232000-05-29 14:26:00 +00002880 FILE *fp;
2881
2882 if( lemp->outname ) free(lemp->outname);
2883 lemp->outname = file_makename(lemp, suffix);
2884 fp = fopen(lemp->outname,mode);
2885 if( fp==0 && *mode=='w' ){
2886 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2887 lemp->errorcnt++;
2888 return 0;
2889 }
2890 return fp;
2891}
2892
2893/* Duplicate the input file without comments and without actions
2894** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002895void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002896{
2897 struct rule *rp;
2898 struct symbol *sp;
2899 int i, j, maxlen, len, ncolumns, skip;
2900 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2901 maxlen = 10;
2902 for(i=0; i<lemp->nsymbol; i++){
2903 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002904 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002905 if( len>maxlen ) maxlen = len;
2906 }
2907 ncolumns = 76/(maxlen+5);
2908 if( ncolumns<1 ) ncolumns = 1;
2909 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2910 for(i=0; i<skip; i++){
2911 printf("//");
2912 for(j=i; j<lemp->nsymbol; j+=skip){
2913 sp = lemp->symbols[j];
2914 assert( sp->index==j );
2915 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2916 }
2917 printf("\n");
2918 }
2919 for(rp=lemp->rule; rp; rp=rp->next){
2920 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002921 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002922 printf(" ::=");
2923 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002924 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002925 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002926 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002927 for(j=1; j<sp->nsubsym; j++){
2928 printf("|%s", sp->subsym[j]->name);
2929 }
drh61f92cd2014-01-11 03:06:18 +00002930 }else{
2931 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002932 }
2933 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002934 }
2935 printf(".");
2936 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002937 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002938 printf("\n");
2939 }
2940}
2941
icculus9e44cf12010-02-14 17:14:22 +00002942void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002943{
2944 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002945 struct symbol *sp;
2946 int i, j;
drh75897232000-05-29 14:26:00 +00002947 rp = cfp->rp;
2948 fprintf(fp,"%s ::=",rp->lhs->name);
2949 for(i=0; i<=rp->nrhs; i++){
2950 if( i==cfp->dot ) fprintf(fp," *");
2951 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002952 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002953 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002954 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002955 for(j=1; j<sp->nsubsym; j++){
2956 fprintf(fp,"|%s",sp->subsym[j]->name);
2957 }
drh61f92cd2014-01-11 03:06:18 +00002958 }else{
2959 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002960 }
drh75897232000-05-29 14:26:00 +00002961 }
2962}
2963
2964/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002965#if 0
drh75897232000-05-29 14:26:00 +00002966/* Print a set */
2967PRIVATE void SetPrint(out,set,lemp)
2968FILE *out;
2969char *set;
2970struct lemon *lemp;
2971{
2972 int i;
2973 char *spacer;
2974 spacer = "";
2975 fprintf(out,"%12s[","");
2976 for(i=0; i<lemp->nterminal; i++){
2977 if( SetFind(set,i) ){
2978 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2979 spacer = " ";
2980 }
2981 }
2982 fprintf(out,"]\n");
2983}
2984
2985/* Print a plink chain */
2986PRIVATE void PlinkPrint(out,plp,tag)
2987FILE *out;
2988struct plink *plp;
2989char *tag;
2990{
2991 while( plp ){
drhada354d2005-11-05 15:03:59 +00002992 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002993 ConfigPrint(out,plp->cfp);
2994 fprintf(out,"\n");
2995 plp = plp->next;
2996 }
2997}
2998#endif
2999
3000/* Print an action to the given file descriptor. Return FALSE if
3001** nothing was actually printed.
3002*/
3003int PrintAction(struct action *ap, FILE *fp, int indent){
3004 int result = 1;
3005 switch( ap->type ){
3006 case SHIFT:
drhada354d2005-11-05 15:03:59 +00003007 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00003008 break;
3009 case REDUCE:
3010 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
3011 break;
3012 case ACCEPT:
3013 fprintf(fp,"%*s accept",indent,ap->sp->name);
3014 break;
3015 case ERROR:
3016 fprintf(fp,"%*s error",indent,ap->sp->name);
3017 break;
drh9892c5d2007-12-21 00:02:11 +00003018 case SRCONFLICT:
3019 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00003020 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
3021 indent,ap->sp->name,ap->x.rp->index);
3022 break;
drh9892c5d2007-12-21 00:02:11 +00003023 case SSCONFLICT:
drhdd7e9db2010-07-19 01:52:07 +00003024 fprintf(fp,"%*s shift %-3d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003025 indent,ap->sp->name,ap->x.stp->statenum);
3026 break;
drh75897232000-05-29 14:26:00 +00003027 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003028 if( showPrecedenceConflict ){
drhdd7e9db2010-07-19 01:52:07 +00003029 fprintf(fp,"%*s shift %-3d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003030 indent,ap->sp->name,ap->x.stp->statenum);
3031 }else{
3032 result = 0;
3033 }
3034 break;
drh75897232000-05-29 14:26:00 +00003035 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003036 if( showPrecedenceConflict ){
drhdd7e9db2010-07-19 01:52:07 +00003037 fprintf(fp,"%*s reduce %-3d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003038 indent,ap->sp->name,ap->x.rp->index);
3039 }else{
3040 result = 0;
3041 }
3042 break;
drh75897232000-05-29 14:26:00 +00003043 case NOT_USED:
3044 result = 0;
3045 break;
3046 }
3047 return result;
3048}
3049
3050/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00003051void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003052{
3053 int i;
3054 struct state *stp;
3055 struct config *cfp;
3056 struct action *ap;
3057 FILE *fp;
3058
drh2aa6ca42004-09-10 00:14:04 +00003059 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003060 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00003061 for(i=0; i<lemp->nstate; i++){
3062 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003063 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003064 if( lemp->basisflag ) cfp=stp->bp;
3065 else cfp=stp->cfp;
3066 while( cfp ){
3067 char buf[20];
3068 if( cfp->dot==cfp->rp->nrhs ){
drh898799f2014-01-10 23:21:00 +00003069 lemon_sprintf(buf,"(%d)",cfp->rp->index);
drh75897232000-05-29 14:26:00 +00003070 fprintf(fp," %5s ",buf);
3071 }else{
3072 fprintf(fp," ");
3073 }
3074 ConfigPrint(fp,cfp);
3075 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003076#if 0
drh75897232000-05-29 14:26:00 +00003077 SetPrint(fp,cfp->fws,lemp);
3078 PlinkPrint(fp,cfp->fplp,"To ");
3079 PlinkPrint(fp,cfp->bplp,"From");
3080#endif
3081 if( lemp->basisflag ) cfp=cfp->bp;
3082 else cfp=cfp->next;
3083 }
3084 fprintf(fp,"\n");
3085 for(ap=stp->ap; ap; ap=ap->next){
3086 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3087 }
3088 fprintf(fp,"\n");
3089 }
drhe9278182007-07-18 18:16:29 +00003090 fprintf(fp, "----------------------------------------------------\n");
3091 fprintf(fp, "Symbols:\n");
3092 for(i=0; i<lemp->nsymbol; i++){
3093 int j;
3094 struct symbol *sp;
3095
3096 sp = lemp->symbols[i];
3097 fprintf(fp, " %3d: %s", i, sp->name);
3098 if( sp->type==NONTERMINAL ){
3099 fprintf(fp, ":");
3100 if( sp->lambda ){
3101 fprintf(fp, " <lambda>");
3102 }
3103 for(j=0; j<lemp->nterminal; j++){
3104 if( sp->firstset && SetFind(sp->firstset, j) ){
3105 fprintf(fp, " %s", lemp->symbols[j]->name);
3106 }
3107 }
3108 }
3109 fprintf(fp, "\n");
3110 }
drh75897232000-05-29 14:26:00 +00003111 fclose(fp);
3112 return;
3113}
3114
3115/* Search for the file "name" which is in the same directory as
3116** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003117PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003118{
icculus9e44cf12010-02-14 17:14:22 +00003119 const char *pathlist;
3120 char *pathbufptr;
3121 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003122 char *path,*cp;
3123 char c;
drh75897232000-05-29 14:26:00 +00003124
3125#ifdef __WIN32__
3126 cp = strrchr(argv0,'\\');
3127#else
3128 cp = strrchr(argv0,'/');
3129#endif
3130 if( cp ){
3131 c = *cp;
3132 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003133 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003134 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003135 *cp = c;
3136 }else{
drh75897232000-05-29 14:26:00 +00003137 pathlist = getenv("PATH");
3138 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003139 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003140 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003141 if( (pathbuf != 0) && (path!=0) ){
3142 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003143 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003144 while( *pathbuf ){
3145 cp = strchr(pathbuf,':');
3146 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003147 c = *cp;
3148 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003149 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003150 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003151 if( c==0 ) pathbuf[0] = 0;
3152 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003153 if( access(path,modemask)==0 ) break;
3154 }
icculus9e44cf12010-02-14 17:14:22 +00003155 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003156 }
3157 }
3158 return path;
3159}
3160
3161/* Given an action, compute the integer value for that action
3162** which is to be put in the action table of the generated machine.
3163** Return negative if no action should be generated.
3164*/
icculus9e44cf12010-02-14 17:14:22 +00003165PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003166{
3167 int act;
3168 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003169 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003170 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3171 case ERROR: act = lemp->nstate + lemp->nrule; break;
3172 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3173 default: act = -1; break;
3174 }
3175 return act;
3176}
3177
3178#define LINESIZE 1000
3179/* The next cluster of routines are for reading the template file
3180** and writing the results to the generated parser */
3181/* The first function transfers data from "in" to "out" until
3182** a line is seen which begins with "%%". The line number is
3183** tracked.
3184**
3185** if name!=0, then any word that begin with "Parse" is changed to
3186** begin with *name instead.
3187*/
icculus9e44cf12010-02-14 17:14:22 +00003188PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003189{
3190 int i, iStart;
3191 char line[LINESIZE];
3192 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3193 (*lineno)++;
3194 iStart = 0;
3195 if( name ){
3196 for(i=0; line[i]; i++){
3197 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3198 && (i==0 || !isalpha(line[i-1]))
3199 ){
3200 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3201 fprintf(out,"%s",name);
3202 i += 4;
3203 iStart = i+1;
3204 }
3205 }
3206 }
3207 fprintf(out,"%s",&line[iStart]);
3208 }
3209}
3210
3211/* The next function finds the template file and opens it, returning
3212** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003213PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003214{
3215 static char templatename[] = "lempar.c";
3216 char buf[1000];
3217 FILE *in;
3218 char *tpltname;
3219 char *cp;
3220
icculus3e143bd2010-02-14 00:48:49 +00003221 /* first, see if user specified a template filename on the command line. */
3222 if (user_templatename != 0) {
3223 if( access(user_templatename,004)==-1 ){
3224 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3225 user_templatename);
3226 lemp->errorcnt++;
3227 return 0;
3228 }
3229 in = fopen(user_templatename,"rb");
3230 if( in==0 ){
3231 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3232 lemp->errorcnt++;
3233 return 0;
3234 }
3235 return in;
3236 }
3237
drh75897232000-05-29 14:26:00 +00003238 cp = strrchr(lemp->filename,'.');
3239 if( cp ){
drh898799f2014-01-10 23:21:00 +00003240 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003241 }else{
drh898799f2014-01-10 23:21:00 +00003242 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003243 }
3244 if( access(buf,004)==0 ){
3245 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003246 }else if( access(templatename,004)==0 ){
3247 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003248 }else{
3249 tpltname = pathsearch(lemp->argv0,templatename,0);
3250 }
3251 if( tpltname==0 ){
3252 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3253 templatename);
3254 lemp->errorcnt++;
3255 return 0;
3256 }
drh2aa6ca42004-09-10 00:14:04 +00003257 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003258 if( in==0 ){
3259 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3260 lemp->errorcnt++;
3261 return 0;
3262 }
3263 return in;
3264}
3265
drhaf805ca2004-09-07 11:28:25 +00003266/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003267PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003268{
3269 fprintf(out,"#line %d \"",lineno);
3270 while( *filename ){
3271 if( *filename == '\\' ) putc('\\',out);
3272 putc(*filename,out);
3273 filename++;
3274 }
3275 fprintf(out,"\"\n");
3276}
3277
drh75897232000-05-29 14:26:00 +00003278/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003279PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003280{
3281 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003282 while( *str ){
drh75897232000-05-29 14:26:00 +00003283 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003284 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003285 str++;
3286 }
drh9db55df2004-09-09 14:01:21 +00003287 if( str[-1]!='\n' ){
3288 putc('\n',out);
3289 (*lineno)++;
3290 }
shane58543932008-12-10 20:10:04 +00003291 if (!lemp->nolinenosflag) {
3292 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3293 }
drh75897232000-05-29 14:26:00 +00003294 return;
3295}
3296
3297/*
3298** The following routine emits code for the destructor for the
3299** symbol sp
3300*/
icculus9e44cf12010-02-14 17:14:22 +00003301void emit_destructor_code(
3302 FILE *out,
3303 struct symbol *sp,
3304 struct lemon *lemp,
3305 int *lineno
3306){
drhcc83b6e2004-04-23 23:38:42 +00003307 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003308
drh75897232000-05-29 14:26:00 +00003309 if( sp->type==TERMINAL ){
3310 cp = lemp->tokendest;
3311 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003312 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003313 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003314 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003315 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003316 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003317 }else if( lemp->vardest ){
3318 cp = lemp->vardest;
3319 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003320 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003321 }else{
3322 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003323 }
3324 for(; *cp; cp++){
3325 if( *cp=='$' && cp[1]=='$' ){
3326 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3327 cp++;
3328 continue;
3329 }
shane58543932008-12-10 20:10:04 +00003330 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003331 fputc(*cp,out);
3332 }
shane58543932008-12-10 20:10:04 +00003333 fprintf(out,"\n"); (*lineno)++;
3334 if (!lemp->nolinenosflag) {
3335 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3336 }
3337 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003338 return;
3339}
3340
3341/*
drh960e8c62001-04-03 16:53:21 +00003342** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003343*/
icculus9e44cf12010-02-14 17:14:22 +00003344int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003345{
3346 int ret;
3347 if( sp->type==TERMINAL ){
3348 ret = lemp->tokendest!=0;
3349 }else{
drh960e8c62001-04-03 16:53:21 +00003350 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003351 }
3352 return ret;
3353}
3354
drh0bb132b2004-07-20 14:06:51 +00003355/*
3356** Append text to a dynamically allocated string. If zText is 0 then
3357** reset the string to be empty again. Always return the complete text
3358** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003359**
3360** n bytes of zText are stored. If n==0 then all of zText up to the first
3361** \000 terminator is stored. zText can contain up to two instances of
3362** %d. The values of p1 and p2 are written into the first and second
3363** %d.
3364**
3365** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003366*/
icculus9e44cf12010-02-14 17:14:22 +00003367PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3368 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003369 static char *z = 0;
3370 static int alloced = 0;
3371 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003372 int c;
drh0bb132b2004-07-20 14:06:51 +00003373 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003374 if( zText==0 ){
3375 used = 0;
3376 return z;
3377 }
drh7ac25c72004-08-19 15:12:26 +00003378 if( n<=0 ){
3379 if( n<0 ){
3380 used += n;
3381 assert( used>=0 );
3382 }
drh87cf1372008-08-13 20:09:06 +00003383 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003384 }
drhdf609712010-11-23 20:55:27 +00003385 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003386 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003387 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003388 }
icculus9e44cf12010-02-14 17:14:22 +00003389 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003390 while( n-- > 0 ){
3391 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003392 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003393 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003394 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003395 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003396 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003397 zText++;
3398 n--;
3399 }else{
mistachkin2318d332015-01-12 18:02:52 +00003400 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003401 }
3402 }
3403 z[used] = 0;
3404 return z;
3405}
3406
3407/*
3408** zCode is a string that is the action associated with a rule. Expand
3409** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003410** stack.
drh0bb132b2004-07-20 14:06:51 +00003411*/
drhaf805ca2004-09-07 11:28:25 +00003412PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003413 char *cp, *xp;
3414 int i;
3415 char lhsused = 0; /* True if the LHS element has been used */
3416 char used[MAXRHS]; /* True for each RHS element which is used */
3417
3418 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3419 lhsused = 0;
3420
drh19c9e562007-03-29 20:13:53 +00003421 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003422 static char newlinestr[2] = { '\n', '\0' };
3423 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003424 rp->line = rp->ruleline;
3425 }
3426
drh0bb132b2004-07-20 14:06:51 +00003427 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003428
3429 /* This const cast is wrong but harmless, if we're careful. */
3430 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003431 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3432 char saved;
3433 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3434 saved = *xp;
3435 *xp = 0;
3436 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003437 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003438 cp = xp;
3439 lhsused = 1;
3440 }else{
3441 for(i=0; i<rp->nrhs; i++){
3442 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003443 if( cp!=rp->code && cp[-1]=='@' ){
3444 /* If the argument is of the form @X then substituted
3445 ** the token number of X, not the value of X */
3446 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3447 }else{
drhfd405312005-11-06 04:06:59 +00003448 struct symbol *sp = rp->rhs[i];
3449 int dtnum;
3450 if( sp->type==MULTITERMINAL ){
3451 dtnum = sp->subsym[0]->dtnum;
3452 }else{
3453 dtnum = sp->dtnum;
3454 }
3455 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003456 }
drh0bb132b2004-07-20 14:06:51 +00003457 cp = xp;
3458 used[i] = 1;
3459 break;
3460 }
3461 }
3462 }
3463 *xp = saved;
3464 }
3465 append_str(cp, 1, 0, 0);
3466 } /* End loop */
3467
3468 /* Check to make sure the LHS has been used */
3469 if( rp->lhsalias && !lhsused ){
3470 ErrorMsg(lemp->filename,rp->ruleline,
3471 "Label \"%s\" for \"%s(%s)\" is never used.",
3472 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3473 lemp->errorcnt++;
3474 }
3475
3476 /* Generate destructor code for RHS symbols which are not used in the
3477 ** reduce code */
3478 for(i=0; i<rp->nrhs; i++){
3479 if( rp->rhsalias[i] && !used[i] ){
3480 ErrorMsg(lemp->filename,rp->ruleline,
3481 "Label %s for \"%s(%s)\" is never used.",
3482 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3483 lemp->errorcnt++;
3484 }else if( rp->rhsalias[i]==0 ){
3485 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003486 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003487 rp->rhs[i]->index,i-rp->nrhs+1);
3488 }else{
3489 /* No destructor defined for this term */
3490 }
3491 }
3492 }
drh61e339a2007-01-16 03:09:02 +00003493 if( rp->code ){
3494 cp = append_str(0,0,0,0);
3495 rp->code = Strsafe(cp?cp:"");
3496 }
drh0bb132b2004-07-20 14:06:51 +00003497}
3498
drh75897232000-05-29 14:26:00 +00003499/*
3500** Generate code which executes when the rule "rp" is reduced. Write
3501** the code to "out". Make sure lineno stays up-to-date.
3502*/
icculus9e44cf12010-02-14 17:14:22 +00003503PRIVATE void emit_code(
3504 FILE *out,
3505 struct rule *rp,
3506 struct lemon *lemp,
3507 int *lineno
3508){
3509 const char *cp;
drh75897232000-05-29 14:26:00 +00003510
3511 /* Generate code to do the reduce action */
3512 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003513 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003514 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003515 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003516 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003517 } /* End loop */
shane58543932008-12-10 20:10:04 +00003518 fprintf(out,"}\n"); (*lineno)++;
3519 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003520 } /* End if( rp->code ) */
3521
drh75897232000-05-29 14:26:00 +00003522 return;
3523}
3524
3525/*
3526** Print the definition of the union used for the parser's data stack.
3527** This union contains fields for every possible data type for tokens
3528** and nonterminals. In the process of computing and printing this
3529** union, also set the ".dtnum" field of every terminal and nonterminal
3530** symbol.
3531*/
icculus9e44cf12010-02-14 17:14:22 +00003532void print_stack_union(
3533 FILE *out, /* The output stream */
3534 struct lemon *lemp, /* The main info structure for this parser */
3535 int *plineno, /* Pointer to the line number */
3536 int mhflag /* True if generating makeheaders output */
3537){
drh75897232000-05-29 14:26:00 +00003538 int lineno = *plineno; /* The line number of the output */
3539 char **types; /* A hash table of datatypes */
3540 int arraysize; /* Size of the "types" array */
3541 int maxdtlength; /* Maximum length of any ".datatype" field. */
3542 char *stddt; /* Standardized name for a datatype */
3543 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003544 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003545 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003546
3547 /* Allocate and initialize types[] and allocate stddt[] */
3548 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003549 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003550 if( types==0 ){
3551 fprintf(stderr,"Out of memory.\n");
3552 exit(1);
3553 }
drh75897232000-05-29 14:26:00 +00003554 for(i=0; i<arraysize; i++) types[i] = 0;
3555 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003556 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003557 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003558 }
drh75897232000-05-29 14:26:00 +00003559 for(i=0; i<lemp->nsymbol; i++){
3560 int len;
3561 struct symbol *sp = lemp->symbols[i];
3562 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003563 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003564 if( len>maxdtlength ) maxdtlength = len;
3565 }
3566 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003567 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003568 fprintf(stderr,"Out of memory.\n");
3569 exit(1);
3570 }
3571
3572 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3573 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003574 ** used for terminal symbols. If there is no %default_type defined then
3575 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3576 ** a datatype using the %type directive.
3577 */
drh75897232000-05-29 14:26:00 +00003578 for(i=0; i<lemp->nsymbol; i++){
3579 struct symbol *sp = lemp->symbols[i];
3580 char *cp;
3581 if( sp==lemp->errsym ){
3582 sp->dtnum = arraysize+1;
3583 continue;
3584 }
drh960e8c62001-04-03 16:53:21 +00003585 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003586 sp->dtnum = 0;
3587 continue;
3588 }
3589 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003590 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003591 j = 0;
3592 while( isspace(*cp) ) cp++;
3593 while( *cp ) stddt[j++] = *cp++;
3594 while( j>0 && isspace(stddt[j-1]) ) j--;
3595 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003596 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003597 sp->dtnum = 0;
3598 continue;
3599 }
drh75897232000-05-29 14:26:00 +00003600 hash = 0;
3601 for(j=0; stddt[j]; j++){
3602 hash = hash*53 + stddt[j];
3603 }
drh3b2129c2003-05-13 00:34:21 +00003604 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003605 while( types[hash] ){
3606 if( strcmp(types[hash],stddt)==0 ){
3607 sp->dtnum = hash + 1;
3608 break;
3609 }
3610 hash++;
drh2b51f212013-10-11 23:01:02 +00003611 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003612 }
3613 if( types[hash]==0 ){
3614 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003615 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003616 if( types[hash]==0 ){
3617 fprintf(stderr,"Out of memory.\n");
3618 exit(1);
3619 }
drh898799f2014-01-10 23:21:00 +00003620 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003621 }
3622 }
3623
3624 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3625 name = lemp->name ? lemp->name : "Parse";
3626 lineno = *plineno;
3627 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3628 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3629 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3630 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3631 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003632 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003633 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3634 for(i=0; i<arraysize; i++){
3635 if( types[i]==0 ) continue;
3636 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3637 free(types[i]);
3638 }
drhc4dd3fd2008-01-22 01:48:05 +00003639 if( lemp->errsym->useCnt ){
3640 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3641 }
drh75897232000-05-29 14:26:00 +00003642 free(stddt);
3643 free(types);
3644 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3645 *plineno = lineno;
3646}
3647
drhb29b0a52002-02-23 19:39:46 +00003648/*
3649** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003650** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003651*/
drh8b582012003-10-21 13:16:03 +00003652static const char *minimum_size_type(int lwr, int upr){
3653 if( lwr>=0 ){
3654 if( upr<=255 ){
3655 return "unsigned char";
3656 }else if( upr<65535 ){
3657 return "unsigned short int";
3658 }else{
3659 return "unsigned int";
3660 }
3661 }else if( lwr>=-127 && upr<=127 ){
3662 return "signed char";
3663 }else if( lwr>=-32767 && upr<32767 ){
3664 return "short";
drhb29b0a52002-02-23 19:39:46 +00003665 }else{
drh8b582012003-10-21 13:16:03 +00003666 return "int";
drhb29b0a52002-02-23 19:39:46 +00003667 }
3668}
3669
drhfdbf9282003-10-21 16:34:41 +00003670/*
3671** Each state contains a set of token transaction and a set of
3672** nonterminal transactions. Each of these sets makes an instance
3673** of the following structure. An array of these structures is used
3674** to order the creation of entries in the yy_action[] table.
3675*/
3676struct axset {
3677 struct state *stp; /* A pointer to a state */
3678 int isTkn; /* True to use tokens. False for non-terminals */
3679 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003680 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003681};
3682
3683/*
3684** Compare to axset structures for sorting purposes
3685*/
3686static int axset_compare(const void *a, const void *b){
3687 struct axset *p1 = (struct axset*)a;
3688 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003689 int c;
3690 c = p2->nAction - p1->nAction;
3691 if( c==0 ){
3692 c = p2->iOrder - p1->iOrder;
3693 }
3694 assert( c!=0 || p1==p2 );
3695 return c;
drhfdbf9282003-10-21 16:34:41 +00003696}
3697
drhc4dd3fd2008-01-22 01:48:05 +00003698/*
3699** Write text on "out" that describes the rule "rp".
3700*/
3701static void writeRuleText(FILE *out, struct rule *rp){
3702 int j;
3703 fprintf(out,"%s ::=", rp->lhs->name);
3704 for(j=0; j<rp->nrhs; j++){
3705 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003706 if( sp->type!=MULTITERMINAL ){
3707 fprintf(out," %s", sp->name);
3708 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003709 int k;
drh61f92cd2014-01-11 03:06:18 +00003710 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003711 for(k=1; k<sp->nsubsym; k++){
3712 fprintf(out,"|%s",sp->subsym[k]->name);
3713 }
3714 }
3715 }
3716}
3717
3718
drh75897232000-05-29 14:26:00 +00003719/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003720void ReportTable(
3721 struct lemon *lemp,
3722 int mhflag /* Output in makeheaders format if true */
3723){
drh75897232000-05-29 14:26:00 +00003724 FILE *out, *in;
3725 char line[LINESIZE];
3726 int lineno;
3727 struct state *stp;
3728 struct action *ap;
3729 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003730 struct acttab *pActtab;
icculusa3191192010-02-17 05:40:34 +00003731 int i, j, n;
icculus9e44cf12010-02-14 17:14:22 +00003732 const char *name;
drh8b582012003-10-21 13:16:03 +00003733 int mnTknOfst, mxTknOfst;
3734 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003735 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003736
3737 in = tplt_open(lemp);
3738 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003739 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003740 if( out==0 ){
3741 fclose(in);
3742 return;
3743 }
3744 lineno = 1;
3745 tplt_xfer(lemp->name,in,out,&lineno);
3746
3747 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003748 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003749 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00003750 char *incName = file_makename(lemp, ".h");
3751 fprintf(out,"#include \"%s\"\n", incName); lineno++;
3752 free(incName);
drh75897232000-05-29 14:26:00 +00003753 }
3754 tplt_xfer(lemp->name,in,out,&lineno);
3755
3756 /* Generate #defines for all tokens */
3757 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003758 const char *prefix;
drh75897232000-05-29 14:26:00 +00003759 fprintf(out,"#if INTERFACE\n"); lineno++;
3760 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3761 else prefix = "";
3762 for(i=1; i<lemp->nterminal; i++){
3763 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3764 lineno++;
3765 }
3766 fprintf(out,"#endif\n"); lineno++;
3767 }
3768 tplt_xfer(lemp->name,in,out,&lineno);
3769
3770 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003771 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003772 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003773 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3774 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003775 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003776 if( lemp->wildcard ){
3777 fprintf(out,"#define YYWILDCARD %d\n",
3778 lemp->wildcard->index); lineno++;
3779 }
drh75897232000-05-29 14:26:00 +00003780 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003781 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003782 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003783 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3784 }else{
3785 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3786 }
drhca44b5a2007-02-22 23:06:58 +00003787 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003788 if( mhflag ){
3789 fprintf(out,"#if INTERFACE\n"); lineno++;
3790 }
3791 name = lemp->name ? lemp->name : "Parse";
3792 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00003793 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003794 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3795 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003796 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3797 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3798 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3799 name,lemp->arg,&lemp->arg[i]); lineno++;
3800 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3801 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003802 }else{
drh1f245e42002-03-11 13:55:50 +00003803 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3804 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3805 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3806 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003807 }
3808 if( mhflag ){
3809 fprintf(out,"#endif\n"); lineno++;
3810 }
3811 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3812 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003813 if( lemp->errsym->useCnt ){
3814 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3815 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3816 }
drh0bd1f4e2002-06-06 18:54:39 +00003817 if( lemp->has_fallback ){
3818 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3819 }
drh75897232000-05-29 14:26:00 +00003820 tplt_xfer(lemp->name,in,out,&lineno);
3821
drh8b582012003-10-21 13:16:03 +00003822 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003823 **
drh8b582012003-10-21 13:16:03 +00003824 ** yy_action[] A single table containing all actions.
3825 ** yy_lookahead[] A table containing the lookahead for each entry in
3826 ** yy_action. Used to detect hash collisions.
3827 ** yy_shift_ofst[] For each state, the offset into yy_action for
3828 ** shifting terminals.
3829 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3830 ** shifting non-terminals after a reduce.
3831 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003832 */
drh75897232000-05-29 14:26:00 +00003833
drh8b582012003-10-21 13:16:03 +00003834 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003835 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003836 if( ax==0 ){
3837 fprintf(stderr,"malloc failed\n");
3838 exit(1);
3839 }
drh75897232000-05-29 14:26:00 +00003840 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003841 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003842 ax[i*2].stp = stp;
3843 ax[i*2].isTkn = 1;
3844 ax[i*2].nAction = stp->nTknAct;
3845 ax[i*2+1].stp = stp;
3846 ax[i*2+1].isTkn = 0;
3847 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003848 }
drh8b582012003-10-21 13:16:03 +00003849 mxTknOfst = mnTknOfst = 0;
3850 mxNtOfst = mnNtOfst = 0;
3851
drhfdbf9282003-10-21 16:34:41 +00003852 /* Compute the action table. In order to try to keep the size of the
3853 ** action table to a minimum, the heuristic of placing the largest action
3854 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003855 */
drhe594bc32009-11-03 13:02:25 +00003856 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003857 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003858 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003859 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3860 stp = ax[i].stp;
3861 if( ax[i].isTkn ){
3862 for(ap=stp->ap; ap; ap=ap->next){
3863 int action;
3864 if( ap->sp->index>=lemp->nterminal ) continue;
3865 action = compute_action(lemp, ap);
3866 if( action<0 ) continue;
3867 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003868 }
drhfdbf9282003-10-21 16:34:41 +00003869 stp->iTknOfst = acttab_insert(pActtab);
3870 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3871 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3872 }else{
3873 for(ap=stp->ap; ap; ap=ap->next){
3874 int action;
3875 if( ap->sp->index<lemp->nterminal ) continue;
3876 if( ap->sp->index==lemp->nsymbol ) continue;
3877 action = compute_action(lemp, ap);
3878 if( action<0 ) continue;
3879 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003880 }
drhfdbf9282003-10-21 16:34:41 +00003881 stp->iNtOfst = acttab_insert(pActtab);
3882 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3883 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003884 }
3885 }
drhfdbf9282003-10-21 16:34:41 +00003886 free(ax);
drh8b582012003-10-21 13:16:03 +00003887
3888 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003889 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003890 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3891 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003892 for(i=j=0; i<n; i++){
3893 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003894 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003895 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003896 fprintf(out, " %4d,", action);
3897 if( j==9 || i==n-1 ){
3898 fprintf(out, "\n"); lineno++;
3899 j = 0;
3900 }else{
3901 j++;
3902 }
3903 }
3904 fprintf(out, "};\n"); lineno++;
3905
3906 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003907 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003908 for(i=j=0; i<n; i++){
3909 int la = acttab_yylookahead(pActtab, i);
3910 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003911 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003912 fprintf(out, " %4d,", la);
3913 if( j==9 || i==n-1 ){
3914 fprintf(out, "\n"); lineno++;
3915 j = 0;
3916 }else{
3917 j++;
3918 }
3919 }
3920 fprintf(out, "};\n"); lineno++;
3921
3922 /* Output the yy_shift_ofst[] table */
3923 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003924 n = lemp->nstate;
3925 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003926 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3927 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3928 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003929 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003930 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003931 for(i=j=0; i<n; i++){
3932 int ofst;
3933 stp = lemp->sorted[i];
3934 ofst = stp->iTknOfst;
3935 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003936 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003937 fprintf(out, " %4d,", ofst);
3938 if( j==9 || i==n-1 ){
3939 fprintf(out, "\n"); lineno++;
3940 j = 0;
3941 }else{
3942 j++;
3943 }
3944 }
3945 fprintf(out, "};\n"); lineno++;
3946
3947 /* Output the yy_reduce_ofst[] table */
3948 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003949 n = lemp->nstate;
3950 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003951 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3952 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3953 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003954 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003955 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003956 for(i=j=0; i<n; i++){
3957 int ofst;
3958 stp = lemp->sorted[i];
3959 ofst = stp->iNtOfst;
3960 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003961 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003962 fprintf(out, " %4d,", ofst);
3963 if( j==9 || i==n-1 ){
3964 fprintf(out, "\n"); lineno++;
3965 j = 0;
3966 }else{
3967 j++;
3968 }
3969 }
3970 fprintf(out, "};\n"); lineno++;
3971
3972 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003973 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003974 n = lemp->nstate;
3975 for(i=j=0; i<n; i++){
3976 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003977 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003978 fprintf(out, " %4d,", stp->iDflt);
3979 if( j==9 || i==n-1 ){
3980 fprintf(out, "\n"); lineno++;
3981 j = 0;
3982 }else{
3983 j++;
3984 }
3985 }
3986 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003987 tplt_xfer(lemp->name,in,out,&lineno);
3988
drh0bd1f4e2002-06-06 18:54:39 +00003989 /* Generate the table of fallback tokens.
3990 */
3991 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003992 int mx = lemp->nterminal - 1;
3993 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3994 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003995 struct symbol *p = lemp->symbols[i];
3996 if( p->fallback==0 ){
3997 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3998 }else{
3999 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4000 p->name, p->fallback->name);
4001 }
4002 lineno++;
4003 }
4004 }
4005 tplt_xfer(lemp->name, in, out, &lineno);
4006
4007 /* Generate a table containing the symbolic name of every symbol
4008 */
drh75897232000-05-29 14:26:00 +00004009 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004010 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004011 fprintf(out," %-15s",line);
4012 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4013 }
4014 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4015 tplt_xfer(lemp->name,in,out,&lineno);
4016
drh0bd1f4e2002-06-06 18:54:39 +00004017 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004018 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004019 ** when tracing REDUCE actions.
4020 */
4021 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4022 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004023 fprintf(out," /* %3d */ \"", i);
4024 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004025 fprintf(out,"\",\n"); lineno++;
4026 }
4027 tplt_xfer(lemp->name,in,out,&lineno);
4028
drh75897232000-05-29 14:26:00 +00004029 /* Generate code which executes every time a symbol is popped from
4030 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004031 ** (In other words, generate the %destructor actions)
4032 */
drh75897232000-05-29 14:26:00 +00004033 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004034 int once = 1;
drh75897232000-05-29 14:26:00 +00004035 for(i=0; i<lemp->nsymbol; i++){
4036 struct symbol *sp = lemp->symbols[i];
4037 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004038 if( once ){
4039 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4040 once = 0;
4041 }
drhc53eed12009-06-12 17:46:19 +00004042 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004043 }
4044 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4045 if( i<lemp->nsymbol ){
4046 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4047 fprintf(out," break;\n"); lineno++;
4048 }
4049 }
drh8d659732005-01-13 23:54:06 +00004050 if( lemp->vardest ){
4051 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004052 int once = 1;
drh8d659732005-01-13 23:54:06 +00004053 for(i=0; i<lemp->nsymbol; i++){
4054 struct symbol *sp = lemp->symbols[i];
4055 if( sp==0 || sp->type==TERMINAL ||
4056 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004057 if( once ){
4058 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4059 once = 0;
4060 }
drhc53eed12009-06-12 17:46:19 +00004061 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004062 dflt_sp = sp;
4063 }
4064 if( dflt_sp!=0 ){
4065 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004066 }
drh4dc8ef52008-07-01 17:13:57 +00004067 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004068 }
drh75897232000-05-29 14:26:00 +00004069 for(i=0; i<lemp->nsymbol; i++){
4070 struct symbol *sp = lemp->symbols[i];
4071 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004072 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004073
4074 /* Combine duplicate destructors into a single case */
4075 for(j=i+1; j<lemp->nsymbol; j++){
4076 struct symbol *sp2 = lemp->symbols[j];
4077 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4078 && sp2->dtnum==sp->dtnum
4079 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004080 fprintf(out," case %d: /* %s */\n",
4081 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004082 sp2->destructor = 0;
4083 }
4084 }
4085
drh75897232000-05-29 14:26:00 +00004086 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4087 fprintf(out," break;\n"); lineno++;
4088 }
drh75897232000-05-29 14:26:00 +00004089 tplt_xfer(lemp->name,in,out,&lineno);
4090
4091 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004092 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004093 tplt_xfer(lemp->name,in,out,&lineno);
4094
4095 /* Generate the table of rule information
4096 **
4097 ** Note: This code depends on the fact that rules are number
4098 ** sequentually beginning with 0.
4099 */
4100 for(rp=lemp->rule; rp; rp=rp->next){
4101 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4102 }
4103 tplt_xfer(lemp->name,in,out,&lineno);
4104
4105 /* Generate code which execution during each REDUCE action */
4106 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004107 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004108 }
drhc53eed12009-06-12 17:46:19 +00004109 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004110 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004111 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004112 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004113 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004114 fprintf(out," case %d: /* ", rp->index);
4115 writeRuleText(out, rp);
4116 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004117 for(rp2=rp->next; rp2; rp2=rp2->next){
4118 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004119 fprintf(out," case %d: /* ", rp2->index);
4120 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004121 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004122 rp2->code = 0;
4123 }
4124 }
drh75897232000-05-29 14:26:00 +00004125 emit_code(out,rp,lemp,&lineno);
4126 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004127 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004128 }
drhc53eed12009-06-12 17:46:19 +00004129 /* Finally, output the default: rule. We choose as the default: all
4130 ** empty actions. */
4131 fprintf(out," default:\n"); lineno++;
4132 for(rp=lemp->rule; rp; rp=rp->next){
4133 if( rp->code==0 ) continue;
4134 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4135 fprintf(out," /* (%d) ", rp->index);
4136 writeRuleText(out, rp);
4137 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4138 }
4139 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004140 tplt_xfer(lemp->name,in,out,&lineno);
4141
4142 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004143 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004144 tplt_xfer(lemp->name,in,out,&lineno);
4145
4146 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004147 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004148 tplt_xfer(lemp->name,in,out,&lineno);
4149
4150 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004151 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004152 tplt_xfer(lemp->name,in,out,&lineno);
4153
4154 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004155 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004156
4157 fclose(in);
4158 fclose(out);
4159 return;
4160}
4161
4162/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004163void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004164{
4165 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004166 const char *prefix;
drh75897232000-05-29 14:26:00 +00004167 char line[LINESIZE];
4168 char pattern[LINESIZE];
4169 int i;
4170
4171 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4172 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004173 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004174 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004175 int nextChar;
drh75897232000-05-29 14:26:00 +00004176 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004177 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4178 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004179 if( strcmp(line,pattern) ) break;
4180 }
drh8ba0d1c2012-06-16 15:26:31 +00004181 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004182 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004183 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004184 /* No change in the file. Don't rewrite it. */
4185 return;
4186 }
4187 }
drh2aa6ca42004-09-10 00:14:04 +00004188 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004189 if( out ){
4190 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004191 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004192 }
4193 fclose(out);
4194 }
4195 return;
4196}
4197
4198/* Reduce the size of the action tables, if possible, by making use
4199** of defaults.
4200**
drhb59499c2002-02-23 18:45:13 +00004201** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004202** it the default. Except, there is no default if the wildcard token
4203** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004204*/
icculus9e44cf12010-02-14 17:14:22 +00004205void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004206{
4207 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004208 struct action *ap, *ap2;
4209 struct rule *rp, *rp2, *rbest;
4210 int nbest, n;
drh75897232000-05-29 14:26:00 +00004211 int i;
drhe09daa92006-06-10 13:29:31 +00004212 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004213
4214 for(i=0; i<lemp->nstate; i++){
4215 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004216 nbest = 0;
4217 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004218 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004219
drhb59499c2002-02-23 18:45:13 +00004220 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004221 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4222 usesWildcard = 1;
4223 }
drhb59499c2002-02-23 18:45:13 +00004224 if( ap->type!=REDUCE ) continue;
4225 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004226 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004227 if( rp==rbest ) continue;
4228 n = 1;
4229 for(ap2=ap->next; ap2; ap2=ap2->next){
4230 if( ap2->type!=REDUCE ) continue;
4231 rp2 = ap2->x.rp;
4232 if( rp2==rbest ) continue;
4233 if( rp2==rp ) n++;
4234 }
4235 if( n>nbest ){
4236 nbest = n;
4237 rbest = rp;
drh75897232000-05-29 14:26:00 +00004238 }
4239 }
drhb59499c2002-02-23 18:45:13 +00004240
4241 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004242 ** is not at least 1 or if the wildcard token is a possible
4243 ** lookahead.
4244 */
4245 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004246
drhb59499c2002-02-23 18:45:13 +00004247
4248 /* Combine matching REDUCE actions into a single default */
4249 for(ap=stp->ap; ap; ap=ap->next){
4250 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4251 }
drh75897232000-05-29 14:26:00 +00004252 assert( ap );
4253 ap->sp = Symbol_new("{default}");
4254 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004255 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004256 }
4257 stp->ap = Action_sort(stp->ap);
4258 }
4259}
drhb59499c2002-02-23 18:45:13 +00004260
drhada354d2005-11-05 15:03:59 +00004261
4262/*
4263** Compare two states for sorting purposes. The smaller state is the
4264** one with the most non-terminal actions. If they have the same number
4265** of non-terminal actions, then the smaller is the one with the most
4266** token actions.
4267*/
4268static int stateResortCompare(const void *a, const void *b){
4269 const struct state *pA = *(const struct state**)a;
4270 const struct state *pB = *(const struct state**)b;
4271 int n;
4272
4273 n = pB->nNtAct - pA->nNtAct;
4274 if( n==0 ){
4275 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004276 if( n==0 ){
4277 n = pB->statenum - pA->statenum;
4278 }
drhada354d2005-11-05 15:03:59 +00004279 }
drhe594bc32009-11-03 13:02:25 +00004280 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004281 return n;
4282}
4283
4284
4285/*
4286** Renumber and resort states so that states with fewer choices
4287** occur at the end. Except, keep state 0 as the first state.
4288*/
icculus9e44cf12010-02-14 17:14:22 +00004289void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004290{
4291 int i;
4292 struct state *stp;
4293 struct action *ap;
4294
4295 for(i=0; i<lemp->nstate; i++){
4296 stp = lemp->sorted[i];
4297 stp->nTknAct = stp->nNtAct = 0;
4298 stp->iDflt = lemp->nstate + lemp->nrule;
4299 stp->iTknOfst = NO_OFFSET;
4300 stp->iNtOfst = NO_OFFSET;
4301 for(ap=stp->ap; ap; ap=ap->next){
4302 if( compute_action(lemp,ap)>=0 ){
4303 if( ap->sp->index<lemp->nterminal ){
4304 stp->nTknAct++;
4305 }else if( ap->sp->index<lemp->nsymbol ){
4306 stp->nNtAct++;
4307 }else{
4308 stp->iDflt = compute_action(lemp, ap);
4309 }
4310 }
4311 }
4312 }
4313 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4314 stateResortCompare);
4315 for(i=0; i<lemp->nstate; i++){
4316 lemp->sorted[i]->statenum = i;
4317 }
4318}
4319
4320
drh75897232000-05-29 14:26:00 +00004321/***************** From the file "set.c" ************************************/
4322/*
4323** Set manipulation routines for the LEMON parser generator.
4324*/
4325
4326static int size = 0;
4327
4328/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004329void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004330{
4331 size = n+1;
4332}
4333
4334/* Allocate a new set */
4335char *SetNew(){
4336 char *s;
drh9892c5d2007-12-21 00:02:11 +00004337 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004338 if( s==0 ){
4339 extern void memory_error();
4340 memory_error();
4341 }
drh75897232000-05-29 14:26:00 +00004342 return s;
4343}
4344
4345/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004346void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004347{
4348 free(s);
4349}
4350
4351/* Add a new element to the set. Return TRUE if the element was added
4352** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004353int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004354{
4355 int rv;
drh9892c5d2007-12-21 00:02:11 +00004356 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004357 rv = s[e];
4358 s[e] = 1;
4359 return !rv;
4360}
4361
4362/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004363int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004364{
4365 int i, progress;
4366 progress = 0;
4367 for(i=0; i<size; i++){
4368 if( s2[i]==0 ) continue;
4369 if( s1[i]==0 ){
4370 progress = 1;
4371 s1[i] = 1;
4372 }
4373 }
4374 return progress;
4375}
4376/********************** From the file "table.c" ****************************/
4377/*
4378** All code in this file has been automatically generated
4379** from a specification in the file
4380** "table.q"
4381** by the associative array code building program "aagen".
4382** Do not edit this file! Instead, edit the specification
4383** file, then rerun aagen.
4384*/
4385/*
4386** Code for processing tables in the LEMON parser generator.
4387*/
4388
drh01f75f22013-10-02 20:46:30 +00004389PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004390{
drh01f75f22013-10-02 20:46:30 +00004391 unsigned h = 0;
4392 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004393 return h;
4394}
4395
4396/* Works like strdup, sort of. Save a string in malloced memory, but
4397** keep strings in a table so that the same string is not in more
4398** than one place.
4399*/
icculus9e44cf12010-02-14 17:14:22 +00004400const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004401{
icculus9e44cf12010-02-14 17:14:22 +00004402 const char *z;
4403 char *cpy;
drh75897232000-05-29 14:26:00 +00004404
drh916f75f2006-07-17 00:19:39 +00004405 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004406 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004407 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004408 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004409 z = cpy;
drh75897232000-05-29 14:26:00 +00004410 Strsafe_insert(z);
4411 }
4412 MemoryCheck(z);
4413 return z;
4414}
4415
4416/* There is one instance of the following structure for each
4417** associative array of type "x1".
4418*/
4419struct s_x1 {
4420 int size; /* The number of available slots. */
4421 /* Must be a power of 2 greater than or */
4422 /* equal to 1 */
4423 int count; /* Number of currently slots filled */
4424 struct s_x1node *tbl; /* The data stored here */
4425 struct s_x1node **ht; /* Hash table for lookups */
4426};
4427
4428/* There is one instance of this structure for every data element
4429** in an associative array of type "x1".
4430*/
4431typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004432 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004433 struct s_x1node *next; /* Next entry with the same hash */
4434 struct s_x1node **from; /* Previous link */
4435} x1node;
4436
4437/* There is only one instance of the array, which is the following */
4438static struct s_x1 *x1a;
4439
4440/* Allocate a new associative array */
4441void Strsafe_init(){
4442 if( x1a ) return;
4443 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4444 if( x1a ){
4445 x1a->size = 1024;
4446 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004447 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004448 if( x1a->tbl==0 ){
4449 free(x1a);
4450 x1a = 0;
4451 }else{
4452 int i;
4453 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4454 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4455 }
4456 }
4457}
4458/* Insert a new record into the array. Return TRUE if successful.
4459** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004460int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004461{
4462 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004463 unsigned h;
4464 unsigned ph;
drh75897232000-05-29 14:26:00 +00004465
4466 if( x1a==0 ) return 0;
4467 ph = strhash(data);
4468 h = ph & (x1a->size-1);
4469 np = x1a->ht[h];
4470 while( np ){
4471 if( strcmp(np->data,data)==0 ){
4472 /* An existing entry with the same key is found. */
4473 /* Fail because overwrite is not allows. */
4474 return 0;
4475 }
4476 np = np->next;
4477 }
4478 if( x1a->count>=x1a->size ){
4479 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004480 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004481 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004482 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004483 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004484 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004485 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004486 array.ht = (x1node**)&(array.tbl[arrSize]);
4487 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004488 for(i=0; i<x1a->count; i++){
4489 x1node *oldnp, *newnp;
4490 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004491 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004492 newnp = &(array.tbl[i]);
4493 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4494 newnp->next = array.ht[h];
4495 newnp->data = oldnp->data;
4496 newnp->from = &(array.ht[h]);
4497 array.ht[h] = newnp;
4498 }
4499 free(x1a->tbl);
4500 *x1a = array;
4501 }
4502 /* Insert the new data */
4503 h = ph & (x1a->size-1);
4504 np = &(x1a->tbl[x1a->count++]);
4505 np->data = data;
4506 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4507 np->next = x1a->ht[h];
4508 x1a->ht[h] = np;
4509 np->from = &(x1a->ht[h]);
4510 return 1;
4511}
4512
4513/* Return a pointer to data assigned to the given key. Return NULL
4514** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004515const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004516{
drh01f75f22013-10-02 20:46:30 +00004517 unsigned h;
drh75897232000-05-29 14:26:00 +00004518 x1node *np;
4519
4520 if( x1a==0 ) return 0;
4521 h = strhash(key) & (x1a->size-1);
4522 np = x1a->ht[h];
4523 while( np ){
4524 if( strcmp(np->data,key)==0 ) break;
4525 np = np->next;
4526 }
4527 return np ? np->data : 0;
4528}
4529
4530/* Return a pointer to the (terminal or nonterminal) symbol "x".
4531** Create a new symbol if this is the first time "x" has been seen.
4532*/
icculus9e44cf12010-02-14 17:14:22 +00004533struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004534{
4535 struct symbol *sp;
4536
4537 sp = Symbol_find(x);
4538 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004539 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004540 MemoryCheck(sp);
4541 sp->name = Strsafe(x);
4542 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4543 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004544 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004545 sp->prec = -1;
4546 sp->assoc = UNK;
4547 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004548 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004549 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004550 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004551 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004552 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004553 Symbol_insert(sp,sp->name);
4554 }
drhc4dd3fd2008-01-22 01:48:05 +00004555 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004556 return sp;
4557}
4558
drh61f92cd2014-01-11 03:06:18 +00004559/* Compare two symbols for sorting purposes. Return negative,
4560** zero, or positive if a is less then, equal to, or greater
4561** than b.
drh60d31652004-02-22 00:08:04 +00004562**
4563** Symbols that begin with upper case letters (terminals or tokens)
4564** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004565** (non-terminals). And MULTITERMINAL symbols (created using the
4566** %token_class directive) must sort at the very end. Other than
4567** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004568**
4569** We find experimentally that leaving the symbols in their original
4570** order (the order they appeared in the grammar file) gives the
4571** smallest parser tables in SQLite.
4572*/
icculus9e44cf12010-02-14 17:14:22 +00004573int Symbolcmpp(const void *_a, const void *_b)
4574{
drh61f92cd2014-01-11 03:06:18 +00004575 const struct symbol *a = *(const struct symbol **) _a;
4576 const struct symbol *b = *(const struct symbol **) _b;
4577 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4578 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4579 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004580}
4581
4582/* There is one instance of the following structure for each
4583** associative array of type "x2".
4584*/
4585struct s_x2 {
4586 int size; /* The number of available slots. */
4587 /* Must be a power of 2 greater than or */
4588 /* equal to 1 */
4589 int count; /* Number of currently slots filled */
4590 struct s_x2node *tbl; /* The data stored here */
4591 struct s_x2node **ht; /* Hash table for lookups */
4592};
4593
4594/* There is one instance of this structure for every data element
4595** in an associative array of type "x2".
4596*/
4597typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004598 struct symbol *data; /* The data */
4599 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004600 struct s_x2node *next; /* Next entry with the same hash */
4601 struct s_x2node **from; /* Previous link */
4602} x2node;
4603
4604/* There is only one instance of the array, which is the following */
4605static struct s_x2 *x2a;
4606
4607/* Allocate a new associative array */
4608void Symbol_init(){
4609 if( x2a ) return;
4610 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4611 if( x2a ){
4612 x2a->size = 128;
4613 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004614 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004615 if( x2a->tbl==0 ){
4616 free(x2a);
4617 x2a = 0;
4618 }else{
4619 int i;
4620 x2a->ht = (x2node**)&(x2a->tbl[128]);
4621 for(i=0; i<128; i++) x2a->ht[i] = 0;
4622 }
4623 }
4624}
4625/* Insert a new record into the array. Return TRUE if successful.
4626** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004627int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004628{
4629 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004630 unsigned h;
4631 unsigned ph;
drh75897232000-05-29 14:26:00 +00004632
4633 if( x2a==0 ) return 0;
4634 ph = strhash(key);
4635 h = ph & (x2a->size-1);
4636 np = x2a->ht[h];
4637 while( np ){
4638 if( strcmp(np->key,key)==0 ){
4639 /* An existing entry with the same key is found. */
4640 /* Fail because overwrite is not allows. */
4641 return 0;
4642 }
4643 np = np->next;
4644 }
4645 if( x2a->count>=x2a->size ){
4646 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004647 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004648 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004649 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004650 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004651 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004652 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004653 array.ht = (x2node**)&(array.tbl[arrSize]);
4654 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004655 for(i=0; i<x2a->count; i++){
4656 x2node *oldnp, *newnp;
4657 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004658 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004659 newnp = &(array.tbl[i]);
4660 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4661 newnp->next = array.ht[h];
4662 newnp->key = oldnp->key;
4663 newnp->data = oldnp->data;
4664 newnp->from = &(array.ht[h]);
4665 array.ht[h] = newnp;
4666 }
4667 free(x2a->tbl);
4668 *x2a = array;
4669 }
4670 /* Insert the new data */
4671 h = ph & (x2a->size-1);
4672 np = &(x2a->tbl[x2a->count++]);
4673 np->key = key;
4674 np->data = data;
4675 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4676 np->next = x2a->ht[h];
4677 x2a->ht[h] = np;
4678 np->from = &(x2a->ht[h]);
4679 return 1;
4680}
4681
4682/* Return a pointer to data assigned to the given key. Return NULL
4683** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004684struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004685{
drh01f75f22013-10-02 20:46:30 +00004686 unsigned h;
drh75897232000-05-29 14:26:00 +00004687 x2node *np;
4688
4689 if( x2a==0 ) return 0;
4690 h = strhash(key) & (x2a->size-1);
4691 np = x2a->ht[h];
4692 while( np ){
4693 if( strcmp(np->key,key)==0 ) break;
4694 np = np->next;
4695 }
4696 return np ? np->data : 0;
4697}
4698
4699/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004700struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004701{
4702 struct symbol *data;
4703 if( x2a && n>0 && n<=x2a->count ){
4704 data = x2a->tbl[n-1].data;
4705 }else{
4706 data = 0;
4707 }
4708 return data;
4709}
4710
4711/* Return the size of the array */
4712int Symbol_count()
4713{
4714 return x2a ? x2a->count : 0;
4715}
4716
4717/* Return an array of pointers to all data in the table.
4718** The array is obtained from malloc. Return NULL if memory allocation
4719** problems, or if the array is empty. */
4720struct symbol **Symbol_arrayof()
4721{
4722 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00004723 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004724 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004725 arrSize = x2a->count;
4726 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004727 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004728 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004729 }
4730 return array;
4731}
4732
4733/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004734int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004735{
icculus9e44cf12010-02-14 17:14:22 +00004736 const struct config *a = (struct config *) _a;
4737 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004738 int x;
4739 x = a->rp->index - b->rp->index;
4740 if( x==0 ) x = a->dot - b->dot;
4741 return x;
4742}
4743
4744/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004745PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004746{
4747 int rc;
4748 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4749 rc = a->rp->index - b->rp->index;
4750 if( rc==0 ) rc = a->dot - b->dot;
4751 }
4752 if( rc==0 ){
4753 if( a ) rc = 1;
4754 if( b ) rc = -1;
4755 }
4756 return rc;
4757}
4758
4759/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00004760PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004761{
drh01f75f22013-10-02 20:46:30 +00004762 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004763 while( a ){
4764 h = h*571 + a->rp->index*37 + a->dot;
4765 a = a->bp;
4766 }
4767 return h;
4768}
4769
4770/* Allocate a new state structure */
4771struct state *State_new()
4772{
icculus9e44cf12010-02-14 17:14:22 +00004773 struct state *newstate;
4774 newstate = (struct state *)calloc(1, sizeof(struct state) );
4775 MemoryCheck(newstate);
4776 return newstate;
drh75897232000-05-29 14:26:00 +00004777}
4778
4779/* There is one instance of the following structure for each
4780** associative array of type "x3".
4781*/
4782struct s_x3 {
4783 int size; /* The number of available slots. */
4784 /* Must be a power of 2 greater than or */
4785 /* equal to 1 */
4786 int count; /* Number of currently slots filled */
4787 struct s_x3node *tbl; /* The data stored here */
4788 struct s_x3node **ht; /* Hash table for lookups */
4789};
4790
4791/* There is one instance of this structure for every data element
4792** in an associative array of type "x3".
4793*/
4794typedef struct s_x3node {
4795 struct state *data; /* The data */
4796 struct config *key; /* The key */
4797 struct s_x3node *next; /* Next entry with the same hash */
4798 struct s_x3node **from; /* Previous link */
4799} x3node;
4800
4801/* There is only one instance of the array, which is the following */
4802static struct s_x3 *x3a;
4803
4804/* Allocate a new associative array */
4805void State_init(){
4806 if( x3a ) return;
4807 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4808 if( x3a ){
4809 x3a->size = 128;
4810 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004811 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00004812 if( x3a->tbl==0 ){
4813 free(x3a);
4814 x3a = 0;
4815 }else{
4816 int i;
4817 x3a->ht = (x3node**)&(x3a->tbl[128]);
4818 for(i=0; i<128; i++) x3a->ht[i] = 0;
4819 }
4820 }
4821}
4822/* Insert a new record into the array. Return TRUE if successful.
4823** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004824int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004825{
4826 x3node *np;
drh01f75f22013-10-02 20:46:30 +00004827 unsigned h;
4828 unsigned ph;
drh75897232000-05-29 14:26:00 +00004829
4830 if( x3a==0 ) return 0;
4831 ph = statehash(key);
4832 h = ph & (x3a->size-1);
4833 np = x3a->ht[h];
4834 while( np ){
4835 if( statecmp(np->key,key)==0 ){
4836 /* An existing entry with the same key is found. */
4837 /* Fail because overwrite is not allows. */
4838 return 0;
4839 }
4840 np = np->next;
4841 }
4842 if( x3a->count>=x3a->size ){
4843 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004844 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004845 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00004846 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00004847 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00004848 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00004849 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004850 array.ht = (x3node**)&(array.tbl[arrSize]);
4851 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004852 for(i=0; i<x3a->count; i++){
4853 x3node *oldnp, *newnp;
4854 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004855 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004856 newnp = &(array.tbl[i]);
4857 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4858 newnp->next = array.ht[h];
4859 newnp->key = oldnp->key;
4860 newnp->data = oldnp->data;
4861 newnp->from = &(array.ht[h]);
4862 array.ht[h] = newnp;
4863 }
4864 free(x3a->tbl);
4865 *x3a = array;
4866 }
4867 /* Insert the new data */
4868 h = ph & (x3a->size-1);
4869 np = &(x3a->tbl[x3a->count++]);
4870 np->key = key;
4871 np->data = data;
4872 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4873 np->next = x3a->ht[h];
4874 x3a->ht[h] = np;
4875 np->from = &(x3a->ht[h]);
4876 return 1;
4877}
4878
4879/* Return a pointer to data assigned to the given key. Return NULL
4880** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004881struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004882{
drh01f75f22013-10-02 20:46:30 +00004883 unsigned h;
drh75897232000-05-29 14:26:00 +00004884 x3node *np;
4885
4886 if( x3a==0 ) return 0;
4887 h = statehash(key) & (x3a->size-1);
4888 np = x3a->ht[h];
4889 while( np ){
4890 if( statecmp(np->key,key)==0 ) break;
4891 np = np->next;
4892 }
4893 return np ? np->data : 0;
4894}
4895
4896/* Return an array of pointers to all data in the table.
4897** The array is obtained from malloc. Return NULL if memory allocation
4898** problems, or if the array is empty. */
4899struct state **State_arrayof()
4900{
4901 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00004902 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004903 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004904 arrSize = x3a->count;
4905 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00004906 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004907 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004908 }
4909 return array;
4910}
4911
4912/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00004913PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004914{
drh01f75f22013-10-02 20:46:30 +00004915 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004916 h = h*571 + a->rp->index*37 + a->dot;
4917 return h;
4918}
4919
4920/* There is one instance of the following structure for each
4921** associative array of type "x4".
4922*/
4923struct s_x4 {
4924 int size; /* The number of available slots. */
4925 /* Must be a power of 2 greater than or */
4926 /* equal to 1 */
4927 int count; /* Number of currently slots filled */
4928 struct s_x4node *tbl; /* The data stored here */
4929 struct s_x4node **ht; /* Hash table for lookups */
4930};
4931
4932/* There is one instance of this structure for every data element
4933** in an associative array of type "x4".
4934*/
4935typedef struct s_x4node {
4936 struct config *data; /* The data */
4937 struct s_x4node *next; /* Next entry with the same hash */
4938 struct s_x4node **from; /* Previous link */
4939} x4node;
4940
4941/* There is only one instance of the array, which is the following */
4942static struct s_x4 *x4a;
4943
4944/* Allocate a new associative array */
4945void Configtable_init(){
4946 if( x4a ) return;
4947 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4948 if( x4a ){
4949 x4a->size = 64;
4950 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004951 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00004952 if( x4a->tbl==0 ){
4953 free(x4a);
4954 x4a = 0;
4955 }else{
4956 int i;
4957 x4a->ht = (x4node**)&(x4a->tbl[64]);
4958 for(i=0; i<64; i++) x4a->ht[i] = 0;
4959 }
4960 }
4961}
4962/* Insert a new record into the array. Return TRUE if successful.
4963** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004964int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00004965{
4966 x4node *np;
drh01f75f22013-10-02 20:46:30 +00004967 unsigned h;
4968 unsigned ph;
drh75897232000-05-29 14:26:00 +00004969
4970 if( x4a==0 ) return 0;
4971 ph = confighash(data);
4972 h = ph & (x4a->size-1);
4973 np = x4a->ht[h];
4974 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004975 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00004976 /* An existing entry with the same key is found. */
4977 /* Fail because overwrite is not allows. */
4978 return 0;
4979 }
4980 np = np->next;
4981 }
4982 if( x4a->count>=x4a->size ){
4983 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004984 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004985 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00004986 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00004987 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00004988 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00004989 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004990 array.ht = (x4node**)&(array.tbl[arrSize]);
4991 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004992 for(i=0; i<x4a->count; i++){
4993 x4node *oldnp, *newnp;
4994 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004995 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004996 newnp = &(array.tbl[i]);
4997 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4998 newnp->next = array.ht[h];
4999 newnp->data = oldnp->data;
5000 newnp->from = &(array.ht[h]);
5001 array.ht[h] = newnp;
5002 }
5003 free(x4a->tbl);
5004 *x4a = array;
5005 }
5006 /* Insert the new data */
5007 h = ph & (x4a->size-1);
5008 np = &(x4a->tbl[x4a->count++]);
5009 np->data = data;
5010 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5011 np->next = x4a->ht[h];
5012 x4a->ht[h] = np;
5013 np->from = &(x4a->ht[h]);
5014 return 1;
5015}
5016
5017/* Return a pointer to data assigned to the given key. Return NULL
5018** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005019struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005020{
5021 int h;
5022 x4node *np;
5023
5024 if( x4a==0 ) return 0;
5025 h = confighash(key) & (x4a->size-1);
5026 np = x4a->ht[h];
5027 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005028 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005029 np = np->next;
5030 }
5031 return np ? np->data : 0;
5032}
5033
5034/* Remove all data from the table. Pass each data to the function "f"
5035** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005036void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005037{
5038 int i;
5039 if( x4a==0 || x4a->count==0 ) return;
5040 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5041 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5042 x4a->count = 0;
5043 return;
5044}