blob: 0eb6f025daa69feddcc10375c78754218a278d6a [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
drhf9a2e7b2003-04-15 01:49:48 +00001343void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001344 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001345 fprintf(stderr, "%s:%d: ", filename, lineno);
1346 va_start(ap, format);
1347 vfprintf(stderr,format,ap);
1348 va_end(ap);
1349 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001350}
1351/**************** From the file "main.c" ************************************/
1352/*
1353** Main program file for the LEMON parser generator.
1354*/
1355
1356/* Report an out-of-memory condition and abort. This function
1357** is used mostly by the "MemoryCheck" macro in struct.h
1358*/
1359void memory_error(){
1360 fprintf(stderr,"Out of memory. Aborting...\n");
1361 exit(1);
1362}
1363
drh6d08b4d2004-07-20 12:45:22 +00001364static int nDefine = 0; /* Number of -D options on the command line */
1365static char **azDefine = 0; /* Name of the -D macros */
1366
1367/* This routine is called with the argument to each -D command-line option.
1368** Add the macro defined to the azDefine array.
1369*/
1370static void handle_D_option(char *z){
1371 char **paz;
1372 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001373 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001374 if( azDefine==0 ){
1375 fprintf(stderr,"out of memory\n");
1376 exit(1);
1377 }
1378 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001379 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001380 if( *paz==0 ){
1381 fprintf(stderr,"out of memory\n");
1382 exit(1);
1383 }
1384 strcpy(*paz, z);
1385 for(z=*paz; *z && *z!='='; z++){}
1386 *z = 0;
1387}
1388
icculus3e143bd2010-02-14 00:48:49 +00001389static char *user_templatename = NULL;
1390static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001391 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001392 if( user_templatename==0 ){
1393 memory_error();
1394 }
1395 strcpy(user_templatename, z);
1396}
drh75897232000-05-29 14:26:00 +00001397
1398/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001399int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001400{
1401 static int version = 0;
1402 static int rpflag = 0;
1403 static int basisflag = 0;
1404 static int compress = 0;
1405 static int quiet = 0;
1406 static int statistics = 0;
1407 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001408 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001409 static struct s_options options[] = {
1410 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1411 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001412 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001413 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001414 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001415 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1416 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001417 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001418 {OPT_FLAG, "s", (char*)&statistics,
1419 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001420 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1421 {OPT_FLAG,0,0,0}
1422 };
1423 int i;
icculus42585cf2010-02-14 05:19:56 +00001424 int exitcode;
drh75897232000-05-29 14:26:00 +00001425 struct lemon lem;
1426
icculusf5ad8242010-02-14 05:34:42 +00001427 atexit(LemonAtExit);
1428
drhb0c86772000-06-02 23:21:26 +00001429 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001430 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001431 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001432 exit(0);
1433 }
drhb0c86772000-06-02 23:21:26 +00001434 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001435 fprintf(stderr,"Exactly one filename argument is required.\n");
1436 exit(1);
1437 }
drh954f6b42006-06-13 13:27:46 +00001438 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001439 lem.errorcnt = 0;
icculus42585cf2010-02-14 05:19:56 +00001440 lem.nexpected = -1;
drh75897232000-05-29 14:26:00 +00001441
1442 /* Initialize the machine */
1443 Strsafe_init();
1444 Symbol_init();
1445 State_init();
1446 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001447 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001448 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001449 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001450 Symbol_new("$");
1451 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001452 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001453
1454 /* Parse the input file */
1455 Parse(&lem);
1456 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001457 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001458 fprintf(stderr,"Empty grammar.\n");
1459 exit(1);
1460 }
1461
1462 /* Count and index the symbols of the grammar */
1463 lem.nsymbol = Symbol_count();
1464 Symbol_new("{default}");
1465 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001466 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
icculus9e44cf12010-02-14 17:14:22 +00001467 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp);
drh75897232000-05-29 14:26:00 +00001468 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1469 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1470 lem.nterminal = i;
1471
1472 /* Generate a reprint of the grammar, if requested on the command line */
1473 if( rpflag ){
1474 Reprint(&lem);
1475 }else{
1476 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001477 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001478
1479 /* Find the precedence for every production rule (that has one) */
1480 FindRulePrecedences(&lem);
1481
1482 /* Compute the lambda-nonterminals and the first-sets for every
1483 ** nonterminal */
1484 FindFirstSets(&lem);
1485
1486 /* Compute all LR(0) states. Also record follow-set propagation
1487 ** links so that the follow-set can be computed later */
1488 lem.nstate = 0;
1489 FindStates(&lem);
1490 lem.sorted = State_arrayof();
1491
1492 /* Tie up loose ends on the propagation links */
1493 FindLinks(&lem);
1494
1495 /* Compute the follow set of every reducible configuration */
1496 FindFollowSets(&lem);
1497
1498 /* Compute the action tables */
1499 FindActions(&lem);
1500
1501 /* Compress the action tables */
1502 if( compress==0 ) CompressTables(&lem);
1503
drhada354d2005-11-05 15:03:59 +00001504 /* Reorder and renumber the states so that states with fewer choices
1505 ** occur at the end. */
1506 ResortStates(&lem);
1507
drh75897232000-05-29 14:26:00 +00001508 /* Generate a report of the parser generated. (the "y.output" file) */
1509 if( !quiet ) ReportOutput(&lem);
1510
1511 /* Generate the source code for the parser */
1512 ReportTable(&lem, mhflag);
1513
1514 /* Produce a header file for use by the scanner. (This step is
1515 ** omitted if the "-m" option is used because makeheaders will
1516 ** generate the file for us.) */
1517 if( !mhflag ) ReportHeader(&lem);
1518 }
1519 if( statistics ){
1520 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1521 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1522 printf(" %d states, %d parser table entries, %d conflicts\n",
1523 lem.nstate, lem.tablesize, lem.nconflict);
1524 }
icculus42585cf2010-02-14 05:19:56 +00001525 if( lem.nexpected < 0 ) {
1526 lem.nexpected = 0; /* grammar didn't have an %expect declaration. */
drh75897232000-05-29 14:26:00 +00001527 }
icculus42585cf2010-02-14 05:19:56 +00001528 if( lem.nconflict != lem.nexpected ){
1529 fprintf(stderr,"%d parsing conflicts (%d expected).\n",lem.nconflict,lem.nexpected);
1530 }
1531
1532 /* return 0 on success, 1 on failure. */
1533 exitcode = ((lem.errorcnt > 0) || (lem.nconflict != lem.nexpected)) ? 1 : 0;
icculusf5ad8242010-02-14 05:34:42 +00001534 successful_exit = (exitcode == 0);
icculus42585cf2010-02-14 05:19:56 +00001535 exit(exitcode);
1536 return (exitcode);
drh75897232000-05-29 14:26:00 +00001537}
1538/******************** From the file "msort.c" *******************************/
1539/*
1540** A generic merge-sort program.
1541**
1542** USAGE:
1543** Let "ptr" be a pointer to some structure which is at the head of
1544** a null-terminated list. Then to sort the list call:
1545**
1546** ptr = msort(ptr,&(ptr->next),cmpfnc);
1547**
1548** In the above, "cmpfnc" is a pointer to a function which compares
1549** two instances of the structure and returns an integer, as in
1550** strcmp. The second argument is a pointer to the pointer to the
1551** second element of the linked list. This address is used to compute
1552** the offset to the "next" field within the structure. The offset to
1553** the "next" field must be constant for all structures in the list.
1554**
1555** The function returns a new pointer which is the head of the list
1556** after sorting.
1557**
1558** ALGORITHM:
1559** Merge-sort.
1560*/
1561
1562/*
1563** Return a pointer to the next structure in the linked list.
1564*/
drhba99af52001-10-25 20:37:16 +00001565#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001566
1567/*
1568** Inputs:
1569** a: A sorted, null-terminated linked list. (May be null).
1570** b: A sorted, null-terminated linked list. (May be null).
1571** cmp: A pointer to the comparison function.
1572** offset: Offset in the structure to the "next" field.
1573**
1574** Return Value:
1575** A pointer to the head of a sorted list containing the elements
1576** of both a and b.
1577**
1578** Side effects:
1579** The "next" pointers for elements in the lists a and b are
1580** changed.
1581*/
drhe9278182007-07-18 18:16:29 +00001582static char *merge(
1583 char *a,
1584 char *b,
1585 int (*cmp)(const char*,const char*),
1586 int offset
1587){
drh75897232000-05-29 14:26:00 +00001588 char *ptr, *head;
1589
1590 if( a==0 ){
1591 head = b;
1592 }else if( b==0 ){
1593 head = a;
1594 }else{
drhe594bc32009-11-03 13:02:25 +00001595 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001596 ptr = a;
1597 a = NEXT(a);
1598 }else{
1599 ptr = b;
1600 b = NEXT(b);
1601 }
1602 head = ptr;
1603 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001604 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001605 NEXT(ptr) = a;
1606 ptr = a;
1607 a = NEXT(a);
1608 }else{
1609 NEXT(ptr) = b;
1610 ptr = b;
1611 b = NEXT(b);
1612 }
1613 }
1614 if( a ) NEXT(ptr) = a;
1615 else NEXT(ptr) = b;
1616 }
1617 return head;
1618}
1619
1620/*
1621** Inputs:
1622** list: Pointer to a singly-linked list of structures.
1623** next: Pointer to pointer to the second element of the list.
1624** cmp: A comparison function.
1625**
1626** Return Value:
1627** A pointer to the head of a sorted list containing the elements
1628** orginally in list.
1629**
1630** Side effects:
1631** The "next" pointers for elements in list are changed.
1632*/
1633#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001634static char *msort(
1635 char *list,
1636 char **next,
1637 int (*cmp)(const char*,const char*)
1638){
drhba99af52001-10-25 20:37:16 +00001639 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001640 char *ep;
1641 char *set[LISTSIZE];
1642 int i;
drhba99af52001-10-25 20:37:16 +00001643 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001644 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1645 while( list ){
1646 ep = list;
1647 list = NEXT(list);
1648 NEXT(ep) = 0;
1649 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1650 ep = merge(ep,set[i],cmp,offset);
1651 set[i] = 0;
1652 }
1653 set[i] = ep;
1654 }
1655 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001656 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001657 return ep;
1658}
1659/************************ From the file "option.c" **************************/
1660static char **argv;
1661static struct s_options *op;
1662static FILE *errstream;
1663
1664#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1665
1666/*
1667** Print the command line with a carrot pointing to the k-th character
1668** of the n-th field.
1669*/
icculus9e44cf12010-02-14 17:14:22 +00001670static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001671{
1672 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001673 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001674 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001675 for(i=1; i<n && argv[i]; i++){
1676 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001677 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001678 }
1679 spcnt += k;
1680 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1681 if( spcnt<20 ){
1682 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1683 }else{
1684 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1685 }
1686}
1687
1688/*
1689** Return the index of the N-th non-switch argument. Return -1
1690** if N is out of range.
1691*/
icculus9e44cf12010-02-14 17:14:22 +00001692static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001693{
1694 int i;
1695 int dashdash = 0;
1696 if( argv!=0 && *argv!=0 ){
1697 for(i=1; argv[i]; i++){
1698 if( dashdash || !ISOPT(argv[i]) ){
1699 if( n==0 ) return i;
1700 n--;
1701 }
1702 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1703 }
1704 }
1705 return -1;
1706}
1707
1708static char emsg[] = "Command line syntax error: ";
1709
1710/*
1711** Process a flag command line argument.
1712*/
icculus9e44cf12010-02-14 17:14:22 +00001713static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001714{
1715 int v;
1716 int errcnt = 0;
1717 int j;
1718 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001719 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001720 }
1721 v = argv[i][0]=='-' ? 1 : 0;
1722 if( op[j].label==0 ){
1723 if( err ){
1724 fprintf(err,"%sundefined option.\n",emsg);
1725 errline(i,1,err);
1726 }
1727 errcnt++;
1728 }else if( op[j].type==OPT_FLAG ){
1729 *((int*)op[j].arg) = v;
1730 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001731 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001732 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001733 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001734 }else{
1735 if( err ){
1736 fprintf(err,"%smissing argument on switch.\n",emsg);
1737 errline(i,1,err);
1738 }
1739 errcnt++;
1740 }
1741 return errcnt;
1742}
1743
1744/*
1745** Process a command line switch which has an argument.
1746*/
icculus9e44cf12010-02-14 17:14:22 +00001747static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001748{
1749 int lv = 0;
1750 double dv = 0.0;
1751 char *sv = 0, *end;
1752 char *cp;
1753 int j;
1754 int errcnt = 0;
1755 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001756 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001757 *cp = 0;
1758 for(j=0; op[j].label; j++){
1759 if( strcmp(argv[i],op[j].label)==0 ) break;
1760 }
1761 *cp = '=';
1762 if( op[j].label==0 ){
1763 if( err ){
1764 fprintf(err,"%sundefined option.\n",emsg);
1765 errline(i,0,err);
1766 }
1767 errcnt++;
1768 }else{
1769 cp++;
1770 switch( op[j].type ){
1771 case OPT_FLAG:
1772 case OPT_FFLAG:
1773 if( err ){
1774 fprintf(err,"%soption requires an argument.\n",emsg);
1775 errline(i,0,err);
1776 }
1777 errcnt++;
1778 break;
1779 case OPT_DBL:
1780 case OPT_FDBL:
1781 dv = strtod(cp,&end);
1782 if( *end ){
1783 if( err ){
1784 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001785 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001786 }
1787 errcnt++;
1788 }
1789 break;
1790 case OPT_INT:
1791 case OPT_FINT:
1792 lv = strtol(cp,&end,0);
1793 if( *end ){
1794 if( err ){
1795 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001796 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001797 }
1798 errcnt++;
1799 }
1800 break;
1801 case OPT_STR:
1802 case OPT_FSTR:
1803 sv = cp;
1804 break;
1805 }
1806 switch( op[j].type ){
1807 case OPT_FLAG:
1808 case OPT_FFLAG:
1809 break;
1810 case OPT_DBL:
1811 *(double*)(op[j].arg) = dv;
1812 break;
1813 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001814 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001815 break;
1816 case OPT_INT:
1817 *(int*)(op[j].arg) = lv;
1818 break;
1819 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001820 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001821 break;
1822 case OPT_STR:
1823 *(char**)(op[j].arg) = sv;
1824 break;
1825 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001826 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001827 break;
1828 }
1829 }
1830 return errcnt;
1831}
1832
icculus9e44cf12010-02-14 17:14:22 +00001833int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001834{
1835 int errcnt = 0;
1836 argv = a;
1837 op = o;
1838 errstream = err;
1839 if( argv && *argv && op ){
1840 int i;
1841 for(i=1; argv[i]; i++){
1842 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1843 errcnt += handleflags(i,err);
1844 }else if( strchr(argv[i],'=') ){
1845 errcnt += handleswitch(i,err);
1846 }
1847 }
1848 }
1849 if( errcnt>0 ){
1850 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001851 OptPrint();
drh75897232000-05-29 14:26:00 +00001852 exit(1);
1853 }
1854 return 0;
1855}
1856
drhb0c86772000-06-02 23:21:26 +00001857int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001858 int cnt = 0;
1859 int dashdash = 0;
1860 int i;
1861 if( argv!=0 && argv[0]!=0 ){
1862 for(i=1; argv[i]; i++){
1863 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1864 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1865 }
1866 }
1867 return cnt;
1868}
1869
icculus9e44cf12010-02-14 17:14:22 +00001870char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001871{
1872 int i;
1873 i = argindex(n);
1874 return i>=0 ? argv[i] : 0;
1875}
1876
icculus9e44cf12010-02-14 17:14:22 +00001877void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001878{
1879 int i;
1880 i = argindex(n);
1881 if( i>=0 ) errline(i,0,errstream);
1882}
1883
drhb0c86772000-06-02 23:21:26 +00001884void OptPrint(){
drh75897232000-05-29 14:26:00 +00001885 int i;
1886 int max, len;
1887 max = 0;
1888 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001889 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001890 switch( op[i].type ){
1891 case OPT_FLAG:
1892 case OPT_FFLAG:
1893 break;
1894 case OPT_INT:
1895 case OPT_FINT:
1896 len += 9; /* length of "<integer>" */
1897 break;
1898 case OPT_DBL:
1899 case OPT_FDBL:
1900 len += 6; /* length of "<real>" */
1901 break;
1902 case OPT_STR:
1903 case OPT_FSTR:
1904 len += 8; /* length of "<string>" */
1905 break;
1906 }
1907 if( len>max ) max = len;
1908 }
1909 for(i=0; op[i].label; i++){
1910 switch( op[i].type ){
1911 case OPT_FLAG:
1912 case OPT_FFLAG:
1913 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1914 break;
1915 case OPT_INT:
1916 case OPT_FINT:
1917 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001918 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001919 break;
1920 case OPT_DBL:
1921 case OPT_FDBL:
1922 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001923 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001924 break;
1925 case OPT_STR:
1926 case OPT_FSTR:
1927 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001928 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001929 break;
1930 }
1931 }
1932}
1933/*********************** From the file "parse.c" ****************************/
1934/*
1935** Input file parser for the LEMON parser generator.
1936*/
1937
1938/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00001939enum e_state {
1940 INITIALIZE,
1941 WAITING_FOR_DECL_OR_RULE,
1942 WAITING_FOR_DECL_KEYWORD,
1943 WAITING_FOR_DECL_ARG,
1944 WAITING_FOR_PRECEDENCE_SYMBOL,
1945 WAITING_FOR_ARROW,
1946 IN_RHS,
1947 LHS_ALIAS_1,
1948 LHS_ALIAS_2,
1949 LHS_ALIAS_3,
1950 RHS_ALIAS_1,
1951 RHS_ALIAS_2,
1952 PRECEDENCE_MARK_1,
1953 PRECEDENCE_MARK_2,
1954 RESYNC_AFTER_RULE_ERROR,
1955 RESYNC_AFTER_DECL_ERROR,
1956 WAITING_FOR_DESTRUCTOR_SYMBOL,
1957 WAITING_FOR_DATATYPE_SYMBOL,
1958 WAITING_FOR_FALLBACK_ID,
1959 WAITING_FOR_EXPECT_VALUE,
1960 WAITING_FOR_WILDCARD_ID
1961};
drh75897232000-05-29 14:26:00 +00001962struct pstate {
1963 char *filename; /* Name of the input file */
1964 int tokenlineno; /* Linenumber at which current token starts */
1965 int errorcnt; /* Number of errors so far */
1966 char *tokenstart; /* Text of current token */
1967 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00001968 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001969 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001970 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00001971 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00001972 int nrhs; /* Number of right-hand side symbols seen */
1973 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00001974 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00001975 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00001976 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00001977 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001978 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001979 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001980 enum e_assoc declassoc; /* Assign this association to decl arguments */
1981 int preccounter; /* Assign this precedence to decl arguments */
1982 struct rule *firstrule; /* Pointer to first rule in the grammar */
1983 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1984};
1985
1986/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00001987static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00001988{
icculus42585cf2010-02-14 05:19:56 +00001989 char *endptr;
icculus9e44cf12010-02-14 17:14:22 +00001990 const char *x;
drh75897232000-05-29 14:26:00 +00001991 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1992#if 0
1993 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1994 x,psp->state);
1995#endif
1996 switch( psp->state ){
1997 case INITIALIZE:
1998 psp->prevrule = 0;
1999 psp->preccounter = 0;
2000 psp->firstrule = psp->lastrule = 0;
2001 psp->gp->nrule = 0;
2002 /* Fall thru to next case */
2003 case WAITING_FOR_DECL_OR_RULE:
2004 if( x[0]=='%' ){
2005 psp->state = WAITING_FOR_DECL_KEYWORD;
2006 }else if( islower(x[0]) ){
2007 psp->lhs = Symbol_new(x);
2008 psp->nrhs = 0;
2009 psp->lhsalias = 0;
2010 psp->state = WAITING_FOR_ARROW;
2011 }else if( x[0]=='{' ){
2012 if( psp->prevrule==0 ){
2013 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002014"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002015fragment which begins on this line.");
2016 psp->errorcnt++;
2017 }else if( psp->prevrule->code!=0 ){
2018 ErrorMsg(psp->filename,psp->tokenlineno,
2019"Code fragment beginning on this line is not the first \
2020to follow the previous rule.");
2021 psp->errorcnt++;
2022 }else{
2023 psp->prevrule->line = psp->tokenlineno;
2024 psp->prevrule->code = &x[1];
2025 }
2026 }else if( x[0]=='[' ){
2027 psp->state = PRECEDENCE_MARK_1;
2028 }else{
2029 ErrorMsg(psp->filename,psp->tokenlineno,
2030 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2031 x);
2032 psp->errorcnt++;
2033 }
2034 break;
2035 case PRECEDENCE_MARK_1:
2036 if( !isupper(x[0]) ){
2037 ErrorMsg(psp->filename,psp->tokenlineno,
2038 "The precedence symbol must be a terminal.");
2039 psp->errorcnt++;
2040 }else if( psp->prevrule==0 ){
2041 ErrorMsg(psp->filename,psp->tokenlineno,
2042 "There is no prior rule to assign precedence \"[%s]\".",x);
2043 psp->errorcnt++;
2044 }else if( psp->prevrule->precsym!=0 ){
2045 ErrorMsg(psp->filename,psp->tokenlineno,
2046"Precedence mark on this line is not the first \
2047to follow the previous rule.");
2048 psp->errorcnt++;
2049 }else{
2050 psp->prevrule->precsym = Symbol_new(x);
2051 }
2052 psp->state = PRECEDENCE_MARK_2;
2053 break;
2054 case PRECEDENCE_MARK_2:
2055 if( x[0]!=']' ){
2056 ErrorMsg(psp->filename,psp->tokenlineno,
2057 "Missing \"]\" on precedence mark.");
2058 psp->errorcnt++;
2059 }
2060 psp->state = WAITING_FOR_DECL_OR_RULE;
2061 break;
2062 case WAITING_FOR_ARROW:
2063 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2064 psp->state = IN_RHS;
2065 }else if( x[0]=='(' ){
2066 psp->state = LHS_ALIAS_1;
2067 }else{
2068 ErrorMsg(psp->filename,psp->tokenlineno,
2069 "Expected to see a \":\" following the LHS symbol \"%s\".",
2070 psp->lhs->name);
2071 psp->errorcnt++;
2072 psp->state = RESYNC_AFTER_RULE_ERROR;
2073 }
2074 break;
2075 case LHS_ALIAS_1:
2076 if( isalpha(x[0]) ){
2077 psp->lhsalias = x;
2078 psp->state = LHS_ALIAS_2;
2079 }else{
2080 ErrorMsg(psp->filename,psp->tokenlineno,
2081 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2082 x,psp->lhs->name);
2083 psp->errorcnt++;
2084 psp->state = RESYNC_AFTER_RULE_ERROR;
2085 }
2086 break;
2087 case LHS_ALIAS_2:
2088 if( x[0]==')' ){
2089 psp->state = LHS_ALIAS_3;
2090 }else{
2091 ErrorMsg(psp->filename,psp->tokenlineno,
2092 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2093 psp->errorcnt++;
2094 psp->state = RESYNC_AFTER_RULE_ERROR;
2095 }
2096 break;
2097 case LHS_ALIAS_3:
2098 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2099 psp->state = IN_RHS;
2100 }else{
2101 ErrorMsg(psp->filename,psp->tokenlineno,
2102 "Missing \"->\" following: \"%s(%s)\".",
2103 psp->lhs->name,psp->lhsalias);
2104 psp->errorcnt++;
2105 psp->state = RESYNC_AFTER_RULE_ERROR;
2106 }
2107 break;
2108 case IN_RHS:
2109 if( x[0]=='.' ){
2110 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002111 rp = (struct rule *)calloc( sizeof(struct rule) +
2112 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002113 if( rp==0 ){
2114 ErrorMsg(psp->filename,psp->tokenlineno,
2115 "Can't allocate enough memory for this rule.");
2116 psp->errorcnt++;
2117 psp->prevrule = 0;
2118 }else{
2119 int i;
2120 rp->ruleline = psp->tokenlineno;
2121 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002122 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002123 for(i=0; i<psp->nrhs; i++){
2124 rp->rhs[i] = psp->rhs[i];
2125 rp->rhsalias[i] = psp->alias[i];
2126 }
2127 rp->lhs = psp->lhs;
2128 rp->lhsalias = psp->lhsalias;
2129 rp->nrhs = psp->nrhs;
2130 rp->code = 0;
2131 rp->precsym = 0;
2132 rp->index = psp->gp->nrule++;
2133 rp->nextlhs = rp->lhs->rule;
2134 rp->lhs->rule = rp;
2135 rp->next = 0;
2136 if( psp->firstrule==0 ){
2137 psp->firstrule = psp->lastrule = rp;
2138 }else{
2139 psp->lastrule->next = rp;
2140 psp->lastrule = rp;
2141 }
2142 psp->prevrule = rp;
2143 }
2144 psp->state = WAITING_FOR_DECL_OR_RULE;
2145 }else if( isalpha(x[0]) ){
2146 if( psp->nrhs>=MAXRHS ){
2147 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002148 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002149 x);
2150 psp->errorcnt++;
2151 psp->state = RESYNC_AFTER_RULE_ERROR;
2152 }else{
2153 psp->rhs[psp->nrhs] = Symbol_new(x);
2154 psp->alias[psp->nrhs] = 0;
2155 psp->nrhs++;
2156 }
drhfd405312005-11-06 04:06:59 +00002157 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2158 struct symbol *msp = psp->rhs[psp->nrhs-1];
2159 if( msp->type!=MULTITERMINAL ){
2160 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002161 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002162 memset(msp, 0, sizeof(*msp));
2163 msp->type = MULTITERMINAL;
2164 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002165 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002166 msp->subsym[0] = origsp;
2167 msp->name = origsp->name;
2168 psp->rhs[psp->nrhs-1] = msp;
2169 }
2170 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002171 msp->subsym = (struct symbol **) realloc(msp->subsym,
2172 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002173 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2174 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2175 ErrorMsg(psp->filename,psp->tokenlineno,
2176 "Cannot form a compound containing a non-terminal");
2177 psp->errorcnt++;
2178 }
drh75897232000-05-29 14:26:00 +00002179 }else if( x[0]=='(' && psp->nrhs>0 ){
2180 psp->state = RHS_ALIAS_1;
2181 }else{
2182 ErrorMsg(psp->filename,psp->tokenlineno,
2183 "Illegal character on RHS of rule: \"%s\".",x);
2184 psp->errorcnt++;
2185 psp->state = RESYNC_AFTER_RULE_ERROR;
2186 }
2187 break;
2188 case RHS_ALIAS_1:
2189 if( isalpha(x[0]) ){
2190 psp->alias[psp->nrhs-1] = x;
2191 psp->state = RHS_ALIAS_2;
2192 }else{
2193 ErrorMsg(psp->filename,psp->tokenlineno,
2194 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2195 x,psp->rhs[psp->nrhs-1]->name);
2196 psp->errorcnt++;
2197 psp->state = RESYNC_AFTER_RULE_ERROR;
2198 }
2199 break;
2200 case RHS_ALIAS_2:
2201 if( x[0]==')' ){
2202 psp->state = IN_RHS;
2203 }else{
2204 ErrorMsg(psp->filename,psp->tokenlineno,
2205 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2206 psp->errorcnt++;
2207 psp->state = RESYNC_AFTER_RULE_ERROR;
2208 }
2209 break;
2210 case WAITING_FOR_DECL_KEYWORD:
2211 if( isalpha(x[0]) ){
2212 psp->declkeyword = x;
2213 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002214 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002215 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002216 psp->state = WAITING_FOR_DECL_ARG;
2217 if( strcmp(x,"name")==0 ){
2218 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002219 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002220 }else if( strcmp(x,"include")==0 ){
2221 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002222 }else if( strcmp(x,"code")==0 ){
2223 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002224 }else if( strcmp(x,"token_destructor")==0 ){
2225 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002226 }else if( strcmp(x,"default_destructor")==0 ){
2227 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002228 }else if( strcmp(x,"token_prefix")==0 ){
2229 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002230 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002231 }else if( strcmp(x,"syntax_error")==0 ){
2232 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002233 }else if( strcmp(x,"parse_accept")==0 ){
2234 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002235 }else if( strcmp(x,"parse_failure")==0 ){
2236 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002237 }else if( strcmp(x,"stack_overflow")==0 ){
2238 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002239 }else if( strcmp(x,"extra_argument")==0 ){
2240 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002241 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002242 }else if( strcmp(x,"token_type")==0 ){
2243 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002244 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002245 }else if( strcmp(x,"default_type")==0 ){
2246 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002247 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002248 }else if( strcmp(x,"stack_size")==0 ){
2249 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002250 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002251 }else if( strcmp(x,"start_symbol")==0 ){
2252 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002253 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002254 }else if( strcmp(x,"left")==0 ){
2255 psp->preccounter++;
2256 psp->declassoc = LEFT;
2257 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2258 }else if( strcmp(x,"right")==0 ){
2259 psp->preccounter++;
2260 psp->declassoc = RIGHT;
2261 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2262 }else if( strcmp(x,"nonassoc")==0 ){
2263 psp->preccounter++;
2264 psp->declassoc = NONE;
2265 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2266 }else if( strcmp(x,"destructor")==0 ){
2267 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2268 }else if( strcmp(x,"type")==0 ){
2269 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002270 }else if( strcmp(x,"fallback")==0 ){
2271 psp->fallback = 0;
2272 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002273 }else if( strcmp(x,"wildcard")==0 ){
2274 psp->state = WAITING_FOR_WILDCARD_ID;
icculus42585cf2010-02-14 05:19:56 +00002275 }else if( strcmp(x,"expect")==0 ){
2276 if (psp->gp->nexpected >= 0) {
2277 ErrorMsg(psp->filename,psp->tokenlineno, "Multiple %expect declarations.");
2278 psp->errorcnt++;
2279 psp->state = RESYNC_AFTER_DECL_ERROR;
2280 } else {
2281 psp->state = WAITING_FOR_EXPECT_VALUE;
2282 }
drh75897232000-05-29 14:26:00 +00002283 }else{
2284 ErrorMsg(psp->filename,psp->tokenlineno,
2285 "Unknown declaration keyword: \"%%%s\".",x);
2286 psp->errorcnt++;
2287 psp->state = RESYNC_AFTER_DECL_ERROR;
2288 }
2289 }else{
2290 ErrorMsg(psp->filename,psp->tokenlineno,
2291 "Illegal declaration keyword: \"%s\".",x);
2292 psp->errorcnt++;
2293 psp->state = RESYNC_AFTER_DECL_ERROR;
2294 }
2295 break;
2296 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2297 if( !isalpha(x[0]) ){
2298 ErrorMsg(psp->filename,psp->tokenlineno,
2299 "Symbol name missing after %destructor keyword");
2300 psp->errorcnt++;
2301 psp->state = RESYNC_AFTER_DECL_ERROR;
2302 }else{
2303 struct symbol *sp = Symbol_new(x);
2304 psp->declargslot = &sp->destructor;
drh4dc8ef52008-07-01 17:13:57 +00002305 psp->decllinenoslot = &sp->destLineno;
drha5808f32008-04-27 22:19:44 +00002306 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002307 psp->state = WAITING_FOR_DECL_ARG;
2308 }
2309 break;
icculus42585cf2010-02-14 05:19:56 +00002310 case WAITING_FOR_EXPECT_VALUE:
2311 psp->gp->nexpected = (int) strtol(x, &endptr, 10);
2312 if( (*endptr != '\0') || (endptr == x) ) {
2313 ErrorMsg(psp->filename,psp->tokenlineno,
2314 "Integer expected after %%expect keyword");
2315 psp->errorcnt++;
2316 } else if (psp->gp->nexpected < 0) {
2317 ErrorMsg(psp->filename,psp->tokenlineno,
2318 "Integer can't be negative after %%expect keyword");
2319 psp->errorcnt++;
2320 }
2321 psp->state = WAITING_FOR_DECL_OR_RULE;
2322 break;
drh75897232000-05-29 14:26:00 +00002323 case WAITING_FOR_DATATYPE_SYMBOL:
2324 if( !isalpha(x[0]) ){
2325 ErrorMsg(psp->filename,psp->tokenlineno,
2326 "Symbol name missing after %destructor keyword");
2327 psp->errorcnt++;
2328 psp->state = RESYNC_AFTER_DECL_ERROR;
2329 }else{
2330 struct symbol *sp = Symbol_new(x);
2331 psp->declargslot = &sp->datatype;
drha5808f32008-04-27 22:19:44 +00002332 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002333 psp->state = WAITING_FOR_DECL_ARG;
2334 }
2335 break;
2336 case WAITING_FOR_PRECEDENCE_SYMBOL:
2337 if( x[0]=='.' ){
2338 psp->state = WAITING_FOR_DECL_OR_RULE;
2339 }else if( isupper(x[0]) ){
2340 struct symbol *sp;
2341 sp = Symbol_new(x);
2342 if( sp->prec>=0 ){
2343 ErrorMsg(psp->filename,psp->tokenlineno,
2344 "Symbol \"%s\" has already be given a precedence.",x);
2345 psp->errorcnt++;
2346 }else{
2347 sp->prec = psp->preccounter;
2348 sp->assoc = psp->declassoc;
2349 }
2350 }else{
2351 ErrorMsg(psp->filename,psp->tokenlineno,
2352 "Can't assign a precedence to \"%s\".",x);
2353 psp->errorcnt++;
2354 }
2355 break;
2356 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002357 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002358 const char *zOld, *zNew;
2359 char *zBuf, *z;
drha5808f32008-04-27 22:19:44 +00002360 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002361 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002362 char zLine[50];
2363 zNew = x;
2364 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002365 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002366 if( *psp->declargslot ){
2367 zOld = *psp->declargslot;
2368 }else{
2369 zOld = "";
2370 }
drh87cf1372008-08-13 20:09:06 +00002371 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002372 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002373 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002374 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2375 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002376 for(z=psp->filename, nBack=0; *z; z++){
2377 if( *z=='\\' ) nBack++;
2378 }
2379 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002380 nLine = lemonStrlen(zLine);
2381 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002382 }
icculus9e44cf12010-02-14 17:14:22 +00002383 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2384 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002385 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002386 if( nOld && zBuf[-1]!='\n' ){
2387 *(zBuf++) = '\n';
2388 }
2389 memcpy(zBuf, zLine, nLine);
2390 zBuf += nLine;
2391 *(zBuf++) = '"';
2392 for(z=psp->filename; *z; z++){
2393 if( *z=='\\' ){
2394 *(zBuf++) = '\\';
2395 }
2396 *(zBuf++) = *z;
2397 }
2398 *(zBuf++) = '"';
2399 *(zBuf++) = '\n';
2400 }
drh4dc8ef52008-07-01 17:13:57 +00002401 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2402 psp->decllinenoslot[0] = psp->tokenlineno;
2403 }
drha5808f32008-04-27 22:19:44 +00002404 memcpy(zBuf, zNew, nNew);
2405 zBuf += nNew;
2406 *zBuf = 0;
2407 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002408 }else{
2409 ErrorMsg(psp->filename,psp->tokenlineno,
2410 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2411 psp->errorcnt++;
2412 psp->state = RESYNC_AFTER_DECL_ERROR;
2413 }
2414 break;
drh0bd1f4e2002-06-06 18:54:39 +00002415 case WAITING_FOR_FALLBACK_ID:
2416 if( x[0]=='.' ){
2417 psp->state = WAITING_FOR_DECL_OR_RULE;
2418 }else if( !isupper(x[0]) ){
2419 ErrorMsg(psp->filename, psp->tokenlineno,
2420 "%%fallback argument \"%s\" should be a token", x);
2421 psp->errorcnt++;
2422 }else{
2423 struct symbol *sp = Symbol_new(x);
2424 if( psp->fallback==0 ){
2425 psp->fallback = sp;
2426 }else if( sp->fallback ){
2427 ErrorMsg(psp->filename, psp->tokenlineno,
2428 "More than one fallback assigned to token %s", x);
2429 psp->errorcnt++;
2430 }else{
2431 sp->fallback = psp->fallback;
2432 psp->gp->has_fallback = 1;
2433 }
2434 }
2435 break;
drhe09daa92006-06-10 13:29:31 +00002436 case WAITING_FOR_WILDCARD_ID:
2437 if( x[0]=='.' ){
2438 psp->state = WAITING_FOR_DECL_OR_RULE;
2439 }else if( !isupper(x[0]) ){
2440 ErrorMsg(psp->filename, psp->tokenlineno,
2441 "%%wildcard argument \"%s\" should be a token", x);
2442 psp->errorcnt++;
2443 }else{
2444 struct symbol *sp = Symbol_new(x);
2445 if( psp->gp->wildcard==0 ){
2446 psp->gp->wildcard = sp;
2447 }else{
2448 ErrorMsg(psp->filename, psp->tokenlineno,
2449 "Extra wildcard to token: %s", x);
2450 psp->errorcnt++;
2451 }
2452 }
2453 break;
drh75897232000-05-29 14:26:00 +00002454 case RESYNC_AFTER_RULE_ERROR:
2455/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2456** break; */
2457 case RESYNC_AFTER_DECL_ERROR:
2458 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2459 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2460 break;
2461 }
2462}
2463
drh34ff57b2008-07-14 12:27:51 +00002464/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002465** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2466** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2467** comments them out. Text in between is also commented out as appropriate.
2468*/
danielk1977940fac92005-01-23 22:41:37 +00002469static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002470 int i, j, k, n;
2471 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002472 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002473 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002474 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002475 for(i=0; z[i]; i++){
2476 if( z[i]=='\n' ) lineno++;
2477 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2478 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2479 if( exclude ){
2480 exclude--;
2481 if( exclude==0 ){
2482 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2483 }
2484 }
2485 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2486 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2487 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2488 if( exclude ){
2489 exclude++;
2490 }else{
2491 for(j=i+7; isspace(z[j]); j++){}
2492 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2493 exclude = 1;
2494 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002495 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002496 exclude = 0;
2497 break;
2498 }
2499 }
2500 if( z[i+3]=='n' ) exclude = !exclude;
2501 if( exclude ){
2502 start = i;
2503 start_lineno = lineno;
2504 }
2505 }
2506 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2507 }
2508 }
2509 if( exclude ){
2510 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2511 exit(1);
2512 }
2513}
2514
drh75897232000-05-29 14:26:00 +00002515/* In spite of its name, this function is really a scanner. It read
2516** in the entire input file (all at once) then tokenizes it. Each
2517** token is passed to the function "parseonetoken" which builds all
2518** the appropriate data structures in the global state vector "gp".
2519*/
icculus9e44cf12010-02-14 17:14:22 +00002520void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002521{
2522 struct pstate ps;
2523 FILE *fp;
2524 char *filebuf;
2525 int filesize;
2526 int lineno;
2527 int c;
2528 char *cp, *nextcp;
2529 int startline = 0;
2530
rse38514a92007-09-20 11:34:17 +00002531 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002532 ps.gp = gp;
2533 ps.filename = gp->filename;
2534 ps.errorcnt = 0;
2535 ps.state = INITIALIZE;
2536
2537 /* Begin by reading the input file */
2538 fp = fopen(ps.filename,"rb");
2539 if( fp==0 ){
2540 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2541 gp->errorcnt++;
2542 return;
2543 }
2544 fseek(fp,0,2);
2545 filesize = ftell(fp);
2546 rewind(fp);
2547 filebuf = (char *)malloc( filesize+1 );
2548 if( filebuf==0 ){
2549 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2550 filesize+1);
2551 gp->errorcnt++;
2552 return;
2553 }
2554 if( fread(filebuf,1,filesize,fp)!=filesize ){
2555 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2556 filesize);
2557 free(filebuf);
2558 gp->errorcnt++;
2559 return;
2560 }
2561 fclose(fp);
2562 filebuf[filesize] = 0;
2563
drh6d08b4d2004-07-20 12:45:22 +00002564 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2565 preprocess_input(filebuf);
2566
drh75897232000-05-29 14:26:00 +00002567 /* Now scan the text of the input file */
2568 lineno = 1;
2569 for(cp=filebuf; (c= *cp)!=0; ){
2570 if( c=='\n' ) lineno++; /* Keep track of the line number */
2571 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2572 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2573 cp+=2;
2574 while( (c= *cp)!=0 && c!='\n' ) cp++;
2575 continue;
2576 }
2577 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2578 cp+=2;
2579 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2580 if( c=='\n' ) lineno++;
2581 cp++;
2582 }
2583 if( c ) cp++;
2584 continue;
2585 }
2586 ps.tokenstart = cp; /* Mark the beginning of the token */
2587 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2588 if( c=='\"' ){ /* String literals */
2589 cp++;
2590 while( (c= *cp)!=0 && c!='\"' ){
2591 if( c=='\n' ) lineno++;
2592 cp++;
2593 }
2594 if( c==0 ){
2595 ErrorMsg(ps.filename,startline,
2596"String starting on this line is not terminated before the end of the file.");
2597 ps.errorcnt++;
2598 nextcp = cp;
2599 }else{
2600 nextcp = cp+1;
2601 }
2602 }else if( c=='{' ){ /* A block of C code */
2603 int level;
2604 cp++;
2605 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2606 if( c=='\n' ) lineno++;
2607 else if( c=='{' ) level++;
2608 else if( c=='}' ) level--;
2609 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2610 int prevc;
2611 cp = &cp[2];
2612 prevc = 0;
2613 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2614 if( c=='\n' ) lineno++;
2615 prevc = c;
2616 cp++;
2617 }
2618 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2619 cp = &cp[2];
2620 while( (c= *cp)!=0 && c!='\n' ) cp++;
2621 if( c ) lineno++;
2622 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2623 int startchar, prevc;
2624 startchar = c;
2625 prevc = 0;
2626 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2627 if( c=='\n' ) lineno++;
2628 if( prevc=='\\' ) prevc = 0;
2629 else prevc = c;
2630 }
2631 }
2632 }
2633 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002634 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002635"C code starting on this line is not terminated before the end of the file.");
2636 ps.errorcnt++;
2637 nextcp = cp;
2638 }else{
2639 nextcp = cp+1;
2640 }
2641 }else if( isalnum(c) ){ /* Identifiers */
2642 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2643 nextcp = cp;
2644 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2645 cp += 3;
2646 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002647 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2648 cp += 2;
2649 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2650 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002651 }else{ /* All other (one character) operators */
2652 cp++;
2653 nextcp = cp;
2654 }
2655 c = *cp;
2656 *cp = 0; /* Null terminate the token */
2657 parseonetoken(&ps); /* Parse the token */
2658 *cp = c; /* Restore the buffer */
2659 cp = nextcp;
2660 }
2661 free(filebuf); /* Release the buffer after parsing */
2662 gp->rule = ps.firstrule;
2663 gp->errorcnt = ps.errorcnt;
2664}
2665/*************************** From the file "plink.c" *********************/
2666/*
2667** Routines processing configuration follow-set propagation links
2668** in the LEMON parser generator.
2669*/
2670static struct plink *plink_freelist = 0;
2671
2672/* Allocate a new plink */
2673struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002674 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002675
2676 if( plink_freelist==0 ){
2677 int i;
2678 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002679 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002680 if( plink_freelist==0 ){
2681 fprintf(stderr,
2682 "Unable to allocate memory for a new follow-set propagation link.\n");
2683 exit(1);
2684 }
2685 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2686 plink_freelist[amt-1].next = 0;
2687 }
icculus9e44cf12010-02-14 17:14:22 +00002688 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002689 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002690 return newlink;
drh75897232000-05-29 14:26:00 +00002691}
2692
2693/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002694void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002695{
icculus9e44cf12010-02-14 17:14:22 +00002696 struct plink *newlink;
2697 newlink = Plink_new();
2698 newlink->next = *plpp;
2699 *plpp = newlink;
2700 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002701}
2702
2703/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002704void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002705{
2706 struct plink *nextpl;
2707 while( from ){
2708 nextpl = from->next;
2709 from->next = *to;
2710 *to = from;
2711 from = nextpl;
2712 }
2713}
2714
2715/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002716void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002717{
2718 struct plink *nextpl;
2719
2720 while( plp ){
2721 nextpl = plp->next;
2722 plp->next = plink_freelist;
2723 plink_freelist = plp;
2724 plp = nextpl;
2725 }
2726}
2727/*********************** From the file "report.c" **************************/
2728/*
2729** Procedures for generating reports and tables in the LEMON parser generator.
2730*/
2731
2732/* Generate a filename with the given suffix. Space to hold the
2733** name comes from malloc() and must be freed by the calling
2734** function.
2735*/
icculus9e44cf12010-02-14 17:14:22 +00002736PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002737{
2738 char *name;
2739 char *cp;
2740
icculus9e44cf12010-02-14 17:14:22 +00002741 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002742 if( name==0 ){
2743 fprintf(stderr,"Can't allocate space for a filename.\n");
2744 exit(1);
2745 }
2746 strcpy(name,lemp->filename);
2747 cp = strrchr(name,'.');
2748 if( cp ) *cp = 0;
2749 strcat(name,suffix);
2750 return name;
2751}
2752
2753/* Open a file with a name based on the name of the input file,
2754** but with a different (specified) suffix, and return a pointer
2755** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002756PRIVATE FILE *file_open(
2757 struct lemon *lemp,
2758 const char *suffix,
2759 const char *mode
2760){
drh75897232000-05-29 14:26:00 +00002761 FILE *fp;
2762
2763 if( lemp->outname ) free(lemp->outname);
2764 lemp->outname = file_makename(lemp, suffix);
2765 fp = fopen(lemp->outname,mode);
2766 if( fp==0 && *mode=='w' ){
2767 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2768 lemp->errorcnt++;
2769 return 0;
2770 }
icculusf5ad8242010-02-14 05:34:42 +00002771
2772 /* Add files we create to a list, so we can delete them if we fail. This
2773 ** is to keep makefiles from getting confused. We don't include .out files,
2774 ** though: this is debug information, and you don't want it deleted if there
2775 ** was an error you need to track down.
2776 */
2777 if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){
2778 const char **ptr = (const char **)
2779 realloc(made_files, sizeof (const char **) * (made_files_count + 1));
2780 char *fname = strdup(lemp->outname);
2781 if ((ptr == NULL) || (fname == NULL)) {
2782 free(ptr);
2783 free(fname);
2784 memory_error();
2785 }
2786 made_files = ptr;
2787 made_files[made_files_count++] = fname;
2788 }
drh75897232000-05-29 14:26:00 +00002789 return fp;
2790}
2791
2792/* Duplicate the input file without comments and without actions
2793** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002794void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002795{
2796 struct rule *rp;
2797 struct symbol *sp;
2798 int i, j, maxlen, len, ncolumns, skip;
2799 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2800 maxlen = 10;
2801 for(i=0; i<lemp->nsymbol; i++){
2802 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002803 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002804 if( len>maxlen ) maxlen = len;
2805 }
2806 ncolumns = 76/(maxlen+5);
2807 if( ncolumns<1 ) ncolumns = 1;
2808 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2809 for(i=0; i<skip; i++){
2810 printf("//");
2811 for(j=i; j<lemp->nsymbol; j+=skip){
2812 sp = lemp->symbols[j];
2813 assert( sp->index==j );
2814 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2815 }
2816 printf("\n");
2817 }
2818 for(rp=lemp->rule; rp; rp=rp->next){
2819 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002820 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002821 printf(" ::=");
2822 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002823 sp = rp->rhs[i];
2824 printf(" %s", sp->name);
2825 if( sp->type==MULTITERMINAL ){
2826 for(j=1; j<sp->nsubsym; j++){
2827 printf("|%s", sp->subsym[j]->name);
2828 }
2829 }
2830 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002831 }
2832 printf(".");
2833 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002834 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002835 printf("\n");
2836 }
2837}
2838
icculus9e44cf12010-02-14 17:14:22 +00002839void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002840{
2841 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002842 struct symbol *sp;
2843 int i, j;
drh75897232000-05-29 14:26:00 +00002844 rp = cfp->rp;
2845 fprintf(fp,"%s ::=",rp->lhs->name);
2846 for(i=0; i<=rp->nrhs; i++){
2847 if( i==cfp->dot ) fprintf(fp," *");
2848 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002849 sp = rp->rhs[i];
2850 fprintf(fp," %s", sp->name);
2851 if( sp->type==MULTITERMINAL ){
2852 for(j=1; j<sp->nsubsym; j++){
2853 fprintf(fp,"|%s",sp->subsym[j]->name);
2854 }
2855 }
drh75897232000-05-29 14:26:00 +00002856 }
2857}
2858
2859/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002860#if 0
drh75897232000-05-29 14:26:00 +00002861/* Print a set */
2862PRIVATE void SetPrint(out,set,lemp)
2863FILE *out;
2864char *set;
2865struct lemon *lemp;
2866{
2867 int i;
2868 char *spacer;
2869 spacer = "";
2870 fprintf(out,"%12s[","");
2871 for(i=0; i<lemp->nterminal; i++){
2872 if( SetFind(set,i) ){
2873 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2874 spacer = " ";
2875 }
2876 }
2877 fprintf(out,"]\n");
2878}
2879
2880/* Print a plink chain */
2881PRIVATE void PlinkPrint(out,plp,tag)
2882FILE *out;
2883struct plink *plp;
2884char *tag;
2885{
2886 while( plp ){
drhada354d2005-11-05 15:03:59 +00002887 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002888 ConfigPrint(out,plp->cfp);
2889 fprintf(out,"\n");
2890 plp = plp->next;
2891 }
2892}
2893#endif
2894
2895/* Print an action to the given file descriptor. Return FALSE if
2896** nothing was actually printed.
2897*/
2898int PrintAction(struct action *ap, FILE *fp, int indent){
2899 int result = 1;
2900 switch( ap->type ){
2901 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002902 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002903 break;
2904 case REDUCE:
2905 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2906 break;
2907 case ACCEPT:
2908 fprintf(fp,"%*s accept",indent,ap->sp->name);
2909 break;
2910 case ERROR:
2911 fprintf(fp,"%*s error",indent,ap->sp->name);
2912 break;
drh9892c5d2007-12-21 00:02:11 +00002913 case SRCONFLICT:
2914 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002915 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2916 indent,ap->sp->name,ap->x.rp->index);
2917 break;
drh9892c5d2007-12-21 00:02:11 +00002918 case SSCONFLICT:
2919 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2920 indent,ap->sp->name,ap->x.stp->statenum);
2921 break;
drh75897232000-05-29 14:26:00 +00002922 case SH_RESOLVED:
2923 case RD_RESOLVED:
2924 case NOT_USED:
2925 result = 0;
2926 break;
2927 }
2928 return result;
2929}
2930
2931/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00002932void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002933{
2934 int i;
2935 struct state *stp;
2936 struct config *cfp;
2937 struct action *ap;
2938 FILE *fp;
2939
drh2aa6ca42004-09-10 00:14:04 +00002940 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002941 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002942 for(i=0; i<lemp->nstate; i++){
2943 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002944 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002945 if( lemp->basisflag ) cfp=stp->bp;
2946 else cfp=stp->cfp;
2947 while( cfp ){
2948 char buf[20];
2949 if( cfp->dot==cfp->rp->nrhs ){
2950 sprintf(buf,"(%d)",cfp->rp->index);
2951 fprintf(fp," %5s ",buf);
2952 }else{
2953 fprintf(fp," ");
2954 }
2955 ConfigPrint(fp,cfp);
2956 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002957#if 0
drh75897232000-05-29 14:26:00 +00002958 SetPrint(fp,cfp->fws,lemp);
2959 PlinkPrint(fp,cfp->fplp,"To ");
2960 PlinkPrint(fp,cfp->bplp,"From");
2961#endif
2962 if( lemp->basisflag ) cfp=cfp->bp;
2963 else cfp=cfp->next;
2964 }
2965 fprintf(fp,"\n");
2966 for(ap=stp->ap; ap; ap=ap->next){
2967 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2968 }
2969 fprintf(fp,"\n");
2970 }
drhe9278182007-07-18 18:16:29 +00002971 fprintf(fp, "----------------------------------------------------\n");
2972 fprintf(fp, "Symbols:\n");
2973 for(i=0; i<lemp->nsymbol; i++){
2974 int j;
2975 struct symbol *sp;
2976
2977 sp = lemp->symbols[i];
2978 fprintf(fp, " %3d: %s", i, sp->name);
2979 if( sp->type==NONTERMINAL ){
2980 fprintf(fp, ":");
2981 if( sp->lambda ){
2982 fprintf(fp, " <lambda>");
2983 }
2984 for(j=0; j<lemp->nterminal; j++){
2985 if( sp->firstset && SetFind(sp->firstset, j) ){
2986 fprintf(fp, " %s", lemp->symbols[j]->name);
2987 }
2988 }
2989 }
2990 fprintf(fp, "\n");
2991 }
drh75897232000-05-29 14:26:00 +00002992 fclose(fp);
2993 return;
2994}
2995
2996/* Search for the file "name" which is in the same directory as
2997** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00002998PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00002999{
icculus9e44cf12010-02-14 17:14:22 +00003000 const char *pathlist;
3001 char *pathbufptr;
3002 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003003 char *path,*cp;
3004 char c;
drh75897232000-05-29 14:26:00 +00003005
3006#ifdef __WIN32__
3007 cp = strrchr(argv0,'\\');
3008#else
3009 cp = strrchr(argv0,'/');
3010#endif
3011 if( cp ){
3012 c = *cp;
3013 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003014 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003015 if( path ) sprintf(path,"%s/%s",argv0,name);
3016 *cp = c;
3017 }else{
drh75897232000-05-29 14:26:00 +00003018 pathlist = getenv("PATH");
3019 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003020 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003021 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003022 if( (pathbuf != 0) && (path!=0) ){
3023 pathbufptr = pathbuf;
3024 strcpy(pathbuf, pathlist);
3025 while( *pathbuf ){
3026 cp = strchr(pathbuf,':');
3027 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003028 c = *cp;
3029 *cp = 0;
icculus9e44cf12010-02-14 17:14:22 +00003030 sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003031 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003032 if( c==0 ) pathbuf[0] = 0;
3033 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003034 if( access(path,modemask)==0 ) break;
3035 }
icculus9e44cf12010-02-14 17:14:22 +00003036 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003037 }
3038 }
3039 return path;
3040}
3041
3042/* Given an action, compute the integer value for that action
3043** which is to be put in the action table of the generated machine.
3044** Return negative if no action should be generated.
3045*/
icculus9e44cf12010-02-14 17:14:22 +00003046PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003047{
3048 int act;
3049 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003050 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003051 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3052 case ERROR: act = lemp->nstate + lemp->nrule; break;
3053 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3054 default: act = -1; break;
3055 }
3056 return act;
3057}
3058
3059#define LINESIZE 1000
3060/* The next cluster of routines are for reading the template file
3061** and writing the results to the generated parser */
3062/* The first function transfers data from "in" to "out" until
3063** a line is seen which begins with "%%". The line number is
3064** tracked.
3065**
3066** if name!=0, then any word that begin with "Parse" is changed to
3067** begin with *name instead.
3068*/
icculus9e44cf12010-02-14 17:14:22 +00003069PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003070{
3071 int i, iStart;
3072 char line[LINESIZE];
3073 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3074 (*lineno)++;
3075 iStart = 0;
3076 if( name ){
3077 for(i=0; line[i]; i++){
3078 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3079 && (i==0 || !isalpha(line[i-1]))
3080 ){
3081 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3082 fprintf(out,"%s",name);
3083 i += 4;
3084 iStart = i+1;
3085 }
3086 }
3087 }
3088 fprintf(out,"%s",&line[iStart]);
3089 }
3090}
3091
3092/* The next function finds the template file and opens it, returning
3093** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003094PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003095{
3096 static char templatename[] = "lempar.c";
3097 char buf[1000];
3098 FILE *in;
3099 char *tpltname;
3100 char *cp;
3101
icculus3e143bd2010-02-14 00:48:49 +00003102 /* first, see if user specified a template filename on the command line. */
3103 if (user_templatename != 0) {
3104 if( access(user_templatename,004)==-1 ){
3105 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3106 user_templatename);
3107 lemp->errorcnt++;
3108 return 0;
3109 }
3110 in = fopen(user_templatename,"rb");
3111 if( in==0 ){
3112 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3113 lemp->errorcnt++;
3114 return 0;
3115 }
3116 return in;
3117 }
3118
drh75897232000-05-29 14:26:00 +00003119 cp = strrchr(lemp->filename,'.');
3120 if( cp ){
drh8b582012003-10-21 13:16:03 +00003121 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003122 }else{
3123 sprintf(buf,"%s.lt",lemp->filename);
3124 }
3125 if( access(buf,004)==0 ){
3126 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003127 }else if( access(templatename,004)==0 ){
3128 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003129 }else{
3130 tpltname = pathsearch(lemp->argv0,templatename,0);
3131 }
3132 if( tpltname==0 ){
3133 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3134 templatename);
3135 lemp->errorcnt++;
3136 return 0;
3137 }
drh2aa6ca42004-09-10 00:14:04 +00003138 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003139 if( in==0 ){
3140 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3141 lemp->errorcnt++;
3142 return 0;
3143 }
3144 return in;
3145}
3146
drhaf805ca2004-09-07 11:28:25 +00003147/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003148PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003149{
3150 fprintf(out,"#line %d \"",lineno);
3151 while( *filename ){
3152 if( *filename == '\\' ) putc('\\',out);
3153 putc(*filename,out);
3154 filename++;
3155 }
3156 fprintf(out,"\"\n");
3157}
3158
drh75897232000-05-29 14:26:00 +00003159/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003160PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003161{
3162 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003163 while( *str ){
drh75897232000-05-29 14:26:00 +00003164 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003165 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003166 str++;
3167 }
drh9db55df2004-09-09 14:01:21 +00003168 if( str[-1]!='\n' ){
3169 putc('\n',out);
3170 (*lineno)++;
3171 }
shane58543932008-12-10 20:10:04 +00003172 if (!lemp->nolinenosflag) {
3173 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3174 }
drh75897232000-05-29 14:26:00 +00003175 return;
3176}
3177
3178/*
3179** The following routine emits code for the destructor for the
3180** symbol sp
3181*/
icculus9e44cf12010-02-14 17:14:22 +00003182void emit_destructor_code(
3183 FILE *out,
3184 struct symbol *sp,
3185 struct lemon *lemp,
3186 int *lineno
3187){
drhcc83b6e2004-04-23 23:38:42 +00003188 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003189
drh75897232000-05-29 14:26:00 +00003190 if( sp->type==TERMINAL ){
3191 cp = lemp->tokendest;
3192 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003193 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003194 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003195 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003196 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003197 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003198 }else if( lemp->vardest ){
3199 cp = lemp->vardest;
3200 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003201 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003202 }else{
3203 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003204 }
3205 for(; *cp; cp++){
3206 if( *cp=='$' && cp[1]=='$' ){
3207 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3208 cp++;
3209 continue;
3210 }
shane58543932008-12-10 20:10:04 +00003211 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003212 fputc(*cp,out);
3213 }
shane58543932008-12-10 20:10:04 +00003214 fprintf(out,"\n"); (*lineno)++;
3215 if (!lemp->nolinenosflag) {
3216 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3217 }
3218 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003219 return;
3220}
3221
3222/*
drh960e8c62001-04-03 16:53:21 +00003223** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003224*/
icculus9e44cf12010-02-14 17:14:22 +00003225int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003226{
3227 int ret;
3228 if( sp->type==TERMINAL ){
3229 ret = lemp->tokendest!=0;
3230 }else{
drh960e8c62001-04-03 16:53:21 +00003231 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003232 }
3233 return ret;
3234}
3235
drh0bb132b2004-07-20 14:06:51 +00003236/*
3237** Append text to a dynamically allocated string. If zText is 0 then
3238** reset the string to be empty again. Always return the complete text
3239** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003240**
3241** n bytes of zText are stored. If n==0 then all of zText up to the first
3242** \000 terminator is stored. zText can contain up to two instances of
3243** %d. The values of p1 and p2 are written into the first and second
3244** %d.
3245**
3246** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003247*/
icculus9e44cf12010-02-14 17:14:22 +00003248PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3249 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003250 static char *z = 0;
3251 static int alloced = 0;
3252 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003253 int c;
drh0bb132b2004-07-20 14:06:51 +00003254 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003255 if( zText==0 ){
3256 used = 0;
3257 return z;
3258 }
drh7ac25c72004-08-19 15:12:26 +00003259 if( n<=0 ){
3260 if( n<0 ){
3261 used += n;
3262 assert( used>=0 );
3263 }
drh87cf1372008-08-13 20:09:06 +00003264 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003265 }
drh0bb132b2004-07-20 14:06:51 +00003266 if( n+sizeof(zInt)*2+used >= alloced ){
3267 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003268 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003269 }
icculus9e44cf12010-02-14 17:14:22 +00003270 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003271 while( n-- > 0 ){
3272 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003273 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003274 sprintf(zInt, "%d", p1);
3275 p1 = p2;
3276 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003277 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003278 zText++;
3279 n--;
3280 }else{
3281 z[used++] = c;
3282 }
3283 }
3284 z[used] = 0;
3285 return z;
3286}
3287
3288/*
3289** zCode is a string that is the action associated with a rule. Expand
3290** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003291** stack.
drh0bb132b2004-07-20 14:06:51 +00003292*/
drhaf805ca2004-09-07 11:28:25 +00003293PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003294 char *cp, *xp;
3295 int i;
3296 char lhsused = 0; /* True if the LHS element has been used */
3297 char used[MAXRHS]; /* True for each RHS element which is used */
3298
3299 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3300 lhsused = 0;
3301
drh19c9e562007-03-29 20:13:53 +00003302 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003303 static char newlinestr[2] = { '\n', '\0' };
3304 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003305 rp->line = rp->ruleline;
3306 }
3307
drh0bb132b2004-07-20 14:06:51 +00003308 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003309
3310 /* This const cast is wrong but harmless, if we're careful. */
3311 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003312 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3313 char saved;
3314 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3315 saved = *xp;
3316 *xp = 0;
3317 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003318 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003319 cp = xp;
3320 lhsused = 1;
3321 }else{
3322 for(i=0; i<rp->nrhs; i++){
3323 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003324 if( cp!=rp->code && cp[-1]=='@' ){
3325 /* If the argument is of the form @X then substituted
3326 ** the token number of X, not the value of X */
3327 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3328 }else{
drhfd405312005-11-06 04:06:59 +00003329 struct symbol *sp = rp->rhs[i];
3330 int dtnum;
3331 if( sp->type==MULTITERMINAL ){
3332 dtnum = sp->subsym[0]->dtnum;
3333 }else{
3334 dtnum = sp->dtnum;
3335 }
3336 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003337 }
drh0bb132b2004-07-20 14:06:51 +00003338 cp = xp;
3339 used[i] = 1;
3340 break;
3341 }
3342 }
3343 }
3344 *xp = saved;
3345 }
3346 append_str(cp, 1, 0, 0);
3347 } /* End loop */
3348
3349 /* Check to make sure the LHS has been used */
3350 if( rp->lhsalias && !lhsused ){
3351 ErrorMsg(lemp->filename,rp->ruleline,
3352 "Label \"%s\" for \"%s(%s)\" is never used.",
3353 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3354 lemp->errorcnt++;
3355 }
3356
3357 /* Generate destructor code for RHS symbols which are not used in the
3358 ** reduce code */
3359 for(i=0; i<rp->nrhs; i++){
3360 if( rp->rhsalias[i] && !used[i] ){
3361 ErrorMsg(lemp->filename,rp->ruleline,
3362 "Label %s for \"%s(%s)\" is never used.",
3363 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3364 lemp->errorcnt++;
3365 }else if( rp->rhsalias[i]==0 ){
3366 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003367 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003368 rp->rhs[i]->index,i-rp->nrhs+1);
3369 }else{
3370 /* No destructor defined for this term */
3371 }
3372 }
3373 }
drh61e339a2007-01-16 03:09:02 +00003374 if( rp->code ){
3375 cp = append_str(0,0,0,0);
3376 rp->code = Strsafe(cp?cp:"");
3377 }
drh0bb132b2004-07-20 14:06:51 +00003378}
3379
drh75897232000-05-29 14:26:00 +00003380/*
3381** Generate code which executes when the rule "rp" is reduced. Write
3382** the code to "out". Make sure lineno stays up-to-date.
3383*/
icculus9e44cf12010-02-14 17:14:22 +00003384PRIVATE void emit_code(
3385 FILE *out,
3386 struct rule *rp,
3387 struct lemon *lemp,
3388 int *lineno
3389){
3390 const char *cp;
drh75897232000-05-29 14:26:00 +00003391
3392 /* Generate code to do the reduce action */
3393 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003394 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003395 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003396 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003397 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003398 } /* End loop */
shane58543932008-12-10 20:10:04 +00003399 fprintf(out,"}\n"); (*lineno)++;
3400 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003401 } /* End if( rp->code ) */
3402
drh75897232000-05-29 14:26:00 +00003403 return;
3404}
3405
3406/*
3407** Print the definition of the union used for the parser's data stack.
3408** This union contains fields for every possible data type for tokens
3409** and nonterminals. In the process of computing and printing this
3410** union, also set the ".dtnum" field of every terminal and nonterminal
3411** symbol.
3412*/
icculus9e44cf12010-02-14 17:14:22 +00003413void print_stack_union(
3414 FILE *out, /* The output stream */
3415 struct lemon *lemp, /* The main info structure for this parser */
3416 int *plineno, /* Pointer to the line number */
3417 int mhflag /* True if generating makeheaders output */
3418){
drh75897232000-05-29 14:26:00 +00003419 int lineno = *plineno; /* The line number of the output */
3420 char **types; /* A hash table of datatypes */
3421 int arraysize; /* Size of the "types" array */
3422 int maxdtlength; /* Maximum length of any ".datatype" field. */
3423 char *stddt; /* Standardized name for a datatype */
3424 int i,j; /* Loop counters */
3425 int hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003426 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003427
3428 /* Allocate and initialize types[] and allocate stddt[] */
3429 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003430 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003431 for(i=0; i<arraysize; i++) types[i] = 0;
3432 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003433 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003434 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003435 }
drh75897232000-05-29 14:26:00 +00003436 for(i=0; i<lemp->nsymbol; i++){
3437 int len;
3438 struct symbol *sp = lemp->symbols[i];
3439 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003440 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003441 if( len>maxdtlength ) maxdtlength = len;
3442 }
3443 stddt = (char*)malloc( maxdtlength*2 + 1 );
3444 if( types==0 || stddt==0 ){
3445 fprintf(stderr,"Out of memory.\n");
3446 exit(1);
3447 }
3448
3449 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3450 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003451 ** used for terminal symbols. If there is no %default_type defined then
3452 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3453 ** a datatype using the %type directive.
3454 */
drh75897232000-05-29 14:26:00 +00003455 for(i=0; i<lemp->nsymbol; i++){
3456 struct symbol *sp = lemp->symbols[i];
3457 char *cp;
3458 if( sp==lemp->errsym ){
3459 sp->dtnum = arraysize+1;
3460 continue;
3461 }
drh960e8c62001-04-03 16:53:21 +00003462 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003463 sp->dtnum = 0;
3464 continue;
3465 }
3466 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003467 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003468 j = 0;
3469 while( isspace(*cp) ) cp++;
3470 while( *cp ) stddt[j++] = *cp++;
3471 while( j>0 && isspace(stddt[j-1]) ) j--;
3472 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003473 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003474 sp->dtnum = 0;
3475 continue;
3476 }
drh75897232000-05-29 14:26:00 +00003477 hash = 0;
3478 for(j=0; stddt[j]; j++){
3479 hash = hash*53 + stddt[j];
3480 }
drh3b2129c2003-05-13 00:34:21 +00003481 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003482 while( types[hash] ){
3483 if( strcmp(types[hash],stddt)==0 ){
3484 sp->dtnum = hash + 1;
3485 break;
3486 }
3487 hash++;
3488 if( hash>=arraysize ) hash = 0;
3489 }
3490 if( types[hash]==0 ){
3491 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003492 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003493 if( types[hash]==0 ){
3494 fprintf(stderr,"Out of memory.\n");
3495 exit(1);
3496 }
3497 strcpy(types[hash],stddt);
3498 }
3499 }
3500
3501 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3502 name = lemp->name ? lemp->name : "Parse";
3503 lineno = *plineno;
3504 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3505 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3506 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3507 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3508 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003509 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003510 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3511 for(i=0; i<arraysize; i++){
3512 if( types[i]==0 ) continue;
3513 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3514 free(types[i]);
3515 }
drhc4dd3fd2008-01-22 01:48:05 +00003516 if( lemp->errsym->useCnt ){
3517 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3518 }
drh75897232000-05-29 14:26:00 +00003519 free(stddt);
3520 free(types);
3521 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3522 *plineno = lineno;
3523}
3524
drhb29b0a52002-02-23 19:39:46 +00003525/*
3526** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003527** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003528*/
drh8b582012003-10-21 13:16:03 +00003529static const char *minimum_size_type(int lwr, int upr){
3530 if( lwr>=0 ){
3531 if( upr<=255 ){
3532 return "unsigned char";
3533 }else if( upr<65535 ){
3534 return "unsigned short int";
3535 }else{
3536 return "unsigned int";
3537 }
3538 }else if( lwr>=-127 && upr<=127 ){
3539 return "signed char";
3540 }else if( lwr>=-32767 && upr<32767 ){
3541 return "short";
drhb29b0a52002-02-23 19:39:46 +00003542 }else{
drh8b582012003-10-21 13:16:03 +00003543 return "int";
drhb29b0a52002-02-23 19:39:46 +00003544 }
3545}
3546
drhfdbf9282003-10-21 16:34:41 +00003547/*
3548** Each state contains a set of token transaction and a set of
3549** nonterminal transactions. Each of these sets makes an instance
3550** of the following structure. An array of these structures is used
3551** to order the creation of entries in the yy_action[] table.
3552*/
3553struct axset {
3554 struct state *stp; /* A pointer to a state */
3555 int isTkn; /* True to use tokens. False for non-terminals */
3556 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003557 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003558};
3559
3560/*
3561** Compare to axset structures for sorting purposes
3562*/
3563static int axset_compare(const void *a, const void *b){
3564 struct axset *p1 = (struct axset*)a;
3565 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003566 int c;
3567 c = p2->nAction - p1->nAction;
3568 if( c==0 ){
3569 c = p2->iOrder - p1->iOrder;
3570 }
3571 assert( c!=0 || p1==p2 );
3572 return c;
drhfdbf9282003-10-21 16:34:41 +00003573}
3574
drhc4dd3fd2008-01-22 01:48:05 +00003575/*
3576** Write text on "out" that describes the rule "rp".
3577*/
3578static void writeRuleText(FILE *out, struct rule *rp){
3579 int j;
3580 fprintf(out,"%s ::=", rp->lhs->name);
3581 for(j=0; j<rp->nrhs; j++){
3582 struct symbol *sp = rp->rhs[j];
3583 fprintf(out," %s", sp->name);
3584 if( sp->type==MULTITERMINAL ){
3585 int k;
3586 for(k=1; k<sp->nsubsym; k++){
3587 fprintf(out,"|%s",sp->subsym[k]->name);
3588 }
3589 }
3590 }
3591}
3592
3593
drh75897232000-05-29 14:26:00 +00003594/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003595void ReportTable(
3596 struct lemon *lemp,
3597 int mhflag /* Output in makeheaders format if true */
3598){
drh75897232000-05-29 14:26:00 +00003599 FILE *out, *in;
3600 char line[LINESIZE];
3601 int lineno;
3602 struct state *stp;
3603 struct action *ap;
3604 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003605 struct acttab *pActtab;
drhf16371d2009-11-03 19:18:31 +00003606 int i, j, k, n;
icculus9e44cf12010-02-14 17:14:22 +00003607 const char *name;
drh8b582012003-10-21 13:16:03 +00003608 int mnTknOfst, mxTknOfst;
3609 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003610 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003611
3612 in = tplt_open(lemp);
3613 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003614 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003615 if( out==0 ){
3616 fclose(in);
3617 return;
3618 }
3619 lineno = 1;
3620 tplt_xfer(lemp->name,in,out,&lineno);
3621
3622 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003623 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003624 if( mhflag ){
3625 char *name = file_makename(lemp, ".h");
3626 fprintf(out,"#include \"%s\"\n", name); lineno++;
3627 free(name);
3628 }
3629 tplt_xfer(lemp->name,in,out,&lineno);
3630
3631 /* Generate #defines for all tokens */
3632 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003633 const char *prefix;
drh75897232000-05-29 14:26:00 +00003634 fprintf(out,"#if INTERFACE\n"); lineno++;
3635 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3636 else prefix = "";
3637 for(i=1; i<lemp->nterminal; i++){
3638 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3639 lineno++;
3640 }
3641 fprintf(out,"#endif\n"); lineno++;
3642 }
3643 tplt_xfer(lemp->name,in,out,&lineno);
3644
3645 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003646 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003647 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003648 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3649 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003650 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003651 if( lemp->wildcard ){
3652 fprintf(out,"#define YYWILDCARD %d\n",
3653 lemp->wildcard->index); lineno++;
3654 }
drh75897232000-05-29 14:26:00 +00003655 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003656 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003657 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003658 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3659 }else{
3660 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3661 }
drhca44b5a2007-02-22 23:06:58 +00003662 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003663 if( mhflag ){
3664 fprintf(out,"#if INTERFACE\n"); lineno++;
3665 }
3666 name = lemp->name ? lemp->name : "Parse";
3667 if( lemp->arg && lemp->arg[0] ){
3668 int i;
drh87cf1372008-08-13 20:09:06 +00003669 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003670 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3671 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003672 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3673 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3674 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3675 name,lemp->arg,&lemp->arg[i]); lineno++;
3676 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3677 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003678 }else{
drh1f245e42002-03-11 13:55:50 +00003679 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3680 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3681 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3682 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003683 }
3684 if( mhflag ){
3685 fprintf(out,"#endif\n"); lineno++;
3686 }
3687 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3688 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003689 if( lemp->errsym->useCnt ){
3690 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3691 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3692 }
drh0bd1f4e2002-06-06 18:54:39 +00003693 if( lemp->has_fallback ){
3694 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3695 }
drh75897232000-05-29 14:26:00 +00003696 tplt_xfer(lemp->name,in,out,&lineno);
3697
drh8b582012003-10-21 13:16:03 +00003698 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003699 **
drh8b582012003-10-21 13:16:03 +00003700 ** yy_action[] A single table containing all actions.
3701 ** yy_lookahead[] A table containing the lookahead for each entry in
3702 ** yy_action. Used to detect hash collisions.
3703 ** yy_shift_ofst[] For each state, the offset into yy_action for
3704 ** shifting terminals.
3705 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3706 ** shifting non-terminals after a reduce.
3707 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003708 */
drh75897232000-05-29 14:26:00 +00003709
drh8b582012003-10-21 13:16:03 +00003710 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003711 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003712 if( ax==0 ){
3713 fprintf(stderr,"malloc failed\n");
3714 exit(1);
3715 }
drh75897232000-05-29 14:26:00 +00003716 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003717 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003718 ax[i*2].stp = stp;
3719 ax[i*2].isTkn = 1;
3720 ax[i*2].nAction = stp->nTknAct;
3721 ax[i*2+1].stp = stp;
3722 ax[i*2+1].isTkn = 0;
3723 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003724 }
drh8b582012003-10-21 13:16:03 +00003725 mxTknOfst = mnTknOfst = 0;
3726 mxNtOfst = mnNtOfst = 0;
3727
drhfdbf9282003-10-21 16:34:41 +00003728 /* Compute the action table. In order to try to keep the size of the
3729 ** action table to a minimum, the heuristic of placing the largest action
3730 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003731 */
drhe594bc32009-11-03 13:02:25 +00003732 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003733 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003734 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003735 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3736 stp = ax[i].stp;
3737 if( ax[i].isTkn ){
3738 for(ap=stp->ap; ap; ap=ap->next){
3739 int action;
3740 if( ap->sp->index>=lemp->nterminal ) continue;
3741 action = compute_action(lemp, ap);
3742 if( action<0 ) continue;
3743 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003744 }
drhfdbf9282003-10-21 16:34:41 +00003745 stp->iTknOfst = acttab_insert(pActtab);
3746 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3747 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3748 }else{
3749 for(ap=stp->ap; ap; ap=ap->next){
3750 int action;
3751 if( ap->sp->index<lemp->nterminal ) continue;
3752 if( ap->sp->index==lemp->nsymbol ) continue;
3753 action = compute_action(lemp, ap);
3754 if( action<0 ) continue;
3755 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003756 }
drhfdbf9282003-10-21 16:34:41 +00003757 stp->iNtOfst = acttab_insert(pActtab);
3758 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3759 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003760 }
3761 }
drhfdbf9282003-10-21 16:34:41 +00003762 free(ax);
drh8b582012003-10-21 13:16:03 +00003763
3764 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003765 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003766 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3767 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003768 for(i=j=0; i<n; i++){
3769 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003770 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003771 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003772 fprintf(out, " %4d,", action);
3773 if( j==9 || i==n-1 ){
3774 fprintf(out, "\n"); lineno++;
3775 j = 0;
3776 }else{
3777 j++;
3778 }
3779 }
3780 fprintf(out, "};\n"); lineno++;
3781
3782 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003783 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003784 for(i=j=0; i<n; i++){
3785 int la = acttab_yylookahead(pActtab, i);
3786 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003787 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003788 fprintf(out, " %4d,", la);
3789 if( j==9 || i==n-1 ){
3790 fprintf(out, "\n"); lineno++;
3791 j = 0;
3792 }else{
3793 j++;
3794 }
3795 }
3796 fprintf(out, "};\n"); lineno++;
3797
3798 /* Output the yy_shift_ofst[] table */
3799 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003800 n = lemp->nstate;
3801 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003802 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3803 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3804 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003805 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003806 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003807 for(i=j=0; i<n; i++){
3808 int ofst;
3809 stp = lemp->sorted[i];
3810 ofst = stp->iTknOfst;
3811 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003812 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003813 fprintf(out, " %4d,", ofst);
3814 if( j==9 || i==n-1 ){
3815 fprintf(out, "\n"); lineno++;
3816 j = 0;
3817 }else{
3818 j++;
3819 }
3820 }
3821 fprintf(out, "};\n"); lineno++;
3822
3823 /* Output the yy_reduce_ofst[] table */
3824 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003825 n = lemp->nstate;
3826 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003827 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3828 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3829 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003830 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003831 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003832 for(i=j=0; i<n; i++){
3833 int ofst;
3834 stp = lemp->sorted[i];
3835 ofst = stp->iNtOfst;
3836 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003837 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003838 fprintf(out, " %4d,", ofst);
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 default action table */
drh57196282004-10-06 15:41:16 +00003849 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003850 n = lemp->nstate;
3851 for(i=j=0; i<n; i++){
3852 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003853 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003854 fprintf(out, " %4d,", stp->iDflt);
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++;
drh75897232000-05-29 14:26:00 +00003863 tplt_xfer(lemp->name,in,out,&lineno);
3864
drh0bd1f4e2002-06-06 18:54:39 +00003865 /* Generate the table of fallback tokens.
3866 */
3867 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003868 int mx = lemp->nterminal - 1;
3869 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3870 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003871 struct symbol *p = lemp->symbols[i];
3872 if( p->fallback==0 ){
3873 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3874 }else{
3875 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3876 p->name, p->fallback->name);
3877 }
3878 lineno++;
3879 }
3880 }
3881 tplt_xfer(lemp->name, in, out, &lineno);
3882
3883 /* Generate a table containing the symbolic name of every symbol
3884 */
drh75897232000-05-29 14:26:00 +00003885 for(i=0; i<lemp->nsymbol; i++){
3886 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3887 fprintf(out," %-15s",line);
3888 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3889 }
3890 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3891 tplt_xfer(lemp->name,in,out,&lineno);
3892
drh0bd1f4e2002-06-06 18:54:39 +00003893 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003894 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003895 ** when tracing REDUCE actions.
3896 */
3897 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3898 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003899 fprintf(out," /* %3d */ \"", i);
3900 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003901 fprintf(out,"\",\n"); lineno++;
3902 }
3903 tplt_xfer(lemp->name,in,out,&lineno);
3904
drh75897232000-05-29 14:26:00 +00003905 /* Generate code which executes every time a symbol is popped from
3906 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003907 ** (In other words, generate the %destructor actions)
3908 */
drh75897232000-05-29 14:26:00 +00003909 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003910 int once = 1;
drh75897232000-05-29 14:26:00 +00003911 for(i=0; i<lemp->nsymbol; i++){
3912 struct symbol *sp = lemp->symbols[i];
3913 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003914 if( once ){
3915 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3916 once = 0;
3917 }
drhc53eed12009-06-12 17:46:19 +00003918 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003919 }
3920 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3921 if( i<lemp->nsymbol ){
3922 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3923 fprintf(out," break;\n"); lineno++;
3924 }
3925 }
drh8d659732005-01-13 23:54:06 +00003926 if( lemp->vardest ){
3927 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003928 int once = 1;
drh8d659732005-01-13 23:54:06 +00003929 for(i=0; i<lemp->nsymbol; i++){
3930 struct symbol *sp = lemp->symbols[i];
3931 if( sp==0 || sp->type==TERMINAL ||
3932 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003933 if( once ){
3934 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3935 once = 0;
3936 }
drhc53eed12009-06-12 17:46:19 +00003937 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003938 dflt_sp = sp;
3939 }
3940 if( dflt_sp!=0 ){
3941 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003942 }
drh4dc8ef52008-07-01 17:13:57 +00003943 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003944 }
drh75897232000-05-29 14:26:00 +00003945 for(i=0; i<lemp->nsymbol; i++){
3946 struct symbol *sp = lemp->symbols[i];
3947 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003948 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003949
3950 /* Combine duplicate destructors into a single case */
3951 for(j=i+1; j<lemp->nsymbol; j++){
3952 struct symbol *sp2 = lemp->symbols[j];
3953 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3954 && sp2->dtnum==sp->dtnum
3955 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003956 fprintf(out," case %d: /* %s */\n",
3957 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003958 sp2->destructor = 0;
3959 }
3960 }
3961
drh75897232000-05-29 14:26:00 +00003962 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3963 fprintf(out," break;\n"); lineno++;
3964 }
drh75897232000-05-29 14:26:00 +00003965 tplt_xfer(lemp->name,in,out,&lineno);
3966
3967 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003968 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003969 tplt_xfer(lemp->name,in,out,&lineno);
3970
3971 /* Generate the table of rule information
3972 **
3973 ** Note: This code depends on the fact that rules are number
3974 ** sequentually beginning with 0.
3975 */
3976 for(rp=lemp->rule; rp; rp=rp->next){
3977 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3978 }
3979 tplt_xfer(lemp->name,in,out,&lineno);
3980
3981 /* Generate code which execution during each REDUCE action */
3982 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003983 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003984 }
drhc53eed12009-06-12 17:46:19 +00003985 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003986 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003987 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003988 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003989 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003990 fprintf(out," case %d: /* ", rp->index);
3991 writeRuleText(out, rp);
3992 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003993 for(rp2=rp->next; rp2; rp2=rp2->next){
3994 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003995 fprintf(out," case %d: /* ", rp2->index);
3996 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003997 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003998 rp2->code = 0;
3999 }
4000 }
drh75897232000-05-29 14:26:00 +00004001 emit_code(out,rp,lemp,&lineno);
4002 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004003 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004004 }
drhc53eed12009-06-12 17:46:19 +00004005 /* Finally, output the default: rule. We choose as the default: all
4006 ** empty actions. */
4007 fprintf(out," default:\n"); lineno++;
4008 for(rp=lemp->rule; rp; rp=rp->next){
4009 if( rp->code==0 ) continue;
4010 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4011 fprintf(out," /* (%d) ", rp->index);
4012 writeRuleText(out, rp);
4013 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4014 }
4015 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004016 tplt_xfer(lemp->name,in,out,&lineno);
4017
4018 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004019 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004020 tplt_xfer(lemp->name,in,out,&lineno);
4021
4022 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004023 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004024 tplt_xfer(lemp->name,in,out,&lineno);
4025
4026 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004027 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004028 tplt_xfer(lemp->name,in,out,&lineno);
4029
4030 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004031 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004032
4033 fclose(in);
4034 fclose(out);
4035 return;
4036}
4037
4038/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004039void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004040{
4041 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004042 const char *prefix;
drh75897232000-05-29 14:26:00 +00004043 char line[LINESIZE];
4044 char pattern[LINESIZE];
4045 int i;
4046
4047 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4048 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004049 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004050 if( in ){
4051 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4052 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4053 if( strcmp(line,pattern) ) break;
4054 }
4055 fclose(in);
4056 if( i==lemp->nterminal ){
4057 /* No change in the file. Don't rewrite it. */
4058 return;
4059 }
4060 }
drh2aa6ca42004-09-10 00:14:04 +00004061 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004062 if( out ){
4063 for(i=1; i<lemp->nterminal; i++){
4064 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4065 }
4066 fclose(out);
4067 }
4068 return;
4069}
4070
4071/* Reduce the size of the action tables, if possible, by making use
4072** of defaults.
4073**
drhb59499c2002-02-23 18:45:13 +00004074** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004075** it the default. Except, there is no default if the wildcard token
4076** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004077*/
icculus9e44cf12010-02-14 17:14:22 +00004078void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004079{
4080 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004081 struct action *ap, *ap2;
4082 struct rule *rp, *rp2, *rbest;
4083 int nbest, n;
drh75897232000-05-29 14:26:00 +00004084 int i;
drhe09daa92006-06-10 13:29:31 +00004085 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004086
4087 for(i=0; i<lemp->nstate; i++){
4088 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004089 nbest = 0;
4090 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004091 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004092
drhb59499c2002-02-23 18:45:13 +00004093 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004094 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4095 usesWildcard = 1;
4096 }
drhb59499c2002-02-23 18:45:13 +00004097 if( ap->type!=REDUCE ) continue;
4098 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004099 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004100 if( rp==rbest ) continue;
4101 n = 1;
4102 for(ap2=ap->next; ap2; ap2=ap2->next){
4103 if( ap2->type!=REDUCE ) continue;
4104 rp2 = ap2->x.rp;
4105 if( rp2==rbest ) continue;
4106 if( rp2==rp ) n++;
4107 }
4108 if( n>nbest ){
4109 nbest = n;
4110 rbest = rp;
drh75897232000-05-29 14:26:00 +00004111 }
4112 }
drhb59499c2002-02-23 18:45:13 +00004113
4114 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004115 ** is not at least 1 or if the wildcard token is a possible
4116 ** lookahead.
4117 */
4118 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004119
drhb59499c2002-02-23 18:45:13 +00004120
4121 /* Combine matching REDUCE actions into a single default */
4122 for(ap=stp->ap; ap; ap=ap->next){
4123 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4124 }
drh75897232000-05-29 14:26:00 +00004125 assert( ap );
4126 ap->sp = Symbol_new("{default}");
4127 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004128 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004129 }
4130 stp->ap = Action_sort(stp->ap);
4131 }
4132}
drhb59499c2002-02-23 18:45:13 +00004133
drhada354d2005-11-05 15:03:59 +00004134
4135/*
4136** Compare two states for sorting purposes. The smaller state is the
4137** one with the most non-terminal actions. If they have the same number
4138** of non-terminal actions, then the smaller is the one with the most
4139** token actions.
4140*/
4141static int stateResortCompare(const void *a, const void *b){
4142 const struct state *pA = *(const struct state**)a;
4143 const struct state *pB = *(const struct state**)b;
4144 int n;
4145
4146 n = pB->nNtAct - pA->nNtAct;
4147 if( n==0 ){
4148 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004149 if( n==0 ){
4150 n = pB->statenum - pA->statenum;
4151 }
drhada354d2005-11-05 15:03:59 +00004152 }
drhe594bc32009-11-03 13:02:25 +00004153 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004154 return n;
4155}
4156
4157
4158/*
4159** Renumber and resort states so that states with fewer choices
4160** occur at the end. Except, keep state 0 as the first state.
4161*/
icculus9e44cf12010-02-14 17:14:22 +00004162void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004163{
4164 int i;
4165 struct state *stp;
4166 struct action *ap;
4167
4168 for(i=0; i<lemp->nstate; i++){
4169 stp = lemp->sorted[i];
4170 stp->nTknAct = stp->nNtAct = 0;
4171 stp->iDflt = lemp->nstate + lemp->nrule;
4172 stp->iTknOfst = NO_OFFSET;
4173 stp->iNtOfst = NO_OFFSET;
4174 for(ap=stp->ap; ap; ap=ap->next){
4175 if( compute_action(lemp,ap)>=0 ){
4176 if( ap->sp->index<lemp->nterminal ){
4177 stp->nTknAct++;
4178 }else if( ap->sp->index<lemp->nsymbol ){
4179 stp->nNtAct++;
4180 }else{
4181 stp->iDflt = compute_action(lemp, ap);
4182 }
4183 }
4184 }
4185 }
4186 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4187 stateResortCompare);
4188 for(i=0; i<lemp->nstate; i++){
4189 lemp->sorted[i]->statenum = i;
4190 }
4191}
4192
4193
drh75897232000-05-29 14:26:00 +00004194/***************** From the file "set.c" ************************************/
4195/*
4196** Set manipulation routines for the LEMON parser generator.
4197*/
4198
4199static int size = 0;
4200
4201/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004202void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004203{
4204 size = n+1;
4205}
4206
4207/* Allocate a new set */
4208char *SetNew(){
4209 char *s;
drh9892c5d2007-12-21 00:02:11 +00004210 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004211 if( s==0 ){
4212 extern void memory_error();
4213 memory_error();
4214 }
drh75897232000-05-29 14:26:00 +00004215 return s;
4216}
4217
4218/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004219void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004220{
4221 free(s);
4222}
4223
4224/* Add a new element to the set. Return TRUE if the element was added
4225** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004226int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004227{
4228 int rv;
drh9892c5d2007-12-21 00:02:11 +00004229 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004230 rv = s[e];
4231 s[e] = 1;
4232 return !rv;
4233}
4234
4235/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004236int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004237{
4238 int i, progress;
4239 progress = 0;
4240 for(i=0; i<size; i++){
4241 if( s2[i]==0 ) continue;
4242 if( s1[i]==0 ){
4243 progress = 1;
4244 s1[i] = 1;
4245 }
4246 }
4247 return progress;
4248}
4249/********************** From the file "table.c" ****************************/
4250/*
4251** All code in this file has been automatically generated
4252** from a specification in the file
4253** "table.q"
4254** by the associative array code building program "aagen".
4255** Do not edit this file! Instead, edit the specification
4256** file, then rerun aagen.
4257*/
4258/*
4259** Code for processing tables in the LEMON parser generator.
4260*/
4261
icculus9e44cf12010-02-14 17:14:22 +00004262PRIVATE int strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004263{
4264 int h = 0;
4265 while( *x) h = h*13 + *(x++);
4266 return h;
4267}
4268
4269/* Works like strdup, sort of. Save a string in malloced memory, but
4270** keep strings in a table so that the same string is not in more
4271** than one place.
4272*/
icculus9e44cf12010-02-14 17:14:22 +00004273const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004274{
icculus9e44cf12010-02-14 17:14:22 +00004275 const char *z;
4276 char *cpy;
drh75897232000-05-29 14:26:00 +00004277
drh916f75f2006-07-17 00:19:39 +00004278 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004279 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004280 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4281 strcpy(cpy,y);
4282 z = cpy;
drh75897232000-05-29 14:26:00 +00004283 Strsafe_insert(z);
4284 }
4285 MemoryCheck(z);
4286 return z;
4287}
4288
4289/* There is one instance of the following structure for each
4290** associative array of type "x1".
4291*/
4292struct s_x1 {
4293 int size; /* The number of available slots. */
4294 /* Must be a power of 2 greater than or */
4295 /* equal to 1 */
4296 int count; /* Number of currently slots filled */
4297 struct s_x1node *tbl; /* The data stored here */
4298 struct s_x1node **ht; /* Hash table for lookups */
4299};
4300
4301/* There is one instance of this structure for every data element
4302** in an associative array of type "x1".
4303*/
4304typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004305 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004306 struct s_x1node *next; /* Next entry with the same hash */
4307 struct s_x1node **from; /* Previous link */
4308} x1node;
4309
4310/* There is only one instance of the array, which is the following */
4311static struct s_x1 *x1a;
4312
4313/* Allocate a new associative array */
4314void Strsafe_init(){
4315 if( x1a ) return;
4316 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4317 if( x1a ){
4318 x1a->size = 1024;
4319 x1a->count = 0;
4320 x1a->tbl = (x1node*)malloc(
4321 (sizeof(x1node) + sizeof(x1node*))*1024 );
4322 if( x1a->tbl==0 ){
4323 free(x1a);
4324 x1a = 0;
4325 }else{
4326 int i;
4327 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4328 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4329 }
4330 }
4331}
4332/* Insert a new record into the array. Return TRUE if successful.
4333** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004334int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004335{
4336 x1node *np;
4337 int h;
4338 int ph;
4339
4340 if( x1a==0 ) return 0;
4341 ph = strhash(data);
4342 h = ph & (x1a->size-1);
4343 np = x1a->ht[h];
4344 while( np ){
4345 if( strcmp(np->data,data)==0 ){
4346 /* An existing entry with the same key is found. */
4347 /* Fail because overwrite is not allows. */
4348 return 0;
4349 }
4350 np = np->next;
4351 }
4352 if( x1a->count>=x1a->size ){
4353 /* Need to make the hash table bigger */
4354 int i,size;
4355 struct s_x1 array;
4356 array.size = size = x1a->size*2;
4357 array.count = x1a->count;
4358 array.tbl = (x1node*)malloc(
4359 (sizeof(x1node) + sizeof(x1node*))*size );
4360 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4361 array.ht = (x1node**)&(array.tbl[size]);
4362 for(i=0; i<size; i++) array.ht[i] = 0;
4363 for(i=0; i<x1a->count; i++){
4364 x1node *oldnp, *newnp;
4365 oldnp = &(x1a->tbl[i]);
4366 h = strhash(oldnp->data) & (size-1);
4367 newnp = &(array.tbl[i]);
4368 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4369 newnp->next = array.ht[h];
4370 newnp->data = oldnp->data;
4371 newnp->from = &(array.ht[h]);
4372 array.ht[h] = newnp;
4373 }
4374 free(x1a->tbl);
4375 *x1a = array;
4376 }
4377 /* Insert the new data */
4378 h = ph & (x1a->size-1);
4379 np = &(x1a->tbl[x1a->count++]);
4380 np->data = data;
4381 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4382 np->next = x1a->ht[h];
4383 x1a->ht[h] = np;
4384 np->from = &(x1a->ht[h]);
4385 return 1;
4386}
4387
4388/* Return a pointer to data assigned to the given key. Return NULL
4389** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004390const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004391{
4392 int h;
4393 x1node *np;
4394
4395 if( x1a==0 ) return 0;
4396 h = strhash(key) & (x1a->size-1);
4397 np = x1a->ht[h];
4398 while( np ){
4399 if( strcmp(np->data,key)==0 ) break;
4400 np = np->next;
4401 }
4402 return np ? np->data : 0;
4403}
4404
4405/* Return a pointer to the (terminal or nonterminal) symbol "x".
4406** Create a new symbol if this is the first time "x" has been seen.
4407*/
icculus9e44cf12010-02-14 17:14:22 +00004408struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004409{
4410 struct symbol *sp;
4411
4412 sp = Symbol_find(x);
4413 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004414 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004415 MemoryCheck(sp);
4416 sp->name = Strsafe(x);
4417 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4418 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004419 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004420 sp->prec = -1;
4421 sp->assoc = UNK;
4422 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004423 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004424 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004425 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004426 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004427 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004428 Symbol_insert(sp,sp->name);
4429 }
drhc4dd3fd2008-01-22 01:48:05 +00004430 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004431 return sp;
4432}
4433
drh60d31652004-02-22 00:08:04 +00004434/* Compare two symbols for working purposes
4435**
4436** Symbols that begin with upper case letters (terminals or tokens)
4437** must sort before symbols that begin with lower case letters
4438** (non-terminals). Other than that, the order does not matter.
4439**
4440** We find experimentally that leaving the symbols in their original
4441** order (the order they appeared in the grammar file) gives the
4442** smallest parser tables in SQLite.
4443*/
icculus9e44cf12010-02-14 17:14:22 +00004444int Symbolcmpp(const void *_a, const void *_b)
4445{
4446 const struct symbol **a = (const struct symbol **) _a;
4447 const struct symbol **b = (const struct symbol **) _b;
drh60d31652004-02-22 00:08:04 +00004448 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4449 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004450 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004451 return i1-i2;
drh75897232000-05-29 14:26:00 +00004452}
4453
4454/* There is one instance of the following structure for each
4455** associative array of type "x2".
4456*/
4457struct s_x2 {
4458 int size; /* The number of available slots. */
4459 /* Must be a power of 2 greater than or */
4460 /* equal to 1 */
4461 int count; /* Number of currently slots filled */
4462 struct s_x2node *tbl; /* The data stored here */
4463 struct s_x2node **ht; /* Hash table for lookups */
4464};
4465
4466/* There is one instance of this structure for every data element
4467** in an associative array of type "x2".
4468*/
4469typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004470 struct symbol *data; /* The data */
4471 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004472 struct s_x2node *next; /* Next entry with the same hash */
4473 struct s_x2node **from; /* Previous link */
4474} x2node;
4475
4476/* There is only one instance of the array, which is the following */
4477static struct s_x2 *x2a;
4478
4479/* Allocate a new associative array */
4480void Symbol_init(){
4481 if( x2a ) return;
4482 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4483 if( x2a ){
4484 x2a->size = 128;
4485 x2a->count = 0;
4486 x2a->tbl = (x2node*)malloc(
4487 (sizeof(x2node) + sizeof(x2node*))*128 );
4488 if( x2a->tbl==0 ){
4489 free(x2a);
4490 x2a = 0;
4491 }else{
4492 int i;
4493 x2a->ht = (x2node**)&(x2a->tbl[128]);
4494 for(i=0; i<128; i++) x2a->ht[i] = 0;
4495 }
4496 }
4497}
4498/* Insert a new record into the array. Return TRUE if successful.
4499** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004500int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004501{
4502 x2node *np;
4503 int h;
4504 int ph;
4505
4506 if( x2a==0 ) return 0;
4507 ph = strhash(key);
4508 h = ph & (x2a->size-1);
4509 np = x2a->ht[h];
4510 while( np ){
4511 if( strcmp(np->key,key)==0 ){
4512 /* An existing entry with the same key is found. */
4513 /* Fail because overwrite is not allows. */
4514 return 0;
4515 }
4516 np = np->next;
4517 }
4518 if( x2a->count>=x2a->size ){
4519 /* Need to make the hash table bigger */
4520 int i,size;
4521 struct s_x2 array;
4522 array.size = size = x2a->size*2;
4523 array.count = x2a->count;
4524 array.tbl = (x2node*)malloc(
4525 (sizeof(x2node) + sizeof(x2node*))*size );
4526 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4527 array.ht = (x2node**)&(array.tbl[size]);
4528 for(i=0; i<size; i++) array.ht[i] = 0;
4529 for(i=0; i<x2a->count; i++){
4530 x2node *oldnp, *newnp;
4531 oldnp = &(x2a->tbl[i]);
4532 h = strhash(oldnp->key) & (size-1);
4533 newnp = &(array.tbl[i]);
4534 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4535 newnp->next = array.ht[h];
4536 newnp->key = oldnp->key;
4537 newnp->data = oldnp->data;
4538 newnp->from = &(array.ht[h]);
4539 array.ht[h] = newnp;
4540 }
4541 free(x2a->tbl);
4542 *x2a = array;
4543 }
4544 /* Insert the new data */
4545 h = ph & (x2a->size-1);
4546 np = &(x2a->tbl[x2a->count++]);
4547 np->key = key;
4548 np->data = data;
4549 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4550 np->next = x2a->ht[h];
4551 x2a->ht[h] = np;
4552 np->from = &(x2a->ht[h]);
4553 return 1;
4554}
4555
4556/* Return a pointer to data assigned to the given key. Return NULL
4557** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004558struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004559{
4560 int h;
4561 x2node *np;
4562
4563 if( x2a==0 ) return 0;
4564 h = strhash(key) & (x2a->size-1);
4565 np = x2a->ht[h];
4566 while( np ){
4567 if( strcmp(np->key,key)==0 ) break;
4568 np = np->next;
4569 }
4570 return np ? np->data : 0;
4571}
4572
4573/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004574struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004575{
4576 struct symbol *data;
4577 if( x2a && n>0 && n<=x2a->count ){
4578 data = x2a->tbl[n-1].data;
4579 }else{
4580 data = 0;
4581 }
4582 return data;
4583}
4584
4585/* Return the size of the array */
4586int Symbol_count()
4587{
4588 return x2a ? x2a->count : 0;
4589}
4590
4591/* Return an array of pointers to all data in the table.
4592** The array is obtained from malloc. Return NULL if memory allocation
4593** problems, or if the array is empty. */
4594struct symbol **Symbol_arrayof()
4595{
4596 struct symbol **array;
4597 int i,size;
4598 if( x2a==0 ) return 0;
4599 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004600 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004601 if( array ){
4602 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4603 }
4604 return array;
4605}
4606
4607/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004608int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004609{
icculus9e44cf12010-02-14 17:14:22 +00004610 const struct config *a = (struct config *) _a;
4611 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004612 int x;
4613 x = a->rp->index - b->rp->index;
4614 if( x==0 ) x = a->dot - b->dot;
4615 return x;
4616}
4617
4618/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004619PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004620{
4621 int rc;
4622 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4623 rc = a->rp->index - b->rp->index;
4624 if( rc==0 ) rc = a->dot - b->dot;
4625 }
4626 if( rc==0 ){
4627 if( a ) rc = 1;
4628 if( b ) rc = -1;
4629 }
4630 return rc;
4631}
4632
4633/* Hash a state */
icculus9e44cf12010-02-14 17:14:22 +00004634PRIVATE int statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004635{
4636 int h=0;
4637 while( a ){
4638 h = h*571 + a->rp->index*37 + a->dot;
4639 a = a->bp;
4640 }
4641 return h;
4642}
4643
4644/* Allocate a new state structure */
4645struct state *State_new()
4646{
icculus9e44cf12010-02-14 17:14:22 +00004647 struct state *newstate;
4648 newstate = (struct state *)calloc(1, sizeof(struct state) );
4649 MemoryCheck(newstate);
4650 return newstate;
drh75897232000-05-29 14:26:00 +00004651}
4652
4653/* There is one instance of the following structure for each
4654** associative array of type "x3".
4655*/
4656struct s_x3 {
4657 int size; /* The number of available slots. */
4658 /* Must be a power of 2 greater than or */
4659 /* equal to 1 */
4660 int count; /* Number of currently slots filled */
4661 struct s_x3node *tbl; /* The data stored here */
4662 struct s_x3node **ht; /* Hash table for lookups */
4663};
4664
4665/* There is one instance of this structure for every data element
4666** in an associative array of type "x3".
4667*/
4668typedef struct s_x3node {
4669 struct state *data; /* The data */
4670 struct config *key; /* The key */
4671 struct s_x3node *next; /* Next entry with the same hash */
4672 struct s_x3node **from; /* Previous link */
4673} x3node;
4674
4675/* There is only one instance of the array, which is the following */
4676static struct s_x3 *x3a;
4677
4678/* Allocate a new associative array */
4679void State_init(){
4680 if( x3a ) return;
4681 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4682 if( x3a ){
4683 x3a->size = 128;
4684 x3a->count = 0;
4685 x3a->tbl = (x3node*)malloc(
4686 (sizeof(x3node) + sizeof(x3node*))*128 );
4687 if( x3a->tbl==0 ){
4688 free(x3a);
4689 x3a = 0;
4690 }else{
4691 int i;
4692 x3a->ht = (x3node**)&(x3a->tbl[128]);
4693 for(i=0; i<128; i++) x3a->ht[i] = 0;
4694 }
4695 }
4696}
4697/* Insert a new record into the array. Return TRUE if successful.
4698** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004699int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004700{
4701 x3node *np;
4702 int h;
4703 int ph;
4704
4705 if( x3a==0 ) return 0;
4706 ph = statehash(key);
4707 h = ph & (x3a->size-1);
4708 np = x3a->ht[h];
4709 while( np ){
4710 if( statecmp(np->key,key)==0 ){
4711 /* An existing entry with the same key is found. */
4712 /* Fail because overwrite is not allows. */
4713 return 0;
4714 }
4715 np = np->next;
4716 }
4717 if( x3a->count>=x3a->size ){
4718 /* Need to make the hash table bigger */
4719 int i,size;
4720 struct s_x3 array;
4721 array.size = size = x3a->size*2;
4722 array.count = x3a->count;
4723 array.tbl = (x3node*)malloc(
4724 (sizeof(x3node) + sizeof(x3node*))*size );
4725 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4726 array.ht = (x3node**)&(array.tbl[size]);
4727 for(i=0; i<size; i++) array.ht[i] = 0;
4728 for(i=0; i<x3a->count; i++){
4729 x3node *oldnp, *newnp;
4730 oldnp = &(x3a->tbl[i]);
4731 h = statehash(oldnp->key) & (size-1);
4732 newnp = &(array.tbl[i]);
4733 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4734 newnp->next = array.ht[h];
4735 newnp->key = oldnp->key;
4736 newnp->data = oldnp->data;
4737 newnp->from = &(array.ht[h]);
4738 array.ht[h] = newnp;
4739 }
4740 free(x3a->tbl);
4741 *x3a = array;
4742 }
4743 /* Insert the new data */
4744 h = ph & (x3a->size-1);
4745 np = &(x3a->tbl[x3a->count++]);
4746 np->key = key;
4747 np->data = data;
4748 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4749 np->next = x3a->ht[h];
4750 x3a->ht[h] = np;
4751 np->from = &(x3a->ht[h]);
4752 return 1;
4753}
4754
4755/* Return a pointer to data assigned to the given key. Return NULL
4756** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004757struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004758{
4759 int h;
4760 x3node *np;
4761
4762 if( x3a==0 ) return 0;
4763 h = statehash(key) & (x3a->size-1);
4764 np = x3a->ht[h];
4765 while( np ){
4766 if( statecmp(np->key,key)==0 ) break;
4767 np = np->next;
4768 }
4769 return np ? np->data : 0;
4770}
4771
4772/* Return an array of pointers to all data in the table.
4773** The array is obtained from malloc. Return NULL if memory allocation
4774** problems, or if the array is empty. */
4775struct state **State_arrayof()
4776{
4777 struct state **array;
4778 int i,size;
4779 if( x3a==0 ) return 0;
4780 size = x3a->count;
4781 array = (struct state **)malloc( sizeof(struct state *)*size );
4782 if( array ){
4783 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4784 }
4785 return array;
4786}
4787
4788/* Hash a configuration */
icculus9e44cf12010-02-14 17:14:22 +00004789PRIVATE int confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004790{
4791 int h=0;
4792 h = h*571 + a->rp->index*37 + a->dot;
4793 return h;
4794}
4795
4796/* There is one instance of the following structure for each
4797** associative array of type "x4".
4798*/
4799struct s_x4 {
4800 int size; /* The number of available slots. */
4801 /* Must be a power of 2 greater than or */
4802 /* equal to 1 */
4803 int count; /* Number of currently slots filled */
4804 struct s_x4node *tbl; /* The data stored here */
4805 struct s_x4node **ht; /* Hash table for lookups */
4806};
4807
4808/* There is one instance of this structure for every data element
4809** in an associative array of type "x4".
4810*/
4811typedef struct s_x4node {
4812 struct config *data; /* The data */
4813 struct s_x4node *next; /* Next entry with the same hash */
4814 struct s_x4node **from; /* Previous link */
4815} x4node;
4816
4817/* There is only one instance of the array, which is the following */
4818static struct s_x4 *x4a;
4819
4820/* Allocate a new associative array */
4821void Configtable_init(){
4822 if( x4a ) return;
4823 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4824 if( x4a ){
4825 x4a->size = 64;
4826 x4a->count = 0;
4827 x4a->tbl = (x4node*)malloc(
4828 (sizeof(x4node) + sizeof(x4node*))*64 );
4829 if( x4a->tbl==0 ){
4830 free(x4a);
4831 x4a = 0;
4832 }else{
4833 int i;
4834 x4a->ht = (x4node**)&(x4a->tbl[64]);
4835 for(i=0; i<64; i++) x4a->ht[i] = 0;
4836 }
4837 }
4838}
4839/* Insert a new record into the array. Return TRUE if successful.
4840** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004841int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00004842{
4843 x4node *np;
4844 int h;
4845 int ph;
4846
4847 if( x4a==0 ) return 0;
4848 ph = confighash(data);
4849 h = ph & (x4a->size-1);
4850 np = x4a->ht[h];
4851 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004852 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00004853 /* An existing entry with the same key is found. */
4854 /* Fail because overwrite is not allows. */
4855 return 0;
4856 }
4857 np = np->next;
4858 }
4859 if( x4a->count>=x4a->size ){
4860 /* Need to make the hash table bigger */
4861 int i,size;
4862 struct s_x4 array;
4863 array.size = size = x4a->size*2;
4864 array.count = x4a->count;
4865 array.tbl = (x4node*)malloc(
4866 (sizeof(x4node) + sizeof(x4node*))*size );
4867 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4868 array.ht = (x4node**)&(array.tbl[size]);
4869 for(i=0; i<size; i++) array.ht[i] = 0;
4870 for(i=0; i<x4a->count; i++){
4871 x4node *oldnp, *newnp;
4872 oldnp = &(x4a->tbl[i]);
4873 h = confighash(oldnp->data) & (size-1);
4874 newnp = &(array.tbl[i]);
4875 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4876 newnp->next = array.ht[h];
4877 newnp->data = oldnp->data;
4878 newnp->from = &(array.ht[h]);
4879 array.ht[h] = newnp;
4880 }
4881 free(x4a->tbl);
4882 *x4a = array;
4883 }
4884 /* Insert the new data */
4885 h = ph & (x4a->size-1);
4886 np = &(x4a->tbl[x4a->count++]);
4887 np->data = data;
4888 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4889 np->next = x4a->ht[h];
4890 x4a->ht[h] = np;
4891 np->from = &(x4a->ht[h]);
4892 return 1;
4893}
4894
4895/* Return a pointer to data assigned to the given key. Return NULL
4896** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004897struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004898{
4899 int h;
4900 x4node *np;
4901
4902 if( x4a==0 ) return 0;
4903 h = confighash(key) & (x4a->size-1);
4904 np = x4a->ht[h];
4905 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004906 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00004907 np = np->next;
4908 }
4909 return np ? np->data : 0;
4910}
4911
4912/* Remove all data from the table. Pass each data to the function "f"
4913** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00004914void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00004915{
4916 int i;
4917 if( x4a==0 || x4a->count==0 ) return;
4918 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4919 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4920 x4a->count = 0;
4921 return;
4922}