blob: 6d8b220ea097a01a8a2b993ccc6bee8755490efa [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
drhf5c4e0f2010-07-18 11:35:53 +000037static int showPrecedenceConflict = 0;
icculusf5ad8242010-02-14 05:34:42 +000038static const char **made_files = NULL;
39static int made_files_count = 0;
40static int successful_exit = 0;
41static void LemonAtExit(void)
42{
43 /* if we failed, delete (most) files we made, to unconfuse build tools. */
44 int i;
45 for (i = 0; i < made_files_count; i++) {
46 if (!successful_exit) {
47 remove(made_files[i]);
48 }
icculusf5ad8242010-02-14 05:34:42 +000049 }
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 */
300 int tablesize; /* Size of the parse tables */
301 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000302 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000303 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000304 char *argv0; /* Name of the program */
305};
306
307#define MemoryCheck(X) if((X)==0){ \
308 extern void memory_error(); \
309 memory_error(); \
310}
311
312/**************** From the file "table.h" *********************************/
313/*
314** All code in this file has been automatically generated
315** from a specification in the file
316** "table.q"
317** by the associative array code building program "aagen".
318** Do not edit this file! Instead, edit the specification
319** file, then rerun aagen.
320*/
321/*
322** Code for processing tables in the LEMON parser generator.
323*/
drh75897232000-05-29 14:26:00 +0000324/* Routines for handling a strings */
325
icculus9e44cf12010-02-14 17:14:22 +0000326const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000327
icculus9e44cf12010-02-14 17:14:22 +0000328void Strsafe_init(void);
329int Strsafe_insert(const char *);
330const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000331
332/* Routines for handling symbols of the grammar */
333
icculus9e44cf12010-02-14 17:14:22 +0000334struct symbol *Symbol_new(const char *);
335int Symbolcmpp(const void *, const void *);
336void Symbol_init(void);
337int Symbol_insert(struct symbol *, const char *);
338struct symbol *Symbol_find(const char *);
339struct symbol *Symbol_Nth(int);
340int Symbol_count(void);
341struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000342
343/* Routines to manage the state table */
344
icculus9e44cf12010-02-14 17:14:22 +0000345int Configcmp(const char *, const char *);
346struct state *State_new(void);
347void State_init(void);
348int State_insert(struct state *, struct config *);
349struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000350struct state **State_arrayof(/* */);
351
352/* Routines used for efficiency in Configlist_add */
353
icculus9e44cf12010-02-14 17:14:22 +0000354void Configtable_init(void);
355int Configtable_insert(struct config *);
356struct config *Configtable_find(struct config *);
357void Configtable_clear(int(*)(struct config *));
358
drh75897232000-05-29 14:26:00 +0000359/****************** From the file "action.c" *******************************/
360/*
361** Routines processing parser actions in the LEMON parser generator.
362*/
363
364/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000365static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000366 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000367 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000368
369 if( freelist==0 ){
370 int i;
371 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000372 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000373 if( freelist==0 ){
374 fprintf(stderr,"Unable to allocate memory for a new parser action.");
375 exit(1);
376 }
377 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
378 freelist[amt-1].next = 0;
379 }
icculus9e44cf12010-02-14 17:14:22 +0000380 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000381 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000382 return newaction;
drh75897232000-05-29 14:26:00 +0000383}
384
drhe9278182007-07-18 18:16:29 +0000385/* Compare two actions for sorting purposes. Return negative, zero, or
386** positive if the first action is less than, equal to, or greater than
387** the first
388*/
389static int actioncmp(
390 struct action *ap1,
391 struct action *ap2
392){
drh75897232000-05-29 14:26:00 +0000393 int rc;
394 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000395 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000396 rc = (int)ap1->type - (int)ap2->type;
397 }
398 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000399 rc = ap1->x.rp->index - ap2->x.rp->index;
400 }
drhe594bc32009-11-03 13:02:25 +0000401 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000402 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000403 }
drh75897232000-05-29 14:26:00 +0000404 return rc;
405}
406
407/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000408static struct action *Action_sort(
409 struct action *ap
410){
411 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
412 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000413 return ap;
414}
415
icculus9e44cf12010-02-14 17:14:22 +0000416void Action_add(
417 struct action **app,
418 enum e_action type,
419 struct symbol *sp,
420 char *arg
421){
422 struct action *newaction;
423 newaction = Action_new();
424 newaction->next = *app;
425 *app = newaction;
426 newaction->type = type;
427 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000428 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000429 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000430 }else{
icculus9e44cf12010-02-14 17:14:22 +0000431 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000432 }
433}
drh8b582012003-10-21 13:16:03 +0000434/********************** New code to implement the "acttab" module ***********/
435/*
436** This module implements routines use to construct the yy_action[] table.
437*/
438
439/*
440** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000441** the following structure.
442**
443** The yy_action table maps the pair (state_number, lookahead) into an
444** action_number. The table is an array of integers pairs. The state_number
445** determines an initial offset into the yy_action array. The lookahead
446** value is then added to this initial offset to get an index X into the
447** yy_action array. If the aAction[X].lookahead equals the value of the
448** of the lookahead input, then the value of the action_number output is
449** aAction[X].action. If the lookaheads do not match then the
450** default action for the state_number is returned.
451**
452** All actions associated with a single state_number are first entered
453** into aLookahead[] using multiple calls to acttab_action(). Then the
454** actions for that single state_number are placed into the aAction[]
455** array with a single call to acttab_insert(). The acttab_insert() call
456** also resets the aLookahead[] array in preparation for the next
457** state number.
drh8b582012003-10-21 13:16:03 +0000458*/
icculus9e44cf12010-02-14 17:14:22 +0000459struct lookahead_action {
460 int lookahead; /* Value of the lookahead token */
461 int action; /* Action to take on the given lookahead */
462};
drh8b582012003-10-21 13:16:03 +0000463typedef struct acttab acttab;
464struct acttab {
465 int nAction; /* Number of used slots in aAction[] */
466 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000467 struct lookahead_action
468 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000469 *aLookahead; /* A single new transaction set */
470 int mnLookahead; /* Minimum aLookahead[].lookahead */
471 int mnAction; /* Action associated with mnLookahead */
472 int mxLookahead; /* Maximum aLookahead[].lookahead */
473 int nLookahead; /* Used slots in aLookahead[] */
474 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
475};
476
477/* Return the number of entries in the yy_action table */
478#define acttab_size(X) ((X)->nAction)
479
480/* The value for the N-th entry in yy_action */
481#define acttab_yyaction(X,N) ((X)->aAction[N].action)
482
483/* The value for the N-th entry in yy_lookahead */
484#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
485
486/* Free all memory associated with the given acttab */
487void acttab_free(acttab *p){
488 free( p->aAction );
489 free( p->aLookahead );
490 free( p );
491}
492
493/* Allocate a new acttab structure */
494acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000495 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000496 if( p==0 ){
497 fprintf(stderr,"Unable to allocate memory for a new acttab.");
498 exit(1);
499 }
500 memset(p, 0, sizeof(*p));
501 return p;
502}
503
drh8dc3e8f2010-01-07 03:53:03 +0000504/* Add a new action to the current transaction set.
505**
506** This routine is called once for each lookahead for a particular
507** state.
drh8b582012003-10-21 13:16:03 +0000508*/
509void acttab_action(acttab *p, int lookahead, int action){
510 if( p->nLookahead>=p->nLookaheadAlloc ){
511 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000512 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000513 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
514 if( p->aLookahead==0 ){
515 fprintf(stderr,"malloc failed\n");
516 exit(1);
517 }
518 }
519 if( p->nLookahead==0 ){
520 p->mxLookahead = lookahead;
521 p->mnLookahead = lookahead;
522 p->mnAction = action;
523 }else{
524 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
525 if( p->mnLookahead>lookahead ){
526 p->mnLookahead = lookahead;
527 p->mnAction = action;
528 }
529 }
530 p->aLookahead[p->nLookahead].lookahead = lookahead;
531 p->aLookahead[p->nLookahead].action = action;
532 p->nLookahead++;
533}
534
535/*
536** Add the transaction set built up with prior calls to acttab_action()
537** into the current action table. Then reset the transaction set back
538** to an empty set in preparation for a new round of acttab_action() calls.
539**
540** Return the offset into the action table of the new transaction.
541*/
542int acttab_insert(acttab *p){
543 int i, j, k, n;
544 assert( p->nLookahead>0 );
545
546 /* Make sure we have enough space to hold the expanded action table
547 ** in the worst case. The worst case occurs if the transaction set
548 ** must be appended to the current action table
549 */
drh784d86f2004-02-19 18:41:53 +0000550 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000551 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000552 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000553 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000554 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000555 sizeof(p->aAction[0])*p->nActionAlloc);
556 if( p->aAction==0 ){
557 fprintf(stderr,"malloc failed\n");
558 exit(1);
559 }
drhfdbf9282003-10-21 16:34:41 +0000560 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000561 p->aAction[i].lookahead = -1;
562 p->aAction[i].action = -1;
563 }
564 }
565
drh8dc3e8f2010-01-07 03:53:03 +0000566 /* Scan the existing action table looking for an offset that is a
567 ** duplicate of the current transaction set. Fall out of the loop
568 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000569 **
570 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
571 */
drh8dc3e8f2010-01-07 03:53:03 +0000572 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000573 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000574 /* All lookaheads and actions in the aLookahead[] transaction
575 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000576 if( p->aAction[i].action!=p->mnAction ) continue;
577 for(j=0; j<p->nLookahead; j++){
578 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
579 if( k<0 || k>=p->nAction ) break;
580 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
581 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
582 }
583 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000584
585 /* No possible lookahead value that is not in the aLookahead[]
586 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000587 n = 0;
588 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000589 if( p->aAction[j].lookahead<0 ) continue;
590 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000591 }
drhfdbf9282003-10-21 16:34:41 +0000592 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000593 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000594 }
drh8b582012003-10-21 13:16:03 +0000595 }
596 }
drh8dc3e8f2010-01-07 03:53:03 +0000597
598 /* If no existing offsets exactly match the current transaction, find an
599 ** an empty offset in the aAction[] table in which we can add the
600 ** aLookahead[] transaction.
601 */
drhf16371d2009-11-03 19:18:31 +0000602 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000603 /* Look for holes in the aAction[] table that fit the current
604 ** aLookahead[] transaction. Leave i set to the offset of the hole.
605 ** If no holes are found, i is left at p->nAction, which means the
606 ** transaction will be appended. */
607 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000608 if( p->aAction[i].lookahead<0 ){
609 for(j=0; j<p->nLookahead; j++){
610 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
611 if( k<0 ) break;
612 if( p->aAction[k].lookahead>=0 ) break;
613 }
614 if( j<p->nLookahead ) continue;
615 for(j=0; j<p->nAction; j++){
616 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
617 }
618 if( j==p->nAction ){
619 break; /* Fits in empty slots */
620 }
621 }
622 }
623 }
drh8b582012003-10-21 13:16:03 +0000624 /* Insert transaction set at index i. */
625 for(j=0; j<p->nLookahead; j++){
626 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
627 p->aAction[k] = p->aLookahead[j];
628 if( k>=p->nAction ) p->nAction = k+1;
629 }
630 p->nLookahead = 0;
631
632 /* Return the offset that is added to the lookahead in order to get the
633 ** index into yy_action of the action */
634 return i - p->mnLookahead;
635}
636
drh75897232000-05-29 14:26:00 +0000637/********************** From the file "build.c" *****************************/
638/*
639** Routines to construction the finite state machine for the LEMON
640** parser generator.
641*/
642
643/* Find a precedence symbol of every rule in the grammar.
644**
645** Those rules which have a precedence symbol coded in the input
646** grammar using the "[symbol]" construct will already have the
647** rp->precsym field filled. Other rules take as their precedence
648** symbol the first RHS symbol with a defined precedence. If there
649** are not RHS symbols with a defined precedence, the precedence
650** symbol field is left blank.
651*/
icculus9e44cf12010-02-14 17:14:22 +0000652void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000653{
654 struct rule *rp;
655 for(rp=xp->rule; rp; rp=rp->next){
656 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000657 int i, j;
658 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
659 struct symbol *sp = rp->rhs[i];
660 if( sp->type==MULTITERMINAL ){
661 for(j=0; j<sp->nsubsym; j++){
662 if( sp->subsym[j]->prec>=0 ){
663 rp->precsym = sp->subsym[j];
664 break;
665 }
666 }
667 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000668 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000669 }
670 }
671 }
672 }
673 return;
674}
675
676/* Find all nonterminals which will generate the empty string.
677** Then go back and compute the first sets of every nonterminal.
678** The first set is the set of all terminal symbols which can begin
679** a string generated by that nonterminal.
680*/
icculus9e44cf12010-02-14 17:14:22 +0000681void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000682{
drhfd405312005-11-06 04:06:59 +0000683 int i, j;
drh75897232000-05-29 14:26:00 +0000684 struct rule *rp;
685 int progress;
686
687 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000688 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000689 }
690 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
691 lemp->symbols[i]->firstset = SetNew();
692 }
693
694 /* First compute all lambdas */
695 do{
696 progress = 0;
697 for(rp=lemp->rule; rp; rp=rp->next){
698 if( rp->lhs->lambda ) continue;
699 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000700 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000701 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000702 }
703 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000704 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000705 progress = 1;
706 }
707 }
708 }while( progress );
709
710 /* Now compute all first sets */
711 do{
712 struct symbol *s1, *s2;
713 progress = 0;
714 for(rp=lemp->rule; rp; rp=rp->next){
715 s1 = rp->lhs;
716 for(i=0; i<rp->nrhs; i++){
717 s2 = rp->rhs[i];
718 if( s2->type==TERMINAL ){
719 progress += SetAdd(s1->firstset,s2->index);
720 break;
drhfd405312005-11-06 04:06:59 +0000721 }else if( s2->type==MULTITERMINAL ){
722 for(j=0; j<s2->nsubsym; j++){
723 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
724 }
725 break;
drh75897232000-05-29 14:26:00 +0000726 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000727 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000728 }else{
729 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000730 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000731 }
732 }
733 }
734 }while( progress );
735 return;
736}
737
738/* Compute all LR(0) states for the grammar. Links
739** are added to between some states so that the LR(1) follow sets
740** can be computed later.
741*/
icculus9e44cf12010-02-14 17:14:22 +0000742PRIVATE struct state *getstate(struct lemon *); /* forward reference */
743void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000744{
745 struct symbol *sp;
746 struct rule *rp;
747
748 Configlist_init();
749
750 /* Find the start symbol */
751 if( lemp->start ){
752 sp = Symbol_find(lemp->start);
753 if( sp==0 ){
754 ErrorMsg(lemp->filename,0,
755"The specified start symbol \"%s\" is not \
756in a nonterminal of the grammar. \"%s\" will be used as the start \
757symbol instead.",lemp->start,lemp->rule->lhs->name);
758 lemp->errorcnt++;
759 sp = lemp->rule->lhs;
760 }
761 }else{
762 sp = lemp->rule->lhs;
763 }
764
765 /* Make sure the start symbol doesn't occur on the right-hand side of
766 ** any rule. Report an error if it does. (YACC would generate a new
767 ** start symbol in this case.) */
768 for(rp=lemp->rule; rp; rp=rp->next){
769 int i;
770 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000771 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000772 ErrorMsg(lemp->filename,0,
773"The start symbol \"%s\" occurs on the \
774right-hand side of a rule. This will result in a parser which \
775does not work properly.",sp->name);
776 lemp->errorcnt++;
777 }
778 }
779 }
780
781 /* The basis configuration set for the first state
782 ** is all rules which have the start symbol as their
783 ** left-hand side */
784 for(rp=sp->rule; rp; rp=rp->nextlhs){
785 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000786 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000787 newcfp = Configlist_addbasis(rp,0);
788 SetAdd(newcfp->fws,0);
789 }
790
791 /* Compute the first state. All other states will be
792 ** computed automatically during the computation of the first one.
793 ** The returned pointer to the first state is not used. */
794 (void)getstate(lemp);
795 return;
796}
797
798/* Return a pointer to a state which is described by the configuration
799** list which has been built from calls to Configlist_add.
800*/
icculus9e44cf12010-02-14 17:14:22 +0000801PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
802PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000803{
804 struct config *cfp, *bp;
805 struct state *stp;
806
807 /* Extract the sorted basis of the new state. The basis was constructed
808 ** by prior calls to "Configlist_addbasis()". */
809 Configlist_sortbasis();
810 bp = Configlist_basis();
811
812 /* Get a state with the same basis */
813 stp = State_find(bp);
814 if( stp ){
815 /* A state with the same basis already exists! Copy all the follow-set
816 ** propagation links from the state under construction into the
817 ** preexisting state, then return a pointer to the preexisting state */
818 struct config *x, *y;
819 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
820 Plink_copy(&y->bplp,x->bplp);
821 Plink_delete(x->fplp);
822 x->fplp = x->bplp = 0;
823 }
824 cfp = Configlist_return();
825 Configlist_eat(cfp);
826 }else{
827 /* This really is a new state. Construct all the details */
828 Configlist_closure(lemp); /* Compute the configuration closure */
829 Configlist_sort(); /* Sort the configuration closure */
830 cfp = Configlist_return(); /* Get a pointer to the config list */
831 stp = State_new(); /* A new state structure */
832 MemoryCheck(stp);
833 stp->bp = bp; /* Remember the configuration basis */
834 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000835 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000836 stp->ap = 0; /* No actions, yet. */
837 State_insert(stp,stp->bp); /* Add to the state table */
838 buildshifts(lemp,stp); /* Recursively compute successor states */
839 }
840 return stp;
841}
842
drhfd405312005-11-06 04:06:59 +0000843/*
844** Return true if two symbols are the same.
845*/
icculus9e44cf12010-02-14 17:14:22 +0000846int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000847{
848 int i;
849 if( a==b ) return 1;
850 if( a->type!=MULTITERMINAL ) return 0;
851 if( b->type!=MULTITERMINAL ) return 0;
852 if( a->nsubsym!=b->nsubsym ) return 0;
853 for(i=0; i<a->nsubsym; i++){
854 if( a->subsym[i]!=b->subsym[i] ) return 0;
855 }
856 return 1;
857}
858
drh75897232000-05-29 14:26:00 +0000859/* Construct all successor states to the given state. A "successor"
860** state is any state which can be reached by a shift action.
861*/
icculus9e44cf12010-02-14 17:14:22 +0000862PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000863{
864 struct config *cfp; /* For looping thru the config closure of "stp" */
865 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000866 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000867 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
868 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
869 struct state *newstp; /* A pointer to a successor state */
870
871 /* Each configuration becomes complete after it contibutes to a successor
872 ** state. Initially, all configurations are incomplete */
873 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
874
875 /* Loop through all configurations of the state "stp" */
876 for(cfp=stp->cfp; cfp; cfp=cfp->next){
877 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
878 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
879 Configlist_reset(); /* Reset the new config set */
880 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
881
882 /* For every configuration in the state "stp" which has the symbol "sp"
883 ** following its dot, add the same configuration to the basis set under
884 ** construction but with the dot shifted one symbol to the right. */
885 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
886 if( bcfp->status==COMPLETE ) continue; /* Already used */
887 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
888 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000889 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000890 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000891 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
892 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000893 }
894
895 /* Get a pointer to the state described by the basis configuration set
896 ** constructed in the preceding loop */
897 newstp = getstate(lemp);
898
899 /* The state "newstp" is reached from the state "stp" by a shift action
900 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000901 if( sp->type==MULTITERMINAL ){
902 int i;
903 for(i=0; i<sp->nsubsym; i++){
904 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
905 }
906 }else{
907 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
908 }
drh75897232000-05-29 14:26:00 +0000909 }
910}
911
912/*
913** Construct the propagation links
914*/
icculus9e44cf12010-02-14 17:14:22 +0000915void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000916{
917 int i;
918 struct config *cfp, *other;
919 struct state *stp;
920 struct plink *plp;
921
922 /* Housekeeping detail:
923 ** Add to every propagate link a pointer back to the state to
924 ** which the link is attached. */
925 for(i=0; i<lemp->nstate; i++){
926 stp = lemp->sorted[i];
927 for(cfp=stp->cfp; cfp; cfp=cfp->next){
928 cfp->stp = stp;
929 }
930 }
931
932 /* Convert all backlinks into forward links. Only the forward
933 ** links are used in the follow-set computation. */
934 for(i=0; i<lemp->nstate; i++){
935 stp = lemp->sorted[i];
936 for(cfp=stp->cfp; cfp; cfp=cfp->next){
937 for(plp=cfp->bplp; plp; plp=plp->next){
938 other = plp->cfp;
939 Plink_add(&other->fplp,cfp);
940 }
941 }
942 }
943}
944
945/* Compute all followsets.
946**
947** A followset is the set of all symbols which can come immediately
948** after a configuration.
949*/
icculus9e44cf12010-02-14 17:14:22 +0000950void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000951{
952 int i;
953 struct config *cfp;
954 struct plink *plp;
955 int progress;
956 int change;
957
958 for(i=0; i<lemp->nstate; i++){
959 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
960 cfp->status = INCOMPLETE;
961 }
962 }
963
964 do{
965 progress = 0;
966 for(i=0; i<lemp->nstate; i++){
967 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
968 if( cfp->status==COMPLETE ) continue;
969 for(plp=cfp->fplp; plp; plp=plp->next){
970 change = SetUnion(plp->cfp->fws,cfp->fws);
971 if( change ){
972 plp->cfp->status = INCOMPLETE;
973 progress = 1;
974 }
975 }
976 cfp->status = COMPLETE;
977 }
978 }
979 }while( progress );
980}
981
icculus9e44cf12010-02-14 17:14:22 +0000982static int resolve_conflict(struct action *,struct action *, struct symbol *);
drh75897232000-05-29 14:26:00 +0000983
984/* Compute the reduce actions, and resolve conflicts.
985*/
icculus9e44cf12010-02-14 17:14:22 +0000986void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000987{
988 int i,j;
989 struct config *cfp;
990 struct state *stp;
991 struct symbol *sp;
992 struct rule *rp;
993
994 /* Add all of the reduce actions
995 ** A reduce action is added for each element of the followset of
996 ** a configuration which has its dot at the extreme right.
997 */
998 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
999 stp = lemp->sorted[i];
1000 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1001 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1002 for(j=0; j<lemp->nterminal; j++){
1003 if( SetFind(cfp->fws,j) ){
1004 /* Add a reduce action to the state "stp" which will reduce by the
1005 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001006 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001007 }
1008 }
1009 }
1010 }
1011 }
1012
1013 /* Add the accepting token */
1014 if( lemp->start ){
1015 sp = Symbol_find(lemp->start);
1016 if( sp==0 ) sp = lemp->rule->lhs;
1017 }else{
1018 sp = lemp->rule->lhs;
1019 }
1020 /* Add to the first state (which is always the starting state of the
1021 ** finite state machine) an action to ACCEPT if the lookahead is the
1022 ** start nonterminal. */
1023 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1024
1025 /* Resolve conflicts */
1026 for(i=0; i<lemp->nstate; i++){
1027 struct action *ap, *nap;
1028 struct state *stp;
1029 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001030 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001031 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001032 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001033 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1034 /* The two actions "ap" and "nap" have the same lookahead.
1035 ** Figure out which one should be used */
1036 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1037 }
1038 }
1039 }
1040
1041 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001042 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001043 for(i=0; i<lemp->nstate; i++){
1044 struct action *ap;
1045 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001046 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001047 }
1048 }
1049 for(rp=lemp->rule; rp; rp=rp->next){
1050 if( rp->canReduce ) continue;
1051 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1052 lemp->errorcnt++;
1053 }
1054}
1055
1056/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001057** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001058**
1059** NO LONGER TRUE:
1060** To resolve a conflict, first look to see if either action
1061** is on an error rule. In that case, take the action which
1062** is not associated with the error rule. If neither or both
1063** actions are associated with an error rule, then try to
1064** use precedence to resolve the conflict.
1065**
1066** If either action is a SHIFT, then it must be apx. This
1067** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1068*/
icculus9e44cf12010-02-14 17:14:22 +00001069static int resolve_conflict(
1070 struct action *apx,
1071 struct action *apy,
1072 struct symbol *errsym /* The error symbol (if defined. NULL otherwise) */
1073){
drh75897232000-05-29 14:26:00 +00001074 struct symbol *spx, *spy;
1075 int errcnt = 0;
1076 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001077 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001078 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001079 errcnt++;
1080 }
drh75897232000-05-29 14:26:00 +00001081 if( apx->type==SHIFT && apy->type==REDUCE ){
1082 spx = apx->sp;
1083 spy = apy->x.rp->precsym;
1084 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1085 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001086 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001087 errcnt++;
1088 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1089 apy->type = RD_RESOLVED;
1090 }else if( spx->prec<spy->prec ){
1091 apx->type = SH_RESOLVED;
1092 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1093 apy->type = RD_RESOLVED; /* associativity */
1094 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1095 apx->type = SH_RESOLVED;
1096 }else{
1097 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001098 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001099 errcnt++;
1100 }
1101 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1102 spx = apx->x.rp->precsym;
1103 spy = apy->x.rp->precsym;
1104 if( spx==0 || spy==0 || spx->prec<0 ||
1105 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001106 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001107 errcnt++;
1108 }else if( spx->prec>spy->prec ){
1109 apy->type = RD_RESOLVED;
1110 }else if( spx->prec<spy->prec ){
1111 apx->type = RD_RESOLVED;
1112 }
1113 }else{
drhb59499c2002-02-23 18:45:13 +00001114 assert(
1115 apx->type==SH_RESOLVED ||
1116 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001117 apx->type==SSCONFLICT ||
1118 apx->type==SRCONFLICT ||
1119 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001120 apy->type==SH_RESOLVED ||
1121 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001122 apy->type==SSCONFLICT ||
1123 apy->type==SRCONFLICT ||
1124 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001125 );
1126 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1127 ** REDUCEs on the list. If we reach this point it must be because
1128 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001129 }
1130 return errcnt;
1131}
1132/********************* From the file "configlist.c" *************************/
1133/*
1134** Routines to processing a configuration list and building a state
1135** in the LEMON parser generator.
1136*/
1137
1138static struct config *freelist = 0; /* List of free configurations */
1139static struct config *current = 0; /* Top of list of configurations */
1140static struct config **currentend = 0; /* Last on list of configs */
1141static struct config *basis = 0; /* Top of list of basis configs */
1142static struct config **basisend = 0; /* End of list of basis configs */
1143
1144/* Return a pointer to a new configuration */
1145PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001146 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001147 if( freelist==0 ){
1148 int i;
1149 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001150 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001151 if( freelist==0 ){
1152 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1153 exit(1);
1154 }
1155 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1156 freelist[amt-1].next = 0;
1157 }
icculus9e44cf12010-02-14 17:14:22 +00001158 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001159 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001160 return newcfg;
drh75897232000-05-29 14:26:00 +00001161}
1162
1163/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001164PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001165{
1166 old->next = freelist;
1167 freelist = old;
1168}
1169
1170/* Initialized the configuration list builder */
1171void Configlist_init(){
1172 current = 0;
1173 currentend = &current;
1174 basis = 0;
1175 basisend = &basis;
1176 Configtable_init();
1177 return;
1178}
1179
1180/* Initialized the configuration list builder */
1181void Configlist_reset(){
1182 current = 0;
1183 currentend = &current;
1184 basis = 0;
1185 basisend = &basis;
1186 Configtable_clear(0);
1187 return;
1188}
1189
1190/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001191struct config *Configlist_add(
1192 struct rule *rp, /* The rule */
1193 int dot /* Index into the RHS of the rule where the dot goes */
1194){
drh75897232000-05-29 14:26:00 +00001195 struct config *cfp, model;
1196
1197 assert( currentend!=0 );
1198 model.rp = rp;
1199 model.dot = dot;
1200 cfp = Configtable_find(&model);
1201 if( cfp==0 ){
1202 cfp = newconfig();
1203 cfp->rp = rp;
1204 cfp->dot = dot;
1205 cfp->fws = SetNew();
1206 cfp->stp = 0;
1207 cfp->fplp = cfp->bplp = 0;
1208 cfp->next = 0;
1209 cfp->bp = 0;
1210 *currentend = cfp;
1211 currentend = &cfp->next;
1212 Configtable_insert(cfp);
1213 }
1214 return cfp;
1215}
1216
1217/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001218struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001219{
1220 struct config *cfp, model;
1221
1222 assert( basisend!=0 );
1223 assert( currentend!=0 );
1224 model.rp = rp;
1225 model.dot = dot;
1226 cfp = Configtable_find(&model);
1227 if( cfp==0 ){
1228 cfp = newconfig();
1229 cfp->rp = rp;
1230 cfp->dot = dot;
1231 cfp->fws = SetNew();
1232 cfp->stp = 0;
1233 cfp->fplp = cfp->bplp = 0;
1234 cfp->next = 0;
1235 cfp->bp = 0;
1236 *currentend = cfp;
1237 currentend = &cfp->next;
1238 *basisend = cfp;
1239 basisend = &cfp->bp;
1240 Configtable_insert(cfp);
1241 }
1242 return cfp;
1243}
1244
1245/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001246void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001247{
1248 struct config *cfp, *newcfp;
1249 struct rule *rp, *newrp;
1250 struct symbol *sp, *xsp;
1251 int i, dot;
1252
1253 assert( currentend!=0 );
1254 for(cfp=current; cfp; cfp=cfp->next){
1255 rp = cfp->rp;
1256 dot = cfp->dot;
1257 if( dot>=rp->nrhs ) continue;
1258 sp = rp->rhs[dot];
1259 if( sp->type==NONTERMINAL ){
1260 if( sp->rule==0 && sp!=lemp->errsym ){
1261 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1262 sp->name);
1263 lemp->errorcnt++;
1264 }
1265 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1266 newcfp = Configlist_add(newrp,0);
1267 for(i=dot+1; i<rp->nrhs; i++){
1268 xsp = rp->rhs[i];
1269 if( xsp->type==TERMINAL ){
1270 SetAdd(newcfp->fws,xsp->index);
1271 break;
drhfd405312005-11-06 04:06:59 +00001272 }else if( xsp->type==MULTITERMINAL ){
1273 int k;
1274 for(k=0; k<xsp->nsubsym; k++){
1275 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1276 }
1277 break;
drh75897232000-05-29 14:26:00 +00001278 }else{
1279 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001280 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001281 }
1282 }
1283 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1284 }
1285 }
1286 }
1287 return;
1288}
1289
1290/* Sort the configuration list */
1291void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001292 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001293 currentend = 0;
1294 return;
1295}
1296
1297/* Sort the basis configuration list */
1298void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001299 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001300 basisend = 0;
1301 return;
1302}
1303
1304/* Return a pointer to the head of the configuration list and
1305** reset the list */
1306struct config *Configlist_return(){
1307 struct config *old;
1308 old = current;
1309 current = 0;
1310 currentend = 0;
1311 return old;
1312}
1313
1314/* Return a pointer to the head of the configuration list and
1315** reset the list */
1316struct config *Configlist_basis(){
1317 struct config *old;
1318 old = basis;
1319 basis = 0;
1320 basisend = 0;
1321 return old;
1322}
1323
1324/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001325void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001326{
1327 struct config *nextcfp;
1328 for(; cfp; cfp=nextcfp){
1329 nextcfp = cfp->next;
1330 assert( cfp->fplp==0 );
1331 assert( cfp->bplp==0 );
1332 if( cfp->fws ) SetFree(cfp->fws);
1333 deleteconfig(cfp);
1334 }
1335 return;
1336}
1337/***************** From the file "error.c" *********************************/
1338/*
1339** Code for printing error message.
1340*/
1341
drhf9a2e7b2003-04-15 01:49:48 +00001342void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001343 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001344 fprintf(stderr, "%s:%d: ", filename, lineno);
1345 va_start(ap, format);
1346 vfprintf(stderr,format,ap);
1347 va_end(ap);
1348 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001349}
1350/**************** From the file "main.c" ************************************/
1351/*
1352** Main program file for the LEMON parser generator.
1353*/
1354
1355/* Report an out-of-memory condition and abort. This function
1356** is used mostly by the "MemoryCheck" macro in struct.h
1357*/
1358void memory_error(){
1359 fprintf(stderr,"Out of memory. Aborting...\n");
1360 exit(1);
1361}
1362
drh6d08b4d2004-07-20 12:45:22 +00001363static int nDefine = 0; /* Number of -D options on the command line */
1364static char **azDefine = 0; /* Name of the -D macros */
1365
1366/* This routine is called with the argument to each -D command-line option.
1367** Add the macro defined to the azDefine array.
1368*/
1369static void handle_D_option(char *z){
1370 char **paz;
1371 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001372 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001373 if( azDefine==0 ){
1374 fprintf(stderr,"out of memory\n");
1375 exit(1);
1376 }
1377 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001378 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001379 if( *paz==0 ){
1380 fprintf(stderr,"out of memory\n");
1381 exit(1);
1382 }
1383 strcpy(*paz, z);
1384 for(z=*paz; *z && *z!='='; z++){}
1385 *z = 0;
1386}
1387
icculus3e143bd2010-02-14 00:48:49 +00001388static char *user_templatename = NULL;
1389static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001390 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001391 if( user_templatename==0 ){
1392 memory_error();
1393 }
1394 strcpy(user_templatename, z);
1395}
drh75897232000-05-29 14:26:00 +00001396
1397/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001398int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001399{
1400 static int version = 0;
1401 static int rpflag = 0;
1402 static int basisflag = 0;
1403 static int compress = 0;
1404 static int quiet = 0;
1405 static int statistics = 0;
1406 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001407 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001408 static struct s_options options[] = {
1409 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1410 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001411 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001412 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001413 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001414 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1415 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drhf5c4e0f2010-07-18 11:35:53 +00001416 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1417 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001418 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001419 {OPT_FLAG, "s", (char*)&statistics,
1420 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001421 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1422 {OPT_FLAG,0,0,0}
1423 };
1424 int i;
icculus42585cf2010-02-14 05:19:56 +00001425 int exitcode;
drh75897232000-05-29 14:26:00 +00001426 struct lemon lem;
1427
icculusf5ad8242010-02-14 05:34:42 +00001428 atexit(LemonAtExit);
1429
drhb0c86772000-06-02 23:21:26 +00001430 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001431 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001432 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001433 exit(0);
1434 }
drhb0c86772000-06-02 23:21:26 +00001435 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001436 fprintf(stderr,"Exactly one filename argument is required.\n");
1437 exit(1);
1438 }
drh954f6b42006-06-13 13:27:46 +00001439 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001440 lem.errorcnt = 0;
1441
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 }
icculus8e158022010-02-16 16:09:03 +00001525 if( lem.nconflict > 0 ){
1526 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001527 }
1528
1529 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001530 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculusf5ad8242010-02-14 05:34:42 +00001531 successful_exit = (exitcode == 0);
icculus42585cf2010-02-14 05:19:56 +00001532 exit(exitcode);
1533 return (exitcode);
drh75897232000-05-29 14:26:00 +00001534}
1535/******************** From the file "msort.c" *******************************/
1536/*
1537** A generic merge-sort program.
1538**
1539** USAGE:
1540** Let "ptr" be a pointer to some structure which is at the head of
1541** a null-terminated list. Then to sort the list call:
1542**
1543** ptr = msort(ptr,&(ptr->next),cmpfnc);
1544**
1545** In the above, "cmpfnc" is a pointer to a function which compares
1546** two instances of the structure and returns an integer, as in
1547** strcmp. The second argument is a pointer to the pointer to the
1548** second element of the linked list. This address is used to compute
1549** the offset to the "next" field within the structure. The offset to
1550** the "next" field must be constant for all structures in the list.
1551**
1552** The function returns a new pointer which is the head of the list
1553** after sorting.
1554**
1555** ALGORITHM:
1556** Merge-sort.
1557*/
1558
1559/*
1560** Return a pointer to the next structure in the linked list.
1561*/
drhba99af52001-10-25 20:37:16 +00001562#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001563
1564/*
1565** Inputs:
1566** a: A sorted, null-terminated linked list. (May be null).
1567** b: A sorted, null-terminated linked list. (May be null).
1568** cmp: A pointer to the comparison function.
1569** offset: Offset in the structure to the "next" field.
1570**
1571** Return Value:
1572** A pointer to the head of a sorted list containing the elements
1573** of both a and b.
1574**
1575** Side effects:
1576** The "next" pointers for elements in the lists a and b are
1577** changed.
1578*/
drhe9278182007-07-18 18:16:29 +00001579static char *merge(
1580 char *a,
1581 char *b,
1582 int (*cmp)(const char*,const char*),
1583 int offset
1584){
drh75897232000-05-29 14:26:00 +00001585 char *ptr, *head;
1586
1587 if( a==0 ){
1588 head = b;
1589 }else if( b==0 ){
1590 head = a;
1591 }else{
drhe594bc32009-11-03 13:02:25 +00001592 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001593 ptr = a;
1594 a = NEXT(a);
1595 }else{
1596 ptr = b;
1597 b = NEXT(b);
1598 }
1599 head = ptr;
1600 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001601 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001602 NEXT(ptr) = a;
1603 ptr = a;
1604 a = NEXT(a);
1605 }else{
1606 NEXT(ptr) = b;
1607 ptr = b;
1608 b = NEXT(b);
1609 }
1610 }
1611 if( a ) NEXT(ptr) = a;
1612 else NEXT(ptr) = b;
1613 }
1614 return head;
1615}
1616
1617/*
1618** Inputs:
1619** list: Pointer to a singly-linked list of structures.
1620** next: Pointer to pointer to the second element of the list.
1621** cmp: A comparison function.
1622**
1623** Return Value:
1624** A pointer to the head of a sorted list containing the elements
1625** orginally in list.
1626**
1627** Side effects:
1628** The "next" pointers for elements in list are changed.
1629*/
1630#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001631static char *msort(
1632 char *list,
1633 char **next,
1634 int (*cmp)(const char*,const char*)
1635){
drhba99af52001-10-25 20:37:16 +00001636 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001637 char *ep;
1638 char *set[LISTSIZE];
1639 int i;
drhba99af52001-10-25 20:37:16 +00001640 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001641 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1642 while( list ){
1643 ep = list;
1644 list = NEXT(list);
1645 NEXT(ep) = 0;
1646 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1647 ep = merge(ep,set[i],cmp,offset);
1648 set[i] = 0;
1649 }
1650 set[i] = ep;
1651 }
1652 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001653 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001654 return ep;
1655}
1656/************************ From the file "option.c" **************************/
1657static char **argv;
1658static struct s_options *op;
1659static FILE *errstream;
1660
1661#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1662
1663/*
1664** Print the command line with a carrot pointing to the k-th character
1665** of the n-th field.
1666*/
icculus9e44cf12010-02-14 17:14:22 +00001667static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001668{
1669 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001670 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001671 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001672 for(i=1; i<n && argv[i]; i++){
1673 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001674 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001675 }
1676 spcnt += k;
1677 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1678 if( spcnt<20 ){
1679 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1680 }else{
1681 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1682 }
1683}
1684
1685/*
1686** Return the index of the N-th non-switch argument. Return -1
1687** if N is out of range.
1688*/
icculus9e44cf12010-02-14 17:14:22 +00001689static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001690{
1691 int i;
1692 int dashdash = 0;
1693 if( argv!=0 && *argv!=0 ){
1694 for(i=1; argv[i]; i++){
1695 if( dashdash || !ISOPT(argv[i]) ){
1696 if( n==0 ) return i;
1697 n--;
1698 }
1699 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1700 }
1701 }
1702 return -1;
1703}
1704
1705static char emsg[] = "Command line syntax error: ";
1706
1707/*
1708** Process a flag command line argument.
1709*/
icculus9e44cf12010-02-14 17:14:22 +00001710static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001711{
1712 int v;
1713 int errcnt = 0;
1714 int j;
1715 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001716 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001717 }
1718 v = argv[i][0]=='-' ? 1 : 0;
1719 if( op[j].label==0 ){
1720 if( err ){
1721 fprintf(err,"%sundefined option.\n",emsg);
1722 errline(i,1,err);
1723 }
1724 errcnt++;
1725 }else if( op[j].type==OPT_FLAG ){
1726 *((int*)op[j].arg) = v;
1727 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001728 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001729 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001730 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001731 }else{
1732 if( err ){
1733 fprintf(err,"%smissing argument on switch.\n",emsg);
1734 errline(i,1,err);
1735 }
1736 errcnt++;
1737 }
1738 return errcnt;
1739}
1740
1741/*
1742** Process a command line switch which has an argument.
1743*/
icculus9e44cf12010-02-14 17:14:22 +00001744static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001745{
1746 int lv = 0;
1747 double dv = 0.0;
1748 char *sv = 0, *end;
1749 char *cp;
1750 int j;
1751 int errcnt = 0;
1752 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001753 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001754 *cp = 0;
1755 for(j=0; op[j].label; j++){
1756 if( strcmp(argv[i],op[j].label)==0 ) break;
1757 }
1758 *cp = '=';
1759 if( op[j].label==0 ){
1760 if( err ){
1761 fprintf(err,"%sundefined option.\n",emsg);
1762 errline(i,0,err);
1763 }
1764 errcnt++;
1765 }else{
1766 cp++;
1767 switch( op[j].type ){
1768 case OPT_FLAG:
1769 case OPT_FFLAG:
1770 if( err ){
1771 fprintf(err,"%soption requires an argument.\n",emsg);
1772 errline(i,0,err);
1773 }
1774 errcnt++;
1775 break;
1776 case OPT_DBL:
1777 case OPT_FDBL:
1778 dv = strtod(cp,&end);
1779 if( *end ){
1780 if( err ){
1781 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001782 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001783 }
1784 errcnt++;
1785 }
1786 break;
1787 case OPT_INT:
1788 case OPT_FINT:
1789 lv = strtol(cp,&end,0);
1790 if( *end ){
1791 if( err ){
1792 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001793 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001794 }
1795 errcnt++;
1796 }
1797 break;
1798 case OPT_STR:
1799 case OPT_FSTR:
1800 sv = cp;
1801 break;
1802 }
1803 switch( op[j].type ){
1804 case OPT_FLAG:
1805 case OPT_FFLAG:
1806 break;
1807 case OPT_DBL:
1808 *(double*)(op[j].arg) = dv;
1809 break;
1810 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001811 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001812 break;
1813 case OPT_INT:
1814 *(int*)(op[j].arg) = lv;
1815 break;
1816 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001817 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001818 break;
1819 case OPT_STR:
1820 *(char**)(op[j].arg) = sv;
1821 break;
1822 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001823 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001824 break;
1825 }
1826 }
1827 return errcnt;
1828}
1829
icculus9e44cf12010-02-14 17:14:22 +00001830int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001831{
1832 int errcnt = 0;
1833 argv = a;
1834 op = o;
1835 errstream = err;
1836 if( argv && *argv && op ){
1837 int i;
1838 for(i=1; argv[i]; i++){
1839 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1840 errcnt += handleflags(i,err);
1841 }else if( strchr(argv[i],'=') ){
1842 errcnt += handleswitch(i,err);
1843 }
1844 }
1845 }
1846 if( errcnt>0 ){
1847 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001848 OptPrint();
drh75897232000-05-29 14:26:00 +00001849 exit(1);
1850 }
1851 return 0;
1852}
1853
drhb0c86772000-06-02 23:21:26 +00001854int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001855 int cnt = 0;
1856 int dashdash = 0;
1857 int i;
1858 if( argv!=0 && argv[0]!=0 ){
1859 for(i=1; argv[i]; i++){
1860 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1861 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1862 }
1863 }
1864 return cnt;
1865}
1866
icculus9e44cf12010-02-14 17:14:22 +00001867char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001868{
1869 int i;
1870 i = argindex(n);
1871 return i>=0 ? argv[i] : 0;
1872}
1873
icculus9e44cf12010-02-14 17:14:22 +00001874void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001875{
1876 int i;
1877 i = argindex(n);
1878 if( i>=0 ) errline(i,0,errstream);
1879}
1880
drhb0c86772000-06-02 23:21:26 +00001881void OptPrint(){
drh75897232000-05-29 14:26:00 +00001882 int i;
1883 int max, len;
1884 max = 0;
1885 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001886 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001887 switch( op[i].type ){
1888 case OPT_FLAG:
1889 case OPT_FFLAG:
1890 break;
1891 case OPT_INT:
1892 case OPT_FINT:
1893 len += 9; /* length of "<integer>" */
1894 break;
1895 case OPT_DBL:
1896 case OPT_FDBL:
1897 len += 6; /* length of "<real>" */
1898 break;
1899 case OPT_STR:
1900 case OPT_FSTR:
1901 len += 8; /* length of "<string>" */
1902 break;
1903 }
1904 if( len>max ) max = len;
1905 }
1906 for(i=0; op[i].label; i++){
1907 switch( op[i].type ){
1908 case OPT_FLAG:
1909 case OPT_FFLAG:
1910 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1911 break;
1912 case OPT_INT:
1913 case OPT_FINT:
1914 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001915 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001916 break;
1917 case OPT_DBL:
1918 case OPT_FDBL:
1919 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001920 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001921 break;
1922 case OPT_STR:
1923 case OPT_FSTR:
1924 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001925 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001926 break;
1927 }
1928 }
1929}
1930/*********************** From the file "parse.c" ****************************/
1931/*
1932** Input file parser for the LEMON parser generator.
1933*/
1934
1935/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00001936enum e_state {
1937 INITIALIZE,
1938 WAITING_FOR_DECL_OR_RULE,
1939 WAITING_FOR_DECL_KEYWORD,
1940 WAITING_FOR_DECL_ARG,
1941 WAITING_FOR_PRECEDENCE_SYMBOL,
1942 WAITING_FOR_ARROW,
1943 IN_RHS,
1944 LHS_ALIAS_1,
1945 LHS_ALIAS_2,
1946 LHS_ALIAS_3,
1947 RHS_ALIAS_1,
1948 RHS_ALIAS_2,
1949 PRECEDENCE_MARK_1,
1950 PRECEDENCE_MARK_2,
1951 RESYNC_AFTER_RULE_ERROR,
1952 RESYNC_AFTER_DECL_ERROR,
1953 WAITING_FOR_DESTRUCTOR_SYMBOL,
1954 WAITING_FOR_DATATYPE_SYMBOL,
1955 WAITING_FOR_FALLBACK_ID,
icculus9e44cf12010-02-14 17:14:22 +00001956 WAITING_FOR_WILDCARD_ID
1957};
drh75897232000-05-29 14:26:00 +00001958struct pstate {
1959 char *filename; /* Name of the input file */
1960 int tokenlineno; /* Linenumber at which current token starts */
1961 int errorcnt; /* Number of errors so far */
1962 char *tokenstart; /* Text of current token */
1963 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00001964 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001965 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001966 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00001967 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00001968 int nrhs; /* Number of right-hand side symbols seen */
1969 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00001970 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00001971 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00001972 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00001973 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001974 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001975 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001976 enum e_assoc declassoc; /* Assign this association to decl arguments */
1977 int preccounter; /* Assign this precedence to decl arguments */
1978 struct rule *firstrule; /* Pointer to first rule in the grammar */
1979 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1980};
1981
1982/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00001983static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00001984{
icculus9e44cf12010-02-14 17:14:22 +00001985 const char *x;
drh75897232000-05-29 14:26:00 +00001986 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1987#if 0
1988 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1989 x,psp->state);
1990#endif
1991 switch( psp->state ){
1992 case INITIALIZE:
1993 psp->prevrule = 0;
1994 psp->preccounter = 0;
1995 psp->firstrule = psp->lastrule = 0;
1996 psp->gp->nrule = 0;
1997 /* Fall thru to next case */
1998 case WAITING_FOR_DECL_OR_RULE:
1999 if( x[0]=='%' ){
2000 psp->state = WAITING_FOR_DECL_KEYWORD;
2001 }else if( islower(x[0]) ){
2002 psp->lhs = Symbol_new(x);
2003 psp->nrhs = 0;
2004 psp->lhsalias = 0;
2005 psp->state = WAITING_FOR_ARROW;
2006 }else if( x[0]=='{' ){
2007 if( psp->prevrule==0 ){
2008 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002009"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002010fragment which begins on this line.");
2011 psp->errorcnt++;
2012 }else if( psp->prevrule->code!=0 ){
2013 ErrorMsg(psp->filename,psp->tokenlineno,
2014"Code fragment beginning on this line is not the first \
2015to follow the previous rule.");
2016 psp->errorcnt++;
2017 }else{
2018 psp->prevrule->line = psp->tokenlineno;
2019 psp->prevrule->code = &x[1];
2020 }
2021 }else if( x[0]=='[' ){
2022 psp->state = PRECEDENCE_MARK_1;
2023 }else{
2024 ErrorMsg(psp->filename,psp->tokenlineno,
2025 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2026 x);
2027 psp->errorcnt++;
2028 }
2029 break;
2030 case PRECEDENCE_MARK_1:
2031 if( !isupper(x[0]) ){
2032 ErrorMsg(psp->filename,psp->tokenlineno,
2033 "The precedence symbol must be a terminal.");
2034 psp->errorcnt++;
2035 }else if( psp->prevrule==0 ){
2036 ErrorMsg(psp->filename,psp->tokenlineno,
2037 "There is no prior rule to assign precedence \"[%s]\".",x);
2038 psp->errorcnt++;
2039 }else if( psp->prevrule->precsym!=0 ){
2040 ErrorMsg(psp->filename,psp->tokenlineno,
2041"Precedence mark on this line is not the first \
2042to follow the previous rule.");
2043 psp->errorcnt++;
2044 }else{
2045 psp->prevrule->precsym = Symbol_new(x);
2046 }
2047 psp->state = PRECEDENCE_MARK_2;
2048 break;
2049 case PRECEDENCE_MARK_2:
2050 if( x[0]!=']' ){
2051 ErrorMsg(psp->filename,psp->tokenlineno,
2052 "Missing \"]\" on precedence mark.");
2053 psp->errorcnt++;
2054 }
2055 psp->state = WAITING_FOR_DECL_OR_RULE;
2056 break;
2057 case WAITING_FOR_ARROW:
2058 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2059 psp->state = IN_RHS;
2060 }else if( x[0]=='(' ){
2061 psp->state = LHS_ALIAS_1;
2062 }else{
2063 ErrorMsg(psp->filename,psp->tokenlineno,
2064 "Expected to see a \":\" following the LHS symbol \"%s\".",
2065 psp->lhs->name);
2066 psp->errorcnt++;
2067 psp->state = RESYNC_AFTER_RULE_ERROR;
2068 }
2069 break;
2070 case LHS_ALIAS_1:
2071 if( isalpha(x[0]) ){
2072 psp->lhsalias = x;
2073 psp->state = LHS_ALIAS_2;
2074 }else{
2075 ErrorMsg(psp->filename,psp->tokenlineno,
2076 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2077 x,psp->lhs->name);
2078 psp->errorcnt++;
2079 psp->state = RESYNC_AFTER_RULE_ERROR;
2080 }
2081 break;
2082 case LHS_ALIAS_2:
2083 if( x[0]==')' ){
2084 psp->state = LHS_ALIAS_3;
2085 }else{
2086 ErrorMsg(psp->filename,psp->tokenlineno,
2087 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2088 psp->errorcnt++;
2089 psp->state = RESYNC_AFTER_RULE_ERROR;
2090 }
2091 break;
2092 case LHS_ALIAS_3:
2093 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2094 psp->state = IN_RHS;
2095 }else{
2096 ErrorMsg(psp->filename,psp->tokenlineno,
2097 "Missing \"->\" following: \"%s(%s)\".",
2098 psp->lhs->name,psp->lhsalias);
2099 psp->errorcnt++;
2100 psp->state = RESYNC_AFTER_RULE_ERROR;
2101 }
2102 break;
2103 case IN_RHS:
2104 if( x[0]=='.' ){
2105 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002106 rp = (struct rule *)calloc( sizeof(struct rule) +
2107 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002108 if( rp==0 ){
2109 ErrorMsg(psp->filename,psp->tokenlineno,
2110 "Can't allocate enough memory for this rule.");
2111 psp->errorcnt++;
2112 psp->prevrule = 0;
2113 }else{
2114 int i;
2115 rp->ruleline = psp->tokenlineno;
2116 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002117 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002118 for(i=0; i<psp->nrhs; i++){
2119 rp->rhs[i] = psp->rhs[i];
2120 rp->rhsalias[i] = psp->alias[i];
2121 }
2122 rp->lhs = psp->lhs;
2123 rp->lhsalias = psp->lhsalias;
2124 rp->nrhs = psp->nrhs;
2125 rp->code = 0;
2126 rp->precsym = 0;
2127 rp->index = psp->gp->nrule++;
2128 rp->nextlhs = rp->lhs->rule;
2129 rp->lhs->rule = rp;
2130 rp->next = 0;
2131 if( psp->firstrule==0 ){
2132 psp->firstrule = psp->lastrule = rp;
2133 }else{
2134 psp->lastrule->next = rp;
2135 psp->lastrule = rp;
2136 }
2137 psp->prevrule = rp;
2138 }
2139 psp->state = WAITING_FOR_DECL_OR_RULE;
2140 }else if( isalpha(x[0]) ){
2141 if( psp->nrhs>=MAXRHS ){
2142 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002143 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002144 x);
2145 psp->errorcnt++;
2146 psp->state = RESYNC_AFTER_RULE_ERROR;
2147 }else{
2148 psp->rhs[psp->nrhs] = Symbol_new(x);
2149 psp->alias[psp->nrhs] = 0;
2150 psp->nrhs++;
2151 }
drhfd405312005-11-06 04:06:59 +00002152 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2153 struct symbol *msp = psp->rhs[psp->nrhs-1];
2154 if( msp->type!=MULTITERMINAL ){
2155 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002156 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002157 memset(msp, 0, sizeof(*msp));
2158 msp->type = MULTITERMINAL;
2159 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002160 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002161 msp->subsym[0] = origsp;
2162 msp->name = origsp->name;
2163 psp->rhs[psp->nrhs-1] = msp;
2164 }
2165 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002166 msp->subsym = (struct symbol **) realloc(msp->subsym,
2167 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002168 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2169 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2170 ErrorMsg(psp->filename,psp->tokenlineno,
2171 "Cannot form a compound containing a non-terminal");
2172 psp->errorcnt++;
2173 }
drh75897232000-05-29 14:26:00 +00002174 }else if( x[0]=='(' && psp->nrhs>0 ){
2175 psp->state = RHS_ALIAS_1;
2176 }else{
2177 ErrorMsg(psp->filename,psp->tokenlineno,
2178 "Illegal character on RHS of rule: \"%s\".",x);
2179 psp->errorcnt++;
2180 psp->state = RESYNC_AFTER_RULE_ERROR;
2181 }
2182 break;
2183 case RHS_ALIAS_1:
2184 if( isalpha(x[0]) ){
2185 psp->alias[psp->nrhs-1] = x;
2186 psp->state = RHS_ALIAS_2;
2187 }else{
2188 ErrorMsg(psp->filename,psp->tokenlineno,
2189 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2190 x,psp->rhs[psp->nrhs-1]->name);
2191 psp->errorcnt++;
2192 psp->state = RESYNC_AFTER_RULE_ERROR;
2193 }
2194 break;
2195 case RHS_ALIAS_2:
2196 if( x[0]==')' ){
2197 psp->state = IN_RHS;
2198 }else{
2199 ErrorMsg(psp->filename,psp->tokenlineno,
2200 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2201 psp->errorcnt++;
2202 psp->state = RESYNC_AFTER_RULE_ERROR;
2203 }
2204 break;
2205 case WAITING_FOR_DECL_KEYWORD:
2206 if( isalpha(x[0]) ){
2207 psp->declkeyword = x;
2208 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002209 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002210 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002211 psp->state = WAITING_FOR_DECL_ARG;
2212 if( strcmp(x,"name")==0 ){
2213 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002214 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002215 }else if( strcmp(x,"include")==0 ){
2216 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002217 }else if( strcmp(x,"code")==0 ){
2218 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002219 }else if( strcmp(x,"token_destructor")==0 ){
2220 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002221 }else if( strcmp(x,"default_destructor")==0 ){
2222 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002223 }else if( strcmp(x,"token_prefix")==0 ){
2224 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002225 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002226 }else if( strcmp(x,"syntax_error")==0 ){
2227 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002228 }else if( strcmp(x,"parse_accept")==0 ){
2229 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002230 }else if( strcmp(x,"parse_failure")==0 ){
2231 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002232 }else if( strcmp(x,"stack_overflow")==0 ){
2233 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002234 }else if( strcmp(x,"extra_argument")==0 ){
2235 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002236 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002237 }else if( strcmp(x,"token_type")==0 ){
2238 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002239 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002240 }else if( strcmp(x,"default_type")==0 ){
2241 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002242 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002243 }else if( strcmp(x,"stack_size")==0 ){
2244 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002245 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002246 }else if( strcmp(x,"start_symbol")==0 ){
2247 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002248 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002249 }else if( strcmp(x,"left")==0 ){
2250 psp->preccounter++;
2251 psp->declassoc = LEFT;
2252 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2253 }else if( strcmp(x,"right")==0 ){
2254 psp->preccounter++;
2255 psp->declassoc = RIGHT;
2256 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2257 }else if( strcmp(x,"nonassoc")==0 ){
2258 psp->preccounter++;
2259 psp->declassoc = NONE;
2260 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2261 }else if( strcmp(x,"destructor")==0 ){
2262 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2263 }else if( strcmp(x,"type")==0 ){
2264 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002265 }else if( strcmp(x,"fallback")==0 ){
2266 psp->fallback = 0;
2267 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002268 }else if( strcmp(x,"wildcard")==0 ){
2269 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002270 }else{
2271 ErrorMsg(psp->filename,psp->tokenlineno,
2272 "Unknown declaration keyword: \"%%%s\".",x);
2273 psp->errorcnt++;
2274 psp->state = RESYNC_AFTER_DECL_ERROR;
2275 }
2276 }else{
2277 ErrorMsg(psp->filename,psp->tokenlineno,
2278 "Illegal declaration keyword: \"%s\".",x);
2279 psp->errorcnt++;
2280 psp->state = RESYNC_AFTER_DECL_ERROR;
2281 }
2282 break;
2283 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2284 if( !isalpha(x[0]) ){
2285 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002286 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002287 psp->errorcnt++;
2288 psp->state = RESYNC_AFTER_DECL_ERROR;
2289 }else{
icculusd286fa62010-03-03 17:06:32 +00002290 struct symbol *sp = Symbol_new(x);
2291 psp->declargslot = &sp->destructor;
2292 psp->decllinenoslot = &sp->destLineno;
2293 psp->insertLineMacro = 1;
2294 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002295 }
2296 break;
2297 case WAITING_FOR_DATATYPE_SYMBOL:
2298 if( !isalpha(x[0]) ){
2299 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002300 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002301 psp->errorcnt++;
2302 psp->state = RESYNC_AFTER_DECL_ERROR;
2303 }else{
icculus866bf1e2010-02-17 20:31:32 +00002304 struct symbol *sp = Symbol_find(x);
2305 if((sp) && (sp->datatype)){
2306 ErrorMsg(psp->filename,psp->tokenlineno,
2307 "Symbol %%type \"%s\" already defined", x);
2308 psp->errorcnt++;
2309 psp->state = RESYNC_AFTER_DECL_ERROR;
2310 }else{
2311 if (!sp){
2312 sp = Symbol_new(x);
2313 }
2314 psp->declargslot = &sp->datatype;
2315 psp->insertLineMacro = 0;
2316 psp->state = WAITING_FOR_DECL_ARG;
2317 }
drh75897232000-05-29 14:26:00 +00002318 }
2319 break;
2320 case WAITING_FOR_PRECEDENCE_SYMBOL:
2321 if( x[0]=='.' ){
2322 psp->state = WAITING_FOR_DECL_OR_RULE;
2323 }else if( isupper(x[0]) ){
2324 struct symbol *sp;
2325 sp = Symbol_new(x);
2326 if( sp->prec>=0 ){
2327 ErrorMsg(psp->filename,psp->tokenlineno,
2328 "Symbol \"%s\" has already be given a precedence.",x);
2329 psp->errorcnt++;
2330 }else{
2331 sp->prec = psp->preccounter;
2332 sp->assoc = psp->declassoc;
2333 }
2334 }else{
2335 ErrorMsg(psp->filename,psp->tokenlineno,
2336 "Can't assign a precedence to \"%s\".",x);
2337 psp->errorcnt++;
2338 }
2339 break;
2340 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002341 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002342 const char *zOld, *zNew;
2343 char *zBuf, *z;
drha5808f32008-04-27 22:19:44 +00002344 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002345 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002346 char zLine[50];
2347 zNew = x;
2348 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002349 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002350 if( *psp->declargslot ){
2351 zOld = *psp->declargslot;
2352 }else{
2353 zOld = "";
2354 }
drh87cf1372008-08-13 20:09:06 +00002355 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002356 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002357 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002358 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2359 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002360 for(z=psp->filename, nBack=0; *z; z++){
2361 if( *z=='\\' ) nBack++;
2362 }
2363 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002364 nLine = lemonStrlen(zLine);
2365 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002366 }
icculus9e44cf12010-02-14 17:14:22 +00002367 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2368 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002369 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002370 if( nOld && zBuf[-1]!='\n' ){
2371 *(zBuf++) = '\n';
2372 }
2373 memcpy(zBuf, zLine, nLine);
2374 zBuf += nLine;
2375 *(zBuf++) = '"';
2376 for(z=psp->filename; *z; z++){
2377 if( *z=='\\' ){
2378 *(zBuf++) = '\\';
2379 }
2380 *(zBuf++) = *z;
2381 }
2382 *(zBuf++) = '"';
2383 *(zBuf++) = '\n';
2384 }
drh4dc8ef52008-07-01 17:13:57 +00002385 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2386 psp->decllinenoslot[0] = psp->tokenlineno;
2387 }
drha5808f32008-04-27 22:19:44 +00002388 memcpy(zBuf, zNew, nNew);
2389 zBuf += nNew;
2390 *zBuf = 0;
2391 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002392 }else{
2393 ErrorMsg(psp->filename,psp->tokenlineno,
2394 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2395 psp->errorcnt++;
2396 psp->state = RESYNC_AFTER_DECL_ERROR;
2397 }
2398 break;
drh0bd1f4e2002-06-06 18:54:39 +00002399 case WAITING_FOR_FALLBACK_ID:
2400 if( x[0]=='.' ){
2401 psp->state = WAITING_FOR_DECL_OR_RULE;
2402 }else if( !isupper(x[0]) ){
2403 ErrorMsg(psp->filename, psp->tokenlineno,
2404 "%%fallback argument \"%s\" should be a token", x);
2405 psp->errorcnt++;
2406 }else{
2407 struct symbol *sp = Symbol_new(x);
2408 if( psp->fallback==0 ){
2409 psp->fallback = sp;
2410 }else if( sp->fallback ){
2411 ErrorMsg(psp->filename, psp->tokenlineno,
2412 "More than one fallback assigned to token %s", x);
2413 psp->errorcnt++;
2414 }else{
2415 sp->fallback = psp->fallback;
2416 psp->gp->has_fallback = 1;
2417 }
2418 }
2419 break;
drhe09daa92006-06-10 13:29:31 +00002420 case WAITING_FOR_WILDCARD_ID:
2421 if( x[0]=='.' ){
2422 psp->state = WAITING_FOR_DECL_OR_RULE;
2423 }else if( !isupper(x[0]) ){
2424 ErrorMsg(psp->filename, psp->tokenlineno,
2425 "%%wildcard argument \"%s\" should be a token", x);
2426 psp->errorcnt++;
2427 }else{
2428 struct symbol *sp = Symbol_new(x);
2429 if( psp->gp->wildcard==0 ){
2430 psp->gp->wildcard = sp;
2431 }else{
2432 ErrorMsg(psp->filename, psp->tokenlineno,
2433 "Extra wildcard to token: %s", x);
2434 psp->errorcnt++;
2435 }
2436 }
2437 break;
drh75897232000-05-29 14:26:00 +00002438 case RESYNC_AFTER_RULE_ERROR:
2439/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2440** break; */
2441 case RESYNC_AFTER_DECL_ERROR:
2442 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2443 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2444 break;
2445 }
2446}
2447
drh34ff57b2008-07-14 12:27:51 +00002448/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002449** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2450** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2451** comments them out. Text in between is also commented out as appropriate.
2452*/
danielk1977940fac92005-01-23 22:41:37 +00002453static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002454 int i, j, k, n;
2455 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002456 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002457 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002458 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002459 for(i=0; z[i]; i++){
2460 if( z[i]=='\n' ) lineno++;
2461 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2462 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2463 if( exclude ){
2464 exclude--;
2465 if( exclude==0 ){
2466 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2467 }
2468 }
2469 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2470 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2471 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2472 if( exclude ){
2473 exclude++;
2474 }else{
2475 for(j=i+7; isspace(z[j]); j++){}
2476 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2477 exclude = 1;
2478 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002479 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002480 exclude = 0;
2481 break;
2482 }
2483 }
2484 if( z[i+3]=='n' ) exclude = !exclude;
2485 if( exclude ){
2486 start = i;
2487 start_lineno = lineno;
2488 }
2489 }
2490 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2491 }
2492 }
2493 if( exclude ){
2494 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2495 exit(1);
2496 }
2497}
2498
drh75897232000-05-29 14:26:00 +00002499/* In spite of its name, this function is really a scanner. It read
2500** in the entire input file (all at once) then tokenizes it. Each
2501** token is passed to the function "parseonetoken" which builds all
2502** the appropriate data structures in the global state vector "gp".
2503*/
icculus9e44cf12010-02-14 17:14:22 +00002504void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002505{
2506 struct pstate ps;
2507 FILE *fp;
2508 char *filebuf;
2509 int filesize;
2510 int lineno;
2511 int c;
2512 char *cp, *nextcp;
2513 int startline = 0;
2514
rse38514a92007-09-20 11:34:17 +00002515 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002516 ps.gp = gp;
2517 ps.filename = gp->filename;
2518 ps.errorcnt = 0;
2519 ps.state = INITIALIZE;
2520
2521 /* Begin by reading the input file */
2522 fp = fopen(ps.filename,"rb");
2523 if( fp==0 ){
2524 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2525 gp->errorcnt++;
2526 return;
2527 }
2528 fseek(fp,0,2);
2529 filesize = ftell(fp);
2530 rewind(fp);
2531 filebuf = (char *)malloc( filesize+1 );
2532 if( filebuf==0 ){
2533 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2534 filesize+1);
2535 gp->errorcnt++;
2536 return;
2537 }
2538 if( fread(filebuf,1,filesize,fp)!=filesize ){
2539 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2540 filesize);
2541 free(filebuf);
2542 gp->errorcnt++;
2543 return;
2544 }
2545 fclose(fp);
2546 filebuf[filesize] = 0;
2547
drh6d08b4d2004-07-20 12:45:22 +00002548 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2549 preprocess_input(filebuf);
2550
drh75897232000-05-29 14:26:00 +00002551 /* Now scan the text of the input file */
2552 lineno = 1;
2553 for(cp=filebuf; (c= *cp)!=0; ){
2554 if( c=='\n' ) lineno++; /* Keep track of the line number */
2555 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2556 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2557 cp+=2;
2558 while( (c= *cp)!=0 && c!='\n' ) cp++;
2559 continue;
2560 }
2561 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2562 cp+=2;
2563 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2564 if( c=='\n' ) lineno++;
2565 cp++;
2566 }
2567 if( c ) cp++;
2568 continue;
2569 }
2570 ps.tokenstart = cp; /* Mark the beginning of the token */
2571 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2572 if( c=='\"' ){ /* String literals */
2573 cp++;
2574 while( (c= *cp)!=0 && c!='\"' ){
2575 if( c=='\n' ) lineno++;
2576 cp++;
2577 }
2578 if( c==0 ){
2579 ErrorMsg(ps.filename,startline,
2580"String starting on this line is not terminated before the end of the file.");
2581 ps.errorcnt++;
2582 nextcp = cp;
2583 }else{
2584 nextcp = cp+1;
2585 }
2586 }else if( c=='{' ){ /* A block of C code */
2587 int level;
2588 cp++;
2589 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2590 if( c=='\n' ) lineno++;
2591 else if( c=='{' ) level++;
2592 else if( c=='}' ) level--;
2593 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2594 int prevc;
2595 cp = &cp[2];
2596 prevc = 0;
2597 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2598 if( c=='\n' ) lineno++;
2599 prevc = c;
2600 cp++;
2601 }
2602 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2603 cp = &cp[2];
2604 while( (c= *cp)!=0 && c!='\n' ) cp++;
2605 if( c ) lineno++;
2606 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2607 int startchar, prevc;
2608 startchar = c;
2609 prevc = 0;
2610 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2611 if( c=='\n' ) lineno++;
2612 if( prevc=='\\' ) prevc = 0;
2613 else prevc = c;
2614 }
2615 }
2616 }
2617 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002618 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002619"C code starting on this line is not terminated before the end of the file.");
2620 ps.errorcnt++;
2621 nextcp = cp;
2622 }else{
2623 nextcp = cp+1;
2624 }
2625 }else if( isalnum(c) ){ /* Identifiers */
2626 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2627 nextcp = cp;
2628 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2629 cp += 3;
2630 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002631 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2632 cp += 2;
2633 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2634 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002635 }else{ /* All other (one character) operators */
2636 cp++;
2637 nextcp = cp;
2638 }
2639 c = *cp;
2640 *cp = 0; /* Null terminate the token */
2641 parseonetoken(&ps); /* Parse the token */
2642 *cp = c; /* Restore the buffer */
2643 cp = nextcp;
2644 }
2645 free(filebuf); /* Release the buffer after parsing */
2646 gp->rule = ps.firstrule;
2647 gp->errorcnt = ps.errorcnt;
2648}
2649/*************************** From the file "plink.c" *********************/
2650/*
2651** Routines processing configuration follow-set propagation links
2652** in the LEMON parser generator.
2653*/
2654static struct plink *plink_freelist = 0;
2655
2656/* Allocate a new plink */
2657struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002658 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002659
2660 if( plink_freelist==0 ){
2661 int i;
2662 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002663 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002664 if( plink_freelist==0 ){
2665 fprintf(stderr,
2666 "Unable to allocate memory for a new follow-set propagation link.\n");
2667 exit(1);
2668 }
2669 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2670 plink_freelist[amt-1].next = 0;
2671 }
icculus9e44cf12010-02-14 17:14:22 +00002672 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002673 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002674 return newlink;
drh75897232000-05-29 14:26:00 +00002675}
2676
2677/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002678void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002679{
icculus9e44cf12010-02-14 17:14:22 +00002680 struct plink *newlink;
2681 newlink = Plink_new();
2682 newlink->next = *plpp;
2683 *plpp = newlink;
2684 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002685}
2686
2687/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002688void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002689{
2690 struct plink *nextpl;
2691 while( from ){
2692 nextpl = from->next;
2693 from->next = *to;
2694 *to = from;
2695 from = nextpl;
2696 }
2697}
2698
2699/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002700void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002701{
2702 struct plink *nextpl;
2703
2704 while( plp ){
2705 nextpl = plp->next;
2706 plp->next = plink_freelist;
2707 plink_freelist = plp;
2708 plp = nextpl;
2709 }
2710}
2711/*********************** From the file "report.c" **************************/
2712/*
2713** Procedures for generating reports and tables in the LEMON parser generator.
2714*/
2715
2716/* Generate a filename with the given suffix. Space to hold the
2717** name comes from malloc() and must be freed by the calling
2718** function.
2719*/
icculus9e44cf12010-02-14 17:14:22 +00002720PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002721{
2722 char *name;
2723 char *cp;
2724
icculus9e44cf12010-02-14 17:14:22 +00002725 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002726 if( name==0 ){
2727 fprintf(stderr,"Can't allocate space for a filename.\n");
2728 exit(1);
2729 }
2730 strcpy(name,lemp->filename);
2731 cp = strrchr(name,'.');
2732 if( cp ) *cp = 0;
2733 strcat(name,suffix);
2734 return name;
2735}
2736
2737/* Open a file with a name based on the name of the input file,
2738** but with a different (specified) suffix, and return a pointer
2739** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002740PRIVATE FILE *file_open(
2741 struct lemon *lemp,
2742 const char *suffix,
2743 const char *mode
2744){
drh75897232000-05-29 14:26:00 +00002745 FILE *fp;
2746
2747 if( lemp->outname ) free(lemp->outname);
2748 lemp->outname = file_makename(lemp, suffix);
2749 fp = fopen(lemp->outname,mode);
2750 if( fp==0 && *mode=='w' ){
2751 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2752 lemp->errorcnt++;
2753 return 0;
2754 }
icculusf5ad8242010-02-14 05:34:42 +00002755
2756 /* Add files we create to a list, so we can delete them if we fail. This
2757 ** is to keep makefiles from getting confused. We don't include .out files,
2758 ** though: this is debug information, and you don't want it deleted if there
2759 ** was an error you need to track down.
2760 */
2761 if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){
2762 const char **ptr = (const char **)
2763 realloc(made_files, sizeof (const char **) * (made_files_count + 1));
icculusd49c1aa2010-03-03 17:00:15 +00002764 const char *fname = Strsafe(lemp->outname);
icculusf5ad8242010-02-14 05:34:42 +00002765 if ((ptr == NULL) || (fname == NULL)) {
2766 free(ptr);
icculusf5ad8242010-02-14 05:34:42 +00002767 memory_error();
2768 }
2769 made_files = ptr;
2770 made_files[made_files_count++] = fname;
2771 }
drh75897232000-05-29 14:26:00 +00002772 return fp;
2773}
2774
2775/* Duplicate the input file without comments and without actions
2776** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002777void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002778{
2779 struct rule *rp;
2780 struct symbol *sp;
2781 int i, j, maxlen, len, ncolumns, skip;
2782 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2783 maxlen = 10;
2784 for(i=0; i<lemp->nsymbol; i++){
2785 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002786 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002787 if( len>maxlen ) maxlen = len;
2788 }
2789 ncolumns = 76/(maxlen+5);
2790 if( ncolumns<1 ) ncolumns = 1;
2791 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2792 for(i=0; i<skip; i++){
2793 printf("//");
2794 for(j=i; j<lemp->nsymbol; j+=skip){
2795 sp = lemp->symbols[j];
2796 assert( sp->index==j );
2797 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2798 }
2799 printf("\n");
2800 }
2801 for(rp=lemp->rule; rp; rp=rp->next){
2802 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002803 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002804 printf(" ::=");
2805 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002806 sp = rp->rhs[i];
2807 printf(" %s", sp->name);
2808 if( sp->type==MULTITERMINAL ){
2809 for(j=1; j<sp->nsubsym; j++){
2810 printf("|%s", sp->subsym[j]->name);
2811 }
2812 }
2813 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002814 }
2815 printf(".");
2816 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002817 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002818 printf("\n");
2819 }
2820}
2821
icculus9e44cf12010-02-14 17:14:22 +00002822void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002823{
2824 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002825 struct symbol *sp;
2826 int i, j;
drh75897232000-05-29 14:26:00 +00002827 rp = cfp->rp;
2828 fprintf(fp,"%s ::=",rp->lhs->name);
2829 for(i=0; i<=rp->nrhs; i++){
2830 if( i==cfp->dot ) fprintf(fp," *");
2831 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002832 sp = rp->rhs[i];
2833 fprintf(fp," %s", sp->name);
2834 if( sp->type==MULTITERMINAL ){
2835 for(j=1; j<sp->nsubsym; j++){
2836 fprintf(fp,"|%s",sp->subsym[j]->name);
2837 }
2838 }
drh75897232000-05-29 14:26:00 +00002839 }
2840}
2841
2842/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002843#if 0
drh75897232000-05-29 14:26:00 +00002844/* Print a set */
2845PRIVATE void SetPrint(out,set,lemp)
2846FILE *out;
2847char *set;
2848struct lemon *lemp;
2849{
2850 int i;
2851 char *spacer;
2852 spacer = "";
2853 fprintf(out,"%12s[","");
2854 for(i=0; i<lemp->nterminal; i++){
2855 if( SetFind(set,i) ){
2856 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2857 spacer = " ";
2858 }
2859 }
2860 fprintf(out,"]\n");
2861}
2862
2863/* Print a plink chain */
2864PRIVATE void PlinkPrint(out,plp,tag)
2865FILE *out;
2866struct plink *plp;
2867char *tag;
2868{
2869 while( plp ){
drhada354d2005-11-05 15:03:59 +00002870 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002871 ConfigPrint(out,plp->cfp);
2872 fprintf(out,"\n");
2873 plp = plp->next;
2874 }
2875}
2876#endif
2877
2878/* Print an action to the given file descriptor. Return FALSE if
2879** nothing was actually printed.
2880*/
2881int PrintAction(struct action *ap, FILE *fp, int indent){
2882 int result = 1;
2883 switch( ap->type ){
2884 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002885 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002886 break;
2887 case REDUCE:
2888 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2889 break;
2890 case ACCEPT:
2891 fprintf(fp,"%*s accept",indent,ap->sp->name);
2892 break;
2893 case ERROR:
2894 fprintf(fp,"%*s error",indent,ap->sp->name);
2895 break;
drh9892c5d2007-12-21 00:02:11 +00002896 case SRCONFLICT:
2897 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002898 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2899 indent,ap->sp->name,ap->x.rp->index);
2900 break;
drh9892c5d2007-12-21 00:02:11 +00002901 case SSCONFLICT:
2902 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2903 indent,ap->sp->name,ap->x.stp->statenum);
2904 break;
drh75897232000-05-29 14:26:00 +00002905 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00002906 if( showPrecedenceConflict ){
2907 fprintf(fp,"%*s shift %d -- dropped by precedence",
2908 indent,ap->sp->name,ap->x.stp->statenum);
2909 }else{
2910 result = 0;
2911 }
2912 break;
drh75897232000-05-29 14:26:00 +00002913 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00002914 if( showPrecedenceConflict ){
2915 fprintf(fp,"%*s reduce %d -- dropped by precedence",
2916 indent,ap->sp->name,ap->x.rp->index);
2917 }else{
2918 result = 0;
2919 }
2920 break;
drh75897232000-05-29 14:26:00 +00002921 case NOT_USED:
2922 result = 0;
2923 break;
2924 }
2925 return result;
2926}
2927
2928/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00002929void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002930{
2931 int i;
2932 struct state *stp;
2933 struct config *cfp;
2934 struct action *ap;
2935 FILE *fp;
2936
drh2aa6ca42004-09-10 00:14:04 +00002937 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002938 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002939 for(i=0; i<lemp->nstate; i++){
2940 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002941 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002942 if( lemp->basisflag ) cfp=stp->bp;
2943 else cfp=stp->cfp;
2944 while( cfp ){
2945 char buf[20];
2946 if( cfp->dot==cfp->rp->nrhs ){
2947 sprintf(buf,"(%d)",cfp->rp->index);
2948 fprintf(fp," %5s ",buf);
2949 }else{
2950 fprintf(fp," ");
2951 }
2952 ConfigPrint(fp,cfp);
2953 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002954#if 0
drh75897232000-05-29 14:26:00 +00002955 SetPrint(fp,cfp->fws,lemp);
2956 PlinkPrint(fp,cfp->fplp,"To ");
2957 PlinkPrint(fp,cfp->bplp,"From");
2958#endif
2959 if( lemp->basisflag ) cfp=cfp->bp;
2960 else cfp=cfp->next;
2961 }
2962 fprintf(fp,"\n");
2963 for(ap=stp->ap; ap; ap=ap->next){
2964 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2965 }
2966 fprintf(fp,"\n");
2967 }
drhe9278182007-07-18 18:16:29 +00002968 fprintf(fp, "----------------------------------------------------\n");
2969 fprintf(fp, "Symbols:\n");
2970 for(i=0; i<lemp->nsymbol; i++){
2971 int j;
2972 struct symbol *sp;
2973
2974 sp = lemp->symbols[i];
2975 fprintf(fp, " %3d: %s", i, sp->name);
2976 if( sp->type==NONTERMINAL ){
2977 fprintf(fp, ":");
2978 if( sp->lambda ){
2979 fprintf(fp, " <lambda>");
2980 }
2981 for(j=0; j<lemp->nterminal; j++){
2982 if( sp->firstset && SetFind(sp->firstset, j) ){
2983 fprintf(fp, " %s", lemp->symbols[j]->name);
2984 }
2985 }
2986 }
2987 fprintf(fp, "\n");
2988 }
drh75897232000-05-29 14:26:00 +00002989 fclose(fp);
2990 return;
2991}
2992
2993/* Search for the file "name" which is in the same directory as
2994** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00002995PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00002996{
icculus9e44cf12010-02-14 17:14:22 +00002997 const char *pathlist;
2998 char *pathbufptr;
2999 char *pathbuf;
drh75897232000-05-29 14:26:00 +00003000 char *path,*cp;
3001 char c;
drh75897232000-05-29 14:26:00 +00003002
3003#ifdef __WIN32__
3004 cp = strrchr(argv0,'\\');
3005#else
3006 cp = strrchr(argv0,'/');
3007#endif
3008 if( cp ){
3009 c = *cp;
3010 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00003011 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00003012 if( path ) sprintf(path,"%s/%s",argv0,name);
3013 *cp = c;
3014 }else{
drh75897232000-05-29 14:26:00 +00003015 pathlist = getenv("PATH");
3016 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003017 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003018 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003019 if( (pathbuf != 0) && (path!=0) ){
3020 pathbufptr = pathbuf;
3021 strcpy(pathbuf, pathlist);
3022 while( *pathbuf ){
3023 cp = strchr(pathbuf,':');
3024 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003025 c = *cp;
3026 *cp = 0;
icculus9e44cf12010-02-14 17:14:22 +00003027 sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003028 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003029 if( c==0 ) pathbuf[0] = 0;
3030 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003031 if( access(path,modemask)==0 ) break;
3032 }
icculus9e44cf12010-02-14 17:14:22 +00003033 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003034 }
3035 }
3036 return path;
3037}
3038
3039/* Given an action, compute the integer value for that action
3040** which is to be put in the action table of the generated machine.
3041** Return negative if no action should be generated.
3042*/
icculus9e44cf12010-02-14 17:14:22 +00003043PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003044{
3045 int act;
3046 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003047 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003048 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3049 case ERROR: act = lemp->nstate + lemp->nrule; break;
3050 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3051 default: act = -1; break;
3052 }
3053 return act;
3054}
3055
3056#define LINESIZE 1000
3057/* The next cluster of routines are for reading the template file
3058** and writing the results to the generated parser */
3059/* The first function transfers data from "in" to "out" until
3060** a line is seen which begins with "%%". The line number is
3061** tracked.
3062**
3063** if name!=0, then any word that begin with "Parse" is changed to
3064** begin with *name instead.
3065*/
icculus9e44cf12010-02-14 17:14:22 +00003066PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003067{
3068 int i, iStart;
3069 char line[LINESIZE];
3070 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3071 (*lineno)++;
3072 iStart = 0;
3073 if( name ){
3074 for(i=0; line[i]; i++){
3075 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3076 && (i==0 || !isalpha(line[i-1]))
3077 ){
3078 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3079 fprintf(out,"%s",name);
3080 i += 4;
3081 iStart = i+1;
3082 }
3083 }
3084 }
3085 fprintf(out,"%s",&line[iStart]);
3086 }
3087}
3088
3089/* The next function finds the template file and opens it, returning
3090** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003091PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003092{
3093 static char templatename[] = "lempar.c";
3094 char buf[1000];
3095 FILE *in;
3096 char *tpltname;
3097 char *cp;
3098
icculus3e143bd2010-02-14 00:48:49 +00003099 /* first, see if user specified a template filename on the command line. */
3100 if (user_templatename != 0) {
3101 if( access(user_templatename,004)==-1 ){
3102 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3103 user_templatename);
3104 lemp->errorcnt++;
3105 return 0;
3106 }
3107 in = fopen(user_templatename,"rb");
3108 if( in==0 ){
3109 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3110 lemp->errorcnt++;
3111 return 0;
3112 }
3113 return in;
3114 }
3115
drh75897232000-05-29 14:26:00 +00003116 cp = strrchr(lemp->filename,'.');
3117 if( cp ){
drh8b582012003-10-21 13:16:03 +00003118 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003119 }else{
3120 sprintf(buf,"%s.lt",lemp->filename);
3121 }
3122 if( access(buf,004)==0 ){
3123 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003124 }else if( access(templatename,004)==0 ){
3125 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003126 }else{
3127 tpltname = pathsearch(lemp->argv0,templatename,0);
3128 }
3129 if( tpltname==0 ){
3130 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3131 templatename);
3132 lemp->errorcnt++;
3133 return 0;
3134 }
drh2aa6ca42004-09-10 00:14:04 +00003135 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003136 if( in==0 ){
3137 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3138 lemp->errorcnt++;
3139 return 0;
3140 }
3141 return in;
3142}
3143
drhaf805ca2004-09-07 11:28:25 +00003144/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003145PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003146{
3147 fprintf(out,"#line %d \"",lineno);
3148 while( *filename ){
3149 if( *filename == '\\' ) putc('\\',out);
3150 putc(*filename,out);
3151 filename++;
3152 }
3153 fprintf(out,"\"\n");
3154}
3155
drh75897232000-05-29 14:26:00 +00003156/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003157PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003158{
3159 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003160 while( *str ){
drh75897232000-05-29 14:26:00 +00003161 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003162 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003163 str++;
3164 }
drh9db55df2004-09-09 14:01:21 +00003165 if( str[-1]!='\n' ){
3166 putc('\n',out);
3167 (*lineno)++;
3168 }
shane58543932008-12-10 20:10:04 +00003169 if (!lemp->nolinenosflag) {
3170 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3171 }
drh75897232000-05-29 14:26:00 +00003172 return;
3173}
3174
3175/*
3176** The following routine emits code for the destructor for the
3177** symbol sp
3178*/
icculus9e44cf12010-02-14 17:14:22 +00003179void emit_destructor_code(
3180 FILE *out,
3181 struct symbol *sp,
3182 struct lemon *lemp,
3183 int *lineno
3184){
drhcc83b6e2004-04-23 23:38:42 +00003185 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003186
drh75897232000-05-29 14:26:00 +00003187 if( sp->type==TERMINAL ){
3188 cp = lemp->tokendest;
3189 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003190 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003191 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003192 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003193 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003194 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003195 }else if( lemp->vardest ){
3196 cp = lemp->vardest;
3197 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003198 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003199 }else{
3200 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003201 }
3202 for(; *cp; cp++){
3203 if( *cp=='$' && cp[1]=='$' ){
3204 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3205 cp++;
3206 continue;
3207 }
shane58543932008-12-10 20:10:04 +00003208 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003209 fputc(*cp,out);
3210 }
shane58543932008-12-10 20:10:04 +00003211 fprintf(out,"\n"); (*lineno)++;
3212 if (!lemp->nolinenosflag) {
3213 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3214 }
3215 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003216 return;
3217}
3218
3219/*
drh960e8c62001-04-03 16:53:21 +00003220** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003221*/
icculus9e44cf12010-02-14 17:14:22 +00003222int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003223{
3224 int ret;
3225 if( sp->type==TERMINAL ){
3226 ret = lemp->tokendest!=0;
3227 }else{
drh960e8c62001-04-03 16:53:21 +00003228 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003229 }
3230 return ret;
3231}
3232
drh0bb132b2004-07-20 14:06:51 +00003233/*
3234** Append text to a dynamically allocated string. If zText is 0 then
3235** reset the string to be empty again. Always return the complete text
3236** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003237**
3238** n bytes of zText are stored. If n==0 then all of zText up to the first
3239** \000 terminator is stored. zText can contain up to two instances of
3240** %d. The values of p1 and p2 are written into the first and second
3241** %d.
3242**
3243** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003244*/
icculus9e44cf12010-02-14 17:14:22 +00003245PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3246 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003247 static char *z = 0;
3248 static int alloced = 0;
3249 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003250 int c;
drh0bb132b2004-07-20 14:06:51 +00003251 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003252 if( zText==0 ){
3253 used = 0;
3254 return z;
3255 }
drh7ac25c72004-08-19 15:12:26 +00003256 if( n<=0 ){
3257 if( n<0 ){
3258 used += n;
3259 assert( used>=0 );
3260 }
drh87cf1372008-08-13 20:09:06 +00003261 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003262 }
drh0bb132b2004-07-20 14:06:51 +00003263 if( n+sizeof(zInt)*2+used >= alloced ){
3264 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003265 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003266 }
icculus9e44cf12010-02-14 17:14:22 +00003267 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003268 while( n-- > 0 ){
3269 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003270 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003271 sprintf(zInt, "%d", p1);
3272 p1 = p2;
3273 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003274 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003275 zText++;
3276 n--;
3277 }else{
3278 z[used++] = c;
3279 }
3280 }
3281 z[used] = 0;
3282 return z;
3283}
3284
3285/*
3286** zCode is a string that is the action associated with a rule. Expand
3287** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003288** stack.
drh0bb132b2004-07-20 14:06:51 +00003289*/
drhaf805ca2004-09-07 11:28:25 +00003290PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003291 char *cp, *xp;
3292 int i;
3293 char lhsused = 0; /* True if the LHS element has been used */
3294 char used[MAXRHS]; /* True for each RHS element which is used */
3295
3296 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3297 lhsused = 0;
3298
drh19c9e562007-03-29 20:13:53 +00003299 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003300 static char newlinestr[2] = { '\n', '\0' };
3301 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003302 rp->line = rp->ruleline;
3303 }
3304
drh0bb132b2004-07-20 14:06:51 +00003305 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003306
3307 /* This const cast is wrong but harmless, if we're careful. */
3308 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003309 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3310 char saved;
3311 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3312 saved = *xp;
3313 *xp = 0;
3314 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003315 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003316 cp = xp;
3317 lhsused = 1;
3318 }else{
3319 for(i=0; i<rp->nrhs; i++){
3320 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003321 if( cp!=rp->code && cp[-1]=='@' ){
3322 /* If the argument is of the form @X then substituted
3323 ** the token number of X, not the value of X */
3324 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3325 }else{
drhfd405312005-11-06 04:06:59 +00003326 struct symbol *sp = rp->rhs[i];
3327 int dtnum;
3328 if( sp->type==MULTITERMINAL ){
3329 dtnum = sp->subsym[0]->dtnum;
3330 }else{
3331 dtnum = sp->dtnum;
3332 }
3333 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003334 }
drh0bb132b2004-07-20 14:06:51 +00003335 cp = xp;
3336 used[i] = 1;
3337 break;
3338 }
3339 }
3340 }
3341 *xp = saved;
3342 }
3343 append_str(cp, 1, 0, 0);
3344 } /* End loop */
3345
3346 /* Check to make sure the LHS has been used */
3347 if( rp->lhsalias && !lhsused ){
3348 ErrorMsg(lemp->filename,rp->ruleline,
3349 "Label \"%s\" for \"%s(%s)\" is never used.",
3350 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3351 lemp->errorcnt++;
3352 }
3353
3354 /* Generate destructor code for RHS symbols which are not used in the
3355 ** reduce code */
3356 for(i=0; i<rp->nrhs; i++){
3357 if( rp->rhsalias[i] && !used[i] ){
3358 ErrorMsg(lemp->filename,rp->ruleline,
3359 "Label %s for \"%s(%s)\" is never used.",
3360 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3361 lemp->errorcnt++;
3362 }else if( rp->rhsalias[i]==0 ){
3363 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003364 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003365 rp->rhs[i]->index,i-rp->nrhs+1);
3366 }else{
3367 /* No destructor defined for this term */
3368 }
3369 }
3370 }
drh61e339a2007-01-16 03:09:02 +00003371 if( rp->code ){
3372 cp = append_str(0,0,0,0);
3373 rp->code = Strsafe(cp?cp:"");
3374 }
drh0bb132b2004-07-20 14:06:51 +00003375}
3376
drh75897232000-05-29 14:26:00 +00003377/*
3378** Generate code which executes when the rule "rp" is reduced. Write
3379** the code to "out". Make sure lineno stays up-to-date.
3380*/
icculus9e44cf12010-02-14 17:14:22 +00003381PRIVATE void emit_code(
3382 FILE *out,
3383 struct rule *rp,
3384 struct lemon *lemp,
3385 int *lineno
3386){
3387 const char *cp;
drh75897232000-05-29 14:26:00 +00003388
3389 /* Generate code to do the reduce action */
3390 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003391 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003392 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003393 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003394 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003395 } /* End loop */
shane58543932008-12-10 20:10:04 +00003396 fprintf(out,"}\n"); (*lineno)++;
3397 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003398 } /* End if( rp->code ) */
3399
drh75897232000-05-29 14:26:00 +00003400 return;
3401}
3402
3403/*
3404** Print the definition of the union used for the parser's data stack.
3405** This union contains fields for every possible data type for tokens
3406** and nonterminals. In the process of computing and printing this
3407** union, also set the ".dtnum" field of every terminal and nonterminal
3408** symbol.
3409*/
icculus9e44cf12010-02-14 17:14:22 +00003410void print_stack_union(
3411 FILE *out, /* The output stream */
3412 struct lemon *lemp, /* The main info structure for this parser */
3413 int *plineno, /* Pointer to the line number */
3414 int mhflag /* True if generating makeheaders output */
3415){
drh75897232000-05-29 14:26:00 +00003416 int lineno = *plineno; /* The line number of the output */
3417 char **types; /* A hash table of datatypes */
3418 int arraysize; /* Size of the "types" array */
3419 int maxdtlength; /* Maximum length of any ".datatype" field. */
3420 char *stddt; /* Standardized name for a datatype */
3421 int i,j; /* Loop counters */
3422 int hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003423 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003424
3425 /* Allocate and initialize types[] and allocate stddt[] */
3426 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003427 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003428 for(i=0; i<arraysize; i++) types[i] = 0;
3429 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003430 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003431 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003432 }
drh75897232000-05-29 14:26:00 +00003433 for(i=0; i<lemp->nsymbol; i++){
3434 int len;
3435 struct symbol *sp = lemp->symbols[i];
3436 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003437 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003438 if( len>maxdtlength ) maxdtlength = len;
3439 }
3440 stddt = (char*)malloc( maxdtlength*2 + 1 );
3441 if( types==0 || stddt==0 ){
3442 fprintf(stderr,"Out of memory.\n");
3443 exit(1);
3444 }
3445
3446 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3447 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003448 ** used for terminal symbols. If there is no %default_type defined then
3449 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3450 ** a datatype using the %type directive.
3451 */
drh75897232000-05-29 14:26:00 +00003452 for(i=0; i<lemp->nsymbol; i++){
3453 struct symbol *sp = lemp->symbols[i];
3454 char *cp;
3455 if( sp==lemp->errsym ){
3456 sp->dtnum = arraysize+1;
3457 continue;
3458 }
drh960e8c62001-04-03 16:53:21 +00003459 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003460 sp->dtnum = 0;
3461 continue;
3462 }
3463 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003464 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003465 j = 0;
3466 while( isspace(*cp) ) cp++;
3467 while( *cp ) stddt[j++] = *cp++;
3468 while( j>0 && isspace(stddt[j-1]) ) j--;
3469 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003470 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003471 sp->dtnum = 0;
3472 continue;
3473 }
drh75897232000-05-29 14:26:00 +00003474 hash = 0;
3475 for(j=0; stddt[j]; j++){
3476 hash = hash*53 + stddt[j];
3477 }
drh3b2129c2003-05-13 00:34:21 +00003478 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003479 while( types[hash] ){
3480 if( strcmp(types[hash],stddt)==0 ){
3481 sp->dtnum = hash + 1;
3482 break;
3483 }
3484 hash++;
3485 if( hash>=arraysize ) hash = 0;
3486 }
3487 if( types[hash]==0 ){
3488 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003489 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003490 if( types[hash]==0 ){
3491 fprintf(stderr,"Out of memory.\n");
3492 exit(1);
3493 }
3494 strcpy(types[hash],stddt);
3495 }
3496 }
3497
3498 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3499 name = lemp->name ? lemp->name : "Parse";
3500 lineno = *plineno;
3501 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3502 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3503 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3504 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3505 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003506 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003507 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3508 for(i=0; i<arraysize; i++){
3509 if( types[i]==0 ) continue;
3510 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3511 free(types[i]);
3512 }
drhc4dd3fd2008-01-22 01:48:05 +00003513 if( lemp->errsym->useCnt ){
3514 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3515 }
drh75897232000-05-29 14:26:00 +00003516 free(stddt);
3517 free(types);
3518 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3519 *plineno = lineno;
3520}
3521
drhb29b0a52002-02-23 19:39:46 +00003522/*
3523** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003524** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003525*/
drh8b582012003-10-21 13:16:03 +00003526static const char *minimum_size_type(int lwr, int upr){
3527 if( lwr>=0 ){
3528 if( upr<=255 ){
3529 return "unsigned char";
3530 }else if( upr<65535 ){
3531 return "unsigned short int";
3532 }else{
3533 return "unsigned int";
3534 }
3535 }else if( lwr>=-127 && upr<=127 ){
3536 return "signed char";
3537 }else if( lwr>=-32767 && upr<32767 ){
3538 return "short";
drhb29b0a52002-02-23 19:39:46 +00003539 }else{
drh8b582012003-10-21 13:16:03 +00003540 return "int";
drhb29b0a52002-02-23 19:39:46 +00003541 }
3542}
3543
drhfdbf9282003-10-21 16:34:41 +00003544/*
3545** Each state contains a set of token transaction and a set of
3546** nonterminal transactions. Each of these sets makes an instance
3547** of the following structure. An array of these structures is used
3548** to order the creation of entries in the yy_action[] table.
3549*/
3550struct axset {
3551 struct state *stp; /* A pointer to a state */
3552 int isTkn; /* True to use tokens. False for non-terminals */
3553 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003554 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003555};
3556
3557/*
3558** Compare to axset structures for sorting purposes
3559*/
3560static int axset_compare(const void *a, const void *b){
3561 struct axset *p1 = (struct axset*)a;
3562 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003563 int c;
3564 c = p2->nAction - p1->nAction;
3565 if( c==0 ){
3566 c = p2->iOrder - p1->iOrder;
3567 }
3568 assert( c!=0 || p1==p2 );
3569 return c;
drhfdbf9282003-10-21 16:34:41 +00003570}
3571
drhc4dd3fd2008-01-22 01:48:05 +00003572/*
3573** Write text on "out" that describes the rule "rp".
3574*/
3575static void writeRuleText(FILE *out, struct rule *rp){
3576 int j;
3577 fprintf(out,"%s ::=", rp->lhs->name);
3578 for(j=0; j<rp->nrhs; j++){
3579 struct symbol *sp = rp->rhs[j];
3580 fprintf(out," %s", sp->name);
3581 if( sp->type==MULTITERMINAL ){
3582 int k;
3583 for(k=1; k<sp->nsubsym; k++){
3584 fprintf(out,"|%s",sp->subsym[k]->name);
3585 }
3586 }
3587 }
3588}
3589
3590
drh75897232000-05-29 14:26:00 +00003591/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003592void ReportTable(
3593 struct lemon *lemp,
3594 int mhflag /* Output in makeheaders format if true */
3595){
drh75897232000-05-29 14:26:00 +00003596 FILE *out, *in;
3597 char line[LINESIZE];
3598 int lineno;
3599 struct state *stp;
3600 struct action *ap;
3601 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003602 struct acttab *pActtab;
icculusa3191192010-02-17 05:40:34 +00003603 int i, j, n;
icculus9e44cf12010-02-14 17:14:22 +00003604 const char *name;
drh8b582012003-10-21 13:16:03 +00003605 int mnTknOfst, mxTknOfst;
3606 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003607 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003608
3609 in = tplt_open(lemp);
3610 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003611 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003612 if( out==0 ){
3613 fclose(in);
3614 return;
3615 }
3616 lineno = 1;
3617 tplt_xfer(lemp->name,in,out,&lineno);
3618
3619 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003620 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003621 if( mhflag ){
3622 char *name = file_makename(lemp, ".h");
3623 fprintf(out,"#include \"%s\"\n", name); lineno++;
3624 free(name);
3625 }
3626 tplt_xfer(lemp->name,in,out,&lineno);
3627
3628 /* Generate #defines for all tokens */
3629 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003630 const char *prefix;
drh75897232000-05-29 14:26:00 +00003631 fprintf(out,"#if INTERFACE\n"); lineno++;
3632 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3633 else prefix = "";
3634 for(i=1; i<lemp->nterminal; i++){
3635 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3636 lineno++;
3637 }
3638 fprintf(out,"#endif\n"); lineno++;
3639 }
3640 tplt_xfer(lemp->name,in,out,&lineno);
3641
3642 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003643 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003644 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003645 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3646 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003647 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003648 if( lemp->wildcard ){
3649 fprintf(out,"#define YYWILDCARD %d\n",
3650 lemp->wildcard->index); lineno++;
3651 }
drh75897232000-05-29 14:26:00 +00003652 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003653 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003654 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003655 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3656 }else{
3657 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3658 }
drhca44b5a2007-02-22 23:06:58 +00003659 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003660 if( mhflag ){
3661 fprintf(out,"#if INTERFACE\n"); lineno++;
3662 }
3663 name = lemp->name ? lemp->name : "Parse";
3664 if( lemp->arg && lemp->arg[0] ){
3665 int i;
drh87cf1372008-08-13 20:09:06 +00003666 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003667 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3668 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003669 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3670 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3671 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3672 name,lemp->arg,&lemp->arg[i]); lineno++;
3673 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3674 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003675 }else{
drh1f245e42002-03-11 13:55:50 +00003676 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3677 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3678 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3679 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003680 }
3681 if( mhflag ){
3682 fprintf(out,"#endif\n"); lineno++;
3683 }
3684 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3685 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003686 if( lemp->errsym->useCnt ){
3687 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3688 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3689 }
drh0bd1f4e2002-06-06 18:54:39 +00003690 if( lemp->has_fallback ){
3691 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3692 }
drh75897232000-05-29 14:26:00 +00003693 tplt_xfer(lemp->name,in,out,&lineno);
3694
drh8b582012003-10-21 13:16:03 +00003695 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003696 **
drh8b582012003-10-21 13:16:03 +00003697 ** yy_action[] A single table containing all actions.
3698 ** yy_lookahead[] A table containing the lookahead for each entry in
3699 ** yy_action. Used to detect hash collisions.
3700 ** yy_shift_ofst[] For each state, the offset into yy_action for
3701 ** shifting terminals.
3702 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3703 ** shifting non-terminals after a reduce.
3704 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003705 */
drh75897232000-05-29 14:26:00 +00003706
drh8b582012003-10-21 13:16:03 +00003707 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003708 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003709 if( ax==0 ){
3710 fprintf(stderr,"malloc failed\n");
3711 exit(1);
3712 }
drh75897232000-05-29 14:26:00 +00003713 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003714 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003715 ax[i*2].stp = stp;
3716 ax[i*2].isTkn = 1;
3717 ax[i*2].nAction = stp->nTknAct;
3718 ax[i*2+1].stp = stp;
3719 ax[i*2+1].isTkn = 0;
3720 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003721 }
drh8b582012003-10-21 13:16:03 +00003722 mxTknOfst = mnTknOfst = 0;
3723 mxNtOfst = mnNtOfst = 0;
3724
drhfdbf9282003-10-21 16:34:41 +00003725 /* Compute the action table. In order to try to keep the size of the
3726 ** action table to a minimum, the heuristic of placing the largest action
3727 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003728 */
drhe594bc32009-11-03 13:02:25 +00003729 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003730 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003731 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003732 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3733 stp = ax[i].stp;
3734 if( ax[i].isTkn ){
3735 for(ap=stp->ap; ap; ap=ap->next){
3736 int action;
3737 if( ap->sp->index>=lemp->nterminal ) continue;
3738 action = compute_action(lemp, ap);
3739 if( action<0 ) continue;
3740 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003741 }
drhfdbf9282003-10-21 16:34:41 +00003742 stp->iTknOfst = acttab_insert(pActtab);
3743 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3744 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3745 }else{
3746 for(ap=stp->ap; ap; ap=ap->next){
3747 int action;
3748 if( ap->sp->index<lemp->nterminal ) continue;
3749 if( ap->sp->index==lemp->nsymbol ) continue;
3750 action = compute_action(lemp, ap);
3751 if( action<0 ) continue;
3752 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003753 }
drhfdbf9282003-10-21 16:34:41 +00003754 stp->iNtOfst = acttab_insert(pActtab);
3755 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3756 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003757 }
3758 }
drhfdbf9282003-10-21 16:34:41 +00003759 free(ax);
drh8b582012003-10-21 13:16:03 +00003760
3761 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003762 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003763 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3764 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003765 for(i=j=0; i<n; i++){
3766 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003767 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003768 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003769 fprintf(out, " %4d,", action);
3770 if( j==9 || i==n-1 ){
3771 fprintf(out, "\n"); lineno++;
3772 j = 0;
3773 }else{
3774 j++;
3775 }
3776 }
3777 fprintf(out, "};\n"); lineno++;
3778
3779 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003780 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003781 for(i=j=0; i<n; i++){
3782 int la = acttab_yylookahead(pActtab, i);
3783 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003784 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003785 fprintf(out, " %4d,", la);
3786 if( j==9 || i==n-1 ){
3787 fprintf(out, "\n"); lineno++;
3788 j = 0;
3789 }else{
3790 j++;
3791 }
3792 }
3793 fprintf(out, "};\n"); lineno++;
3794
3795 /* Output the yy_shift_ofst[] table */
3796 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003797 n = lemp->nstate;
3798 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003799 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3800 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3801 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003802 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003803 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003804 for(i=j=0; i<n; i++){
3805 int ofst;
3806 stp = lemp->sorted[i];
3807 ofst = stp->iTknOfst;
3808 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003809 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003810 fprintf(out, " %4d,", ofst);
3811 if( j==9 || i==n-1 ){
3812 fprintf(out, "\n"); lineno++;
3813 j = 0;
3814 }else{
3815 j++;
3816 }
3817 }
3818 fprintf(out, "};\n"); lineno++;
3819
3820 /* Output the yy_reduce_ofst[] table */
3821 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003822 n = lemp->nstate;
3823 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003824 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3825 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3826 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003827 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003828 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003829 for(i=j=0; i<n; i++){
3830 int ofst;
3831 stp = lemp->sorted[i];
3832 ofst = stp->iNtOfst;
3833 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003834 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003835 fprintf(out, " %4d,", ofst);
3836 if( j==9 || i==n-1 ){
3837 fprintf(out, "\n"); lineno++;
3838 j = 0;
3839 }else{
3840 j++;
3841 }
3842 }
3843 fprintf(out, "};\n"); lineno++;
3844
3845 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003846 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003847 n = lemp->nstate;
3848 for(i=j=0; i<n; i++){
3849 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003850 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003851 fprintf(out, " %4d,", stp->iDflt);
3852 if( j==9 || i==n-1 ){
3853 fprintf(out, "\n"); lineno++;
3854 j = 0;
3855 }else{
3856 j++;
3857 }
3858 }
3859 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003860 tplt_xfer(lemp->name,in,out,&lineno);
3861
drh0bd1f4e2002-06-06 18:54:39 +00003862 /* Generate the table of fallback tokens.
3863 */
3864 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003865 int mx = lemp->nterminal - 1;
3866 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3867 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003868 struct symbol *p = lemp->symbols[i];
3869 if( p->fallback==0 ){
3870 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3871 }else{
3872 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3873 p->name, p->fallback->name);
3874 }
3875 lineno++;
3876 }
3877 }
3878 tplt_xfer(lemp->name, in, out, &lineno);
3879
3880 /* Generate a table containing the symbolic name of every symbol
3881 */
drh75897232000-05-29 14:26:00 +00003882 for(i=0; i<lemp->nsymbol; i++){
3883 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3884 fprintf(out," %-15s",line);
3885 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3886 }
3887 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3888 tplt_xfer(lemp->name,in,out,&lineno);
3889
drh0bd1f4e2002-06-06 18:54:39 +00003890 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003891 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003892 ** when tracing REDUCE actions.
3893 */
3894 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3895 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003896 fprintf(out," /* %3d */ \"", i);
3897 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003898 fprintf(out,"\",\n"); lineno++;
3899 }
3900 tplt_xfer(lemp->name,in,out,&lineno);
3901
drh75897232000-05-29 14:26:00 +00003902 /* Generate code which executes every time a symbol is popped from
3903 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003904 ** (In other words, generate the %destructor actions)
3905 */
drh75897232000-05-29 14:26:00 +00003906 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003907 int once = 1;
drh75897232000-05-29 14:26:00 +00003908 for(i=0; i<lemp->nsymbol; i++){
3909 struct symbol *sp = lemp->symbols[i];
3910 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003911 if( once ){
3912 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3913 once = 0;
3914 }
drhc53eed12009-06-12 17:46:19 +00003915 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003916 }
3917 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3918 if( i<lemp->nsymbol ){
3919 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3920 fprintf(out," break;\n"); lineno++;
3921 }
3922 }
drh8d659732005-01-13 23:54:06 +00003923 if( lemp->vardest ){
3924 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003925 int once = 1;
drh8d659732005-01-13 23:54:06 +00003926 for(i=0; i<lemp->nsymbol; i++){
3927 struct symbol *sp = lemp->symbols[i];
3928 if( sp==0 || sp->type==TERMINAL ||
3929 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003930 if( once ){
3931 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3932 once = 0;
3933 }
drhc53eed12009-06-12 17:46:19 +00003934 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003935 dflt_sp = sp;
3936 }
3937 if( dflt_sp!=0 ){
3938 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003939 }
drh4dc8ef52008-07-01 17:13:57 +00003940 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003941 }
drh75897232000-05-29 14:26:00 +00003942 for(i=0; i<lemp->nsymbol; i++){
3943 struct symbol *sp = lemp->symbols[i];
3944 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003945 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003946
3947 /* Combine duplicate destructors into a single case */
3948 for(j=i+1; j<lemp->nsymbol; j++){
3949 struct symbol *sp2 = lemp->symbols[j];
3950 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3951 && sp2->dtnum==sp->dtnum
3952 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003953 fprintf(out," case %d: /* %s */\n",
3954 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003955 sp2->destructor = 0;
3956 }
3957 }
3958
drh75897232000-05-29 14:26:00 +00003959 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3960 fprintf(out," break;\n"); lineno++;
3961 }
drh75897232000-05-29 14:26:00 +00003962 tplt_xfer(lemp->name,in,out,&lineno);
3963
3964 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003965 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003966 tplt_xfer(lemp->name,in,out,&lineno);
3967
3968 /* Generate the table of rule information
3969 **
3970 ** Note: This code depends on the fact that rules are number
3971 ** sequentually beginning with 0.
3972 */
3973 for(rp=lemp->rule; rp; rp=rp->next){
3974 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3975 }
3976 tplt_xfer(lemp->name,in,out,&lineno);
3977
3978 /* Generate code which execution during each REDUCE action */
3979 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003980 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003981 }
drhc53eed12009-06-12 17:46:19 +00003982 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003983 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003984 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003985 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003986 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003987 fprintf(out," case %d: /* ", rp->index);
3988 writeRuleText(out, rp);
3989 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003990 for(rp2=rp->next; rp2; rp2=rp2->next){
3991 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003992 fprintf(out," case %d: /* ", rp2->index);
3993 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003994 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003995 rp2->code = 0;
3996 }
3997 }
drh75897232000-05-29 14:26:00 +00003998 emit_code(out,rp,lemp,&lineno);
3999 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00004000 rp->code = 0;
drh75897232000-05-29 14:26:00 +00004001 }
drhc53eed12009-06-12 17:46:19 +00004002 /* Finally, output the default: rule. We choose as the default: all
4003 ** empty actions. */
4004 fprintf(out," default:\n"); lineno++;
4005 for(rp=lemp->rule; rp; rp=rp->next){
4006 if( rp->code==0 ) continue;
4007 assert( rp->code[0]=='\n' && rp->code[1]==0 );
4008 fprintf(out," /* (%d) ", rp->index);
4009 writeRuleText(out, rp);
4010 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
4011 }
4012 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00004013 tplt_xfer(lemp->name,in,out,&lineno);
4014
4015 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00004016 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004017 tplt_xfer(lemp->name,in,out,&lineno);
4018
4019 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004020 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004021 tplt_xfer(lemp->name,in,out,&lineno);
4022
4023 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004024 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004025 tplt_xfer(lemp->name,in,out,&lineno);
4026
4027 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004028 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004029
4030 fclose(in);
4031 fclose(out);
4032 return;
4033}
4034
4035/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004036void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004037{
4038 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004039 const char *prefix;
drh75897232000-05-29 14:26:00 +00004040 char line[LINESIZE];
4041 char pattern[LINESIZE];
4042 int i;
4043
4044 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4045 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004046 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004047 if( in ){
4048 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4049 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4050 if( strcmp(line,pattern) ) break;
4051 }
4052 fclose(in);
4053 if( i==lemp->nterminal ){
4054 /* No change in the file. Don't rewrite it. */
4055 return;
4056 }
4057 }
drh2aa6ca42004-09-10 00:14:04 +00004058 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004059 if( out ){
4060 for(i=1; i<lemp->nterminal; i++){
4061 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4062 }
4063 fclose(out);
4064 }
4065 return;
4066}
4067
4068/* Reduce the size of the action tables, if possible, by making use
4069** of defaults.
4070**
drhb59499c2002-02-23 18:45:13 +00004071** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004072** it the default. Except, there is no default if the wildcard token
4073** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004074*/
icculus9e44cf12010-02-14 17:14:22 +00004075void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004076{
4077 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004078 struct action *ap, *ap2;
4079 struct rule *rp, *rp2, *rbest;
4080 int nbest, n;
drh75897232000-05-29 14:26:00 +00004081 int i;
drhe09daa92006-06-10 13:29:31 +00004082 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004083
4084 for(i=0; i<lemp->nstate; i++){
4085 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004086 nbest = 0;
4087 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004088 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004089
drhb59499c2002-02-23 18:45:13 +00004090 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004091 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4092 usesWildcard = 1;
4093 }
drhb59499c2002-02-23 18:45:13 +00004094 if( ap->type!=REDUCE ) continue;
4095 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004096 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004097 if( rp==rbest ) continue;
4098 n = 1;
4099 for(ap2=ap->next; ap2; ap2=ap2->next){
4100 if( ap2->type!=REDUCE ) continue;
4101 rp2 = ap2->x.rp;
4102 if( rp2==rbest ) continue;
4103 if( rp2==rp ) n++;
4104 }
4105 if( n>nbest ){
4106 nbest = n;
4107 rbest = rp;
drh75897232000-05-29 14:26:00 +00004108 }
4109 }
drhb59499c2002-02-23 18:45:13 +00004110
4111 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004112 ** is not at least 1 or if the wildcard token is a possible
4113 ** lookahead.
4114 */
4115 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004116
drhb59499c2002-02-23 18:45:13 +00004117
4118 /* Combine matching REDUCE actions into a single default */
4119 for(ap=stp->ap; ap; ap=ap->next){
4120 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4121 }
drh75897232000-05-29 14:26:00 +00004122 assert( ap );
4123 ap->sp = Symbol_new("{default}");
4124 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004125 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004126 }
4127 stp->ap = Action_sort(stp->ap);
4128 }
4129}
drhb59499c2002-02-23 18:45:13 +00004130
drhada354d2005-11-05 15:03:59 +00004131
4132/*
4133** Compare two states for sorting purposes. The smaller state is the
4134** one with the most non-terminal actions. If they have the same number
4135** of non-terminal actions, then the smaller is the one with the most
4136** token actions.
4137*/
4138static int stateResortCompare(const void *a, const void *b){
4139 const struct state *pA = *(const struct state**)a;
4140 const struct state *pB = *(const struct state**)b;
4141 int n;
4142
4143 n = pB->nNtAct - pA->nNtAct;
4144 if( n==0 ){
4145 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004146 if( n==0 ){
4147 n = pB->statenum - pA->statenum;
4148 }
drhada354d2005-11-05 15:03:59 +00004149 }
drhe594bc32009-11-03 13:02:25 +00004150 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004151 return n;
4152}
4153
4154
4155/*
4156** Renumber and resort states so that states with fewer choices
4157** occur at the end. Except, keep state 0 as the first state.
4158*/
icculus9e44cf12010-02-14 17:14:22 +00004159void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004160{
4161 int i;
4162 struct state *stp;
4163 struct action *ap;
4164
4165 for(i=0; i<lemp->nstate; i++){
4166 stp = lemp->sorted[i];
4167 stp->nTknAct = stp->nNtAct = 0;
4168 stp->iDflt = lemp->nstate + lemp->nrule;
4169 stp->iTknOfst = NO_OFFSET;
4170 stp->iNtOfst = NO_OFFSET;
4171 for(ap=stp->ap; ap; ap=ap->next){
4172 if( compute_action(lemp,ap)>=0 ){
4173 if( ap->sp->index<lemp->nterminal ){
4174 stp->nTknAct++;
4175 }else if( ap->sp->index<lemp->nsymbol ){
4176 stp->nNtAct++;
4177 }else{
4178 stp->iDflt = compute_action(lemp, ap);
4179 }
4180 }
4181 }
4182 }
4183 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4184 stateResortCompare);
4185 for(i=0; i<lemp->nstate; i++){
4186 lemp->sorted[i]->statenum = i;
4187 }
4188}
4189
4190
drh75897232000-05-29 14:26:00 +00004191/***************** From the file "set.c" ************************************/
4192/*
4193** Set manipulation routines for the LEMON parser generator.
4194*/
4195
4196static int size = 0;
4197
4198/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004199void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004200{
4201 size = n+1;
4202}
4203
4204/* Allocate a new set */
4205char *SetNew(){
4206 char *s;
drh9892c5d2007-12-21 00:02:11 +00004207 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004208 if( s==0 ){
4209 extern void memory_error();
4210 memory_error();
4211 }
drh75897232000-05-29 14:26:00 +00004212 return s;
4213}
4214
4215/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004216void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004217{
4218 free(s);
4219}
4220
4221/* Add a new element to the set. Return TRUE if the element was added
4222** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004223int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004224{
4225 int rv;
drh9892c5d2007-12-21 00:02:11 +00004226 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004227 rv = s[e];
4228 s[e] = 1;
4229 return !rv;
4230}
4231
4232/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004233int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004234{
4235 int i, progress;
4236 progress = 0;
4237 for(i=0; i<size; i++){
4238 if( s2[i]==0 ) continue;
4239 if( s1[i]==0 ){
4240 progress = 1;
4241 s1[i] = 1;
4242 }
4243 }
4244 return progress;
4245}
4246/********************** From the file "table.c" ****************************/
4247/*
4248** All code in this file has been automatically generated
4249** from a specification in the file
4250** "table.q"
4251** by the associative array code building program "aagen".
4252** Do not edit this file! Instead, edit the specification
4253** file, then rerun aagen.
4254*/
4255/*
4256** Code for processing tables in the LEMON parser generator.
4257*/
4258
icculus9e44cf12010-02-14 17:14:22 +00004259PRIVATE int strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004260{
4261 int h = 0;
4262 while( *x) h = h*13 + *(x++);
4263 return h;
4264}
4265
4266/* Works like strdup, sort of. Save a string in malloced memory, but
4267** keep strings in a table so that the same string is not in more
4268** than one place.
4269*/
icculus9e44cf12010-02-14 17:14:22 +00004270const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004271{
icculus9e44cf12010-02-14 17:14:22 +00004272 const char *z;
4273 char *cpy;
drh75897232000-05-29 14:26:00 +00004274
drh916f75f2006-07-17 00:19:39 +00004275 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004276 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004277 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4278 strcpy(cpy,y);
4279 z = cpy;
drh75897232000-05-29 14:26:00 +00004280 Strsafe_insert(z);
4281 }
4282 MemoryCheck(z);
4283 return z;
4284}
4285
4286/* There is one instance of the following structure for each
4287** associative array of type "x1".
4288*/
4289struct s_x1 {
4290 int size; /* The number of available slots. */
4291 /* Must be a power of 2 greater than or */
4292 /* equal to 1 */
4293 int count; /* Number of currently slots filled */
4294 struct s_x1node *tbl; /* The data stored here */
4295 struct s_x1node **ht; /* Hash table for lookups */
4296};
4297
4298/* There is one instance of this structure for every data element
4299** in an associative array of type "x1".
4300*/
4301typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004302 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004303 struct s_x1node *next; /* Next entry with the same hash */
4304 struct s_x1node **from; /* Previous link */
4305} x1node;
4306
4307/* There is only one instance of the array, which is the following */
4308static struct s_x1 *x1a;
4309
4310/* Allocate a new associative array */
4311void Strsafe_init(){
4312 if( x1a ) return;
4313 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4314 if( x1a ){
4315 x1a->size = 1024;
4316 x1a->count = 0;
4317 x1a->tbl = (x1node*)malloc(
4318 (sizeof(x1node) + sizeof(x1node*))*1024 );
4319 if( x1a->tbl==0 ){
4320 free(x1a);
4321 x1a = 0;
4322 }else{
4323 int i;
4324 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4325 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4326 }
4327 }
4328}
4329/* Insert a new record into the array. Return TRUE if successful.
4330** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004331int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004332{
4333 x1node *np;
4334 int h;
4335 int ph;
4336
4337 if( x1a==0 ) return 0;
4338 ph = strhash(data);
4339 h = ph & (x1a->size-1);
4340 np = x1a->ht[h];
4341 while( np ){
4342 if( strcmp(np->data,data)==0 ){
4343 /* An existing entry with the same key is found. */
4344 /* Fail because overwrite is not allows. */
4345 return 0;
4346 }
4347 np = np->next;
4348 }
4349 if( x1a->count>=x1a->size ){
4350 /* Need to make the hash table bigger */
4351 int i,size;
4352 struct s_x1 array;
4353 array.size = size = x1a->size*2;
4354 array.count = x1a->count;
4355 array.tbl = (x1node*)malloc(
4356 (sizeof(x1node) + sizeof(x1node*))*size );
4357 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4358 array.ht = (x1node**)&(array.tbl[size]);
4359 for(i=0; i<size; i++) array.ht[i] = 0;
4360 for(i=0; i<x1a->count; i++){
4361 x1node *oldnp, *newnp;
4362 oldnp = &(x1a->tbl[i]);
4363 h = strhash(oldnp->data) & (size-1);
4364 newnp = &(array.tbl[i]);
4365 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4366 newnp->next = array.ht[h];
4367 newnp->data = oldnp->data;
4368 newnp->from = &(array.ht[h]);
4369 array.ht[h] = newnp;
4370 }
4371 free(x1a->tbl);
4372 *x1a = array;
4373 }
4374 /* Insert the new data */
4375 h = ph & (x1a->size-1);
4376 np = &(x1a->tbl[x1a->count++]);
4377 np->data = data;
4378 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4379 np->next = x1a->ht[h];
4380 x1a->ht[h] = np;
4381 np->from = &(x1a->ht[h]);
4382 return 1;
4383}
4384
4385/* Return a pointer to data assigned to the given key. Return NULL
4386** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004387const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004388{
4389 int h;
4390 x1node *np;
4391
4392 if( x1a==0 ) return 0;
4393 h = strhash(key) & (x1a->size-1);
4394 np = x1a->ht[h];
4395 while( np ){
4396 if( strcmp(np->data,key)==0 ) break;
4397 np = np->next;
4398 }
4399 return np ? np->data : 0;
4400}
4401
4402/* Return a pointer to the (terminal or nonterminal) symbol "x".
4403** Create a new symbol if this is the first time "x" has been seen.
4404*/
icculus9e44cf12010-02-14 17:14:22 +00004405struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004406{
4407 struct symbol *sp;
4408
4409 sp = Symbol_find(x);
4410 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004411 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004412 MemoryCheck(sp);
4413 sp->name = Strsafe(x);
4414 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4415 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004416 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004417 sp->prec = -1;
4418 sp->assoc = UNK;
4419 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004420 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004421 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004422 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004423 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004424 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004425 Symbol_insert(sp,sp->name);
4426 }
drhc4dd3fd2008-01-22 01:48:05 +00004427 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004428 return sp;
4429}
4430
drh60d31652004-02-22 00:08:04 +00004431/* Compare two symbols for working purposes
4432**
4433** Symbols that begin with upper case letters (terminals or tokens)
4434** must sort before symbols that begin with lower case letters
4435** (non-terminals). Other than that, the order does not matter.
4436**
4437** We find experimentally that leaving the symbols in their original
4438** order (the order they appeared in the grammar file) gives the
4439** smallest parser tables in SQLite.
4440*/
icculus9e44cf12010-02-14 17:14:22 +00004441int Symbolcmpp(const void *_a, const void *_b)
4442{
4443 const struct symbol **a = (const struct symbol **) _a;
4444 const struct symbol **b = (const struct symbol **) _b;
drh60d31652004-02-22 00:08:04 +00004445 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4446 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004447 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004448 return i1-i2;
drh75897232000-05-29 14:26:00 +00004449}
4450
4451/* There is one instance of the following structure for each
4452** associative array of type "x2".
4453*/
4454struct s_x2 {
4455 int size; /* The number of available slots. */
4456 /* Must be a power of 2 greater than or */
4457 /* equal to 1 */
4458 int count; /* Number of currently slots filled */
4459 struct s_x2node *tbl; /* The data stored here */
4460 struct s_x2node **ht; /* Hash table for lookups */
4461};
4462
4463/* There is one instance of this structure for every data element
4464** in an associative array of type "x2".
4465*/
4466typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004467 struct symbol *data; /* The data */
4468 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004469 struct s_x2node *next; /* Next entry with the same hash */
4470 struct s_x2node **from; /* Previous link */
4471} x2node;
4472
4473/* There is only one instance of the array, which is the following */
4474static struct s_x2 *x2a;
4475
4476/* Allocate a new associative array */
4477void Symbol_init(){
4478 if( x2a ) return;
4479 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4480 if( x2a ){
4481 x2a->size = 128;
4482 x2a->count = 0;
4483 x2a->tbl = (x2node*)malloc(
4484 (sizeof(x2node) + sizeof(x2node*))*128 );
4485 if( x2a->tbl==0 ){
4486 free(x2a);
4487 x2a = 0;
4488 }else{
4489 int i;
4490 x2a->ht = (x2node**)&(x2a->tbl[128]);
4491 for(i=0; i<128; i++) x2a->ht[i] = 0;
4492 }
4493 }
4494}
4495/* Insert a new record into the array. Return TRUE if successful.
4496** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004497int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004498{
4499 x2node *np;
4500 int h;
4501 int ph;
4502
4503 if( x2a==0 ) return 0;
4504 ph = strhash(key);
4505 h = ph & (x2a->size-1);
4506 np = x2a->ht[h];
4507 while( np ){
4508 if( strcmp(np->key,key)==0 ){
4509 /* An existing entry with the same key is found. */
4510 /* Fail because overwrite is not allows. */
4511 return 0;
4512 }
4513 np = np->next;
4514 }
4515 if( x2a->count>=x2a->size ){
4516 /* Need to make the hash table bigger */
4517 int i,size;
4518 struct s_x2 array;
4519 array.size = size = x2a->size*2;
4520 array.count = x2a->count;
4521 array.tbl = (x2node*)malloc(
4522 (sizeof(x2node) + sizeof(x2node*))*size );
4523 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4524 array.ht = (x2node**)&(array.tbl[size]);
4525 for(i=0; i<size; i++) array.ht[i] = 0;
4526 for(i=0; i<x2a->count; i++){
4527 x2node *oldnp, *newnp;
4528 oldnp = &(x2a->tbl[i]);
4529 h = strhash(oldnp->key) & (size-1);
4530 newnp = &(array.tbl[i]);
4531 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4532 newnp->next = array.ht[h];
4533 newnp->key = oldnp->key;
4534 newnp->data = oldnp->data;
4535 newnp->from = &(array.ht[h]);
4536 array.ht[h] = newnp;
4537 }
4538 free(x2a->tbl);
4539 *x2a = array;
4540 }
4541 /* Insert the new data */
4542 h = ph & (x2a->size-1);
4543 np = &(x2a->tbl[x2a->count++]);
4544 np->key = key;
4545 np->data = data;
4546 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4547 np->next = x2a->ht[h];
4548 x2a->ht[h] = np;
4549 np->from = &(x2a->ht[h]);
4550 return 1;
4551}
4552
4553/* Return a pointer to data assigned to the given key. Return NULL
4554** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004555struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004556{
4557 int h;
4558 x2node *np;
4559
4560 if( x2a==0 ) return 0;
4561 h = strhash(key) & (x2a->size-1);
4562 np = x2a->ht[h];
4563 while( np ){
4564 if( strcmp(np->key,key)==0 ) break;
4565 np = np->next;
4566 }
4567 return np ? np->data : 0;
4568}
4569
4570/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004571struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004572{
4573 struct symbol *data;
4574 if( x2a && n>0 && n<=x2a->count ){
4575 data = x2a->tbl[n-1].data;
4576 }else{
4577 data = 0;
4578 }
4579 return data;
4580}
4581
4582/* Return the size of the array */
4583int Symbol_count()
4584{
4585 return x2a ? x2a->count : 0;
4586}
4587
4588/* Return an array of pointers to all data in the table.
4589** The array is obtained from malloc. Return NULL if memory allocation
4590** problems, or if the array is empty. */
4591struct symbol **Symbol_arrayof()
4592{
4593 struct symbol **array;
4594 int i,size;
4595 if( x2a==0 ) return 0;
4596 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004597 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004598 if( array ){
4599 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4600 }
4601 return array;
4602}
4603
4604/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004605int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004606{
icculus9e44cf12010-02-14 17:14:22 +00004607 const struct config *a = (struct config *) _a;
4608 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004609 int x;
4610 x = a->rp->index - b->rp->index;
4611 if( x==0 ) x = a->dot - b->dot;
4612 return x;
4613}
4614
4615/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004616PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004617{
4618 int rc;
4619 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4620 rc = a->rp->index - b->rp->index;
4621 if( rc==0 ) rc = a->dot - b->dot;
4622 }
4623 if( rc==0 ){
4624 if( a ) rc = 1;
4625 if( b ) rc = -1;
4626 }
4627 return rc;
4628}
4629
4630/* Hash a state */
icculus9e44cf12010-02-14 17:14:22 +00004631PRIVATE int statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004632{
4633 int h=0;
4634 while( a ){
4635 h = h*571 + a->rp->index*37 + a->dot;
4636 a = a->bp;
4637 }
4638 return h;
4639}
4640
4641/* Allocate a new state structure */
4642struct state *State_new()
4643{
icculus9e44cf12010-02-14 17:14:22 +00004644 struct state *newstate;
4645 newstate = (struct state *)calloc(1, sizeof(struct state) );
4646 MemoryCheck(newstate);
4647 return newstate;
drh75897232000-05-29 14:26:00 +00004648}
4649
4650/* There is one instance of the following structure for each
4651** associative array of type "x3".
4652*/
4653struct s_x3 {
4654 int size; /* The number of available slots. */
4655 /* Must be a power of 2 greater than or */
4656 /* equal to 1 */
4657 int count; /* Number of currently slots filled */
4658 struct s_x3node *tbl; /* The data stored here */
4659 struct s_x3node **ht; /* Hash table for lookups */
4660};
4661
4662/* There is one instance of this structure for every data element
4663** in an associative array of type "x3".
4664*/
4665typedef struct s_x3node {
4666 struct state *data; /* The data */
4667 struct config *key; /* The key */
4668 struct s_x3node *next; /* Next entry with the same hash */
4669 struct s_x3node **from; /* Previous link */
4670} x3node;
4671
4672/* There is only one instance of the array, which is the following */
4673static struct s_x3 *x3a;
4674
4675/* Allocate a new associative array */
4676void State_init(){
4677 if( x3a ) return;
4678 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4679 if( x3a ){
4680 x3a->size = 128;
4681 x3a->count = 0;
4682 x3a->tbl = (x3node*)malloc(
4683 (sizeof(x3node) + sizeof(x3node*))*128 );
4684 if( x3a->tbl==0 ){
4685 free(x3a);
4686 x3a = 0;
4687 }else{
4688 int i;
4689 x3a->ht = (x3node**)&(x3a->tbl[128]);
4690 for(i=0; i<128; i++) x3a->ht[i] = 0;
4691 }
4692 }
4693}
4694/* Insert a new record into the array. Return TRUE if successful.
4695** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004696int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004697{
4698 x3node *np;
4699 int h;
4700 int ph;
4701
4702 if( x3a==0 ) return 0;
4703 ph = statehash(key);
4704 h = ph & (x3a->size-1);
4705 np = x3a->ht[h];
4706 while( np ){
4707 if( statecmp(np->key,key)==0 ){
4708 /* An existing entry with the same key is found. */
4709 /* Fail because overwrite is not allows. */
4710 return 0;
4711 }
4712 np = np->next;
4713 }
4714 if( x3a->count>=x3a->size ){
4715 /* Need to make the hash table bigger */
4716 int i,size;
4717 struct s_x3 array;
4718 array.size = size = x3a->size*2;
4719 array.count = x3a->count;
4720 array.tbl = (x3node*)malloc(
4721 (sizeof(x3node) + sizeof(x3node*))*size );
4722 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4723 array.ht = (x3node**)&(array.tbl[size]);
4724 for(i=0; i<size; i++) array.ht[i] = 0;
4725 for(i=0; i<x3a->count; i++){
4726 x3node *oldnp, *newnp;
4727 oldnp = &(x3a->tbl[i]);
4728 h = statehash(oldnp->key) & (size-1);
4729 newnp = &(array.tbl[i]);
4730 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4731 newnp->next = array.ht[h];
4732 newnp->key = oldnp->key;
4733 newnp->data = oldnp->data;
4734 newnp->from = &(array.ht[h]);
4735 array.ht[h] = newnp;
4736 }
4737 free(x3a->tbl);
4738 *x3a = array;
4739 }
4740 /* Insert the new data */
4741 h = ph & (x3a->size-1);
4742 np = &(x3a->tbl[x3a->count++]);
4743 np->key = key;
4744 np->data = data;
4745 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4746 np->next = x3a->ht[h];
4747 x3a->ht[h] = np;
4748 np->from = &(x3a->ht[h]);
4749 return 1;
4750}
4751
4752/* Return a pointer to data assigned to the given key. Return NULL
4753** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004754struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004755{
4756 int h;
4757 x3node *np;
4758
4759 if( x3a==0 ) return 0;
4760 h = statehash(key) & (x3a->size-1);
4761 np = x3a->ht[h];
4762 while( np ){
4763 if( statecmp(np->key,key)==0 ) break;
4764 np = np->next;
4765 }
4766 return np ? np->data : 0;
4767}
4768
4769/* Return an array of pointers to all data in the table.
4770** The array is obtained from malloc. Return NULL if memory allocation
4771** problems, or if the array is empty. */
4772struct state **State_arrayof()
4773{
4774 struct state **array;
4775 int i,size;
4776 if( x3a==0 ) return 0;
4777 size = x3a->count;
4778 array = (struct state **)malloc( sizeof(struct state *)*size );
4779 if( array ){
4780 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4781 }
4782 return array;
4783}
4784
4785/* Hash a configuration */
icculus9e44cf12010-02-14 17:14:22 +00004786PRIVATE int confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004787{
4788 int h=0;
4789 h = h*571 + a->rp->index*37 + a->dot;
4790 return h;
4791}
4792
4793/* There is one instance of the following structure for each
4794** associative array of type "x4".
4795*/
4796struct s_x4 {
4797 int size; /* The number of available slots. */
4798 /* Must be a power of 2 greater than or */
4799 /* equal to 1 */
4800 int count; /* Number of currently slots filled */
4801 struct s_x4node *tbl; /* The data stored here */
4802 struct s_x4node **ht; /* Hash table for lookups */
4803};
4804
4805/* There is one instance of this structure for every data element
4806** in an associative array of type "x4".
4807*/
4808typedef struct s_x4node {
4809 struct config *data; /* The data */
4810 struct s_x4node *next; /* Next entry with the same hash */
4811 struct s_x4node **from; /* Previous link */
4812} x4node;
4813
4814/* There is only one instance of the array, which is the following */
4815static struct s_x4 *x4a;
4816
4817/* Allocate a new associative array */
4818void Configtable_init(){
4819 if( x4a ) return;
4820 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4821 if( x4a ){
4822 x4a->size = 64;
4823 x4a->count = 0;
4824 x4a->tbl = (x4node*)malloc(
4825 (sizeof(x4node) + sizeof(x4node*))*64 );
4826 if( x4a->tbl==0 ){
4827 free(x4a);
4828 x4a = 0;
4829 }else{
4830 int i;
4831 x4a->ht = (x4node**)&(x4a->tbl[64]);
4832 for(i=0; i<64; i++) x4a->ht[i] = 0;
4833 }
4834 }
4835}
4836/* Insert a new record into the array. Return TRUE if successful.
4837** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004838int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00004839{
4840 x4node *np;
4841 int h;
4842 int ph;
4843
4844 if( x4a==0 ) return 0;
4845 ph = confighash(data);
4846 h = ph & (x4a->size-1);
4847 np = x4a->ht[h];
4848 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004849 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00004850 /* An existing entry with the same key is found. */
4851 /* Fail because overwrite is not allows. */
4852 return 0;
4853 }
4854 np = np->next;
4855 }
4856 if( x4a->count>=x4a->size ){
4857 /* Need to make the hash table bigger */
4858 int i,size;
4859 struct s_x4 array;
4860 array.size = size = x4a->size*2;
4861 array.count = x4a->count;
4862 array.tbl = (x4node*)malloc(
4863 (sizeof(x4node) + sizeof(x4node*))*size );
4864 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4865 array.ht = (x4node**)&(array.tbl[size]);
4866 for(i=0; i<size; i++) array.ht[i] = 0;
4867 for(i=0; i<x4a->count; i++){
4868 x4node *oldnp, *newnp;
4869 oldnp = &(x4a->tbl[i]);
4870 h = confighash(oldnp->data) & (size-1);
4871 newnp = &(array.tbl[i]);
4872 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4873 newnp->next = array.ht[h];
4874 newnp->data = oldnp->data;
4875 newnp->from = &(array.ht[h]);
4876 array.ht[h] = newnp;
4877 }
4878 free(x4a->tbl);
4879 *x4a = array;
4880 }
4881 /* Insert the new data */
4882 h = ph & (x4a->size-1);
4883 np = &(x4a->tbl[x4a->count++]);
4884 np->data = data;
4885 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4886 np->next = x4a->ht[h];
4887 x4a->ht[h] = np;
4888 np->from = &(x4a->ht[h]);
4889 return 1;
4890}
4891
4892/* Return a pointer to data assigned to the given key. Return NULL
4893** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004894struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004895{
4896 int h;
4897 x4node *np;
4898
4899 if( x4a==0 ) return 0;
4900 h = confighash(key) & (x4a->size-1);
4901 np = x4a->ht[h];
4902 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004903 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00004904 np = np->next;
4905 }
4906 return np ? np->data : 0;
4907}
4908
4909/* Remove all data from the table. Pass each data to the function "f"
4910** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00004911void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00004912{
4913 int i;
4914 if( x4a==0 || x4a->count==0 ) return;
4915 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4916 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4917 x4a->count = 0;
4918 return;
4919}