blob: 2e8054b5ccb819d0f0522b79bde269c2d6e092fe [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
drh25473362015-09-04 18:03:45 +000058** lemon_addtext(). The first two are replacements for sprintf() and vsprintf().
drh898799f2014-01-10 23:21:00 +000059** 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 */
drh3bd48ab2015-09-07 18:23:37 +0000319 NOT_USED, /* Deleted by compression */
320 SHIFTREDUCE /* Shift first, then reduce */
icculus9e44cf12010-02-14 17:14:22 +0000321};
322
drh75897232000-05-29 14:26:00 +0000323/* Every shift or reduce operation is stored as one of the following */
324struct action {
325 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000326 enum e_action type;
drh75897232000-05-29 14:26:00 +0000327 union {
328 struct state *stp; /* The new state, if a shift */
329 struct rule *rp; /* The rule, if a reduce */
330 } x;
331 struct action *next; /* Next action for this state */
332 struct action *collide; /* Next action with the same hash */
333};
334
335/* Each state of the generated parser's finite state machine
336** is encoded as an instance of the following structure. */
337struct state {
338 struct config *bp; /* The basis configurations for this state */
339 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000340 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000341 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000342 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
343 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
drh3bd48ab2015-09-07 18:23:37 +0000344 int iDfltReduce; /* Default action is to REDUCE by this rule */
345 struct rule *pDfltReduce;/* The default REDUCE rule. */
346 int autoReduce; /* True if this is an auto-reduce state */
drh75897232000-05-29 14:26:00 +0000347};
drh8b582012003-10-21 13:16:03 +0000348#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000349
350/* A followset propagation link indicates that the contents of one
351** configuration followset should be propagated to another whenever
352** the first changes. */
353struct plink {
354 struct config *cfp; /* The configuration to which linked */
355 struct plink *next; /* The next propagate link */
356};
357
358/* The state vector for the entire parser generator is recorded as
359** follows. (LEMON uses no global variables and makes little use of
360** static variables. Fields in the following structure can be thought
361** of as begin global variables in the program.) */
362struct lemon {
363 struct state **sorted; /* Table of states sorted by state number */
364 struct rule *rule; /* List of all rules */
365 int nstate; /* Number of states */
drh3bd48ab2015-09-07 18:23:37 +0000366 int nxstate; /* nstate with tail degenerate states removed */
drh75897232000-05-29 14:26:00 +0000367 int nrule; /* Number of rules */
368 int nsymbol; /* Number of terminal and nonterminal symbols */
369 int nterminal; /* Number of terminal symbols */
370 struct symbol **symbols; /* Sorted array of pointers to symbols */
371 int errorcnt; /* Number of errors */
372 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000373 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000374 char *name; /* Name of the generated parser */
375 char *arg; /* Declaration of the 3th argument to parser */
376 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000377 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000378 char *start; /* Name of the start symbol for the grammar */
379 char *stacksize; /* Size of the parser stack */
380 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000381 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000382 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000383 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000384 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000385 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000386 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000387 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000388 char *filename; /* Name of the input file */
389 char *outname; /* Name of the current output file */
390 char *tokenprefix; /* A prefix added to token names in the .h file */
391 int nconflict; /* Number of parsing conflicts */
drhc75e0162015-09-07 02:23:02 +0000392 int nactiontab; /* Number of entries in the yy_action[] table */
393 int tablesize; /* Total table size of all tables in bytes */
drh75897232000-05-29 14:26:00 +0000394 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000395 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000396 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000397 char *argv0; /* Name of the program */
398};
399
400#define MemoryCheck(X) if((X)==0){ \
401 extern void memory_error(); \
402 memory_error(); \
403}
404
405/**************** From the file "table.h" *********************************/
406/*
407** All code in this file has been automatically generated
408** from a specification in the file
409** "table.q"
410** by the associative array code building program "aagen".
411** Do not edit this file! Instead, edit the specification
412** file, then rerun aagen.
413*/
414/*
415** Code for processing tables in the LEMON parser generator.
416*/
drh75897232000-05-29 14:26:00 +0000417/* Routines for handling a strings */
418
icculus9e44cf12010-02-14 17:14:22 +0000419const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000420
icculus9e44cf12010-02-14 17:14:22 +0000421void Strsafe_init(void);
422int Strsafe_insert(const char *);
423const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000424
425/* Routines for handling symbols of the grammar */
426
icculus9e44cf12010-02-14 17:14:22 +0000427struct symbol *Symbol_new(const char *);
428int Symbolcmpp(const void *, const void *);
429void Symbol_init(void);
430int Symbol_insert(struct symbol *, const char *);
431struct symbol *Symbol_find(const char *);
432struct symbol *Symbol_Nth(int);
433int Symbol_count(void);
434struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000435
436/* Routines to manage the state table */
437
icculus9e44cf12010-02-14 17:14:22 +0000438int Configcmp(const char *, const char *);
439struct state *State_new(void);
440void State_init(void);
441int State_insert(struct state *, struct config *);
442struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000443struct state **State_arrayof(/* */);
444
445/* Routines used for efficiency in Configlist_add */
446
icculus9e44cf12010-02-14 17:14:22 +0000447void Configtable_init(void);
448int Configtable_insert(struct config *);
449struct config *Configtable_find(struct config *);
450void Configtable_clear(int(*)(struct config *));
451
drh75897232000-05-29 14:26:00 +0000452/****************** From the file "action.c" *******************************/
453/*
454** Routines processing parser actions in the LEMON parser generator.
455*/
456
457/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000458static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000459 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000460 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000461
462 if( freelist==0 ){
463 int i;
464 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000465 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000466 if( freelist==0 ){
467 fprintf(stderr,"Unable to allocate memory for a new parser action.");
468 exit(1);
469 }
470 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
471 freelist[amt-1].next = 0;
472 }
icculus9e44cf12010-02-14 17:14:22 +0000473 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000474 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000475 return newaction;
drh75897232000-05-29 14:26:00 +0000476}
477
drhe9278182007-07-18 18:16:29 +0000478/* Compare two actions for sorting purposes. Return negative, zero, or
479** positive if the first action is less than, equal to, or greater than
480** the first
481*/
482static int actioncmp(
483 struct action *ap1,
484 struct action *ap2
485){
drh75897232000-05-29 14:26:00 +0000486 int rc;
487 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000488 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000489 rc = (int)ap1->type - (int)ap2->type;
490 }
drh3bd48ab2015-09-07 18:23:37 +0000491 if( rc==0 && (ap1->type==REDUCE || ap1->type==SHIFTREDUCE) ){
drh75897232000-05-29 14:26:00 +0000492 rc = ap1->x.rp->index - ap2->x.rp->index;
493 }
drhe594bc32009-11-03 13:02:25 +0000494 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000495 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000496 }
drh75897232000-05-29 14:26:00 +0000497 return rc;
498}
499
500/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000501static struct action *Action_sort(
502 struct action *ap
503){
504 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
505 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000506 return ap;
507}
508
icculus9e44cf12010-02-14 17:14:22 +0000509void Action_add(
510 struct action **app,
511 enum e_action type,
512 struct symbol *sp,
513 char *arg
514){
515 struct action *newaction;
516 newaction = Action_new();
517 newaction->next = *app;
518 *app = newaction;
519 newaction->type = type;
520 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000521 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000522 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000523 }else{
icculus9e44cf12010-02-14 17:14:22 +0000524 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000525 }
526}
drh8b582012003-10-21 13:16:03 +0000527/********************** New code to implement the "acttab" module ***********/
528/*
529** This module implements routines use to construct the yy_action[] table.
530*/
531
532/*
533** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000534** the following structure.
535**
536** The yy_action table maps the pair (state_number, lookahead) into an
537** action_number. The table is an array of integers pairs. The state_number
538** determines an initial offset into the yy_action array. The lookahead
539** value is then added to this initial offset to get an index X into the
540** yy_action array. If the aAction[X].lookahead equals the value of the
541** of the lookahead input, then the value of the action_number output is
542** aAction[X].action. If the lookaheads do not match then the
543** default action for the state_number is returned.
544**
545** All actions associated with a single state_number are first entered
546** into aLookahead[] using multiple calls to acttab_action(). Then the
547** actions for that single state_number are placed into the aAction[]
548** array with a single call to acttab_insert(). The acttab_insert() call
549** also resets the aLookahead[] array in preparation for the next
550** state number.
drh8b582012003-10-21 13:16:03 +0000551*/
icculus9e44cf12010-02-14 17:14:22 +0000552struct lookahead_action {
553 int lookahead; /* Value of the lookahead token */
554 int action; /* Action to take on the given lookahead */
555};
drh8b582012003-10-21 13:16:03 +0000556typedef struct acttab acttab;
557struct acttab {
558 int nAction; /* Number of used slots in aAction[] */
559 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000560 struct lookahead_action
561 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000562 *aLookahead; /* A single new transaction set */
563 int mnLookahead; /* Minimum aLookahead[].lookahead */
564 int mnAction; /* Action associated with mnLookahead */
565 int mxLookahead; /* Maximum aLookahead[].lookahead */
566 int nLookahead; /* Used slots in aLookahead[] */
567 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
568};
569
570/* Return the number of entries in the yy_action table */
571#define acttab_size(X) ((X)->nAction)
572
573/* The value for the N-th entry in yy_action */
574#define acttab_yyaction(X,N) ((X)->aAction[N].action)
575
576/* The value for the N-th entry in yy_lookahead */
577#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
578
579/* Free all memory associated with the given acttab */
580void acttab_free(acttab *p){
581 free( p->aAction );
582 free( p->aLookahead );
583 free( p );
584}
585
586/* Allocate a new acttab structure */
587acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000588 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000589 if( p==0 ){
590 fprintf(stderr,"Unable to allocate memory for a new acttab.");
591 exit(1);
592 }
593 memset(p, 0, sizeof(*p));
594 return p;
595}
596
drh8dc3e8f2010-01-07 03:53:03 +0000597/* Add a new action to the current transaction set.
598**
599** This routine is called once for each lookahead for a particular
600** state.
drh8b582012003-10-21 13:16:03 +0000601*/
602void acttab_action(acttab *p, int lookahead, int action){
603 if( p->nLookahead>=p->nLookaheadAlloc ){
604 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000605 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000606 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
607 if( p->aLookahead==0 ){
608 fprintf(stderr,"malloc failed\n");
609 exit(1);
610 }
611 }
612 if( p->nLookahead==0 ){
613 p->mxLookahead = lookahead;
614 p->mnLookahead = lookahead;
615 p->mnAction = action;
616 }else{
617 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
618 if( p->mnLookahead>lookahead ){
619 p->mnLookahead = lookahead;
620 p->mnAction = action;
621 }
622 }
623 p->aLookahead[p->nLookahead].lookahead = lookahead;
624 p->aLookahead[p->nLookahead].action = action;
625 p->nLookahead++;
626}
627
628/*
629** Add the transaction set built up with prior calls to acttab_action()
630** into the current action table. Then reset the transaction set back
631** to an empty set in preparation for a new round of acttab_action() calls.
632**
633** Return the offset into the action table of the new transaction.
634*/
635int acttab_insert(acttab *p){
636 int i, j, k, n;
637 assert( p->nLookahead>0 );
638
639 /* Make sure we have enough space to hold the expanded action table
640 ** in the worst case. The worst case occurs if the transaction set
641 ** must be appended to the current action table
642 */
drh784d86f2004-02-19 18:41:53 +0000643 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000644 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000645 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000646 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000647 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000648 sizeof(p->aAction[0])*p->nActionAlloc);
649 if( p->aAction==0 ){
650 fprintf(stderr,"malloc failed\n");
651 exit(1);
652 }
drhfdbf9282003-10-21 16:34:41 +0000653 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000654 p->aAction[i].lookahead = -1;
655 p->aAction[i].action = -1;
656 }
657 }
658
drh8dc3e8f2010-01-07 03:53:03 +0000659 /* Scan the existing action table looking for an offset that is a
660 ** duplicate of the current transaction set. Fall out of the loop
661 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000662 **
663 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
664 */
drh8dc3e8f2010-01-07 03:53:03 +0000665 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000666 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000667 /* All lookaheads and actions in the aLookahead[] transaction
668 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000669 if( p->aAction[i].action!=p->mnAction ) continue;
670 for(j=0; j<p->nLookahead; j++){
671 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
672 if( k<0 || k>=p->nAction ) break;
673 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
674 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
675 }
676 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000677
678 /* No possible lookahead value that is not in the aLookahead[]
679 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000680 n = 0;
681 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000682 if( p->aAction[j].lookahead<0 ) continue;
683 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000684 }
drhfdbf9282003-10-21 16:34:41 +0000685 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000686 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000687 }
drh8b582012003-10-21 13:16:03 +0000688 }
689 }
drh8dc3e8f2010-01-07 03:53:03 +0000690
691 /* If no existing offsets exactly match the current transaction, find an
692 ** an empty offset in the aAction[] table in which we can add the
693 ** aLookahead[] transaction.
694 */
drhf16371d2009-11-03 19:18:31 +0000695 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000696 /* Look for holes in the aAction[] table that fit the current
697 ** aLookahead[] transaction. Leave i set to the offset of the hole.
698 ** If no holes are found, i is left at p->nAction, which means the
699 ** transaction will be appended. */
700 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000701 if( p->aAction[i].lookahead<0 ){
702 for(j=0; j<p->nLookahead; j++){
703 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
704 if( k<0 ) break;
705 if( p->aAction[k].lookahead>=0 ) break;
706 }
707 if( j<p->nLookahead ) continue;
708 for(j=0; j<p->nAction; j++){
709 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
710 }
711 if( j==p->nAction ){
712 break; /* Fits in empty slots */
713 }
714 }
715 }
716 }
drh8b582012003-10-21 13:16:03 +0000717 /* Insert transaction set at index i. */
718 for(j=0; j<p->nLookahead; j++){
719 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
720 p->aAction[k] = p->aLookahead[j];
721 if( k>=p->nAction ) p->nAction = k+1;
722 }
723 p->nLookahead = 0;
724
725 /* Return the offset that is added to the lookahead in order to get the
726 ** index into yy_action of the action */
727 return i - p->mnLookahead;
728}
729
drh75897232000-05-29 14:26:00 +0000730/********************** From the file "build.c" *****************************/
731/*
732** Routines to construction the finite state machine for the LEMON
733** parser generator.
734*/
735
736/* Find a precedence symbol of every rule in the grammar.
737**
738** Those rules which have a precedence symbol coded in the input
739** grammar using the "[symbol]" construct will already have the
740** rp->precsym field filled. Other rules take as their precedence
741** symbol the first RHS symbol with a defined precedence. If there
742** are not RHS symbols with a defined precedence, the precedence
743** symbol field is left blank.
744*/
icculus9e44cf12010-02-14 17:14:22 +0000745void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000746{
747 struct rule *rp;
748 for(rp=xp->rule; rp; rp=rp->next){
749 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000750 int i, j;
751 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
752 struct symbol *sp = rp->rhs[i];
753 if( sp->type==MULTITERMINAL ){
754 for(j=0; j<sp->nsubsym; j++){
755 if( sp->subsym[j]->prec>=0 ){
756 rp->precsym = sp->subsym[j];
757 break;
758 }
759 }
760 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000761 rp->precsym = rp->rhs[i];
drhf2f105d2012-08-20 15:53:54 +0000762 }
drh75897232000-05-29 14:26:00 +0000763 }
764 }
765 }
766 return;
767}
768
769/* Find all nonterminals which will generate the empty string.
770** Then go back and compute the first sets of every nonterminal.
771** The first set is the set of all terminal symbols which can begin
772** a string generated by that nonterminal.
773*/
icculus9e44cf12010-02-14 17:14:22 +0000774void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000775{
drhfd405312005-11-06 04:06:59 +0000776 int i, j;
drh75897232000-05-29 14:26:00 +0000777 struct rule *rp;
778 int progress;
779
780 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000781 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000782 }
783 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
784 lemp->symbols[i]->firstset = SetNew();
785 }
786
787 /* First compute all lambdas */
788 do{
789 progress = 0;
790 for(rp=lemp->rule; rp; rp=rp->next){
791 if( rp->lhs->lambda ) continue;
792 for(i=0; i<rp->nrhs; i++){
drh7dd1ac62012-01-07 15:17:18 +0000793 struct symbol *sp = rp->rhs[i];
794 assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE );
795 if( sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000796 }
797 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000798 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000799 progress = 1;
800 }
801 }
802 }while( progress );
803
804 /* Now compute all first sets */
805 do{
806 struct symbol *s1, *s2;
807 progress = 0;
808 for(rp=lemp->rule; rp; rp=rp->next){
809 s1 = rp->lhs;
810 for(i=0; i<rp->nrhs; i++){
811 s2 = rp->rhs[i];
812 if( s2->type==TERMINAL ){
813 progress += SetAdd(s1->firstset,s2->index);
814 break;
drhfd405312005-11-06 04:06:59 +0000815 }else if( s2->type==MULTITERMINAL ){
816 for(j=0; j<s2->nsubsym; j++){
817 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
818 }
819 break;
drhf2f105d2012-08-20 15:53:54 +0000820 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000821 if( s1->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000822 }else{
drh75897232000-05-29 14:26:00 +0000823 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000824 if( s2->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +0000825 }
drh75897232000-05-29 14:26:00 +0000826 }
827 }
828 }while( progress );
829 return;
830}
831
832/* Compute all LR(0) states for the grammar. Links
833** are added to between some states so that the LR(1) follow sets
834** can be computed later.
835*/
icculus9e44cf12010-02-14 17:14:22 +0000836PRIVATE struct state *getstate(struct lemon *); /* forward reference */
837void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000838{
839 struct symbol *sp;
840 struct rule *rp;
841
842 Configlist_init();
843
844 /* Find the start symbol */
845 if( lemp->start ){
846 sp = Symbol_find(lemp->start);
847 if( sp==0 ){
848 ErrorMsg(lemp->filename,0,
849"The specified start symbol \"%s\" is not \
850in a nonterminal of the grammar. \"%s\" will be used as the start \
851symbol instead.",lemp->start,lemp->rule->lhs->name);
852 lemp->errorcnt++;
853 sp = lemp->rule->lhs;
854 }
855 }else{
856 sp = lemp->rule->lhs;
857 }
858
859 /* Make sure the start symbol doesn't occur on the right-hand side of
860 ** any rule. Report an error if it does. (YACC would generate a new
861 ** start symbol in this case.) */
862 for(rp=lemp->rule; rp; rp=rp->next){
863 int i;
864 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000865 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000866 ErrorMsg(lemp->filename,0,
867"The start symbol \"%s\" occurs on the \
868right-hand side of a rule. This will result in a parser which \
869does not work properly.",sp->name);
870 lemp->errorcnt++;
871 }
872 }
873 }
874
875 /* The basis configuration set for the first state
876 ** is all rules which have the start symbol as their
877 ** left-hand side */
878 for(rp=sp->rule; rp; rp=rp->nextlhs){
879 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000880 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000881 newcfp = Configlist_addbasis(rp,0);
882 SetAdd(newcfp->fws,0);
883 }
884
885 /* Compute the first state. All other states will be
886 ** computed automatically during the computation of the first one.
887 ** The returned pointer to the first state is not used. */
888 (void)getstate(lemp);
889 return;
890}
891
892/* Return a pointer to a state which is described by the configuration
893** list which has been built from calls to Configlist_add.
894*/
icculus9e44cf12010-02-14 17:14:22 +0000895PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
896PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000897{
898 struct config *cfp, *bp;
899 struct state *stp;
900
901 /* Extract the sorted basis of the new state. The basis was constructed
902 ** by prior calls to "Configlist_addbasis()". */
903 Configlist_sortbasis();
904 bp = Configlist_basis();
905
906 /* Get a state with the same basis */
907 stp = State_find(bp);
908 if( stp ){
909 /* A state with the same basis already exists! Copy all the follow-set
910 ** propagation links from the state under construction into the
911 ** preexisting state, then return a pointer to the preexisting state */
912 struct config *x, *y;
913 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
914 Plink_copy(&y->bplp,x->bplp);
915 Plink_delete(x->fplp);
916 x->fplp = x->bplp = 0;
917 }
918 cfp = Configlist_return();
919 Configlist_eat(cfp);
920 }else{
921 /* This really is a new state. Construct all the details */
922 Configlist_closure(lemp); /* Compute the configuration closure */
923 Configlist_sort(); /* Sort the configuration closure */
924 cfp = Configlist_return(); /* Get a pointer to the config list */
925 stp = State_new(); /* A new state structure */
926 MemoryCheck(stp);
927 stp->bp = bp; /* Remember the configuration basis */
928 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000929 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000930 stp->ap = 0; /* No actions, yet. */
931 State_insert(stp,stp->bp); /* Add to the state table */
932 buildshifts(lemp,stp); /* Recursively compute successor states */
933 }
934 return stp;
935}
936
drhfd405312005-11-06 04:06:59 +0000937/*
938** Return true if two symbols are the same.
939*/
icculus9e44cf12010-02-14 17:14:22 +0000940int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000941{
942 int i;
943 if( a==b ) return 1;
944 if( a->type!=MULTITERMINAL ) return 0;
945 if( b->type!=MULTITERMINAL ) return 0;
946 if( a->nsubsym!=b->nsubsym ) return 0;
947 for(i=0; i<a->nsubsym; i++){
948 if( a->subsym[i]!=b->subsym[i] ) return 0;
949 }
950 return 1;
951}
952
drh75897232000-05-29 14:26:00 +0000953/* Construct all successor states to the given state. A "successor"
954** state is any state which can be reached by a shift action.
955*/
icculus9e44cf12010-02-14 17:14:22 +0000956PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000957{
958 struct config *cfp; /* For looping thru the config closure of "stp" */
959 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000960 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000961 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
962 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
963 struct state *newstp; /* A pointer to a successor state */
964
965 /* Each configuration becomes complete after it contibutes to a successor
966 ** state. Initially, all configurations are incomplete */
967 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
968
969 /* Loop through all configurations of the state "stp" */
970 for(cfp=stp->cfp; cfp; cfp=cfp->next){
971 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
972 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
973 Configlist_reset(); /* Reset the new config set */
974 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
975
976 /* For every configuration in the state "stp" which has the symbol "sp"
977 ** following its dot, add the same configuration to the basis set under
978 ** construction but with the dot shifted one symbol to the right. */
979 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
980 if( bcfp->status==COMPLETE ) continue; /* Already used */
981 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
982 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000983 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000984 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000985 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
986 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000987 }
988
989 /* Get a pointer to the state described by the basis configuration set
990 ** constructed in the preceding loop */
991 newstp = getstate(lemp);
992
993 /* The state "newstp" is reached from the state "stp" by a shift action
994 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000995 if( sp->type==MULTITERMINAL ){
996 int i;
997 for(i=0; i<sp->nsubsym; i++){
998 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
999 }
1000 }else{
1001 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
1002 }
drh75897232000-05-29 14:26:00 +00001003 }
1004}
1005
1006/*
1007** Construct the propagation links
1008*/
icculus9e44cf12010-02-14 17:14:22 +00001009void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001010{
1011 int i;
1012 struct config *cfp, *other;
1013 struct state *stp;
1014 struct plink *plp;
1015
1016 /* Housekeeping detail:
1017 ** Add to every propagate link a pointer back to the state to
1018 ** which the link is attached. */
1019 for(i=0; i<lemp->nstate; i++){
1020 stp = lemp->sorted[i];
1021 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1022 cfp->stp = stp;
1023 }
1024 }
1025
1026 /* Convert all backlinks into forward links. Only the forward
1027 ** links are used in the follow-set computation. */
1028 for(i=0; i<lemp->nstate; i++){
1029 stp = lemp->sorted[i];
1030 for(cfp=stp->cfp; cfp; cfp=cfp->next){
1031 for(plp=cfp->bplp; plp; plp=plp->next){
1032 other = plp->cfp;
1033 Plink_add(&other->fplp,cfp);
1034 }
1035 }
1036 }
1037}
1038
1039/* Compute all followsets.
1040**
1041** A followset is the set of all symbols which can come immediately
1042** after a configuration.
1043*/
icculus9e44cf12010-02-14 17:14:22 +00001044void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001045{
1046 int i;
1047 struct config *cfp;
1048 struct plink *plp;
1049 int progress;
1050 int change;
1051
1052 for(i=0; i<lemp->nstate; i++){
1053 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1054 cfp->status = INCOMPLETE;
1055 }
1056 }
1057
1058 do{
1059 progress = 0;
1060 for(i=0; i<lemp->nstate; i++){
1061 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
1062 if( cfp->status==COMPLETE ) continue;
1063 for(plp=cfp->fplp; plp; plp=plp->next){
1064 change = SetUnion(plp->cfp->fws,cfp->fws);
1065 if( change ){
1066 plp->cfp->status = INCOMPLETE;
1067 progress = 1;
drhf2f105d2012-08-20 15:53:54 +00001068 }
1069 }
drh75897232000-05-29 14:26:00 +00001070 cfp->status = COMPLETE;
1071 }
1072 }
1073 }while( progress );
1074}
1075
drh3cb2f6e2012-01-09 14:19:05 +00001076static int resolve_conflict(struct action *,struct action *);
drh75897232000-05-29 14:26:00 +00001077
1078/* Compute the reduce actions, and resolve conflicts.
1079*/
icculus9e44cf12010-02-14 17:14:22 +00001080void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001081{
1082 int i,j;
1083 struct config *cfp;
1084 struct state *stp;
1085 struct symbol *sp;
1086 struct rule *rp;
1087
1088 /* Add all of the reduce actions
1089 ** A reduce action is added for each element of the followset of
1090 ** a configuration which has its dot at the extreme right.
1091 */
1092 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1093 stp = lemp->sorted[i];
1094 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1095 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1096 for(j=0; j<lemp->nterminal; j++){
1097 if( SetFind(cfp->fws,j) ){
1098 /* Add a reduce action to the state "stp" which will reduce by the
1099 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001100 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001101 }
drhf2f105d2012-08-20 15:53:54 +00001102 }
drh75897232000-05-29 14:26:00 +00001103 }
1104 }
1105 }
1106
1107 /* Add the accepting token */
1108 if( lemp->start ){
1109 sp = Symbol_find(lemp->start);
1110 if( sp==0 ) sp = lemp->rule->lhs;
1111 }else{
1112 sp = lemp->rule->lhs;
1113 }
1114 /* Add to the first state (which is always the starting state of the
1115 ** finite state machine) an action to ACCEPT if the lookahead is the
1116 ** start nonterminal. */
1117 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1118
1119 /* Resolve conflicts */
1120 for(i=0; i<lemp->nstate; i++){
1121 struct action *ap, *nap;
drh75897232000-05-29 14:26:00 +00001122 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001123 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001124 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001125 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001126 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1127 /* The two actions "ap" and "nap" have the same lookahead.
1128 ** Figure out which one should be used */
drh3cb2f6e2012-01-09 14:19:05 +00001129 lemp->nconflict += resolve_conflict(ap,nap);
drh75897232000-05-29 14:26:00 +00001130 }
1131 }
1132 }
1133
1134 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001135 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001136 for(i=0; i<lemp->nstate; i++){
1137 struct action *ap;
1138 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001139 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001140 }
1141 }
1142 for(rp=lemp->rule; rp; rp=rp->next){
1143 if( rp->canReduce ) continue;
1144 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1145 lemp->errorcnt++;
1146 }
1147}
1148
1149/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001150** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001151**
1152** NO LONGER TRUE:
1153** To resolve a conflict, first look to see if either action
1154** is on an error rule. In that case, take the action which
1155** is not associated with the error rule. If neither or both
1156** actions are associated with an error rule, then try to
1157** use precedence to resolve the conflict.
1158**
1159** If either action is a SHIFT, then it must be apx. This
1160** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1161*/
icculus9e44cf12010-02-14 17:14:22 +00001162static int resolve_conflict(
1163 struct action *apx,
drh3cb2f6e2012-01-09 14:19:05 +00001164 struct action *apy
icculus9e44cf12010-02-14 17:14:22 +00001165){
drh75897232000-05-29 14:26:00 +00001166 struct symbol *spx, *spy;
1167 int errcnt = 0;
1168 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001169 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001170 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001171 errcnt++;
1172 }
drh75897232000-05-29 14:26:00 +00001173 if( apx->type==SHIFT && apy->type==REDUCE ){
1174 spx = apx->sp;
1175 spy = apy->x.rp->precsym;
1176 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1177 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001178 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001179 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001180 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001181 apy->type = RD_RESOLVED;
1182 }else if( spx->prec<spy->prec ){
1183 apx->type = SH_RESOLVED;
1184 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1185 apy->type = RD_RESOLVED; /* associativity */
1186 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1187 apx->type = SH_RESOLVED;
1188 }else{
1189 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh62a223e2014-06-09 13:11:40 +00001190 apx->type = ERROR;
drh75897232000-05-29 14:26:00 +00001191 }
1192 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1193 spx = apx->x.rp->precsym;
1194 spy = apy->x.rp->precsym;
1195 if( spx==0 || spy==0 || spx->prec<0 ||
1196 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001197 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001198 errcnt++;
1199 }else if( spx->prec>spy->prec ){
1200 apy->type = RD_RESOLVED;
1201 }else if( spx->prec<spy->prec ){
1202 apx->type = RD_RESOLVED;
1203 }
1204 }else{
drhb59499c2002-02-23 18:45:13 +00001205 assert(
1206 apx->type==SH_RESOLVED ||
1207 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001208 apx->type==SSCONFLICT ||
1209 apx->type==SRCONFLICT ||
1210 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001211 apy->type==SH_RESOLVED ||
1212 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001213 apy->type==SSCONFLICT ||
1214 apy->type==SRCONFLICT ||
1215 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001216 );
1217 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1218 ** REDUCEs on the list. If we reach this point it must be because
1219 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001220 }
1221 return errcnt;
1222}
1223/********************* From the file "configlist.c" *************************/
1224/*
1225** Routines to processing a configuration list and building a state
1226** in the LEMON parser generator.
1227*/
1228
1229static struct config *freelist = 0; /* List of free configurations */
1230static struct config *current = 0; /* Top of list of configurations */
1231static struct config **currentend = 0; /* Last on list of configs */
1232static struct config *basis = 0; /* Top of list of basis configs */
1233static struct config **basisend = 0; /* End of list of basis configs */
1234
1235/* Return a pointer to a new configuration */
1236PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001237 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001238 if( freelist==0 ){
1239 int i;
1240 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001241 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001242 if( freelist==0 ){
1243 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1244 exit(1);
1245 }
1246 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1247 freelist[amt-1].next = 0;
1248 }
icculus9e44cf12010-02-14 17:14:22 +00001249 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001250 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001251 return newcfg;
drh75897232000-05-29 14:26:00 +00001252}
1253
1254/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001255PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001256{
1257 old->next = freelist;
1258 freelist = old;
1259}
1260
1261/* Initialized the configuration list builder */
1262void Configlist_init(){
1263 current = 0;
1264 currentend = &current;
1265 basis = 0;
1266 basisend = &basis;
1267 Configtable_init();
1268 return;
1269}
1270
1271/* Initialized the configuration list builder */
1272void Configlist_reset(){
1273 current = 0;
1274 currentend = &current;
1275 basis = 0;
1276 basisend = &basis;
1277 Configtable_clear(0);
1278 return;
1279}
1280
1281/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001282struct config *Configlist_add(
1283 struct rule *rp, /* The rule */
1284 int dot /* Index into the RHS of the rule where the dot goes */
1285){
drh75897232000-05-29 14:26:00 +00001286 struct config *cfp, model;
1287
1288 assert( currentend!=0 );
1289 model.rp = rp;
1290 model.dot = dot;
1291 cfp = Configtable_find(&model);
1292 if( cfp==0 ){
1293 cfp = newconfig();
1294 cfp->rp = rp;
1295 cfp->dot = dot;
1296 cfp->fws = SetNew();
1297 cfp->stp = 0;
1298 cfp->fplp = cfp->bplp = 0;
1299 cfp->next = 0;
1300 cfp->bp = 0;
1301 *currentend = cfp;
1302 currentend = &cfp->next;
1303 Configtable_insert(cfp);
1304 }
1305 return cfp;
1306}
1307
1308/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001309struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001310{
1311 struct config *cfp, model;
1312
1313 assert( basisend!=0 );
1314 assert( currentend!=0 );
1315 model.rp = rp;
1316 model.dot = dot;
1317 cfp = Configtable_find(&model);
1318 if( cfp==0 ){
1319 cfp = newconfig();
1320 cfp->rp = rp;
1321 cfp->dot = dot;
1322 cfp->fws = SetNew();
1323 cfp->stp = 0;
1324 cfp->fplp = cfp->bplp = 0;
1325 cfp->next = 0;
1326 cfp->bp = 0;
1327 *currentend = cfp;
1328 currentend = &cfp->next;
1329 *basisend = cfp;
1330 basisend = &cfp->bp;
1331 Configtable_insert(cfp);
1332 }
1333 return cfp;
1334}
1335
1336/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001337void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001338{
1339 struct config *cfp, *newcfp;
1340 struct rule *rp, *newrp;
1341 struct symbol *sp, *xsp;
1342 int i, dot;
1343
1344 assert( currentend!=0 );
1345 for(cfp=current; cfp; cfp=cfp->next){
1346 rp = cfp->rp;
1347 dot = cfp->dot;
1348 if( dot>=rp->nrhs ) continue;
1349 sp = rp->rhs[dot];
1350 if( sp->type==NONTERMINAL ){
1351 if( sp->rule==0 && sp!=lemp->errsym ){
1352 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1353 sp->name);
1354 lemp->errorcnt++;
1355 }
1356 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1357 newcfp = Configlist_add(newrp,0);
1358 for(i=dot+1; i<rp->nrhs; i++){
1359 xsp = rp->rhs[i];
1360 if( xsp->type==TERMINAL ){
1361 SetAdd(newcfp->fws,xsp->index);
1362 break;
drhfd405312005-11-06 04:06:59 +00001363 }else if( xsp->type==MULTITERMINAL ){
1364 int k;
1365 for(k=0; k<xsp->nsubsym; k++){
1366 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1367 }
1368 break;
drhf2f105d2012-08-20 15:53:54 +00001369 }else{
drh75897232000-05-29 14:26:00 +00001370 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001371 if( xsp->lambda==LEMON_FALSE ) break;
drhf2f105d2012-08-20 15:53:54 +00001372 }
1373 }
drh75897232000-05-29 14:26:00 +00001374 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1375 }
1376 }
1377 }
1378 return;
1379}
1380
1381/* Sort the configuration list */
1382void Configlist_sort(){
drh25473362015-09-04 18:03:45 +00001383 current = (struct config*)msort((char*)current,(char**)&(current->next),
1384 Configcmp);
drh75897232000-05-29 14:26:00 +00001385 currentend = 0;
1386 return;
1387}
1388
1389/* Sort the basis configuration list */
1390void Configlist_sortbasis(){
drh25473362015-09-04 18:03:45 +00001391 basis = (struct config*)msort((char*)current,(char**)&(current->bp),
1392 Configcmp);
drh75897232000-05-29 14:26:00 +00001393 basisend = 0;
1394 return;
1395}
1396
1397/* Return a pointer to the head of the configuration list and
1398** reset the list */
1399struct config *Configlist_return(){
1400 struct config *old;
1401 old = current;
1402 current = 0;
1403 currentend = 0;
1404 return old;
1405}
1406
1407/* Return a pointer to the head of the configuration list and
1408** reset the list */
1409struct config *Configlist_basis(){
1410 struct config *old;
1411 old = basis;
1412 basis = 0;
1413 basisend = 0;
1414 return old;
1415}
1416
1417/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001418void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001419{
1420 struct config *nextcfp;
1421 for(; cfp; cfp=nextcfp){
1422 nextcfp = cfp->next;
1423 assert( cfp->fplp==0 );
1424 assert( cfp->bplp==0 );
1425 if( cfp->fws ) SetFree(cfp->fws);
1426 deleteconfig(cfp);
1427 }
1428 return;
1429}
1430/***************** From the file "error.c" *********************************/
1431/*
1432** Code for printing error message.
1433*/
1434
drhf9a2e7b2003-04-15 01:49:48 +00001435void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001436 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001437 fprintf(stderr, "%s:%d: ", filename, lineno);
1438 va_start(ap, format);
1439 vfprintf(stderr,format,ap);
1440 va_end(ap);
1441 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001442}
1443/**************** From the file "main.c" ************************************/
1444/*
1445** Main program file for the LEMON parser generator.
1446*/
1447
1448/* Report an out-of-memory condition and abort. This function
1449** is used mostly by the "MemoryCheck" macro in struct.h
1450*/
1451void memory_error(){
1452 fprintf(stderr,"Out of memory. Aborting...\n");
1453 exit(1);
1454}
1455
drh6d08b4d2004-07-20 12:45:22 +00001456static int nDefine = 0; /* Number of -D options on the command line */
1457static char **azDefine = 0; /* Name of the -D macros */
1458
1459/* This routine is called with the argument to each -D command-line option.
1460** Add the macro defined to the azDefine array.
1461*/
1462static void handle_D_option(char *z){
1463 char **paz;
1464 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001465 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001466 if( azDefine==0 ){
1467 fprintf(stderr,"out of memory\n");
1468 exit(1);
1469 }
1470 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001471 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001472 if( *paz==0 ){
1473 fprintf(stderr,"out of memory\n");
1474 exit(1);
1475 }
drh898799f2014-01-10 23:21:00 +00001476 lemon_strcpy(*paz, z);
drh6d08b4d2004-07-20 12:45:22 +00001477 for(z=*paz; *z && *z!='='; z++){}
1478 *z = 0;
1479}
1480
icculus3e143bd2010-02-14 00:48:49 +00001481static char *user_templatename = NULL;
1482static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001483 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001484 if( user_templatename==0 ){
1485 memory_error();
1486 }
drh898799f2014-01-10 23:21:00 +00001487 lemon_strcpy(user_templatename, z);
icculus3e143bd2010-02-14 00:48:49 +00001488}
drh75897232000-05-29 14:26:00 +00001489
drhc75e0162015-09-07 02:23:02 +00001490/* forward reference */
1491static const char *minimum_size_type(int lwr, int upr, int *pnByte);
1492
1493/* Print a single line of the "Parser Stats" output
1494*/
1495static void stats_line(const char *zLabel, int iValue){
1496 int nLabel = lemonStrlen(zLabel);
1497 printf(" %s%.*s %5d\n", zLabel,
1498 35-nLabel, "................................",
1499 iValue);
1500}
1501
drh75897232000-05-29 14:26:00 +00001502/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001503int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001504{
1505 static int version = 0;
1506 static int rpflag = 0;
1507 static int basisflag = 0;
1508 static int compress = 0;
1509 static int quiet = 0;
1510 static int statistics = 0;
1511 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001512 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001513 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001514 static struct s_options options[] = {
1515 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1516 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001517 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
drh0325d392015-01-01 19:11:22 +00001518 {OPT_FSTR, "f", 0, "Ignored. (Placeholder for -f compiler options.)"},
drh75897232000-05-29 14:26:00 +00001519 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
drh0325d392015-01-01 19:11:22 +00001520 {OPT_FSTR, "I", 0, "Ignored. (Placeholder for '-I' compiler options.)"},
shane58543932008-12-10 20:10:04 +00001521 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1522 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh0325d392015-01-01 19:11:22 +00001523 {OPT_FSTR, "O", 0, "Ignored. (Placeholder for '-O' compiler options.)"},
drhf5c4e0f2010-07-18 11:35:53 +00001524 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1525 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001526 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001527 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001528 {OPT_FLAG, "s", (char*)&statistics,
1529 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001530 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
drh0325d392015-01-01 19:11:22 +00001531 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
1532 {OPT_FSTR, "W", 0, "Ignored. (Placeholder for '-W' compiler options.)"},
drh75897232000-05-29 14:26:00 +00001533 {OPT_FLAG,0,0,0}
1534 };
1535 int i;
icculus42585cf2010-02-14 05:19:56 +00001536 int exitcode;
drh75897232000-05-29 14:26:00 +00001537 struct lemon lem;
1538
drhb0c86772000-06-02 23:21:26 +00001539 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001540 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001541 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001542 exit(0);
1543 }
drhb0c86772000-06-02 23:21:26 +00001544 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001545 fprintf(stderr,"Exactly one filename argument is required.\n");
1546 exit(1);
1547 }
drh954f6b42006-06-13 13:27:46 +00001548 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001549 lem.errorcnt = 0;
1550
1551 /* Initialize the machine */
1552 Strsafe_init();
1553 Symbol_init();
1554 State_init();
1555 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001556 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001557 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001558 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001559 Symbol_new("$");
1560 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001561 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001562
1563 /* Parse the input file */
1564 Parse(&lem);
1565 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001566 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001567 fprintf(stderr,"Empty grammar.\n");
1568 exit(1);
1569 }
1570
1571 /* Count and index the symbols of the grammar */
drh75897232000-05-29 14:26:00 +00001572 Symbol_new("{default}");
drh61f92cd2014-01-11 03:06:18 +00001573 lem.nsymbol = Symbol_count();
drh75897232000-05-29 14:26:00 +00001574 lem.symbols = Symbol_arrayof();
drh61f92cd2014-01-11 03:06:18 +00001575 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1576 qsort(lem.symbols,lem.nsymbol,sizeof(struct symbol*), Symbolcmpp);
1577 for(i=0; i<lem.nsymbol; i++) lem.symbols[i]->index = i;
1578 while( lem.symbols[i-1]->type==MULTITERMINAL ){ i--; }
1579 assert( strcmp(lem.symbols[i-1]->name,"{default}")==0 );
1580 lem.nsymbol = i - 1;
drh75897232000-05-29 14:26:00 +00001581 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1582 lem.nterminal = i;
1583
1584 /* Generate a reprint of the grammar, if requested on the command line */
1585 if( rpflag ){
1586 Reprint(&lem);
1587 }else{
1588 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001589 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001590
1591 /* Find the precedence for every production rule (that has one) */
1592 FindRulePrecedences(&lem);
1593
1594 /* Compute the lambda-nonterminals and the first-sets for every
1595 ** nonterminal */
1596 FindFirstSets(&lem);
1597
1598 /* Compute all LR(0) states. Also record follow-set propagation
1599 ** links so that the follow-set can be computed later */
1600 lem.nstate = 0;
1601 FindStates(&lem);
1602 lem.sorted = State_arrayof();
1603
1604 /* Tie up loose ends on the propagation links */
1605 FindLinks(&lem);
1606
1607 /* Compute the follow set of every reducible configuration */
1608 FindFollowSets(&lem);
1609
1610 /* Compute the action tables */
1611 FindActions(&lem);
1612
1613 /* Compress the action tables */
1614 if( compress==0 ) CompressTables(&lem);
1615
drhada354d2005-11-05 15:03:59 +00001616 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001617 ** occur at the end. This is an optimization that helps make the
1618 ** generated parser tables smaller. */
1619 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001620
drh75897232000-05-29 14:26:00 +00001621 /* Generate a report of the parser generated. (the "y.output" file) */
1622 if( !quiet ) ReportOutput(&lem);
1623
1624 /* Generate the source code for the parser */
1625 ReportTable(&lem, mhflag);
1626
1627 /* Produce a header file for use by the scanner. (This step is
1628 ** omitted if the "-m" option is used because makeheaders will
1629 ** generate the file for us.) */
1630 if( !mhflag ) ReportHeader(&lem);
1631 }
1632 if( statistics ){
drhc75e0162015-09-07 02:23:02 +00001633 printf("Parser statistics:\n");
1634 stats_line("terminal symbols", lem.nterminal);
1635 stats_line("non-terminal symbols", lem.nsymbol - lem.nterminal);
1636 stats_line("total symbols", lem.nsymbol);
1637 stats_line("rules", lem.nrule);
drh3bd48ab2015-09-07 18:23:37 +00001638 stats_line("states", lem.nxstate);
drhc75e0162015-09-07 02:23:02 +00001639 stats_line("conflicts", lem.nconflict);
1640 stats_line("action table entries", lem.nactiontab);
1641 stats_line("total table size (bytes)", lem.tablesize);
drh75897232000-05-29 14:26:00 +00001642 }
icculus8e158022010-02-16 16:09:03 +00001643 if( lem.nconflict > 0 ){
1644 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001645 }
1646
1647 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001648 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001649 exit(exitcode);
1650 return (exitcode);
drh75897232000-05-29 14:26:00 +00001651}
1652/******************** From the file "msort.c" *******************************/
1653/*
1654** A generic merge-sort program.
1655**
1656** USAGE:
1657** Let "ptr" be a pointer to some structure which is at the head of
1658** a null-terminated list. Then to sort the list call:
1659**
1660** ptr = msort(ptr,&(ptr->next),cmpfnc);
1661**
1662** In the above, "cmpfnc" is a pointer to a function which compares
1663** two instances of the structure and returns an integer, as in
1664** strcmp. The second argument is a pointer to the pointer to the
1665** second element of the linked list. This address is used to compute
1666** the offset to the "next" field within the structure. The offset to
1667** the "next" field must be constant for all structures in the list.
1668**
1669** The function returns a new pointer which is the head of the list
1670** after sorting.
1671**
1672** ALGORITHM:
1673** Merge-sort.
1674*/
1675
1676/*
1677** Return a pointer to the next structure in the linked list.
1678*/
drhd25d6922012-04-18 09:59:56 +00001679#define NEXT(A) (*(char**)(((char*)A)+offset))
drh75897232000-05-29 14:26:00 +00001680
1681/*
1682** Inputs:
1683** a: A sorted, null-terminated linked list. (May be null).
1684** b: A sorted, null-terminated linked list. (May be null).
1685** cmp: A pointer to the comparison function.
1686** offset: Offset in the structure to the "next" field.
1687**
1688** Return Value:
1689** A pointer to the head of a sorted list containing the elements
1690** of both a and b.
1691**
1692** Side effects:
1693** The "next" pointers for elements in the lists a and b are
1694** changed.
1695*/
drhe9278182007-07-18 18:16:29 +00001696static char *merge(
1697 char *a,
1698 char *b,
1699 int (*cmp)(const char*,const char*),
1700 int offset
1701){
drh75897232000-05-29 14:26:00 +00001702 char *ptr, *head;
1703
1704 if( a==0 ){
1705 head = b;
1706 }else if( b==0 ){
1707 head = a;
1708 }else{
drhe594bc32009-11-03 13:02:25 +00001709 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001710 ptr = a;
1711 a = NEXT(a);
1712 }else{
1713 ptr = b;
1714 b = NEXT(b);
1715 }
1716 head = ptr;
1717 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001718 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001719 NEXT(ptr) = a;
1720 ptr = a;
1721 a = NEXT(a);
1722 }else{
1723 NEXT(ptr) = b;
1724 ptr = b;
1725 b = NEXT(b);
1726 }
1727 }
1728 if( a ) NEXT(ptr) = a;
1729 else NEXT(ptr) = b;
1730 }
1731 return head;
1732}
1733
1734/*
1735** Inputs:
1736** list: Pointer to a singly-linked list of structures.
1737** next: Pointer to pointer to the second element of the list.
1738** cmp: A comparison function.
1739**
1740** Return Value:
1741** A pointer to the head of a sorted list containing the elements
1742** orginally in list.
1743**
1744** Side effects:
1745** The "next" pointers for elements in list are changed.
1746*/
1747#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001748static char *msort(
1749 char *list,
1750 char **next,
1751 int (*cmp)(const char*,const char*)
1752){
drhba99af52001-10-25 20:37:16 +00001753 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001754 char *ep;
1755 char *set[LISTSIZE];
1756 int i;
drh1cc0d112015-03-31 15:15:48 +00001757 offset = (unsigned long)((char*)next - (char*)list);
drh75897232000-05-29 14:26:00 +00001758 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1759 while( list ){
1760 ep = list;
1761 list = NEXT(list);
1762 NEXT(ep) = 0;
1763 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1764 ep = merge(ep,set[i],cmp,offset);
1765 set[i] = 0;
1766 }
1767 set[i] = ep;
1768 }
1769 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001770 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001771 return ep;
1772}
1773/************************ From the file "option.c" **************************/
1774static char **argv;
1775static struct s_options *op;
1776static FILE *errstream;
1777
1778#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1779
1780/*
1781** Print the command line with a carrot pointing to the k-th character
1782** of the n-th field.
1783*/
icculus9e44cf12010-02-14 17:14:22 +00001784static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001785{
1786 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001787 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001788 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001789 for(i=1; i<n && argv[i]; i++){
1790 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001791 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001792 }
1793 spcnt += k;
1794 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1795 if( spcnt<20 ){
1796 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1797 }else{
1798 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1799 }
1800}
1801
1802/*
1803** Return the index of the N-th non-switch argument. Return -1
1804** if N is out of range.
1805*/
icculus9e44cf12010-02-14 17:14:22 +00001806static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001807{
1808 int i;
1809 int dashdash = 0;
1810 if( argv!=0 && *argv!=0 ){
1811 for(i=1; argv[i]; i++){
1812 if( dashdash || !ISOPT(argv[i]) ){
1813 if( n==0 ) return i;
1814 n--;
1815 }
1816 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1817 }
1818 }
1819 return -1;
1820}
1821
1822static char emsg[] = "Command line syntax error: ";
1823
1824/*
1825** Process a flag command line argument.
1826*/
icculus9e44cf12010-02-14 17:14:22 +00001827static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001828{
1829 int v;
1830 int errcnt = 0;
1831 int j;
1832 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001833 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001834 }
1835 v = argv[i][0]=='-' ? 1 : 0;
1836 if( op[j].label==0 ){
1837 if( err ){
1838 fprintf(err,"%sundefined option.\n",emsg);
1839 errline(i,1,err);
1840 }
1841 errcnt++;
drh0325d392015-01-01 19:11:22 +00001842 }else if( op[j].arg==0 ){
1843 /* Ignore this option */
drh75897232000-05-29 14:26:00 +00001844 }else if( op[j].type==OPT_FLAG ){
1845 *((int*)op[j].arg) = v;
1846 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001847 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001848 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001849 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001850 }else{
1851 if( err ){
1852 fprintf(err,"%smissing argument on switch.\n",emsg);
1853 errline(i,1,err);
1854 }
1855 errcnt++;
1856 }
1857 return errcnt;
1858}
1859
1860/*
1861** Process a command line switch which has an argument.
1862*/
icculus9e44cf12010-02-14 17:14:22 +00001863static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001864{
1865 int lv = 0;
1866 double dv = 0.0;
1867 char *sv = 0, *end;
1868 char *cp;
1869 int j;
1870 int errcnt = 0;
1871 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001872 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001873 *cp = 0;
1874 for(j=0; op[j].label; j++){
1875 if( strcmp(argv[i],op[j].label)==0 ) break;
1876 }
1877 *cp = '=';
1878 if( op[j].label==0 ){
1879 if( err ){
1880 fprintf(err,"%sundefined option.\n",emsg);
1881 errline(i,0,err);
1882 }
1883 errcnt++;
1884 }else{
1885 cp++;
1886 switch( op[j].type ){
1887 case OPT_FLAG:
1888 case OPT_FFLAG:
1889 if( err ){
1890 fprintf(err,"%soption requires an argument.\n",emsg);
1891 errline(i,0,err);
1892 }
1893 errcnt++;
1894 break;
1895 case OPT_DBL:
1896 case OPT_FDBL:
1897 dv = strtod(cp,&end);
1898 if( *end ){
1899 if( err ){
drh25473362015-09-04 18:03:45 +00001900 fprintf(err,
1901 "%sillegal character in floating-point argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001902 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001903 }
1904 errcnt++;
1905 }
1906 break;
1907 case OPT_INT:
1908 case OPT_FINT:
1909 lv = strtol(cp,&end,0);
1910 if( *end ){
1911 if( err ){
1912 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drh1cc0d112015-03-31 15:15:48 +00001913 errline(i,(int)((char*)end-(char*)argv[i]),err);
drh75897232000-05-29 14:26:00 +00001914 }
1915 errcnt++;
1916 }
1917 break;
1918 case OPT_STR:
1919 case OPT_FSTR:
1920 sv = cp;
1921 break;
1922 }
1923 switch( op[j].type ){
1924 case OPT_FLAG:
1925 case OPT_FFLAG:
1926 break;
1927 case OPT_DBL:
1928 *(double*)(op[j].arg) = dv;
1929 break;
1930 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001931 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001932 break;
1933 case OPT_INT:
1934 *(int*)(op[j].arg) = lv;
1935 break;
1936 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001937 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001938 break;
1939 case OPT_STR:
1940 *(char**)(op[j].arg) = sv;
1941 break;
1942 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001943 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001944 break;
1945 }
1946 }
1947 return errcnt;
1948}
1949
icculus9e44cf12010-02-14 17:14:22 +00001950int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001951{
1952 int errcnt = 0;
1953 argv = a;
1954 op = o;
1955 errstream = err;
1956 if( argv && *argv && op ){
1957 int i;
1958 for(i=1; argv[i]; i++){
1959 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1960 errcnt += handleflags(i,err);
1961 }else if( strchr(argv[i],'=') ){
1962 errcnt += handleswitch(i,err);
1963 }
1964 }
1965 }
1966 if( errcnt>0 ){
1967 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001968 OptPrint();
drh75897232000-05-29 14:26:00 +00001969 exit(1);
1970 }
1971 return 0;
1972}
1973
drhb0c86772000-06-02 23:21:26 +00001974int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001975 int cnt = 0;
1976 int dashdash = 0;
1977 int i;
1978 if( argv!=0 && argv[0]!=0 ){
1979 for(i=1; argv[i]; i++){
1980 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1981 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1982 }
1983 }
1984 return cnt;
1985}
1986
icculus9e44cf12010-02-14 17:14:22 +00001987char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001988{
1989 int i;
1990 i = argindex(n);
1991 return i>=0 ? argv[i] : 0;
1992}
1993
icculus9e44cf12010-02-14 17:14:22 +00001994void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001995{
1996 int i;
1997 i = argindex(n);
1998 if( i>=0 ) errline(i,0,errstream);
1999}
2000
drhb0c86772000-06-02 23:21:26 +00002001void OptPrint(){
drh75897232000-05-29 14:26:00 +00002002 int i;
2003 int max, len;
2004 max = 0;
2005 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00002006 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00002007 switch( op[i].type ){
2008 case OPT_FLAG:
2009 case OPT_FFLAG:
2010 break;
2011 case OPT_INT:
2012 case OPT_FINT:
2013 len += 9; /* length of "<integer>" */
2014 break;
2015 case OPT_DBL:
2016 case OPT_FDBL:
2017 len += 6; /* length of "<real>" */
2018 break;
2019 case OPT_STR:
2020 case OPT_FSTR:
2021 len += 8; /* length of "<string>" */
2022 break;
2023 }
2024 if( len>max ) max = len;
2025 }
2026 for(i=0; op[i].label; i++){
2027 switch( op[i].type ){
2028 case OPT_FLAG:
2029 case OPT_FFLAG:
2030 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
2031 break;
2032 case OPT_INT:
2033 case OPT_FINT:
drh0325d392015-01-01 19:11:22 +00002034 fprintf(errstream," -%s<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002035 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002036 break;
2037 case OPT_DBL:
2038 case OPT_FDBL:
drh0325d392015-01-01 19:11:22 +00002039 fprintf(errstream," -%s<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002040 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002041 break;
2042 case OPT_STR:
2043 case OPT_FSTR:
drh0325d392015-01-01 19:11:22 +00002044 fprintf(errstream," -%s<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00002045 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00002046 break;
2047 }
2048 }
2049}
2050/*********************** From the file "parse.c" ****************************/
2051/*
2052** Input file parser for the LEMON parser generator.
2053*/
2054
2055/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002056enum e_state {
2057 INITIALIZE,
2058 WAITING_FOR_DECL_OR_RULE,
2059 WAITING_FOR_DECL_KEYWORD,
2060 WAITING_FOR_DECL_ARG,
2061 WAITING_FOR_PRECEDENCE_SYMBOL,
2062 WAITING_FOR_ARROW,
2063 IN_RHS,
2064 LHS_ALIAS_1,
2065 LHS_ALIAS_2,
2066 LHS_ALIAS_3,
2067 RHS_ALIAS_1,
2068 RHS_ALIAS_2,
2069 PRECEDENCE_MARK_1,
2070 PRECEDENCE_MARK_2,
2071 RESYNC_AFTER_RULE_ERROR,
2072 RESYNC_AFTER_DECL_ERROR,
2073 WAITING_FOR_DESTRUCTOR_SYMBOL,
2074 WAITING_FOR_DATATYPE_SYMBOL,
2075 WAITING_FOR_FALLBACK_ID,
drh61f92cd2014-01-11 03:06:18 +00002076 WAITING_FOR_WILDCARD_ID,
2077 WAITING_FOR_CLASS_ID,
2078 WAITING_FOR_CLASS_TOKEN
icculus9e44cf12010-02-14 17:14:22 +00002079};
drh75897232000-05-29 14:26:00 +00002080struct pstate {
2081 char *filename; /* Name of the input file */
2082 int tokenlineno; /* Linenumber at which current token starts */
2083 int errorcnt; /* Number of errors so far */
2084 char *tokenstart; /* Text of current token */
2085 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002086 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002087 struct symbol *fallback; /* The fallback token */
drh61f92cd2014-01-11 03:06:18 +00002088 struct symbol *tkclass; /* Token class symbol */
drh75897232000-05-29 14:26:00 +00002089 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002090 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002091 int nrhs; /* Number of right-hand side symbols seen */
2092 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002093 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002094 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002095 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002096 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002097 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002098 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002099 enum e_assoc declassoc; /* Assign this association to decl arguments */
2100 int preccounter; /* Assign this precedence to decl arguments */
2101 struct rule *firstrule; /* Pointer to first rule in the grammar */
2102 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2103};
2104
2105/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002106static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002107{
icculus9e44cf12010-02-14 17:14:22 +00002108 const char *x;
drh75897232000-05-29 14:26:00 +00002109 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2110#if 0
2111 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2112 x,psp->state);
2113#endif
2114 switch( psp->state ){
2115 case INITIALIZE:
2116 psp->prevrule = 0;
2117 psp->preccounter = 0;
2118 psp->firstrule = psp->lastrule = 0;
2119 psp->gp->nrule = 0;
2120 /* Fall thru to next case */
2121 case WAITING_FOR_DECL_OR_RULE:
2122 if( x[0]=='%' ){
2123 psp->state = WAITING_FOR_DECL_KEYWORD;
2124 }else if( islower(x[0]) ){
2125 psp->lhs = Symbol_new(x);
2126 psp->nrhs = 0;
2127 psp->lhsalias = 0;
2128 psp->state = WAITING_FOR_ARROW;
2129 }else if( x[0]=='{' ){
2130 if( psp->prevrule==0 ){
2131 ErrorMsg(psp->filename,psp->tokenlineno,
drh3cb2f6e2012-01-09 14:19:05 +00002132"There is no prior rule upon which to attach the code \
drh75897232000-05-29 14:26:00 +00002133fragment which begins on this line.");
2134 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002135 }else if( psp->prevrule->code!=0 ){
drh75897232000-05-29 14:26:00 +00002136 ErrorMsg(psp->filename,psp->tokenlineno,
2137"Code fragment beginning on this line is not the first \
2138to follow the previous rule.");
2139 psp->errorcnt++;
2140 }else{
2141 psp->prevrule->line = psp->tokenlineno;
2142 psp->prevrule->code = &x[1];
drhf2f105d2012-08-20 15:53:54 +00002143 }
drh75897232000-05-29 14:26:00 +00002144 }else if( x[0]=='[' ){
2145 psp->state = PRECEDENCE_MARK_1;
2146 }else{
2147 ErrorMsg(psp->filename,psp->tokenlineno,
2148 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2149 x);
2150 psp->errorcnt++;
2151 }
2152 break;
2153 case PRECEDENCE_MARK_1:
2154 if( !isupper(x[0]) ){
2155 ErrorMsg(psp->filename,psp->tokenlineno,
2156 "The precedence symbol must be a terminal.");
2157 psp->errorcnt++;
2158 }else if( psp->prevrule==0 ){
2159 ErrorMsg(psp->filename,psp->tokenlineno,
2160 "There is no prior rule to assign precedence \"[%s]\".",x);
2161 psp->errorcnt++;
2162 }else if( psp->prevrule->precsym!=0 ){
2163 ErrorMsg(psp->filename,psp->tokenlineno,
2164"Precedence mark on this line is not the first \
2165to follow the previous rule.");
2166 psp->errorcnt++;
2167 }else{
2168 psp->prevrule->precsym = Symbol_new(x);
2169 }
2170 psp->state = PRECEDENCE_MARK_2;
2171 break;
2172 case PRECEDENCE_MARK_2:
2173 if( x[0]!=']' ){
2174 ErrorMsg(psp->filename,psp->tokenlineno,
2175 "Missing \"]\" on precedence mark.");
2176 psp->errorcnt++;
2177 }
2178 psp->state = WAITING_FOR_DECL_OR_RULE;
2179 break;
2180 case WAITING_FOR_ARROW:
2181 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2182 psp->state = IN_RHS;
2183 }else if( x[0]=='(' ){
2184 psp->state = LHS_ALIAS_1;
2185 }else{
2186 ErrorMsg(psp->filename,psp->tokenlineno,
2187 "Expected to see a \":\" following the LHS symbol \"%s\".",
2188 psp->lhs->name);
2189 psp->errorcnt++;
2190 psp->state = RESYNC_AFTER_RULE_ERROR;
2191 }
2192 break;
2193 case LHS_ALIAS_1:
2194 if( isalpha(x[0]) ){
2195 psp->lhsalias = x;
2196 psp->state = LHS_ALIAS_2;
2197 }else{
2198 ErrorMsg(psp->filename,psp->tokenlineno,
2199 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2200 x,psp->lhs->name);
2201 psp->errorcnt++;
2202 psp->state = RESYNC_AFTER_RULE_ERROR;
2203 }
2204 break;
2205 case LHS_ALIAS_2:
2206 if( x[0]==')' ){
2207 psp->state = LHS_ALIAS_3;
2208 }else{
2209 ErrorMsg(psp->filename,psp->tokenlineno,
2210 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2211 psp->errorcnt++;
2212 psp->state = RESYNC_AFTER_RULE_ERROR;
2213 }
2214 break;
2215 case LHS_ALIAS_3:
2216 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2217 psp->state = IN_RHS;
2218 }else{
2219 ErrorMsg(psp->filename,psp->tokenlineno,
2220 "Missing \"->\" following: \"%s(%s)\".",
2221 psp->lhs->name,psp->lhsalias);
2222 psp->errorcnt++;
2223 psp->state = RESYNC_AFTER_RULE_ERROR;
2224 }
2225 break;
2226 case IN_RHS:
2227 if( x[0]=='.' ){
2228 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002229 rp = (struct rule *)calloc( sizeof(struct rule) +
2230 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002231 if( rp==0 ){
2232 ErrorMsg(psp->filename,psp->tokenlineno,
2233 "Can't allocate enough memory for this rule.");
2234 psp->errorcnt++;
2235 psp->prevrule = 0;
drhf2f105d2012-08-20 15:53:54 +00002236 }else{
drh75897232000-05-29 14:26:00 +00002237 int i;
2238 rp->ruleline = psp->tokenlineno;
2239 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002240 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002241 for(i=0; i<psp->nrhs; i++){
2242 rp->rhs[i] = psp->rhs[i];
2243 rp->rhsalias[i] = psp->alias[i];
drhf2f105d2012-08-20 15:53:54 +00002244 }
drh75897232000-05-29 14:26:00 +00002245 rp->lhs = psp->lhs;
2246 rp->lhsalias = psp->lhsalias;
2247 rp->nrhs = psp->nrhs;
2248 rp->code = 0;
2249 rp->precsym = 0;
2250 rp->index = psp->gp->nrule++;
2251 rp->nextlhs = rp->lhs->rule;
2252 rp->lhs->rule = rp;
2253 rp->next = 0;
2254 if( psp->firstrule==0 ){
2255 psp->firstrule = psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002256 }else{
drh75897232000-05-29 14:26:00 +00002257 psp->lastrule->next = rp;
2258 psp->lastrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002259 }
drh75897232000-05-29 14:26:00 +00002260 psp->prevrule = rp;
drhf2f105d2012-08-20 15:53:54 +00002261 }
drh75897232000-05-29 14:26:00 +00002262 psp->state = WAITING_FOR_DECL_OR_RULE;
2263 }else if( isalpha(x[0]) ){
2264 if( psp->nrhs>=MAXRHS ){
2265 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002266 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002267 x);
2268 psp->errorcnt++;
2269 psp->state = RESYNC_AFTER_RULE_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002270 }else{
drh75897232000-05-29 14:26:00 +00002271 psp->rhs[psp->nrhs] = Symbol_new(x);
2272 psp->alias[psp->nrhs] = 0;
2273 psp->nrhs++;
drhf2f105d2012-08-20 15:53:54 +00002274 }
drhfd405312005-11-06 04:06:59 +00002275 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2276 struct symbol *msp = psp->rhs[psp->nrhs-1];
2277 if( msp->type!=MULTITERMINAL ){
2278 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002279 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002280 memset(msp, 0, sizeof(*msp));
2281 msp->type = MULTITERMINAL;
2282 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002283 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002284 msp->subsym[0] = origsp;
2285 msp->name = origsp->name;
2286 psp->rhs[psp->nrhs-1] = msp;
2287 }
2288 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002289 msp->subsym = (struct symbol **) realloc(msp->subsym,
2290 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002291 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2292 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2293 ErrorMsg(psp->filename,psp->tokenlineno,
2294 "Cannot form a compound containing a non-terminal");
2295 psp->errorcnt++;
2296 }
drh75897232000-05-29 14:26:00 +00002297 }else if( x[0]=='(' && psp->nrhs>0 ){
2298 psp->state = RHS_ALIAS_1;
2299 }else{
2300 ErrorMsg(psp->filename,psp->tokenlineno,
2301 "Illegal character on RHS of rule: \"%s\".",x);
2302 psp->errorcnt++;
2303 psp->state = RESYNC_AFTER_RULE_ERROR;
2304 }
2305 break;
2306 case RHS_ALIAS_1:
2307 if( isalpha(x[0]) ){
2308 psp->alias[psp->nrhs-1] = x;
2309 psp->state = RHS_ALIAS_2;
2310 }else{
2311 ErrorMsg(psp->filename,psp->tokenlineno,
2312 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2313 x,psp->rhs[psp->nrhs-1]->name);
2314 psp->errorcnt++;
2315 psp->state = RESYNC_AFTER_RULE_ERROR;
2316 }
2317 break;
2318 case RHS_ALIAS_2:
2319 if( x[0]==')' ){
2320 psp->state = IN_RHS;
2321 }else{
2322 ErrorMsg(psp->filename,psp->tokenlineno,
2323 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2324 psp->errorcnt++;
2325 psp->state = RESYNC_AFTER_RULE_ERROR;
2326 }
2327 break;
2328 case WAITING_FOR_DECL_KEYWORD:
2329 if( isalpha(x[0]) ){
2330 psp->declkeyword = x;
2331 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002332 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002333 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002334 psp->state = WAITING_FOR_DECL_ARG;
2335 if( strcmp(x,"name")==0 ){
2336 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002337 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002338 }else if( strcmp(x,"include")==0 ){
drh75897232000-05-29 14:26:00 +00002339 psp->declargslot = &(psp->gp->include);
drhf2f105d2012-08-20 15:53:54 +00002340 }else if( strcmp(x,"code")==0 ){
drh75897232000-05-29 14:26:00 +00002341 psp->declargslot = &(psp->gp->extracode);
drhf2f105d2012-08-20 15:53:54 +00002342 }else if( strcmp(x,"token_destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002343 psp->declargslot = &psp->gp->tokendest;
drhf2f105d2012-08-20 15:53:54 +00002344 }else if( strcmp(x,"default_destructor")==0 ){
drh960e8c62001-04-03 16:53:21 +00002345 psp->declargslot = &psp->gp->vardest;
drhf2f105d2012-08-20 15:53:54 +00002346 }else if( strcmp(x,"token_prefix")==0 ){
drh75897232000-05-29 14:26:00 +00002347 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002348 psp->insertLineMacro = 0;
drhf2f105d2012-08-20 15:53:54 +00002349 }else if( strcmp(x,"syntax_error")==0 ){
drh75897232000-05-29 14:26:00 +00002350 psp->declargslot = &(psp->gp->error);
drhf2f105d2012-08-20 15:53:54 +00002351 }else if( strcmp(x,"parse_accept")==0 ){
drh75897232000-05-29 14:26:00 +00002352 psp->declargslot = &(psp->gp->accept);
drhf2f105d2012-08-20 15:53:54 +00002353 }else if( strcmp(x,"parse_failure")==0 ){
drh75897232000-05-29 14:26:00 +00002354 psp->declargslot = &(psp->gp->failure);
drhf2f105d2012-08-20 15:53:54 +00002355 }else if( strcmp(x,"stack_overflow")==0 ){
drh75897232000-05-29 14:26:00 +00002356 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002357 }else if( strcmp(x,"extra_argument")==0 ){
2358 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002359 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002360 }else if( strcmp(x,"token_type")==0 ){
2361 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002362 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002363 }else if( strcmp(x,"default_type")==0 ){
2364 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002365 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002366 }else if( strcmp(x,"stack_size")==0 ){
2367 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002368 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002369 }else if( strcmp(x,"start_symbol")==0 ){
2370 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002371 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002372 }else if( strcmp(x,"left")==0 ){
2373 psp->preccounter++;
2374 psp->declassoc = LEFT;
2375 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2376 }else if( strcmp(x,"right")==0 ){
2377 psp->preccounter++;
2378 psp->declassoc = RIGHT;
2379 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2380 }else if( strcmp(x,"nonassoc")==0 ){
2381 psp->preccounter++;
2382 psp->declassoc = NONE;
2383 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002384 }else if( strcmp(x,"destructor")==0 ){
drh75897232000-05-29 14:26:00 +00002385 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
drhf2f105d2012-08-20 15:53:54 +00002386 }else if( strcmp(x,"type")==0 ){
drh75897232000-05-29 14:26:00 +00002387 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002388 }else if( strcmp(x,"fallback")==0 ){
2389 psp->fallback = 0;
2390 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002391 }else if( strcmp(x,"wildcard")==0 ){
2392 psp->state = WAITING_FOR_WILDCARD_ID;
drh61f92cd2014-01-11 03:06:18 +00002393 }else if( strcmp(x,"token_class")==0 ){
2394 psp->state = WAITING_FOR_CLASS_ID;
drh75897232000-05-29 14:26:00 +00002395 }else{
2396 ErrorMsg(psp->filename,psp->tokenlineno,
2397 "Unknown declaration keyword: \"%%%s\".",x);
2398 psp->errorcnt++;
2399 psp->state = RESYNC_AFTER_DECL_ERROR;
drhf2f105d2012-08-20 15:53:54 +00002400 }
drh75897232000-05-29 14:26:00 +00002401 }else{
2402 ErrorMsg(psp->filename,psp->tokenlineno,
2403 "Illegal declaration keyword: \"%s\".",x);
2404 psp->errorcnt++;
2405 psp->state = RESYNC_AFTER_DECL_ERROR;
2406 }
2407 break;
2408 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2409 if( !isalpha(x[0]) ){
2410 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002411 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002412 psp->errorcnt++;
2413 psp->state = RESYNC_AFTER_DECL_ERROR;
2414 }else{
icculusd286fa62010-03-03 17:06:32 +00002415 struct symbol *sp = Symbol_new(x);
2416 psp->declargslot = &sp->destructor;
2417 psp->decllinenoslot = &sp->destLineno;
2418 psp->insertLineMacro = 1;
2419 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002420 }
2421 break;
2422 case WAITING_FOR_DATATYPE_SYMBOL:
2423 if( !isalpha(x[0]) ){
2424 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002425 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002426 psp->errorcnt++;
2427 psp->state = RESYNC_AFTER_DECL_ERROR;
2428 }else{
icculus866bf1e2010-02-17 20:31:32 +00002429 struct symbol *sp = Symbol_find(x);
2430 if((sp) && (sp->datatype)){
2431 ErrorMsg(psp->filename,psp->tokenlineno,
2432 "Symbol %%type \"%s\" already defined", x);
2433 psp->errorcnt++;
2434 psp->state = RESYNC_AFTER_DECL_ERROR;
2435 }else{
2436 if (!sp){
2437 sp = Symbol_new(x);
2438 }
2439 psp->declargslot = &sp->datatype;
2440 psp->insertLineMacro = 0;
2441 psp->state = WAITING_FOR_DECL_ARG;
2442 }
drh75897232000-05-29 14:26:00 +00002443 }
2444 break;
2445 case WAITING_FOR_PRECEDENCE_SYMBOL:
2446 if( x[0]=='.' ){
2447 psp->state = WAITING_FOR_DECL_OR_RULE;
2448 }else if( isupper(x[0]) ){
2449 struct symbol *sp;
2450 sp = Symbol_new(x);
2451 if( sp->prec>=0 ){
2452 ErrorMsg(psp->filename,psp->tokenlineno,
2453 "Symbol \"%s\" has already be given a precedence.",x);
2454 psp->errorcnt++;
drhf2f105d2012-08-20 15:53:54 +00002455 }else{
drh75897232000-05-29 14:26:00 +00002456 sp->prec = psp->preccounter;
2457 sp->assoc = psp->declassoc;
drhf2f105d2012-08-20 15:53:54 +00002458 }
drh75897232000-05-29 14:26:00 +00002459 }else{
2460 ErrorMsg(psp->filename,psp->tokenlineno,
2461 "Can't assign a precedence to \"%s\".",x);
2462 psp->errorcnt++;
2463 }
2464 break;
2465 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002466 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002467 const char *zOld, *zNew;
2468 char *zBuf, *z;
mistachkin2318d332015-01-12 18:02:52 +00002469 int nOld, n, nLine = 0, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002470 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002471 char zLine[50];
2472 zNew = x;
2473 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002474 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002475 if( *psp->declargslot ){
2476 zOld = *psp->declargslot;
2477 }else{
2478 zOld = "";
2479 }
drh87cf1372008-08-13 20:09:06 +00002480 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002481 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002482 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002483 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2484 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002485 for(z=psp->filename, nBack=0; *z; z++){
2486 if( *z=='\\' ) nBack++;
2487 }
drh898799f2014-01-10 23:21:00 +00002488 lemon_sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002489 nLine = lemonStrlen(zLine);
2490 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002491 }
icculus9e44cf12010-02-14 17:14:22 +00002492 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2493 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002494 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002495 if( nOld && zBuf[-1]!='\n' ){
2496 *(zBuf++) = '\n';
2497 }
2498 memcpy(zBuf, zLine, nLine);
2499 zBuf += nLine;
2500 *(zBuf++) = '"';
2501 for(z=psp->filename; *z; z++){
2502 if( *z=='\\' ){
2503 *(zBuf++) = '\\';
2504 }
2505 *(zBuf++) = *z;
2506 }
2507 *(zBuf++) = '"';
2508 *(zBuf++) = '\n';
2509 }
drh4dc8ef52008-07-01 17:13:57 +00002510 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2511 psp->decllinenoslot[0] = psp->tokenlineno;
2512 }
drha5808f32008-04-27 22:19:44 +00002513 memcpy(zBuf, zNew, nNew);
2514 zBuf += nNew;
2515 *zBuf = 0;
2516 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002517 }else{
2518 ErrorMsg(psp->filename,psp->tokenlineno,
2519 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2520 psp->errorcnt++;
2521 psp->state = RESYNC_AFTER_DECL_ERROR;
2522 }
2523 break;
drh0bd1f4e2002-06-06 18:54:39 +00002524 case WAITING_FOR_FALLBACK_ID:
2525 if( x[0]=='.' ){
2526 psp->state = WAITING_FOR_DECL_OR_RULE;
2527 }else if( !isupper(x[0]) ){
2528 ErrorMsg(psp->filename, psp->tokenlineno,
2529 "%%fallback argument \"%s\" should be a token", x);
2530 psp->errorcnt++;
2531 }else{
2532 struct symbol *sp = Symbol_new(x);
2533 if( psp->fallback==0 ){
2534 psp->fallback = sp;
2535 }else if( sp->fallback ){
2536 ErrorMsg(psp->filename, psp->tokenlineno,
2537 "More than one fallback assigned to token %s", x);
2538 psp->errorcnt++;
2539 }else{
2540 sp->fallback = psp->fallback;
2541 psp->gp->has_fallback = 1;
2542 }
2543 }
2544 break;
drhe09daa92006-06-10 13:29:31 +00002545 case WAITING_FOR_WILDCARD_ID:
2546 if( x[0]=='.' ){
2547 psp->state = WAITING_FOR_DECL_OR_RULE;
2548 }else if( !isupper(x[0]) ){
2549 ErrorMsg(psp->filename, psp->tokenlineno,
2550 "%%wildcard argument \"%s\" should be a token", x);
2551 psp->errorcnt++;
2552 }else{
2553 struct symbol *sp = Symbol_new(x);
2554 if( psp->gp->wildcard==0 ){
2555 psp->gp->wildcard = sp;
2556 }else{
2557 ErrorMsg(psp->filename, psp->tokenlineno,
2558 "Extra wildcard to token: %s", x);
2559 psp->errorcnt++;
2560 }
2561 }
2562 break;
drh61f92cd2014-01-11 03:06:18 +00002563 case WAITING_FOR_CLASS_ID:
2564 if( !islower(x[0]) ){
2565 ErrorMsg(psp->filename, psp->tokenlineno,
2566 "%%token_class must be followed by an identifier: ", x);
2567 psp->errorcnt++;
2568 psp->state = RESYNC_AFTER_DECL_ERROR;
2569 }else if( Symbol_find(x) ){
2570 ErrorMsg(psp->filename, psp->tokenlineno,
2571 "Symbol \"%s\" already used", x);
2572 psp->errorcnt++;
2573 psp->state = RESYNC_AFTER_DECL_ERROR;
2574 }else{
2575 psp->tkclass = Symbol_new(x);
2576 psp->tkclass->type = MULTITERMINAL;
2577 psp->state = WAITING_FOR_CLASS_TOKEN;
2578 }
2579 break;
2580 case WAITING_FOR_CLASS_TOKEN:
2581 if( x[0]=='.' ){
2582 psp->state = WAITING_FOR_DECL_OR_RULE;
2583 }else if( isupper(x[0]) || ((x[0]=='|' || x[0]=='/') && isupper(x[1])) ){
2584 struct symbol *msp = psp->tkclass;
2585 msp->nsubsym++;
2586 msp->subsym = (struct symbol **) realloc(msp->subsym,
2587 sizeof(struct symbol*)*msp->nsubsym);
2588 if( !isupper(x[0]) ) x++;
2589 msp->subsym[msp->nsubsym-1] = Symbol_new(x);
2590 }else{
2591 ErrorMsg(psp->filename, psp->tokenlineno,
2592 "%%token_class argument \"%s\" should be a token", x);
2593 psp->errorcnt++;
2594 psp->state = RESYNC_AFTER_DECL_ERROR;
2595 }
2596 break;
drh75897232000-05-29 14:26:00 +00002597 case RESYNC_AFTER_RULE_ERROR:
2598/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2599** break; */
2600 case RESYNC_AFTER_DECL_ERROR:
2601 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2602 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2603 break;
2604 }
2605}
2606
drh34ff57b2008-07-14 12:27:51 +00002607/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002608** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2609** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2610** comments them out. Text in between is also commented out as appropriate.
2611*/
danielk1977940fac92005-01-23 22:41:37 +00002612static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002613 int i, j, k, n;
2614 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002615 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002616 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002617 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002618 for(i=0; z[i]; i++){
2619 if( z[i]=='\n' ) lineno++;
2620 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2621 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2622 if( exclude ){
2623 exclude--;
2624 if( exclude==0 ){
2625 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2626 }
2627 }
2628 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2629 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2630 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2631 if( exclude ){
2632 exclude++;
2633 }else{
2634 for(j=i+7; isspace(z[j]); j++){}
2635 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2636 exclude = 1;
2637 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002638 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002639 exclude = 0;
2640 break;
2641 }
2642 }
2643 if( z[i+3]=='n' ) exclude = !exclude;
2644 if( exclude ){
2645 start = i;
2646 start_lineno = lineno;
2647 }
2648 }
2649 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2650 }
2651 }
2652 if( exclude ){
2653 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2654 exit(1);
2655 }
2656}
2657
drh75897232000-05-29 14:26:00 +00002658/* In spite of its name, this function is really a scanner. It read
2659** in the entire input file (all at once) then tokenizes it. Each
2660** token is passed to the function "parseonetoken" which builds all
2661** the appropriate data structures in the global state vector "gp".
2662*/
icculus9e44cf12010-02-14 17:14:22 +00002663void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002664{
2665 struct pstate ps;
2666 FILE *fp;
2667 char *filebuf;
mistachkin2318d332015-01-12 18:02:52 +00002668 unsigned int filesize;
drh75897232000-05-29 14:26:00 +00002669 int lineno;
2670 int c;
2671 char *cp, *nextcp;
2672 int startline = 0;
2673
rse38514a92007-09-20 11:34:17 +00002674 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002675 ps.gp = gp;
2676 ps.filename = gp->filename;
2677 ps.errorcnt = 0;
2678 ps.state = INITIALIZE;
2679
2680 /* Begin by reading the input file */
2681 fp = fopen(ps.filename,"rb");
2682 if( fp==0 ){
2683 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2684 gp->errorcnt++;
2685 return;
2686 }
2687 fseek(fp,0,2);
2688 filesize = ftell(fp);
2689 rewind(fp);
2690 filebuf = (char *)malloc( filesize+1 );
drh03e1b1f2014-01-11 12:52:25 +00002691 if( filesize>100000000 || filebuf==0 ){
2692 ErrorMsg(ps.filename,0,"Input file too large.");
drh75897232000-05-29 14:26:00 +00002693 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002694 fclose(fp);
drh75897232000-05-29 14:26:00 +00002695 return;
2696 }
2697 if( fread(filebuf,1,filesize,fp)!=filesize ){
2698 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2699 filesize);
2700 free(filebuf);
2701 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002702 fclose(fp);
drh75897232000-05-29 14:26:00 +00002703 return;
2704 }
2705 fclose(fp);
2706 filebuf[filesize] = 0;
2707
drh6d08b4d2004-07-20 12:45:22 +00002708 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2709 preprocess_input(filebuf);
2710
drh75897232000-05-29 14:26:00 +00002711 /* Now scan the text of the input file */
2712 lineno = 1;
2713 for(cp=filebuf; (c= *cp)!=0; ){
2714 if( c=='\n' ) lineno++; /* Keep track of the line number */
2715 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2716 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2717 cp+=2;
2718 while( (c= *cp)!=0 && c!='\n' ) cp++;
2719 continue;
2720 }
2721 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2722 cp+=2;
2723 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2724 if( c=='\n' ) lineno++;
2725 cp++;
2726 }
2727 if( c ) cp++;
2728 continue;
2729 }
2730 ps.tokenstart = cp; /* Mark the beginning of the token */
2731 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2732 if( c=='\"' ){ /* String literals */
2733 cp++;
2734 while( (c= *cp)!=0 && c!='\"' ){
2735 if( c=='\n' ) lineno++;
2736 cp++;
2737 }
2738 if( c==0 ){
2739 ErrorMsg(ps.filename,startline,
2740"String starting on this line is not terminated before the end of the file.");
2741 ps.errorcnt++;
2742 nextcp = cp;
2743 }else{
2744 nextcp = cp+1;
2745 }
2746 }else if( c=='{' ){ /* A block of C code */
2747 int level;
2748 cp++;
2749 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2750 if( c=='\n' ) lineno++;
2751 else if( c=='{' ) level++;
2752 else if( c=='}' ) level--;
2753 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2754 int prevc;
2755 cp = &cp[2];
2756 prevc = 0;
2757 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2758 if( c=='\n' ) lineno++;
2759 prevc = c;
2760 cp++;
drhf2f105d2012-08-20 15:53:54 +00002761 }
2762 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
drh75897232000-05-29 14:26:00 +00002763 cp = &cp[2];
2764 while( (c= *cp)!=0 && c!='\n' ) cp++;
2765 if( c ) lineno++;
drhf2f105d2012-08-20 15:53:54 +00002766 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
drh75897232000-05-29 14:26:00 +00002767 int startchar, prevc;
2768 startchar = c;
2769 prevc = 0;
2770 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2771 if( c=='\n' ) lineno++;
2772 if( prevc=='\\' ) prevc = 0;
2773 else prevc = c;
drhf2f105d2012-08-20 15:53:54 +00002774 }
2775 }
drh75897232000-05-29 14:26:00 +00002776 }
2777 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002778 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002779"C code starting on this line is not terminated before the end of the file.");
2780 ps.errorcnt++;
2781 nextcp = cp;
2782 }else{
2783 nextcp = cp+1;
2784 }
2785 }else if( isalnum(c) ){ /* Identifiers */
2786 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2787 nextcp = cp;
2788 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2789 cp += 3;
2790 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002791 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2792 cp += 2;
2793 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2794 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002795 }else{ /* All other (one character) operators */
2796 cp++;
2797 nextcp = cp;
2798 }
2799 c = *cp;
2800 *cp = 0; /* Null terminate the token */
2801 parseonetoken(&ps); /* Parse the token */
mistachkin2318d332015-01-12 18:02:52 +00002802 *cp = (char)c; /* Restore the buffer */
drh75897232000-05-29 14:26:00 +00002803 cp = nextcp;
2804 }
2805 free(filebuf); /* Release the buffer after parsing */
2806 gp->rule = ps.firstrule;
2807 gp->errorcnt = ps.errorcnt;
2808}
2809/*************************** From the file "plink.c" *********************/
2810/*
2811** Routines processing configuration follow-set propagation links
2812** in the LEMON parser generator.
2813*/
2814static struct plink *plink_freelist = 0;
2815
2816/* Allocate a new plink */
2817struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002818 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002819
2820 if( plink_freelist==0 ){
2821 int i;
2822 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002823 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002824 if( plink_freelist==0 ){
2825 fprintf(stderr,
2826 "Unable to allocate memory for a new follow-set propagation link.\n");
2827 exit(1);
2828 }
2829 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2830 plink_freelist[amt-1].next = 0;
2831 }
icculus9e44cf12010-02-14 17:14:22 +00002832 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002833 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002834 return newlink;
drh75897232000-05-29 14:26:00 +00002835}
2836
2837/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002838void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002839{
icculus9e44cf12010-02-14 17:14:22 +00002840 struct plink *newlink;
2841 newlink = Plink_new();
2842 newlink->next = *plpp;
2843 *plpp = newlink;
2844 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002845}
2846
2847/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002848void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002849{
2850 struct plink *nextpl;
2851 while( from ){
2852 nextpl = from->next;
2853 from->next = *to;
2854 *to = from;
2855 from = nextpl;
2856 }
2857}
2858
2859/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002860void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002861{
2862 struct plink *nextpl;
2863
2864 while( plp ){
2865 nextpl = plp->next;
2866 plp->next = plink_freelist;
2867 plink_freelist = plp;
2868 plp = nextpl;
2869 }
2870}
2871/*********************** From the file "report.c" **************************/
2872/*
2873** Procedures for generating reports and tables in the LEMON parser generator.
2874*/
2875
2876/* Generate a filename with the given suffix. Space to hold the
2877** name comes from malloc() and must be freed by the calling
2878** function.
2879*/
icculus9e44cf12010-02-14 17:14:22 +00002880PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002881{
2882 char *name;
2883 char *cp;
2884
icculus9e44cf12010-02-14 17:14:22 +00002885 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002886 if( name==0 ){
2887 fprintf(stderr,"Can't allocate space for a filename.\n");
2888 exit(1);
2889 }
drh898799f2014-01-10 23:21:00 +00002890 lemon_strcpy(name,lemp->filename);
drh75897232000-05-29 14:26:00 +00002891 cp = strrchr(name,'.');
2892 if( cp ) *cp = 0;
drh898799f2014-01-10 23:21:00 +00002893 lemon_strcat(name,suffix);
drh75897232000-05-29 14:26:00 +00002894 return name;
2895}
2896
2897/* Open a file with a name based on the name of the input file,
2898** but with a different (specified) suffix, and return a pointer
2899** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002900PRIVATE FILE *file_open(
2901 struct lemon *lemp,
2902 const char *suffix,
2903 const char *mode
2904){
drh75897232000-05-29 14:26:00 +00002905 FILE *fp;
2906
2907 if( lemp->outname ) free(lemp->outname);
2908 lemp->outname = file_makename(lemp, suffix);
2909 fp = fopen(lemp->outname,mode);
2910 if( fp==0 && *mode=='w' ){
2911 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2912 lemp->errorcnt++;
2913 return 0;
2914 }
2915 return fp;
2916}
2917
2918/* Duplicate the input file without comments and without actions
2919** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002920void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002921{
2922 struct rule *rp;
2923 struct symbol *sp;
2924 int i, j, maxlen, len, ncolumns, skip;
2925 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2926 maxlen = 10;
2927 for(i=0; i<lemp->nsymbol; i++){
2928 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002929 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002930 if( len>maxlen ) maxlen = len;
2931 }
2932 ncolumns = 76/(maxlen+5);
2933 if( ncolumns<1 ) ncolumns = 1;
2934 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2935 for(i=0; i<skip; i++){
2936 printf("//");
2937 for(j=i; j<lemp->nsymbol; j+=skip){
2938 sp = lemp->symbols[j];
2939 assert( sp->index==j );
2940 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2941 }
2942 printf("\n");
2943 }
2944 for(rp=lemp->rule; rp; rp=rp->next){
2945 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002946 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002947 printf(" ::=");
2948 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002949 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002950 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002951 printf(" %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002952 for(j=1; j<sp->nsubsym; j++){
2953 printf("|%s", sp->subsym[j]->name);
2954 }
drh61f92cd2014-01-11 03:06:18 +00002955 }else{
2956 printf(" %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002957 }
2958 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002959 }
2960 printf(".");
2961 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002962 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002963 printf("\n");
2964 }
2965}
2966
drh7e698e92015-09-07 14:22:24 +00002967/* Print a single rule.
2968*/
2969void RulePrint(FILE *fp, struct rule *rp, int iCursor){
drhfd405312005-11-06 04:06:59 +00002970 struct symbol *sp;
2971 int i, j;
drh75897232000-05-29 14:26:00 +00002972 fprintf(fp,"%s ::=",rp->lhs->name);
2973 for(i=0; i<=rp->nrhs; i++){
drh7e698e92015-09-07 14:22:24 +00002974 if( i==iCursor ) fprintf(fp," *");
drh75897232000-05-29 14:26:00 +00002975 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002976 sp = rp->rhs[i];
drhfd405312005-11-06 04:06:59 +00002977 if( sp->type==MULTITERMINAL ){
drh61f92cd2014-01-11 03:06:18 +00002978 fprintf(fp," %s", sp->subsym[0]->name);
drhfd405312005-11-06 04:06:59 +00002979 for(j=1; j<sp->nsubsym; j++){
2980 fprintf(fp,"|%s",sp->subsym[j]->name);
2981 }
drh61f92cd2014-01-11 03:06:18 +00002982 }else{
2983 fprintf(fp," %s", sp->name);
drhfd405312005-11-06 04:06:59 +00002984 }
drh75897232000-05-29 14:26:00 +00002985 }
2986}
2987
drh7e698e92015-09-07 14:22:24 +00002988/* Print the rule for a configuration.
2989*/
2990void ConfigPrint(FILE *fp, struct config *cfp){
2991 RulePrint(fp, cfp->rp, cfp->dot);
2992}
2993
drh75897232000-05-29 14:26:00 +00002994/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002995#if 0
drh75897232000-05-29 14:26:00 +00002996/* Print a set */
2997PRIVATE void SetPrint(out,set,lemp)
2998FILE *out;
2999char *set;
3000struct lemon *lemp;
3001{
3002 int i;
3003 char *spacer;
3004 spacer = "";
3005 fprintf(out,"%12s[","");
3006 for(i=0; i<lemp->nterminal; i++){
3007 if( SetFind(set,i) ){
3008 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
3009 spacer = " ";
3010 }
3011 }
3012 fprintf(out,"]\n");
3013}
3014
3015/* Print a plink chain */
3016PRIVATE void PlinkPrint(out,plp,tag)
3017FILE *out;
3018struct plink *plp;
3019char *tag;
3020{
3021 while( plp ){
drhada354d2005-11-05 15:03:59 +00003022 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00003023 ConfigPrint(out,plp->cfp);
3024 fprintf(out,"\n");
3025 plp = plp->next;
3026 }
3027}
3028#endif
3029
3030/* Print an action to the given file descriptor. Return FALSE if
3031** nothing was actually printed.
3032*/
drh7e698e92015-09-07 14:22:24 +00003033int PrintAction(
3034 struct action *ap, /* The action to print */
3035 FILE *fp, /* Print the action here */
drh3bd48ab2015-09-07 18:23:37 +00003036 int indent /* Indent by this amount */
drh7e698e92015-09-07 14:22:24 +00003037){
drh75897232000-05-29 14:26:00 +00003038 int result = 1;
3039 switch( ap->type ){
drh7e698e92015-09-07 14:22:24 +00003040 case SHIFT: {
3041 struct state *stp = ap->x.stp;
drh3bd48ab2015-09-07 18:23:37 +00003042 fprintf(fp,"%*s shift %-7d",indent,ap->sp->name,stp->statenum);
drh75897232000-05-29 14:26:00 +00003043 break;
drh7e698e92015-09-07 14:22:24 +00003044 }
3045 case REDUCE: {
3046 struct rule *rp = ap->x.rp;
drh3bd48ab2015-09-07 18:23:37 +00003047 fprintf(fp,"%*s reduce %-7d",indent,ap->sp->name,rp->index);
3048 RulePrint(fp, rp, -1);
3049 break;
3050 }
3051 case SHIFTREDUCE: {
3052 struct rule *rp = ap->x.rp;
3053 fprintf(fp,"%*s shift-reduce %-7d",indent,ap->sp->name,rp->index);
3054 RulePrint(fp, rp, -1);
drh75897232000-05-29 14:26:00 +00003055 break;
drh7e698e92015-09-07 14:22:24 +00003056 }
drh75897232000-05-29 14:26:00 +00003057 case ACCEPT:
3058 fprintf(fp,"%*s accept",indent,ap->sp->name);
3059 break;
3060 case ERROR:
3061 fprintf(fp,"%*s error",indent,ap->sp->name);
3062 break;
drh9892c5d2007-12-21 00:02:11 +00003063 case SRCONFLICT:
3064 case RRCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003065 fprintf(fp,"%*s reduce %-7d ** Parsing conflict **",
drh75897232000-05-29 14:26:00 +00003066 indent,ap->sp->name,ap->x.rp->index);
3067 break;
drh9892c5d2007-12-21 00:02:11 +00003068 case SSCONFLICT:
drh3bd48ab2015-09-07 18:23:37 +00003069 fprintf(fp,"%*s shift %-7d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00003070 indent,ap->sp->name,ap->x.stp->statenum);
3071 break;
drh75897232000-05-29 14:26:00 +00003072 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003073 if( showPrecedenceConflict ){
drh3bd48ab2015-09-07 18:23:37 +00003074 fprintf(fp,"%*s shift %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003075 indent,ap->sp->name,ap->x.stp->statenum);
3076 }else{
3077 result = 0;
3078 }
3079 break;
drh75897232000-05-29 14:26:00 +00003080 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00003081 if( showPrecedenceConflict ){
drh7e698e92015-09-07 14:22:24 +00003082 fprintf(fp,"%*s reduce %-7d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00003083 indent,ap->sp->name,ap->x.rp->index);
3084 }else{
3085 result = 0;
3086 }
3087 break;
drh75897232000-05-29 14:26:00 +00003088 case NOT_USED:
3089 result = 0;
3090 break;
3091 }
3092 return result;
3093}
3094
drh3bd48ab2015-09-07 18:23:37 +00003095/* Generate the "*.out" log file */
icculus9e44cf12010-02-14 17:14:22 +00003096void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003097{
3098 int i;
3099 struct state *stp;
3100 struct config *cfp;
3101 struct action *ap;
3102 FILE *fp;
3103
drh2aa6ca42004-09-10 00:14:04 +00003104 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003105 if( fp==0 ) return;
drh3bd48ab2015-09-07 18:23:37 +00003106 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003107 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003108 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003109 if( lemp->basisflag ) cfp=stp->bp;
3110 else cfp=stp->cfp;
3111 while( cfp ){
3112 char buf[20];
3113 if( cfp->dot==cfp->rp->nrhs ){
drh898799f2014-01-10 23:21:00 +00003114 lemon_sprintf(buf,"(%d)",cfp->rp->index);
drh75897232000-05-29 14:26:00 +00003115 fprintf(fp," %5s ",buf);
3116 }else{
3117 fprintf(fp," ");
3118 }
3119 ConfigPrint(fp,cfp);
3120 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003121#if 0
drh75897232000-05-29 14:26:00 +00003122 SetPrint(fp,cfp->fws,lemp);
3123 PlinkPrint(fp,cfp->fplp,"To ");
3124 PlinkPrint(fp,cfp->bplp,"From");
3125#endif
3126 if( lemp->basisflag ) cfp=cfp->bp;
3127 else cfp=cfp->next;
3128 }
3129 fprintf(fp,"\n");
3130 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00003131 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
drh75897232000-05-29 14:26:00 +00003132 }
3133 fprintf(fp,"\n");
3134 }
drhe9278182007-07-18 18:16:29 +00003135 fprintf(fp, "----------------------------------------------------\n");
3136 fprintf(fp, "Symbols:\n");
3137 for(i=0; i<lemp->nsymbol; i++){
3138 int j;
3139 struct symbol *sp;
3140
3141 sp = lemp->symbols[i];
3142 fprintf(fp, " %3d: %s", i, sp->name);
3143 if( sp->type==NONTERMINAL ){
3144 fprintf(fp, ":");
3145 if( sp->lambda ){
3146 fprintf(fp, " <lambda>");
3147 }
3148 for(j=0; j<lemp->nterminal; j++){
3149 if( sp->firstset && SetFind(sp->firstset, j) ){
3150 fprintf(fp, " %s", lemp->symbols[j]->name);
3151 }
3152 }
3153 }
3154 fprintf(fp, "\n");
3155 }
drh75897232000-05-29 14:26:00 +00003156 fclose(fp);
3157 return;
3158}
3159
3160/* Search for the file "name" which is in the same directory as
3161** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003162PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003163{
icculus9e44cf12010-02-14 17:14:22 +00003164 const char *pathlist;
3165 char *pathbufptr;
3166 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003167 char *path,*cp;
3168 char c;
drh75897232000-05-29 14:26:00 +00003169
3170#ifdef __WIN32__
3171 cp = strrchr(argv0,'\\');
3172#else
3173 cp = strrchr(argv0,'/');
3174#endif
3175 if( cp ){
3176 c = *cp;
3177 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003178 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh898799f2014-01-10 23:21:00 +00003179 if( path ) lemon_sprintf(path,"%s/%s",argv0,name);
drh75897232000-05-29 14:26:00 +00003180 *cp = c;
3181 }else{
drh75897232000-05-29 14:26:00 +00003182 pathlist = getenv("PATH");
3183 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003184 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003185 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003186 if( (pathbuf != 0) && (path!=0) ){
3187 pathbufptr = pathbuf;
drh898799f2014-01-10 23:21:00 +00003188 lemon_strcpy(pathbuf, pathlist);
icculus9e44cf12010-02-14 17:14:22 +00003189 while( *pathbuf ){
3190 cp = strchr(pathbuf,':');
3191 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003192 c = *cp;
3193 *cp = 0;
drh898799f2014-01-10 23:21:00 +00003194 lemon_sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003195 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003196 if( c==0 ) pathbuf[0] = 0;
3197 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003198 if( access(path,modemask)==0 ) break;
3199 }
icculus9e44cf12010-02-14 17:14:22 +00003200 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003201 }
3202 }
3203 return path;
3204}
3205
3206/* Given an action, compute the integer value for that action
3207** which is to be put in the action table of the generated machine.
3208** Return negative if no action should be generated.
3209*/
icculus9e44cf12010-02-14 17:14:22 +00003210PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003211{
3212 int act;
3213 switch( ap->type ){
drh3bd48ab2015-09-07 18:23:37 +00003214 case SHIFT: act = ap->x.stp->statenum; break;
3215 case SHIFTREDUCE: act = ap->x.rp->index + lemp->nstate; break;
3216 case REDUCE: act = ap->x.rp->index + lemp->nstate+lemp->nrule; break;
3217 case ERROR: act = lemp->nstate + lemp->nrule*2; break;
3218 case ACCEPT: act = lemp->nstate + lemp->nrule*2 + 1; break;
drh75897232000-05-29 14:26:00 +00003219 default: act = -1; break;
3220 }
3221 return act;
3222}
3223
3224#define LINESIZE 1000
3225/* The next cluster of routines are for reading the template file
3226** and writing the results to the generated parser */
3227/* The first function transfers data from "in" to "out" until
3228** a line is seen which begins with "%%". The line number is
3229** tracked.
3230**
3231** if name!=0, then any word that begin with "Parse" is changed to
3232** begin with *name instead.
3233*/
icculus9e44cf12010-02-14 17:14:22 +00003234PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003235{
3236 int i, iStart;
3237 char line[LINESIZE];
3238 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3239 (*lineno)++;
3240 iStart = 0;
3241 if( name ){
3242 for(i=0; line[i]; i++){
3243 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3244 && (i==0 || !isalpha(line[i-1]))
3245 ){
3246 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3247 fprintf(out,"%s",name);
3248 i += 4;
3249 iStart = i+1;
3250 }
3251 }
3252 }
3253 fprintf(out,"%s",&line[iStart]);
3254 }
3255}
3256
3257/* The next function finds the template file and opens it, returning
3258** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003259PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003260{
3261 static char templatename[] = "lempar.c";
3262 char buf[1000];
3263 FILE *in;
3264 char *tpltname;
3265 char *cp;
3266
icculus3e143bd2010-02-14 00:48:49 +00003267 /* first, see if user specified a template filename on the command line. */
3268 if (user_templatename != 0) {
3269 if( access(user_templatename,004)==-1 ){
3270 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3271 user_templatename);
3272 lemp->errorcnt++;
3273 return 0;
3274 }
3275 in = fopen(user_templatename,"rb");
3276 if( in==0 ){
drh25473362015-09-04 18:03:45 +00003277 fprintf(stderr,"Can't open the template file \"%s\".\n",
3278 user_templatename);
icculus3e143bd2010-02-14 00:48:49 +00003279 lemp->errorcnt++;
3280 return 0;
3281 }
3282 return in;
3283 }
3284
drh75897232000-05-29 14:26:00 +00003285 cp = strrchr(lemp->filename,'.');
3286 if( cp ){
drh898799f2014-01-10 23:21:00 +00003287 lemon_sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003288 }else{
drh898799f2014-01-10 23:21:00 +00003289 lemon_sprintf(buf,"%s.lt",lemp->filename);
drh75897232000-05-29 14:26:00 +00003290 }
3291 if( access(buf,004)==0 ){
3292 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003293 }else if( access(templatename,004)==0 ){
3294 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003295 }else{
3296 tpltname = pathsearch(lemp->argv0,templatename,0);
3297 }
3298 if( tpltname==0 ){
3299 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3300 templatename);
3301 lemp->errorcnt++;
3302 return 0;
3303 }
drh2aa6ca42004-09-10 00:14:04 +00003304 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003305 if( in==0 ){
3306 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3307 lemp->errorcnt++;
3308 return 0;
3309 }
3310 return in;
3311}
3312
drhaf805ca2004-09-07 11:28:25 +00003313/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003314PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003315{
3316 fprintf(out,"#line %d \"",lineno);
3317 while( *filename ){
3318 if( *filename == '\\' ) putc('\\',out);
3319 putc(*filename,out);
3320 filename++;
3321 }
3322 fprintf(out,"\"\n");
3323}
3324
drh75897232000-05-29 14:26:00 +00003325/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003326PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003327{
3328 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003329 while( *str ){
drh75897232000-05-29 14:26:00 +00003330 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003331 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003332 str++;
3333 }
drh9db55df2004-09-09 14:01:21 +00003334 if( str[-1]!='\n' ){
3335 putc('\n',out);
3336 (*lineno)++;
3337 }
shane58543932008-12-10 20:10:04 +00003338 if (!lemp->nolinenosflag) {
3339 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3340 }
drh75897232000-05-29 14:26:00 +00003341 return;
3342}
3343
3344/*
3345** The following routine emits code for the destructor for the
3346** symbol sp
3347*/
icculus9e44cf12010-02-14 17:14:22 +00003348void emit_destructor_code(
3349 FILE *out,
3350 struct symbol *sp,
3351 struct lemon *lemp,
3352 int *lineno
3353){
drhcc83b6e2004-04-23 23:38:42 +00003354 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003355
drh75897232000-05-29 14:26:00 +00003356 if( sp->type==TERMINAL ){
3357 cp = lemp->tokendest;
3358 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003359 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003360 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003361 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003362 fprintf(out,"{\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003363 if( !lemp->nolinenosflag ){
3364 (*lineno)++;
3365 tplt_linedir(out,sp->destLineno,lemp->filename);
3366 }
drh960e8c62001-04-03 16:53:21 +00003367 }else if( lemp->vardest ){
3368 cp = lemp->vardest;
3369 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003370 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003371 }else{
3372 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003373 }
3374 for(; *cp; cp++){
3375 if( *cp=='$' && cp[1]=='$' ){
3376 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3377 cp++;
3378 continue;
3379 }
shane58543932008-12-10 20:10:04 +00003380 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003381 fputc(*cp,out);
3382 }
shane58543932008-12-10 20:10:04 +00003383 fprintf(out,"\n"); (*lineno)++;
3384 if (!lemp->nolinenosflag) {
3385 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3386 }
3387 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003388 return;
3389}
3390
3391/*
drh960e8c62001-04-03 16:53:21 +00003392** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003393*/
icculus9e44cf12010-02-14 17:14:22 +00003394int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003395{
3396 int ret;
3397 if( sp->type==TERMINAL ){
3398 ret = lemp->tokendest!=0;
3399 }else{
drh960e8c62001-04-03 16:53:21 +00003400 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003401 }
3402 return ret;
3403}
3404
drh0bb132b2004-07-20 14:06:51 +00003405/*
3406** Append text to a dynamically allocated string. If zText is 0 then
3407** reset the string to be empty again. Always return the complete text
3408** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003409**
3410** n bytes of zText are stored. If n==0 then all of zText up to the first
3411** \000 terminator is stored. zText can contain up to two instances of
3412** %d. The values of p1 and p2 are written into the first and second
3413** %d.
3414**
3415** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003416*/
icculus9e44cf12010-02-14 17:14:22 +00003417PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3418 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003419 static char *z = 0;
3420 static int alloced = 0;
3421 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003422 int c;
drh0bb132b2004-07-20 14:06:51 +00003423 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003424 if( zText==0 ){
3425 used = 0;
3426 return z;
3427 }
drh7ac25c72004-08-19 15:12:26 +00003428 if( n<=0 ){
3429 if( n<0 ){
3430 used += n;
3431 assert( used>=0 );
3432 }
drh87cf1372008-08-13 20:09:06 +00003433 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003434 }
drhdf609712010-11-23 20:55:27 +00003435 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003436 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003437 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003438 }
icculus9e44cf12010-02-14 17:14:22 +00003439 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003440 while( n-- > 0 ){
3441 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003442 if( c=='%' && n>0 && zText[0]=='d' ){
drh898799f2014-01-10 23:21:00 +00003443 lemon_sprintf(zInt, "%d", p1);
drh0bb132b2004-07-20 14:06:51 +00003444 p1 = p2;
drh898799f2014-01-10 23:21:00 +00003445 lemon_strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003446 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003447 zText++;
3448 n--;
3449 }else{
mistachkin2318d332015-01-12 18:02:52 +00003450 z[used++] = (char)c;
drh0bb132b2004-07-20 14:06:51 +00003451 }
3452 }
3453 z[used] = 0;
3454 return z;
3455}
3456
3457/*
3458** zCode is a string that is the action associated with a rule. Expand
3459** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003460** stack.
drh0bb132b2004-07-20 14:06:51 +00003461*/
drhaf805ca2004-09-07 11:28:25 +00003462PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003463 char *cp, *xp;
3464 int i;
3465 char lhsused = 0; /* True if the LHS element has been used */
3466 char used[MAXRHS]; /* True for each RHS element which is used */
3467
3468 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3469 lhsused = 0;
3470
drh19c9e562007-03-29 20:13:53 +00003471 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003472 static char newlinestr[2] = { '\n', '\0' };
3473 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003474 rp->line = rp->ruleline;
3475 }
3476
drh0bb132b2004-07-20 14:06:51 +00003477 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003478
3479 /* This const cast is wrong but harmless, if we're careful. */
3480 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003481 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3482 char saved;
3483 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3484 saved = *xp;
3485 *xp = 0;
3486 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003487 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003488 cp = xp;
3489 lhsused = 1;
3490 }else{
3491 for(i=0; i<rp->nrhs; i++){
3492 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003493 if( cp!=rp->code && cp[-1]=='@' ){
3494 /* If the argument is of the form @X then substituted
3495 ** the token number of X, not the value of X */
3496 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3497 }else{
drhfd405312005-11-06 04:06:59 +00003498 struct symbol *sp = rp->rhs[i];
3499 int dtnum;
3500 if( sp->type==MULTITERMINAL ){
3501 dtnum = sp->subsym[0]->dtnum;
3502 }else{
3503 dtnum = sp->dtnum;
3504 }
3505 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003506 }
drh0bb132b2004-07-20 14:06:51 +00003507 cp = xp;
3508 used[i] = 1;
3509 break;
3510 }
3511 }
3512 }
3513 *xp = saved;
3514 }
3515 append_str(cp, 1, 0, 0);
3516 } /* End loop */
3517
3518 /* Check to make sure the LHS has been used */
3519 if( rp->lhsalias && !lhsused ){
3520 ErrorMsg(lemp->filename,rp->ruleline,
3521 "Label \"%s\" for \"%s(%s)\" is never used.",
3522 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3523 lemp->errorcnt++;
3524 }
3525
3526 /* Generate destructor code for RHS symbols which are not used in the
3527 ** reduce code */
3528 for(i=0; i<rp->nrhs; i++){
3529 if( rp->rhsalias[i] && !used[i] ){
3530 ErrorMsg(lemp->filename,rp->ruleline,
3531 "Label %s for \"%s(%s)\" is never used.",
3532 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3533 lemp->errorcnt++;
3534 }else if( rp->rhsalias[i]==0 ){
3535 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003536 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003537 rp->rhs[i]->index,i-rp->nrhs+1);
3538 }else{
3539 /* No destructor defined for this term */
3540 }
3541 }
3542 }
drh61e339a2007-01-16 03:09:02 +00003543 if( rp->code ){
3544 cp = append_str(0,0,0,0);
3545 rp->code = Strsafe(cp?cp:"");
3546 }
drh0bb132b2004-07-20 14:06:51 +00003547}
3548
drh75897232000-05-29 14:26:00 +00003549/*
3550** Generate code which executes when the rule "rp" is reduced. Write
3551** the code to "out". Make sure lineno stays up-to-date.
3552*/
icculus9e44cf12010-02-14 17:14:22 +00003553PRIVATE void emit_code(
3554 FILE *out,
3555 struct rule *rp,
3556 struct lemon *lemp,
3557 int *lineno
3558){
3559 const char *cp;
drh75897232000-05-29 14:26:00 +00003560
3561 /* Generate code to do the reduce action */
3562 if( rp->code ){
drh25473362015-09-04 18:03:45 +00003563 if( !lemp->nolinenosflag ){
3564 (*lineno)++;
3565 tplt_linedir(out,rp->line,lemp->filename);
3566 }
drhaf805ca2004-09-07 11:28:25 +00003567 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003568 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003569 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003570 } /* End loop */
shane58543932008-12-10 20:10:04 +00003571 fprintf(out,"}\n"); (*lineno)++;
drh25473362015-09-04 18:03:45 +00003572 if( !lemp->nolinenosflag ){
3573 (*lineno)++;
3574 tplt_linedir(out,*lineno,lemp->outname);
3575 }
drh75897232000-05-29 14:26:00 +00003576 } /* End if( rp->code ) */
3577
drh75897232000-05-29 14:26:00 +00003578 return;
3579}
3580
3581/*
3582** Print the definition of the union used for the parser's data stack.
3583** This union contains fields for every possible data type for tokens
3584** and nonterminals. In the process of computing and printing this
3585** union, also set the ".dtnum" field of every terminal and nonterminal
3586** symbol.
3587*/
icculus9e44cf12010-02-14 17:14:22 +00003588void print_stack_union(
3589 FILE *out, /* The output stream */
3590 struct lemon *lemp, /* The main info structure for this parser */
3591 int *plineno, /* Pointer to the line number */
3592 int mhflag /* True if generating makeheaders output */
3593){
drh75897232000-05-29 14:26:00 +00003594 int lineno = *plineno; /* The line number of the output */
3595 char **types; /* A hash table of datatypes */
3596 int arraysize; /* Size of the "types" array */
3597 int maxdtlength; /* Maximum length of any ".datatype" field. */
3598 char *stddt; /* Standardized name for a datatype */
3599 int i,j; /* Loop counters */
drh01f75f22013-10-02 20:46:30 +00003600 unsigned hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003601 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003602
3603 /* Allocate and initialize types[] and allocate stddt[] */
3604 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003605 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003606 if( types==0 ){
3607 fprintf(stderr,"Out of memory.\n");
3608 exit(1);
3609 }
drh75897232000-05-29 14:26:00 +00003610 for(i=0; i<arraysize; i++) types[i] = 0;
3611 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003612 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003613 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003614 }
drh75897232000-05-29 14:26:00 +00003615 for(i=0; i<lemp->nsymbol; i++){
3616 int len;
3617 struct symbol *sp = lemp->symbols[i];
3618 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003619 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003620 if( len>maxdtlength ) maxdtlength = len;
3621 }
3622 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003623 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003624 fprintf(stderr,"Out of memory.\n");
3625 exit(1);
3626 }
3627
3628 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3629 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003630 ** used for terminal symbols. If there is no %default_type defined then
3631 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3632 ** a datatype using the %type directive.
3633 */
drh75897232000-05-29 14:26:00 +00003634 for(i=0; i<lemp->nsymbol; i++){
3635 struct symbol *sp = lemp->symbols[i];
3636 char *cp;
3637 if( sp==lemp->errsym ){
3638 sp->dtnum = arraysize+1;
3639 continue;
3640 }
drh960e8c62001-04-03 16:53:21 +00003641 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003642 sp->dtnum = 0;
3643 continue;
3644 }
3645 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003646 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003647 j = 0;
3648 while( isspace(*cp) ) cp++;
3649 while( *cp ) stddt[j++] = *cp++;
3650 while( j>0 && isspace(stddt[j-1]) ) j--;
3651 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003652 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003653 sp->dtnum = 0;
3654 continue;
3655 }
drh75897232000-05-29 14:26:00 +00003656 hash = 0;
3657 for(j=0; stddt[j]; j++){
3658 hash = hash*53 + stddt[j];
3659 }
drh3b2129c2003-05-13 00:34:21 +00003660 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003661 while( types[hash] ){
3662 if( strcmp(types[hash],stddt)==0 ){
3663 sp->dtnum = hash + 1;
3664 break;
3665 }
3666 hash++;
drh2b51f212013-10-11 23:01:02 +00003667 if( hash>=(unsigned)arraysize ) hash = 0;
drh75897232000-05-29 14:26:00 +00003668 }
3669 if( types[hash]==0 ){
3670 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003671 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003672 if( types[hash]==0 ){
3673 fprintf(stderr,"Out of memory.\n");
3674 exit(1);
3675 }
drh898799f2014-01-10 23:21:00 +00003676 lemon_strcpy(types[hash],stddt);
drh75897232000-05-29 14:26:00 +00003677 }
3678 }
3679
3680 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3681 name = lemp->name ? lemp->name : "Parse";
3682 lineno = *plineno;
3683 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3684 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3685 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3686 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3687 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003688 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003689 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3690 for(i=0; i<arraysize; i++){
3691 if( types[i]==0 ) continue;
3692 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3693 free(types[i]);
3694 }
drhc4dd3fd2008-01-22 01:48:05 +00003695 if( lemp->errsym->useCnt ){
3696 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3697 }
drh75897232000-05-29 14:26:00 +00003698 free(stddt);
3699 free(types);
3700 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3701 *plineno = lineno;
3702}
3703
drhb29b0a52002-02-23 19:39:46 +00003704/*
3705** Return the name of a C datatype able to represent values between
drhc75e0162015-09-07 02:23:02 +00003706** lwr and upr, inclusive. If pnByte!=NULL then also write the sizeof
3707** for that type (1, 2, or 4) into *pnByte.
drhb29b0a52002-02-23 19:39:46 +00003708*/
drhc75e0162015-09-07 02:23:02 +00003709static const char *minimum_size_type(int lwr, int upr, int *pnByte){
3710 const char *zType = "int";
3711 int nByte = 4;
drh8b582012003-10-21 13:16:03 +00003712 if( lwr>=0 ){
3713 if( upr<=255 ){
drhc75e0162015-09-07 02:23:02 +00003714 zType = "unsigned char";
3715 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003716 }else if( upr<65535 ){
drhc75e0162015-09-07 02:23:02 +00003717 zType = "unsigned short int";
3718 nByte = 2;
drh8b582012003-10-21 13:16:03 +00003719 }else{
drhc75e0162015-09-07 02:23:02 +00003720 zType = "unsigned int";
3721 nByte = 4;
drh8b582012003-10-21 13:16:03 +00003722 }
3723 }else if( lwr>=-127 && upr<=127 ){
drhc75e0162015-09-07 02:23:02 +00003724 zType = "signed char";
3725 nByte = 1;
drh8b582012003-10-21 13:16:03 +00003726 }else if( lwr>=-32767 && upr<32767 ){
drhc75e0162015-09-07 02:23:02 +00003727 zType = "short";
3728 nByte = 2;
drhb29b0a52002-02-23 19:39:46 +00003729 }
drhc75e0162015-09-07 02:23:02 +00003730 if( pnByte ) *pnByte = nByte;
3731 return zType;
drhb29b0a52002-02-23 19:39:46 +00003732}
3733
drhfdbf9282003-10-21 16:34:41 +00003734/*
3735** Each state contains a set of token transaction and a set of
3736** nonterminal transactions. Each of these sets makes an instance
3737** of the following structure. An array of these structures is used
3738** to order the creation of entries in the yy_action[] table.
3739*/
3740struct axset {
3741 struct state *stp; /* A pointer to a state */
3742 int isTkn; /* True to use tokens. False for non-terminals */
3743 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003744 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003745};
3746
3747/*
3748** Compare to axset structures for sorting purposes
3749*/
3750static int axset_compare(const void *a, const void *b){
3751 struct axset *p1 = (struct axset*)a;
3752 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003753 int c;
3754 c = p2->nAction - p1->nAction;
3755 if( c==0 ){
drh337cd0d2015-09-07 23:40:42 +00003756 c = p1->iOrder - p2->iOrder;
drhe594bc32009-11-03 13:02:25 +00003757 }
3758 assert( c!=0 || p1==p2 );
3759 return c;
drhfdbf9282003-10-21 16:34:41 +00003760}
3761
drhc4dd3fd2008-01-22 01:48:05 +00003762/*
3763** Write text on "out" that describes the rule "rp".
3764*/
3765static void writeRuleText(FILE *out, struct rule *rp){
3766 int j;
3767 fprintf(out,"%s ::=", rp->lhs->name);
3768 for(j=0; j<rp->nrhs; j++){
3769 struct symbol *sp = rp->rhs[j];
drh61f92cd2014-01-11 03:06:18 +00003770 if( sp->type!=MULTITERMINAL ){
3771 fprintf(out," %s", sp->name);
3772 }else{
drhc4dd3fd2008-01-22 01:48:05 +00003773 int k;
drh61f92cd2014-01-11 03:06:18 +00003774 fprintf(out," %s", sp->subsym[0]->name);
drhc4dd3fd2008-01-22 01:48:05 +00003775 for(k=1; k<sp->nsubsym; k++){
3776 fprintf(out,"|%s",sp->subsym[k]->name);
3777 }
3778 }
3779 }
3780}
3781
3782
drh75897232000-05-29 14:26:00 +00003783/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003784void ReportTable(
3785 struct lemon *lemp,
3786 int mhflag /* Output in makeheaders format if true */
3787){
drh75897232000-05-29 14:26:00 +00003788 FILE *out, *in;
3789 char line[LINESIZE];
3790 int lineno;
3791 struct state *stp;
3792 struct action *ap;
3793 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003794 struct acttab *pActtab;
drhc75e0162015-09-07 02:23:02 +00003795 int i, j, n, sz;
3796 int szActionType; /* sizeof(YYACTIONTYPE) */
3797 int szCodeType; /* sizeof(YYCODETYPE) */
icculus9e44cf12010-02-14 17:14:22 +00003798 const char *name;
drh8b582012003-10-21 13:16:03 +00003799 int mnTknOfst, mxTknOfst;
3800 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003801 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003802
3803 in = tplt_open(lemp);
3804 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003805 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003806 if( out==0 ){
3807 fclose(in);
3808 return;
3809 }
3810 lineno = 1;
3811 tplt_xfer(lemp->name,in,out,&lineno);
3812
3813 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003814 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003815 if( mhflag ){
mistachkin8e189222015-04-19 21:43:16 +00003816 char *incName = file_makename(lemp, ".h");
3817 fprintf(out,"#include \"%s\"\n", incName); lineno++;
3818 free(incName);
drh75897232000-05-29 14:26:00 +00003819 }
3820 tplt_xfer(lemp->name,in,out,&lineno);
3821
3822 /* Generate #defines for all tokens */
3823 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003824 const char *prefix;
drh75897232000-05-29 14:26:00 +00003825 fprintf(out,"#if INTERFACE\n"); lineno++;
3826 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3827 else prefix = "";
3828 for(i=1; i<lemp->nterminal; i++){
3829 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3830 lineno++;
3831 }
3832 fprintf(out,"#endif\n"); lineno++;
3833 }
3834 tplt_xfer(lemp->name,in,out,&lineno);
3835
3836 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003837 fprintf(out,"#define YYCODETYPE %s\n",
drhc75e0162015-09-07 02:23:02 +00003838 minimum_size_type(0, lemp->nsymbol+1, &szCodeType)); lineno++;
drh75897232000-05-29 14:26:00 +00003839 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3840 fprintf(out,"#define YYACTIONTYPE %s\n",
drh3bd48ab2015-09-07 18:23:37 +00003841 minimum_size_type(0,lemp->nstate+lemp->nrule*2+5,&szActionType)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003842 if( lemp->wildcard ){
3843 fprintf(out,"#define YYWILDCARD %d\n",
3844 lemp->wildcard->index); lineno++;
3845 }
drh75897232000-05-29 14:26:00 +00003846 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003847 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003848 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003849 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3850 }else{
3851 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3852 }
drhca44b5a2007-02-22 23:06:58 +00003853 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003854 if( mhflag ){
3855 fprintf(out,"#if INTERFACE\n"); lineno++;
3856 }
3857 name = lemp->name ? lemp->name : "Parse";
3858 if( lemp->arg && lemp->arg[0] ){
drh87cf1372008-08-13 20:09:06 +00003859 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003860 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3861 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003862 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3863 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3864 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3865 name,lemp->arg,&lemp->arg[i]); lineno++;
3866 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3867 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003868 }else{
drh1f245e42002-03-11 13:55:50 +00003869 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3870 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3871 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3872 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003873 }
3874 if( mhflag ){
3875 fprintf(out,"#endif\n"); lineno++;
3876 }
drhc4dd3fd2008-01-22 01:48:05 +00003877 if( lemp->errsym->useCnt ){
drh3bd48ab2015-09-07 18:23:37 +00003878 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3879 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003880 }
drh0bd1f4e2002-06-06 18:54:39 +00003881 if( lemp->has_fallback ){
3882 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3883 }
drh75897232000-05-29 14:26:00 +00003884
drh3bd48ab2015-09-07 18:23:37 +00003885 /* Compute the action table, but do not output it yet. The action
3886 ** table must be computed before generating the YYNSTATE macro because
3887 ** we need to know how many states can be eliminated.
drh75897232000-05-29 14:26:00 +00003888 */
drh3bd48ab2015-09-07 18:23:37 +00003889 ax = (struct axset *) calloc(lemp->nxstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003890 if( ax==0 ){
3891 fprintf(stderr,"malloc failed\n");
3892 exit(1);
3893 }
drh3bd48ab2015-09-07 18:23:37 +00003894 for(i=0; i<lemp->nxstate; i++){
drh75897232000-05-29 14:26:00 +00003895 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003896 ax[i*2].stp = stp;
3897 ax[i*2].isTkn = 1;
3898 ax[i*2].nAction = stp->nTknAct;
3899 ax[i*2+1].stp = stp;
3900 ax[i*2+1].isTkn = 0;
3901 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003902 }
drh8b582012003-10-21 13:16:03 +00003903 mxTknOfst = mnTknOfst = 0;
3904 mxNtOfst = mnNtOfst = 0;
drh3bd48ab2015-09-07 18:23:37 +00003905 /* In an effort to minimize the action table size, use the heuristic
3906 ** of placing the largest action sets first */
3907 for(i=0; i<lemp->nxstate*2; i++) ax[i].iOrder = i;
3908 qsort(ax, lemp->nxstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003909 pActtab = acttab_alloc();
drh3bd48ab2015-09-07 18:23:37 +00003910 for(i=0; i<lemp->nxstate*2 && ax[i].nAction>0; i++){
drhfdbf9282003-10-21 16:34:41 +00003911 stp = ax[i].stp;
3912 if( ax[i].isTkn ){
3913 for(ap=stp->ap; ap; ap=ap->next){
3914 int action;
3915 if( ap->sp->index>=lemp->nterminal ) continue;
3916 action = compute_action(lemp, ap);
3917 if( action<0 ) continue;
3918 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003919 }
drhfdbf9282003-10-21 16:34:41 +00003920 stp->iTknOfst = acttab_insert(pActtab);
3921 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3922 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3923 }else{
3924 for(ap=stp->ap; ap; ap=ap->next){
3925 int action;
3926 if( ap->sp->index<lemp->nterminal ) continue;
3927 if( ap->sp->index==lemp->nsymbol ) continue;
3928 action = compute_action(lemp, ap);
3929 if( action<0 ) continue;
3930 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003931 }
drhfdbf9282003-10-21 16:34:41 +00003932 stp->iNtOfst = acttab_insert(pActtab);
3933 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3934 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003935 }
drh337cd0d2015-09-07 23:40:42 +00003936#if 0 /* Uncomment for a trace of how the yy_action[] table fills out */
3937 { int jj, nn;
3938 for(jj=nn=0; jj<pActtab->nAction; jj++){
3939 if( pActtab->aAction[jj].action<0 ) nn++;
3940 }
3941 printf("%4d: State %3d %s n: %2d size: %5d freespace: %d\n",
3942 i, stp->statenum, ax[i].isTkn ? "Token" : "Var ",
3943 ax[i].nAction, pActtab->nAction, nn);
3944 }
3945#endif
drh8b582012003-10-21 13:16:03 +00003946 }
drhfdbf9282003-10-21 16:34:41 +00003947 free(ax);
drh8b582012003-10-21 13:16:03 +00003948
drh3bd48ab2015-09-07 18:23:37 +00003949 /* Finish rendering the constants now that the action table has
3950 ** been computed */
3951 fprintf(out,"#define YYNSTATE %d\n",lemp->nxstate); lineno++;
3952 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drh337cd0d2015-09-07 23:40:42 +00003953 fprintf(out,"#define YY_MAX_SHIFT %d\n",lemp->nxstate-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00003954 fprintf(out,"#define YY_MIN_SHIFTREDUCE %d\n",lemp->nstate); lineno++;
3955 i = lemp->nstate + lemp->nrule;
3956 fprintf(out,"#define YY_MAX_SHIFTREDUCE %d\n", i-1); lineno++;
3957 fprintf(out,"#define YY_MIN_REDUCE %d\n", i); lineno++;
3958 i = lemp->nstate + lemp->nrule*2;
3959 fprintf(out,"#define YY_MAX_REDUCE %d\n", i-1); lineno++;
3960 fprintf(out,"#define YY_ERROR_ACTION %d\n", i); lineno++;
3961 fprintf(out,"#define YY_ACCEPT_ACTION %d\n", i+1); lineno++;
3962 fprintf(out,"#define YY_NO_ACTION %d\n", i+2); lineno++;
3963 tplt_xfer(lemp->name,in,out,&lineno);
3964
3965 /* Now output the action table and its associates:
3966 **
3967 ** yy_action[] A single table containing all actions.
3968 ** yy_lookahead[] A table containing the lookahead for each entry in
3969 ** yy_action. Used to detect hash collisions.
3970 ** yy_shift_ofst[] For each state, the offset into yy_action for
3971 ** shifting terminals.
3972 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3973 ** shifting non-terminals after a reduce.
3974 ** yy_default[] Default action for each state.
3975 */
3976
drh8b582012003-10-21 13:16:03 +00003977 /* Output the yy_action table */
drhc75e0162015-09-07 02:23:02 +00003978 lemp->nactiontab = n = acttab_size(pActtab);
3979 lemp->tablesize += n*szActionType;
drhf16371d2009-11-03 19:18:31 +00003980 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3981 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003982 for(i=j=0; i<n; i++){
3983 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003984 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003985 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003986 fprintf(out, " %4d,", action);
3987 if( j==9 || i==n-1 ){
3988 fprintf(out, "\n"); lineno++;
3989 j = 0;
3990 }else{
3991 j++;
3992 }
3993 }
3994 fprintf(out, "};\n"); lineno++;
3995
3996 /* Output the yy_lookahead table */
drhc75e0162015-09-07 02:23:02 +00003997 lemp->tablesize += n*szCodeType;
drh57196282004-10-06 15:41:16 +00003998 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003999 for(i=j=0; i<n; i++){
4000 int la = acttab_yylookahead(pActtab, i);
4001 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00004002 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004003 fprintf(out, " %4d,", la);
4004 if( j==9 || i==n-1 ){
4005 fprintf(out, "\n"); lineno++;
4006 j = 0;
4007 }else{
4008 j++;
4009 }
4010 }
4011 fprintf(out, "};\n"); lineno++;
4012
4013 /* Output the yy_shift_ofst[] table */
4014 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004015 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004016 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004017 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
4018 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
4019 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004020 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004021 minimum_size_type(mnTknOfst-1, mxTknOfst, &sz)); lineno++;
4022 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004023 for(i=j=0; i<n; i++){
4024 int ofst;
4025 stp = lemp->sorted[i];
4026 ofst = stp->iTknOfst;
4027 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004028 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004029 fprintf(out, " %4d,", ofst);
4030 if( j==9 || i==n-1 ){
4031 fprintf(out, "\n"); lineno++;
4032 j = 0;
4033 }else{
4034 j++;
4035 }
4036 }
4037 fprintf(out, "};\n"); lineno++;
4038
4039 /* Output the yy_reduce_ofst[] table */
4040 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004041 n = lemp->nxstate;
drhada354d2005-11-05 15:03:59 +00004042 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00004043 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
4044 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
4045 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00004046 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drhc75e0162015-09-07 02:23:02 +00004047 minimum_size_type(mnNtOfst-1, mxNtOfst, &sz)); lineno++;
4048 lemp->tablesize += n*sz;
drh8b582012003-10-21 13:16:03 +00004049 for(i=j=0; i<n; i++){
4050 int ofst;
4051 stp = lemp->sorted[i];
4052 ofst = stp->iNtOfst;
4053 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00004054 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00004055 fprintf(out, " %4d,", ofst);
4056 if( j==9 || i==n-1 ){
4057 fprintf(out, "\n"); lineno++;
4058 j = 0;
4059 }else{
4060 j++;
4061 }
4062 }
4063 fprintf(out, "};\n"); lineno++;
4064
4065 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00004066 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh3bd48ab2015-09-07 18:23:37 +00004067 n = lemp->nxstate;
drhc75e0162015-09-07 02:23:02 +00004068 lemp->tablesize += n*szActionType;
drh8b582012003-10-21 13:16:03 +00004069 for(i=j=0; i<n; i++){
4070 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00004071 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh3bd48ab2015-09-07 18:23:37 +00004072 fprintf(out, " %4d,", stp->iDfltReduce+lemp->nstate+lemp->nrule);
drh8b582012003-10-21 13:16:03 +00004073 if( j==9 || i==n-1 ){
4074 fprintf(out, "\n"); lineno++;
4075 j = 0;
4076 }else{
4077 j++;
4078 }
4079 }
4080 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004081 tplt_xfer(lemp->name,in,out,&lineno);
4082
drh0bd1f4e2002-06-06 18:54:39 +00004083 /* Generate the table of fallback tokens.
4084 */
4085 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00004086 int mx = lemp->nterminal - 1;
4087 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
drhc75e0162015-09-07 02:23:02 +00004088 lemp->tablesize += (mx+1)*szCodeType;
drh1441f3e2009-06-12 12:50:50 +00004089 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00004090 struct symbol *p = lemp->symbols[i];
4091 if( p->fallback==0 ){
4092 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
4093 }else{
4094 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
4095 p->name, p->fallback->name);
4096 }
4097 lineno++;
4098 }
4099 }
4100 tplt_xfer(lemp->name, in, out, &lineno);
4101
4102 /* Generate a table containing the symbolic name of every symbol
4103 */
drh75897232000-05-29 14:26:00 +00004104 for(i=0; i<lemp->nsymbol; i++){
drh898799f2014-01-10 23:21:00 +00004105 lemon_sprintf(line,"\"%s\",",lemp->symbols[i]->name);
drh75897232000-05-29 14:26:00 +00004106 fprintf(out," %-15s",line);
4107 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
4108 }
4109 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
4110 tplt_xfer(lemp->name,in,out,&lineno);
4111
drh0bd1f4e2002-06-06 18:54:39 +00004112 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00004113 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00004114 ** when tracing REDUCE actions.
4115 */
4116 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
4117 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00004118 fprintf(out," /* %3d */ \"", i);
4119 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00004120 fprintf(out,"\",\n"); lineno++;
4121 }
4122 tplt_xfer(lemp->name,in,out,&lineno);
4123
drh75897232000-05-29 14:26:00 +00004124 /* Generate code which executes every time a symbol is popped from
4125 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00004126 ** (In other words, generate the %destructor actions)
4127 */
drh75897232000-05-29 14:26:00 +00004128 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00004129 int once = 1;
drh75897232000-05-29 14:26:00 +00004130 for(i=0; i<lemp->nsymbol; i++){
4131 struct symbol *sp = lemp->symbols[i];
4132 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004133 if( once ){
4134 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
4135 once = 0;
4136 }
drhc53eed12009-06-12 17:46:19 +00004137 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00004138 }
4139 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
4140 if( i<lemp->nsymbol ){
4141 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4142 fprintf(out," break;\n"); lineno++;
4143 }
4144 }
drh8d659732005-01-13 23:54:06 +00004145 if( lemp->vardest ){
4146 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00004147 int once = 1;
drh8d659732005-01-13 23:54:06 +00004148 for(i=0; i<lemp->nsymbol; i++){
4149 struct symbol *sp = lemp->symbols[i];
4150 if( sp==0 || sp->type==TERMINAL ||
4151 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00004152 if( once ){
4153 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4154 once = 0;
4155 }
drhc53eed12009-06-12 17:46:19 +00004156 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004157 dflt_sp = sp;
4158 }
4159 if( dflt_sp!=0 ){
4160 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004161 }
drh4dc8ef52008-07-01 17:13:57 +00004162 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004163 }
drh75897232000-05-29 14:26:00 +00004164 for(i=0; i<lemp->nsymbol; i++){
4165 struct symbol *sp = lemp->symbols[i];
4166 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004167 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004168
4169 /* Combine duplicate destructors into a single case */
4170 for(j=i+1; j<lemp->nsymbol; j++){
4171 struct symbol *sp2 = lemp->symbols[j];
4172 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4173 && sp2->dtnum==sp->dtnum
4174 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004175 fprintf(out," case %d: /* %s */\n",
4176 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004177 sp2->destructor = 0;
4178 }
4179 }
4180
drh75897232000-05-29 14:26:00 +00004181 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4182 fprintf(out," break;\n"); lineno++;
4183 }
drh75897232000-05-29 14:26:00 +00004184 tplt_xfer(lemp->name,in,out,&lineno);
4185
4186 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004187 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004188 tplt_xfer(lemp->name,in,out,&lineno);
4189
4190 /* Generate the table of rule information
4191 **
4192 ** Note: This code depends on the fact that rules are number
4193 ** sequentually beginning with 0.
4194 */
4195 for(rp=lemp->rule; rp; rp=rp->next){
4196 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4197 }
4198 tplt_xfer(lemp->name,in,out,&lineno);
4199
4200 /* Generate code which execution during each REDUCE action */
4201 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004202 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004203 }
drhc53eed12009-06-12 17:46:19 +00004204 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004205 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004206 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004207 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004208 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004209 fprintf(out," case %d: /* ", rp->index);
4210 writeRuleText(out, rp);
4211 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004212 for(rp2=rp->next; rp2; rp2=rp2->next){
4213 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004214 fprintf(out," case %d: /* ", rp2->index);
4215 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004216 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004217 rp2->code = 0;
4218 }
4219 }
drh75897232000-05-29 14:26:00 +00004220 emit_code(out,rp,lemp,&lineno);
4221 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004222 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004223 }
drhc53eed12009-06-12 17:46:19 +00004224 /* Finally, output the default: rule. We choose as the default: all
4225 ** empty actions. */
4226 fprintf(out," default:\n"); lineno++;
4227 for(rp=lemp->rule; rp; rp=rp->next){
4228 if( rp->code==0 ) continue;
4229 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4230 fprintf(out," /* (%d) ", rp->index);
4231 writeRuleText(out, rp);
4232 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4233 }
4234 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004235 tplt_xfer(lemp->name,in,out,&lineno);
4236
4237 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004238 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004239 tplt_xfer(lemp->name,in,out,&lineno);
4240
4241 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004242 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004243 tplt_xfer(lemp->name,in,out,&lineno);
4244
4245 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004246 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004247 tplt_xfer(lemp->name,in,out,&lineno);
4248
4249 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004250 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004251
4252 fclose(in);
4253 fclose(out);
4254 return;
4255}
4256
4257/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004258void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004259{
4260 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004261 const char *prefix;
drh75897232000-05-29 14:26:00 +00004262 char line[LINESIZE];
4263 char pattern[LINESIZE];
4264 int i;
4265
4266 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4267 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004268 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004269 if( in ){
drh8ba0d1c2012-06-16 15:26:31 +00004270 int nextChar;
drh75897232000-05-29 14:26:00 +00004271 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
drh61f92cd2014-01-11 03:06:18 +00004272 lemon_sprintf(pattern,"#define %s%-30s %3d\n",
4273 prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004274 if( strcmp(line,pattern) ) break;
4275 }
drh8ba0d1c2012-06-16 15:26:31 +00004276 nextChar = fgetc(in);
drh75897232000-05-29 14:26:00 +00004277 fclose(in);
drh8ba0d1c2012-06-16 15:26:31 +00004278 if( i==lemp->nterminal && nextChar==EOF ){
drh75897232000-05-29 14:26:00 +00004279 /* No change in the file. Don't rewrite it. */
4280 return;
4281 }
4282 }
drh2aa6ca42004-09-10 00:14:04 +00004283 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004284 if( out ){
4285 for(i=1; i<lemp->nterminal; i++){
drh61f92cd2014-01-11 03:06:18 +00004286 fprintf(out,"#define %s%-30s %3d\n",prefix,lemp->symbols[i]->name,i);
drh75897232000-05-29 14:26:00 +00004287 }
4288 fclose(out);
4289 }
4290 return;
4291}
4292
4293/* Reduce the size of the action tables, if possible, by making use
4294** of defaults.
4295**
drhb59499c2002-02-23 18:45:13 +00004296** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004297** it the default. Except, there is no default if the wildcard token
4298** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004299*/
icculus9e44cf12010-02-14 17:14:22 +00004300void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004301{
4302 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004303 struct action *ap, *ap2;
4304 struct rule *rp, *rp2, *rbest;
drh0c6dfaa2015-09-08 21:16:46 +00004305 int nbest, n;
drh75897232000-05-29 14:26:00 +00004306 int i;
drhe09daa92006-06-10 13:29:31 +00004307 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004308
4309 for(i=0; i<lemp->nstate; i++){
4310 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004311 nbest = 0;
4312 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004313 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004314
drhb59499c2002-02-23 18:45:13 +00004315 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004316 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4317 usesWildcard = 1;
4318 }
drhb59499c2002-02-23 18:45:13 +00004319 if( ap->type!=REDUCE ) continue;
4320 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004321 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004322 if( rp==rbest ) continue;
4323 n = 1;
4324 for(ap2=ap->next; ap2; ap2=ap2->next){
4325 if( ap2->type!=REDUCE ) continue;
4326 rp2 = ap2->x.rp;
4327 if( rp2==rbest ) continue;
4328 if( rp2==rp ) n++;
4329 }
4330 if( n>nbest ){
4331 nbest = n;
4332 rbest = rp;
drh75897232000-05-29 14:26:00 +00004333 }
4334 }
drhb59499c2002-02-23 18:45:13 +00004335
4336 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004337 ** is not at least 1 or if the wildcard token is a possible
4338 ** lookahead.
4339 */
4340 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004341
drhb59499c2002-02-23 18:45:13 +00004342
4343 /* Combine matching REDUCE actions into a single default */
4344 for(ap=stp->ap; ap; ap=ap->next){
4345 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4346 }
drh75897232000-05-29 14:26:00 +00004347 assert( ap );
4348 ap->sp = Symbol_new("{default}");
4349 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004350 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004351 }
4352 stp->ap = Action_sort(stp->ap);
drh3bd48ab2015-09-07 18:23:37 +00004353
4354 for(ap=stp->ap; ap; ap=ap->next){
4355 if( ap->type==SHIFT ) break;
4356 if( ap->type==REDUCE && ap->x.rp!=rbest ) break;
4357 }
4358 if( ap==0 ){
4359 stp->autoReduce = 1;
4360 stp->pDfltReduce = rbest;
4361 }
4362 }
4363
4364 /* Make a second pass over all states and actions. Convert
4365 ** every action that is a SHIFT to an autoReduce state into
4366 ** a SHIFTREDUCE action.
4367 */
4368 for(i=0; i<lemp->nstate; i++){
4369 stp = lemp->sorted[i];
4370 for(ap=stp->ap; ap; ap=ap->next){
4371 struct state *pNextState;
4372 if( ap->type!=SHIFT ) continue;
4373 pNextState = ap->x.stp;
4374 if( pNextState->autoReduce && pNextState->pDfltReduce!=0 ){
4375 ap->type = SHIFTREDUCE;
4376 ap->x.rp = pNextState->pDfltReduce;
4377 }
4378 }
drh75897232000-05-29 14:26:00 +00004379 }
4380}
drhb59499c2002-02-23 18:45:13 +00004381
drhada354d2005-11-05 15:03:59 +00004382
4383/*
4384** Compare two states for sorting purposes. The smaller state is the
4385** one with the most non-terminal actions. If they have the same number
4386** of non-terminal actions, then the smaller is the one with the most
4387** token actions.
4388*/
4389static int stateResortCompare(const void *a, const void *b){
4390 const struct state *pA = *(const struct state**)a;
4391 const struct state *pB = *(const struct state**)b;
4392 int n;
4393
4394 n = pB->nNtAct - pA->nNtAct;
4395 if( n==0 ){
4396 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004397 if( n==0 ){
4398 n = pB->statenum - pA->statenum;
4399 }
drhada354d2005-11-05 15:03:59 +00004400 }
drhe594bc32009-11-03 13:02:25 +00004401 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004402 return n;
4403}
4404
4405
4406/*
4407** Renumber and resort states so that states with fewer choices
4408** occur at the end. Except, keep state 0 as the first state.
4409*/
icculus9e44cf12010-02-14 17:14:22 +00004410void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004411{
4412 int i;
4413 struct state *stp;
4414 struct action *ap;
4415
4416 for(i=0; i<lemp->nstate; i++){
4417 stp = lemp->sorted[i];
4418 stp->nTknAct = stp->nNtAct = 0;
drh3bd48ab2015-09-07 18:23:37 +00004419 stp->iDfltReduce = lemp->nrule; /* Init dflt action to "syntax error" */
drhada354d2005-11-05 15:03:59 +00004420 stp->iTknOfst = NO_OFFSET;
4421 stp->iNtOfst = NO_OFFSET;
4422 for(ap=stp->ap; ap; ap=ap->next){
drh3bd48ab2015-09-07 18:23:37 +00004423 int iAction = compute_action(lemp,ap);
4424 if( iAction>=0 ){
drhada354d2005-11-05 15:03:59 +00004425 if( ap->sp->index<lemp->nterminal ){
4426 stp->nTknAct++;
4427 }else if( ap->sp->index<lemp->nsymbol ){
4428 stp->nNtAct++;
4429 }else{
drh3bd48ab2015-09-07 18:23:37 +00004430 assert( stp->autoReduce==0 || stp->pDfltReduce==ap->x.rp );
4431 stp->iDfltReduce = iAction - lemp->nstate - lemp->nrule;
drhada354d2005-11-05 15:03:59 +00004432 }
4433 }
4434 }
4435 }
4436 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4437 stateResortCompare);
4438 for(i=0; i<lemp->nstate; i++){
4439 lemp->sorted[i]->statenum = i;
4440 }
drh3bd48ab2015-09-07 18:23:37 +00004441 lemp->nxstate = lemp->nstate;
4442 while( lemp->nxstate>1 && lemp->sorted[lemp->nxstate-1]->autoReduce ){
4443 lemp->nxstate--;
4444 }
drhada354d2005-11-05 15:03:59 +00004445}
4446
4447
drh75897232000-05-29 14:26:00 +00004448/***************** From the file "set.c" ************************************/
4449/*
4450** Set manipulation routines for the LEMON parser generator.
4451*/
4452
4453static int size = 0;
4454
4455/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004456void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004457{
4458 size = n+1;
4459}
4460
4461/* Allocate a new set */
4462char *SetNew(){
4463 char *s;
drh9892c5d2007-12-21 00:02:11 +00004464 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004465 if( s==0 ){
4466 extern void memory_error();
4467 memory_error();
4468 }
drh75897232000-05-29 14:26:00 +00004469 return s;
4470}
4471
4472/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004473void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004474{
4475 free(s);
4476}
4477
4478/* Add a new element to the set. Return TRUE if the element was added
4479** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004480int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004481{
4482 int rv;
drh9892c5d2007-12-21 00:02:11 +00004483 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004484 rv = s[e];
4485 s[e] = 1;
4486 return !rv;
4487}
4488
4489/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004490int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004491{
4492 int i, progress;
4493 progress = 0;
4494 for(i=0; i<size; i++){
4495 if( s2[i]==0 ) continue;
4496 if( s1[i]==0 ){
4497 progress = 1;
4498 s1[i] = 1;
4499 }
4500 }
4501 return progress;
4502}
4503/********************** From the file "table.c" ****************************/
4504/*
4505** All code in this file has been automatically generated
4506** from a specification in the file
4507** "table.q"
4508** by the associative array code building program "aagen".
4509** Do not edit this file! Instead, edit the specification
4510** file, then rerun aagen.
4511*/
4512/*
4513** Code for processing tables in the LEMON parser generator.
4514*/
4515
drh01f75f22013-10-02 20:46:30 +00004516PRIVATE unsigned strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004517{
drh01f75f22013-10-02 20:46:30 +00004518 unsigned h = 0;
4519 while( *x ) h = h*13 + *(x++);
drh75897232000-05-29 14:26:00 +00004520 return h;
4521}
4522
4523/* Works like strdup, sort of. Save a string in malloced memory, but
4524** keep strings in a table so that the same string is not in more
4525** than one place.
4526*/
icculus9e44cf12010-02-14 17:14:22 +00004527const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004528{
icculus9e44cf12010-02-14 17:14:22 +00004529 const char *z;
4530 char *cpy;
drh75897232000-05-29 14:26:00 +00004531
drh916f75f2006-07-17 00:19:39 +00004532 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004533 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004534 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
drh898799f2014-01-10 23:21:00 +00004535 lemon_strcpy(cpy,y);
icculus9e44cf12010-02-14 17:14:22 +00004536 z = cpy;
drh75897232000-05-29 14:26:00 +00004537 Strsafe_insert(z);
4538 }
4539 MemoryCheck(z);
4540 return z;
4541}
4542
4543/* There is one instance of the following structure for each
4544** associative array of type "x1".
4545*/
4546struct s_x1 {
4547 int size; /* The number of available slots. */
4548 /* Must be a power of 2 greater than or */
4549 /* equal to 1 */
4550 int count; /* Number of currently slots filled */
4551 struct s_x1node *tbl; /* The data stored here */
4552 struct s_x1node **ht; /* Hash table for lookups */
4553};
4554
4555/* There is one instance of this structure for every data element
4556** in an associative array of type "x1".
4557*/
4558typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004559 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004560 struct s_x1node *next; /* Next entry with the same hash */
4561 struct s_x1node **from; /* Previous link */
4562} x1node;
4563
4564/* There is only one instance of the array, which is the following */
4565static struct s_x1 *x1a;
4566
4567/* Allocate a new associative array */
4568void Strsafe_init(){
4569 if( x1a ) return;
4570 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4571 if( x1a ){
4572 x1a->size = 1024;
4573 x1a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004574 x1a->tbl = (x1node*)calloc(1024, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004575 if( x1a->tbl==0 ){
4576 free(x1a);
4577 x1a = 0;
4578 }else{
4579 int i;
4580 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4581 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4582 }
4583 }
4584}
4585/* Insert a new record into the array. Return TRUE if successful.
4586** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004587int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004588{
4589 x1node *np;
drh01f75f22013-10-02 20:46:30 +00004590 unsigned h;
4591 unsigned ph;
drh75897232000-05-29 14:26:00 +00004592
4593 if( x1a==0 ) return 0;
4594 ph = strhash(data);
4595 h = ph & (x1a->size-1);
4596 np = x1a->ht[h];
4597 while( np ){
4598 if( strcmp(np->data,data)==0 ){
4599 /* An existing entry with the same key is found. */
4600 /* Fail because overwrite is not allows. */
4601 return 0;
4602 }
4603 np = np->next;
4604 }
4605 if( x1a->count>=x1a->size ){
4606 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004607 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004608 struct s_x1 array;
mistachkin8e189222015-04-19 21:43:16 +00004609 array.size = arrSize = x1a->size*2;
drh75897232000-05-29 14:26:00 +00004610 array.count = x1a->count;
mistachkin8e189222015-04-19 21:43:16 +00004611 array.tbl = (x1node*)calloc(arrSize, sizeof(x1node) + sizeof(x1node*));
drh75897232000-05-29 14:26:00 +00004612 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004613 array.ht = (x1node**)&(array.tbl[arrSize]);
4614 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004615 for(i=0; i<x1a->count; i++){
4616 x1node *oldnp, *newnp;
4617 oldnp = &(x1a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004618 h = strhash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004619 newnp = &(array.tbl[i]);
4620 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4621 newnp->next = array.ht[h];
4622 newnp->data = oldnp->data;
4623 newnp->from = &(array.ht[h]);
4624 array.ht[h] = newnp;
4625 }
4626 free(x1a->tbl);
4627 *x1a = array;
4628 }
4629 /* Insert the new data */
4630 h = ph & (x1a->size-1);
4631 np = &(x1a->tbl[x1a->count++]);
4632 np->data = data;
4633 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4634 np->next = x1a->ht[h];
4635 x1a->ht[h] = np;
4636 np->from = &(x1a->ht[h]);
4637 return 1;
4638}
4639
4640/* Return a pointer to data assigned to the given key. Return NULL
4641** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004642const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004643{
drh01f75f22013-10-02 20:46:30 +00004644 unsigned h;
drh75897232000-05-29 14:26:00 +00004645 x1node *np;
4646
4647 if( x1a==0 ) return 0;
4648 h = strhash(key) & (x1a->size-1);
4649 np = x1a->ht[h];
4650 while( np ){
4651 if( strcmp(np->data,key)==0 ) break;
4652 np = np->next;
4653 }
4654 return np ? np->data : 0;
4655}
4656
4657/* Return a pointer to the (terminal or nonterminal) symbol "x".
4658** Create a new symbol if this is the first time "x" has been seen.
4659*/
icculus9e44cf12010-02-14 17:14:22 +00004660struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004661{
4662 struct symbol *sp;
4663
4664 sp = Symbol_find(x);
4665 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004666 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004667 MemoryCheck(sp);
4668 sp->name = Strsafe(x);
4669 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4670 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004671 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004672 sp->prec = -1;
4673 sp->assoc = UNK;
4674 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004675 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004676 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004677 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004678 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004679 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004680 Symbol_insert(sp,sp->name);
4681 }
drhc4dd3fd2008-01-22 01:48:05 +00004682 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004683 return sp;
4684}
4685
drh61f92cd2014-01-11 03:06:18 +00004686/* Compare two symbols for sorting purposes. Return negative,
4687** zero, or positive if a is less then, equal to, or greater
4688** than b.
drh60d31652004-02-22 00:08:04 +00004689**
4690** Symbols that begin with upper case letters (terminals or tokens)
4691** must sort before symbols that begin with lower case letters
drh61f92cd2014-01-11 03:06:18 +00004692** (non-terminals). And MULTITERMINAL symbols (created using the
4693** %token_class directive) must sort at the very end. Other than
4694** that, the order does not matter.
drh60d31652004-02-22 00:08:04 +00004695**
4696** We find experimentally that leaving the symbols in their original
4697** order (the order they appeared in the grammar file) gives the
4698** smallest parser tables in SQLite.
4699*/
icculus9e44cf12010-02-14 17:14:22 +00004700int Symbolcmpp(const void *_a, const void *_b)
4701{
drh61f92cd2014-01-11 03:06:18 +00004702 const struct symbol *a = *(const struct symbol **) _a;
4703 const struct symbol *b = *(const struct symbol **) _b;
4704 int i1 = a->type==MULTITERMINAL ? 3 : a->name[0]>'Z' ? 2 : 1;
4705 int i2 = b->type==MULTITERMINAL ? 3 : b->name[0]>'Z' ? 2 : 1;
4706 return i1==i2 ? a->index - b->index : i1 - i2;
drh75897232000-05-29 14:26:00 +00004707}
4708
4709/* There is one instance of the following structure for each
4710** associative array of type "x2".
4711*/
4712struct s_x2 {
4713 int size; /* The number of available slots. */
4714 /* Must be a power of 2 greater than or */
4715 /* equal to 1 */
4716 int count; /* Number of currently slots filled */
4717 struct s_x2node *tbl; /* The data stored here */
4718 struct s_x2node **ht; /* Hash table for lookups */
4719};
4720
4721/* There is one instance of this structure for every data element
4722** in an associative array of type "x2".
4723*/
4724typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004725 struct symbol *data; /* The data */
4726 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004727 struct s_x2node *next; /* Next entry with the same hash */
4728 struct s_x2node **from; /* Previous link */
4729} x2node;
4730
4731/* There is only one instance of the array, which is the following */
4732static struct s_x2 *x2a;
4733
4734/* Allocate a new associative array */
4735void Symbol_init(){
4736 if( x2a ) return;
4737 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4738 if( x2a ){
4739 x2a->size = 128;
4740 x2a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004741 x2a->tbl = (x2node*)calloc(128, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004742 if( x2a->tbl==0 ){
4743 free(x2a);
4744 x2a = 0;
4745 }else{
4746 int i;
4747 x2a->ht = (x2node**)&(x2a->tbl[128]);
4748 for(i=0; i<128; i++) x2a->ht[i] = 0;
4749 }
4750 }
4751}
4752/* Insert a new record into the array. Return TRUE if successful.
4753** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004754int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004755{
4756 x2node *np;
drh01f75f22013-10-02 20:46:30 +00004757 unsigned h;
4758 unsigned ph;
drh75897232000-05-29 14:26:00 +00004759
4760 if( x2a==0 ) return 0;
4761 ph = strhash(key);
4762 h = ph & (x2a->size-1);
4763 np = x2a->ht[h];
4764 while( np ){
4765 if( strcmp(np->key,key)==0 ){
4766 /* An existing entry with the same key is found. */
4767 /* Fail because overwrite is not allows. */
4768 return 0;
4769 }
4770 np = np->next;
4771 }
4772 if( x2a->count>=x2a->size ){
4773 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004774 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004775 struct s_x2 array;
mistachkin8e189222015-04-19 21:43:16 +00004776 array.size = arrSize = x2a->size*2;
drh75897232000-05-29 14:26:00 +00004777 array.count = x2a->count;
mistachkin8e189222015-04-19 21:43:16 +00004778 array.tbl = (x2node*)calloc(arrSize, sizeof(x2node) + sizeof(x2node*));
drh75897232000-05-29 14:26:00 +00004779 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004780 array.ht = (x2node**)&(array.tbl[arrSize]);
4781 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004782 for(i=0; i<x2a->count; i++){
4783 x2node *oldnp, *newnp;
4784 oldnp = &(x2a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004785 h = strhash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004786 newnp = &(array.tbl[i]);
4787 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4788 newnp->next = array.ht[h];
4789 newnp->key = oldnp->key;
4790 newnp->data = oldnp->data;
4791 newnp->from = &(array.ht[h]);
4792 array.ht[h] = newnp;
4793 }
4794 free(x2a->tbl);
4795 *x2a = array;
4796 }
4797 /* Insert the new data */
4798 h = ph & (x2a->size-1);
4799 np = &(x2a->tbl[x2a->count++]);
4800 np->key = key;
4801 np->data = data;
4802 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4803 np->next = x2a->ht[h];
4804 x2a->ht[h] = np;
4805 np->from = &(x2a->ht[h]);
4806 return 1;
4807}
4808
4809/* Return a pointer to data assigned to the given key. Return NULL
4810** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004811struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004812{
drh01f75f22013-10-02 20:46:30 +00004813 unsigned h;
drh75897232000-05-29 14:26:00 +00004814 x2node *np;
4815
4816 if( x2a==0 ) return 0;
4817 h = strhash(key) & (x2a->size-1);
4818 np = x2a->ht[h];
4819 while( np ){
4820 if( strcmp(np->key,key)==0 ) break;
4821 np = np->next;
4822 }
4823 return np ? np->data : 0;
4824}
4825
4826/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004827struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004828{
4829 struct symbol *data;
4830 if( x2a && n>0 && n<=x2a->count ){
4831 data = x2a->tbl[n-1].data;
4832 }else{
4833 data = 0;
4834 }
4835 return data;
4836}
4837
4838/* Return the size of the array */
4839int Symbol_count()
4840{
4841 return x2a ? x2a->count : 0;
4842}
4843
4844/* Return an array of pointers to all data in the table.
4845** The array is obtained from malloc. Return NULL if memory allocation
4846** problems, or if the array is empty. */
4847struct symbol **Symbol_arrayof()
4848{
4849 struct symbol **array;
mistachkin8e189222015-04-19 21:43:16 +00004850 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004851 if( x2a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00004852 arrSize = x2a->count;
4853 array = (struct symbol **)calloc(arrSize, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004854 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00004855 for(i=0; i<arrSize; i++) array[i] = x2a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00004856 }
4857 return array;
4858}
4859
4860/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004861int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004862{
icculus9e44cf12010-02-14 17:14:22 +00004863 const struct config *a = (struct config *) _a;
4864 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004865 int x;
4866 x = a->rp->index - b->rp->index;
4867 if( x==0 ) x = a->dot - b->dot;
4868 return x;
4869}
4870
4871/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004872PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004873{
4874 int rc;
4875 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4876 rc = a->rp->index - b->rp->index;
4877 if( rc==0 ) rc = a->dot - b->dot;
4878 }
4879 if( rc==0 ){
4880 if( a ) rc = 1;
4881 if( b ) rc = -1;
4882 }
4883 return rc;
4884}
4885
4886/* Hash a state */
drh01f75f22013-10-02 20:46:30 +00004887PRIVATE unsigned statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004888{
drh01f75f22013-10-02 20:46:30 +00004889 unsigned h=0;
drh75897232000-05-29 14:26:00 +00004890 while( a ){
4891 h = h*571 + a->rp->index*37 + a->dot;
4892 a = a->bp;
4893 }
4894 return h;
4895}
4896
4897/* Allocate a new state structure */
4898struct state *State_new()
4899{
icculus9e44cf12010-02-14 17:14:22 +00004900 struct state *newstate;
4901 newstate = (struct state *)calloc(1, sizeof(struct state) );
4902 MemoryCheck(newstate);
4903 return newstate;
drh75897232000-05-29 14:26:00 +00004904}
4905
4906/* There is one instance of the following structure for each
4907** associative array of type "x3".
4908*/
4909struct s_x3 {
4910 int size; /* The number of available slots. */
4911 /* Must be a power of 2 greater than or */
4912 /* equal to 1 */
4913 int count; /* Number of currently slots filled */
4914 struct s_x3node *tbl; /* The data stored here */
4915 struct s_x3node **ht; /* Hash table for lookups */
4916};
4917
4918/* There is one instance of this structure for every data element
4919** in an associative array of type "x3".
4920*/
4921typedef struct s_x3node {
4922 struct state *data; /* The data */
4923 struct config *key; /* The key */
4924 struct s_x3node *next; /* Next entry with the same hash */
4925 struct s_x3node **from; /* Previous link */
4926} x3node;
4927
4928/* There is only one instance of the array, which is the following */
4929static struct s_x3 *x3a;
4930
4931/* Allocate a new associative array */
4932void State_init(){
4933 if( x3a ) return;
4934 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4935 if( x3a ){
4936 x3a->size = 128;
4937 x3a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00004938 x3a->tbl = (x3node*)calloc(128, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00004939 if( x3a->tbl==0 ){
4940 free(x3a);
4941 x3a = 0;
4942 }else{
4943 int i;
4944 x3a->ht = (x3node**)&(x3a->tbl[128]);
4945 for(i=0; i<128; i++) x3a->ht[i] = 0;
4946 }
4947 }
4948}
4949/* Insert a new record into the array. Return TRUE if successful.
4950** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004951int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004952{
4953 x3node *np;
drh01f75f22013-10-02 20:46:30 +00004954 unsigned h;
4955 unsigned ph;
drh75897232000-05-29 14:26:00 +00004956
4957 if( x3a==0 ) return 0;
4958 ph = statehash(key);
4959 h = ph & (x3a->size-1);
4960 np = x3a->ht[h];
4961 while( np ){
4962 if( statecmp(np->key,key)==0 ){
4963 /* An existing entry with the same key is found. */
4964 /* Fail because overwrite is not allows. */
4965 return 0;
4966 }
4967 np = np->next;
4968 }
4969 if( x3a->count>=x3a->size ){
4970 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00004971 int i,arrSize;
drh75897232000-05-29 14:26:00 +00004972 struct s_x3 array;
mistachkin8e189222015-04-19 21:43:16 +00004973 array.size = arrSize = x3a->size*2;
drh75897232000-05-29 14:26:00 +00004974 array.count = x3a->count;
mistachkin8e189222015-04-19 21:43:16 +00004975 array.tbl = (x3node*)calloc(arrSize, sizeof(x3node) + sizeof(x3node*));
drh75897232000-05-29 14:26:00 +00004976 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00004977 array.ht = (x3node**)&(array.tbl[arrSize]);
4978 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00004979 for(i=0; i<x3a->count; i++){
4980 x3node *oldnp, *newnp;
4981 oldnp = &(x3a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00004982 h = statehash(oldnp->key) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00004983 newnp = &(array.tbl[i]);
4984 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4985 newnp->next = array.ht[h];
4986 newnp->key = oldnp->key;
4987 newnp->data = oldnp->data;
4988 newnp->from = &(array.ht[h]);
4989 array.ht[h] = newnp;
4990 }
4991 free(x3a->tbl);
4992 *x3a = array;
4993 }
4994 /* Insert the new data */
4995 h = ph & (x3a->size-1);
4996 np = &(x3a->tbl[x3a->count++]);
4997 np->key = key;
4998 np->data = data;
4999 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
5000 np->next = x3a->ht[h];
5001 x3a->ht[h] = np;
5002 np->from = &(x3a->ht[h]);
5003 return 1;
5004}
5005
5006/* Return a pointer to data assigned to the given key. Return NULL
5007** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005008struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005009{
drh01f75f22013-10-02 20:46:30 +00005010 unsigned h;
drh75897232000-05-29 14:26:00 +00005011 x3node *np;
5012
5013 if( x3a==0 ) return 0;
5014 h = statehash(key) & (x3a->size-1);
5015 np = x3a->ht[h];
5016 while( np ){
5017 if( statecmp(np->key,key)==0 ) break;
5018 np = np->next;
5019 }
5020 return np ? np->data : 0;
5021}
5022
5023/* Return an array of pointers to all data in the table.
5024** The array is obtained from malloc. Return NULL if memory allocation
5025** problems, or if the array is empty. */
5026struct state **State_arrayof()
5027{
5028 struct state **array;
mistachkin8e189222015-04-19 21:43:16 +00005029 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005030 if( x3a==0 ) return 0;
mistachkin8e189222015-04-19 21:43:16 +00005031 arrSize = x3a->count;
5032 array = (struct state **)calloc(arrSize, sizeof(struct state *));
drh75897232000-05-29 14:26:00 +00005033 if( array ){
mistachkin8e189222015-04-19 21:43:16 +00005034 for(i=0; i<arrSize; i++) array[i] = x3a->tbl[i].data;
drh75897232000-05-29 14:26:00 +00005035 }
5036 return array;
5037}
5038
5039/* Hash a configuration */
drh01f75f22013-10-02 20:46:30 +00005040PRIVATE unsigned confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00005041{
drh01f75f22013-10-02 20:46:30 +00005042 unsigned h=0;
drh75897232000-05-29 14:26:00 +00005043 h = h*571 + a->rp->index*37 + a->dot;
5044 return h;
5045}
5046
5047/* There is one instance of the following structure for each
5048** associative array of type "x4".
5049*/
5050struct s_x4 {
5051 int size; /* The number of available slots. */
5052 /* Must be a power of 2 greater than or */
5053 /* equal to 1 */
5054 int count; /* Number of currently slots filled */
5055 struct s_x4node *tbl; /* The data stored here */
5056 struct s_x4node **ht; /* Hash table for lookups */
5057};
5058
5059/* There is one instance of this structure for every data element
5060** in an associative array of type "x4".
5061*/
5062typedef struct s_x4node {
5063 struct config *data; /* The data */
5064 struct s_x4node *next; /* Next entry with the same hash */
5065 struct s_x4node **from; /* Previous link */
5066} x4node;
5067
5068/* There is only one instance of the array, which is the following */
5069static struct s_x4 *x4a;
5070
5071/* Allocate a new associative array */
5072void Configtable_init(){
5073 if( x4a ) return;
5074 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
5075 if( x4a ){
5076 x4a->size = 64;
5077 x4a->count = 0;
drh03e1b1f2014-01-11 12:52:25 +00005078 x4a->tbl = (x4node*)calloc(64, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005079 if( x4a->tbl==0 ){
5080 free(x4a);
5081 x4a = 0;
5082 }else{
5083 int i;
5084 x4a->ht = (x4node**)&(x4a->tbl[64]);
5085 for(i=0; i<64; i++) x4a->ht[i] = 0;
5086 }
5087 }
5088}
5089/* Insert a new record into the array. Return TRUE if successful.
5090** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00005091int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00005092{
5093 x4node *np;
drh01f75f22013-10-02 20:46:30 +00005094 unsigned h;
5095 unsigned ph;
drh75897232000-05-29 14:26:00 +00005096
5097 if( x4a==0 ) return 0;
5098 ph = confighash(data);
5099 h = ph & (x4a->size-1);
5100 np = x4a->ht[h];
5101 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005102 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00005103 /* An existing entry with the same key is found. */
5104 /* Fail because overwrite is not allows. */
5105 return 0;
5106 }
5107 np = np->next;
5108 }
5109 if( x4a->count>=x4a->size ){
5110 /* Need to make the hash table bigger */
mistachkin8e189222015-04-19 21:43:16 +00005111 int i,arrSize;
drh75897232000-05-29 14:26:00 +00005112 struct s_x4 array;
mistachkin8e189222015-04-19 21:43:16 +00005113 array.size = arrSize = x4a->size*2;
drh75897232000-05-29 14:26:00 +00005114 array.count = x4a->count;
mistachkin8e189222015-04-19 21:43:16 +00005115 array.tbl = (x4node*)calloc(arrSize, sizeof(x4node) + sizeof(x4node*));
drh75897232000-05-29 14:26:00 +00005116 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
mistachkin8e189222015-04-19 21:43:16 +00005117 array.ht = (x4node**)&(array.tbl[arrSize]);
5118 for(i=0; i<arrSize; i++) array.ht[i] = 0;
drh75897232000-05-29 14:26:00 +00005119 for(i=0; i<x4a->count; i++){
5120 x4node *oldnp, *newnp;
5121 oldnp = &(x4a->tbl[i]);
mistachkin8e189222015-04-19 21:43:16 +00005122 h = confighash(oldnp->data) & (arrSize-1);
drh75897232000-05-29 14:26:00 +00005123 newnp = &(array.tbl[i]);
5124 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
5125 newnp->next = array.ht[h];
5126 newnp->data = oldnp->data;
5127 newnp->from = &(array.ht[h]);
5128 array.ht[h] = newnp;
5129 }
5130 free(x4a->tbl);
5131 *x4a = array;
5132 }
5133 /* Insert the new data */
5134 h = ph & (x4a->size-1);
5135 np = &(x4a->tbl[x4a->count++]);
5136 np->data = data;
5137 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
5138 np->next = x4a->ht[h];
5139 x4a->ht[h] = np;
5140 np->from = &(x4a->ht[h]);
5141 return 1;
5142}
5143
5144/* Return a pointer to data assigned to the given key. Return NULL
5145** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00005146struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00005147{
5148 int h;
5149 x4node *np;
5150
5151 if( x4a==0 ) return 0;
5152 h = confighash(key) & (x4a->size-1);
5153 np = x4a->ht[h];
5154 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00005155 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00005156 np = np->next;
5157 }
5158 return np ? np->data : 0;
5159}
5160
5161/* Remove all data from the table. Pass each data to the function "f"
5162** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00005163void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00005164{
5165 int i;
5166 if( x4a==0 || x4a->count==0 ) return;
5167 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
5168 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
5169 x4a->count = 0;
5170 return;
5171}