blob: fa8368aca040645cbee9f4ce42ff9c2c54aeeb77 [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)
18# define __WIN32__
19# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
23extern int access();
24#else
25#include <unistd.h>
26#endif
27
drh75897232000-05-29 14:26:00 +000028/* #define PRIVATE static */
29#define PRIVATE
30
31#ifdef TEST
32#define MAXRHS 5 /* Set low to exercise exception code */
33#else
34#define MAXRHS 1000
35#endif
36
icculusf5ad8242010-02-14 05:34:42 +000037static const char **made_files = NULL;
38static int made_files_count = 0;
39static int successful_exit = 0;
40static void LemonAtExit(void)
41{
42 /* if we failed, delete (most) files we made, to unconfuse build tools. */
43 int i;
44 for (i = 0; i < made_files_count; i++) {
45 if (!successful_exit) {
46 remove(made_files[i]);
47 }
48 free((void *) made_files[i]);
49 }
50 free(made_files);
51 made_files_count = 0;
52 made_files = NULL;
53}
54
drhe9278182007-07-18 18:16:29 +000055static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000056
drh87cf1372008-08-13 20:09:06 +000057/*
58** Compilers are getting increasingly pedantic about type conversions
59** as C evolves ever closer to Ada.... To work around the latest problems
60** we have to define the following variant of strlen().
61*/
62#define lemonStrlen(X) ((int)strlen(X))
63
icculus9e44cf12010-02-14 17:14:22 +000064/* a few forward declarations... */
65struct rule;
66struct lemon;
67struct action;
68
drhe9278182007-07-18 18:16:29 +000069static struct action *Action_new(void);
70static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000071
72/********** From the file "build.h" ************************************/
73void FindRulePrecedences();
74void FindFirstSets();
75void FindStates();
76void FindLinks();
77void FindFollowSets();
78void FindActions();
79
80/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +000081void Configlist_init(void);
82struct config *Configlist_add(struct rule *, int);
83struct config *Configlist_addbasis(struct rule *, int);
84void Configlist_closure(struct lemon *);
85void Configlist_sort(void);
86void Configlist_sortbasis(void);
87struct config *Configlist_return(void);
88struct config *Configlist_basis(void);
89void Configlist_eat(struct config *);
90void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +000091
92/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000093void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000094
95/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +000096enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
97 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +000098struct s_options {
icculus9e44cf12010-02-14 17:14:22 +000099 enum option_type type;
100 const char *label;
drh75897232000-05-29 14:26:00 +0000101 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000102 const char *message;
drh75897232000-05-29 14:26:00 +0000103};
icculus9e44cf12010-02-14 17:14:22 +0000104int OptInit(char**,struct s_options*,FILE*);
105int OptNArgs(void);
106char *OptArg(int);
107void OptErr(int);
108void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000109
110/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000111void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000112
113/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000114struct plink *Plink_new(void);
115void Plink_add(struct plink **, struct config *);
116void Plink_copy(struct plink **, struct plink *);
117void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000118
119/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000120void Reprint(struct lemon *);
121void ReportOutput(struct lemon *);
122void ReportTable(struct lemon *, int);
123void ReportHeader(struct lemon *);
124void CompressTables(struct lemon *);
125void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000126
127/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000128void SetSize(int); /* All sets will be of size N */
129char *SetNew(void); /* A new set for element 0..N */
130void SetFree(char*); /* Deallocate a set */
drh75897232000-05-29 14:26:00 +0000131
icculus9e44cf12010-02-14 17:14:22 +0000132char *SetNew(void); /* A new set for element 0..N */
133int SetAdd(char*,int); /* Add element to a set */
134int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000135#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
136
137/********** From the file "struct.h" *************************************/
138/*
139** Principal data structures for the LEMON parser generator.
140*/
141
drhaa9f1122007-08-23 02:50:56 +0000142typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000143
144/* Symbols (terminals and nonterminals) of the grammar are stored
145** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000146enum symbol_type {
147 TERMINAL,
148 NONTERMINAL,
149 MULTITERMINAL
150};
151enum e_assoc {
drh75897232000-05-29 14:26:00 +0000152 LEFT,
153 RIGHT,
154 NONE,
155 UNK
icculus9e44cf12010-02-14 17:14:22 +0000156};
157struct symbol {
158 const char *name; /* Name of the symbol */
159 int index; /* Index number for this symbol */
160 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
161 struct rule *rule; /* Linked list of rules of this (if an NT) */
162 struct symbol *fallback; /* fallback token in case this token doesn't parse */
163 int prec; /* Precedence if defined (-1 otherwise) */
164 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000165 char *firstset; /* First-set for all rules of this symbol */
166 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000167 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000168 char *destructor; /* Code which executes whenever this symbol is
169 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000170 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000171 char *datatype; /* The data type of information held by this
172 ** object. Only used if type==NONTERMINAL */
173 int dtnum; /* The data type number. In the parser, the value
174 ** stack is a union. The .yy%d element of this
175 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000176 /* The following fields are used by MULTITERMINALs only */
177 int nsubsym; /* Number of constituent symbols in the MULTI */
178 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000179};
180
181/* Each production rule in the grammar is stored in the following
182** structure. */
183struct rule {
184 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000185 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000186 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000187 int ruleline; /* Line number for the rule */
188 int nrhs; /* Number of RHS symbols */
189 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000190 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000191 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000192 const char *code; /* The code executed when this rule is reduced */
drh75897232000-05-29 14:26:00 +0000193 struct symbol *precsym; /* Precedence symbol for this rule */
194 int index; /* An index number for this rule */
195 Boolean canReduce; /* True if this rule is ever reduced */
196 struct rule *nextlhs; /* Next rule with the same LHS */
197 struct rule *next; /* Next rule in the global list */
198};
199
200/* A configuration is a production rule of the grammar together with
201** a mark (dot) showing how much of that rule has been processed so far.
202** Configurations also contain a follow-set which is a list of terminal
203** symbols which are allowed to immediately follow the end of the rule.
204** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000205enum cfgstatus {
206 COMPLETE,
207 INCOMPLETE
208};
drh75897232000-05-29 14:26:00 +0000209struct config {
210 struct rule *rp; /* The rule upon which the configuration is based */
211 int dot; /* The parse point */
212 char *fws; /* Follow-set for this configuration only */
213 struct plink *fplp; /* Follow-set forward propagation links */
214 struct plink *bplp; /* Follow-set backwards propagation links */
215 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000216 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000217 struct config *next; /* Next configuration in the state */
218 struct config *bp; /* The next basis configuration */
219};
220
icculus9e44cf12010-02-14 17:14:22 +0000221enum e_action {
222 SHIFT,
223 ACCEPT,
224 REDUCE,
225 ERROR,
226 SSCONFLICT, /* A shift/shift conflict */
227 SRCONFLICT, /* Was a reduce, but part of a conflict */
228 RRCONFLICT, /* Was a reduce, but part of a conflict */
229 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
230 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
231 NOT_USED /* Deleted by compression */
232};
233
drh75897232000-05-29 14:26:00 +0000234/* Every shift or reduce operation is stored as one of the following */
235struct action {
236 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000237 enum e_action type;
drh75897232000-05-29 14:26:00 +0000238 union {
239 struct state *stp; /* The new state, if a shift */
240 struct rule *rp; /* The rule, if a reduce */
241 } x;
242 struct action *next; /* Next action for this state */
243 struct action *collide; /* Next action with the same hash */
244};
245
246/* Each state of the generated parser's finite state machine
247** is encoded as an instance of the following structure. */
248struct state {
249 struct config *bp; /* The basis configurations for this state */
250 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000251 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000252 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000253 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
254 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
255 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000256};
drh8b582012003-10-21 13:16:03 +0000257#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000258
259/* A followset propagation link indicates that the contents of one
260** configuration followset should be propagated to another whenever
261** the first changes. */
262struct plink {
263 struct config *cfp; /* The configuration to which linked */
264 struct plink *next; /* The next propagate link */
265};
266
267/* The state vector for the entire parser generator is recorded as
268** follows. (LEMON uses no global variables and makes little use of
269** static variables. Fields in the following structure can be thought
270** of as begin global variables in the program.) */
271struct lemon {
272 struct state **sorted; /* Table of states sorted by state number */
273 struct rule *rule; /* List of all rules */
274 int nstate; /* Number of states */
275 int nrule; /* Number of rules */
276 int nsymbol; /* Number of terminal and nonterminal symbols */
277 int nterminal; /* Number of terminal symbols */
278 struct symbol **symbols; /* Sorted array of pointers to symbols */
279 int errorcnt; /* Number of errors */
280 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000281 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000282 char *name; /* Name of the generated parser */
283 char *arg; /* Declaration of the 3th argument to parser */
284 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000285 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000286 char *start; /* Name of the start symbol for the grammar */
287 char *stacksize; /* Size of the parser stack */
288 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000289 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000290 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000291 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000292 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000293 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000294 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000295 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000296 char *filename; /* Name of the input file */
297 char *outname; /* Name of the current output file */
298 char *tokenprefix; /* A prefix added to token names in the .h file */
299 int nconflict; /* Number of parsing conflicts */
icculus42585cf2010-02-14 05:19:56 +0000300 int nexpected; /* Number of expected parsing conflicts */
drh75897232000-05-29 14:26:00 +0000301 int tablesize; /* Size of the parse tables */
302 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000303 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000304 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000305 char *argv0; /* Name of the program */
306};
307
308#define MemoryCheck(X) if((X)==0){ \
309 extern void memory_error(); \
310 memory_error(); \
311}
312
313/**************** From the file "table.h" *********************************/
314/*
315** All code in this file has been automatically generated
316** from a specification in the file
317** "table.q"
318** by the associative array code building program "aagen".
319** Do not edit this file! Instead, edit the specification
320** file, then rerun aagen.
321*/
322/*
323** Code for processing tables in the LEMON parser generator.
324*/
drh75897232000-05-29 14:26:00 +0000325/* Routines for handling a strings */
326
icculus9e44cf12010-02-14 17:14:22 +0000327const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000328
icculus9e44cf12010-02-14 17:14:22 +0000329void Strsafe_init(void);
330int Strsafe_insert(const char *);
331const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000332
333/* Routines for handling symbols of the grammar */
334
icculus9e44cf12010-02-14 17:14:22 +0000335struct symbol *Symbol_new(const char *);
336int Symbolcmpp(const void *, const void *);
337void Symbol_init(void);
338int Symbol_insert(struct symbol *, const char *);
339struct symbol *Symbol_find(const char *);
340struct symbol *Symbol_Nth(int);
341int Symbol_count(void);
342struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000343
344/* Routines to manage the state table */
345
icculus9e44cf12010-02-14 17:14:22 +0000346int Configcmp(const char *, const char *);
347struct state *State_new(void);
348void State_init(void);
349int State_insert(struct state *, struct config *);
350struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000351struct state **State_arrayof(/* */);
352
353/* Routines used for efficiency in Configlist_add */
354
icculus9e44cf12010-02-14 17:14:22 +0000355void Configtable_init(void);
356int Configtable_insert(struct config *);
357struct config *Configtable_find(struct config *);
358void Configtable_clear(int(*)(struct config *));
359
drh75897232000-05-29 14:26:00 +0000360/****************** From the file "action.c" *******************************/
361/*
362** Routines processing parser actions in the LEMON parser generator.
363*/
364
365/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000366static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000367 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000368 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000369
370 if( freelist==0 ){
371 int i;
372 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000373 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000374 if( freelist==0 ){
375 fprintf(stderr,"Unable to allocate memory for a new parser action.");
376 exit(1);
377 }
378 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
379 freelist[amt-1].next = 0;
380 }
icculus9e44cf12010-02-14 17:14:22 +0000381 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000382 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000383 return newaction;
drh75897232000-05-29 14:26:00 +0000384}
385
drhe9278182007-07-18 18:16:29 +0000386/* Compare two actions for sorting purposes. Return negative, zero, or
387** positive if the first action is less than, equal to, or greater than
388** the first
389*/
390static int actioncmp(
391 struct action *ap1,
392 struct action *ap2
393){
drh75897232000-05-29 14:26:00 +0000394 int rc;
395 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000396 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000397 rc = (int)ap1->type - (int)ap2->type;
398 }
399 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000400 rc = ap1->x.rp->index - ap2->x.rp->index;
401 }
drhe594bc32009-11-03 13:02:25 +0000402 if( rc==0 ){
403 rc = ap2 - ap1;
404 }
drh75897232000-05-29 14:26:00 +0000405 return rc;
406}
407
408/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000409static struct action *Action_sort(
410 struct action *ap
411){
412 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
413 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000414 return ap;
415}
416
icculus9e44cf12010-02-14 17:14:22 +0000417void Action_add(
418 struct action **app,
419 enum e_action type,
420 struct symbol *sp,
421 char *arg
422){
423 struct action *newaction;
424 newaction = Action_new();
425 newaction->next = *app;
426 *app = newaction;
427 newaction->type = type;
428 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000429 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000430 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000431 }else{
icculus9e44cf12010-02-14 17:14:22 +0000432 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000433 }
434}
drh8b582012003-10-21 13:16:03 +0000435/********************** New code to implement the "acttab" module ***********/
436/*
437** This module implements routines use to construct the yy_action[] table.
438*/
439
440/*
441** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000442** the following structure.
443**
444** The yy_action table maps the pair (state_number, lookahead) into an
445** action_number. The table is an array of integers pairs. The state_number
446** determines an initial offset into the yy_action array. The lookahead
447** value is then added to this initial offset to get an index X into the
448** yy_action array. If the aAction[X].lookahead equals the value of the
449** of the lookahead input, then the value of the action_number output is
450** aAction[X].action. If the lookaheads do not match then the
451** default action for the state_number is returned.
452**
453** All actions associated with a single state_number are first entered
454** into aLookahead[] using multiple calls to acttab_action(). Then the
455** actions for that single state_number are placed into the aAction[]
456** array with a single call to acttab_insert(). The acttab_insert() call
457** also resets the aLookahead[] array in preparation for the next
458** state number.
drh8b582012003-10-21 13:16:03 +0000459*/
icculus9e44cf12010-02-14 17:14:22 +0000460struct lookahead_action {
461 int lookahead; /* Value of the lookahead token */
462 int action; /* Action to take on the given lookahead */
463};
drh8b582012003-10-21 13:16:03 +0000464typedef struct acttab acttab;
465struct acttab {
466 int nAction; /* Number of used slots in aAction[] */
467 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000468 struct lookahead_action
469 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000470 *aLookahead; /* A single new transaction set */
471 int mnLookahead; /* Minimum aLookahead[].lookahead */
472 int mnAction; /* Action associated with mnLookahead */
473 int mxLookahead; /* Maximum aLookahead[].lookahead */
474 int nLookahead; /* Used slots in aLookahead[] */
475 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
476};
477
478/* Return the number of entries in the yy_action table */
479#define acttab_size(X) ((X)->nAction)
480
481/* The value for the N-th entry in yy_action */
482#define acttab_yyaction(X,N) ((X)->aAction[N].action)
483
484/* The value for the N-th entry in yy_lookahead */
485#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
486
487/* Free all memory associated with the given acttab */
488void acttab_free(acttab *p){
489 free( p->aAction );
490 free( p->aLookahead );
491 free( p );
492}
493
494/* Allocate a new acttab structure */
495acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000496 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000497 if( p==0 ){
498 fprintf(stderr,"Unable to allocate memory for a new acttab.");
499 exit(1);
500 }
501 memset(p, 0, sizeof(*p));
502 return p;
503}
504
drh8dc3e8f2010-01-07 03:53:03 +0000505/* Add a new action to the current transaction set.
506**
507** This routine is called once for each lookahead for a particular
508** state.
drh8b582012003-10-21 13:16:03 +0000509*/
510void acttab_action(acttab *p, int lookahead, int action){
511 if( p->nLookahead>=p->nLookaheadAlloc ){
512 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000513 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000514 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
515 if( p->aLookahead==0 ){
516 fprintf(stderr,"malloc failed\n");
517 exit(1);
518 }
519 }
520 if( p->nLookahead==0 ){
521 p->mxLookahead = lookahead;
522 p->mnLookahead = lookahead;
523 p->mnAction = action;
524 }else{
525 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
526 if( p->mnLookahead>lookahead ){
527 p->mnLookahead = lookahead;
528 p->mnAction = action;
529 }
530 }
531 p->aLookahead[p->nLookahead].lookahead = lookahead;
532 p->aLookahead[p->nLookahead].action = action;
533 p->nLookahead++;
534}
535
536/*
537** Add the transaction set built up with prior calls to acttab_action()
538** into the current action table. Then reset the transaction set back
539** to an empty set in preparation for a new round of acttab_action() calls.
540**
541** Return the offset into the action table of the new transaction.
542*/
543int acttab_insert(acttab *p){
544 int i, j, k, n;
545 assert( p->nLookahead>0 );
546
547 /* Make sure we have enough space to hold the expanded action table
548 ** in the worst case. The worst case occurs if the transaction set
549 ** must be appended to the current action table
550 */
drh784d86f2004-02-19 18:41:53 +0000551 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000552 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000553 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000554 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000555 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000556 sizeof(p->aAction[0])*p->nActionAlloc);
557 if( p->aAction==0 ){
558 fprintf(stderr,"malloc failed\n");
559 exit(1);
560 }
drhfdbf9282003-10-21 16:34:41 +0000561 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000562 p->aAction[i].lookahead = -1;
563 p->aAction[i].action = -1;
564 }
565 }
566
drh8dc3e8f2010-01-07 03:53:03 +0000567 /* Scan the existing action table looking for an offset that is a
568 ** duplicate of the current transaction set. Fall out of the loop
569 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000570 **
571 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
572 */
drh8dc3e8f2010-01-07 03:53:03 +0000573 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000574 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000575 /* All lookaheads and actions in the aLookahead[] transaction
576 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000577 if( p->aAction[i].action!=p->mnAction ) continue;
578 for(j=0; j<p->nLookahead; j++){
579 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
580 if( k<0 || k>=p->nAction ) break;
581 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
582 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
583 }
584 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000585
586 /* No possible lookahead value that is not in the aLookahead[]
587 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000588 n = 0;
589 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000590 if( p->aAction[j].lookahead<0 ) continue;
591 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000592 }
drhfdbf9282003-10-21 16:34:41 +0000593 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000594 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000595 }
drh8b582012003-10-21 13:16:03 +0000596 }
597 }
drh8dc3e8f2010-01-07 03:53:03 +0000598
599 /* If no existing offsets exactly match the current transaction, find an
600 ** an empty offset in the aAction[] table in which we can add the
601 ** aLookahead[] transaction.
602 */
drhf16371d2009-11-03 19:18:31 +0000603 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000604 /* Look for holes in the aAction[] table that fit the current
605 ** aLookahead[] transaction. Leave i set to the offset of the hole.
606 ** If no holes are found, i is left at p->nAction, which means the
607 ** transaction will be appended. */
608 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000609 if( p->aAction[i].lookahead<0 ){
610 for(j=0; j<p->nLookahead; j++){
611 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
612 if( k<0 ) break;
613 if( p->aAction[k].lookahead>=0 ) break;
614 }
615 if( j<p->nLookahead ) continue;
616 for(j=0; j<p->nAction; j++){
617 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
618 }
619 if( j==p->nAction ){
620 break; /* Fits in empty slots */
621 }
622 }
623 }
624 }
drh8b582012003-10-21 13:16:03 +0000625 /* Insert transaction set at index i. */
626 for(j=0; j<p->nLookahead; j++){
627 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
628 p->aAction[k] = p->aLookahead[j];
629 if( k>=p->nAction ) p->nAction = k+1;
630 }
631 p->nLookahead = 0;
632
633 /* Return the offset that is added to the lookahead in order to get the
634 ** index into yy_action of the action */
635 return i - p->mnLookahead;
636}
637
drh75897232000-05-29 14:26:00 +0000638/********************** From the file "build.c" *****************************/
639/*
640** Routines to construction the finite state machine for the LEMON
641** parser generator.
642*/
643
644/* Find a precedence symbol of every rule in the grammar.
645**
646** Those rules which have a precedence symbol coded in the input
647** grammar using the "[symbol]" construct will already have the
648** rp->precsym field filled. Other rules take as their precedence
649** symbol the first RHS symbol with a defined precedence. If there
650** are not RHS symbols with a defined precedence, the precedence
651** symbol field is left blank.
652*/
icculus9e44cf12010-02-14 17:14:22 +0000653void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000654{
655 struct rule *rp;
656 for(rp=xp->rule; rp; rp=rp->next){
657 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000658 int i, j;
659 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
660 struct symbol *sp = rp->rhs[i];
661 if( sp->type==MULTITERMINAL ){
662 for(j=0; j<sp->nsubsym; j++){
663 if( sp->subsym[j]->prec>=0 ){
664 rp->precsym = sp->subsym[j];
665 break;
666 }
667 }
668 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000669 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000670 }
671 }
672 }
673 }
674 return;
675}
676
677/* Find all nonterminals which will generate the empty string.
678** Then go back and compute the first sets of every nonterminal.
679** The first set is the set of all terminal symbols which can begin
680** a string generated by that nonterminal.
681*/
icculus9e44cf12010-02-14 17:14:22 +0000682void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000683{
drhfd405312005-11-06 04:06:59 +0000684 int i, j;
drh75897232000-05-29 14:26:00 +0000685 struct rule *rp;
686 int progress;
687
688 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000689 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000690 }
691 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
692 lemp->symbols[i]->firstset = SetNew();
693 }
694
695 /* First compute all lambdas */
696 do{
697 progress = 0;
698 for(rp=lemp->rule; rp; rp=rp->next){
699 if( rp->lhs->lambda ) continue;
700 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000701 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000702 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000703 }
704 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000705 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000706 progress = 1;
707 }
708 }
709 }while( progress );
710
711 /* Now compute all first sets */
712 do{
713 struct symbol *s1, *s2;
714 progress = 0;
715 for(rp=lemp->rule; rp; rp=rp->next){
716 s1 = rp->lhs;
717 for(i=0; i<rp->nrhs; i++){
718 s2 = rp->rhs[i];
719 if( s2->type==TERMINAL ){
720 progress += SetAdd(s1->firstset,s2->index);
721 break;
drhfd405312005-11-06 04:06:59 +0000722 }else if( s2->type==MULTITERMINAL ){
723 for(j=0; j<s2->nsubsym; j++){
724 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
725 }
726 break;
drh75897232000-05-29 14:26:00 +0000727 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000728 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000729 }else{
730 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000731 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000732 }
733 }
734 }
735 }while( progress );
736 return;
737}
738
739/* Compute all LR(0) states for the grammar. Links
740** are added to between some states so that the LR(1) follow sets
741** can be computed later.
742*/
icculus9e44cf12010-02-14 17:14:22 +0000743PRIVATE struct state *getstate(struct lemon *); /* forward reference */
744void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000745{
746 struct symbol *sp;
747 struct rule *rp;
748
749 Configlist_init();
750
751 /* Find the start symbol */
752 if( lemp->start ){
753 sp = Symbol_find(lemp->start);
754 if( sp==0 ){
755 ErrorMsg(lemp->filename,0,
756"The specified start symbol \"%s\" is not \
757in a nonterminal of the grammar. \"%s\" will be used as the start \
758symbol instead.",lemp->start,lemp->rule->lhs->name);
759 lemp->errorcnt++;
760 sp = lemp->rule->lhs;
761 }
762 }else{
763 sp = lemp->rule->lhs;
764 }
765
766 /* Make sure the start symbol doesn't occur on the right-hand side of
767 ** any rule. Report an error if it does. (YACC would generate a new
768 ** start symbol in this case.) */
769 for(rp=lemp->rule; rp; rp=rp->next){
770 int i;
771 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000772 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000773 ErrorMsg(lemp->filename,0,
774"The start symbol \"%s\" occurs on the \
775right-hand side of a rule. This will result in a parser which \
776does not work properly.",sp->name);
777 lemp->errorcnt++;
778 }
779 }
780 }
781
782 /* The basis configuration set for the first state
783 ** is all rules which have the start symbol as their
784 ** left-hand side */
785 for(rp=sp->rule; rp; rp=rp->nextlhs){
786 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000787 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000788 newcfp = Configlist_addbasis(rp,0);
789 SetAdd(newcfp->fws,0);
790 }
791
792 /* Compute the first state. All other states will be
793 ** computed automatically during the computation of the first one.
794 ** The returned pointer to the first state is not used. */
795 (void)getstate(lemp);
796 return;
797}
798
799/* Return a pointer to a state which is described by the configuration
800** list which has been built from calls to Configlist_add.
801*/
icculus9e44cf12010-02-14 17:14:22 +0000802PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
803PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000804{
805 struct config *cfp, *bp;
806 struct state *stp;
807
808 /* Extract the sorted basis of the new state. The basis was constructed
809 ** by prior calls to "Configlist_addbasis()". */
810 Configlist_sortbasis();
811 bp = Configlist_basis();
812
813 /* Get a state with the same basis */
814 stp = State_find(bp);
815 if( stp ){
816 /* A state with the same basis already exists! Copy all the follow-set
817 ** propagation links from the state under construction into the
818 ** preexisting state, then return a pointer to the preexisting state */
819 struct config *x, *y;
820 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
821 Plink_copy(&y->bplp,x->bplp);
822 Plink_delete(x->fplp);
823 x->fplp = x->bplp = 0;
824 }
825 cfp = Configlist_return();
826 Configlist_eat(cfp);
827 }else{
828 /* This really is a new state. Construct all the details */
829 Configlist_closure(lemp); /* Compute the configuration closure */
830 Configlist_sort(); /* Sort the configuration closure */
831 cfp = Configlist_return(); /* Get a pointer to the config list */
832 stp = State_new(); /* A new state structure */
833 MemoryCheck(stp);
834 stp->bp = bp; /* Remember the configuration basis */
835 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000836 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000837 stp->ap = 0; /* No actions, yet. */
838 State_insert(stp,stp->bp); /* Add to the state table */
839 buildshifts(lemp,stp); /* Recursively compute successor states */
840 }
841 return stp;
842}
843
drhfd405312005-11-06 04:06:59 +0000844/*
845** Return true if two symbols are the same.
846*/
icculus9e44cf12010-02-14 17:14:22 +0000847int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000848{
849 int i;
850 if( a==b ) return 1;
851 if( a->type!=MULTITERMINAL ) return 0;
852 if( b->type!=MULTITERMINAL ) return 0;
853 if( a->nsubsym!=b->nsubsym ) return 0;
854 for(i=0; i<a->nsubsym; i++){
855 if( a->subsym[i]!=b->subsym[i] ) return 0;
856 }
857 return 1;
858}
859
drh75897232000-05-29 14:26:00 +0000860/* Construct all successor states to the given state. A "successor"
861** state is any state which can be reached by a shift action.
862*/
icculus9e44cf12010-02-14 17:14:22 +0000863PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000864{
865 struct config *cfp; /* For looping thru the config closure of "stp" */
866 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000867 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000868 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
869 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
870 struct state *newstp; /* A pointer to a successor state */
871
872 /* Each configuration becomes complete after it contibutes to a successor
873 ** state. Initially, all configurations are incomplete */
874 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
875
876 /* Loop through all configurations of the state "stp" */
877 for(cfp=stp->cfp; cfp; cfp=cfp->next){
878 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
879 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
880 Configlist_reset(); /* Reset the new config set */
881 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
882
883 /* For every configuration in the state "stp" which has the symbol "sp"
884 ** following its dot, add the same configuration to the basis set under
885 ** construction but with the dot shifted one symbol to the right. */
886 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
887 if( bcfp->status==COMPLETE ) continue; /* Already used */
888 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
889 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000890 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000891 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000892 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
893 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000894 }
895
896 /* Get a pointer to the state described by the basis configuration set
897 ** constructed in the preceding loop */
898 newstp = getstate(lemp);
899
900 /* The state "newstp" is reached from the state "stp" by a shift action
901 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000902 if( sp->type==MULTITERMINAL ){
903 int i;
904 for(i=0; i<sp->nsubsym; i++){
905 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
906 }
907 }else{
908 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
909 }
drh75897232000-05-29 14:26:00 +0000910 }
911}
912
913/*
914** Construct the propagation links
915*/
icculus9e44cf12010-02-14 17:14:22 +0000916void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000917{
918 int i;
919 struct config *cfp, *other;
920 struct state *stp;
921 struct plink *plp;
922
923 /* Housekeeping detail:
924 ** Add to every propagate link a pointer back to the state to
925 ** which the link is attached. */
926 for(i=0; i<lemp->nstate; i++){
927 stp = lemp->sorted[i];
928 for(cfp=stp->cfp; cfp; cfp=cfp->next){
929 cfp->stp = stp;
930 }
931 }
932
933 /* Convert all backlinks into forward links. Only the forward
934 ** links are used in the follow-set computation. */
935 for(i=0; i<lemp->nstate; i++){
936 stp = lemp->sorted[i];
937 for(cfp=stp->cfp; cfp; cfp=cfp->next){
938 for(plp=cfp->bplp; plp; plp=plp->next){
939 other = plp->cfp;
940 Plink_add(&other->fplp,cfp);
941 }
942 }
943 }
944}
945
946/* Compute all followsets.
947**
948** A followset is the set of all symbols which can come immediately
949** after a configuration.
950*/
icculus9e44cf12010-02-14 17:14:22 +0000951void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000952{
953 int i;
954 struct config *cfp;
955 struct plink *plp;
956 int progress;
957 int change;
958
959 for(i=0; i<lemp->nstate; i++){
960 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
961 cfp->status = INCOMPLETE;
962 }
963 }
964
965 do{
966 progress = 0;
967 for(i=0; i<lemp->nstate; i++){
968 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
969 if( cfp->status==COMPLETE ) continue;
970 for(plp=cfp->fplp; plp; plp=plp->next){
971 change = SetUnion(plp->cfp->fws,cfp->fws);
972 if( change ){
973 plp->cfp->status = INCOMPLETE;
974 progress = 1;
975 }
976 }
977 cfp->status = COMPLETE;
978 }
979 }
980 }while( progress );
981}
982
icculus9e44cf12010-02-14 17:14:22 +0000983static int resolve_conflict(struct action *,struct action *, struct symbol *);
drh75897232000-05-29 14:26:00 +0000984
985/* Compute the reduce actions, and resolve conflicts.
986*/
icculus9e44cf12010-02-14 17:14:22 +0000987void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000988{
989 int i,j;
990 struct config *cfp;
991 struct state *stp;
992 struct symbol *sp;
993 struct rule *rp;
994
995 /* Add all of the reduce actions
996 ** A reduce action is added for each element of the followset of
997 ** a configuration which has its dot at the extreme right.
998 */
999 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
1000 stp = lemp->sorted[i];
1001 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1002 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1003 for(j=0; j<lemp->nterminal; j++){
1004 if( SetFind(cfp->fws,j) ){
1005 /* Add a reduce action to the state "stp" which will reduce by the
1006 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001007 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001008 }
1009 }
1010 }
1011 }
1012 }
1013
1014 /* Add the accepting token */
1015 if( lemp->start ){
1016 sp = Symbol_find(lemp->start);
1017 if( sp==0 ) sp = lemp->rule->lhs;
1018 }else{
1019 sp = lemp->rule->lhs;
1020 }
1021 /* Add to the first state (which is always the starting state of the
1022 ** finite state machine) an action to ACCEPT if the lookahead is the
1023 ** start nonterminal. */
1024 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1025
1026 /* Resolve conflicts */
1027 for(i=0; i<lemp->nstate; i++){
1028 struct action *ap, *nap;
1029 struct state *stp;
1030 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001031 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001032 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001033 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001034 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1035 /* The two actions "ap" and "nap" have the same lookahead.
1036 ** Figure out which one should be used */
1037 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1038 }
1039 }
1040 }
1041
1042 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001043 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001044 for(i=0; i<lemp->nstate; i++){
1045 struct action *ap;
1046 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001047 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001048 }
1049 }
1050 for(rp=lemp->rule; rp; rp=rp->next){
1051 if( rp->canReduce ) continue;
1052 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1053 lemp->errorcnt++;
1054 }
1055}
1056
1057/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001058** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001059**
1060** NO LONGER TRUE:
1061** To resolve a conflict, first look to see if either action
1062** is on an error rule. In that case, take the action which
1063** is not associated with the error rule. If neither or both
1064** actions are associated with an error rule, then try to
1065** use precedence to resolve the conflict.
1066**
1067** If either action is a SHIFT, then it must be apx. This
1068** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1069*/
icculus9e44cf12010-02-14 17:14:22 +00001070static int resolve_conflict(
1071 struct action *apx,
1072 struct action *apy,
1073 struct symbol *errsym /* The error symbol (if defined. NULL otherwise) */
1074){
drh75897232000-05-29 14:26:00 +00001075 struct symbol *spx, *spy;
1076 int errcnt = 0;
1077 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001078 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001079 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001080 errcnt++;
1081 }
drh75897232000-05-29 14:26:00 +00001082 if( apx->type==SHIFT && apy->type==REDUCE ){
1083 spx = apx->sp;
1084 spy = apy->x.rp->precsym;
1085 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1086 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001087 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001088 errcnt++;
1089 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1090 apy->type = RD_RESOLVED;
1091 }else if( spx->prec<spy->prec ){
1092 apx->type = SH_RESOLVED;
1093 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1094 apy->type = RD_RESOLVED; /* associativity */
1095 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1096 apx->type = SH_RESOLVED;
1097 }else{
1098 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001099 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001100 errcnt++;
1101 }
1102 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1103 spx = apx->x.rp->precsym;
1104 spy = apy->x.rp->precsym;
1105 if( spx==0 || spy==0 || spx->prec<0 ||
1106 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001107 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001108 errcnt++;
1109 }else if( spx->prec>spy->prec ){
1110 apy->type = RD_RESOLVED;
1111 }else if( spx->prec<spy->prec ){
1112 apx->type = RD_RESOLVED;
1113 }
1114 }else{
drhb59499c2002-02-23 18:45:13 +00001115 assert(
1116 apx->type==SH_RESOLVED ||
1117 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001118 apx->type==SSCONFLICT ||
1119 apx->type==SRCONFLICT ||
1120 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001121 apy->type==SH_RESOLVED ||
1122 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001123 apy->type==SSCONFLICT ||
1124 apy->type==SRCONFLICT ||
1125 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001126 );
1127 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1128 ** REDUCEs on the list. If we reach this point it must be because
1129 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001130 }
1131 return errcnt;
1132}
1133/********************* From the file "configlist.c" *************************/
1134/*
1135** Routines to processing a configuration list and building a state
1136** in the LEMON parser generator.
1137*/
1138
1139static struct config *freelist = 0; /* List of free configurations */
1140static struct config *current = 0; /* Top of list of configurations */
1141static struct config **currentend = 0; /* Last on list of configs */
1142static struct config *basis = 0; /* Top of list of basis configs */
1143static struct config **basisend = 0; /* End of list of basis configs */
1144
1145/* Return a pointer to a new configuration */
1146PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001147 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001148 if( freelist==0 ){
1149 int i;
1150 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001151 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001152 if( freelist==0 ){
1153 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1154 exit(1);
1155 }
1156 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1157 freelist[amt-1].next = 0;
1158 }
icculus9e44cf12010-02-14 17:14:22 +00001159 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001160 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001161 return newcfg;
drh75897232000-05-29 14:26:00 +00001162}
1163
1164/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001165PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001166{
1167 old->next = freelist;
1168 freelist = old;
1169}
1170
1171/* Initialized the configuration list builder */
1172void Configlist_init(){
1173 current = 0;
1174 currentend = &current;
1175 basis = 0;
1176 basisend = &basis;
1177 Configtable_init();
1178 return;
1179}
1180
1181/* Initialized the configuration list builder */
1182void Configlist_reset(){
1183 current = 0;
1184 currentend = &current;
1185 basis = 0;
1186 basisend = &basis;
1187 Configtable_clear(0);
1188 return;
1189}
1190
1191/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001192struct config *Configlist_add(
1193 struct rule *rp, /* The rule */
1194 int dot /* Index into the RHS of the rule where the dot goes */
1195){
drh75897232000-05-29 14:26:00 +00001196 struct config *cfp, model;
1197
1198 assert( currentend!=0 );
1199 model.rp = rp;
1200 model.dot = dot;
1201 cfp = Configtable_find(&model);
1202 if( cfp==0 ){
1203 cfp = newconfig();
1204 cfp->rp = rp;
1205 cfp->dot = dot;
1206 cfp->fws = SetNew();
1207 cfp->stp = 0;
1208 cfp->fplp = cfp->bplp = 0;
1209 cfp->next = 0;
1210 cfp->bp = 0;
1211 *currentend = cfp;
1212 currentend = &cfp->next;
1213 Configtable_insert(cfp);
1214 }
1215 return cfp;
1216}
1217
1218/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001219struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001220{
1221 struct config *cfp, model;
1222
1223 assert( basisend!=0 );
1224 assert( currentend!=0 );
1225 model.rp = rp;
1226 model.dot = dot;
1227 cfp = Configtable_find(&model);
1228 if( cfp==0 ){
1229 cfp = newconfig();
1230 cfp->rp = rp;
1231 cfp->dot = dot;
1232 cfp->fws = SetNew();
1233 cfp->stp = 0;
1234 cfp->fplp = cfp->bplp = 0;
1235 cfp->next = 0;
1236 cfp->bp = 0;
1237 *currentend = cfp;
1238 currentend = &cfp->next;
1239 *basisend = cfp;
1240 basisend = &cfp->bp;
1241 Configtable_insert(cfp);
1242 }
1243 return cfp;
1244}
1245
1246/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001247void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001248{
1249 struct config *cfp, *newcfp;
1250 struct rule *rp, *newrp;
1251 struct symbol *sp, *xsp;
1252 int i, dot;
1253
1254 assert( currentend!=0 );
1255 for(cfp=current; cfp; cfp=cfp->next){
1256 rp = cfp->rp;
1257 dot = cfp->dot;
1258 if( dot>=rp->nrhs ) continue;
1259 sp = rp->rhs[dot];
1260 if( sp->type==NONTERMINAL ){
1261 if( sp->rule==0 && sp!=lemp->errsym ){
1262 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1263 sp->name);
1264 lemp->errorcnt++;
1265 }
1266 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1267 newcfp = Configlist_add(newrp,0);
1268 for(i=dot+1; i<rp->nrhs; i++){
1269 xsp = rp->rhs[i];
1270 if( xsp->type==TERMINAL ){
1271 SetAdd(newcfp->fws,xsp->index);
1272 break;
drhfd405312005-11-06 04:06:59 +00001273 }else if( xsp->type==MULTITERMINAL ){
1274 int k;
1275 for(k=0; k<xsp->nsubsym; k++){
1276 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1277 }
1278 break;
drh75897232000-05-29 14:26:00 +00001279 }else{
1280 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001281 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001282 }
1283 }
1284 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1285 }
1286 }
1287 }
1288 return;
1289}
1290
1291/* Sort the configuration list */
1292void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001293 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001294 currentend = 0;
1295 return;
1296}
1297
1298/* Sort the basis configuration list */
1299void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001300 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001301 basisend = 0;
1302 return;
1303}
1304
1305/* Return a pointer to the head of the configuration list and
1306** reset the list */
1307struct config *Configlist_return(){
1308 struct config *old;
1309 old = current;
1310 current = 0;
1311 currentend = 0;
1312 return old;
1313}
1314
1315/* Return a pointer to the head of the configuration list and
1316** reset the list */
1317struct config *Configlist_basis(){
1318 struct config *old;
1319 old = basis;
1320 basis = 0;
1321 basisend = 0;
1322 return old;
1323}
1324
1325/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001326void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001327{
1328 struct config *nextcfp;
1329 for(; cfp; cfp=nextcfp){
1330 nextcfp = cfp->next;
1331 assert( cfp->fplp==0 );
1332 assert( cfp->bplp==0 );
1333 if( cfp->fws ) SetFree(cfp->fws);
1334 deleteconfig(cfp);
1335 }
1336 return;
1337}
1338/***************** From the file "error.c" *********************************/
1339/*
1340** Code for printing error message.
1341*/
1342
1343/* Find a good place to break "msg" so that its length is at least "min"
1344** but no more than "max". Make the point as close to max as possible.
1345*/
icculus9e44cf12010-02-14 17:14:22 +00001346static int findbreak(char *msg, int min, int max)
drh75897232000-05-29 14:26:00 +00001347{
1348 int i,spot;
1349 char c;
1350 for(i=spot=min; i<=max; i++){
1351 c = msg[i];
1352 if( c=='\t' ) msg[i] = ' ';
1353 if( c=='\n' ){ msg[i] = ' '; spot = i; break; }
1354 if( c==0 ){ spot = i; break; }
1355 if( c=='-' && i<max-1 ) spot = i+1;
1356 if( c==' ' ) spot = i;
1357 }
1358 return spot;
1359}
1360
1361/*
1362** The error message is split across multiple lines if necessary. The
1363** splits occur at a space, if there is a space available near the end
1364** of the line.
1365*/
1366#define ERRMSGSIZE 10000 /* Hope this is big enough. No way to error check */
1367#define LINEWIDTH 79 /* Max width of any output line */
1368#define PREFIXLIMIT 30 /* Max width of the prefix on each line */
icculusd1912822010-02-14 05:42:46 +00001369static int noerrorclipping = 0;
drhf9a2e7b2003-04-15 01:49:48 +00001370void ErrorMsg(const char *filename, int lineno, const char *format, ...){
drh75897232000-05-29 14:26:00 +00001371 char errmsg[ERRMSGSIZE];
1372 char prefix[PREFIXLIMIT+10];
1373 int errmsgsize;
1374 int prefixsize;
1375 int availablewidth;
1376 va_list ap;
1377 int end, restart, base;
1378
icculusd1912822010-02-14 05:42:46 +00001379 if( noerrorclipping ) {
1380 fprintf(stderr, "%s:%d: ", filename, lineno);
1381 va_start(ap, format);
1382 vfprintf(stderr,format,ap);
1383 va_end(ap);
1384 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001385 }else{
icculusd1912822010-02-14 05:42:46 +00001386 va_start(ap, format);
1387 /* Prepare a prefix to be prepended to every output line */
1388 if( lineno>0 ){
1389 sprintf(prefix,"%.*s:%d: ",PREFIXLIMIT-10,filename,lineno);
1390 }else{
1391 sprintf(prefix,"%.*s: ",PREFIXLIMIT-10,filename);
1392 }
1393 prefixsize = lemonStrlen(prefix);
1394 availablewidth = LINEWIDTH - prefixsize;
drh75897232000-05-29 14:26:00 +00001395
icculusd1912822010-02-14 05:42:46 +00001396 /* Generate the error message */
1397 vsprintf(errmsg,format,ap);
1398 va_end(ap);
1399 errmsgsize = lemonStrlen(errmsg);
1400 /* Remove trailing '\n's from the error message. */
1401 while( errmsgsize>0 && errmsg[errmsgsize-1]=='\n' ){
1402 errmsg[--errmsgsize] = 0;
1403 }
drh75897232000-05-29 14:26:00 +00001404
icculusd1912822010-02-14 05:42:46 +00001405 /* Print the error message */
1406 base = 0;
1407 while( errmsg[base]!=0 ){
1408 end = restart = findbreak(&errmsg[base],0,availablewidth);
1409 restart += base;
1410 while( errmsg[restart]==' ' ) restart++;
1411 fprintf(stdout,"%s%.*s\n",prefix,end,&errmsg[base]);
1412 base = restart;
1413 }
drh75897232000-05-29 14:26:00 +00001414 }
1415}
1416/**************** From the file "main.c" ************************************/
1417/*
1418** Main program file for the LEMON parser generator.
1419*/
1420
1421/* Report an out-of-memory condition and abort. This function
1422** is used mostly by the "MemoryCheck" macro in struct.h
1423*/
1424void memory_error(){
1425 fprintf(stderr,"Out of memory. Aborting...\n");
1426 exit(1);
1427}
1428
drh6d08b4d2004-07-20 12:45:22 +00001429static int nDefine = 0; /* Number of -D options on the command line */
1430static char **azDefine = 0; /* Name of the -D macros */
1431
1432/* This routine is called with the argument to each -D command-line option.
1433** Add the macro defined to the azDefine array.
1434*/
1435static void handle_D_option(char *z){
1436 char **paz;
1437 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001438 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001439 if( azDefine==0 ){
1440 fprintf(stderr,"out of memory\n");
1441 exit(1);
1442 }
1443 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001444 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001445 if( *paz==0 ){
1446 fprintf(stderr,"out of memory\n");
1447 exit(1);
1448 }
1449 strcpy(*paz, z);
1450 for(z=*paz; *z && *z!='='; z++){}
1451 *z = 0;
1452}
1453
icculus3e143bd2010-02-14 00:48:49 +00001454static char *user_templatename = NULL;
1455static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001456 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001457 if( user_templatename==0 ){
1458 memory_error();
1459 }
1460 strcpy(user_templatename, z);
1461}
drh75897232000-05-29 14:26:00 +00001462
1463/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001464int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001465{
1466 static int version = 0;
1467 static int rpflag = 0;
1468 static int basisflag = 0;
1469 static int compress = 0;
1470 static int quiet = 0;
1471 static int statistics = 0;
1472 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001473 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001474 static struct s_options options[] = {
1475 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
icculusd1912822010-02-14 05:42:46 +00001476 {OPT_FLAG, "e", (char*)&noerrorclipping, "Don't clip error output."},
drh75897232000-05-29 14:26:00 +00001477 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001478 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001479 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001480 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001481 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1482 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001483 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001484 {OPT_FLAG, "s", (char*)&statistics,
1485 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001486 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1487 {OPT_FLAG,0,0,0}
1488 };
1489 int i;
icculus42585cf2010-02-14 05:19:56 +00001490 int exitcode;
drh75897232000-05-29 14:26:00 +00001491 struct lemon lem;
1492
icculusf5ad8242010-02-14 05:34:42 +00001493 atexit(LemonAtExit);
1494
drhb0c86772000-06-02 23:21:26 +00001495 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001496 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001497 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001498 exit(0);
1499 }
drhb0c86772000-06-02 23:21:26 +00001500 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001501 fprintf(stderr,"Exactly one filename argument is required.\n");
1502 exit(1);
1503 }
drh954f6b42006-06-13 13:27:46 +00001504 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001505 lem.errorcnt = 0;
icculus42585cf2010-02-14 05:19:56 +00001506 lem.nexpected = -1;
drh75897232000-05-29 14:26:00 +00001507
1508 /* Initialize the machine */
1509 Strsafe_init();
1510 Symbol_init();
1511 State_init();
1512 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001513 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001514 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001515 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001516 Symbol_new("$");
1517 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001518 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001519
1520 /* Parse the input file */
1521 Parse(&lem);
1522 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001523 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001524 fprintf(stderr,"Empty grammar.\n");
1525 exit(1);
1526 }
1527
1528 /* Count and index the symbols of the grammar */
1529 lem.nsymbol = Symbol_count();
1530 Symbol_new("{default}");
1531 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001532 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
icculus9e44cf12010-02-14 17:14:22 +00001533 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp);
drh75897232000-05-29 14:26:00 +00001534 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1535 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1536 lem.nterminal = i;
1537
1538 /* Generate a reprint of the grammar, if requested on the command line */
1539 if( rpflag ){
1540 Reprint(&lem);
1541 }else{
1542 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001543 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001544
1545 /* Find the precedence for every production rule (that has one) */
1546 FindRulePrecedences(&lem);
1547
1548 /* Compute the lambda-nonterminals and the first-sets for every
1549 ** nonterminal */
1550 FindFirstSets(&lem);
1551
1552 /* Compute all LR(0) states. Also record follow-set propagation
1553 ** links so that the follow-set can be computed later */
1554 lem.nstate = 0;
1555 FindStates(&lem);
1556 lem.sorted = State_arrayof();
1557
1558 /* Tie up loose ends on the propagation links */
1559 FindLinks(&lem);
1560
1561 /* Compute the follow set of every reducible configuration */
1562 FindFollowSets(&lem);
1563
1564 /* Compute the action tables */
1565 FindActions(&lem);
1566
1567 /* Compress the action tables */
1568 if( compress==0 ) CompressTables(&lem);
1569
drhada354d2005-11-05 15:03:59 +00001570 /* Reorder and renumber the states so that states with fewer choices
1571 ** occur at the end. */
1572 ResortStates(&lem);
1573
drh75897232000-05-29 14:26:00 +00001574 /* Generate a report of the parser generated. (the "y.output" file) */
1575 if( !quiet ) ReportOutput(&lem);
1576
1577 /* Generate the source code for the parser */
1578 ReportTable(&lem, mhflag);
1579
1580 /* Produce a header file for use by the scanner. (This step is
1581 ** omitted if the "-m" option is used because makeheaders will
1582 ** generate the file for us.) */
1583 if( !mhflag ) ReportHeader(&lem);
1584 }
1585 if( statistics ){
1586 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1587 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1588 printf(" %d states, %d parser table entries, %d conflicts\n",
1589 lem.nstate, lem.tablesize, lem.nconflict);
1590 }
icculus42585cf2010-02-14 05:19:56 +00001591 if( lem.nexpected < 0 ) {
1592 lem.nexpected = 0; /* grammar didn't have an %expect declaration. */
drh75897232000-05-29 14:26:00 +00001593 }
icculus42585cf2010-02-14 05:19:56 +00001594 if( lem.nconflict != lem.nexpected ){
1595 fprintf(stderr,"%d parsing conflicts (%d expected).\n",lem.nconflict,lem.nexpected);
1596 }
1597
1598 /* return 0 on success, 1 on failure. */
1599 exitcode = ((lem.errorcnt > 0) || (lem.nconflict != lem.nexpected)) ? 1 : 0;
icculusf5ad8242010-02-14 05:34:42 +00001600 successful_exit = (exitcode == 0);
icculus42585cf2010-02-14 05:19:56 +00001601 exit(exitcode);
1602 return (exitcode);
drh75897232000-05-29 14:26:00 +00001603}
1604/******************** From the file "msort.c" *******************************/
1605/*
1606** A generic merge-sort program.
1607**
1608** USAGE:
1609** Let "ptr" be a pointer to some structure which is at the head of
1610** a null-terminated list. Then to sort the list call:
1611**
1612** ptr = msort(ptr,&(ptr->next),cmpfnc);
1613**
1614** In the above, "cmpfnc" is a pointer to a function which compares
1615** two instances of the structure and returns an integer, as in
1616** strcmp. The second argument is a pointer to the pointer to the
1617** second element of the linked list. This address is used to compute
1618** the offset to the "next" field within the structure. The offset to
1619** the "next" field must be constant for all structures in the list.
1620**
1621** The function returns a new pointer which is the head of the list
1622** after sorting.
1623**
1624** ALGORITHM:
1625** Merge-sort.
1626*/
1627
1628/*
1629** Return a pointer to the next structure in the linked list.
1630*/
drhba99af52001-10-25 20:37:16 +00001631#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001632
1633/*
1634** Inputs:
1635** a: A sorted, null-terminated linked list. (May be null).
1636** b: A sorted, null-terminated linked list. (May be null).
1637** cmp: A pointer to the comparison function.
1638** offset: Offset in the structure to the "next" field.
1639**
1640** Return Value:
1641** A pointer to the head of a sorted list containing the elements
1642** of both a and b.
1643**
1644** Side effects:
1645** The "next" pointers for elements in the lists a and b are
1646** changed.
1647*/
drhe9278182007-07-18 18:16:29 +00001648static char *merge(
1649 char *a,
1650 char *b,
1651 int (*cmp)(const char*,const char*),
1652 int offset
1653){
drh75897232000-05-29 14:26:00 +00001654 char *ptr, *head;
1655
1656 if( a==0 ){
1657 head = b;
1658 }else if( b==0 ){
1659 head = a;
1660 }else{
drhe594bc32009-11-03 13:02:25 +00001661 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001662 ptr = a;
1663 a = NEXT(a);
1664 }else{
1665 ptr = b;
1666 b = NEXT(b);
1667 }
1668 head = ptr;
1669 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001670 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001671 NEXT(ptr) = a;
1672 ptr = a;
1673 a = NEXT(a);
1674 }else{
1675 NEXT(ptr) = b;
1676 ptr = b;
1677 b = NEXT(b);
1678 }
1679 }
1680 if( a ) NEXT(ptr) = a;
1681 else NEXT(ptr) = b;
1682 }
1683 return head;
1684}
1685
1686/*
1687** Inputs:
1688** list: Pointer to a singly-linked list of structures.
1689** next: Pointer to pointer to the second element of the list.
1690** cmp: A comparison function.
1691**
1692** Return Value:
1693** A pointer to the head of a sorted list containing the elements
1694** orginally in list.
1695**
1696** Side effects:
1697** The "next" pointers for elements in list are changed.
1698*/
1699#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001700static char *msort(
1701 char *list,
1702 char **next,
1703 int (*cmp)(const char*,const char*)
1704){
drhba99af52001-10-25 20:37:16 +00001705 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001706 char *ep;
1707 char *set[LISTSIZE];
1708 int i;
drhba99af52001-10-25 20:37:16 +00001709 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001710 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1711 while( list ){
1712 ep = list;
1713 list = NEXT(list);
1714 NEXT(ep) = 0;
1715 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1716 ep = merge(ep,set[i],cmp,offset);
1717 set[i] = 0;
1718 }
1719 set[i] = ep;
1720 }
1721 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001722 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001723 return ep;
1724}
1725/************************ From the file "option.c" **************************/
1726static char **argv;
1727static struct s_options *op;
1728static FILE *errstream;
1729
1730#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1731
1732/*
1733** Print the command line with a carrot pointing to the k-th character
1734** of the n-th field.
1735*/
icculus9e44cf12010-02-14 17:14:22 +00001736static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001737{
1738 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001739 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001740 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001741 for(i=1; i<n && argv[i]; i++){
1742 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001743 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001744 }
1745 spcnt += k;
1746 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1747 if( spcnt<20 ){
1748 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1749 }else{
1750 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1751 }
1752}
1753
1754/*
1755** Return the index of the N-th non-switch argument. Return -1
1756** if N is out of range.
1757*/
icculus9e44cf12010-02-14 17:14:22 +00001758static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001759{
1760 int i;
1761 int dashdash = 0;
1762 if( argv!=0 && *argv!=0 ){
1763 for(i=1; argv[i]; i++){
1764 if( dashdash || !ISOPT(argv[i]) ){
1765 if( n==0 ) return i;
1766 n--;
1767 }
1768 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1769 }
1770 }
1771 return -1;
1772}
1773
1774static char emsg[] = "Command line syntax error: ";
1775
1776/*
1777** Process a flag command line argument.
1778*/
icculus9e44cf12010-02-14 17:14:22 +00001779static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001780{
1781 int v;
1782 int errcnt = 0;
1783 int j;
1784 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001785 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001786 }
1787 v = argv[i][0]=='-' ? 1 : 0;
1788 if( op[j].label==0 ){
1789 if( err ){
1790 fprintf(err,"%sundefined option.\n",emsg);
1791 errline(i,1,err);
1792 }
1793 errcnt++;
1794 }else if( op[j].type==OPT_FLAG ){
1795 *((int*)op[j].arg) = v;
1796 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001797 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001798 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001799 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001800 }else{
1801 if( err ){
1802 fprintf(err,"%smissing argument on switch.\n",emsg);
1803 errline(i,1,err);
1804 }
1805 errcnt++;
1806 }
1807 return errcnt;
1808}
1809
1810/*
1811** Process a command line switch which has an argument.
1812*/
icculus9e44cf12010-02-14 17:14:22 +00001813static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001814{
1815 int lv = 0;
1816 double dv = 0.0;
1817 char *sv = 0, *end;
1818 char *cp;
1819 int j;
1820 int errcnt = 0;
1821 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001822 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001823 *cp = 0;
1824 for(j=0; op[j].label; j++){
1825 if( strcmp(argv[i],op[j].label)==0 ) break;
1826 }
1827 *cp = '=';
1828 if( op[j].label==0 ){
1829 if( err ){
1830 fprintf(err,"%sundefined option.\n",emsg);
1831 errline(i,0,err);
1832 }
1833 errcnt++;
1834 }else{
1835 cp++;
1836 switch( op[j].type ){
1837 case OPT_FLAG:
1838 case OPT_FFLAG:
1839 if( err ){
1840 fprintf(err,"%soption requires an argument.\n",emsg);
1841 errline(i,0,err);
1842 }
1843 errcnt++;
1844 break;
1845 case OPT_DBL:
1846 case OPT_FDBL:
1847 dv = strtod(cp,&end);
1848 if( *end ){
1849 if( err ){
1850 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001851 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001852 }
1853 errcnt++;
1854 }
1855 break;
1856 case OPT_INT:
1857 case OPT_FINT:
1858 lv = strtol(cp,&end,0);
1859 if( *end ){
1860 if( err ){
1861 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001862 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001863 }
1864 errcnt++;
1865 }
1866 break;
1867 case OPT_STR:
1868 case OPT_FSTR:
1869 sv = cp;
1870 break;
1871 }
1872 switch( op[j].type ){
1873 case OPT_FLAG:
1874 case OPT_FFLAG:
1875 break;
1876 case OPT_DBL:
1877 *(double*)(op[j].arg) = dv;
1878 break;
1879 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001880 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001881 break;
1882 case OPT_INT:
1883 *(int*)(op[j].arg) = lv;
1884 break;
1885 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001886 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001887 break;
1888 case OPT_STR:
1889 *(char**)(op[j].arg) = sv;
1890 break;
1891 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001892 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001893 break;
1894 }
1895 }
1896 return errcnt;
1897}
1898
icculus9e44cf12010-02-14 17:14:22 +00001899int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001900{
1901 int errcnt = 0;
1902 argv = a;
1903 op = o;
1904 errstream = err;
1905 if( argv && *argv && op ){
1906 int i;
1907 for(i=1; argv[i]; i++){
1908 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1909 errcnt += handleflags(i,err);
1910 }else if( strchr(argv[i],'=') ){
1911 errcnt += handleswitch(i,err);
1912 }
1913 }
1914 }
1915 if( errcnt>0 ){
1916 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001917 OptPrint();
drh75897232000-05-29 14:26:00 +00001918 exit(1);
1919 }
1920 return 0;
1921}
1922
drhb0c86772000-06-02 23:21:26 +00001923int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001924 int cnt = 0;
1925 int dashdash = 0;
1926 int i;
1927 if( argv!=0 && argv[0]!=0 ){
1928 for(i=1; argv[i]; i++){
1929 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1930 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1931 }
1932 }
1933 return cnt;
1934}
1935
icculus9e44cf12010-02-14 17:14:22 +00001936char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001937{
1938 int i;
1939 i = argindex(n);
1940 return i>=0 ? argv[i] : 0;
1941}
1942
icculus9e44cf12010-02-14 17:14:22 +00001943void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001944{
1945 int i;
1946 i = argindex(n);
1947 if( i>=0 ) errline(i,0,errstream);
1948}
1949
drhb0c86772000-06-02 23:21:26 +00001950void OptPrint(){
drh75897232000-05-29 14:26:00 +00001951 int i;
1952 int max, len;
1953 max = 0;
1954 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001955 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001956 switch( op[i].type ){
1957 case OPT_FLAG:
1958 case OPT_FFLAG:
1959 break;
1960 case OPT_INT:
1961 case OPT_FINT:
1962 len += 9; /* length of "<integer>" */
1963 break;
1964 case OPT_DBL:
1965 case OPT_FDBL:
1966 len += 6; /* length of "<real>" */
1967 break;
1968 case OPT_STR:
1969 case OPT_FSTR:
1970 len += 8; /* length of "<string>" */
1971 break;
1972 }
1973 if( len>max ) max = len;
1974 }
1975 for(i=0; op[i].label; i++){
1976 switch( op[i].type ){
1977 case OPT_FLAG:
1978 case OPT_FFLAG:
1979 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1980 break;
1981 case OPT_INT:
1982 case OPT_FINT:
1983 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001984 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001985 break;
1986 case OPT_DBL:
1987 case OPT_FDBL:
1988 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001989 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001990 break;
1991 case OPT_STR:
1992 case OPT_FSTR:
1993 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001994 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001995 break;
1996 }
1997 }
1998}
1999/*********************** From the file "parse.c" ****************************/
2000/*
2001** Input file parser for the LEMON parser generator.
2002*/
2003
2004/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00002005enum e_state {
2006 INITIALIZE,
2007 WAITING_FOR_DECL_OR_RULE,
2008 WAITING_FOR_DECL_KEYWORD,
2009 WAITING_FOR_DECL_ARG,
2010 WAITING_FOR_PRECEDENCE_SYMBOL,
2011 WAITING_FOR_ARROW,
2012 IN_RHS,
2013 LHS_ALIAS_1,
2014 LHS_ALIAS_2,
2015 LHS_ALIAS_3,
2016 RHS_ALIAS_1,
2017 RHS_ALIAS_2,
2018 PRECEDENCE_MARK_1,
2019 PRECEDENCE_MARK_2,
2020 RESYNC_AFTER_RULE_ERROR,
2021 RESYNC_AFTER_DECL_ERROR,
2022 WAITING_FOR_DESTRUCTOR_SYMBOL,
2023 WAITING_FOR_DATATYPE_SYMBOL,
2024 WAITING_FOR_FALLBACK_ID,
2025 WAITING_FOR_EXPECT_VALUE,
2026 WAITING_FOR_WILDCARD_ID
2027};
drh75897232000-05-29 14:26:00 +00002028struct pstate {
2029 char *filename; /* Name of the input file */
2030 int tokenlineno; /* Linenumber at which current token starts */
2031 int errorcnt; /* Number of errors so far */
2032 char *tokenstart; /* Text of current token */
2033 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00002034 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00002035 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00002036 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00002037 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00002038 int nrhs; /* Number of right-hand side symbols seen */
2039 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00002040 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00002041 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00002042 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00002043 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00002044 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00002045 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00002046 enum e_assoc declassoc; /* Assign this association to decl arguments */
2047 int preccounter; /* Assign this precedence to decl arguments */
2048 struct rule *firstrule; /* Pointer to first rule in the grammar */
2049 struct rule *lastrule; /* Pointer to the most recently parsed rule */
2050};
2051
2052/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00002053static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00002054{
icculus42585cf2010-02-14 05:19:56 +00002055 char *endptr;
icculus9e44cf12010-02-14 17:14:22 +00002056 const char *x;
drh75897232000-05-29 14:26:00 +00002057 x = Strsafe(psp->tokenstart); /* Save the token permanently */
2058#if 0
2059 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
2060 x,psp->state);
2061#endif
2062 switch( psp->state ){
2063 case INITIALIZE:
2064 psp->prevrule = 0;
2065 psp->preccounter = 0;
2066 psp->firstrule = psp->lastrule = 0;
2067 psp->gp->nrule = 0;
2068 /* Fall thru to next case */
2069 case WAITING_FOR_DECL_OR_RULE:
2070 if( x[0]=='%' ){
2071 psp->state = WAITING_FOR_DECL_KEYWORD;
2072 }else if( islower(x[0]) ){
2073 psp->lhs = Symbol_new(x);
2074 psp->nrhs = 0;
2075 psp->lhsalias = 0;
2076 psp->state = WAITING_FOR_ARROW;
2077 }else if( x[0]=='{' ){
2078 if( psp->prevrule==0 ){
2079 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002080"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002081fragment which begins on this line.");
2082 psp->errorcnt++;
2083 }else if( psp->prevrule->code!=0 ){
2084 ErrorMsg(psp->filename,psp->tokenlineno,
2085"Code fragment beginning on this line is not the first \
2086to follow the previous rule.");
2087 psp->errorcnt++;
2088 }else{
2089 psp->prevrule->line = psp->tokenlineno;
2090 psp->prevrule->code = &x[1];
2091 }
2092 }else if( x[0]=='[' ){
2093 psp->state = PRECEDENCE_MARK_1;
2094 }else{
2095 ErrorMsg(psp->filename,psp->tokenlineno,
2096 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2097 x);
2098 psp->errorcnt++;
2099 }
2100 break;
2101 case PRECEDENCE_MARK_1:
2102 if( !isupper(x[0]) ){
2103 ErrorMsg(psp->filename,psp->tokenlineno,
2104 "The precedence symbol must be a terminal.");
2105 psp->errorcnt++;
2106 }else if( psp->prevrule==0 ){
2107 ErrorMsg(psp->filename,psp->tokenlineno,
2108 "There is no prior rule to assign precedence \"[%s]\".",x);
2109 psp->errorcnt++;
2110 }else if( psp->prevrule->precsym!=0 ){
2111 ErrorMsg(psp->filename,psp->tokenlineno,
2112"Precedence mark on this line is not the first \
2113to follow the previous rule.");
2114 psp->errorcnt++;
2115 }else{
2116 psp->prevrule->precsym = Symbol_new(x);
2117 }
2118 psp->state = PRECEDENCE_MARK_2;
2119 break;
2120 case PRECEDENCE_MARK_2:
2121 if( x[0]!=']' ){
2122 ErrorMsg(psp->filename,psp->tokenlineno,
2123 "Missing \"]\" on precedence mark.");
2124 psp->errorcnt++;
2125 }
2126 psp->state = WAITING_FOR_DECL_OR_RULE;
2127 break;
2128 case WAITING_FOR_ARROW:
2129 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2130 psp->state = IN_RHS;
2131 }else if( x[0]=='(' ){
2132 psp->state = LHS_ALIAS_1;
2133 }else{
2134 ErrorMsg(psp->filename,psp->tokenlineno,
2135 "Expected to see a \":\" following the LHS symbol \"%s\".",
2136 psp->lhs->name);
2137 psp->errorcnt++;
2138 psp->state = RESYNC_AFTER_RULE_ERROR;
2139 }
2140 break;
2141 case LHS_ALIAS_1:
2142 if( isalpha(x[0]) ){
2143 psp->lhsalias = x;
2144 psp->state = LHS_ALIAS_2;
2145 }else{
2146 ErrorMsg(psp->filename,psp->tokenlineno,
2147 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2148 x,psp->lhs->name);
2149 psp->errorcnt++;
2150 psp->state = RESYNC_AFTER_RULE_ERROR;
2151 }
2152 break;
2153 case LHS_ALIAS_2:
2154 if( x[0]==')' ){
2155 psp->state = LHS_ALIAS_3;
2156 }else{
2157 ErrorMsg(psp->filename,psp->tokenlineno,
2158 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2159 psp->errorcnt++;
2160 psp->state = RESYNC_AFTER_RULE_ERROR;
2161 }
2162 break;
2163 case LHS_ALIAS_3:
2164 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2165 psp->state = IN_RHS;
2166 }else{
2167 ErrorMsg(psp->filename,psp->tokenlineno,
2168 "Missing \"->\" following: \"%s(%s)\".",
2169 psp->lhs->name,psp->lhsalias);
2170 psp->errorcnt++;
2171 psp->state = RESYNC_AFTER_RULE_ERROR;
2172 }
2173 break;
2174 case IN_RHS:
2175 if( x[0]=='.' ){
2176 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002177 rp = (struct rule *)calloc( sizeof(struct rule) +
2178 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002179 if( rp==0 ){
2180 ErrorMsg(psp->filename,psp->tokenlineno,
2181 "Can't allocate enough memory for this rule.");
2182 psp->errorcnt++;
2183 psp->prevrule = 0;
2184 }else{
2185 int i;
2186 rp->ruleline = psp->tokenlineno;
2187 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002188 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002189 for(i=0; i<psp->nrhs; i++){
2190 rp->rhs[i] = psp->rhs[i];
2191 rp->rhsalias[i] = psp->alias[i];
2192 }
2193 rp->lhs = psp->lhs;
2194 rp->lhsalias = psp->lhsalias;
2195 rp->nrhs = psp->nrhs;
2196 rp->code = 0;
2197 rp->precsym = 0;
2198 rp->index = psp->gp->nrule++;
2199 rp->nextlhs = rp->lhs->rule;
2200 rp->lhs->rule = rp;
2201 rp->next = 0;
2202 if( psp->firstrule==0 ){
2203 psp->firstrule = psp->lastrule = rp;
2204 }else{
2205 psp->lastrule->next = rp;
2206 psp->lastrule = rp;
2207 }
2208 psp->prevrule = rp;
2209 }
2210 psp->state = WAITING_FOR_DECL_OR_RULE;
2211 }else if( isalpha(x[0]) ){
2212 if( psp->nrhs>=MAXRHS ){
2213 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002214 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002215 x);
2216 psp->errorcnt++;
2217 psp->state = RESYNC_AFTER_RULE_ERROR;
2218 }else{
2219 psp->rhs[psp->nrhs] = Symbol_new(x);
2220 psp->alias[psp->nrhs] = 0;
2221 psp->nrhs++;
2222 }
drhfd405312005-11-06 04:06:59 +00002223 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2224 struct symbol *msp = psp->rhs[psp->nrhs-1];
2225 if( msp->type!=MULTITERMINAL ){
2226 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002227 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002228 memset(msp, 0, sizeof(*msp));
2229 msp->type = MULTITERMINAL;
2230 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002231 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002232 msp->subsym[0] = origsp;
2233 msp->name = origsp->name;
2234 psp->rhs[psp->nrhs-1] = msp;
2235 }
2236 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002237 msp->subsym = (struct symbol **) realloc(msp->subsym,
2238 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002239 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2240 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2241 ErrorMsg(psp->filename,psp->tokenlineno,
2242 "Cannot form a compound containing a non-terminal");
2243 psp->errorcnt++;
2244 }
drh75897232000-05-29 14:26:00 +00002245 }else if( x[0]=='(' && psp->nrhs>0 ){
2246 psp->state = RHS_ALIAS_1;
2247 }else{
2248 ErrorMsg(psp->filename,psp->tokenlineno,
2249 "Illegal character on RHS of rule: \"%s\".",x);
2250 psp->errorcnt++;
2251 psp->state = RESYNC_AFTER_RULE_ERROR;
2252 }
2253 break;
2254 case RHS_ALIAS_1:
2255 if( isalpha(x[0]) ){
2256 psp->alias[psp->nrhs-1] = x;
2257 psp->state = RHS_ALIAS_2;
2258 }else{
2259 ErrorMsg(psp->filename,psp->tokenlineno,
2260 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2261 x,psp->rhs[psp->nrhs-1]->name);
2262 psp->errorcnt++;
2263 psp->state = RESYNC_AFTER_RULE_ERROR;
2264 }
2265 break;
2266 case RHS_ALIAS_2:
2267 if( x[0]==')' ){
2268 psp->state = IN_RHS;
2269 }else{
2270 ErrorMsg(psp->filename,psp->tokenlineno,
2271 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2272 psp->errorcnt++;
2273 psp->state = RESYNC_AFTER_RULE_ERROR;
2274 }
2275 break;
2276 case WAITING_FOR_DECL_KEYWORD:
2277 if( isalpha(x[0]) ){
2278 psp->declkeyword = x;
2279 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002280 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002281 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002282 psp->state = WAITING_FOR_DECL_ARG;
2283 if( strcmp(x,"name")==0 ){
2284 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002285 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002286 }else if( strcmp(x,"include")==0 ){
2287 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002288 }else if( strcmp(x,"code")==0 ){
2289 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002290 }else if( strcmp(x,"token_destructor")==0 ){
2291 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002292 }else if( strcmp(x,"default_destructor")==0 ){
2293 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002294 }else if( strcmp(x,"token_prefix")==0 ){
2295 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002296 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002297 }else if( strcmp(x,"syntax_error")==0 ){
2298 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002299 }else if( strcmp(x,"parse_accept")==0 ){
2300 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002301 }else if( strcmp(x,"parse_failure")==0 ){
2302 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002303 }else if( strcmp(x,"stack_overflow")==0 ){
2304 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002305 }else if( strcmp(x,"extra_argument")==0 ){
2306 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002307 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002308 }else if( strcmp(x,"token_type")==0 ){
2309 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002310 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002311 }else if( strcmp(x,"default_type")==0 ){
2312 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002313 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002314 }else if( strcmp(x,"stack_size")==0 ){
2315 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002316 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002317 }else if( strcmp(x,"start_symbol")==0 ){
2318 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002319 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002320 }else if( strcmp(x,"left")==0 ){
2321 psp->preccounter++;
2322 psp->declassoc = LEFT;
2323 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2324 }else if( strcmp(x,"right")==0 ){
2325 psp->preccounter++;
2326 psp->declassoc = RIGHT;
2327 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2328 }else if( strcmp(x,"nonassoc")==0 ){
2329 psp->preccounter++;
2330 psp->declassoc = NONE;
2331 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2332 }else if( strcmp(x,"destructor")==0 ){
2333 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2334 }else if( strcmp(x,"type")==0 ){
2335 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002336 }else if( strcmp(x,"fallback")==0 ){
2337 psp->fallback = 0;
2338 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002339 }else if( strcmp(x,"wildcard")==0 ){
2340 psp->state = WAITING_FOR_WILDCARD_ID;
icculus42585cf2010-02-14 05:19:56 +00002341 }else if( strcmp(x,"expect")==0 ){
2342 if (psp->gp->nexpected >= 0) {
2343 ErrorMsg(psp->filename,psp->tokenlineno, "Multiple %expect declarations.");
2344 psp->errorcnt++;
2345 psp->state = RESYNC_AFTER_DECL_ERROR;
2346 } else {
2347 psp->state = WAITING_FOR_EXPECT_VALUE;
2348 }
drh75897232000-05-29 14:26:00 +00002349 }else{
2350 ErrorMsg(psp->filename,psp->tokenlineno,
2351 "Unknown declaration keyword: \"%%%s\".",x);
2352 psp->errorcnt++;
2353 psp->state = RESYNC_AFTER_DECL_ERROR;
2354 }
2355 }else{
2356 ErrorMsg(psp->filename,psp->tokenlineno,
2357 "Illegal declaration keyword: \"%s\".",x);
2358 psp->errorcnt++;
2359 psp->state = RESYNC_AFTER_DECL_ERROR;
2360 }
2361 break;
2362 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2363 if( !isalpha(x[0]) ){
2364 ErrorMsg(psp->filename,psp->tokenlineno,
2365 "Symbol name missing after %destructor keyword");
2366 psp->errorcnt++;
2367 psp->state = RESYNC_AFTER_DECL_ERROR;
2368 }else{
2369 struct symbol *sp = Symbol_new(x);
2370 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002371 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002372 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002373 psp->state = WAITING_FOR_DECL_ARG;
2374 }
2375 break;
icculus42585cf2010-02-14 05:19:56 +00002376 case WAITING_FOR_EXPECT_VALUE:
2377 psp->gp->nexpected = (int) strtol(x, &endptr, 10);
2378 if( (*endptr != '\0') || (endptr == x) ) {
2379 ErrorMsg(psp->filename,psp->tokenlineno,
2380 "Integer expected after %%expect keyword");
2381 psp->errorcnt++;
2382 } else if (psp->gp->nexpected < 0) {
2383 ErrorMsg(psp->filename,psp->tokenlineno,
2384 "Integer can't be negative after %%expect keyword");
2385 psp->errorcnt++;
2386 }
2387 psp->state = WAITING_FOR_DECL_OR_RULE;
2388 break;
drh75897232000-05-29 14:26:00 +00002389 case WAITING_FOR_DATATYPE_SYMBOL:
2390 if( !isalpha(x[0]) ){
2391 ErrorMsg(psp->filename,psp->tokenlineno,
2392 "Symbol name missing after %destructor keyword");
2393 psp->errorcnt++;
2394 psp->state = RESYNC_AFTER_DECL_ERROR;
2395 }else{
2396 struct symbol *sp = Symbol_new(x);
2397 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002398 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002399 psp->state = WAITING_FOR_DECL_ARG;
2400 }
2401 break;
2402 case WAITING_FOR_PRECEDENCE_SYMBOL:
2403 if( x[0]=='.' ){
2404 psp->state = WAITING_FOR_DECL_OR_RULE;
2405 }else if( isupper(x[0]) ){
2406 struct symbol *sp;
2407 sp = Symbol_new(x);
2408 if( sp->prec>=0 ){
2409 ErrorMsg(psp->filename,psp->tokenlineno,
2410 "Symbol \"%s\" has already be given a precedence.",x);
2411 psp->errorcnt++;
2412 }else{
2413 sp->prec = psp->preccounter;
2414 sp->assoc = psp->declassoc;
2415 }
2416 }else{
2417 ErrorMsg(psp->filename,psp->tokenlineno,
2418 "Can't assign a precedence to \"%s\".",x);
2419 psp->errorcnt++;
2420 }
2421 break;
2422 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002423 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002424 const char *zOld, *zNew;
2425 char *zBuf, *z;
drha5808f32008-04-27 22:19:44 +00002426 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002427 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002428 char zLine[50];
2429 zNew = x;
2430 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002431 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002432 if( *psp->declargslot ){
2433 zOld = *psp->declargslot;
2434 }else{
2435 zOld = "";
2436 }
drh87cf1372008-08-13 20:09:06 +00002437 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002438 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002439 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002440 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2441 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002442 for(z=psp->filename, nBack=0; *z; z++){
2443 if( *z=='\\' ) nBack++;
2444 }
2445 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002446 nLine = lemonStrlen(zLine);
2447 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002448 }
icculus9e44cf12010-02-14 17:14:22 +00002449 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2450 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002451 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002452 if( nOld && zBuf[-1]!='\n' ){
2453 *(zBuf++) = '\n';
2454 }
2455 memcpy(zBuf, zLine, nLine);
2456 zBuf += nLine;
2457 *(zBuf++) = '"';
2458 for(z=psp->filename; *z; z++){
2459 if( *z=='\\' ){
2460 *(zBuf++) = '\\';
2461 }
2462 *(zBuf++) = *z;
2463 }
2464 *(zBuf++) = '"';
2465 *(zBuf++) = '\n';
2466 }
drh4dc8ef52008-07-01 17:13:57 +00002467 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2468 psp->decllinenoslot[0] = psp->tokenlineno;
2469 }
drha5808f32008-04-27 22:19:44 +00002470 memcpy(zBuf, zNew, nNew);
2471 zBuf += nNew;
2472 *zBuf = 0;
2473 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002474 }else{
2475 ErrorMsg(psp->filename,psp->tokenlineno,
2476 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2477 psp->errorcnt++;
2478 psp->state = RESYNC_AFTER_DECL_ERROR;
2479 }
2480 break;
drh0bd1f4e2002-06-06 18:54:39 +00002481 case WAITING_FOR_FALLBACK_ID:
2482 if( x[0]=='.' ){
2483 psp->state = WAITING_FOR_DECL_OR_RULE;
2484 }else if( !isupper(x[0]) ){
2485 ErrorMsg(psp->filename, psp->tokenlineno,
2486 "%%fallback argument \"%s\" should be a token", x);
2487 psp->errorcnt++;
2488 }else{
2489 struct symbol *sp = Symbol_new(x);
2490 if( psp->fallback==0 ){
2491 psp->fallback = sp;
2492 }else if( sp->fallback ){
2493 ErrorMsg(psp->filename, psp->tokenlineno,
2494 "More than one fallback assigned to token %s", x);
2495 psp->errorcnt++;
2496 }else{
2497 sp->fallback = psp->fallback;
2498 psp->gp->has_fallback = 1;
2499 }
2500 }
2501 break;
drhe09daa92006-06-10 13:29:31 +00002502 case WAITING_FOR_WILDCARD_ID:
2503 if( x[0]=='.' ){
2504 psp->state = WAITING_FOR_DECL_OR_RULE;
2505 }else if( !isupper(x[0]) ){
2506 ErrorMsg(psp->filename, psp->tokenlineno,
2507 "%%wildcard argument \"%s\" should be a token", x);
2508 psp->errorcnt++;
2509 }else{
2510 struct symbol *sp = Symbol_new(x);
2511 if( psp->gp->wildcard==0 ){
2512 psp->gp->wildcard = sp;
2513 }else{
2514 ErrorMsg(psp->filename, psp->tokenlineno,
2515 "Extra wildcard to token: %s", x);
2516 psp->errorcnt++;
2517 }
2518 }
2519 break;
drh75897232000-05-29 14:26:00 +00002520 case RESYNC_AFTER_RULE_ERROR:
2521/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2522** break; */
2523 case RESYNC_AFTER_DECL_ERROR:
2524 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2525 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2526 break;
2527 }
2528}
2529
drh34ff57b2008-07-14 12:27:51 +00002530/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002531** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2532** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2533** comments them out. Text in between is also commented out as appropriate.
2534*/
danielk1977940fac92005-01-23 22:41:37 +00002535static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002536 int i, j, k, n;
2537 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002538 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002539 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002540 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002541 for(i=0; z[i]; i++){
2542 if( z[i]=='\n' ) lineno++;
2543 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2544 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2545 if( exclude ){
2546 exclude--;
2547 if( exclude==0 ){
2548 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2549 }
2550 }
2551 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2552 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2553 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2554 if( exclude ){
2555 exclude++;
2556 }else{
2557 for(j=i+7; isspace(z[j]); j++){}
2558 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2559 exclude = 1;
2560 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002561 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002562 exclude = 0;
2563 break;
2564 }
2565 }
2566 if( z[i+3]=='n' ) exclude = !exclude;
2567 if( exclude ){
2568 start = i;
2569 start_lineno = lineno;
2570 }
2571 }
2572 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2573 }
2574 }
2575 if( exclude ){
2576 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2577 exit(1);
2578 }
2579}
2580
drh75897232000-05-29 14:26:00 +00002581/* In spite of its name, this function is really a scanner. It read
2582** in the entire input file (all at once) then tokenizes it. Each
2583** token is passed to the function "parseonetoken" which builds all
2584** the appropriate data structures in the global state vector "gp".
2585*/
icculus9e44cf12010-02-14 17:14:22 +00002586void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002587{
2588 struct pstate ps;
2589 FILE *fp;
2590 char *filebuf;
2591 int filesize;
2592 int lineno;
2593 int c;
2594 char *cp, *nextcp;
2595 int startline = 0;
2596
rse38514a92007-09-20 11:34:17 +00002597 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002598 ps.gp = gp;
2599 ps.filename = gp->filename;
2600 ps.errorcnt = 0;
2601 ps.state = INITIALIZE;
2602
2603 /* Begin by reading the input file */
2604 fp = fopen(ps.filename,"rb");
2605 if( fp==0 ){
2606 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2607 gp->errorcnt++;
2608 return;
2609 }
2610 fseek(fp,0,2);
2611 filesize = ftell(fp);
2612 rewind(fp);
2613 filebuf = (char *)malloc( filesize+1 );
2614 if( filebuf==0 ){
2615 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2616 filesize+1);
2617 gp->errorcnt++;
2618 return;
2619 }
2620 if( fread(filebuf,1,filesize,fp)!=filesize ){
2621 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2622 filesize);
2623 free(filebuf);
2624 gp->errorcnt++;
2625 return;
2626 }
2627 fclose(fp);
2628 filebuf[filesize] = 0;
2629
drh6d08b4d2004-07-20 12:45:22 +00002630 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2631 preprocess_input(filebuf);
2632
drh75897232000-05-29 14:26:00 +00002633 /* Now scan the text of the input file */
2634 lineno = 1;
2635 for(cp=filebuf; (c= *cp)!=0; ){
2636 if( c=='\n' ) lineno++; /* Keep track of the line number */
2637 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2638 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2639 cp+=2;
2640 while( (c= *cp)!=0 && c!='\n' ) cp++;
2641 continue;
2642 }
2643 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2644 cp+=2;
2645 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2646 if( c=='\n' ) lineno++;
2647 cp++;
2648 }
2649 if( c ) cp++;
2650 continue;
2651 }
2652 ps.tokenstart = cp; /* Mark the beginning of the token */
2653 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2654 if( c=='\"' ){ /* String literals */
2655 cp++;
2656 while( (c= *cp)!=0 && c!='\"' ){
2657 if( c=='\n' ) lineno++;
2658 cp++;
2659 }
2660 if( c==0 ){
2661 ErrorMsg(ps.filename,startline,
2662"String starting on this line is not terminated before the end of the file.");
2663 ps.errorcnt++;
2664 nextcp = cp;
2665 }else{
2666 nextcp = cp+1;
2667 }
2668 }else if( c=='{' ){ /* A block of C code */
2669 int level;
2670 cp++;
2671 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2672 if( c=='\n' ) lineno++;
2673 else if( c=='{' ) level++;
2674 else if( c=='}' ) level--;
2675 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2676 int prevc;
2677 cp = &cp[2];
2678 prevc = 0;
2679 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2680 if( c=='\n' ) lineno++;
2681 prevc = c;
2682 cp++;
2683 }
2684 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2685 cp = &cp[2];
2686 while( (c= *cp)!=0 && c!='\n' ) cp++;
2687 if( c ) lineno++;
2688 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2689 int startchar, prevc;
2690 startchar = c;
2691 prevc = 0;
2692 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2693 if( c=='\n' ) lineno++;
2694 if( prevc=='\\' ) prevc = 0;
2695 else prevc = c;
2696 }
2697 }
2698 }
2699 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002700 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002701"C code starting on this line is not terminated before the end of the file.");
2702 ps.errorcnt++;
2703 nextcp = cp;
2704 }else{
2705 nextcp = cp+1;
2706 }
2707 }else if( isalnum(c) ){ /* Identifiers */
2708 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2709 nextcp = cp;
2710 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2711 cp += 3;
2712 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002713 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2714 cp += 2;
2715 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2716 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002717 }else{ /* All other (one character) operators */
2718 cp++;
2719 nextcp = cp;
2720 }
2721 c = *cp;
2722 *cp = 0; /* Null terminate the token */
2723 parseonetoken(&ps); /* Parse the token */
2724 *cp = c; /* Restore the buffer */
2725 cp = nextcp;
2726 }
2727 free(filebuf); /* Release the buffer after parsing */
2728 gp->rule = ps.firstrule;
2729 gp->errorcnt = ps.errorcnt;
2730}
2731/*************************** From the file "plink.c" *********************/
2732/*
2733** Routines processing configuration follow-set propagation links
2734** in the LEMON parser generator.
2735*/
2736static struct plink *plink_freelist = 0;
2737
2738/* Allocate a new plink */
2739struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002740 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002741
2742 if( plink_freelist==0 ){
2743 int i;
2744 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002745 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002746 if( plink_freelist==0 ){
2747 fprintf(stderr,
2748 "Unable to allocate memory for a new follow-set propagation link.\n");
2749 exit(1);
2750 }
2751 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2752 plink_freelist[amt-1].next = 0;
2753 }
icculus9e44cf12010-02-14 17:14:22 +00002754 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002755 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002756 return newlink;
drh75897232000-05-29 14:26:00 +00002757}
2758
2759/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002760void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002761{
icculus9e44cf12010-02-14 17:14:22 +00002762 struct plink *newlink;
2763 newlink = Plink_new();
2764 newlink->next = *plpp;
2765 *plpp = newlink;
2766 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002767}
2768
2769/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002770void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002771{
2772 struct plink *nextpl;
2773 while( from ){
2774 nextpl = from->next;
2775 from->next = *to;
2776 *to = from;
2777 from = nextpl;
2778 }
2779}
2780
2781/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002782void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002783{
2784 struct plink *nextpl;
2785
2786 while( plp ){
2787 nextpl = plp->next;
2788 plp->next = plink_freelist;
2789 plink_freelist = plp;
2790 plp = nextpl;
2791 }
2792}
2793/*********************** From the file "report.c" **************************/
2794/*
2795** Procedures for generating reports and tables in the LEMON parser generator.
2796*/
2797
2798/* Generate a filename with the given suffix. Space to hold the
2799** name comes from malloc() and must be freed by the calling
2800** function.
2801*/
icculus9e44cf12010-02-14 17:14:22 +00002802PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002803{
2804 char *name;
2805 char *cp;
2806
icculus9e44cf12010-02-14 17:14:22 +00002807 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002808 if( name==0 ){
2809 fprintf(stderr,"Can't allocate space for a filename.\n");
2810 exit(1);
2811 }
2812 strcpy(name,lemp->filename);
2813 cp = strrchr(name,'.');
2814 if( cp ) *cp = 0;
2815 strcat(name,suffix);
2816 return name;
2817}
2818
2819/* Open a file with a name based on the name of the input file,
2820** but with a different (specified) suffix, and return a pointer
2821** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002822PRIVATE FILE *file_open(
2823 struct lemon *lemp,
2824 const char *suffix,
2825 const char *mode
2826){
drh75897232000-05-29 14:26:00 +00002827 FILE *fp;
2828
2829 if( lemp->outname ) free(lemp->outname);
2830 lemp->outname = file_makename(lemp, suffix);
2831 fp = fopen(lemp->outname,mode);
2832 if( fp==0 && *mode=='w' ){
2833 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2834 lemp->errorcnt++;
2835 return 0;
2836 }
icculusf5ad8242010-02-14 05:34:42 +00002837
2838 /* Add files we create to a list, so we can delete them if we fail. This
2839 ** is to keep makefiles from getting confused. We don't include .out files,
2840 ** though: this is debug information, and you don't want it deleted if there
2841 ** was an error you need to track down.
2842 */
2843 if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){
2844 const char **ptr = (const char **)
2845 realloc(made_files, sizeof (const char **) * (made_files_count + 1));
2846 char *fname = strdup(lemp->outname);
2847 if ((ptr == NULL) || (fname == NULL)) {
2848 free(ptr);
2849 free(fname);
2850 memory_error();
2851 }
2852 made_files = ptr;
2853 made_files[made_files_count++] = fname;
2854 }
drh75897232000-05-29 14:26:00 +00002855 return fp;
2856}
2857
2858/* Duplicate the input file without comments and without actions
2859** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002860void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002861{
2862 struct rule *rp;
2863 struct symbol *sp;
2864 int i, j, maxlen, len, ncolumns, skip;
2865 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2866 maxlen = 10;
2867 for(i=0; i<lemp->nsymbol; i++){
2868 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002869 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002870 if( len>maxlen ) maxlen = len;
2871 }
2872 ncolumns = 76/(maxlen+5);
2873 if( ncolumns<1 ) ncolumns = 1;
2874 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2875 for(i=0; i<skip; i++){
2876 printf("//");
2877 for(j=i; j<lemp->nsymbol; j+=skip){
2878 sp = lemp->symbols[j];
2879 assert( sp->index==j );
2880 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2881 }
2882 printf("\n");
2883 }
2884 for(rp=lemp->rule; rp; rp=rp->next){
2885 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002886 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002887 printf(" ::=");
2888 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002889 sp = rp->rhs[i];
2890 printf(" %s", sp->name);
2891 if( sp->type==MULTITERMINAL ){
2892 for(j=1; j<sp->nsubsym; j++){
2893 printf("|%s", sp->subsym[j]->name);
2894 }
2895 }
2896 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002897 }
2898 printf(".");
2899 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002900 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002901 printf("\n");
2902 }
2903}
2904
icculus9e44cf12010-02-14 17:14:22 +00002905void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002906{
2907 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002908 struct symbol *sp;
2909 int i, j;
drh75897232000-05-29 14:26:00 +00002910 rp = cfp->rp;
2911 fprintf(fp,"%s ::=",rp->lhs->name);
2912 for(i=0; i<=rp->nrhs; i++){
2913 if( i==cfp->dot ) fprintf(fp," *");
2914 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002915 sp = rp->rhs[i];
2916 fprintf(fp," %s", sp->name);
2917 if( sp->type==MULTITERMINAL ){
2918 for(j=1; j<sp->nsubsym; j++){
2919 fprintf(fp,"|%s",sp->subsym[j]->name);
2920 }
2921 }
drh75897232000-05-29 14:26:00 +00002922 }
2923}
2924
2925/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002926#if 0
drh75897232000-05-29 14:26:00 +00002927/* Print a set */
2928PRIVATE void SetPrint(out,set,lemp)
2929FILE *out;
2930char *set;
2931struct lemon *lemp;
2932{
2933 int i;
2934 char *spacer;
2935 spacer = "";
2936 fprintf(out,"%12s[","");
2937 for(i=0; i<lemp->nterminal; i++){
2938 if( SetFind(set,i) ){
2939 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2940 spacer = " ";
2941 }
2942 }
2943 fprintf(out,"]\n");
2944}
2945
2946/* Print a plink chain */
2947PRIVATE void PlinkPrint(out,plp,tag)
2948FILE *out;
2949struct plink *plp;
2950char *tag;
2951{
2952 while( plp ){
drhada354d2005-11-05 15:03:59 +00002953 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002954 ConfigPrint(out,plp->cfp);
2955 fprintf(out,"\n");
2956 plp = plp->next;
2957 }
2958}
2959#endif
2960
2961/* Print an action to the given file descriptor. Return FALSE if
2962** nothing was actually printed.
2963*/
2964int PrintAction(struct action *ap, FILE *fp, int indent){
2965 int result = 1;
2966 switch( ap->type ){
2967 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002968 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002969 break;
2970 case REDUCE:
2971 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2972 break;
2973 case ACCEPT:
2974 fprintf(fp,"%*s accept",indent,ap->sp->name);
2975 break;
2976 case ERROR:
2977 fprintf(fp,"%*s error",indent,ap->sp->name);
2978 break;
drh9892c5d2007-12-21 00:02:11 +00002979 case SRCONFLICT:
2980 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002981 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2982 indent,ap->sp->name,ap->x.rp->index);
2983 break;
drh9892c5d2007-12-21 00:02:11 +00002984 case SSCONFLICT:
2985 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2986 indent,ap->sp->name,ap->x.stp->statenum);
2987 break;
drh75897232000-05-29 14:26:00 +00002988 case SH_RESOLVED:
2989 case RD_RESOLVED:
2990 case NOT_USED:
2991 result = 0;
2992 break;
2993 }
2994 return result;
2995}
2996
2997/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00002998void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002999{
3000 int i;
3001 struct state *stp;
3002 struct config *cfp;
3003 struct action *ap;
3004 FILE *fp;
3005
drh2aa6ca42004-09-10 00:14:04 +00003006 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00003007 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00003008 for(i=0; i<lemp->nstate; i++){
3009 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00003010 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00003011 if( lemp->basisflag ) cfp=stp->bp;
3012 else cfp=stp->cfp;
3013 while( cfp ){
3014 char buf[20];
3015 if( cfp->dot==cfp->rp->nrhs ){
3016 sprintf(buf,"(%d)",cfp->rp->index);
3017 fprintf(fp," %5s ",buf);
3018 }else{
3019 fprintf(fp," ");
3020 }
3021 ConfigPrint(fp,cfp);
3022 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00003023#if 0
drh75897232000-05-29 14:26:00 +00003024 SetPrint(fp,cfp->fws,lemp);
3025 PlinkPrint(fp,cfp->fplp,"To ");
3026 PlinkPrint(fp,cfp->bplp,"From");
3027#endif
3028 if( lemp->basisflag ) cfp=cfp->bp;
3029 else cfp=cfp->next;
3030 }
3031 fprintf(fp,"\n");
3032 for(ap=stp->ap; ap; ap=ap->next){
3033 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
3034 }
3035 fprintf(fp,"\n");
3036 }
drhe9278182007-07-18 18:16:29 +00003037 fprintf(fp, "----------------------------------------------------\n");
3038 fprintf(fp, "Symbols:\n");
3039 for(i=0; i<lemp->nsymbol; i++){
3040 int j;
3041 struct symbol *sp;
3042
3043 sp = lemp->symbols[i];
3044 fprintf(fp, " %3d: %s", i, sp->name);
3045 if( sp->type==NONTERMINAL ){
3046 fprintf(fp, ":");
3047 if( sp->lambda ){
3048 fprintf(fp, " <lambda>");
3049 }
3050 for(j=0; j<lemp->nterminal; j++){
3051 if( sp->firstset && SetFind(sp->firstset, j) ){
3052 fprintf(fp, " %s", lemp->symbols[j]->name);
3053 }
3054 }
3055 }
3056 fprintf(fp, "\n");
3057 }
drh75897232000-05-29 14:26:00 +00003058 fclose(fp);
3059 return;
3060}
3061
3062/* Search for the file "name" which is in the same directory as
3063** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00003064PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00003065{
icculus9e44cf12010-02-14 17:14:22 +00003066 const char *pathlist;
3067 char *pathbufptr;
3068 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003069 char *path,*cp;
3070 char c;
drh75897232000-05-29 14:26:00 +00003071
3072#ifdef __WIN32__
3073 cp = strrchr(argv0,'\\');
3074#else
3075 cp = strrchr(argv0,'/');
3076#endif
3077 if( cp ){
3078 c = *cp;
3079 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003080 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003081 if( path ) sprintf(path,"%s/%s",argv0,name);
3082 *cp = c;
3083 }else{
drh75897232000-05-29 14:26:00 +00003084 pathlist = getenv("PATH");
3085 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003086 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003087 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003088 if( (pathbuf != 0) && (path!=0) ){
3089 pathbufptr = pathbuf;
3090 strcpy(pathbuf, pathlist);
3091 while( *pathbuf ){
3092 cp = strchr(pathbuf,':');
3093 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003094 c = *cp;
3095 *cp = 0;
icculus9e44cf12010-02-14 17:14:22 +00003096 sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003097 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003098 if( c==0 ) pathbuf[0] = 0;
3099 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003100 if( access(path,modemask)==0 ) break;
3101 }
icculus9e44cf12010-02-14 17:14:22 +00003102 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003103 }
3104 }
3105 return path;
3106}
3107
3108/* Given an action, compute the integer value for that action
3109** which is to be put in the action table of the generated machine.
3110** Return negative if no action should be generated.
3111*/
icculus9e44cf12010-02-14 17:14:22 +00003112PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003113{
3114 int act;
3115 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003116 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003117 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3118 case ERROR: act = lemp->nstate + lemp->nrule; break;
3119 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3120 default: act = -1; break;
3121 }
3122 return act;
3123}
3124
3125#define LINESIZE 1000
3126/* The next cluster of routines are for reading the template file
3127** and writing the results to the generated parser */
3128/* The first function transfers data from "in" to "out" until
3129** a line is seen which begins with "%%". The line number is
3130** tracked.
3131**
3132** if name!=0, then any word that begin with "Parse" is changed to
3133** begin with *name instead.
3134*/
icculus9e44cf12010-02-14 17:14:22 +00003135PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003136{
3137 int i, iStart;
3138 char line[LINESIZE];
3139 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3140 (*lineno)++;
3141 iStart = 0;
3142 if( name ){
3143 for(i=0; line[i]; i++){
3144 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3145 && (i==0 || !isalpha(line[i-1]))
3146 ){
3147 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3148 fprintf(out,"%s",name);
3149 i += 4;
3150 iStart = i+1;
3151 }
3152 }
3153 }
3154 fprintf(out,"%s",&line[iStart]);
3155 }
3156}
3157
3158/* The next function finds the template file and opens it, returning
3159** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003160PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003161{
3162 static char templatename[] = "lempar.c";
3163 char buf[1000];
3164 FILE *in;
3165 char *tpltname;
3166 char *cp;
3167
icculus3e143bd2010-02-14 00:48:49 +00003168 /* first, see if user specified a template filename on the command line. */
3169 if (user_templatename != 0) {
3170 if( access(user_templatename,004)==-1 ){
3171 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3172 user_templatename);
3173 lemp->errorcnt++;
3174 return 0;
3175 }
3176 in = fopen(user_templatename,"rb");
3177 if( in==0 ){
3178 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3179 lemp->errorcnt++;
3180 return 0;
3181 }
3182 return in;
3183 }
3184
drh75897232000-05-29 14:26:00 +00003185 cp = strrchr(lemp->filename,'.');
3186 if( cp ){
drh8b582012003-10-21 13:16:03 +00003187 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003188 }else{
3189 sprintf(buf,"%s.lt",lemp->filename);
3190 }
3191 if( access(buf,004)==0 ){
3192 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003193 }else if( access(templatename,004)==0 ){
3194 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003195 }else{
3196 tpltname = pathsearch(lemp->argv0,templatename,0);
3197 }
3198 if( tpltname==0 ){
3199 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3200 templatename);
3201 lemp->errorcnt++;
3202 return 0;
3203 }
drh2aa6ca42004-09-10 00:14:04 +00003204 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003205 if( in==0 ){
3206 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3207 lemp->errorcnt++;
3208 return 0;
3209 }
3210 return in;
3211}
3212
drhaf805ca2004-09-07 11:28:25 +00003213/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003214PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003215{
3216 fprintf(out,"#line %d \"",lineno);
3217 while( *filename ){
3218 if( *filename == '\\' ) putc('\\',out);
3219 putc(*filename,out);
3220 filename++;
3221 }
3222 fprintf(out,"\"\n");
3223}
3224
drh75897232000-05-29 14:26:00 +00003225/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003226PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003227{
3228 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003229 while( *str ){
drh75897232000-05-29 14:26:00 +00003230 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003231 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003232 str++;
3233 }
drh9db55df2004-09-09 14:01:21 +00003234 if( str[-1]!='\n' ){
3235 putc('\n',out);
3236 (*lineno)++;
3237 }
shane58543932008-12-10 20:10:04 +00003238 if (!lemp->nolinenosflag) {
3239 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3240 }
drh75897232000-05-29 14:26:00 +00003241 return;
3242}
3243
3244/*
3245** The following routine emits code for the destructor for the
3246** symbol sp
3247*/
icculus9e44cf12010-02-14 17:14:22 +00003248void emit_destructor_code(
3249 FILE *out,
3250 struct symbol *sp,
3251 struct lemon *lemp,
3252 int *lineno
3253){
drhcc83b6e2004-04-23 23:38:42 +00003254 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003255
drh75897232000-05-29 14:26:00 +00003256 if( sp->type==TERMINAL ){
3257 cp = lemp->tokendest;
3258 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003259 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003260 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003261 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003262 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003263 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003264 }else if( lemp->vardest ){
3265 cp = lemp->vardest;
3266 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003267 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003268 }else{
3269 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003270 }
3271 for(; *cp; cp++){
3272 if( *cp=='$' && cp[1]=='$' ){
3273 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3274 cp++;
3275 continue;
3276 }
shane58543932008-12-10 20:10:04 +00003277 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003278 fputc(*cp,out);
3279 }
shane58543932008-12-10 20:10:04 +00003280 fprintf(out,"\n"); (*lineno)++;
3281 if (!lemp->nolinenosflag) {
3282 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3283 }
3284 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003285 return;
3286}
3287
3288/*
drh960e8c62001-04-03 16:53:21 +00003289** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003290*/
icculus9e44cf12010-02-14 17:14:22 +00003291int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003292{
3293 int ret;
3294 if( sp->type==TERMINAL ){
3295 ret = lemp->tokendest!=0;
3296 }else{
drh960e8c62001-04-03 16:53:21 +00003297 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003298 }
3299 return ret;
3300}
3301
drh0bb132b2004-07-20 14:06:51 +00003302/*
3303** Append text to a dynamically allocated string. If zText is 0 then
3304** reset the string to be empty again. Always return the complete text
3305** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003306**
3307** n bytes of zText are stored. If n==0 then all of zText up to the first
3308** \000 terminator is stored. zText can contain up to two instances of
3309** %d. The values of p1 and p2 are written into the first and second
3310** %d.
3311**
3312** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003313*/
icculus9e44cf12010-02-14 17:14:22 +00003314PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3315 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003316 static char *z = 0;
3317 static int alloced = 0;
3318 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003319 int c;
drh0bb132b2004-07-20 14:06:51 +00003320 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003321 if( zText==0 ){
3322 used = 0;
3323 return z;
3324 }
drh7ac25c72004-08-19 15:12:26 +00003325 if( n<=0 ){
3326 if( n<0 ){
3327 used += n;
3328 assert( used>=0 );
3329 }
drh87cf1372008-08-13 20:09:06 +00003330 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003331 }
drh0bb132b2004-07-20 14:06:51 +00003332 if( n+sizeof(zInt)*2+used >= alloced ){
3333 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003334 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003335 }
icculus9e44cf12010-02-14 17:14:22 +00003336 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003337 while( n-- > 0 ){
3338 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003339 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003340 sprintf(zInt, "%d", p1);
3341 p1 = p2;
3342 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003343 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003344 zText++;
3345 n--;
3346 }else{
3347 z[used++] = c;
3348 }
3349 }
3350 z[used] = 0;
3351 return z;
3352}
3353
3354/*
3355** zCode is a string that is the action associated with a rule. Expand
3356** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003357** stack.
drh0bb132b2004-07-20 14:06:51 +00003358*/
drhaf805ca2004-09-07 11:28:25 +00003359PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003360 char *cp, *xp;
3361 int i;
3362 char lhsused = 0; /* True if the LHS element has been used */
3363 char used[MAXRHS]; /* True for each RHS element which is used */
3364
3365 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3366 lhsused = 0;
3367
drh19c9e562007-03-29 20:13:53 +00003368 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003369 static char newlinestr[2] = { '\n', '\0' };
3370 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003371 rp->line = rp->ruleline;
3372 }
3373
drh0bb132b2004-07-20 14:06:51 +00003374 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003375
3376 /* This const cast is wrong but harmless, if we're careful. */
3377 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003378 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3379 char saved;
3380 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3381 saved = *xp;
3382 *xp = 0;
3383 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003384 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003385 cp = xp;
3386 lhsused = 1;
3387 }else{
3388 for(i=0; i<rp->nrhs; i++){
3389 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003390 if( cp!=rp->code && cp[-1]=='@' ){
3391 /* If the argument is of the form @X then substituted
3392 ** the token number of X, not the value of X */
3393 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3394 }else{
drhfd405312005-11-06 04:06:59 +00003395 struct symbol *sp = rp->rhs[i];
3396 int dtnum;
3397 if( sp->type==MULTITERMINAL ){
3398 dtnum = sp->subsym[0]->dtnum;
3399 }else{
3400 dtnum = sp->dtnum;
3401 }
3402 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003403 }
drh0bb132b2004-07-20 14:06:51 +00003404 cp = xp;
3405 used[i] = 1;
3406 break;
3407 }
3408 }
3409 }
3410 *xp = saved;
3411 }
3412 append_str(cp, 1, 0, 0);
3413 } /* End loop */
3414
3415 /* Check to make sure the LHS has been used */
3416 if( rp->lhsalias && !lhsused ){
3417 ErrorMsg(lemp->filename,rp->ruleline,
3418 "Label \"%s\" for \"%s(%s)\" is never used.",
3419 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3420 lemp->errorcnt++;
3421 }
3422
3423 /* Generate destructor code for RHS symbols which are not used in the
3424 ** reduce code */
3425 for(i=0; i<rp->nrhs; i++){
3426 if( rp->rhsalias[i] && !used[i] ){
3427 ErrorMsg(lemp->filename,rp->ruleline,
3428 "Label %s for \"%s(%s)\" is never used.",
3429 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3430 lemp->errorcnt++;
3431 }else if( rp->rhsalias[i]==0 ){
3432 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003433 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003434 rp->rhs[i]->index,i-rp->nrhs+1);
3435 }else{
3436 /* No destructor defined for this term */
3437 }
3438 }
3439 }
drh61e339a2007-01-16 03:09:02 +00003440 if( rp->code ){
3441 cp = append_str(0,0,0,0);
3442 rp->code = Strsafe(cp?cp:"");
3443 }
drh0bb132b2004-07-20 14:06:51 +00003444}
3445
drh75897232000-05-29 14:26:00 +00003446/*
3447** Generate code which executes when the rule "rp" is reduced. Write
3448** the code to "out". Make sure lineno stays up-to-date.
3449*/
icculus9e44cf12010-02-14 17:14:22 +00003450PRIVATE void emit_code(
3451 FILE *out,
3452 struct rule *rp,
3453 struct lemon *lemp,
3454 int *lineno
3455){
3456 const char *cp;
drh75897232000-05-29 14:26:00 +00003457
3458 /* Generate code to do the reduce action */
3459 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003460 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003461 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003462 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003463 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003464 } /* End loop */
shane58543932008-12-10 20:10:04 +00003465 fprintf(out,"}\n"); (*lineno)++;
3466 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003467 } /* End if( rp->code ) */
3468
drh75897232000-05-29 14:26:00 +00003469 return;
3470}
3471
3472/*
3473** Print the definition of the union used for the parser's data stack.
3474** This union contains fields for every possible data type for tokens
3475** and nonterminals. In the process of computing and printing this
3476** union, also set the ".dtnum" field of every terminal and nonterminal
3477** symbol.
3478*/
icculus9e44cf12010-02-14 17:14:22 +00003479void print_stack_union(
3480 FILE *out, /* The output stream */
3481 struct lemon *lemp, /* The main info structure for this parser */
3482 int *plineno, /* Pointer to the line number */
3483 int mhflag /* True if generating makeheaders output */
3484){
drh75897232000-05-29 14:26:00 +00003485 int lineno = *plineno; /* The line number of the output */
3486 char **types; /* A hash table of datatypes */
3487 int arraysize; /* Size of the "types" array */
3488 int maxdtlength; /* Maximum length of any ".datatype" field. */
3489 char *stddt; /* Standardized name for a datatype */
3490 int i,j; /* Loop counters */
3491 int hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003492 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003493
3494 /* Allocate and initialize types[] and allocate stddt[] */
3495 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003496 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003497 for(i=0; i<arraysize; i++) types[i] = 0;
3498 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003499 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003500 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003501 }
drh75897232000-05-29 14:26:00 +00003502 for(i=0; i<lemp->nsymbol; i++){
3503 int len;
3504 struct symbol *sp = lemp->symbols[i];
3505 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003506 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003507 if( len>maxdtlength ) maxdtlength = len;
3508 }
3509 stddt = (char*)malloc( maxdtlength*2 + 1 );
3510 if( types==0 || stddt==0 ){
3511 fprintf(stderr,"Out of memory.\n");
3512 exit(1);
3513 }
3514
3515 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3516 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003517 ** used for terminal symbols. If there is no %default_type defined then
3518 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3519 ** a datatype using the %type directive.
3520 */
drh75897232000-05-29 14:26:00 +00003521 for(i=0; i<lemp->nsymbol; i++){
3522 struct symbol *sp = lemp->symbols[i];
3523 char *cp;
3524 if( sp==lemp->errsym ){
3525 sp->dtnum = arraysize+1;
3526 continue;
3527 }
drh960e8c62001-04-03 16:53:21 +00003528 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003529 sp->dtnum = 0;
3530 continue;
3531 }
3532 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003533 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003534 j = 0;
3535 while( isspace(*cp) ) cp++;
3536 while( *cp ) stddt[j++] = *cp++;
3537 while( j>0 && isspace(stddt[j-1]) ) j--;
3538 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003539 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003540 sp->dtnum = 0;
3541 continue;
3542 }
drh75897232000-05-29 14:26:00 +00003543 hash = 0;
3544 for(j=0; stddt[j]; j++){
3545 hash = hash*53 + stddt[j];
3546 }
drh3b2129c2003-05-13 00:34:21 +00003547 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003548 while( types[hash] ){
3549 if( strcmp(types[hash],stddt)==0 ){
3550 sp->dtnum = hash + 1;
3551 break;
3552 }
3553 hash++;
3554 if( hash>=arraysize ) hash = 0;
3555 }
3556 if( types[hash]==0 ){
3557 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003558 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003559 if( types[hash]==0 ){
3560 fprintf(stderr,"Out of memory.\n");
3561 exit(1);
3562 }
3563 strcpy(types[hash],stddt);
3564 }
3565 }
3566
3567 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3568 name = lemp->name ? lemp->name : "Parse";
3569 lineno = *plineno;
3570 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3571 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3572 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3573 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3574 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003575 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003576 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3577 for(i=0; i<arraysize; i++){
3578 if( types[i]==0 ) continue;
3579 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3580 free(types[i]);
3581 }
drhc4dd3fd2008-01-22 01:48:05 +00003582 if( lemp->errsym->useCnt ){
3583 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3584 }
drh75897232000-05-29 14:26:00 +00003585 free(stddt);
3586 free(types);
3587 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3588 *plineno = lineno;
3589}
3590
drhb29b0a52002-02-23 19:39:46 +00003591/*
3592** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003593** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003594*/
drh8b582012003-10-21 13:16:03 +00003595static const char *minimum_size_type(int lwr, int upr){
3596 if( lwr>=0 ){
3597 if( upr<=255 ){
3598 return "unsigned char";
3599 }else if( upr<65535 ){
3600 return "unsigned short int";
3601 }else{
3602 return "unsigned int";
3603 }
3604 }else if( lwr>=-127 && upr<=127 ){
3605 return "signed char";
3606 }else if( lwr>=-32767 && upr<32767 ){
3607 return "short";
drhb29b0a52002-02-23 19:39:46 +00003608 }else{
drh8b582012003-10-21 13:16:03 +00003609 return "int";
drhb29b0a52002-02-23 19:39:46 +00003610 }
3611}
3612
drhfdbf9282003-10-21 16:34:41 +00003613/*
3614** Each state contains a set of token transaction and a set of
3615** nonterminal transactions. Each of these sets makes an instance
3616** of the following structure. An array of these structures is used
3617** to order the creation of entries in the yy_action[] table.
3618*/
3619struct axset {
3620 struct state *stp; /* A pointer to a state */
3621 int isTkn; /* True to use tokens. False for non-terminals */
3622 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003623 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003624};
3625
3626/*
3627** Compare to axset structures for sorting purposes
3628*/
3629static int axset_compare(const void *a, const void *b){
3630 struct axset *p1 = (struct axset*)a;
3631 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003632 int c;
3633 c = p2->nAction - p1->nAction;
3634 if( c==0 ){
3635 c = p2->iOrder - p1->iOrder;
3636 }
3637 assert( c!=0 || p1==p2 );
3638 return c;
drhfdbf9282003-10-21 16:34:41 +00003639}
3640
drhc4dd3fd2008-01-22 01:48:05 +00003641/*
3642** Write text on "out" that describes the rule "rp".
3643*/
3644static void writeRuleText(FILE *out, struct rule *rp){
3645 int j;
3646 fprintf(out,"%s ::=", rp->lhs->name);
3647 for(j=0; j<rp->nrhs; j++){
3648 struct symbol *sp = rp->rhs[j];
3649 fprintf(out," %s", sp->name);
3650 if( sp->type==MULTITERMINAL ){
3651 int k;
3652 for(k=1; k<sp->nsubsym; k++){
3653 fprintf(out,"|%s",sp->subsym[k]->name);
3654 }
3655 }
3656 }
3657}
3658
3659
drh75897232000-05-29 14:26:00 +00003660/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003661void ReportTable(
3662 struct lemon *lemp,
3663 int mhflag /* Output in makeheaders format if true */
3664){
drh75897232000-05-29 14:26:00 +00003665 FILE *out, *in;
3666 char line[LINESIZE];
3667 int lineno;
3668 struct state *stp;
3669 struct action *ap;
3670 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003671 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003672 int i, j, k, n;
icculus9e44cf12010-02-14 17:14:22 +00003673 const char *name;
drh8b582012003-10-21 13:16:03 +00003674 int mnTknOfst, mxTknOfst;
3675 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003676 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003677
3678 in = tplt_open(lemp);
3679 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003680 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003681 if( out==0 ){
3682 fclose(in);
3683 return;
3684 }
3685 lineno = 1;
3686 tplt_xfer(lemp->name,in,out,&lineno);
3687
3688 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003689 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003690 if( mhflag ){
3691 char *name = file_makename(lemp, ".h");
3692 fprintf(out,"#include \"%s\"\n", name); lineno++;
3693 free(name);
3694 }
3695 tplt_xfer(lemp->name,in,out,&lineno);
3696
3697 /* Generate #defines for all tokens */
3698 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003699 const char *prefix;
drh75897232000-05-29 14:26:00 +00003700 fprintf(out,"#if INTERFACE\n"); lineno++;
3701 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3702 else prefix = "";
3703 for(i=1; i<lemp->nterminal; i++){
3704 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3705 lineno++;
3706 }
3707 fprintf(out,"#endif\n"); lineno++;
3708 }
3709 tplt_xfer(lemp->name,in,out,&lineno);
3710
3711 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003712 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003713 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003714 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3715 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003716 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003717 if( lemp->wildcard ){
3718 fprintf(out,"#define YYWILDCARD %d\n",
3719 lemp->wildcard->index); lineno++;
3720 }
drh75897232000-05-29 14:26:00 +00003721 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003722 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003723 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003724 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3725 }else{
3726 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3727 }
drhca44b5a2007-02-22 23:06:58 +00003728 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003729 if( mhflag ){
3730 fprintf(out,"#if INTERFACE\n"); lineno++;
3731 }
3732 name = lemp->name ? lemp->name : "Parse";
3733 if( lemp->arg && lemp->arg[0] ){
3734 int i;
drh87cf1372008-08-13 20:09:06 +00003735 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003736 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3737 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003738 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3739 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3740 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3741 name,lemp->arg,&lemp->arg[i]); lineno++;
3742 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3743 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003744 }else{
drh1f245e42002-03-11 13:55:50 +00003745 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3746 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3747 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3748 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003749 }
3750 if( mhflag ){
3751 fprintf(out,"#endif\n"); lineno++;
3752 }
3753 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3754 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003755 if( lemp->errsym->useCnt ){
3756 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3757 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3758 }
drh0bd1f4e2002-06-06 18:54:39 +00003759 if( lemp->has_fallback ){
3760 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3761 }
drh75897232000-05-29 14:26:00 +00003762 tplt_xfer(lemp->name,in,out,&lineno);
3763
drh8b582012003-10-21 13:16:03 +00003764 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003765 **
drh8b582012003-10-21 13:16:03 +00003766 ** yy_action[] A single table containing all actions.
3767 ** yy_lookahead[] A table containing the lookahead for each entry in
3768 ** yy_action. Used to detect hash collisions.
3769 ** yy_shift_ofst[] For each state, the offset into yy_action for
3770 ** shifting terminals.
3771 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3772 ** shifting non-terminals after a reduce.
3773 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003774 */
drh75897232000-05-29 14:26:00 +00003775
drh8b582012003-10-21 13:16:03 +00003776 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003777 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003778 if( ax==0 ){
3779 fprintf(stderr,"malloc failed\n");
3780 exit(1);
3781 }
drh75897232000-05-29 14:26:00 +00003782 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003783 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003784 ax[i*2].stp = stp;
3785 ax[i*2].isTkn = 1;
3786 ax[i*2].nAction = stp->nTknAct;
3787 ax[i*2+1].stp = stp;
3788 ax[i*2+1].isTkn = 0;
3789 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003790 }
drh8b582012003-10-21 13:16:03 +00003791 mxTknOfst = mnTknOfst = 0;
3792 mxNtOfst = mnNtOfst = 0;
3793
drhfdbf9282003-10-21 16:34:41 +00003794 /* Compute the action table. In order to try to keep the size of the
3795 ** action table to a minimum, the heuristic of placing the largest action
3796 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003797 */
drhe594bc32009-11-03 13:02:25 +00003798 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003799 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003800 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003801 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3802 stp = ax[i].stp;
3803 if( ax[i].isTkn ){
3804 for(ap=stp->ap; ap; ap=ap->next){
3805 int action;
3806 if( ap->sp->index>=lemp->nterminal ) continue;
3807 action = compute_action(lemp, ap);
3808 if( action<0 ) continue;
3809 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003810 }
drhfdbf9282003-10-21 16:34:41 +00003811 stp->iTknOfst = acttab_insert(pActtab);
3812 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3813 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3814 }else{
3815 for(ap=stp->ap; ap; ap=ap->next){
3816 int action;
3817 if( ap->sp->index<lemp->nterminal ) continue;
3818 if( ap->sp->index==lemp->nsymbol ) continue;
3819 action = compute_action(lemp, ap);
3820 if( action<0 ) continue;
3821 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003822 }
drhfdbf9282003-10-21 16:34:41 +00003823 stp->iNtOfst = acttab_insert(pActtab);
3824 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3825 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003826 }
3827 }
drhfdbf9282003-10-21 16:34:41 +00003828 free(ax);
drh8b582012003-10-21 13:16:03 +00003829
3830 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003831 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003832 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3833 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003834 for(i=j=0; i<n; i++){
3835 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003836 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003837 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003838 fprintf(out, " %4d,", action);
3839 if( j==9 || i==n-1 ){
3840 fprintf(out, "\n"); lineno++;
3841 j = 0;
3842 }else{
3843 j++;
3844 }
3845 }
3846 fprintf(out, "};\n"); lineno++;
3847
3848 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003849 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003850 for(i=j=0; i<n; i++){
3851 int la = acttab_yylookahead(pActtab, i);
3852 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003853 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003854 fprintf(out, " %4d,", la);
3855 if( j==9 || i==n-1 ){
3856 fprintf(out, "\n"); lineno++;
3857 j = 0;
3858 }else{
3859 j++;
3860 }
3861 }
3862 fprintf(out, "};\n"); lineno++;
3863
3864 /* Output the yy_shift_ofst[] table */
3865 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003866 n = lemp->nstate;
3867 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003868 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3869 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3870 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003871 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003872 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003873 for(i=j=0; i<n; i++){
3874 int ofst;
3875 stp = lemp->sorted[i];
3876 ofst = stp->iTknOfst;
3877 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003878 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003879 fprintf(out, " %4d,", ofst);
3880 if( j==9 || i==n-1 ){
3881 fprintf(out, "\n"); lineno++;
3882 j = 0;
3883 }else{
3884 j++;
3885 }
3886 }
3887 fprintf(out, "};\n"); lineno++;
3888
3889 /* Output the yy_reduce_ofst[] table */
3890 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003891 n = lemp->nstate;
3892 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003893 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3894 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3895 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003896 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003897 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003898 for(i=j=0; i<n; i++){
3899 int ofst;
3900 stp = lemp->sorted[i];
3901 ofst = stp->iNtOfst;
3902 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003903 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003904 fprintf(out, " %4d,", ofst);
3905 if( j==9 || i==n-1 ){
3906 fprintf(out, "\n"); lineno++;
3907 j = 0;
3908 }else{
3909 j++;
3910 }
3911 }
3912 fprintf(out, "};\n"); lineno++;
3913
3914 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003915 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003916 n = lemp->nstate;
3917 for(i=j=0; i<n; i++){
3918 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003919 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003920 fprintf(out, " %4d,", stp->iDflt);
3921 if( j==9 || i==n-1 ){
3922 fprintf(out, "\n"); lineno++;
3923 j = 0;
3924 }else{
3925 j++;
3926 }
3927 }
3928 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003929 tplt_xfer(lemp->name,in,out,&lineno);
3930
drh0bd1f4e2002-06-06 18:54:39 +00003931 /* Generate the table of fallback tokens.
3932 */
3933 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003934 int mx = lemp->nterminal - 1;
3935 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3936 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003937 struct symbol *p = lemp->symbols[i];
3938 if( p->fallback==0 ){
3939 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3940 }else{
3941 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3942 p->name, p->fallback->name);
3943 }
3944 lineno++;
3945 }
3946 }
3947 tplt_xfer(lemp->name, in, out, &lineno);
3948
3949 /* Generate a table containing the symbolic name of every symbol
3950 */
drh75897232000-05-29 14:26:00 +00003951 for(i=0; i<lemp->nsymbol; i++){
3952 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3953 fprintf(out," %-15s",line);
3954 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3955 }
3956 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3957 tplt_xfer(lemp->name,in,out,&lineno);
3958
drh0bd1f4e2002-06-06 18:54:39 +00003959 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003960 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003961 ** when tracing REDUCE actions.
3962 */
3963 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3964 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003965 fprintf(out," /* %3d */ \"", i);
3966 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003967 fprintf(out,"\",\n"); lineno++;
3968 }
3969 tplt_xfer(lemp->name,in,out,&lineno);
3970
drh75897232000-05-29 14:26:00 +00003971 /* Generate code which executes every time a symbol is popped from
3972 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003973 ** (In other words, generate the %destructor actions)
3974 */
drh75897232000-05-29 14:26:00 +00003975 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003976 int once = 1;
drh75897232000-05-29 14:26:00 +00003977 for(i=0; i<lemp->nsymbol; i++){
3978 struct symbol *sp = lemp->symbols[i];
3979 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003980 if( once ){
3981 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3982 once = 0;
3983 }
drhc53eed12009-06-12 17:46:19 +00003984 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003985 }
3986 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3987 if( i<lemp->nsymbol ){
3988 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3989 fprintf(out," break;\n"); lineno++;
3990 }
3991 }
drh8d659732005-01-13 23:54:06 +00003992 if( lemp->vardest ){
3993 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003994 int once = 1;
drh8d659732005-01-13 23:54:06 +00003995 for(i=0; i<lemp->nsymbol; i++){
3996 struct symbol *sp = lemp->symbols[i];
3997 if( sp==0 || sp->type==TERMINAL ||
3998 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003999 if( once ){
4000 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
4001 once = 0;
4002 }
drhc53eed12009-06-12 17:46:19 +00004003 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00004004 dflt_sp = sp;
4005 }
4006 if( dflt_sp!=0 ){
4007 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00004008 }
drh4dc8ef52008-07-01 17:13:57 +00004009 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00004010 }
drh75897232000-05-29 14:26:00 +00004011 for(i=0; i<lemp->nsymbol; i++){
4012 struct symbol *sp = lemp->symbols[i];
4013 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00004014 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004015
4016 /* Combine duplicate destructors into a single case */
4017 for(j=i+1; j<lemp->nsymbol; j++){
4018 struct symbol *sp2 = lemp->symbols[j];
4019 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
4020 && sp2->dtnum==sp->dtnum
4021 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00004022 fprintf(out," case %d: /* %s */\n",
4023 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004024 sp2->destructor = 0;
4025 }
4026 }
4027
drh75897232000-05-29 14:26:00 +00004028 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
4029 fprintf(out," break;\n"); lineno++;
4030 }
drh75897232000-05-29 14:26:00 +00004031 tplt_xfer(lemp->name,in,out,&lineno);
4032
4033 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00004034 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00004035 tplt_xfer(lemp->name,in,out,&lineno);
4036
4037 /* Generate the table of rule information
4038 **
4039 ** Note: This code depends on the fact that rules are number
4040 ** sequentually beginning with 0.
4041 */
4042 for(rp=lemp->rule; rp; rp=rp->next){
4043 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
4044 }
4045 tplt_xfer(lemp->name,in,out,&lineno);
4046
4047 /* Generate code which execution during each REDUCE action */
4048 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00004049 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00004050 }
drhc53eed12009-06-12 17:46:19 +00004051 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00004052 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00004053 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00004054 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00004055 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00004056 fprintf(out," case %d: /* ", rp->index);
4057 writeRuleText(out, rp);
4058 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004059 for(rp2=rp->next; rp2; rp2=rp2->next){
4060 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00004061 fprintf(out," case %d: /* ", rp2->index);
4062 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00004063 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00004064 rp2->code = 0;
4065 }
4066 }
drh75897232000-05-29 14:26:00 +00004067 emit_code(out,rp,lemp,&lineno);
4068 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004069 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004070 }
drhc53eed12009-06-12 17:46:19 +00004071 /* Finally, output the default: rule. We choose as the default: all
4072 ** empty actions. */
4073 fprintf(out," default:\n"); lineno++;
4074 for(rp=lemp->rule; rp; rp=rp->next){
4075 if( rp->code==0 ) continue;
4076 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4077 fprintf(out," /* (%d) ", rp->index);
4078 writeRuleText(out, rp);
4079 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4080 }
4081 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004082 tplt_xfer(lemp->name,in,out,&lineno);
4083
4084 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004085 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004086 tplt_xfer(lemp->name,in,out,&lineno);
4087
4088 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004089 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004090 tplt_xfer(lemp->name,in,out,&lineno);
4091
4092 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004093 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004094 tplt_xfer(lemp->name,in,out,&lineno);
4095
4096 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004097 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004098
4099 fclose(in);
4100 fclose(out);
4101 return;
4102}
4103
4104/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004105void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004106{
4107 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004108 const char *prefix;
drh75897232000-05-29 14:26:00 +00004109 char line[LINESIZE];
4110 char pattern[LINESIZE];
4111 int i;
4112
4113 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4114 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004115 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004116 if( in ){
4117 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4118 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4119 if( strcmp(line,pattern) ) break;
4120 }
4121 fclose(in);
4122 if( i==lemp->nterminal ){
4123 /* No change in the file. Don't rewrite it. */
4124 return;
4125 }
4126 }
drh2aa6ca42004-09-10 00:14:04 +00004127 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004128 if( out ){
4129 for(i=1; i<lemp->nterminal; i++){
4130 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4131 }
4132 fclose(out);
4133 }
4134 return;
4135}
4136
4137/* Reduce the size of the action tables, if possible, by making use
4138** of defaults.
4139**
drhb59499c2002-02-23 18:45:13 +00004140** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004141** it the default. Except, there is no default if the wildcard token
4142** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004143*/
icculus9e44cf12010-02-14 17:14:22 +00004144void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004145{
4146 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004147 struct action *ap, *ap2;
4148 struct rule *rp, *rp2, *rbest;
4149 int nbest, n;
drh75897232000-05-29 14:26:00 +00004150 int i;
drhe09daa92006-06-10 13:29:31 +00004151 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004152
4153 for(i=0; i<lemp->nstate; i++){
4154 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004155 nbest = 0;
4156 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004157 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004158
drhb59499c2002-02-23 18:45:13 +00004159 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004160 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4161 usesWildcard = 1;
4162 }
drhb59499c2002-02-23 18:45:13 +00004163 if( ap->type!=REDUCE ) continue;
4164 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004165 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004166 if( rp==rbest ) continue;
4167 n = 1;
4168 for(ap2=ap->next; ap2; ap2=ap2->next){
4169 if( ap2->type!=REDUCE ) continue;
4170 rp2 = ap2->x.rp;
4171 if( rp2==rbest ) continue;
4172 if( rp2==rp ) n++;
4173 }
4174 if( n>nbest ){
4175 nbest = n;
4176 rbest = rp;
drh75897232000-05-29 14:26:00 +00004177 }
4178 }
drhb59499c2002-02-23 18:45:13 +00004179
4180 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004181 ** is not at least 1 or if the wildcard token is a possible
4182 ** lookahead.
4183 */
4184 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004185
drhb59499c2002-02-23 18:45:13 +00004186
4187 /* Combine matching REDUCE actions into a single default */
4188 for(ap=stp->ap; ap; ap=ap->next){
4189 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4190 }
drh75897232000-05-29 14:26:00 +00004191 assert( ap );
4192 ap->sp = Symbol_new("{default}");
4193 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004194 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004195 }
4196 stp->ap = Action_sort(stp->ap);
4197 }
4198}
drhb59499c2002-02-23 18:45:13 +00004199
drhada354d2005-11-05 15:03:59 +00004200
4201/*
4202** Compare two states for sorting purposes. The smaller state is the
4203** one with the most non-terminal actions. If they have the same number
4204** of non-terminal actions, then the smaller is the one with the most
4205** token actions.
4206*/
4207static int stateResortCompare(const void *a, const void *b){
4208 const struct state *pA = *(const struct state**)a;
4209 const struct state *pB = *(const struct state**)b;
4210 int n;
4211
4212 n = pB->nNtAct - pA->nNtAct;
4213 if( n==0 ){
4214 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004215 if( n==0 ){
4216 n = pB->statenum - pA->statenum;
4217 }
drhada354d2005-11-05 15:03:59 +00004218 }
drhe594bc32009-11-03 13:02:25 +00004219 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004220 return n;
4221}
4222
4223
4224/*
4225** Renumber and resort states so that states with fewer choices
4226** occur at the end. Except, keep state 0 as the first state.
4227*/
icculus9e44cf12010-02-14 17:14:22 +00004228void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004229{
4230 int i;
4231 struct state *stp;
4232 struct action *ap;
4233
4234 for(i=0; i<lemp->nstate; i++){
4235 stp = lemp->sorted[i];
4236 stp->nTknAct = stp->nNtAct = 0;
4237 stp->iDflt = lemp->nstate + lemp->nrule;
4238 stp->iTknOfst = NO_OFFSET;
4239 stp->iNtOfst = NO_OFFSET;
4240 for(ap=stp->ap; ap; ap=ap->next){
4241 if( compute_action(lemp,ap)>=0 ){
4242 if( ap->sp->index<lemp->nterminal ){
4243 stp->nTknAct++;
4244 }else if( ap->sp->index<lemp->nsymbol ){
4245 stp->nNtAct++;
4246 }else{
4247 stp->iDflt = compute_action(lemp, ap);
4248 }
4249 }
4250 }
4251 }
4252 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4253 stateResortCompare);
4254 for(i=0; i<lemp->nstate; i++){
4255 lemp->sorted[i]->statenum = i;
4256 }
4257}
4258
4259
drh75897232000-05-29 14:26:00 +00004260/***************** From the file "set.c" ************************************/
4261/*
4262** Set manipulation routines for the LEMON parser generator.
4263*/
4264
4265static int size = 0;
4266
4267/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004268void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004269{
4270 size = n+1;
4271}
4272
4273/* Allocate a new set */
4274char *SetNew(){
4275 char *s;
drh9892c5d2007-12-21 00:02:11 +00004276 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004277 if( s==0 ){
4278 extern void memory_error();
4279 memory_error();
4280 }
drh75897232000-05-29 14:26:00 +00004281 return s;
4282}
4283
4284/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004285void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004286{
4287 free(s);
4288}
4289
4290/* Add a new element to the set. Return TRUE if the element was added
4291** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004292int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004293{
4294 int rv;
drh9892c5d2007-12-21 00:02:11 +00004295 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004296 rv = s[e];
4297 s[e] = 1;
4298 return !rv;
4299}
4300
4301/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004302int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004303{
4304 int i, progress;
4305 progress = 0;
4306 for(i=0; i<size; i++){
4307 if( s2[i]==0 ) continue;
4308 if( s1[i]==0 ){
4309 progress = 1;
4310 s1[i] = 1;
4311 }
4312 }
4313 return progress;
4314}
4315/********************** From the file "table.c" ****************************/
4316/*
4317** All code in this file has been automatically generated
4318** from a specification in the file
4319** "table.q"
4320** by the associative array code building program "aagen".
4321** Do not edit this file! Instead, edit the specification
4322** file, then rerun aagen.
4323*/
4324/*
4325** Code for processing tables in the LEMON parser generator.
4326*/
4327
icculus9e44cf12010-02-14 17:14:22 +00004328PRIVATE int strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004329{
4330 int h = 0;
4331 while( *x) h = h*13 + *(x++);
4332 return h;
4333}
4334
4335/* Works like strdup, sort of. Save a string in malloced memory, but
4336** keep strings in a table so that the same string is not in more
4337** than one place.
4338*/
icculus9e44cf12010-02-14 17:14:22 +00004339const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004340{
icculus9e44cf12010-02-14 17:14:22 +00004341 const char *z;
4342 char *cpy;
drh75897232000-05-29 14:26:00 +00004343
drh916f75f2006-07-17 00:19:39 +00004344 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004345 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004346 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4347 strcpy(cpy,y);
4348 z = cpy;
drh75897232000-05-29 14:26:00 +00004349 Strsafe_insert(z);
4350 }
4351 MemoryCheck(z);
4352 return z;
4353}
4354
4355/* There is one instance of the following structure for each
4356** associative array of type "x1".
4357*/
4358struct s_x1 {
4359 int size; /* The number of available slots. */
4360 /* Must be a power of 2 greater than or */
4361 /* equal to 1 */
4362 int count; /* Number of currently slots filled */
4363 struct s_x1node *tbl; /* The data stored here */
4364 struct s_x1node **ht; /* Hash table for lookups */
4365};
4366
4367/* There is one instance of this structure for every data element
4368** in an associative array of type "x1".
4369*/
4370typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004371 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004372 struct s_x1node *next; /* Next entry with the same hash */
4373 struct s_x1node **from; /* Previous link */
4374} x1node;
4375
4376/* There is only one instance of the array, which is the following */
4377static struct s_x1 *x1a;
4378
4379/* Allocate a new associative array */
4380void Strsafe_init(){
4381 if( x1a ) return;
4382 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4383 if( x1a ){
4384 x1a->size = 1024;
4385 x1a->count = 0;
4386 x1a->tbl = (x1node*)malloc(
4387 (sizeof(x1node) + sizeof(x1node*))*1024 );
4388 if( x1a->tbl==0 ){
4389 free(x1a);
4390 x1a = 0;
4391 }else{
4392 int i;
4393 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4394 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4395 }
4396 }
4397}
4398/* Insert a new record into the array. Return TRUE if successful.
4399** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004400int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004401{
4402 x1node *np;
4403 int h;
4404 int ph;
4405
4406 if( x1a==0 ) return 0;
4407 ph = strhash(data);
4408 h = ph & (x1a->size-1);
4409 np = x1a->ht[h];
4410 while( np ){
4411 if( strcmp(np->data,data)==0 ){
4412 /* An existing entry with the same key is found. */
4413 /* Fail because overwrite is not allows. */
4414 return 0;
4415 }
4416 np = np->next;
4417 }
4418 if( x1a->count>=x1a->size ){
4419 /* Need to make the hash table bigger */
4420 int i,size;
4421 struct s_x1 array;
4422 array.size = size = x1a->size*2;
4423 array.count = x1a->count;
4424 array.tbl = (x1node*)malloc(
4425 (sizeof(x1node) + sizeof(x1node*))*size );
4426 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4427 array.ht = (x1node**)&(array.tbl[size]);
4428 for(i=0; i<size; i++) array.ht[i] = 0;
4429 for(i=0; i<x1a->count; i++){
4430 x1node *oldnp, *newnp;
4431 oldnp = &(x1a->tbl[i]);
4432 h = strhash(oldnp->data) & (size-1);
4433 newnp = &(array.tbl[i]);
4434 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4435 newnp->next = array.ht[h];
4436 newnp->data = oldnp->data;
4437 newnp->from = &(array.ht[h]);
4438 array.ht[h] = newnp;
4439 }
4440 free(x1a->tbl);
4441 *x1a = array;
4442 }
4443 /* Insert the new data */
4444 h = ph & (x1a->size-1);
4445 np = &(x1a->tbl[x1a->count++]);
4446 np->data = data;
4447 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4448 np->next = x1a->ht[h];
4449 x1a->ht[h] = np;
4450 np->from = &(x1a->ht[h]);
4451 return 1;
4452}
4453
4454/* Return a pointer to data assigned to the given key. Return NULL
4455** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004456const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004457{
4458 int h;
4459 x1node *np;
4460
4461 if( x1a==0 ) return 0;
4462 h = strhash(key) & (x1a->size-1);
4463 np = x1a->ht[h];
4464 while( np ){
4465 if( strcmp(np->data,key)==0 ) break;
4466 np = np->next;
4467 }
4468 return np ? np->data : 0;
4469}
4470
4471/* Return a pointer to the (terminal or nonterminal) symbol "x".
4472** Create a new symbol if this is the first time "x" has been seen.
4473*/
icculus9e44cf12010-02-14 17:14:22 +00004474struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004475{
4476 struct symbol *sp;
4477
4478 sp = Symbol_find(x);
4479 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004480 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004481 MemoryCheck(sp);
4482 sp->name = Strsafe(x);
4483 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4484 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004485 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004486 sp->prec = -1;
4487 sp->assoc = UNK;
4488 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004489 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004490 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004491 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004492 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004493 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004494 Symbol_insert(sp,sp->name);
4495 }
drhc4dd3fd2008-01-22 01:48:05 +00004496 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004497 return sp;
4498}
4499
drh60d31652004-02-22 00:08:04 +00004500/* Compare two symbols for working purposes
4501**
4502** Symbols that begin with upper case letters (terminals or tokens)
4503** must sort before symbols that begin with lower case letters
4504** (non-terminals). Other than that, the order does not matter.
4505**
4506** We find experimentally that leaving the symbols in their original
4507** order (the order they appeared in the grammar file) gives the
4508** smallest parser tables in SQLite.
4509*/
icculus9e44cf12010-02-14 17:14:22 +00004510int Symbolcmpp(const void *_a, const void *_b)
4511{
4512 const struct symbol **a = (const struct symbol **) _a;
4513 const struct symbol **b = (const struct symbol **) _b;
drh60d31652004-02-22 00:08:04 +00004514 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4515 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004516 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004517 return i1-i2;
drh75897232000-05-29 14:26:00 +00004518}
4519
4520/* There is one instance of the following structure for each
4521** associative array of type "x2".
4522*/
4523struct s_x2 {
4524 int size; /* The number of available slots. */
4525 /* Must be a power of 2 greater than or */
4526 /* equal to 1 */
4527 int count; /* Number of currently slots filled */
4528 struct s_x2node *tbl; /* The data stored here */
4529 struct s_x2node **ht; /* Hash table for lookups */
4530};
4531
4532/* There is one instance of this structure for every data element
4533** in an associative array of type "x2".
4534*/
4535typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004536 struct symbol *data; /* The data */
4537 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004538 struct s_x2node *next; /* Next entry with the same hash */
4539 struct s_x2node **from; /* Previous link */
4540} x2node;
4541
4542/* There is only one instance of the array, which is the following */
4543static struct s_x2 *x2a;
4544
4545/* Allocate a new associative array */
4546void Symbol_init(){
4547 if( x2a ) return;
4548 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4549 if( x2a ){
4550 x2a->size = 128;
4551 x2a->count = 0;
4552 x2a->tbl = (x2node*)malloc(
4553 (sizeof(x2node) + sizeof(x2node*))*128 );
4554 if( x2a->tbl==0 ){
4555 free(x2a);
4556 x2a = 0;
4557 }else{
4558 int i;
4559 x2a->ht = (x2node**)&(x2a->tbl[128]);
4560 for(i=0; i<128; i++) x2a->ht[i] = 0;
4561 }
4562 }
4563}
4564/* Insert a new record into the array. Return TRUE if successful.
4565** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004566int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004567{
4568 x2node *np;
4569 int h;
4570 int ph;
4571
4572 if( x2a==0 ) return 0;
4573 ph = strhash(key);
4574 h = ph & (x2a->size-1);
4575 np = x2a->ht[h];
4576 while( np ){
4577 if( strcmp(np->key,key)==0 ){
4578 /* An existing entry with the same key is found. */
4579 /* Fail because overwrite is not allows. */
4580 return 0;
4581 }
4582 np = np->next;
4583 }
4584 if( x2a->count>=x2a->size ){
4585 /* Need to make the hash table bigger */
4586 int i,size;
4587 struct s_x2 array;
4588 array.size = size = x2a->size*2;
4589 array.count = x2a->count;
4590 array.tbl = (x2node*)malloc(
4591 (sizeof(x2node) + sizeof(x2node*))*size );
4592 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4593 array.ht = (x2node**)&(array.tbl[size]);
4594 for(i=0; i<size; i++) array.ht[i] = 0;
4595 for(i=0; i<x2a->count; i++){
4596 x2node *oldnp, *newnp;
4597 oldnp = &(x2a->tbl[i]);
4598 h = strhash(oldnp->key) & (size-1);
4599 newnp = &(array.tbl[i]);
4600 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4601 newnp->next = array.ht[h];
4602 newnp->key = oldnp->key;
4603 newnp->data = oldnp->data;
4604 newnp->from = &(array.ht[h]);
4605 array.ht[h] = newnp;
4606 }
4607 free(x2a->tbl);
4608 *x2a = array;
4609 }
4610 /* Insert the new data */
4611 h = ph & (x2a->size-1);
4612 np = &(x2a->tbl[x2a->count++]);
4613 np->key = key;
4614 np->data = data;
4615 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4616 np->next = x2a->ht[h];
4617 x2a->ht[h] = np;
4618 np->from = &(x2a->ht[h]);
4619 return 1;
4620}
4621
4622/* Return a pointer to data assigned to the given key. Return NULL
4623** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004624struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004625{
4626 int h;
4627 x2node *np;
4628
4629 if( x2a==0 ) return 0;
4630 h = strhash(key) & (x2a->size-1);
4631 np = x2a->ht[h];
4632 while( np ){
4633 if( strcmp(np->key,key)==0 ) break;
4634 np = np->next;
4635 }
4636 return np ? np->data : 0;
4637}
4638
4639/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004640struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004641{
4642 struct symbol *data;
4643 if( x2a && n>0 && n<=x2a->count ){
4644 data = x2a->tbl[n-1].data;
4645 }else{
4646 data = 0;
4647 }
4648 return data;
4649}
4650
4651/* Return the size of the array */
4652int Symbol_count()
4653{
4654 return x2a ? x2a->count : 0;
4655}
4656
4657/* Return an array of pointers to all data in the table.
4658** The array is obtained from malloc. Return NULL if memory allocation
4659** problems, or if the array is empty. */
4660struct symbol **Symbol_arrayof()
4661{
4662 struct symbol **array;
4663 int i,size;
4664 if( x2a==0 ) return 0;
4665 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004666 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004667 if( array ){
4668 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4669 }
4670 return array;
4671}
4672
4673/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004674int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004675{
icculus9e44cf12010-02-14 17:14:22 +00004676 const struct config *a = (struct config *) _a;
4677 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004678 int x;
4679 x = a->rp->index - b->rp->index;
4680 if( x==0 ) x = a->dot - b->dot;
4681 return x;
4682}
4683
4684/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004685PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004686{
4687 int rc;
4688 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4689 rc = a->rp->index - b->rp->index;
4690 if( rc==0 ) rc = a->dot - b->dot;
4691 }
4692 if( rc==0 ){
4693 if( a ) rc = 1;
4694 if( b ) rc = -1;
4695 }
4696 return rc;
4697}
4698
4699/* Hash a state */
icculus9e44cf12010-02-14 17:14:22 +00004700PRIVATE int statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004701{
4702 int h=0;
4703 while( a ){
4704 h = h*571 + a->rp->index*37 + a->dot;
4705 a = a->bp;
4706 }
4707 return h;
4708}
4709
4710/* Allocate a new state structure */
4711struct state *State_new()
4712{
icculus9e44cf12010-02-14 17:14:22 +00004713 struct state *newstate;
4714 newstate = (struct state *)calloc(1, sizeof(struct state) );
4715 MemoryCheck(newstate);
4716 return newstate;
drh75897232000-05-29 14:26:00 +00004717}
4718
4719/* There is one instance of the following structure for each
4720** associative array of type "x3".
4721*/
4722struct s_x3 {
4723 int size; /* The number of available slots. */
4724 /* Must be a power of 2 greater than or */
4725 /* equal to 1 */
4726 int count; /* Number of currently slots filled */
4727 struct s_x3node *tbl; /* The data stored here */
4728 struct s_x3node **ht; /* Hash table for lookups */
4729};
4730
4731/* There is one instance of this structure for every data element
4732** in an associative array of type "x3".
4733*/
4734typedef struct s_x3node {
4735 struct state *data; /* The data */
4736 struct config *key; /* The key */
4737 struct s_x3node *next; /* Next entry with the same hash */
4738 struct s_x3node **from; /* Previous link */
4739} x3node;
4740
4741/* There is only one instance of the array, which is the following */
4742static struct s_x3 *x3a;
4743
4744/* Allocate a new associative array */
4745void State_init(){
4746 if( x3a ) return;
4747 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4748 if( x3a ){
4749 x3a->size = 128;
4750 x3a->count = 0;
4751 x3a->tbl = (x3node*)malloc(
4752 (sizeof(x3node) + sizeof(x3node*))*128 );
4753 if( x3a->tbl==0 ){
4754 free(x3a);
4755 x3a = 0;
4756 }else{
4757 int i;
4758 x3a->ht = (x3node**)&(x3a->tbl[128]);
4759 for(i=0; i<128; i++) x3a->ht[i] = 0;
4760 }
4761 }
4762}
4763/* Insert a new record into the array. Return TRUE if successful.
4764** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004765int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004766{
4767 x3node *np;
4768 int h;
4769 int ph;
4770
4771 if( x3a==0 ) return 0;
4772 ph = statehash(key);
4773 h = ph & (x3a->size-1);
4774 np = x3a->ht[h];
4775 while( np ){
4776 if( statecmp(np->key,key)==0 ){
4777 /* An existing entry with the same key is found. */
4778 /* Fail because overwrite is not allows. */
4779 return 0;
4780 }
4781 np = np->next;
4782 }
4783 if( x3a->count>=x3a->size ){
4784 /* Need to make the hash table bigger */
4785 int i,size;
4786 struct s_x3 array;
4787 array.size = size = x3a->size*2;
4788 array.count = x3a->count;
4789 array.tbl = (x3node*)malloc(
4790 (sizeof(x3node) + sizeof(x3node*))*size );
4791 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4792 array.ht = (x3node**)&(array.tbl[size]);
4793 for(i=0; i<size; i++) array.ht[i] = 0;
4794 for(i=0; i<x3a->count; i++){
4795 x3node *oldnp, *newnp;
4796 oldnp = &(x3a->tbl[i]);
4797 h = statehash(oldnp->key) & (size-1);
4798 newnp = &(array.tbl[i]);
4799 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4800 newnp->next = array.ht[h];
4801 newnp->key = oldnp->key;
4802 newnp->data = oldnp->data;
4803 newnp->from = &(array.ht[h]);
4804 array.ht[h] = newnp;
4805 }
4806 free(x3a->tbl);
4807 *x3a = array;
4808 }
4809 /* Insert the new data */
4810 h = ph & (x3a->size-1);
4811 np = &(x3a->tbl[x3a->count++]);
4812 np->key = key;
4813 np->data = data;
4814 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4815 np->next = x3a->ht[h];
4816 x3a->ht[h] = np;
4817 np->from = &(x3a->ht[h]);
4818 return 1;
4819}
4820
4821/* Return a pointer to data assigned to the given key. Return NULL
4822** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004823struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004824{
4825 int h;
4826 x3node *np;
4827
4828 if( x3a==0 ) return 0;
4829 h = statehash(key) & (x3a->size-1);
4830 np = x3a->ht[h];
4831 while( np ){
4832 if( statecmp(np->key,key)==0 ) break;
4833 np = np->next;
4834 }
4835 return np ? np->data : 0;
4836}
4837
4838/* Return an array of pointers to all data in the table.
4839** The array is obtained from malloc. Return NULL if memory allocation
4840** problems, or if the array is empty. */
4841struct state **State_arrayof()
4842{
4843 struct state **array;
4844 int i,size;
4845 if( x3a==0 ) return 0;
4846 size = x3a->count;
4847 array = (struct state **)malloc( sizeof(struct state *)*size );
4848 if( array ){
4849 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4850 }
4851 return array;
4852}
4853
4854/* Hash a configuration */
icculus9e44cf12010-02-14 17:14:22 +00004855PRIVATE int confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004856{
4857 int h=0;
4858 h = h*571 + a->rp->index*37 + a->dot;
4859 return h;
4860}
4861
4862/* There is one instance of the following structure for each
4863** associative array of type "x4".
4864*/
4865struct s_x4 {
4866 int size; /* The number of available slots. */
4867 /* Must be a power of 2 greater than or */
4868 /* equal to 1 */
4869 int count; /* Number of currently slots filled */
4870 struct s_x4node *tbl; /* The data stored here */
4871 struct s_x4node **ht; /* Hash table for lookups */
4872};
4873
4874/* There is one instance of this structure for every data element
4875** in an associative array of type "x4".
4876*/
4877typedef struct s_x4node {
4878 struct config *data; /* The data */
4879 struct s_x4node *next; /* Next entry with the same hash */
4880 struct s_x4node **from; /* Previous link */
4881} x4node;
4882
4883/* There is only one instance of the array, which is the following */
4884static struct s_x4 *x4a;
4885
4886/* Allocate a new associative array */
4887void Configtable_init(){
4888 if( x4a ) return;
4889 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4890 if( x4a ){
4891 x4a->size = 64;
4892 x4a->count = 0;
4893 x4a->tbl = (x4node*)malloc(
4894 (sizeof(x4node) + sizeof(x4node*))*64 );
4895 if( x4a->tbl==0 ){
4896 free(x4a);
4897 x4a = 0;
4898 }else{
4899 int i;
4900 x4a->ht = (x4node**)&(x4a->tbl[64]);
4901 for(i=0; i<64; i++) x4a->ht[i] = 0;
4902 }
4903 }
4904}
4905/* Insert a new record into the array. Return TRUE if successful.
4906** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004907int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00004908{
4909 x4node *np;
4910 int h;
4911 int ph;
4912
4913 if( x4a==0 ) return 0;
4914 ph = confighash(data);
4915 h = ph & (x4a->size-1);
4916 np = x4a->ht[h];
4917 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004918 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00004919 /* An existing entry with the same key is found. */
4920 /* Fail because overwrite is not allows. */
4921 return 0;
4922 }
4923 np = np->next;
4924 }
4925 if( x4a->count>=x4a->size ){
4926 /* Need to make the hash table bigger */
4927 int i,size;
4928 struct s_x4 array;
4929 array.size = size = x4a->size*2;
4930 array.count = x4a->count;
4931 array.tbl = (x4node*)malloc(
4932 (sizeof(x4node) + sizeof(x4node*))*size );
4933 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4934 array.ht = (x4node**)&(array.tbl[size]);
4935 for(i=0; i<size; i++) array.ht[i] = 0;
4936 for(i=0; i<x4a->count; i++){
4937 x4node *oldnp, *newnp;
4938 oldnp = &(x4a->tbl[i]);
4939 h = confighash(oldnp->data) & (size-1);
4940 newnp = &(array.tbl[i]);
4941 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4942 newnp->next = array.ht[h];
4943 newnp->data = oldnp->data;
4944 newnp->from = &(array.ht[h]);
4945 array.ht[h] = newnp;
4946 }
4947 free(x4a->tbl);
4948 *x4a = array;
4949 }
4950 /* Insert the new data */
4951 h = ph & (x4a->size-1);
4952 np = &(x4a->tbl[x4a->count++]);
4953 np->data = data;
4954 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4955 np->next = x4a->ht[h];
4956 x4a->ht[h] = np;
4957 np->from = &(x4a->ht[h]);
4958 return 1;
4959}
4960
4961/* Return a pointer to data assigned to the given key. Return NULL
4962** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004963struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004964{
4965 int h;
4966 x4node *np;
4967
4968 if( x4a==0 ) return 0;
4969 h = confighash(key) & (x4a->size-1);
4970 np = x4a->ht[h];
4971 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004972 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00004973 np = np->next;
4974 }
4975 return np ? np->data : 0;
4976}
4977
4978/* Remove all data from the table. Pass each data to the function "f"
4979** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00004980void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00004981{
4982 int i;
4983 if( x4a==0 || x4a->count==0 ) return;
4984 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4985 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4986 x4a->count = 0;
4987 return;
4988}