blob: 057a883c1fbb327e68f4edf2717635be9cab4ddd [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drh75897232000-05-29 14:26:00 +00002** This file contains all sources (including headers) to the LEMON
3** LALR(1) parser generator. The sources have been combined into a
drh960e8c62001-04-03 16:53:21 +00004** single file to make it easy to include LEMON in the source tree
5** and Makefile of another program.
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** The author of this program disclaims copyright.
drh75897232000-05-29 14:26:00 +00008*/
9#include <stdio.h>
drhf9a2e7b2003-04-15 01:49:48 +000010#include <stdarg.h>
drh75897232000-05-29 14:26:00 +000011#include <string.h>
12#include <ctype.h>
drh8b582012003-10-21 13:16:03 +000013#include <stdlib.h>
drhe9278182007-07-18 18:16:29 +000014#include <assert.h>
drh75897232000-05-29 14:26:00 +000015
drh75897232000-05-29 14:26:00 +000016#ifndef __WIN32__
17# if defined(_WIN32) || defined(WIN32)
18# define __WIN32__
19# endif
20#endif
21
rse8f304482007-07-30 18:31:53 +000022#ifdef __WIN32__
23extern int access();
24#else
25#include <unistd.h>
26#endif
27
drh75897232000-05-29 14:26:00 +000028/* #define PRIVATE static */
29#define PRIVATE
30
31#ifdef TEST
32#define MAXRHS 5 /* Set low to exercise exception code */
33#else
34#define MAXRHS 1000
35#endif
36
icculusf5ad8242010-02-14 05:34:42 +000037static const char **made_files = NULL;
38static int made_files_count = 0;
39static int successful_exit = 0;
40static void LemonAtExit(void)
41{
42 /* if we failed, delete (most) files we made, to unconfuse build tools. */
43 int i;
44 for (i = 0; i < made_files_count; i++) {
45 if (!successful_exit) {
46 remove(made_files[i]);
47 }
icculusf5ad8242010-02-14 05:34:42 +000048 }
49 free(made_files);
50 made_files_count = 0;
51 made_files = NULL;
52}
53
drhe9278182007-07-18 18:16:29 +000054static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000055
drh87cf1372008-08-13 20:09:06 +000056/*
57** Compilers are getting increasingly pedantic about type conversions
58** as C evolves ever closer to Ada.... To work around the latest problems
59** we have to define the following variant of strlen().
60*/
61#define lemonStrlen(X) ((int)strlen(X))
62
icculus9e44cf12010-02-14 17:14:22 +000063/* a few forward declarations... */
64struct rule;
65struct lemon;
66struct action;
67
drhe9278182007-07-18 18:16:29 +000068static struct action *Action_new(void);
69static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000070
71/********** From the file "build.h" ************************************/
72void FindRulePrecedences();
73void FindFirstSets();
74void FindStates();
75void FindLinks();
76void FindFollowSets();
77void FindActions();
78
79/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +000080void Configlist_init(void);
81struct config *Configlist_add(struct rule *, int);
82struct config *Configlist_addbasis(struct rule *, int);
83void Configlist_closure(struct lemon *);
84void Configlist_sort(void);
85void Configlist_sortbasis(void);
86struct config *Configlist_return(void);
87struct config *Configlist_basis(void);
88void Configlist_eat(struct config *);
89void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +000090
91/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000092void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000093
94/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +000095enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
96 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +000097struct s_options {
icculus9e44cf12010-02-14 17:14:22 +000098 enum option_type type;
99 const char *label;
drh75897232000-05-29 14:26:00 +0000100 char *arg;
icculus9e44cf12010-02-14 17:14:22 +0000101 const char *message;
drh75897232000-05-29 14:26:00 +0000102};
icculus9e44cf12010-02-14 17:14:22 +0000103int OptInit(char**,struct s_options*,FILE*);
104int OptNArgs(void);
105char *OptArg(int);
106void OptErr(int);
107void OptPrint(void);
drh75897232000-05-29 14:26:00 +0000108
109/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000110void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000111
112/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000113struct plink *Plink_new(void);
114void Plink_add(struct plink **, struct config *);
115void Plink_copy(struct plink **, struct plink *);
116void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000117
118/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000119void Reprint(struct lemon *);
120void ReportOutput(struct lemon *);
121void ReportTable(struct lemon *, int);
122void ReportHeader(struct lemon *);
123void CompressTables(struct lemon *);
124void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000125
126/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000127void SetSize(int); /* All sets will be of size N */
128char *SetNew(void); /* A new set for element 0..N */
129void SetFree(char*); /* Deallocate a set */
drh75897232000-05-29 14:26:00 +0000130
icculus9e44cf12010-02-14 17:14:22 +0000131char *SetNew(void); /* A new set for element 0..N */
132int SetAdd(char*,int); /* Add element to a set */
133int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000134#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
135
136/********** From the file "struct.h" *************************************/
137/*
138** Principal data structures for the LEMON parser generator.
139*/
140
drhaa9f1122007-08-23 02:50:56 +0000141typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000142
143/* Symbols (terminals and nonterminals) of the grammar are stored
144** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000145enum symbol_type {
146 TERMINAL,
147 NONTERMINAL,
148 MULTITERMINAL
149};
150enum e_assoc {
drh75897232000-05-29 14:26:00 +0000151 LEFT,
152 RIGHT,
153 NONE,
154 UNK
icculus9e44cf12010-02-14 17:14:22 +0000155};
156struct symbol {
157 const char *name; /* Name of the symbol */
158 int index; /* Index number for this symbol */
159 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
160 struct rule *rule; /* Linked list of rules of this (if an NT) */
161 struct symbol *fallback; /* fallback token in case this token doesn't parse */
162 int prec; /* Precedence if defined (-1 otherwise) */
163 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000164 char *firstset; /* First-set for all rules of this symbol */
165 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000166 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000167 char *destructor; /* Code which executes whenever this symbol is
168 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000169 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000170 char *datatype; /* The data type of information held by this
171 ** object. Only used if type==NONTERMINAL */
172 int dtnum; /* The data type number. In the parser, the value
173 ** stack is a union. The .yy%d element of this
174 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000175 /* The following fields are used by MULTITERMINALs only */
176 int nsubsym; /* Number of constituent symbols in the MULTI */
177 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000178};
179
180/* Each production rule in the grammar is stored in the following
181** structure. */
182struct rule {
183 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000184 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000185 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000186 int ruleline; /* Line number for the rule */
187 int nrhs; /* Number of RHS symbols */
188 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000189 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000190 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000191 const char *code; /* The code executed when this rule is reduced */
drh75897232000-05-29 14:26:00 +0000192 struct symbol *precsym; /* Precedence symbol for this rule */
193 int index; /* An index number for this rule */
194 Boolean canReduce; /* True if this rule is ever reduced */
195 struct rule *nextlhs; /* Next rule with the same LHS */
196 struct rule *next; /* Next rule in the global list */
197};
198
199/* A configuration is a production rule of the grammar together with
200** a mark (dot) showing how much of that rule has been processed so far.
201** Configurations also contain a follow-set which is a list of terminal
202** symbols which are allowed to immediately follow the end of the rule.
203** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000204enum cfgstatus {
205 COMPLETE,
206 INCOMPLETE
207};
drh75897232000-05-29 14:26:00 +0000208struct config {
209 struct rule *rp; /* The rule upon which the configuration is based */
210 int dot; /* The parse point */
211 char *fws; /* Follow-set for this configuration only */
212 struct plink *fplp; /* Follow-set forward propagation links */
213 struct plink *bplp; /* Follow-set backwards propagation links */
214 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000215 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000216 struct config *next; /* Next configuration in the state */
217 struct config *bp; /* The next basis configuration */
218};
219
icculus9e44cf12010-02-14 17:14:22 +0000220enum e_action {
221 SHIFT,
222 ACCEPT,
223 REDUCE,
224 ERROR,
225 SSCONFLICT, /* A shift/shift conflict */
226 SRCONFLICT, /* Was a reduce, but part of a conflict */
227 RRCONFLICT, /* Was a reduce, but part of a conflict */
228 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
229 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
230 NOT_USED /* Deleted by compression */
231};
232
drh75897232000-05-29 14:26:00 +0000233/* Every shift or reduce operation is stored as one of the following */
234struct action {
235 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000236 enum e_action type;
drh75897232000-05-29 14:26:00 +0000237 union {
238 struct state *stp; /* The new state, if a shift */
239 struct rule *rp; /* The rule, if a reduce */
240 } x;
241 struct action *next; /* Next action for this state */
242 struct action *collide; /* Next action with the same hash */
243};
244
245/* Each state of the generated parser's finite state machine
246** is encoded as an instance of the following structure. */
247struct state {
248 struct config *bp; /* The basis configurations for this state */
249 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000250 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000251 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000252 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
253 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
254 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000255};
drh8b582012003-10-21 13:16:03 +0000256#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000257
258/* A followset propagation link indicates that the contents of one
259** configuration followset should be propagated to another whenever
260** the first changes. */
261struct plink {
262 struct config *cfp; /* The configuration to which linked */
263 struct plink *next; /* The next propagate link */
264};
265
266/* The state vector for the entire parser generator is recorded as
267** follows. (LEMON uses no global variables and makes little use of
268** static variables. Fields in the following structure can be thought
269** of as begin global variables in the program.) */
270struct lemon {
271 struct state **sorted; /* Table of states sorted by state number */
272 struct rule *rule; /* List of all rules */
273 int nstate; /* Number of states */
274 int nrule; /* Number of rules */
275 int nsymbol; /* Number of terminal and nonterminal symbols */
276 int nterminal; /* Number of terminal symbols */
277 struct symbol **symbols; /* Sorted array of pointers to symbols */
278 int errorcnt; /* Number of errors */
279 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000280 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000281 char *name; /* Name of the generated parser */
282 char *arg; /* Declaration of the 3th argument to parser */
283 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000284 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000285 char *start; /* Name of the start symbol for the grammar */
286 char *stacksize; /* Size of the parser stack */
287 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000288 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000289 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000290 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000291 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000292 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000293 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000294 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000295 char *filename; /* Name of the input file */
296 char *outname; /* Name of the current output file */
297 char *tokenprefix; /* A prefix added to token names in the .h file */
298 int nconflict; /* Number of parsing conflicts */
299 int tablesize; /* Size of the parse tables */
300 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000301 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000302 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000303 char *argv0; /* Name of the program */
304};
305
306#define MemoryCheck(X) if((X)==0){ \
307 extern void memory_error(); \
308 memory_error(); \
309}
310
311/**************** From the file "table.h" *********************************/
312/*
313** All code in this file has been automatically generated
314** from a specification in the file
315** "table.q"
316** by the associative array code building program "aagen".
317** Do not edit this file! Instead, edit the specification
318** file, then rerun aagen.
319*/
320/*
321** Code for processing tables in the LEMON parser generator.
322*/
drh75897232000-05-29 14:26:00 +0000323/* Routines for handling a strings */
324
icculus9e44cf12010-02-14 17:14:22 +0000325const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000326
icculus9e44cf12010-02-14 17:14:22 +0000327void Strsafe_init(void);
328int Strsafe_insert(const char *);
329const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000330
331/* Routines for handling symbols of the grammar */
332
icculus9e44cf12010-02-14 17:14:22 +0000333struct symbol *Symbol_new(const char *);
334int Symbolcmpp(const void *, const void *);
335void Symbol_init(void);
336int Symbol_insert(struct symbol *, const char *);
337struct symbol *Symbol_find(const char *);
338struct symbol *Symbol_Nth(int);
339int Symbol_count(void);
340struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000341
342/* Routines to manage the state table */
343
icculus9e44cf12010-02-14 17:14:22 +0000344int Configcmp(const char *, const char *);
345struct state *State_new(void);
346void State_init(void);
347int State_insert(struct state *, struct config *);
348struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000349struct state **State_arrayof(/* */);
350
351/* Routines used for efficiency in Configlist_add */
352
icculus9e44cf12010-02-14 17:14:22 +0000353void Configtable_init(void);
354int Configtable_insert(struct config *);
355struct config *Configtable_find(struct config *);
356void Configtable_clear(int(*)(struct config *));
357
drh75897232000-05-29 14:26:00 +0000358/****************** From the file "action.c" *******************************/
359/*
360** Routines processing parser actions in the LEMON parser generator.
361*/
362
363/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000364static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000365 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000366 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000367
368 if( freelist==0 ){
369 int i;
370 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000371 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000372 if( freelist==0 ){
373 fprintf(stderr,"Unable to allocate memory for a new parser action.");
374 exit(1);
375 }
376 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
377 freelist[amt-1].next = 0;
378 }
icculus9e44cf12010-02-14 17:14:22 +0000379 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000380 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000381 return newaction;
drh75897232000-05-29 14:26:00 +0000382}
383
drhe9278182007-07-18 18:16:29 +0000384/* Compare two actions for sorting purposes. Return negative, zero, or
385** positive if the first action is less than, equal to, or greater than
386** the first
387*/
388static int actioncmp(
389 struct action *ap1,
390 struct action *ap2
391){
drh75897232000-05-29 14:26:00 +0000392 int rc;
393 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000394 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000395 rc = (int)ap1->type - (int)ap2->type;
396 }
397 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000398 rc = ap1->x.rp->index - ap2->x.rp->index;
399 }
drhe594bc32009-11-03 13:02:25 +0000400 if( rc==0 ){
401 rc = ap2 - ap1;
402 }
drh75897232000-05-29 14:26:00 +0000403 return rc;
404}
405
406/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000407static struct action *Action_sort(
408 struct action *ap
409){
410 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
411 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000412 return ap;
413}
414
icculus9e44cf12010-02-14 17:14:22 +0000415void Action_add(
416 struct action **app,
417 enum e_action type,
418 struct symbol *sp,
419 char *arg
420){
421 struct action *newaction;
422 newaction = Action_new();
423 newaction->next = *app;
424 *app = newaction;
425 newaction->type = type;
426 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000427 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000428 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000429 }else{
icculus9e44cf12010-02-14 17:14:22 +0000430 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000431 }
432}
drh8b582012003-10-21 13:16:03 +0000433/********************** New code to implement the "acttab" module ***********/
434/*
435** This module implements routines use to construct the yy_action[] table.
436*/
437
438/*
439** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000440** the following structure.
441**
442** The yy_action table maps the pair (state_number, lookahead) into an
443** action_number. The table is an array of integers pairs. The state_number
444** determines an initial offset into the yy_action array. The lookahead
445** value is then added to this initial offset to get an index X into the
446** yy_action array. If the aAction[X].lookahead equals the value of the
447** of the lookahead input, then the value of the action_number output is
448** aAction[X].action. If the lookaheads do not match then the
449** default action for the state_number is returned.
450**
451** All actions associated with a single state_number are first entered
452** into aLookahead[] using multiple calls to acttab_action(). Then the
453** actions for that single state_number are placed into the aAction[]
454** array with a single call to acttab_insert(). The acttab_insert() call
455** also resets the aLookahead[] array in preparation for the next
456** state number.
drh8b582012003-10-21 13:16:03 +0000457*/
icculus9e44cf12010-02-14 17:14:22 +0000458struct lookahead_action {
459 int lookahead; /* Value of the lookahead token */
460 int action; /* Action to take on the given lookahead */
461};
drh8b582012003-10-21 13:16:03 +0000462typedef struct acttab acttab;
463struct acttab {
464 int nAction; /* Number of used slots in aAction[] */
465 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000466 struct lookahead_action
467 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000468 *aLookahead; /* A single new transaction set */
469 int mnLookahead; /* Minimum aLookahead[].lookahead */
470 int mnAction; /* Action associated with mnLookahead */
471 int mxLookahead; /* Maximum aLookahead[].lookahead */
472 int nLookahead; /* Used slots in aLookahead[] */
473 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
474};
475
476/* Return the number of entries in the yy_action table */
477#define acttab_size(X) ((X)->nAction)
478
479/* The value for the N-th entry in yy_action */
480#define acttab_yyaction(X,N) ((X)->aAction[N].action)
481
482/* The value for the N-th entry in yy_lookahead */
483#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
484
485/* Free all memory associated with the given acttab */
486void acttab_free(acttab *p){
487 free( p->aAction );
488 free( p->aLookahead );
489 free( p );
490}
491
492/* Allocate a new acttab structure */
493acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000494 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000495 if( p==0 ){
496 fprintf(stderr,"Unable to allocate memory for a new acttab.");
497 exit(1);
498 }
499 memset(p, 0, sizeof(*p));
500 return p;
501}
502
drh8dc3e8f2010-01-07 03:53:03 +0000503/* Add a new action to the current transaction set.
504**
505** This routine is called once for each lookahead for a particular
506** state.
drh8b582012003-10-21 13:16:03 +0000507*/
508void acttab_action(acttab *p, int lookahead, int action){
509 if( p->nLookahead>=p->nLookaheadAlloc ){
510 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000511 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000512 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
513 if( p->aLookahead==0 ){
514 fprintf(stderr,"malloc failed\n");
515 exit(1);
516 }
517 }
518 if( p->nLookahead==0 ){
519 p->mxLookahead = lookahead;
520 p->mnLookahead = lookahead;
521 p->mnAction = action;
522 }else{
523 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
524 if( p->mnLookahead>lookahead ){
525 p->mnLookahead = lookahead;
526 p->mnAction = action;
527 }
528 }
529 p->aLookahead[p->nLookahead].lookahead = lookahead;
530 p->aLookahead[p->nLookahead].action = action;
531 p->nLookahead++;
532}
533
534/*
535** Add the transaction set built up with prior calls to acttab_action()
536** into the current action table. Then reset the transaction set back
537** to an empty set in preparation for a new round of acttab_action() calls.
538**
539** Return the offset into the action table of the new transaction.
540*/
541int acttab_insert(acttab *p){
542 int i, j, k, n;
543 assert( p->nLookahead>0 );
544
545 /* Make sure we have enough space to hold the expanded action table
546 ** in the worst case. The worst case occurs if the transaction set
547 ** must be appended to the current action table
548 */
drh784d86f2004-02-19 18:41:53 +0000549 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000550 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000551 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000552 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000553 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000554 sizeof(p->aAction[0])*p->nActionAlloc);
555 if( p->aAction==0 ){
556 fprintf(stderr,"malloc failed\n");
557 exit(1);
558 }
drhfdbf9282003-10-21 16:34:41 +0000559 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000560 p->aAction[i].lookahead = -1;
561 p->aAction[i].action = -1;
562 }
563 }
564
drh8dc3e8f2010-01-07 03:53:03 +0000565 /* Scan the existing action table looking for an offset that is a
566 ** duplicate of the current transaction set. Fall out of the loop
567 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000568 **
569 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
570 */
drh8dc3e8f2010-01-07 03:53:03 +0000571 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000572 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000573 /* All lookaheads and actions in the aLookahead[] transaction
574 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000575 if( p->aAction[i].action!=p->mnAction ) continue;
576 for(j=0; j<p->nLookahead; j++){
577 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
578 if( k<0 || k>=p->nAction ) break;
579 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
580 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
581 }
582 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000583
584 /* No possible lookahead value that is not in the aLookahead[]
585 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000586 n = 0;
587 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000588 if( p->aAction[j].lookahead<0 ) continue;
589 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000590 }
drhfdbf9282003-10-21 16:34:41 +0000591 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000592 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000593 }
drh8b582012003-10-21 13:16:03 +0000594 }
595 }
drh8dc3e8f2010-01-07 03:53:03 +0000596
597 /* If no existing offsets exactly match the current transaction, find an
598 ** an empty offset in the aAction[] table in which we can add the
599 ** aLookahead[] transaction.
600 */
drhf16371d2009-11-03 19:18:31 +0000601 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000602 /* Look for holes in the aAction[] table that fit the current
603 ** aLookahead[] transaction. Leave i set to the offset of the hole.
604 ** If no holes are found, i is left at p->nAction, which means the
605 ** transaction will be appended. */
606 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000607 if( p->aAction[i].lookahead<0 ){
608 for(j=0; j<p->nLookahead; j++){
609 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
610 if( k<0 ) break;
611 if( p->aAction[k].lookahead>=0 ) break;
612 }
613 if( j<p->nLookahead ) continue;
614 for(j=0; j<p->nAction; j++){
615 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
616 }
617 if( j==p->nAction ){
618 break; /* Fits in empty slots */
619 }
620 }
621 }
622 }
drh8b582012003-10-21 13:16:03 +0000623 /* Insert transaction set at index i. */
624 for(j=0; j<p->nLookahead; j++){
625 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
626 p->aAction[k] = p->aLookahead[j];
627 if( k>=p->nAction ) p->nAction = k+1;
628 }
629 p->nLookahead = 0;
630
631 /* Return the offset that is added to the lookahead in order to get the
632 ** index into yy_action of the action */
633 return i - p->mnLookahead;
634}
635
drh75897232000-05-29 14:26:00 +0000636/********************** From the file "build.c" *****************************/
637/*
638** Routines to construction the finite state machine for the LEMON
639** parser generator.
640*/
641
642/* Find a precedence symbol of every rule in the grammar.
643**
644** Those rules which have a precedence symbol coded in the input
645** grammar using the "[symbol]" construct will already have the
646** rp->precsym field filled. Other rules take as their precedence
647** symbol the first RHS symbol with a defined precedence. If there
648** are not RHS symbols with a defined precedence, the precedence
649** symbol field is left blank.
650*/
icculus9e44cf12010-02-14 17:14:22 +0000651void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000652{
653 struct rule *rp;
654 for(rp=xp->rule; rp; rp=rp->next){
655 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000656 int i, j;
657 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
658 struct symbol *sp = rp->rhs[i];
659 if( sp->type==MULTITERMINAL ){
660 for(j=0; j<sp->nsubsym; j++){
661 if( sp->subsym[j]->prec>=0 ){
662 rp->precsym = sp->subsym[j];
663 break;
664 }
665 }
666 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000667 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000668 }
669 }
670 }
671 }
672 return;
673}
674
675/* Find all nonterminals which will generate the empty string.
676** Then go back and compute the first sets of every nonterminal.
677** The first set is the set of all terminal symbols which can begin
678** a string generated by that nonterminal.
679*/
icculus9e44cf12010-02-14 17:14:22 +0000680void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000681{
drhfd405312005-11-06 04:06:59 +0000682 int i, j;
drh75897232000-05-29 14:26:00 +0000683 struct rule *rp;
684 int progress;
685
686 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000687 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000688 }
689 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
690 lemp->symbols[i]->firstset = SetNew();
691 }
692
693 /* First compute all lambdas */
694 do{
695 progress = 0;
696 for(rp=lemp->rule; rp; rp=rp->next){
697 if( rp->lhs->lambda ) continue;
698 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000699 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000700 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000701 }
702 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000703 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000704 progress = 1;
705 }
706 }
707 }while( progress );
708
709 /* Now compute all first sets */
710 do{
711 struct symbol *s1, *s2;
712 progress = 0;
713 for(rp=lemp->rule; rp; rp=rp->next){
714 s1 = rp->lhs;
715 for(i=0; i<rp->nrhs; i++){
716 s2 = rp->rhs[i];
717 if( s2->type==TERMINAL ){
718 progress += SetAdd(s1->firstset,s2->index);
719 break;
drhfd405312005-11-06 04:06:59 +0000720 }else if( s2->type==MULTITERMINAL ){
721 for(j=0; j<s2->nsubsym; j++){
722 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
723 }
724 break;
drh75897232000-05-29 14:26:00 +0000725 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000726 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000727 }else{
728 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000729 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000730 }
731 }
732 }
733 }while( progress );
734 return;
735}
736
737/* Compute all LR(0) states for the grammar. Links
738** are added to between some states so that the LR(1) follow sets
739** can be computed later.
740*/
icculus9e44cf12010-02-14 17:14:22 +0000741PRIVATE struct state *getstate(struct lemon *); /* forward reference */
742void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000743{
744 struct symbol *sp;
745 struct rule *rp;
746
747 Configlist_init();
748
749 /* Find the start symbol */
750 if( lemp->start ){
751 sp = Symbol_find(lemp->start);
752 if( sp==0 ){
753 ErrorMsg(lemp->filename,0,
754"The specified start symbol \"%s\" is not \
755in a nonterminal of the grammar. \"%s\" will be used as the start \
756symbol instead.",lemp->start,lemp->rule->lhs->name);
757 lemp->errorcnt++;
758 sp = lemp->rule->lhs;
759 }
760 }else{
761 sp = lemp->rule->lhs;
762 }
763
764 /* Make sure the start symbol doesn't occur on the right-hand side of
765 ** any rule. Report an error if it does. (YACC would generate a new
766 ** start symbol in this case.) */
767 for(rp=lemp->rule; rp; rp=rp->next){
768 int i;
769 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000770 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000771 ErrorMsg(lemp->filename,0,
772"The start symbol \"%s\" occurs on the \
773right-hand side of a rule. This will result in a parser which \
774does not work properly.",sp->name);
775 lemp->errorcnt++;
776 }
777 }
778 }
779
780 /* The basis configuration set for the first state
781 ** is all rules which have the start symbol as their
782 ** left-hand side */
783 for(rp=sp->rule; rp; rp=rp->nextlhs){
784 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000785 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000786 newcfp = Configlist_addbasis(rp,0);
787 SetAdd(newcfp->fws,0);
788 }
789
790 /* Compute the first state. All other states will be
791 ** computed automatically during the computation of the first one.
792 ** The returned pointer to the first state is not used. */
793 (void)getstate(lemp);
794 return;
795}
796
797/* Return a pointer to a state which is described by the configuration
798** list which has been built from calls to Configlist_add.
799*/
icculus9e44cf12010-02-14 17:14:22 +0000800PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
801PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000802{
803 struct config *cfp, *bp;
804 struct state *stp;
805
806 /* Extract the sorted basis of the new state. The basis was constructed
807 ** by prior calls to "Configlist_addbasis()". */
808 Configlist_sortbasis();
809 bp = Configlist_basis();
810
811 /* Get a state with the same basis */
812 stp = State_find(bp);
813 if( stp ){
814 /* A state with the same basis already exists! Copy all the follow-set
815 ** propagation links from the state under construction into the
816 ** preexisting state, then return a pointer to the preexisting state */
817 struct config *x, *y;
818 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
819 Plink_copy(&y->bplp,x->bplp);
820 Plink_delete(x->fplp);
821 x->fplp = x->bplp = 0;
822 }
823 cfp = Configlist_return();
824 Configlist_eat(cfp);
825 }else{
826 /* This really is a new state. Construct all the details */
827 Configlist_closure(lemp); /* Compute the configuration closure */
828 Configlist_sort(); /* Sort the configuration closure */
829 cfp = Configlist_return(); /* Get a pointer to the config list */
830 stp = State_new(); /* A new state structure */
831 MemoryCheck(stp);
832 stp->bp = bp; /* Remember the configuration basis */
833 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000834 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000835 stp->ap = 0; /* No actions, yet. */
836 State_insert(stp,stp->bp); /* Add to the state table */
837 buildshifts(lemp,stp); /* Recursively compute successor states */
838 }
839 return stp;
840}
841
drhfd405312005-11-06 04:06:59 +0000842/*
843** Return true if two symbols are the same.
844*/
icculus9e44cf12010-02-14 17:14:22 +0000845int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000846{
847 int i;
848 if( a==b ) return 1;
849 if( a->type!=MULTITERMINAL ) return 0;
850 if( b->type!=MULTITERMINAL ) return 0;
851 if( a->nsubsym!=b->nsubsym ) return 0;
852 for(i=0; i<a->nsubsym; i++){
853 if( a->subsym[i]!=b->subsym[i] ) return 0;
854 }
855 return 1;
856}
857
drh75897232000-05-29 14:26:00 +0000858/* Construct all successor states to the given state. A "successor"
859** state is any state which can be reached by a shift action.
860*/
icculus9e44cf12010-02-14 17:14:22 +0000861PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000862{
863 struct config *cfp; /* For looping thru the config closure of "stp" */
864 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000865 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000866 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
867 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
868 struct state *newstp; /* A pointer to a successor state */
869
870 /* Each configuration becomes complete after it contibutes to a successor
871 ** state. Initially, all configurations are incomplete */
872 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
873
874 /* Loop through all configurations of the state "stp" */
875 for(cfp=stp->cfp; cfp; cfp=cfp->next){
876 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
877 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
878 Configlist_reset(); /* Reset the new config set */
879 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
880
881 /* For every configuration in the state "stp" which has the symbol "sp"
882 ** following its dot, add the same configuration to the basis set under
883 ** construction but with the dot shifted one symbol to the right. */
884 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
885 if( bcfp->status==COMPLETE ) continue; /* Already used */
886 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
887 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000888 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000889 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000890 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
891 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000892 }
893
894 /* Get a pointer to the state described by the basis configuration set
895 ** constructed in the preceding loop */
896 newstp = getstate(lemp);
897
898 /* The state "newstp" is reached from the state "stp" by a shift action
899 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000900 if( sp->type==MULTITERMINAL ){
901 int i;
902 for(i=0; i<sp->nsubsym; i++){
903 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
904 }
905 }else{
906 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
907 }
drh75897232000-05-29 14:26:00 +0000908 }
909}
910
911/*
912** Construct the propagation links
913*/
icculus9e44cf12010-02-14 17:14:22 +0000914void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000915{
916 int i;
917 struct config *cfp, *other;
918 struct state *stp;
919 struct plink *plp;
920
921 /* Housekeeping detail:
922 ** Add to every propagate link a pointer back to the state to
923 ** which the link is attached. */
924 for(i=0; i<lemp->nstate; i++){
925 stp = lemp->sorted[i];
926 for(cfp=stp->cfp; cfp; cfp=cfp->next){
927 cfp->stp = stp;
928 }
929 }
930
931 /* Convert all backlinks into forward links. Only the forward
932 ** links are used in the follow-set computation. */
933 for(i=0; i<lemp->nstate; i++){
934 stp = lemp->sorted[i];
935 for(cfp=stp->cfp; cfp; cfp=cfp->next){
936 for(plp=cfp->bplp; plp; plp=plp->next){
937 other = plp->cfp;
938 Plink_add(&other->fplp,cfp);
939 }
940 }
941 }
942}
943
944/* Compute all followsets.
945**
946** A followset is the set of all symbols which can come immediately
947** after a configuration.
948*/
icculus9e44cf12010-02-14 17:14:22 +0000949void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000950{
951 int i;
952 struct config *cfp;
953 struct plink *plp;
954 int progress;
955 int change;
956
957 for(i=0; i<lemp->nstate; i++){
958 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
959 cfp->status = INCOMPLETE;
960 }
961 }
962
963 do{
964 progress = 0;
965 for(i=0; i<lemp->nstate; i++){
966 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
967 if( cfp->status==COMPLETE ) continue;
968 for(plp=cfp->fplp; plp; plp=plp->next){
969 change = SetUnion(plp->cfp->fws,cfp->fws);
970 if( change ){
971 plp->cfp->status = INCOMPLETE;
972 progress = 1;
973 }
974 }
975 cfp->status = COMPLETE;
976 }
977 }
978 }while( progress );
979}
980
icculus9e44cf12010-02-14 17:14:22 +0000981static int resolve_conflict(struct action *,struct action *, struct symbol *);
drh75897232000-05-29 14:26:00 +0000982
983/* Compute the reduce actions, and resolve conflicts.
984*/
icculus9e44cf12010-02-14 17:14:22 +0000985void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000986{
987 int i,j;
988 struct config *cfp;
989 struct state *stp;
990 struct symbol *sp;
991 struct rule *rp;
992
993 /* Add all of the reduce actions
994 ** A reduce action is added for each element of the followset of
995 ** a configuration which has its dot at the extreme right.
996 */
997 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
998 stp = lemp->sorted[i];
999 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
1000 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
1001 for(j=0; j<lemp->nterminal; j++){
1002 if( SetFind(cfp->fws,j) ){
1003 /* Add a reduce action to the state "stp" which will reduce by the
1004 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +00001005 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +00001006 }
1007 }
1008 }
1009 }
1010 }
1011
1012 /* Add the accepting token */
1013 if( lemp->start ){
1014 sp = Symbol_find(lemp->start);
1015 if( sp==0 ) sp = lemp->rule->lhs;
1016 }else{
1017 sp = lemp->rule->lhs;
1018 }
1019 /* Add to the first state (which is always the starting state of the
1020 ** finite state machine) an action to ACCEPT if the lookahead is the
1021 ** start nonterminal. */
1022 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1023
1024 /* Resolve conflicts */
1025 for(i=0; i<lemp->nstate; i++){
1026 struct action *ap, *nap;
1027 struct state *stp;
1028 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001029 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001030 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001031 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001032 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1033 /* The two actions "ap" and "nap" have the same lookahead.
1034 ** Figure out which one should be used */
1035 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1036 }
1037 }
1038 }
1039
1040 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001041 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001042 for(i=0; i<lemp->nstate; i++){
1043 struct action *ap;
1044 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001045 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001046 }
1047 }
1048 for(rp=lemp->rule; rp; rp=rp->next){
1049 if( rp->canReduce ) continue;
1050 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1051 lemp->errorcnt++;
1052 }
1053}
1054
1055/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001056** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001057**
1058** NO LONGER TRUE:
1059** To resolve a conflict, first look to see if either action
1060** is on an error rule. In that case, take the action which
1061** is not associated with the error rule. If neither or both
1062** actions are associated with an error rule, then try to
1063** use precedence to resolve the conflict.
1064**
1065** If either action is a SHIFT, then it must be apx. This
1066** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1067*/
icculus9e44cf12010-02-14 17:14:22 +00001068static int resolve_conflict(
1069 struct action *apx,
1070 struct action *apy,
1071 struct symbol *errsym /* The error symbol (if defined. NULL otherwise) */
1072){
drh75897232000-05-29 14:26:00 +00001073 struct symbol *spx, *spy;
1074 int errcnt = 0;
1075 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001076 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001077 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001078 errcnt++;
1079 }
drh75897232000-05-29 14:26:00 +00001080 if( apx->type==SHIFT && apy->type==REDUCE ){
1081 spx = apx->sp;
1082 spy = apy->x.rp->precsym;
1083 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1084 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001085 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001086 errcnt++;
1087 }else if( spx->prec>spy->prec ){ /* Lower precedence wins */
1088 apy->type = RD_RESOLVED;
1089 }else if( spx->prec<spy->prec ){
1090 apx->type = SH_RESOLVED;
1091 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1092 apy->type = RD_RESOLVED; /* associativity */
1093 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1094 apx->type = SH_RESOLVED;
1095 }else{
1096 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001097 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001098 errcnt++;
1099 }
1100 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1101 spx = apx->x.rp->precsym;
1102 spy = apy->x.rp->precsym;
1103 if( spx==0 || spy==0 || spx->prec<0 ||
1104 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001105 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001106 errcnt++;
1107 }else if( spx->prec>spy->prec ){
1108 apy->type = RD_RESOLVED;
1109 }else if( spx->prec<spy->prec ){
1110 apx->type = RD_RESOLVED;
1111 }
1112 }else{
drhb59499c2002-02-23 18:45:13 +00001113 assert(
1114 apx->type==SH_RESOLVED ||
1115 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001116 apx->type==SSCONFLICT ||
1117 apx->type==SRCONFLICT ||
1118 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001119 apy->type==SH_RESOLVED ||
1120 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001121 apy->type==SSCONFLICT ||
1122 apy->type==SRCONFLICT ||
1123 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001124 );
1125 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1126 ** REDUCEs on the list. If we reach this point it must be because
1127 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001128 }
1129 return errcnt;
1130}
1131/********************* From the file "configlist.c" *************************/
1132/*
1133** Routines to processing a configuration list and building a state
1134** in the LEMON parser generator.
1135*/
1136
1137static struct config *freelist = 0; /* List of free configurations */
1138static struct config *current = 0; /* Top of list of configurations */
1139static struct config **currentend = 0; /* Last on list of configs */
1140static struct config *basis = 0; /* Top of list of basis configs */
1141static struct config **basisend = 0; /* End of list of basis configs */
1142
1143/* Return a pointer to a new configuration */
1144PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001145 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001146 if( freelist==0 ){
1147 int i;
1148 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001149 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001150 if( freelist==0 ){
1151 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1152 exit(1);
1153 }
1154 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1155 freelist[amt-1].next = 0;
1156 }
icculus9e44cf12010-02-14 17:14:22 +00001157 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001158 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001159 return newcfg;
drh75897232000-05-29 14:26:00 +00001160}
1161
1162/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001163PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001164{
1165 old->next = freelist;
1166 freelist = old;
1167}
1168
1169/* Initialized the configuration list builder */
1170void Configlist_init(){
1171 current = 0;
1172 currentend = &current;
1173 basis = 0;
1174 basisend = &basis;
1175 Configtable_init();
1176 return;
1177}
1178
1179/* Initialized the configuration list builder */
1180void Configlist_reset(){
1181 current = 0;
1182 currentend = &current;
1183 basis = 0;
1184 basisend = &basis;
1185 Configtable_clear(0);
1186 return;
1187}
1188
1189/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001190struct config *Configlist_add(
1191 struct rule *rp, /* The rule */
1192 int dot /* Index into the RHS of the rule where the dot goes */
1193){
drh75897232000-05-29 14:26:00 +00001194 struct config *cfp, model;
1195
1196 assert( currentend!=0 );
1197 model.rp = rp;
1198 model.dot = dot;
1199 cfp = Configtable_find(&model);
1200 if( cfp==0 ){
1201 cfp = newconfig();
1202 cfp->rp = rp;
1203 cfp->dot = dot;
1204 cfp->fws = SetNew();
1205 cfp->stp = 0;
1206 cfp->fplp = cfp->bplp = 0;
1207 cfp->next = 0;
1208 cfp->bp = 0;
1209 *currentend = cfp;
1210 currentend = &cfp->next;
1211 Configtable_insert(cfp);
1212 }
1213 return cfp;
1214}
1215
1216/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001217struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001218{
1219 struct config *cfp, model;
1220
1221 assert( basisend!=0 );
1222 assert( currentend!=0 );
1223 model.rp = rp;
1224 model.dot = dot;
1225 cfp = Configtable_find(&model);
1226 if( cfp==0 ){
1227 cfp = newconfig();
1228 cfp->rp = rp;
1229 cfp->dot = dot;
1230 cfp->fws = SetNew();
1231 cfp->stp = 0;
1232 cfp->fplp = cfp->bplp = 0;
1233 cfp->next = 0;
1234 cfp->bp = 0;
1235 *currentend = cfp;
1236 currentend = &cfp->next;
1237 *basisend = cfp;
1238 basisend = &cfp->bp;
1239 Configtable_insert(cfp);
1240 }
1241 return cfp;
1242}
1243
1244/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001245void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001246{
1247 struct config *cfp, *newcfp;
1248 struct rule *rp, *newrp;
1249 struct symbol *sp, *xsp;
1250 int i, dot;
1251
1252 assert( currentend!=0 );
1253 for(cfp=current; cfp; cfp=cfp->next){
1254 rp = cfp->rp;
1255 dot = cfp->dot;
1256 if( dot>=rp->nrhs ) continue;
1257 sp = rp->rhs[dot];
1258 if( sp->type==NONTERMINAL ){
1259 if( sp->rule==0 && sp!=lemp->errsym ){
1260 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1261 sp->name);
1262 lemp->errorcnt++;
1263 }
1264 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1265 newcfp = Configlist_add(newrp,0);
1266 for(i=dot+1; i<rp->nrhs; i++){
1267 xsp = rp->rhs[i];
1268 if( xsp->type==TERMINAL ){
1269 SetAdd(newcfp->fws,xsp->index);
1270 break;
drhfd405312005-11-06 04:06:59 +00001271 }else if( xsp->type==MULTITERMINAL ){
1272 int k;
1273 for(k=0; k<xsp->nsubsym; k++){
1274 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1275 }
1276 break;
drh75897232000-05-29 14:26:00 +00001277 }else{
1278 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001279 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001280 }
1281 }
1282 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1283 }
1284 }
1285 }
1286 return;
1287}
1288
1289/* Sort the configuration list */
1290void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001291 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001292 currentend = 0;
1293 return;
1294}
1295
1296/* Sort the basis configuration list */
1297void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001298 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001299 basisend = 0;
1300 return;
1301}
1302
1303/* Return a pointer to the head of the configuration list and
1304** reset the list */
1305struct config *Configlist_return(){
1306 struct config *old;
1307 old = current;
1308 current = 0;
1309 currentend = 0;
1310 return old;
1311}
1312
1313/* Return a pointer to the head of the configuration list and
1314** reset the list */
1315struct config *Configlist_basis(){
1316 struct config *old;
1317 old = basis;
1318 basis = 0;
1319 basisend = 0;
1320 return old;
1321}
1322
1323/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001324void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001325{
1326 struct config *nextcfp;
1327 for(; cfp; cfp=nextcfp){
1328 nextcfp = cfp->next;
1329 assert( cfp->fplp==0 );
1330 assert( cfp->bplp==0 );
1331 if( cfp->fws ) SetFree(cfp->fws);
1332 deleteconfig(cfp);
1333 }
1334 return;
1335}
1336/***************** From the file "error.c" *********************************/
1337/*
1338** Code for printing error message.
1339*/
1340
drhf9a2e7b2003-04-15 01:49:48 +00001341void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001342 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001343 fprintf(stderr, "%s:%d: ", filename, lineno);
1344 va_start(ap, format);
1345 vfprintf(stderr,format,ap);
1346 va_end(ap);
1347 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001348}
1349/**************** From the file "main.c" ************************************/
1350/*
1351** Main program file for the LEMON parser generator.
1352*/
1353
1354/* Report an out-of-memory condition and abort. This function
1355** is used mostly by the "MemoryCheck" macro in struct.h
1356*/
1357void memory_error(){
1358 fprintf(stderr,"Out of memory. Aborting...\n");
1359 exit(1);
1360}
1361
drh6d08b4d2004-07-20 12:45:22 +00001362static int nDefine = 0; /* Number of -D options on the command line */
1363static char **azDefine = 0; /* Name of the -D macros */
1364
1365/* This routine is called with the argument to each -D command-line option.
1366** Add the macro defined to the azDefine array.
1367*/
1368static void handle_D_option(char *z){
1369 char **paz;
1370 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001371 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001372 if( azDefine==0 ){
1373 fprintf(stderr,"out of memory\n");
1374 exit(1);
1375 }
1376 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001377 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001378 if( *paz==0 ){
1379 fprintf(stderr,"out of memory\n");
1380 exit(1);
1381 }
1382 strcpy(*paz, z);
1383 for(z=*paz; *z && *z!='='; z++){}
1384 *z = 0;
1385}
1386
icculus3e143bd2010-02-14 00:48:49 +00001387static char *user_templatename = NULL;
1388static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001389 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001390 if( user_templatename==0 ){
1391 memory_error();
1392 }
1393 strcpy(user_templatename, z);
1394}
drh75897232000-05-29 14:26:00 +00001395
1396/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001397int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001398{
1399 static int version = 0;
1400 static int rpflag = 0;
1401 static int basisflag = 0;
1402 static int compress = 0;
1403 static int quiet = 0;
1404 static int statistics = 0;
1405 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001406 static int nolinenosflag = 0;
drh75897232000-05-29 14:26:00 +00001407 static struct s_options options[] = {
1408 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1409 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001410 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001411 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001412 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001413 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1414 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drh75897232000-05-29 14:26:00 +00001415 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drh6d08b4d2004-07-20 12:45:22 +00001416 {OPT_FLAG, "s", (char*)&statistics,
1417 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001418 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1419 {OPT_FLAG,0,0,0}
1420 };
1421 int i;
icculus42585cf2010-02-14 05:19:56 +00001422 int exitcode;
drh75897232000-05-29 14:26:00 +00001423 struct lemon lem;
1424
icculusf5ad8242010-02-14 05:34:42 +00001425 atexit(LemonAtExit);
1426
drhb0c86772000-06-02 23:21:26 +00001427 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001428 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001429 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001430 exit(0);
1431 }
drhb0c86772000-06-02 23:21:26 +00001432 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001433 fprintf(stderr,"Exactly one filename argument is required.\n");
1434 exit(1);
1435 }
drh954f6b42006-06-13 13:27:46 +00001436 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001437 lem.errorcnt = 0;
1438
1439 /* Initialize the machine */
1440 Strsafe_init();
1441 Symbol_init();
1442 State_init();
1443 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001444 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001445 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001446 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001447 Symbol_new("$");
1448 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001449 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001450
1451 /* Parse the input file */
1452 Parse(&lem);
1453 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001454 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001455 fprintf(stderr,"Empty grammar.\n");
1456 exit(1);
1457 }
1458
1459 /* Count and index the symbols of the grammar */
1460 lem.nsymbol = Symbol_count();
1461 Symbol_new("{default}");
1462 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001463 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
icculus9e44cf12010-02-14 17:14:22 +00001464 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp);
drh75897232000-05-29 14:26:00 +00001465 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1466 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1467 lem.nterminal = i;
1468
1469 /* Generate a reprint of the grammar, if requested on the command line */
1470 if( rpflag ){
1471 Reprint(&lem);
1472 }else{
1473 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001474 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001475
1476 /* Find the precedence for every production rule (that has one) */
1477 FindRulePrecedences(&lem);
1478
1479 /* Compute the lambda-nonterminals and the first-sets for every
1480 ** nonterminal */
1481 FindFirstSets(&lem);
1482
1483 /* Compute all LR(0) states. Also record follow-set propagation
1484 ** links so that the follow-set can be computed later */
1485 lem.nstate = 0;
1486 FindStates(&lem);
1487 lem.sorted = State_arrayof();
1488
1489 /* Tie up loose ends on the propagation links */
1490 FindLinks(&lem);
1491
1492 /* Compute the follow set of every reducible configuration */
1493 FindFollowSets(&lem);
1494
1495 /* Compute the action tables */
1496 FindActions(&lem);
1497
1498 /* Compress the action tables */
1499 if( compress==0 ) CompressTables(&lem);
1500
drhada354d2005-11-05 15:03:59 +00001501 /* Reorder and renumber the states so that states with fewer choices
1502 ** occur at the end. */
1503 ResortStates(&lem);
1504
drh75897232000-05-29 14:26:00 +00001505 /* Generate a report of the parser generated. (the "y.output" file) */
1506 if( !quiet ) ReportOutput(&lem);
1507
1508 /* Generate the source code for the parser */
1509 ReportTable(&lem, mhflag);
1510
1511 /* Produce a header file for use by the scanner. (This step is
1512 ** omitted if the "-m" option is used because makeheaders will
1513 ** generate the file for us.) */
1514 if( !mhflag ) ReportHeader(&lem);
1515 }
1516 if( statistics ){
1517 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1518 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1519 printf(" %d states, %d parser table entries, %d conflicts\n",
1520 lem.nstate, lem.tablesize, lem.nconflict);
1521 }
icculus8e158022010-02-16 16:09:03 +00001522 if( lem.nconflict > 0 ){
1523 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001524 }
1525
1526 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001527 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculusf5ad8242010-02-14 05:34:42 +00001528 successful_exit = (exitcode == 0);
icculus42585cf2010-02-14 05:19:56 +00001529 exit(exitcode);
1530 return (exitcode);
drh75897232000-05-29 14:26:00 +00001531}
1532/******************** From the file "msort.c" *******************************/
1533/*
1534** A generic merge-sort program.
1535**
1536** USAGE:
1537** Let "ptr" be a pointer to some structure which is at the head of
1538** a null-terminated list. Then to sort the list call:
1539**
1540** ptr = msort(ptr,&(ptr->next),cmpfnc);
1541**
1542** In the above, "cmpfnc" is a pointer to a function which compares
1543** two instances of the structure and returns an integer, as in
1544** strcmp. The second argument is a pointer to the pointer to the
1545** second element of the linked list. This address is used to compute
1546** the offset to the "next" field within the structure. The offset to
1547** the "next" field must be constant for all structures in the list.
1548**
1549** The function returns a new pointer which is the head of the list
1550** after sorting.
1551**
1552** ALGORITHM:
1553** Merge-sort.
1554*/
1555
1556/*
1557** Return a pointer to the next structure in the linked list.
1558*/
drhba99af52001-10-25 20:37:16 +00001559#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001560
1561/*
1562** Inputs:
1563** a: A sorted, null-terminated linked list. (May be null).
1564** b: A sorted, null-terminated linked list. (May be null).
1565** cmp: A pointer to the comparison function.
1566** offset: Offset in the structure to the "next" field.
1567**
1568** Return Value:
1569** A pointer to the head of a sorted list containing the elements
1570** of both a and b.
1571**
1572** Side effects:
1573** The "next" pointers for elements in the lists a and b are
1574** changed.
1575*/
drhe9278182007-07-18 18:16:29 +00001576static char *merge(
1577 char *a,
1578 char *b,
1579 int (*cmp)(const char*,const char*),
1580 int offset
1581){
drh75897232000-05-29 14:26:00 +00001582 char *ptr, *head;
1583
1584 if( a==0 ){
1585 head = b;
1586 }else if( b==0 ){
1587 head = a;
1588 }else{
drhe594bc32009-11-03 13:02:25 +00001589 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001590 ptr = a;
1591 a = NEXT(a);
1592 }else{
1593 ptr = b;
1594 b = NEXT(b);
1595 }
1596 head = ptr;
1597 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001598 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001599 NEXT(ptr) = a;
1600 ptr = a;
1601 a = NEXT(a);
1602 }else{
1603 NEXT(ptr) = b;
1604 ptr = b;
1605 b = NEXT(b);
1606 }
1607 }
1608 if( a ) NEXT(ptr) = a;
1609 else NEXT(ptr) = b;
1610 }
1611 return head;
1612}
1613
1614/*
1615** Inputs:
1616** list: Pointer to a singly-linked list of structures.
1617** next: Pointer to pointer to the second element of the list.
1618** cmp: A comparison function.
1619**
1620** Return Value:
1621** A pointer to the head of a sorted list containing the elements
1622** orginally in list.
1623**
1624** Side effects:
1625** The "next" pointers for elements in list are changed.
1626*/
1627#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001628static char *msort(
1629 char *list,
1630 char **next,
1631 int (*cmp)(const char*,const char*)
1632){
drhba99af52001-10-25 20:37:16 +00001633 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001634 char *ep;
1635 char *set[LISTSIZE];
1636 int i;
drhba99af52001-10-25 20:37:16 +00001637 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001638 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1639 while( list ){
1640 ep = list;
1641 list = NEXT(list);
1642 NEXT(ep) = 0;
1643 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1644 ep = merge(ep,set[i],cmp,offset);
1645 set[i] = 0;
1646 }
1647 set[i] = ep;
1648 }
1649 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001650 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001651 return ep;
1652}
1653/************************ From the file "option.c" **************************/
1654static char **argv;
1655static struct s_options *op;
1656static FILE *errstream;
1657
1658#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1659
1660/*
1661** Print the command line with a carrot pointing to the k-th character
1662** of the n-th field.
1663*/
icculus9e44cf12010-02-14 17:14:22 +00001664static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001665{
1666 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001667 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001668 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001669 for(i=1; i<n && argv[i]; i++){
1670 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001671 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001672 }
1673 spcnt += k;
1674 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1675 if( spcnt<20 ){
1676 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1677 }else{
1678 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1679 }
1680}
1681
1682/*
1683** Return the index of the N-th non-switch argument. Return -1
1684** if N is out of range.
1685*/
icculus9e44cf12010-02-14 17:14:22 +00001686static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001687{
1688 int i;
1689 int dashdash = 0;
1690 if( argv!=0 && *argv!=0 ){
1691 for(i=1; argv[i]; i++){
1692 if( dashdash || !ISOPT(argv[i]) ){
1693 if( n==0 ) return i;
1694 n--;
1695 }
1696 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1697 }
1698 }
1699 return -1;
1700}
1701
1702static char emsg[] = "Command line syntax error: ";
1703
1704/*
1705** Process a flag command line argument.
1706*/
icculus9e44cf12010-02-14 17:14:22 +00001707static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001708{
1709 int v;
1710 int errcnt = 0;
1711 int j;
1712 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001713 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001714 }
1715 v = argv[i][0]=='-' ? 1 : 0;
1716 if( op[j].label==0 ){
1717 if( err ){
1718 fprintf(err,"%sundefined option.\n",emsg);
1719 errline(i,1,err);
1720 }
1721 errcnt++;
1722 }else if( op[j].type==OPT_FLAG ){
1723 *((int*)op[j].arg) = v;
1724 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001725 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001726 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001727 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001728 }else{
1729 if( err ){
1730 fprintf(err,"%smissing argument on switch.\n",emsg);
1731 errline(i,1,err);
1732 }
1733 errcnt++;
1734 }
1735 return errcnt;
1736}
1737
1738/*
1739** Process a command line switch which has an argument.
1740*/
icculus9e44cf12010-02-14 17:14:22 +00001741static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001742{
1743 int lv = 0;
1744 double dv = 0.0;
1745 char *sv = 0, *end;
1746 char *cp;
1747 int j;
1748 int errcnt = 0;
1749 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001750 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001751 *cp = 0;
1752 for(j=0; op[j].label; j++){
1753 if( strcmp(argv[i],op[j].label)==0 ) break;
1754 }
1755 *cp = '=';
1756 if( op[j].label==0 ){
1757 if( err ){
1758 fprintf(err,"%sundefined option.\n",emsg);
1759 errline(i,0,err);
1760 }
1761 errcnt++;
1762 }else{
1763 cp++;
1764 switch( op[j].type ){
1765 case OPT_FLAG:
1766 case OPT_FFLAG:
1767 if( err ){
1768 fprintf(err,"%soption requires an argument.\n",emsg);
1769 errline(i,0,err);
1770 }
1771 errcnt++;
1772 break;
1773 case OPT_DBL:
1774 case OPT_FDBL:
1775 dv = strtod(cp,&end);
1776 if( *end ){
1777 if( err ){
1778 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001779 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001780 }
1781 errcnt++;
1782 }
1783 break;
1784 case OPT_INT:
1785 case OPT_FINT:
1786 lv = strtol(cp,&end,0);
1787 if( *end ){
1788 if( err ){
1789 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001790 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001791 }
1792 errcnt++;
1793 }
1794 break;
1795 case OPT_STR:
1796 case OPT_FSTR:
1797 sv = cp;
1798 break;
1799 }
1800 switch( op[j].type ){
1801 case OPT_FLAG:
1802 case OPT_FFLAG:
1803 break;
1804 case OPT_DBL:
1805 *(double*)(op[j].arg) = dv;
1806 break;
1807 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001808 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001809 break;
1810 case OPT_INT:
1811 *(int*)(op[j].arg) = lv;
1812 break;
1813 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001814 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001815 break;
1816 case OPT_STR:
1817 *(char**)(op[j].arg) = sv;
1818 break;
1819 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001820 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001821 break;
1822 }
1823 }
1824 return errcnt;
1825}
1826
icculus9e44cf12010-02-14 17:14:22 +00001827int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001828{
1829 int errcnt = 0;
1830 argv = a;
1831 op = o;
1832 errstream = err;
1833 if( argv && *argv && op ){
1834 int i;
1835 for(i=1; argv[i]; i++){
1836 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1837 errcnt += handleflags(i,err);
1838 }else if( strchr(argv[i],'=') ){
1839 errcnt += handleswitch(i,err);
1840 }
1841 }
1842 }
1843 if( errcnt>0 ){
1844 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001845 OptPrint();
drh75897232000-05-29 14:26:00 +00001846 exit(1);
1847 }
1848 return 0;
1849}
1850
drhb0c86772000-06-02 23:21:26 +00001851int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001852 int cnt = 0;
1853 int dashdash = 0;
1854 int i;
1855 if( argv!=0 && argv[0]!=0 ){
1856 for(i=1; argv[i]; i++){
1857 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1858 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1859 }
1860 }
1861 return cnt;
1862}
1863
icculus9e44cf12010-02-14 17:14:22 +00001864char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001865{
1866 int i;
1867 i = argindex(n);
1868 return i>=0 ? argv[i] : 0;
1869}
1870
icculus9e44cf12010-02-14 17:14:22 +00001871void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001872{
1873 int i;
1874 i = argindex(n);
1875 if( i>=0 ) errline(i,0,errstream);
1876}
1877
drhb0c86772000-06-02 23:21:26 +00001878void OptPrint(){
drh75897232000-05-29 14:26:00 +00001879 int i;
1880 int max, len;
1881 max = 0;
1882 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001883 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001884 switch( op[i].type ){
1885 case OPT_FLAG:
1886 case OPT_FFLAG:
1887 break;
1888 case OPT_INT:
1889 case OPT_FINT:
1890 len += 9; /* length of "<integer>" */
1891 break;
1892 case OPT_DBL:
1893 case OPT_FDBL:
1894 len += 6; /* length of "<real>" */
1895 break;
1896 case OPT_STR:
1897 case OPT_FSTR:
1898 len += 8; /* length of "<string>" */
1899 break;
1900 }
1901 if( len>max ) max = len;
1902 }
1903 for(i=0; op[i].label; i++){
1904 switch( op[i].type ){
1905 case OPT_FLAG:
1906 case OPT_FFLAG:
1907 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1908 break;
1909 case OPT_INT:
1910 case OPT_FINT:
1911 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001912 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001913 break;
1914 case OPT_DBL:
1915 case OPT_FDBL:
1916 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001917 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001918 break;
1919 case OPT_STR:
1920 case OPT_FSTR:
1921 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001922 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001923 break;
1924 }
1925 }
1926}
1927/*********************** From the file "parse.c" ****************************/
1928/*
1929** Input file parser for the LEMON parser generator.
1930*/
1931
1932/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00001933enum e_state {
1934 INITIALIZE,
1935 WAITING_FOR_DECL_OR_RULE,
1936 WAITING_FOR_DECL_KEYWORD,
1937 WAITING_FOR_DECL_ARG,
1938 WAITING_FOR_PRECEDENCE_SYMBOL,
1939 WAITING_FOR_ARROW,
1940 IN_RHS,
1941 LHS_ALIAS_1,
1942 LHS_ALIAS_2,
1943 LHS_ALIAS_3,
1944 RHS_ALIAS_1,
1945 RHS_ALIAS_2,
1946 PRECEDENCE_MARK_1,
1947 PRECEDENCE_MARK_2,
1948 RESYNC_AFTER_RULE_ERROR,
1949 RESYNC_AFTER_DECL_ERROR,
1950 WAITING_FOR_DESTRUCTOR_SYMBOL,
1951 WAITING_FOR_DATATYPE_SYMBOL,
1952 WAITING_FOR_FALLBACK_ID,
icculus9e44cf12010-02-14 17:14:22 +00001953 WAITING_FOR_WILDCARD_ID
1954};
drh75897232000-05-29 14:26:00 +00001955struct pstate {
1956 char *filename; /* Name of the input file */
1957 int tokenlineno; /* Linenumber at which current token starts */
1958 int errorcnt; /* Number of errors so far */
1959 char *tokenstart; /* Text of current token */
1960 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00001961 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001962 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001963 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00001964 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00001965 int nrhs; /* Number of right-hand side symbols seen */
1966 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00001967 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00001968 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00001969 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00001970 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001971 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001972 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001973 enum e_assoc declassoc; /* Assign this association to decl arguments */
1974 int preccounter; /* Assign this precedence to decl arguments */
1975 struct rule *firstrule; /* Pointer to first rule in the grammar */
1976 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1977};
1978
1979/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00001980static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00001981{
icculus9e44cf12010-02-14 17:14:22 +00001982 const char *x;
drh75897232000-05-29 14:26:00 +00001983 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1984#if 0
1985 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1986 x,psp->state);
1987#endif
1988 switch( psp->state ){
1989 case INITIALIZE:
1990 psp->prevrule = 0;
1991 psp->preccounter = 0;
1992 psp->firstrule = psp->lastrule = 0;
1993 psp->gp->nrule = 0;
1994 /* Fall thru to next case */
1995 case WAITING_FOR_DECL_OR_RULE:
1996 if( x[0]=='%' ){
1997 psp->state = WAITING_FOR_DECL_KEYWORD;
1998 }else if( islower(x[0]) ){
1999 psp->lhs = Symbol_new(x);
2000 psp->nrhs = 0;
2001 psp->lhsalias = 0;
2002 psp->state = WAITING_FOR_ARROW;
2003 }else if( x[0]=='{' ){
2004 if( psp->prevrule==0 ){
2005 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00002006"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00002007fragment which begins on this line.");
2008 psp->errorcnt++;
2009 }else if( psp->prevrule->code!=0 ){
2010 ErrorMsg(psp->filename,psp->tokenlineno,
2011"Code fragment beginning on this line is not the first \
2012to follow the previous rule.");
2013 psp->errorcnt++;
2014 }else{
2015 psp->prevrule->line = psp->tokenlineno;
2016 psp->prevrule->code = &x[1];
2017 }
2018 }else if( x[0]=='[' ){
2019 psp->state = PRECEDENCE_MARK_1;
2020 }else{
2021 ErrorMsg(psp->filename,psp->tokenlineno,
2022 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2023 x);
2024 psp->errorcnt++;
2025 }
2026 break;
2027 case PRECEDENCE_MARK_1:
2028 if( !isupper(x[0]) ){
2029 ErrorMsg(psp->filename,psp->tokenlineno,
2030 "The precedence symbol must be a terminal.");
2031 psp->errorcnt++;
2032 }else if( psp->prevrule==0 ){
2033 ErrorMsg(psp->filename,psp->tokenlineno,
2034 "There is no prior rule to assign precedence \"[%s]\".",x);
2035 psp->errorcnt++;
2036 }else if( psp->prevrule->precsym!=0 ){
2037 ErrorMsg(psp->filename,psp->tokenlineno,
2038"Precedence mark on this line is not the first \
2039to follow the previous rule.");
2040 psp->errorcnt++;
2041 }else{
2042 psp->prevrule->precsym = Symbol_new(x);
2043 }
2044 psp->state = PRECEDENCE_MARK_2;
2045 break;
2046 case PRECEDENCE_MARK_2:
2047 if( x[0]!=']' ){
2048 ErrorMsg(psp->filename,psp->tokenlineno,
2049 "Missing \"]\" on precedence mark.");
2050 psp->errorcnt++;
2051 }
2052 psp->state = WAITING_FOR_DECL_OR_RULE;
2053 break;
2054 case WAITING_FOR_ARROW:
2055 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2056 psp->state = IN_RHS;
2057 }else if( x[0]=='(' ){
2058 psp->state = LHS_ALIAS_1;
2059 }else{
2060 ErrorMsg(psp->filename,psp->tokenlineno,
2061 "Expected to see a \":\" following the LHS symbol \"%s\".",
2062 psp->lhs->name);
2063 psp->errorcnt++;
2064 psp->state = RESYNC_AFTER_RULE_ERROR;
2065 }
2066 break;
2067 case LHS_ALIAS_1:
2068 if( isalpha(x[0]) ){
2069 psp->lhsalias = x;
2070 psp->state = LHS_ALIAS_2;
2071 }else{
2072 ErrorMsg(psp->filename,psp->tokenlineno,
2073 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2074 x,psp->lhs->name);
2075 psp->errorcnt++;
2076 psp->state = RESYNC_AFTER_RULE_ERROR;
2077 }
2078 break;
2079 case LHS_ALIAS_2:
2080 if( x[0]==')' ){
2081 psp->state = LHS_ALIAS_3;
2082 }else{
2083 ErrorMsg(psp->filename,psp->tokenlineno,
2084 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2085 psp->errorcnt++;
2086 psp->state = RESYNC_AFTER_RULE_ERROR;
2087 }
2088 break;
2089 case LHS_ALIAS_3:
2090 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2091 psp->state = IN_RHS;
2092 }else{
2093 ErrorMsg(psp->filename,psp->tokenlineno,
2094 "Missing \"->\" following: \"%s(%s)\".",
2095 psp->lhs->name,psp->lhsalias);
2096 psp->errorcnt++;
2097 psp->state = RESYNC_AFTER_RULE_ERROR;
2098 }
2099 break;
2100 case IN_RHS:
2101 if( x[0]=='.' ){
2102 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002103 rp = (struct rule *)calloc( sizeof(struct rule) +
2104 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002105 if( rp==0 ){
2106 ErrorMsg(psp->filename,psp->tokenlineno,
2107 "Can't allocate enough memory for this rule.");
2108 psp->errorcnt++;
2109 psp->prevrule = 0;
2110 }else{
2111 int i;
2112 rp->ruleline = psp->tokenlineno;
2113 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002114 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002115 for(i=0; i<psp->nrhs; i++){
2116 rp->rhs[i] = psp->rhs[i];
2117 rp->rhsalias[i] = psp->alias[i];
2118 }
2119 rp->lhs = psp->lhs;
2120 rp->lhsalias = psp->lhsalias;
2121 rp->nrhs = psp->nrhs;
2122 rp->code = 0;
2123 rp->precsym = 0;
2124 rp->index = psp->gp->nrule++;
2125 rp->nextlhs = rp->lhs->rule;
2126 rp->lhs->rule = rp;
2127 rp->next = 0;
2128 if( psp->firstrule==0 ){
2129 psp->firstrule = psp->lastrule = rp;
2130 }else{
2131 psp->lastrule->next = rp;
2132 psp->lastrule = rp;
2133 }
2134 psp->prevrule = rp;
2135 }
2136 psp->state = WAITING_FOR_DECL_OR_RULE;
2137 }else if( isalpha(x[0]) ){
2138 if( psp->nrhs>=MAXRHS ){
2139 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002140 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002141 x);
2142 psp->errorcnt++;
2143 psp->state = RESYNC_AFTER_RULE_ERROR;
2144 }else{
2145 psp->rhs[psp->nrhs] = Symbol_new(x);
2146 psp->alias[psp->nrhs] = 0;
2147 psp->nrhs++;
2148 }
drhfd405312005-11-06 04:06:59 +00002149 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2150 struct symbol *msp = psp->rhs[psp->nrhs-1];
2151 if( msp->type!=MULTITERMINAL ){
2152 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002153 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002154 memset(msp, 0, sizeof(*msp));
2155 msp->type = MULTITERMINAL;
2156 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002157 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002158 msp->subsym[0] = origsp;
2159 msp->name = origsp->name;
2160 psp->rhs[psp->nrhs-1] = msp;
2161 }
2162 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002163 msp->subsym = (struct symbol **) realloc(msp->subsym,
2164 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002165 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2166 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2167 ErrorMsg(psp->filename,psp->tokenlineno,
2168 "Cannot form a compound containing a non-terminal");
2169 psp->errorcnt++;
2170 }
drh75897232000-05-29 14:26:00 +00002171 }else if( x[0]=='(' && psp->nrhs>0 ){
2172 psp->state = RHS_ALIAS_1;
2173 }else{
2174 ErrorMsg(psp->filename,psp->tokenlineno,
2175 "Illegal character on RHS of rule: \"%s\".",x);
2176 psp->errorcnt++;
2177 psp->state = RESYNC_AFTER_RULE_ERROR;
2178 }
2179 break;
2180 case RHS_ALIAS_1:
2181 if( isalpha(x[0]) ){
2182 psp->alias[psp->nrhs-1] = x;
2183 psp->state = RHS_ALIAS_2;
2184 }else{
2185 ErrorMsg(psp->filename,psp->tokenlineno,
2186 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2187 x,psp->rhs[psp->nrhs-1]->name);
2188 psp->errorcnt++;
2189 psp->state = RESYNC_AFTER_RULE_ERROR;
2190 }
2191 break;
2192 case RHS_ALIAS_2:
2193 if( x[0]==')' ){
2194 psp->state = IN_RHS;
2195 }else{
2196 ErrorMsg(psp->filename,psp->tokenlineno,
2197 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2198 psp->errorcnt++;
2199 psp->state = RESYNC_AFTER_RULE_ERROR;
2200 }
2201 break;
2202 case WAITING_FOR_DECL_KEYWORD:
2203 if( isalpha(x[0]) ){
2204 psp->declkeyword = x;
2205 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002206 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002207 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002208 psp->state = WAITING_FOR_DECL_ARG;
2209 if( strcmp(x,"name")==0 ){
2210 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002211 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002212 }else if( strcmp(x,"include")==0 ){
2213 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002214 }else if( strcmp(x,"code")==0 ){
2215 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002216 }else if( strcmp(x,"token_destructor")==0 ){
2217 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002218 }else if( strcmp(x,"default_destructor")==0 ){
2219 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002220 }else if( strcmp(x,"token_prefix")==0 ){
2221 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002222 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002223 }else if( strcmp(x,"syntax_error")==0 ){
2224 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002225 }else if( strcmp(x,"parse_accept")==0 ){
2226 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002227 }else if( strcmp(x,"parse_failure")==0 ){
2228 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002229 }else if( strcmp(x,"stack_overflow")==0 ){
2230 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002231 }else if( strcmp(x,"extra_argument")==0 ){
2232 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002233 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002234 }else if( strcmp(x,"token_type")==0 ){
2235 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002236 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002237 }else if( strcmp(x,"default_type")==0 ){
2238 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002239 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002240 }else if( strcmp(x,"stack_size")==0 ){
2241 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002242 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002243 }else if( strcmp(x,"start_symbol")==0 ){
2244 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002245 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002246 }else if( strcmp(x,"left")==0 ){
2247 psp->preccounter++;
2248 psp->declassoc = LEFT;
2249 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2250 }else if( strcmp(x,"right")==0 ){
2251 psp->preccounter++;
2252 psp->declassoc = RIGHT;
2253 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2254 }else if( strcmp(x,"nonassoc")==0 ){
2255 psp->preccounter++;
2256 psp->declassoc = NONE;
2257 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2258 }else if( strcmp(x,"destructor")==0 ){
2259 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2260 }else if( strcmp(x,"type")==0 ){
2261 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002262 }else if( strcmp(x,"fallback")==0 ){
2263 psp->fallback = 0;
2264 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002265 }else if( strcmp(x,"wildcard")==0 ){
2266 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002267 }else{
2268 ErrorMsg(psp->filename,psp->tokenlineno,
2269 "Unknown declaration keyword: \"%%%s\".",x);
2270 psp->errorcnt++;
2271 psp->state = RESYNC_AFTER_DECL_ERROR;
2272 }
2273 }else{
2274 ErrorMsg(psp->filename,psp->tokenlineno,
2275 "Illegal declaration keyword: \"%s\".",x);
2276 psp->errorcnt++;
2277 psp->state = RESYNC_AFTER_DECL_ERROR;
2278 }
2279 break;
2280 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2281 if( !isalpha(x[0]) ){
2282 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002283 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002284 psp->errorcnt++;
2285 psp->state = RESYNC_AFTER_DECL_ERROR;
2286 }else{
icculusd286fa62010-03-03 17:06:32 +00002287 struct symbol *sp = Symbol_new(x);
2288 psp->declargslot = &sp->destructor;
2289 psp->decllinenoslot = &sp->destLineno;
2290 psp->insertLineMacro = 1;
2291 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002292 }
2293 break;
2294 case WAITING_FOR_DATATYPE_SYMBOL:
2295 if( !isalpha(x[0]) ){
2296 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002297 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002298 psp->errorcnt++;
2299 psp->state = RESYNC_AFTER_DECL_ERROR;
2300 }else{
icculus866bf1e2010-02-17 20:31:32 +00002301 struct symbol *sp = Symbol_find(x);
2302 if((sp) && (sp->datatype)){
2303 ErrorMsg(psp->filename,psp->tokenlineno,
2304 "Symbol %%type \"%s\" already defined", x);
2305 psp->errorcnt++;
2306 psp->state = RESYNC_AFTER_DECL_ERROR;
2307 }else{
2308 if (!sp){
2309 sp = Symbol_new(x);
2310 }
2311 psp->declargslot = &sp->datatype;
2312 psp->insertLineMacro = 0;
2313 psp->state = WAITING_FOR_DECL_ARG;
2314 }
drh75897232000-05-29 14:26:00 +00002315 }
2316 break;
2317 case WAITING_FOR_PRECEDENCE_SYMBOL:
2318 if( x[0]=='.' ){
2319 psp->state = WAITING_FOR_DECL_OR_RULE;
2320 }else if( isupper(x[0]) ){
2321 struct symbol *sp;
2322 sp = Symbol_new(x);
2323 if( sp->prec>=0 ){
2324 ErrorMsg(psp->filename,psp->tokenlineno,
2325 "Symbol \"%s\" has already be given a precedence.",x);
2326 psp->errorcnt++;
2327 }else{
2328 sp->prec = psp->preccounter;
2329 sp->assoc = psp->declassoc;
2330 }
2331 }else{
2332 ErrorMsg(psp->filename,psp->tokenlineno,
2333 "Can't assign a precedence to \"%s\".",x);
2334 psp->errorcnt++;
2335 }
2336 break;
2337 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002338 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002339 const char *zOld, *zNew;
2340 char *zBuf, *z;
drha5808f32008-04-27 22:19:44 +00002341 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002342 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002343 char zLine[50];
2344 zNew = x;
2345 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002346 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002347 if( *psp->declargslot ){
2348 zOld = *psp->declargslot;
2349 }else{
2350 zOld = "";
2351 }
drh87cf1372008-08-13 20:09:06 +00002352 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002353 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002354 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002355 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2356 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002357 for(z=psp->filename, nBack=0; *z; z++){
2358 if( *z=='\\' ) nBack++;
2359 }
2360 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002361 nLine = lemonStrlen(zLine);
2362 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002363 }
icculus9e44cf12010-02-14 17:14:22 +00002364 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2365 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002366 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002367 if( nOld && zBuf[-1]!='\n' ){
2368 *(zBuf++) = '\n';
2369 }
2370 memcpy(zBuf, zLine, nLine);
2371 zBuf += nLine;
2372 *(zBuf++) = '"';
2373 for(z=psp->filename; *z; z++){
2374 if( *z=='\\' ){
2375 *(zBuf++) = '\\';
2376 }
2377 *(zBuf++) = *z;
2378 }
2379 *(zBuf++) = '"';
2380 *(zBuf++) = '\n';
2381 }
drh4dc8ef52008-07-01 17:13:57 +00002382 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2383 psp->decllinenoslot[0] = psp->tokenlineno;
2384 }
drha5808f32008-04-27 22:19:44 +00002385 memcpy(zBuf, zNew, nNew);
2386 zBuf += nNew;
2387 *zBuf = 0;
2388 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002389 }else{
2390 ErrorMsg(psp->filename,psp->tokenlineno,
2391 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2392 psp->errorcnt++;
2393 psp->state = RESYNC_AFTER_DECL_ERROR;
2394 }
2395 break;
drh0bd1f4e2002-06-06 18:54:39 +00002396 case WAITING_FOR_FALLBACK_ID:
2397 if( x[0]=='.' ){
2398 psp->state = WAITING_FOR_DECL_OR_RULE;
2399 }else if( !isupper(x[0]) ){
2400 ErrorMsg(psp->filename, psp->tokenlineno,
2401 "%%fallback argument \"%s\" should be a token", x);
2402 psp->errorcnt++;
2403 }else{
2404 struct symbol *sp = Symbol_new(x);
2405 if( psp->fallback==0 ){
2406 psp->fallback = sp;
2407 }else if( sp->fallback ){
2408 ErrorMsg(psp->filename, psp->tokenlineno,
2409 "More than one fallback assigned to token %s", x);
2410 psp->errorcnt++;
2411 }else{
2412 sp->fallback = psp->fallback;
2413 psp->gp->has_fallback = 1;
2414 }
2415 }
2416 break;
drhe09daa92006-06-10 13:29:31 +00002417 case WAITING_FOR_WILDCARD_ID:
2418 if( x[0]=='.' ){
2419 psp->state = WAITING_FOR_DECL_OR_RULE;
2420 }else if( !isupper(x[0]) ){
2421 ErrorMsg(psp->filename, psp->tokenlineno,
2422 "%%wildcard argument \"%s\" should be a token", x);
2423 psp->errorcnt++;
2424 }else{
2425 struct symbol *sp = Symbol_new(x);
2426 if( psp->gp->wildcard==0 ){
2427 psp->gp->wildcard = sp;
2428 }else{
2429 ErrorMsg(psp->filename, psp->tokenlineno,
2430 "Extra wildcard to token: %s", x);
2431 psp->errorcnt++;
2432 }
2433 }
2434 break;
drh75897232000-05-29 14:26:00 +00002435 case RESYNC_AFTER_RULE_ERROR:
2436/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2437** break; */
2438 case RESYNC_AFTER_DECL_ERROR:
2439 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2440 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2441 break;
2442 }
2443}
2444
drh34ff57b2008-07-14 12:27:51 +00002445/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002446** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2447** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2448** comments them out. Text in between is also commented out as appropriate.
2449*/
danielk1977940fac92005-01-23 22:41:37 +00002450static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002451 int i, j, k, n;
2452 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002453 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002454 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002455 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002456 for(i=0; z[i]; i++){
2457 if( z[i]=='\n' ) lineno++;
2458 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2459 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2460 if( exclude ){
2461 exclude--;
2462 if( exclude==0 ){
2463 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2464 }
2465 }
2466 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2467 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2468 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2469 if( exclude ){
2470 exclude++;
2471 }else{
2472 for(j=i+7; isspace(z[j]); j++){}
2473 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2474 exclude = 1;
2475 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002476 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002477 exclude = 0;
2478 break;
2479 }
2480 }
2481 if( z[i+3]=='n' ) exclude = !exclude;
2482 if( exclude ){
2483 start = i;
2484 start_lineno = lineno;
2485 }
2486 }
2487 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2488 }
2489 }
2490 if( exclude ){
2491 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2492 exit(1);
2493 }
2494}
2495
drh75897232000-05-29 14:26:00 +00002496/* In spite of its name, this function is really a scanner. It read
2497** in the entire input file (all at once) then tokenizes it. Each
2498** token is passed to the function "parseonetoken" which builds all
2499** the appropriate data structures in the global state vector "gp".
2500*/
icculus9e44cf12010-02-14 17:14:22 +00002501void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002502{
2503 struct pstate ps;
2504 FILE *fp;
2505 char *filebuf;
2506 int filesize;
2507 int lineno;
2508 int c;
2509 char *cp, *nextcp;
2510 int startline = 0;
2511
rse38514a92007-09-20 11:34:17 +00002512 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002513 ps.gp = gp;
2514 ps.filename = gp->filename;
2515 ps.errorcnt = 0;
2516 ps.state = INITIALIZE;
2517
2518 /* Begin by reading the input file */
2519 fp = fopen(ps.filename,"rb");
2520 if( fp==0 ){
2521 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2522 gp->errorcnt++;
2523 return;
2524 }
2525 fseek(fp,0,2);
2526 filesize = ftell(fp);
2527 rewind(fp);
2528 filebuf = (char *)malloc( filesize+1 );
2529 if( filebuf==0 ){
2530 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2531 filesize+1);
2532 gp->errorcnt++;
2533 return;
2534 }
2535 if( fread(filebuf,1,filesize,fp)!=filesize ){
2536 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2537 filesize);
2538 free(filebuf);
2539 gp->errorcnt++;
2540 return;
2541 }
2542 fclose(fp);
2543 filebuf[filesize] = 0;
2544
drh6d08b4d2004-07-20 12:45:22 +00002545 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2546 preprocess_input(filebuf);
2547
drh75897232000-05-29 14:26:00 +00002548 /* Now scan the text of the input file */
2549 lineno = 1;
2550 for(cp=filebuf; (c= *cp)!=0; ){
2551 if( c=='\n' ) lineno++; /* Keep track of the line number */
2552 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2553 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2554 cp+=2;
2555 while( (c= *cp)!=0 && c!='\n' ) cp++;
2556 continue;
2557 }
2558 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2559 cp+=2;
2560 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2561 if( c=='\n' ) lineno++;
2562 cp++;
2563 }
2564 if( c ) cp++;
2565 continue;
2566 }
2567 ps.tokenstart = cp; /* Mark the beginning of the token */
2568 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2569 if( c=='\"' ){ /* String literals */
2570 cp++;
2571 while( (c= *cp)!=0 && c!='\"' ){
2572 if( c=='\n' ) lineno++;
2573 cp++;
2574 }
2575 if( c==0 ){
2576 ErrorMsg(ps.filename,startline,
2577"String starting on this line is not terminated before the end of the file.");
2578 ps.errorcnt++;
2579 nextcp = cp;
2580 }else{
2581 nextcp = cp+1;
2582 }
2583 }else if( c=='{' ){ /* A block of C code */
2584 int level;
2585 cp++;
2586 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2587 if( c=='\n' ) lineno++;
2588 else if( c=='{' ) level++;
2589 else if( c=='}' ) level--;
2590 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2591 int prevc;
2592 cp = &cp[2];
2593 prevc = 0;
2594 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2595 if( c=='\n' ) lineno++;
2596 prevc = c;
2597 cp++;
2598 }
2599 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2600 cp = &cp[2];
2601 while( (c= *cp)!=0 && c!='\n' ) cp++;
2602 if( c ) lineno++;
2603 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2604 int startchar, prevc;
2605 startchar = c;
2606 prevc = 0;
2607 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2608 if( c=='\n' ) lineno++;
2609 if( prevc=='\\' ) prevc = 0;
2610 else prevc = c;
2611 }
2612 }
2613 }
2614 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002615 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002616"C code starting on this line is not terminated before the end of the file.");
2617 ps.errorcnt++;
2618 nextcp = cp;
2619 }else{
2620 nextcp = cp+1;
2621 }
2622 }else if( isalnum(c) ){ /* Identifiers */
2623 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2624 nextcp = cp;
2625 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2626 cp += 3;
2627 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002628 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2629 cp += 2;
2630 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2631 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002632 }else{ /* All other (one character) operators */
2633 cp++;
2634 nextcp = cp;
2635 }
2636 c = *cp;
2637 *cp = 0; /* Null terminate the token */
2638 parseonetoken(&ps); /* Parse the token */
2639 *cp = c; /* Restore the buffer */
2640 cp = nextcp;
2641 }
2642 free(filebuf); /* Release the buffer after parsing */
2643 gp->rule = ps.firstrule;
2644 gp->errorcnt = ps.errorcnt;
2645}
2646/*************************** From the file "plink.c" *********************/
2647/*
2648** Routines processing configuration follow-set propagation links
2649** in the LEMON parser generator.
2650*/
2651static struct plink *plink_freelist = 0;
2652
2653/* Allocate a new plink */
2654struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002655 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002656
2657 if( plink_freelist==0 ){
2658 int i;
2659 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002660 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002661 if( plink_freelist==0 ){
2662 fprintf(stderr,
2663 "Unable to allocate memory for a new follow-set propagation link.\n");
2664 exit(1);
2665 }
2666 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2667 plink_freelist[amt-1].next = 0;
2668 }
icculus9e44cf12010-02-14 17:14:22 +00002669 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002670 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002671 return newlink;
drh75897232000-05-29 14:26:00 +00002672}
2673
2674/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002675void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002676{
icculus9e44cf12010-02-14 17:14:22 +00002677 struct plink *newlink;
2678 newlink = Plink_new();
2679 newlink->next = *plpp;
2680 *plpp = newlink;
2681 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002682}
2683
2684/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002685void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002686{
2687 struct plink *nextpl;
2688 while( from ){
2689 nextpl = from->next;
2690 from->next = *to;
2691 *to = from;
2692 from = nextpl;
2693 }
2694}
2695
2696/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002697void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002698{
2699 struct plink *nextpl;
2700
2701 while( plp ){
2702 nextpl = plp->next;
2703 plp->next = plink_freelist;
2704 plink_freelist = plp;
2705 plp = nextpl;
2706 }
2707}
2708/*********************** From the file "report.c" **************************/
2709/*
2710** Procedures for generating reports and tables in the LEMON parser generator.
2711*/
2712
2713/* Generate a filename with the given suffix. Space to hold the
2714** name comes from malloc() and must be freed by the calling
2715** function.
2716*/
icculus9e44cf12010-02-14 17:14:22 +00002717PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002718{
2719 char *name;
2720 char *cp;
2721
icculus9e44cf12010-02-14 17:14:22 +00002722 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002723 if( name==0 ){
2724 fprintf(stderr,"Can't allocate space for a filename.\n");
2725 exit(1);
2726 }
2727 strcpy(name,lemp->filename);
2728 cp = strrchr(name,'.');
2729 if( cp ) *cp = 0;
2730 strcat(name,suffix);
2731 return name;
2732}
2733
2734/* Open a file with a name based on the name of the input file,
2735** but with a different (specified) suffix, and return a pointer
2736** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002737PRIVATE FILE *file_open(
2738 struct lemon *lemp,
2739 const char *suffix,
2740 const char *mode
2741){
drh75897232000-05-29 14:26:00 +00002742 FILE *fp;
2743
2744 if( lemp->outname ) free(lemp->outname);
2745 lemp->outname = file_makename(lemp, suffix);
2746 fp = fopen(lemp->outname,mode);
2747 if( fp==0 && *mode=='w' ){
2748 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2749 lemp->errorcnt++;
2750 return 0;
2751 }
icculusf5ad8242010-02-14 05:34:42 +00002752
2753 /* Add files we create to a list, so we can delete them if we fail. This
2754 ** is to keep makefiles from getting confused. We don't include .out files,
2755 ** though: this is debug information, and you don't want it deleted if there
2756 ** was an error you need to track down.
2757 */
2758 if(( *mode=='w' ) && (strcmp(suffix, ".out") != 0)){
2759 const char **ptr = (const char **)
2760 realloc(made_files, sizeof (const char **) * (made_files_count + 1));
icculusd49c1aa2010-03-03 17:00:15 +00002761 const char *fname = Strsafe(lemp->outname);
icculusf5ad8242010-02-14 05:34:42 +00002762 if ((ptr == NULL) || (fname == NULL)) {
2763 free(ptr);
icculusf5ad8242010-02-14 05:34:42 +00002764 memory_error();
2765 }
2766 made_files = ptr;
2767 made_files[made_files_count++] = fname;
2768 }
drh75897232000-05-29 14:26:00 +00002769 return fp;
2770}
2771
2772/* Duplicate the input file without comments and without actions
2773** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002774void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002775{
2776 struct rule *rp;
2777 struct symbol *sp;
2778 int i, j, maxlen, len, ncolumns, skip;
2779 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2780 maxlen = 10;
2781 for(i=0; i<lemp->nsymbol; i++){
2782 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002783 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002784 if( len>maxlen ) maxlen = len;
2785 }
2786 ncolumns = 76/(maxlen+5);
2787 if( ncolumns<1 ) ncolumns = 1;
2788 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2789 for(i=0; i<skip; i++){
2790 printf("//");
2791 for(j=i; j<lemp->nsymbol; j+=skip){
2792 sp = lemp->symbols[j];
2793 assert( sp->index==j );
2794 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2795 }
2796 printf("\n");
2797 }
2798 for(rp=lemp->rule; rp; rp=rp->next){
2799 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002800 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002801 printf(" ::=");
2802 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002803 sp = rp->rhs[i];
2804 printf(" %s", sp->name);
2805 if( sp->type==MULTITERMINAL ){
2806 for(j=1; j<sp->nsubsym; j++){
2807 printf("|%s", sp->subsym[j]->name);
2808 }
2809 }
2810 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002811 }
2812 printf(".");
2813 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002814 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002815 printf("\n");
2816 }
2817}
2818
icculus9e44cf12010-02-14 17:14:22 +00002819void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002820{
2821 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002822 struct symbol *sp;
2823 int i, j;
drh75897232000-05-29 14:26:00 +00002824 rp = cfp->rp;
2825 fprintf(fp,"%s ::=",rp->lhs->name);
2826 for(i=0; i<=rp->nrhs; i++){
2827 if( i==cfp->dot ) fprintf(fp," *");
2828 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002829 sp = rp->rhs[i];
2830 fprintf(fp," %s", sp->name);
2831 if( sp->type==MULTITERMINAL ){
2832 for(j=1; j<sp->nsubsym; j++){
2833 fprintf(fp,"|%s",sp->subsym[j]->name);
2834 }
2835 }
drh75897232000-05-29 14:26:00 +00002836 }
2837}
2838
2839/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002840#if 0
drh75897232000-05-29 14:26:00 +00002841/* Print a set */
2842PRIVATE void SetPrint(out,set,lemp)
2843FILE *out;
2844char *set;
2845struct lemon *lemp;
2846{
2847 int i;
2848 char *spacer;
2849 spacer = "";
2850 fprintf(out,"%12s[","");
2851 for(i=0; i<lemp->nterminal; i++){
2852 if( SetFind(set,i) ){
2853 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2854 spacer = " ";
2855 }
2856 }
2857 fprintf(out,"]\n");
2858}
2859
2860/* Print a plink chain */
2861PRIVATE void PlinkPrint(out,plp,tag)
2862FILE *out;
2863struct plink *plp;
2864char *tag;
2865{
2866 while( plp ){
drhada354d2005-11-05 15:03:59 +00002867 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002868 ConfigPrint(out,plp->cfp);
2869 fprintf(out,"\n");
2870 plp = plp->next;
2871 }
2872}
2873#endif
2874
2875/* Print an action to the given file descriptor. Return FALSE if
2876** nothing was actually printed.
2877*/
2878int PrintAction(struct action *ap, FILE *fp, int indent){
2879 int result = 1;
2880 switch( ap->type ){
2881 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002882 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002883 break;
2884 case REDUCE:
2885 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2886 break;
2887 case ACCEPT:
2888 fprintf(fp,"%*s accept",indent,ap->sp->name);
2889 break;
2890 case ERROR:
2891 fprintf(fp,"%*s error",indent,ap->sp->name);
2892 break;
drh9892c5d2007-12-21 00:02:11 +00002893 case SRCONFLICT:
2894 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002895 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2896 indent,ap->sp->name,ap->x.rp->index);
2897 break;
drh9892c5d2007-12-21 00:02:11 +00002898 case SSCONFLICT:
2899 fprintf(fp,"%*s shift %d ** Parsing conflict **",
2900 indent,ap->sp->name,ap->x.stp->statenum);
2901 break;
drh75897232000-05-29 14:26:00 +00002902 case SH_RESOLVED:
2903 case RD_RESOLVED:
2904 case NOT_USED:
2905 result = 0;
2906 break;
2907 }
2908 return result;
2909}
2910
2911/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00002912void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002913{
2914 int i;
2915 struct state *stp;
2916 struct config *cfp;
2917 struct action *ap;
2918 FILE *fp;
2919
drh2aa6ca42004-09-10 00:14:04 +00002920 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002921 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002922 for(i=0; i<lemp->nstate; i++){
2923 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002924 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002925 if( lemp->basisflag ) cfp=stp->bp;
2926 else cfp=stp->cfp;
2927 while( cfp ){
2928 char buf[20];
2929 if( cfp->dot==cfp->rp->nrhs ){
2930 sprintf(buf,"(%d)",cfp->rp->index);
2931 fprintf(fp," %5s ",buf);
2932 }else{
2933 fprintf(fp," ");
2934 }
2935 ConfigPrint(fp,cfp);
2936 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002937#if 0
drh75897232000-05-29 14:26:00 +00002938 SetPrint(fp,cfp->fws,lemp);
2939 PlinkPrint(fp,cfp->fplp,"To ");
2940 PlinkPrint(fp,cfp->bplp,"From");
2941#endif
2942 if( lemp->basisflag ) cfp=cfp->bp;
2943 else cfp=cfp->next;
2944 }
2945 fprintf(fp,"\n");
2946 for(ap=stp->ap; ap; ap=ap->next){
2947 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2948 }
2949 fprintf(fp,"\n");
2950 }
drhe9278182007-07-18 18:16:29 +00002951 fprintf(fp, "----------------------------------------------------\n");
2952 fprintf(fp, "Symbols:\n");
2953 for(i=0; i<lemp->nsymbol; i++){
2954 int j;
2955 struct symbol *sp;
2956
2957 sp = lemp->symbols[i];
2958 fprintf(fp, " %3d: %s", i, sp->name);
2959 if( sp->type==NONTERMINAL ){
2960 fprintf(fp, ":");
2961 if( sp->lambda ){
2962 fprintf(fp, " <lambda>");
2963 }
2964 for(j=0; j<lemp->nterminal; j++){
2965 if( sp->firstset && SetFind(sp->firstset, j) ){
2966 fprintf(fp, " %s", lemp->symbols[j]->name);
2967 }
2968 }
2969 }
2970 fprintf(fp, "\n");
2971 }
drh75897232000-05-29 14:26:00 +00002972 fclose(fp);
2973 return;
2974}
2975
2976/* Search for the file "name" which is in the same directory as
2977** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00002978PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00002979{
icculus9e44cf12010-02-14 17:14:22 +00002980 const char *pathlist;
2981 char *pathbufptr;
2982 char *pathbuf;
drh75897232000-05-29 14:26:00 +00002983 char *path,*cp;
2984 char c;
drh75897232000-05-29 14:26:00 +00002985
2986#ifdef __WIN32__
2987 cp = strrchr(argv0,'\\');
2988#else
2989 cp = strrchr(argv0,'/');
2990#endif
2991 if( cp ){
2992 c = *cp;
2993 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00002994 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00002995 if( path ) sprintf(path,"%s/%s",argv0,name);
2996 *cp = c;
2997 }else{
drh75897232000-05-29 14:26:00 +00002998 pathlist = getenv("PATH");
2999 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00003000 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00003001 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00003002 if( (pathbuf != 0) && (path!=0) ){
3003 pathbufptr = pathbuf;
3004 strcpy(pathbuf, pathlist);
3005 while( *pathbuf ){
3006 cp = strchr(pathbuf,':');
3007 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00003008 c = *cp;
3009 *cp = 0;
icculus9e44cf12010-02-14 17:14:22 +00003010 sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003011 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003012 if( c==0 ) pathbuf[0] = 0;
3013 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003014 if( access(path,modemask)==0 ) break;
3015 }
icculus9e44cf12010-02-14 17:14:22 +00003016 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003017 }
3018 }
3019 return path;
3020}
3021
3022/* Given an action, compute the integer value for that action
3023** which is to be put in the action table of the generated machine.
3024** Return negative if no action should be generated.
3025*/
icculus9e44cf12010-02-14 17:14:22 +00003026PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003027{
3028 int act;
3029 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003030 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003031 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3032 case ERROR: act = lemp->nstate + lemp->nrule; break;
3033 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3034 default: act = -1; break;
3035 }
3036 return act;
3037}
3038
3039#define LINESIZE 1000
3040/* The next cluster of routines are for reading the template file
3041** and writing the results to the generated parser */
3042/* The first function transfers data from "in" to "out" until
3043** a line is seen which begins with "%%". The line number is
3044** tracked.
3045**
3046** if name!=0, then any word that begin with "Parse" is changed to
3047** begin with *name instead.
3048*/
icculus9e44cf12010-02-14 17:14:22 +00003049PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003050{
3051 int i, iStart;
3052 char line[LINESIZE];
3053 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3054 (*lineno)++;
3055 iStart = 0;
3056 if( name ){
3057 for(i=0; line[i]; i++){
3058 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3059 && (i==0 || !isalpha(line[i-1]))
3060 ){
3061 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3062 fprintf(out,"%s",name);
3063 i += 4;
3064 iStart = i+1;
3065 }
3066 }
3067 }
3068 fprintf(out,"%s",&line[iStart]);
3069 }
3070}
3071
3072/* The next function finds the template file and opens it, returning
3073** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003074PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003075{
3076 static char templatename[] = "lempar.c";
3077 char buf[1000];
3078 FILE *in;
3079 char *tpltname;
3080 char *cp;
3081
icculus3e143bd2010-02-14 00:48:49 +00003082 /* first, see if user specified a template filename on the command line. */
3083 if (user_templatename != 0) {
3084 if( access(user_templatename,004)==-1 ){
3085 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3086 user_templatename);
3087 lemp->errorcnt++;
3088 return 0;
3089 }
3090 in = fopen(user_templatename,"rb");
3091 if( in==0 ){
3092 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3093 lemp->errorcnt++;
3094 return 0;
3095 }
3096 return in;
3097 }
3098
drh75897232000-05-29 14:26:00 +00003099 cp = strrchr(lemp->filename,'.');
3100 if( cp ){
drh8b582012003-10-21 13:16:03 +00003101 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003102 }else{
3103 sprintf(buf,"%s.lt",lemp->filename);
3104 }
3105 if( access(buf,004)==0 ){
3106 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003107 }else if( access(templatename,004)==0 ){
3108 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003109 }else{
3110 tpltname = pathsearch(lemp->argv0,templatename,0);
3111 }
3112 if( tpltname==0 ){
3113 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3114 templatename);
3115 lemp->errorcnt++;
3116 return 0;
3117 }
drh2aa6ca42004-09-10 00:14:04 +00003118 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003119 if( in==0 ){
3120 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3121 lemp->errorcnt++;
3122 return 0;
3123 }
3124 return in;
3125}
3126
drhaf805ca2004-09-07 11:28:25 +00003127/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003128PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003129{
3130 fprintf(out,"#line %d \"",lineno);
3131 while( *filename ){
3132 if( *filename == '\\' ) putc('\\',out);
3133 putc(*filename,out);
3134 filename++;
3135 }
3136 fprintf(out,"\"\n");
3137}
3138
drh75897232000-05-29 14:26:00 +00003139/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003140PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003141{
3142 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003143 while( *str ){
drh75897232000-05-29 14:26:00 +00003144 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003145 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003146 str++;
3147 }
drh9db55df2004-09-09 14:01:21 +00003148 if( str[-1]!='\n' ){
3149 putc('\n',out);
3150 (*lineno)++;
3151 }
shane58543932008-12-10 20:10:04 +00003152 if (!lemp->nolinenosflag) {
3153 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3154 }
drh75897232000-05-29 14:26:00 +00003155 return;
3156}
3157
3158/*
3159** The following routine emits code for the destructor for the
3160** symbol sp
3161*/
icculus9e44cf12010-02-14 17:14:22 +00003162void emit_destructor_code(
3163 FILE *out,
3164 struct symbol *sp,
3165 struct lemon *lemp,
3166 int *lineno
3167){
drhcc83b6e2004-04-23 23:38:42 +00003168 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003169
drh75897232000-05-29 14:26:00 +00003170 if( sp->type==TERMINAL ){
3171 cp = lemp->tokendest;
3172 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003173 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003174 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003175 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003176 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003177 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003178 }else if( lemp->vardest ){
3179 cp = lemp->vardest;
3180 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003181 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003182 }else{
3183 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003184 }
3185 for(; *cp; cp++){
3186 if( *cp=='$' && cp[1]=='$' ){
3187 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3188 cp++;
3189 continue;
3190 }
shane58543932008-12-10 20:10:04 +00003191 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003192 fputc(*cp,out);
3193 }
shane58543932008-12-10 20:10:04 +00003194 fprintf(out,"\n"); (*lineno)++;
3195 if (!lemp->nolinenosflag) {
3196 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3197 }
3198 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003199 return;
3200}
3201
3202/*
drh960e8c62001-04-03 16:53:21 +00003203** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003204*/
icculus9e44cf12010-02-14 17:14:22 +00003205int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003206{
3207 int ret;
3208 if( sp->type==TERMINAL ){
3209 ret = lemp->tokendest!=0;
3210 }else{
drh960e8c62001-04-03 16:53:21 +00003211 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003212 }
3213 return ret;
3214}
3215
drh0bb132b2004-07-20 14:06:51 +00003216/*
3217** Append text to a dynamically allocated string. If zText is 0 then
3218** reset the string to be empty again. Always return the complete text
3219** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003220**
3221** n bytes of zText are stored. If n==0 then all of zText up to the first
3222** \000 terminator is stored. zText can contain up to two instances of
3223** %d. The values of p1 and p2 are written into the first and second
3224** %d.
3225**
3226** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003227*/
icculus9e44cf12010-02-14 17:14:22 +00003228PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3229 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003230 static char *z = 0;
3231 static int alloced = 0;
3232 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003233 int c;
drh0bb132b2004-07-20 14:06:51 +00003234 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003235 if( zText==0 ){
3236 used = 0;
3237 return z;
3238 }
drh7ac25c72004-08-19 15:12:26 +00003239 if( n<=0 ){
3240 if( n<0 ){
3241 used += n;
3242 assert( used>=0 );
3243 }
drh87cf1372008-08-13 20:09:06 +00003244 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003245 }
drh0bb132b2004-07-20 14:06:51 +00003246 if( n+sizeof(zInt)*2+used >= alloced ){
3247 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003248 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003249 }
icculus9e44cf12010-02-14 17:14:22 +00003250 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003251 while( n-- > 0 ){
3252 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003253 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003254 sprintf(zInt, "%d", p1);
3255 p1 = p2;
3256 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003257 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003258 zText++;
3259 n--;
3260 }else{
3261 z[used++] = c;
3262 }
3263 }
3264 z[used] = 0;
3265 return z;
3266}
3267
3268/*
3269** zCode is a string that is the action associated with a rule. Expand
3270** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003271** stack.
drh0bb132b2004-07-20 14:06:51 +00003272*/
drhaf805ca2004-09-07 11:28:25 +00003273PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003274 char *cp, *xp;
3275 int i;
3276 char lhsused = 0; /* True if the LHS element has been used */
3277 char used[MAXRHS]; /* True for each RHS element which is used */
3278
3279 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3280 lhsused = 0;
3281
drh19c9e562007-03-29 20:13:53 +00003282 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003283 static char newlinestr[2] = { '\n', '\0' };
3284 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003285 rp->line = rp->ruleline;
3286 }
3287
drh0bb132b2004-07-20 14:06:51 +00003288 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003289
3290 /* This const cast is wrong but harmless, if we're careful. */
3291 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003292 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3293 char saved;
3294 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3295 saved = *xp;
3296 *xp = 0;
3297 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003298 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003299 cp = xp;
3300 lhsused = 1;
3301 }else{
3302 for(i=0; i<rp->nrhs; i++){
3303 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003304 if( cp!=rp->code && cp[-1]=='@' ){
3305 /* If the argument is of the form @X then substituted
3306 ** the token number of X, not the value of X */
3307 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3308 }else{
drhfd405312005-11-06 04:06:59 +00003309 struct symbol *sp = rp->rhs[i];
3310 int dtnum;
3311 if( sp->type==MULTITERMINAL ){
3312 dtnum = sp->subsym[0]->dtnum;
3313 }else{
3314 dtnum = sp->dtnum;
3315 }
3316 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003317 }
drh0bb132b2004-07-20 14:06:51 +00003318 cp = xp;
3319 used[i] = 1;
3320 break;
3321 }
3322 }
3323 }
3324 *xp = saved;
3325 }
3326 append_str(cp, 1, 0, 0);
3327 } /* End loop */
3328
3329 /* Check to make sure the LHS has been used */
3330 if( rp->lhsalias && !lhsused ){
3331 ErrorMsg(lemp->filename,rp->ruleline,
3332 "Label \"%s\" for \"%s(%s)\" is never used.",
3333 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3334 lemp->errorcnt++;
3335 }
3336
3337 /* Generate destructor code for RHS symbols which are not used in the
3338 ** reduce code */
3339 for(i=0; i<rp->nrhs; i++){
3340 if( rp->rhsalias[i] && !used[i] ){
3341 ErrorMsg(lemp->filename,rp->ruleline,
3342 "Label %s for \"%s(%s)\" is never used.",
3343 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3344 lemp->errorcnt++;
3345 }else if( rp->rhsalias[i]==0 ){
3346 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003347 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003348 rp->rhs[i]->index,i-rp->nrhs+1);
3349 }else{
3350 /* No destructor defined for this term */
3351 }
3352 }
3353 }
drh61e339a2007-01-16 03:09:02 +00003354 if( rp->code ){
3355 cp = append_str(0,0,0,0);
3356 rp->code = Strsafe(cp?cp:"");
3357 }
drh0bb132b2004-07-20 14:06:51 +00003358}
3359
drh75897232000-05-29 14:26:00 +00003360/*
3361** Generate code which executes when the rule "rp" is reduced. Write
3362** the code to "out". Make sure lineno stays up-to-date.
3363*/
icculus9e44cf12010-02-14 17:14:22 +00003364PRIVATE void emit_code(
3365 FILE *out,
3366 struct rule *rp,
3367 struct lemon *lemp,
3368 int *lineno
3369){
3370 const char *cp;
drh75897232000-05-29 14:26:00 +00003371
3372 /* Generate code to do the reduce action */
3373 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003374 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003375 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003376 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003377 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003378 } /* End loop */
shane58543932008-12-10 20:10:04 +00003379 fprintf(out,"}\n"); (*lineno)++;
3380 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003381 } /* End if( rp->code ) */
3382
drh75897232000-05-29 14:26:00 +00003383 return;
3384}
3385
3386/*
3387** Print the definition of the union used for the parser's data stack.
3388** This union contains fields for every possible data type for tokens
3389** and nonterminals. In the process of computing and printing this
3390** union, also set the ".dtnum" field of every terminal and nonterminal
3391** symbol.
3392*/
icculus9e44cf12010-02-14 17:14:22 +00003393void print_stack_union(
3394 FILE *out, /* The output stream */
3395 struct lemon *lemp, /* The main info structure for this parser */
3396 int *plineno, /* Pointer to the line number */
3397 int mhflag /* True if generating makeheaders output */
3398){
drh75897232000-05-29 14:26:00 +00003399 int lineno = *plineno; /* The line number of the output */
3400 char **types; /* A hash table of datatypes */
3401 int arraysize; /* Size of the "types" array */
3402 int maxdtlength; /* Maximum length of any ".datatype" field. */
3403 char *stddt; /* Standardized name for a datatype */
3404 int i,j; /* Loop counters */
3405 int hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003406 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003407
3408 /* Allocate and initialize types[] and allocate stddt[] */
3409 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003410 types = (char**)calloc( arraysize, sizeof(char*) );
drh75897232000-05-29 14:26:00 +00003411 for(i=0; i<arraysize; i++) types[i] = 0;
3412 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003413 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003414 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003415 }
drh75897232000-05-29 14:26:00 +00003416 for(i=0; i<lemp->nsymbol; i++){
3417 int len;
3418 struct symbol *sp = lemp->symbols[i];
3419 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003420 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003421 if( len>maxdtlength ) maxdtlength = len;
3422 }
3423 stddt = (char*)malloc( maxdtlength*2 + 1 );
3424 if( types==0 || stddt==0 ){
3425 fprintf(stderr,"Out of memory.\n");
3426 exit(1);
3427 }
3428
3429 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3430 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003431 ** used for terminal symbols. If there is no %default_type defined then
3432 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3433 ** a datatype using the %type directive.
3434 */
drh75897232000-05-29 14:26:00 +00003435 for(i=0; i<lemp->nsymbol; i++){
3436 struct symbol *sp = lemp->symbols[i];
3437 char *cp;
3438 if( sp==lemp->errsym ){
3439 sp->dtnum = arraysize+1;
3440 continue;
3441 }
drh960e8c62001-04-03 16:53:21 +00003442 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003443 sp->dtnum = 0;
3444 continue;
3445 }
3446 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003447 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003448 j = 0;
3449 while( isspace(*cp) ) cp++;
3450 while( *cp ) stddt[j++] = *cp++;
3451 while( j>0 && isspace(stddt[j-1]) ) j--;
3452 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003453 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003454 sp->dtnum = 0;
3455 continue;
3456 }
drh75897232000-05-29 14:26:00 +00003457 hash = 0;
3458 for(j=0; stddt[j]; j++){
3459 hash = hash*53 + stddt[j];
3460 }
drh3b2129c2003-05-13 00:34:21 +00003461 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003462 while( types[hash] ){
3463 if( strcmp(types[hash],stddt)==0 ){
3464 sp->dtnum = hash + 1;
3465 break;
3466 }
3467 hash++;
3468 if( hash>=arraysize ) hash = 0;
3469 }
3470 if( types[hash]==0 ){
3471 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003472 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003473 if( types[hash]==0 ){
3474 fprintf(stderr,"Out of memory.\n");
3475 exit(1);
3476 }
3477 strcpy(types[hash],stddt);
3478 }
3479 }
3480
3481 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3482 name = lemp->name ? lemp->name : "Parse";
3483 lineno = *plineno;
3484 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3485 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3486 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3487 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3488 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003489 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003490 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3491 for(i=0; i<arraysize; i++){
3492 if( types[i]==0 ) continue;
3493 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3494 free(types[i]);
3495 }
drhc4dd3fd2008-01-22 01:48:05 +00003496 if( lemp->errsym->useCnt ){
3497 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3498 }
drh75897232000-05-29 14:26:00 +00003499 free(stddt);
3500 free(types);
3501 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3502 *plineno = lineno;
3503}
3504
drhb29b0a52002-02-23 19:39:46 +00003505/*
3506** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003507** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003508*/
drh8b582012003-10-21 13:16:03 +00003509static const char *minimum_size_type(int lwr, int upr){
3510 if( lwr>=0 ){
3511 if( upr<=255 ){
3512 return "unsigned char";
3513 }else if( upr<65535 ){
3514 return "unsigned short int";
3515 }else{
3516 return "unsigned int";
3517 }
3518 }else if( lwr>=-127 && upr<=127 ){
3519 return "signed char";
3520 }else if( lwr>=-32767 && upr<32767 ){
3521 return "short";
drhb29b0a52002-02-23 19:39:46 +00003522 }else{
drh8b582012003-10-21 13:16:03 +00003523 return "int";
drhb29b0a52002-02-23 19:39:46 +00003524 }
3525}
3526
drhfdbf9282003-10-21 16:34:41 +00003527/*
3528** Each state contains a set of token transaction and a set of
3529** nonterminal transactions. Each of these sets makes an instance
3530** of the following structure. An array of these structures is used
3531** to order the creation of entries in the yy_action[] table.
3532*/
3533struct axset {
3534 struct state *stp; /* A pointer to a state */
3535 int isTkn; /* True to use tokens. False for non-terminals */
3536 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003537 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003538};
3539
3540/*
3541** Compare to axset structures for sorting purposes
3542*/
3543static int axset_compare(const void *a, const void *b){
3544 struct axset *p1 = (struct axset*)a;
3545 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003546 int c;
3547 c = p2->nAction - p1->nAction;
3548 if( c==0 ){
3549 c = p2->iOrder - p1->iOrder;
3550 }
3551 assert( c!=0 || p1==p2 );
3552 return c;
drhfdbf9282003-10-21 16:34:41 +00003553}
3554
drhc4dd3fd2008-01-22 01:48:05 +00003555/*
3556** Write text on "out" that describes the rule "rp".
3557*/
3558static void writeRuleText(FILE *out, struct rule *rp){
3559 int j;
3560 fprintf(out,"%s ::=", rp->lhs->name);
3561 for(j=0; j<rp->nrhs; j++){
3562 struct symbol *sp = rp->rhs[j];
3563 fprintf(out," %s", sp->name);
3564 if( sp->type==MULTITERMINAL ){
3565 int k;
3566 for(k=1; k<sp->nsubsym; k++){
3567 fprintf(out,"|%s",sp->subsym[k]->name);
3568 }
3569 }
3570 }
3571}
3572
3573
drh75897232000-05-29 14:26:00 +00003574/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003575void ReportTable(
3576 struct lemon *lemp,
3577 int mhflag /* Output in makeheaders format if true */
3578){
drh75897232000-05-29 14:26:00 +00003579 FILE *out, *in;
3580 char line[LINESIZE];
3581 int lineno;
3582 struct state *stp;
3583 struct action *ap;
3584 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003585 struct acttab *pActtab;
icculusa3191192010-02-17 05:40:34 +00003586 int i, j, n;
icculus9e44cf12010-02-14 17:14:22 +00003587 const char *name;
drh8b582012003-10-21 13:16:03 +00003588 int mnTknOfst, mxTknOfst;
3589 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003590 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003591
3592 in = tplt_open(lemp);
3593 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003594 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003595 if( out==0 ){
3596 fclose(in);
3597 return;
3598 }
3599 lineno = 1;
3600 tplt_xfer(lemp->name,in,out,&lineno);
3601
3602 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003603 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003604 if( mhflag ){
3605 char *name = file_makename(lemp, ".h");
3606 fprintf(out,"#include \"%s\"\n", name); lineno++;
3607 free(name);
3608 }
3609 tplt_xfer(lemp->name,in,out,&lineno);
3610
3611 /* Generate #defines for all tokens */
3612 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003613 const char *prefix;
drh75897232000-05-29 14:26:00 +00003614 fprintf(out,"#if INTERFACE\n"); lineno++;
3615 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3616 else prefix = "";
3617 for(i=1; i<lemp->nterminal; i++){
3618 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3619 lineno++;
3620 }
3621 fprintf(out,"#endif\n"); lineno++;
3622 }
3623 tplt_xfer(lemp->name,in,out,&lineno);
3624
3625 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003626 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003627 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003628 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3629 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003630 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003631 if( lemp->wildcard ){
3632 fprintf(out,"#define YYWILDCARD %d\n",
3633 lemp->wildcard->index); lineno++;
3634 }
drh75897232000-05-29 14:26:00 +00003635 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003636 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003637 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003638 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3639 }else{
3640 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3641 }
drhca44b5a2007-02-22 23:06:58 +00003642 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003643 if( mhflag ){
3644 fprintf(out,"#if INTERFACE\n"); lineno++;
3645 }
3646 name = lemp->name ? lemp->name : "Parse";
3647 if( lemp->arg && lemp->arg[0] ){
3648 int i;
drh87cf1372008-08-13 20:09:06 +00003649 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003650 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3651 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003652 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3653 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3654 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3655 name,lemp->arg,&lemp->arg[i]); lineno++;
3656 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3657 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003658 }else{
drh1f245e42002-03-11 13:55:50 +00003659 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3660 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3661 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3662 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003663 }
3664 if( mhflag ){
3665 fprintf(out,"#endif\n"); lineno++;
3666 }
3667 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3668 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003669 if( lemp->errsym->useCnt ){
3670 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3671 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3672 }
drh0bd1f4e2002-06-06 18:54:39 +00003673 if( lemp->has_fallback ){
3674 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3675 }
drh75897232000-05-29 14:26:00 +00003676 tplt_xfer(lemp->name,in,out,&lineno);
3677
drh8b582012003-10-21 13:16:03 +00003678 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003679 **
drh8b582012003-10-21 13:16:03 +00003680 ** yy_action[] A single table containing all actions.
3681 ** yy_lookahead[] A table containing the lookahead for each entry in
3682 ** yy_action. Used to detect hash collisions.
3683 ** yy_shift_ofst[] For each state, the offset into yy_action for
3684 ** shifting terminals.
3685 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3686 ** shifting non-terminals after a reduce.
3687 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003688 */
drh75897232000-05-29 14:26:00 +00003689
drh8b582012003-10-21 13:16:03 +00003690 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003691 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003692 if( ax==0 ){
3693 fprintf(stderr,"malloc failed\n");
3694 exit(1);
3695 }
drh75897232000-05-29 14:26:00 +00003696 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003697 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003698 ax[i*2].stp = stp;
3699 ax[i*2].isTkn = 1;
3700 ax[i*2].nAction = stp->nTknAct;
3701 ax[i*2+1].stp = stp;
3702 ax[i*2+1].isTkn = 0;
3703 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003704 }
drh8b582012003-10-21 13:16:03 +00003705 mxTknOfst = mnTknOfst = 0;
3706 mxNtOfst = mnNtOfst = 0;
3707
drhfdbf9282003-10-21 16:34:41 +00003708 /* Compute the action table. In order to try to keep the size of the
3709 ** action table to a minimum, the heuristic of placing the largest action
3710 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003711 */
drhe594bc32009-11-03 13:02:25 +00003712 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003713 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003714 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003715 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3716 stp = ax[i].stp;
3717 if( ax[i].isTkn ){
3718 for(ap=stp->ap; ap; ap=ap->next){
3719 int action;
3720 if( ap->sp->index>=lemp->nterminal ) continue;
3721 action = compute_action(lemp, ap);
3722 if( action<0 ) continue;
3723 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003724 }
drhfdbf9282003-10-21 16:34:41 +00003725 stp->iTknOfst = acttab_insert(pActtab);
3726 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3727 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3728 }else{
3729 for(ap=stp->ap; ap; ap=ap->next){
3730 int action;
3731 if( ap->sp->index<lemp->nterminal ) continue;
3732 if( ap->sp->index==lemp->nsymbol ) continue;
3733 action = compute_action(lemp, ap);
3734 if( action<0 ) continue;
3735 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003736 }
drhfdbf9282003-10-21 16:34:41 +00003737 stp->iNtOfst = acttab_insert(pActtab);
3738 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3739 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003740 }
3741 }
drhfdbf9282003-10-21 16:34:41 +00003742 free(ax);
drh8b582012003-10-21 13:16:03 +00003743
3744 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003745 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003746 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3747 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003748 for(i=j=0; i<n; i++){
3749 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003750 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003751 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003752 fprintf(out, " %4d,", action);
3753 if( j==9 || i==n-1 ){
3754 fprintf(out, "\n"); lineno++;
3755 j = 0;
3756 }else{
3757 j++;
3758 }
3759 }
3760 fprintf(out, "};\n"); lineno++;
3761
3762 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003763 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003764 for(i=j=0; i<n; i++){
3765 int la = acttab_yylookahead(pActtab, i);
3766 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003767 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003768 fprintf(out, " %4d,", la);
3769 if( j==9 || i==n-1 ){
3770 fprintf(out, "\n"); lineno++;
3771 j = 0;
3772 }else{
3773 j++;
3774 }
3775 }
3776 fprintf(out, "};\n"); lineno++;
3777
3778 /* Output the yy_shift_ofst[] table */
3779 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003780 n = lemp->nstate;
3781 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003782 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3783 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3784 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003785 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003786 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003787 for(i=j=0; i<n; i++){
3788 int ofst;
3789 stp = lemp->sorted[i];
3790 ofst = stp->iTknOfst;
3791 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003792 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003793 fprintf(out, " %4d,", ofst);
3794 if( j==9 || i==n-1 ){
3795 fprintf(out, "\n"); lineno++;
3796 j = 0;
3797 }else{
3798 j++;
3799 }
3800 }
3801 fprintf(out, "};\n"); lineno++;
3802
3803 /* Output the yy_reduce_ofst[] table */
3804 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003805 n = lemp->nstate;
3806 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003807 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3808 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3809 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003810 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003811 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003812 for(i=j=0; i<n; i++){
3813 int ofst;
3814 stp = lemp->sorted[i];
3815 ofst = stp->iNtOfst;
3816 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003817 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003818 fprintf(out, " %4d,", ofst);
3819 if( j==9 || i==n-1 ){
3820 fprintf(out, "\n"); lineno++;
3821 j = 0;
3822 }else{
3823 j++;
3824 }
3825 }
3826 fprintf(out, "};\n"); lineno++;
3827
3828 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003829 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003830 n = lemp->nstate;
3831 for(i=j=0; i<n; i++){
3832 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003833 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003834 fprintf(out, " %4d,", stp->iDflt);
3835 if( j==9 || i==n-1 ){
3836 fprintf(out, "\n"); lineno++;
3837 j = 0;
3838 }else{
3839 j++;
3840 }
3841 }
3842 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003843 tplt_xfer(lemp->name,in,out,&lineno);
3844
drh0bd1f4e2002-06-06 18:54:39 +00003845 /* Generate the table of fallback tokens.
3846 */
3847 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003848 int mx = lemp->nterminal - 1;
3849 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3850 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003851 struct symbol *p = lemp->symbols[i];
3852 if( p->fallback==0 ){
3853 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3854 }else{
3855 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3856 p->name, p->fallback->name);
3857 }
3858 lineno++;
3859 }
3860 }
3861 tplt_xfer(lemp->name, in, out, &lineno);
3862
3863 /* Generate a table containing the symbolic name of every symbol
3864 */
drh75897232000-05-29 14:26:00 +00003865 for(i=0; i<lemp->nsymbol; i++){
3866 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3867 fprintf(out," %-15s",line);
3868 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3869 }
3870 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3871 tplt_xfer(lemp->name,in,out,&lineno);
3872
drh0bd1f4e2002-06-06 18:54:39 +00003873 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003874 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003875 ** when tracing REDUCE actions.
3876 */
3877 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3878 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003879 fprintf(out," /* %3d */ \"", i);
3880 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003881 fprintf(out,"\",\n"); lineno++;
3882 }
3883 tplt_xfer(lemp->name,in,out,&lineno);
3884
drh75897232000-05-29 14:26:00 +00003885 /* Generate code which executes every time a symbol is popped from
3886 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003887 ** (In other words, generate the %destructor actions)
3888 */
drh75897232000-05-29 14:26:00 +00003889 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003890 int once = 1;
drh75897232000-05-29 14:26:00 +00003891 for(i=0; i<lemp->nsymbol; i++){
3892 struct symbol *sp = lemp->symbols[i];
3893 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003894 if( once ){
3895 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3896 once = 0;
3897 }
drhc53eed12009-06-12 17:46:19 +00003898 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003899 }
3900 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3901 if( i<lemp->nsymbol ){
3902 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3903 fprintf(out," break;\n"); lineno++;
3904 }
3905 }
drh8d659732005-01-13 23:54:06 +00003906 if( lemp->vardest ){
3907 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003908 int once = 1;
drh8d659732005-01-13 23:54:06 +00003909 for(i=0; i<lemp->nsymbol; i++){
3910 struct symbol *sp = lemp->symbols[i];
3911 if( sp==0 || sp->type==TERMINAL ||
3912 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003913 if( once ){
3914 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3915 once = 0;
3916 }
drhc53eed12009-06-12 17:46:19 +00003917 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003918 dflt_sp = sp;
3919 }
3920 if( dflt_sp!=0 ){
3921 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003922 }
drh4dc8ef52008-07-01 17:13:57 +00003923 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003924 }
drh75897232000-05-29 14:26:00 +00003925 for(i=0; i<lemp->nsymbol; i++){
3926 struct symbol *sp = lemp->symbols[i];
3927 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003928 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003929
3930 /* Combine duplicate destructors into a single case */
3931 for(j=i+1; j<lemp->nsymbol; j++){
3932 struct symbol *sp2 = lemp->symbols[j];
3933 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3934 && sp2->dtnum==sp->dtnum
3935 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003936 fprintf(out," case %d: /* %s */\n",
3937 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003938 sp2->destructor = 0;
3939 }
3940 }
3941
drh75897232000-05-29 14:26:00 +00003942 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3943 fprintf(out," break;\n"); lineno++;
3944 }
drh75897232000-05-29 14:26:00 +00003945 tplt_xfer(lemp->name,in,out,&lineno);
3946
3947 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003948 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003949 tplt_xfer(lemp->name,in,out,&lineno);
3950
3951 /* Generate the table of rule information
3952 **
3953 ** Note: This code depends on the fact that rules are number
3954 ** sequentually beginning with 0.
3955 */
3956 for(rp=lemp->rule; rp; rp=rp->next){
3957 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3958 }
3959 tplt_xfer(lemp->name,in,out,&lineno);
3960
3961 /* Generate code which execution during each REDUCE action */
3962 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003963 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003964 }
drhc53eed12009-06-12 17:46:19 +00003965 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003966 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003967 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003968 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003969 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003970 fprintf(out," case %d: /* ", rp->index);
3971 writeRuleText(out, rp);
3972 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003973 for(rp2=rp->next; rp2; rp2=rp2->next){
3974 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003975 fprintf(out," case %d: /* ", rp2->index);
3976 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003977 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003978 rp2->code = 0;
3979 }
3980 }
drh75897232000-05-29 14:26:00 +00003981 emit_code(out,rp,lemp,&lineno);
3982 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00003983 rp->code = 0;
drh75897232000-05-29 14:26:00 +00003984 }
drhc53eed12009-06-12 17:46:19 +00003985 /* Finally, output the default: rule. We choose as the default: all
3986 ** empty actions. */
3987 fprintf(out," default:\n"); lineno++;
3988 for(rp=lemp->rule; rp; rp=rp->next){
3989 if( rp->code==0 ) continue;
3990 assert( rp->code[0]=='\n' && rp->code[1]==0 );
3991 fprintf(out," /* (%d) ", rp->index);
3992 writeRuleText(out, rp);
3993 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
3994 }
3995 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003996 tplt_xfer(lemp->name,in,out,&lineno);
3997
3998 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003999 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00004000 tplt_xfer(lemp->name,in,out,&lineno);
4001
4002 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00004003 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00004004 tplt_xfer(lemp->name,in,out,&lineno);
4005
4006 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004007 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004008 tplt_xfer(lemp->name,in,out,&lineno);
4009
4010 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004011 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004012
4013 fclose(in);
4014 fclose(out);
4015 return;
4016}
4017
4018/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004019void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004020{
4021 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004022 const char *prefix;
drh75897232000-05-29 14:26:00 +00004023 char line[LINESIZE];
4024 char pattern[LINESIZE];
4025 int i;
4026
4027 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4028 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004029 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004030 if( in ){
4031 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4032 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4033 if( strcmp(line,pattern) ) break;
4034 }
4035 fclose(in);
4036 if( i==lemp->nterminal ){
4037 /* No change in the file. Don't rewrite it. */
4038 return;
4039 }
4040 }
drh2aa6ca42004-09-10 00:14:04 +00004041 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004042 if( out ){
4043 for(i=1; i<lemp->nterminal; i++){
4044 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4045 }
4046 fclose(out);
4047 }
4048 return;
4049}
4050
4051/* Reduce the size of the action tables, if possible, by making use
4052** of defaults.
4053**
drhb59499c2002-02-23 18:45:13 +00004054** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004055** it the default. Except, there is no default if the wildcard token
4056** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004057*/
icculus9e44cf12010-02-14 17:14:22 +00004058void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004059{
4060 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004061 struct action *ap, *ap2;
4062 struct rule *rp, *rp2, *rbest;
4063 int nbest, n;
drh75897232000-05-29 14:26:00 +00004064 int i;
drhe09daa92006-06-10 13:29:31 +00004065 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004066
4067 for(i=0; i<lemp->nstate; i++){
4068 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004069 nbest = 0;
4070 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004071 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004072
drhb59499c2002-02-23 18:45:13 +00004073 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004074 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4075 usesWildcard = 1;
4076 }
drhb59499c2002-02-23 18:45:13 +00004077 if( ap->type!=REDUCE ) continue;
4078 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004079 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004080 if( rp==rbest ) continue;
4081 n = 1;
4082 for(ap2=ap->next; ap2; ap2=ap2->next){
4083 if( ap2->type!=REDUCE ) continue;
4084 rp2 = ap2->x.rp;
4085 if( rp2==rbest ) continue;
4086 if( rp2==rp ) n++;
4087 }
4088 if( n>nbest ){
4089 nbest = n;
4090 rbest = rp;
drh75897232000-05-29 14:26:00 +00004091 }
4092 }
drhb59499c2002-02-23 18:45:13 +00004093
4094 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004095 ** is not at least 1 or if the wildcard token is a possible
4096 ** lookahead.
4097 */
4098 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004099
drhb59499c2002-02-23 18:45:13 +00004100
4101 /* Combine matching REDUCE actions into a single default */
4102 for(ap=stp->ap; ap; ap=ap->next){
4103 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4104 }
drh75897232000-05-29 14:26:00 +00004105 assert( ap );
4106 ap->sp = Symbol_new("{default}");
4107 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004108 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004109 }
4110 stp->ap = Action_sort(stp->ap);
4111 }
4112}
drhb59499c2002-02-23 18:45:13 +00004113
drhada354d2005-11-05 15:03:59 +00004114
4115/*
4116** Compare two states for sorting purposes. The smaller state is the
4117** one with the most non-terminal actions. If they have the same number
4118** of non-terminal actions, then the smaller is the one with the most
4119** token actions.
4120*/
4121static int stateResortCompare(const void *a, const void *b){
4122 const struct state *pA = *(const struct state**)a;
4123 const struct state *pB = *(const struct state**)b;
4124 int n;
4125
4126 n = pB->nNtAct - pA->nNtAct;
4127 if( n==0 ){
4128 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004129 if( n==0 ){
4130 n = pB->statenum - pA->statenum;
4131 }
drhada354d2005-11-05 15:03:59 +00004132 }
drhe594bc32009-11-03 13:02:25 +00004133 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004134 return n;
4135}
4136
4137
4138/*
4139** Renumber and resort states so that states with fewer choices
4140** occur at the end. Except, keep state 0 as the first state.
4141*/
icculus9e44cf12010-02-14 17:14:22 +00004142void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004143{
4144 int i;
4145 struct state *stp;
4146 struct action *ap;
4147
4148 for(i=0; i<lemp->nstate; i++){
4149 stp = lemp->sorted[i];
4150 stp->nTknAct = stp->nNtAct = 0;
4151 stp->iDflt = lemp->nstate + lemp->nrule;
4152 stp->iTknOfst = NO_OFFSET;
4153 stp->iNtOfst = NO_OFFSET;
4154 for(ap=stp->ap; ap; ap=ap->next){
4155 if( compute_action(lemp,ap)>=0 ){
4156 if( ap->sp->index<lemp->nterminal ){
4157 stp->nTknAct++;
4158 }else if( ap->sp->index<lemp->nsymbol ){
4159 stp->nNtAct++;
4160 }else{
4161 stp->iDflt = compute_action(lemp, ap);
4162 }
4163 }
4164 }
4165 }
4166 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4167 stateResortCompare);
4168 for(i=0; i<lemp->nstate; i++){
4169 lemp->sorted[i]->statenum = i;
4170 }
4171}
4172
4173
drh75897232000-05-29 14:26:00 +00004174/***************** From the file "set.c" ************************************/
4175/*
4176** Set manipulation routines for the LEMON parser generator.
4177*/
4178
4179static int size = 0;
4180
4181/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004182void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004183{
4184 size = n+1;
4185}
4186
4187/* Allocate a new set */
4188char *SetNew(){
4189 char *s;
drh9892c5d2007-12-21 00:02:11 +00004190 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004191 if( s==0 ){
4192 extern void memory_error();
4193 memory_error();
4194 }
drh75897232000-05-29 14:26:00 +00004195 return s;
4196}
4197
4198/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004199void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004200{
4201 free(s);
4202}
4203
4204/* Add a new element to the set. Return TRUE if the element was added
4205** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004206int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004207{
4208 int rv;
drh9892c5d2007-12-21 00:02:11 +00004209 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004210 rv = s[e];
4211 s[e] = 1;
4212 return !rv;
4213}
4214
4215/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004216int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004217{
4218 int i, progress;
4219 progress = 0;
4220 for(i=0; i<size; i++){
4221 if( s2[i]==0 ) continue;
4222 if( s1[i]==0 ){
4223 progress = 1;
4224 s1[i] = 1;
4225 }
4226 }
4227 return progress;
4228}
4229/********************** From the file "table.c" ****************************/
4230/*
4231** All code in this file has been automatically generated
4232** from a specification in the file
4233** "table.q"
4234** by the associative array code building program "aagen".
4235** Do not edit this file! Instead, edit the specification
4236** file, then rerun aagen.
4237*/
4238/*
4239** Code for processing tables in the LEMON parser generator.
4240*/
4241
icculus9e44cf12010-02-14 17:14:22 +00004242PRIVATE int strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004243{
4244 int h = 0;
4245 while( *x) h = h*13 + *(x++);
4246 return h;
4247}
4248
4249/* Works like strdup, sort of. Save a string in malloced memory, but
4250** keep strings in a table so that the same string is not in more
4251** than one place.
4252*/
icculus9e44cf12010-02-14 17:14:22 +00004253const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004254{
icculus9e44cf12010-02-14 17:14:22 +00004255 const char *z;
4256 char *cpy;
drh75897232000-05-29 14:26:00 +00004257
drh916f75f2006-07-17 00:19:39 +00004258 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004259 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004260 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4261 strcpy(cpy,y);
4262 z = cpy;
drh75897232000-05-29 14:26:00 +00004263 Strsafe_insert(z);
4264 }
4265 MemoryCheck(z);
4266 return z;
4267}
4268
4269/* There is one instance of the following structure for each
4270** associative array of type "x1".
4271*/
4272struct s_x1 {
4273 int size; /* The number of available slots. */
4274 /* Must be a power of 2 greater than or */
4275 /* equal to 1 */
4276 int count; /* Number of currently slots filled */
4277 struct s_x1node *tbl; /* The data stored here */
4278 struct s_x1node **ht; /* Hash table for lookups */
4279};
4280
4281/* There is one instance of this structure for every data element
4282** in an associative array of type "x1".
4283*/
4284typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004285 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004286 struct s_x1node *next; /* Next entry with the same hash */
4287 struct s_x1node **from; /* Previous link */
4288} x1node;
4289
4290/* There is only one instance of the array, which is the following */
4291static struct s_x1 *x1a;
4292
4293/* Allocate a new associative array */
4294void Strsafe_init(){
4295 if( x1a ) return;
4296 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4297 if( x1a ){
4298 x1a->size = 1024;
4299 x1a->count = 0;
4300 x1a->tbl = (x1node*)malloc(
4301 (sizeof(x1node) + sizeof(x1node*))*1024 );
4302 if( x1a->tbl==0 ){
4303 free(x1a);
4304 x1a = 0;
4305 }else{
4306 int i;
4307 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4308 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4309 }
4310 }
4311}
4312/* Insert a new record into the array. Return TRUE if successful.
4313** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004314int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004315{
4316 x1node *np;
4317 int h;
4318 int ph;
4319
4320 if( x1a==0 ) return 0;
4321 ph = strhash(data);
4322 h = ph & (x1a->size-1);
4323 np = x1a->ht[h];
4324 while( np ){
4325 if( strcmp(np->data,data)==0 ){
4326 /* An existing entry with the same key is found. */
4327 /* Fail because overwrite is not allows. */
4328 return 0;
4329 }
4330 np = np->next;
4331 }
4332 if( x1a->count>=x1a->size ){
4333 /* Need to make the hash table bigger */
4334 int i,size;
4335 struct s_x1 array;
4336 array.size = size = x1a->size*2;
4337 array.count = x1a->count;
4338 array.tbl = (x1node*)malloc(
4339 (sizeof(x1node) + sizeof(x1node*))*size );
4340 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4341 array.ht = (x1node**)&(array.tbl[size]);
4342 for(i=0; i<size; i++) array.ht[i] = 0;
4343 for(i=0; i<x1a->count; i++){
4344 x1node *oldnp, *newnp;
4345 oldnp = &(x1a->tbl[i]);
4346 h = strhash(oldnp->data) & (size-1);
4347 newnp = &(array.tbl[i]);
4348 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4349 newnp->next = array.ht[h];
4350 newnp->data = oldnp->data;
4351 newnp->from = &(array.ht[h]);
4352 array.ht[h] = newnp;
4353 }
4354 free(x1a->tbl);
4355 *x1a = array;
4356 }
4357 /* Insert the new data */
4358 h = ph & (x1a->size-1);
4359 np = &(x1a->tbl[x1a->count++]);
4360 np->data = data;
4361 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4362 np->next = x1a->ht[h];
4363 x1a->ht[h] = np;
4364 np->from = &(x1a->ht[h]);
4365 return 1;
4366}
4367
4368/* Return a pointer to data assigned to the given key. Return NULL
4369** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004370const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004371{
4372 int h;
4373 x1node *np;
4374
4375 if( x1a==0 ) return 0;
4376 h = strhash(key) & (x1a->size-1);
4377 np = x1a->ht[h];
4378 while( np ){
4379 if( strcmp(np->data,key)==0 ) break;
4380 np = np->next;
4381 }
4382 return np ? np->data : 0;
4383}
4384
4385/* Return a pointer to the (terminal or nonterminal) symbol "x".
4386** Create a new symbol if this is the first time "x" has been seen.
4387*/
icculus9e44cf12010-02-14 17:14:22 +00004388struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004389{
4390 struct symbol *sp;
4391
4392 sp = Symbol_find(x);
4393 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004394 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004395 MemoryCheck(sp);
4396 sp->name = Strsafe(x);
4397 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4398 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004399 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004400 sp->prec = -1;
4401 sp->assoc = UNK;
4402 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004403 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004404 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004405 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004406 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004407 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004408 Symbol_insert(sp,sp->name);
4409 }
drhc4dd3fd2008-01-22 01:48:05 +00004410 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004411 return sp;
4412}
4413
drh60d31652004-02-22 00:08:04 +00004414/* Compare two symbols for working purposes
4415**
4416** Symbols that begin with upper case letters (terminals or tokens)
4417** must sort before symbols that begin with lower case letters
4418** (non-terminals). Other than that, the order does not matter.
4419**
4420** We find experimentally that leaving the symbols in their original
4421** order (the order they appeared in the grammar file) gives the
4422** smallest parser tables in SQLite.
4423*/
icculus9e44cf12010-02-14 17:14:22 +00004424int Symbolcmpp(const void *_a, const void *_b)
4425{
4426 const struct symbol **a = (const struct symbol **) _a;
4427 const struct symbol **b = (const struct symbol **) _b;
drh60d31652004-02-22 00:08:04 +00004428 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4429 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004430 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004431 return i1-i2;
drh75897232000-05-29 14:26:00 +00004432}
4433
4434/* There is one instance of the following structure for each
4435** associative array of type "x2".
4436*/
4437struct s_x2 {
4438 int size; /* The number of available slots. */
4439 /* Must be a power of 2 greater than or */
4440 /* equal to 1 */
4441 int count; /* Number of currently slots filled */
4442 struct s_x2node *tbl; /* The data stored here */
4443 struct s_x2node **ht; /* Hash table for lookups */
4444};
4445
4446/* There is one instance of this structure for every data element
4447** in an associative array of type "x2".
4448*/
4449typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004450 struct symbol *data; /* The data */
4451 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004452 struct s_x2node *next; /* Next entry with the same hash */
4453 struct s_x2node **from; /* Previous link */
4454} x2node;
4455
4456/* There is only one instance of the array, which is the following */
4457static struct s_x2 *x2a;
4458
4459/* Allocate a new associative array */
4460void Symbol_init(){
4461 if( x2a ) return;
4462 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4463 if( x2a ){
4464 x2a->size = 128;
4465 x2a->count = 0;
4466 x2a->tbl = (x2node*)malloc(
4467 (sizeof(x2node) + sizeof(x2node*))*128 );
4468 if( x2a->tbl==0 ){
4469 free(x2a);
4470 x2a = 0;
4471 }else{
4472 int i;
4473 x2a->ht = (x2node**)&(x2a->tbl[128]);
4474 for(i=0; i<128; i++) x2a->ht[i] = 0;
4475 }
4476 }
4477}
4478/* Insert a new record into the array. Return TRUE if successful.
4479** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004480int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004481{
4482 x2node *np;
4483 int h;
4484 int ph;
4485
4486 if( x2a==0 ) return 0;
4487 ph = strhash(key);
4488 h = ph & (x2a->size-1);
4489 np = x2a->ht[h];
4490 while( np ){
4491 if( strcmp(np->key,key)==0 ){
4492 /* An existing entry with the same key is found. */
4493 /* Fail because overwrite is not allows. */
4494 return 0;
4495 }
4496 np = np->next;
4497 }
4498 if( x2a->count>=x2a->size ){
4499 /* Need to make the hash table bigger */
4500 int i,size;
4501 struct s_x2 array;
4502 array.size = size = x2a->size*2;
4503 array.count = x2a->count;
4504 array.tbl = (x2node*)malloc(
4505 (sizeof(x2node) + sizeof(x2node*))*size );
4506 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4507 array.ht = (x2node**)&(array.tbl[size]);
4508 for(i=0; i<size; i++) array.ht[i] = 0;
4509 for(i=0; i<x2a->count; i++){
4510 x2node *oldnp, *newnp;
4511 oldnp = &(x2a->tbl[i]);
4512 h = strhash(oldnp->key) & (size-1);
4513 newnp = &(array.tbl[i]);
4514 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4515 newnp->next = array.ht[h];
4516 newnp->key = oldnp->key;
4517 newnp->data = oldnp->data;
4518 newnp->from = &(array.ht[h]);
4519 array.ht[h] = newnp;
4520 }
4521 free(x2a->tbl);
4522 *x2a = array;
4523 }
4524 /* Insert the new data */
4525 h = ph & (x2a->size-1);
4526 np = &(x2a->tbl[x2a->count++]);
4527 np->key = key;
4528 np->data = data;
4529 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4530 np->next = x2a->ht[h];
4531 x2a->ht[h] = np;
4532 np->from = &(x2a->ht[h]);
4533 return 1;
4534}
4535
4536/* Return a pointer to data assigned to the given key. Return NULL
4537** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004538struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004539{
4540 int h;
4541 x2node *np;
4542
4543 if( x2a==0 ) return 0;
4544 h = strhash(key) & (x2a->size-1);
4545 np = x2a->ht[h];
4546 while( np ){
4547 if( strcmp(np->key,key)==0 ) break;
4548 np = np->next;
4549 }
4550 return np ? np->data : 0;
4551}
4552
4553/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004554struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004555{
4556 struct symbol *data;
4557 if( x2a && n>0 && n<=x2a->count ){
4558 data = x2a->tbl[n-1].data;
4559 }else{
4560 data = 0;
4561 }
4562 return data;
4563}
4564
4565/* Return the size of the array */
4566int Symbol_count()
4567{
4568 return x2a ? x2a->count : 0;
4569}
4570
4571/* Return an array of pointers to all data in the table.
4572** The array is obtained from malloc. Return NULL if memory allocation
4573** problems, or if the array is empty. */
4574struct symbol **Symbol_arrayof()
4575{
4576 struct symbol **array;
4577 int i,size;
4578 if( x2a==0 ) return 0;
4579 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004580 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004581 if( array ){
4582 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4583 }
4584 return array;
4585}
4586
4587/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004588int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004589{
icculus9e44cf12010-02-14 17:14:22 +00004590 const struct config *a = (struct config *) _a;
4591 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004592 int x;
4593 x = a->rp->index - b->rp->index;
4594 if( x==0 ) x = a->dot - b->dot;
4595 return x;
4596}
4597
4598/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004599PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004600{
4601 int rc;
4602 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4603 rc = a->rp->index - b->rp->index;
4604 if( rc==0 ) rc = a->dot - b->dot;
4605 }
4606 if( rc==0 ){
4607 if( a ) rc = 1;
4608 if( b ) rc = -1;
4609 }
4610 return rc;
4611}
4612
4613/* Hash a state */
icculus9e44cf12010-02-14 17:14:22 +00004614PRIVATE int statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004615{
4616 int h=0;
4617 while( a ){
4618 h = h*571 + a->rp->index*37 + a->dot;
4619 a = a->bp;
4620 }
4621 return h;
4622}
4623
4624/* Allocate a new state structure */
4625struct state *State_new()
4626{
icculus9e44cf12010-02-14 17:14:22 +00004627 struct state *newstate;
4628 newstate = (struct state *)calloc(1, sizeof(struct state) );
4629 MemoryCheck(newstate);
4630 return newstate;
drh75897232000-05-29 14:26:00 +00004631}
4632
4633/* There is one instance of the following structure for each
4634** associative array of type "x3".
4635*/
4636struct s_x3 {
4637 int size; /* The number of available slots. */
4638 /* Must be a power of 2 greater than or */
4639 /* equal to 1 */
4640 int count; /* Number of currently slots filled */
4641 struct s_x3node *tbl; /* The data stored here */
4642 struct s_x3node **ht; /* Hash table for lookups */
4643};
4644
4645/* There is one instance of this structure for every data element
4646** in an associative array of type "x3".
4647*/
4648typedef struct s_x3node {
4649 struct state *data; /* The data */
4650 struct config *key; /* The key */
4651 struct s_x3node *next; /* Next entry with the same hash */
4652 struct s_x3node **from; /* Previous link */
4653} x3node;
4654
4655/* There is only one instance of the array, which is the following */
4656static struct s_x3 *x3a;
4657
4658/* Allocate a new associative array */
4659void State_init(){
4660 if( x3a ) return;
4661 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4662 if( x3a ){
4663 x3a->size = 128;
4664 x3a->count = 0;
4665 x3a->tbl = (x3node*)malloc(
4666 (sizeof(x3node) + sizeof(x3node*))*128 );
4667 if( x3a->tbl==0 ){
4668 free(x3a);
4669 x3a = 0;
4670 }else{
4671 int i;
4672 x3a->ht = (x3node**)&(x3a->tbl[128]);
4673 for(i=0; i<128; i++) x3a->ht[i] = 0;
4674 }
4675 }
4676}
4677/* Insert a new record into the array. Return TRUE if successful.
4678** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004679int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004680{
4681 x3node *np;
4682 int h;
4683 int ph;
4684
4685 if( x3a==0 ) return 0;
4686 ph = statehash(key);
4687 h = ph & (x3a->size-1);
4688 np = x3a->ht[h];
4689 while( np ){
4690 if( statecmp(np->key,key)==0 ){
4691 /* An existing entry with the same key is found. */
4692 /* Fail because overwrite is not allows. */
4693 return 0;
4694 }
4695 np = np->next;
4696 }
4697 if( x3a->count>=x3a->size ){
4698 /* Need to make the hash table bigger */
4699 int i,size;
4700 struct s_x3 array;
4701 array.size = size = x3a->size*2;
4702 array.count = x3a->count;
4703 array.tbl = (x3node*)malloc(
4704 (sizeof(x3node) + sizeof(x3node*))*size );
4705 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4706 array.ht = (x3node**)&(array.tbl[size]);
4707 for(i=0; i<size; i++) array.ht[i] = 0;
4708 for(i=0; i<x3a->count; i++){
4709 x3node *oldnp, *newnp;
4710 oldnp = &(x3a->tbl[i]);
4711 h = statehash(oldnp->key) & (size-1);
4712 newnp = &(array.tbl[i]);
4713 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4714 newnp->next = array.ht[h];
4715 newnp->key = oldnp->key;
4716 newnp->data = oldnp->data;
4717 newnp->from = &(array.ht[h]);
4718 array.ht[h] = newnp;
4719 }
4720 free(x3a->tbl);
4721 *x3a = array;
4722 }
4723 /* Insert the new data */
4724 h = ph & (x3a->size-1);
4725 np = &(x3a->tbl[x3a->count++]);
4726 np->key = key;
4727 np->data = data;
4728 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4729 np->next = x3a->ht[h];
4730 x3a->ht[h] = np;
4731 np->from = &(x3a->ht[h]);
4732 return 1;
4733}
4734
4735/* Return a pointer to data assigned to the given key. Return NULL
4736** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004737struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004738{
4739 int h;
4740 x3node *np;
4741
4742 if( x3a==0 ) return 0;
4743 h = statehash(key) & (x3a->size-1);
4744 np = x3a->ht[h];
4745 while( np ){
4746 if( statecmp(np->key,key)==0 ) break;
4747 np = np->next;
4748 }
4749 return np ? np->data : 0;
4750}
4751
4752/* Return an array of pointers to all data in the table.
4753** The array is obtained from malloc. Return NULL if memory allocation
4754** problems, or if the array is empty. */
4755struct state **State_arrayof()
4756{
4757 struct state **array;
4758 int i,size;
4759 if( x3a==0 ) return 0;
4760 size = x3a->count;
4761 array = (struct state **)malloc( sizeof(struct state *)*size );
4762 if( array ){
4763 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4764 }
4765 return array;
4766}
4767
4768/* Hash a configuration */
icculus9e44cf12010-02-14 17:14:22 +00004769PRIVATE int confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004770{
4771 int h=0;
4772 h = h*571 + a->rp->index*37 + a->dot;
4773 return h;
4774}
4775
4776/* There is one instance of the following structure for each
4777** associative array of type "x4".
4778*/
4779struct s_x4 {
4780 int size; /* The number of available slots. */
4781 /* Must be a power of 2 greater than or */
4782 /* equal to 1 */
4783 int count; /* Number of currently slots filled */
4784 struct s_x4node *tbl; /* The data stored here */
4785 struct s_x4node **ht; /* Hash table for lookups */
4786};
4787
4788/* There is one instance of this structure for every data element
4789** in an associative array of type "x4".
4790*/
4791typedef struct s_x4node {
4792 struct config *data; /* The data */
4793 struct s_x4node *next; /* Next entry with the same hash */
4794 struct s_x4node **from; /* Previous link */
4795} x4node;
4796
4797/* There is only one instance of the array, which is the following */
4798static struct s_x4 *x4a;
4799
4800/* Allocate a new associative array */
4801void Configtable_init(){
4802 if( x4a ) return;
4803 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4804 if( x4a ){
4805 x4a->size = 64;
4806 x4a->count = 0;
4807 x4a->tbl = (x4node*)malloc(
4808 (sizeof(x4node) + sizeof(x4node*))*64 );
4809 if( x4a->tbl==0 ){
4810 free(x4a);
4811 x4a = 0;
4812 }else{
4813 int i;
4814 x4a->ht = (x4node**)&(x4a->tbl[64]);
4815 for(i=0; i<64; i++) x4a->ht[i] = 0;
4816 }
4817 }
4818}
4819/* Insert a new record into the array. Return TRUE if successful.
4820** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004821int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00004822{
4823 x4node *np;
4824 int h;
4825 int ph;
4826
4827 if( x4a==0 ) return 0;
4828 ph = confighash(data);
4829 h = ph & (x4a->size-1);
4830 np = x4a->ht[h];
4831 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004832 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00004833 /* An existing entry with the same key is found. */
4834 /* Fail because overwrite is not allows. */
4835 return 0;
4836 }
4837 np = np->next;
4838 }
4839 if( x4a->count>=x4a->size ){
4840 /* Need to make the hash table bigger */
4841 int i,size;
4842 struct s_x4 array;
4843 array.size = size = x4a->size*2;
4844 array.count = x4a->count;
4845 array.tbl = (x4node*)malloc(
4846 (sizeof(x4node) + sizeof(x4node*))*size );
4847 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4848 array.ht = (x4node**)&(array.tbl[size]);
4849 for(i=0; i<size; i++) array.ht[i] = 0;
4850 for(i=0; i<x4a->count; i++){
4851 x4node *oldnp, *newnp;
4852 oldnp = &(x4a->tbl[i]);
4853 h = confighash(oldnp->data) & (size-1);
4854 newnp = &(array.tbl[i]);
4855 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4856 newnp->next = array.ht[h];
4857 newnp->data = oldnp->data;
4858 newnp->from = &(array.ht[h]);
4859 array.ht[h] = newnp;
4860 }
4861 free(x4a->tbl);
4862 *x4a = array;
4863 }
4864 /* Insert the new data */
4865 h = ph & (x4a->size-1);
4866 np = &(x4a->tbl[x4a->count++]);
4867 np->data = data;
4868 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4869 np->next = x4a->ht[h];
4870 x4a->ht[h] = np;
4871 np->from = &(x4a->ht[h]);
4872 return 1;
4873}
4874
4875/* Return a pointer to data assigned to the given key. Return NULL
4876** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004877struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004878{
4879 int h;
4880 x4node *np;
4881
4882 if( x4a==0 ) return 0;
4883 h = confighash(key) & (x4a->size-1);
4884 np = x4a->ht[h];
4885 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004886 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00004887 np = np->next;
4888 }
4889 return np ? np->data : 0;
4890}
4891
4892/* Remove all data from the table. Pass each data to the function "f"
4893** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00004894void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00004895{
4896 int i;
4897 if( x4a==0 || x4a->count==0 ) return;
4898 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4899 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4900 x4a->count = 0;
4901 return;
4902}