blob: 1fb0308bec6db2473879eb4da96b84366e19c22f [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__
drhdf609712010-11-23 20:55:27 +000023#ifdef __cplusplus
24extern "C" {
25#endif
26extern int access(const char *path, int mode);
27#ifdef __cplusplus
28}
29#endif
rse8f304482007-07-30 18:31:53 +000030#else
31#include <unistd.h>
32#endif
33
drh75897232000-05-29 14:26:00 +000034/* #define PRIVATE static */
35#define PRIVATE
36
37#ifdef TEST
38#define MAXRHS 5 /* Set low to exercise exception code */
39#else
40#define MAXRHS 1000
41#endif
42
drhf5c4e0f2010-07-18 11:35:53 +000043static int showPrecedenceConflict = 0;
drhe9278182007-07-18 18:16:29 +000044static char *msort(char*,char**,int(*)(const char*,const char*));
drh75897232000-05-29 14:26:00 +000045
drh87cf1372008-08-13 20:09:06 +000046/*
47** Compilers are getting increasingly pedantic about type conversions
48** as C evolves ever closer to Ada.... To work around the latest problems
49** we have to define the following variant of strlen().
50*/
51#define lemonStrlen(X) ((int)strlen(X))
52
icculus9e44cf12010-02-14 17:14:22 +000053/* a few forward declarations... */
54struct rule;
55struct lemon;
56struct action;
57
drhe9278182007-07-18 18:16:29 +000058static struct action *Action_new(void);
59static struct action *Action_sort(struct action *);
drh75897232000-05-29 14:26:00 +000060
61/********** From the file "build.h" ************************************/
62void FindRulePrecedences();
63void FindFirstSets();
64void FindStates();
65void FindLinks();
66void FindFollowSets();
67void FindActions();
68
69/********* From the file "configlist.h" *********************************/
icculus9e44cf12010-02-14 17:14:22 +000070void Configlist_init(void);
71struct config *Configlist_add(struct rule *, int);
72struct config *Configlist_addbasis(struct rule *, int);
73void Configlist_closure(struct lemon *);
74void Configlist_sort(void);
75void Configlist_sortbasis(void);
76struct config *Configlist_return(void);
77struct config *Configlist_basis(void);
78void Configlist_eat(struct config *);
79void Configlist_reset(void);
drh75897232000-05-29 14:26:00 +000080
81/********* From the file "error.h" ***************************************/
drhf9a2e7b2003-04-15 01:49:48 +000082void ErrorMsg(const char *, int,const char *, ...);
drh75897232000-05-29 14:26:00 +000083
84/****** From the file "option.h" ******************************************/
icculus9e44cf12010-02-14 17:14:22 +000085enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR,
86 OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR};
drh75897232000-05-29 14:26:00 +000087struct s_options {
icculus9e44cf12010-02-14 17:14:22 +000088 enum option_type type;
89 const char *label;
drh75897232000-05-29 14:26:00 +000090 char *arg;
icculus9e44cf12010-02-14 17:14:22 +000091 const char *message;
drh75897232000-05-29 14:26:00 +000092};
icculus9e44cf12010-02-14 17:14:22 +000093int OptInit(char**,struct s_options*,FILE*);
94int OptNArgs(void);
95char *OptArg(int);
96void OptErr(int);
97void OptPrint(void);
drh75897232000-05-29 14:26:00 +000098
99/******** From the file "parse.h" *****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000100void Parse(struct lemon *lemp);
drh75897232000-05-29 14:26:00 +0000101
102/********* From the file "plink.h" ***************************************/
icculus9e44cf12010-02-14 17:14:22 +0000103struct plink *Plink_new(void);
104void Plink_add(struct plink **, struct config *);
105void Plink_copy(struct plink **, struct plink *);
106void Plink_delete(struct plink *);
drh75897232000-05-29 14:26:00 +0000107
108/********** From the file "report.h" *************************************/
icculus9e44cf12010-02-14 17:14:22 +0000109void Reprint(struct lemon *);
110void ReportOutput(struct lemon *);
111void ReportTable(struct lemon *, int);
112void ReportHeader(struct lemon *);
113void CompressTables(struct lemon *);
114void ResortStates(struct lemon *);
drh75897232000-05-29 14:26:00 +0000115
116/********** From the file "set.h" ****************************************/
icculus9e44cf12010-02-14 17:14:22 +0000117void SetSize(int); /* All sets will be of size N */
118char *SetNew(void); /* A new set for element 0..N */
119void SetFree(char*); /* Deallocate a set */
drh75897232000-05-29 14:26:00 +0000120
icculus9e44cf12010-02-14 17:14:22 +0000121char *SetNew(void); /* A new set for element 0..N */
122int SetAdd(char*,int); /* Add element to a set */
123int SetUnion(char *,char *); /* A <- A U B, thru element N */
drh75897232000-05-29 14:26:00 +0000124#define SetFind(X,Y) (X[Y]) /* True if Y is in set X */
125
126/********** From the file "struct.h" *************************************/
127/*
128** Principal data structures for the LEMON parser generator.
129*/
130
drhaa9f1122007-08-23 02:50:56 +0000131typedef enum {LEMON_FALSE=0, LEMON_TRUE} Boolean;
drh75897232000-05-29 14:26:00 +0000132
133/* Symbols (terminals and nonterminals) of the grammar are stored
134** in the following: */
icculus9e44cf12010-02-14 17:14:22 +0000135enum symbol_type {
136 TERMINAL,
137 NONTERMINAL,
138 MULTITERMINAL
139};
140enum e_assoc {
drh75897232000-05-29 14:26:00 +0000141 LEFT,
142 RIGHT,
143 NONE,
144 UNK
icculus9e44cf12010-02-14 17:14:22 +0000145};
146struct symbol {
147 const char *name; /* Name of the symbol */
148 int index; /* Index number for this symbol */
149 enum symbol_type type; /* Symbols are all either TERMINALS or NTs */
150 struct rule *rule; /* Linked list of rules of this (if an NT) */
151 struct symbol *fallback; /* fallback token in case this token doesn't parse */
152 int prec; /* Precedence if defined (-1 otherwise) */
153 enum e_assoc assoc; /* Associativity if precedence is defined */
drh75897232000-05-29 14:26:00 +0000154 char *firstset; /* First-set for all rules of this symbol */
155 Boolean lambda; /* True if NT and can generate an empty string */
drhc4dd3fd2008-01-22 01:48:05 +0000156 int useCnt; /* Number of times used */
drh75897232000-05-29 14:26:00 +0000157 char *destructor; /* Code which executes whenever this symbol is
158 ** popped from the stack during error processing */
drh4dc8ef52008-07-01 17:13:57 +0000159 int destLineno; /* Line number for start of destructor */
drh75897232000-05-29 14:26:00 +0000160 char *datatype; /* The data type of information held by this
161 ** object. Only used if type==NONTERMINAL */
162 int dtnum; /* The data type number. In the parser, the value
163 ** stack is a union. The .yy%d element of this
164 ** union is the correct data type for this object */
drhfd405312005-11-06 04:06:59 +0000165 /* The following fields are used by MULTITERMINALs only */
166 int nsubsym; /* Number of constituent symbols in the MULTI */
167 struct symbol **subsym; /* Array of constituent symbols */
drh75897232000-05-29 14:26:00 +0000168};
169
170/* Each production rule in the grammar is stored in the following
171** structure. */
172struct rule {
173 struct symbol *lhs; /* Left-hand side of the rule */
icculus9e44cf12010-02-14 17:14:22 +0000174 const char *lhsalias; /* Alias for the LHS (NULL if none) */
drhb4960992007-10-05 16:16:36 +0000175 int lhsStart; /* True if left-hand side is the start symbol */
drh75897232000-05-29 14:26:00 +0000176 int ruleline; /* Line number for the rule */
177 int nrhs; /* Number of RHS symbols */
178 struct symbol **rhs; /* The RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +0000179 const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */
drh75897232000-05-29 14:26:00 +0000180 int line; /* Line number at which code begins */
icculus9e44cf12010-02-14 17:14:22 +0000181 const char *code; /* The code executed when this rule is reduced */
drh75897232000-05-29 14:26:00 +0000182 struct symbol *precsym; /* Precedence symbol for this rule */
183 int index; /* An index number for this rule */
184 Boolean canReduce; /* True if this rule is ever reduced */
185 struct rule *nextlhs; /* Next rule with the same LHS */
186 struct rule *next; /* Next rule in the global list */
187};
188
189/* A configuration is a production rule of the grammar together with
190** a mark (dot) showing how much of that rule has been processed so far.
191** Configurations also contain a follow-set which is a list of terminal
192** symbols which are allowed to immediately follow the end of the rule.
193** Every configuration is recorded as an instance of the following: */
icculus9e44cf12010-02-14 17:14:22 +0000194enum cfgstatus {
195 COMPLETE,
196 INCOMPLETE
197};
drh75897232000-05-29 14:26:00 +0000198struct config {
199 struct rule *rp; /* The rule upon which the configuration is based */
200 int dot; /* The parse point */
201 char *fws; /* Follow-set for this configuration only */
202 struct plink *fplp; /* Follow-set forward propagation links */
203 struct plink *bplp; /* Follow-set backwards propagation links */
204 struct state *stp; /* Pointer to state which contains this */
icculus9e44cf12010-02-14 17:14:22 +0000205 enum cfgstatus status; /* used during followset and shift computations */
drh75897232000-05-29 14:26:00 +0000206 struct config *next; /* Next configuration in the state */
207 struct config *bp; /* The next basis configuration */
208};
209
icculus9e44cf12010-02-14 17:14:22 +0000210enum e_action {
211 SHIFT,
212 ACCEPT,
213 REDUCE,
214 ERROR,
215 SSCONFLICT, /* A shift/shift conflict */
216 SRCONFLICT, /* Was a reduce, but part of a conflict */
217 RRCONFLICT, /* Was a reduce, but part of a conflict */
218 SH_RESOLVED, /* Was a shift. Precedence resolved conflict */
219 RD_RESOLVED, /* Was reduce. Precedence resolved conflict */
220 NOT_USED /* Deleted by compression */
221};
222
drh75897232000-05-29 14:26:00 +0000223/* Every shift or reduce operation is stored as one of the following */
224struct action {
225 struct symbol *sp; /* The look-ahead symbol */
icculus9e44cf12010-02-14 17:14:22 +0000226 enum e_action type;
drh75897232000-05-29 14:26:00 +0000227 union {
228 struct state *stp; /* The new state, if a shift */
229 struct rule *rp; /* The rule, if a reduce */
230 } x;
231 struct action *next; /* Next action for this state */
232 struct action *collide; /* Next action with the same hash */
233};
234
235/* Each state of the generated parser's finite state machine
236** is encoded as an instance of the following structure. */
237struct state {
238 struct config *bp; /* The basis configurations for this state */
239 struct config *cfp; /* All configurations in this set */
drh34ff57b2008-07-14 12:27:51 +0000240 int statenum; /* Sequential number for this state */
drh75897232000-05-29 14:26:00 +0000241 struct action *ap; /* Array of actions for this state */
drh8b582012003-10-21 13:16:03 +0000242 int nTknAct, nNtAct; /* Number of actions on terminals and nonterminals */
243 int iTknOfst, iNtOfst; /* yy_action[] offset for terminals and nonterms */
244 int iDflt; /* Default action */
drh75897232000-05-29 14:26:00 +0000245};
drh8b582012003-10-21 13:16:03 +0000246#define NO_OFFSET (-2147483647)
drh75897232000-05-29 14:26:00 +0000247
248/* A followset propagation link indicates that the contents of one
249** configuration followset should be propagated to another whenever
250** the first changes. */
251struct plink {
252 struct config *cfp; /* The configuration to which linked */
253 struct plink *next; /* The next propagate link */
254};
255
256/* The state vector for the entire parser generator is recorded as
257** follows. (LEMON uses no global variables and makes little use of
258** static variables. Fields in the following structure can be thought
259** of as begin global variables in the program.) */
260struct lemon {
261 struct state **sorted; /* Table of states sorted by state number */
262 struct rule *rule; /* List of all rules */
263 int nstate; /* Number of states */
264 int nrule; /* Number of rules */
265 int nsymbol; /* Number of terminal and nonterminal symbols */
266 int nterminal; /* Number of terminal symbols */
267 struct symbol **symbols; /* Sorted array of pointers to symbols */
268 int errorcnt; /* Number of errors */
269 struct symbol *errsym; /* The error symbol */
drhe09daa92006-06-10 13:29:31 +0000270 struct symbol *wildcard; /* Token that matches anything */
drh75897232000-05-29 14:26:00 +0000271 char *name; /* Name of the generated parser */
272 char *arg; /* Declaration of the 3th argument to parser */
273 char *tokentype; /* Type of terminal symbols in the parser stack */
drh960e8c62001-04-03 16:53:21 +0000274 char *vartype; /* The default type of non-terminal symbols */
drh75897232000-05-29 14:26:00 +0000275 char *start; /* Name of the start symbol for the grammar */
276 char *stacksize; /* Size of the parser stack */
277 char *include; /* Code to put at the start of the C file */
drh75897232000-05-29 14:26:00 +0000278 char *error; /* Code to execute when an error is seen */
drh75897232000-05-29 14:26:00 +0000279 char *overflow; /* Code to execute on a stack overflow */
drh75897232000-05-29 14:26:00 +0000280 char *failure; /* Code to execute on parser failure */
drh75897232000-05-29 14:26:00 +0000281 char *accept; /* Code to execute when the parser excepts */
drh75897232000-05-29 14:26:00 +0000282 char *extracode; /* Code appended to the generated file */
drh75897232000-05-29 14:26:00 +0000283 char *tokendest; /* Code to execute to destroy token data */
drh960e8c62001-04-03 16:53:21 +0000284 char *vardest; /* Code for the default non-terminal destructor */
drh75897232000-05-29 14:26:00 +0000285 char *filename; /* Name of the input file */
286 char *outname; /* Name of the current output file */
287 char *tokenprefix; /* A prefix added to token names in the .h file */
288 int nconflict; /* Number of parsing conflicts */
289 int tablesize; /* Size of the parse tables */
290 int basisflag; /* Print only basis configurations */
drh34ff57b2008-07-14 12:27:51 +0000291 int has_fallback; /* True if any %fallback is seen in the grammar */
shane58543932008-12-10 20:10:04 +0000292 int nolinenosflag; /* True if #line statements should not be printed */
drh75897232000-05-29 14:26:00 +0000293 char *argv0; /* Name of the program */
294};
295
296#define MemoryCheck(X) if((X)==0){ \
297 extern void memory_error(); \
298 memory_error(); \
299}
300
301/**************** From the file "table.h" *********************************/
302/*
303** All code in this file has been automatically generated
304** from a specification in the file
305** "table.q"
306** by the associative array code building program "aagen".
307** Do not edit this file! Instead, edit the specification
308** file, then rerun aagen.
309*/
310/*
311** Code for processing tables in the LEMON parser generator.
312*/
drh75897232000-05-29 14:26:00 +0000313/* Routines for handling a strings */
314
icculus9e44cf12010-02-14 17:14:22 +0000315const char *Strsafe(const char *);
drh75897232000-05-29 14:26:00 +0000316
icculus9e44cf12010-02-14 17:14:22 +0000317void Strsafe_init(void);
318int Strsafe_insert(const char *);
319const char *Strsafe_find(const char *);
drh75897232000-05-29 14:26:00 +0000320
321/* Routines for handling symbols of the grammar */
322
icculus9e44cf12010-02-14 17:14:22 +0000323struct symbol *Symbol_new(const char *);
324int Symbolcmpp(const void *, const void *);
325void Symbol_init(void);
326int Symbol_insert(struct symbol *, const char *);
327struct symbol *Symbol_find(const char *);
328struct symbol *Symbol_Nth(int);
329int Symbol_count(void);
330struct symbol **Symbol_arrayof(void);
drh75897232000-05-29 14:26:00 +0000331
332/* Routines to manage the state table */
333
icculus9e44cf12010-02-14 17:14:22 +0000334int Configcmp(const char *, const char *);
335struct state *State_new(void);
336void State_init(void);
337int State_insert(struct state *, struct config *);
338struct state *State_find(struct config *);
drh75897232000-05-29 14:26:00 +0000339struct state **State_arrayof(/* */);
340
341/* Routines used for efficiency in Configlist_add */
342
icculus9e44cf12010-02-14 17:14:22 +0000343void Configtable_init(void);
344int Configtable_insert(struct config *);
345struct config *Configtable_find(struct config *);
346void Configtable_clear(int(*)(struct config *));
347
drh75897232000-05-29 14:26:00 +0000348/****************** From the file "action.c" *******************************/
349/*
350** Routines processing parser actions in the LEMON parser generator.
351*/
352
353/* Allocate a new parser action */
drhe9278182007-07-18 18:16:29 +0000354static struct action *Action_new(void){
drh75897232000-05-29 14:26:00 +0000355 static struct action *freelist = 0;
icculus9e44cf12010-02-14 17:14:22 +0000356 struct action *newaction;
drh75897232000-05-29 14:26:00 +0000357
358 if( freelist==0 ){
359 int i;
360 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +0000361 freelist = (struct action *)calloc(amt, sizeof(struct action));
drh75897232000-05-29 14:26:00 +0000362 if( freelist==0 ){
363 fprintf(stderr,"Unable to allocate memory for a new parser action.");
364 exit(1);
365 }
366 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
367 freelist[amt-1].next = 0;
368 }
icculus9e44cf12010-02-14 17:14:22 +0000369 newaction = freelist;
drh75897232000-05-29 14:26:00 +0000370 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +0000371 return newaction;
drh75897232000-05-29 14:26:00 +0000372}
373
drhe9278182007-07-18 18:16:29 +0000374/* Compare two actions for sorting purposes. Return negative, zero, or
375** positive if the first action is less than, equal to, or greater than
376** the first
377*/
378static int actioncmp(
379 struct action *ap1,
380 struct action *ap2
381){
drh75897232000-05-29 14:26:00 +0000382 int rc;
383 rc = ap1->sp->index - ap2->sp->index;
drh75897232000-05-29 14:26:00 +0000384 if( rc==0 ){
drh9892c5d2007-12-21 00:02:11 +0000385 rc = (int)ap1->type - (int)ap2->type;
386 }
387 if( rc==0 && ap1->type==REDUCE ){
drh75897232000-05-29 14:26:00 +0000388 rc = ap1->x.rp->index - ap2->x.rp->index;
389 }
drhe594bc32009-11-03 13:02:25 +0000390 if( rc==0 ){
icculus7b429aa2010-03-03 17:09:01 +0000391 rc = (int) (ap2 - ap1);
drhe594bc32009-11-03 13:02:25 +0000392 }
drh75897232000-05-29 14:26:00 +0000393 return rc;
394}
395
396/* Sort parser actions */
drhe9278182007-07-18 18:16:29 +0000397static struct action *Action_sort(
398 struct action *ap
399){
400 ap = (struct action *)msort((char *)ap,(char **)&ap->next,
401 (int(*)(const char*,const char*))actioncmp);
drh75897232000-05-29 14:26:00 +0000402 return ap;
403}
404
icculus9e44cf12010-02-14 17:14:22 +0000405void Action_add(
406 struct action **app,
407 enum e_action type,
408 struct symbol *sp,
409 char *arg
410){
411 struct action *newaction;
412 newaction = Action_new();
413 newaction->next = *app;
414 *app = newaction;
415 newaction->type = type;
416 newaction->sp = sp;
drh75897232000-05-29 14:26:00 +0000417 if( type==SHIFT ){
icculus9e44cf12010-02-14 17:14:22 +0000418 newaction->x.stp = (struct state *)arg;
drh75897232000-05-29 14:26:00 +0000419 }else{
icculus9e44cf12010-02-14 17:14:22 +0000420 newaction->x.rp = (struct rule *)arg;
drh75897232000-05-29 14:26:00 +0000421 }
422}
drh8b582012003-10-21 13:16:03 +0000423/********************** New code to implement the "acttab" module ***********/
424/*
425** This module implements routines use to construct the yy_action[] table.
426*/
427
428/*
429** The state of the yy_action table under construction is an instance of
drh8dc3e8f2010-01-07 03:53:03 +0000430** the following structure.
431**
432** The yy_action table maps the pair (state_number, lookahead) into an
433** action_number. The table is an array of integers pairs. The state_number
434** determines an initial offset into the yy_action array. The lookahead
435** value is then added to this initial offset to get an index X into the
436** yy_action array. If the aAction[X].lookahead equals the value of the
437** of the lookahead input, then the value of the action_number output is
438** aAction[X].action. If the lookaheads do not match then the
439** default action for the state_number is returned.
440**
441** All actions associated with a single state_number are first entered
442** into aLookahead[] using multiple calls to acttab_action(). Then the
443** actions for that single state_number are placed into the aAction[]
444** array with a single call to acttab_insert(). The acttab_insert() call
445** also resets the aLookahead[] array in preparation for the next
446** state number.
drh8b582012003-10-21 13:16:03 +0000447*/
icculus9e44cf12010-02-14 17:14:22 +0000448struct lookahead_action {
449 int lookahead; /* Value of the lookahead token */
450 int action; /* Action to take on the given lookahead */
451};
drh8b582012003-10-21 13:16:03 +0000452typedef struct acttab acttab;
453struct acttab {
454 int nAction; /* Number of used slots in aAction[] */
455 int nActionAlloc; /* Slots allocated for aAction[] */
icculus9e44cf12010-02-14 17:14:22 +0000456 struct lookahead_action
457 *aAction, /* The yy_action[] table under construction */
drh8b582012003-10-21 13:16:03 +0000458 *aLookahead; /* A single new transaction set */
459 int mnLookahead; /* Minimum aLookahead[].lookahead */
460 int mnAction; /* Action associated with mnLookahead */
461 int mxLookahead; /* Maximum aLookahead[].lookahead */
462 int nLookahead; /* Used slots in aLookahead[] */
463 int nLookaheadAlloc; /* Slots allocated in aLookahead[] */
464};
465
466/* Return the number of entries in the yy_action table */
467#define acttab_size(X) ((X)->nAction)
468
469/* The value for the N-th entry in yy_action */
470#define acttab_yyaction(X,N) ((X)->aAction[N].action)
471
472/* The value for the N-th entry in yy_lookahead */
473#define acttab_yylookahead(X,N) ((X)->aAction[N].lookahead)
474
475/* Free all memory associated with the given acttab */
476void acttab_free(acttab *p){
477 free( p->aAction );
478 free( p->aLookahead );
479 free( p );
480}
481
482/* Allocate a new acttab structure */
483acttab *acttab_alloc(void){
icculus9e44cf12010-02-14 17:14:22 +0000484 acttab *p = (acttab *) calloc( 1, sizeof(*p) );
drh8b582012003-10-21 13:16:03 +0000485 if( p==0 ){
486 fprintf(stderr,"Unable to allocate memory for a new acttab.");
487 exit(1);
488 }
489 memset(p, 0, sizeof(*p));
490 return p;
491}
492
drh8dc3e8f2010-01-07 03:53:03 +0000493/* Add a new action to the current transaction set.
494**
495** This routine is called once for each lookahead for a particular
496** state.
drh8b582012003-10-21 13:16:03 +0000497*/
498void acttab_action(acttab *p, int lookahead, int action){
499 if( p->nLookahead>=p->nLookaheadAlloc ){
500 p->nLookaheadAlloc += 25;
icculus9e44cf12010-02-14 17:14:22 +0000501 p->aLookahead = (struct lookahead_action *) realloc( p->aLookahead,
drh8b582012003-10-21 13:16:03 +0000502 sizeof(p->aLookahead[0])*p->nLookaheadAlloc );
503 if( p->aLookahead==0 ){
504 fprintf(stderr,"malloc failed\n");
505 exit(1);
506 }
507 }
508 if( p->nLookahead==0 ){
509 p->mxLookahead = lookahead;
510 p->mnLookahead = lookahead;
511 p->mnAction = action;
512 }else{
513 if( p->mxLookahead<lookahead ) p->mxLookahead = lookahead;
514 if( p->mnLookahead>lookahead ){
515 p->mnLookahead = lookahead;
516 p->mnAction = action;
517 }
518 }
519 p->aLookahead[p->nLookahead].lookahead = lookahead;
520 p->aLookahead[p->nLookahead].action = action;
521 p->nLookahead++;
522}
523
524/*
525** Add the transaction set built up with prior calls to acttab_action()
526** into the current action table. Then reset the transaction set back
527** to an empty set in preparation for a new round of acttab_action() calls.
528**
529** Return the offset into the action table of the new transaction.
530*/
531int acttab_insert(acttab *p){
532 int i, j, k, n;
533 assert( p->nLookahead>0 );
534
535 /* Make sure we have enough space to hold the expanded action table
536 ** in the worst case. The worst case occurs if the transaction set
537 ** must be appended to the current action table
538 */
drh784d86f2004-02-19 18:41:53 +0000539 n = p->mxLookahead + 1;
drh8dc3e8f2010-01-07 03:53:03 +0000540 if( p->nAction + n >= p->nActionAlloc ){
drhfdbf9282003-10-21 16:34:41 +0000541 int oldAlloc = p->nActionAlloc;
drh8b582012003-10-21 13:16:03 +0000542 p->nActionAlloc = p->nAction + n + p->nActionAlloc + 20;
icculus9e44cf12010-02-14 17:14:22 +0000543 p->aAction = (struct lookahead_action *) realloc( p->aAction,
drh8b582012003-10-21 13:16:03 +0000544 sizeof(p->aAction[0])*p->nActionAlloc);
545 if( p->aAction==0 ){
546 fprintf(stderr,"malloc failed\n");
547 exit(1);
548 }
drhfdbf9282003-10-21 16:34:41 +0000549 for(i=oldAlloc; i<p->nActionAlloc; i++){
drh8b582012003-10-21 13:16:03 +0000550 p->aAction[i].lookahead = -1;
551 p->aAction[i].action = -1;
552 }
553 }
554
drh8dc3e8f2010-01-07 03:53:03 +0000555 /* Scan the existing action table looking for an offset that is a
556 ** duplicate of the current transaction set. Fall out of the loop
557 ** if and when the duplicate is found.
drh8b582012003-10-21 13:16:03 +0000558 **
559 ** i is the index in p->aAction[] where p->mnLookahead is inserted.
560 */
drh8dc3e8f2010-01-07 03:53:03 +0000561 for(i=p->nAction-1; i>=0; i--){
drhf16371d2009-11-03 19:18:31 +0000562 if( p->aAction[i].lookahead==p->mnLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000563 /* All lookaheads and actions in the aLookahead[] transaction
564 ** must match against the candidate aAction[i] entry. */
drh8b582012003-10-21 13:16:03 +0000565 if( p->aAction[i].action!=p->mnAction ) continue;
566 for(j=0; j<p->nLookahead; j++){
567 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
568 if( k<0 || k>=p->nAction ) break;
569 if( p->aLookahead[j].lookahead!=p->aAction[k].lookahead ) break;
570 if( p->aLookahead[j].action!=p->aAction[k].action ) break;
571 }
572 if( j<p->nLookahead ) continue;
drh8dc3e8f2010-01-07 03:53:03 +0000573
574 /* No possible lookahead value that is not in the aLookahead[]
575 ** transaction is allowed to match aAction[i] */
drh8b582012003-10-21 13:16:03 +0000576 n = 0;
577 for(j=0; j<p->nAction; j++){
drhfdbf9282003-10-21 16:34:41 +0000578 if( p->aAction[j].lookahead<0 ) continue;
579 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) n++;
drh8b582012003-10-21 13:16:03 +0000580 }
drhfdbf9282003-10-21 16:34:41 +0000581 if( n==p->nLookahead ){
drh8dc3e8f2010-01-07 03:53:03 +0000582 break; /* An exact match is found at offset i */
drhfdbf9282003-10-21 16:34:41 +0000583 }
drh8b582012003-10-21 13:16:03 +0000584 }
585 }
drh8dc3e8f2010-01-07 03:53:03 +0000586
587 /* If no existing offsets exactly match the current transaction, find an
588 ** an empty offset in the aAction[] table in which we can add the
589 ** aLookahead[] transaction.
590 */
drhf16371d2009-11-03 19:18:31 +0000591 if( i<0 ){
drh8dc3e8f2010-01-07 03:53:03 +0000592 /* Look for holes in the aAction[] table that fit the current
593 ** aLookahead[] transaction. Leave i set to the offset of the hole.
594 ** If no holes are found, i is left at p->nAction, which means the
595 ** transaction will be appended. */
596 for(i=0; i<p->nActionAlloc - p->mxLookahead; i++){
drhf16371d2009-11-03 19:18:31 +0000597 if( p->aAction[i].lookahead<0 ){
598 for(j=0; j<p->nLookahead; j++){
599 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
600 if( k<0 ) break;
601 if( p->aAction[k].lookahead>=0 ) break;
602 }
603 if( j<p->nLookahead ) continue;
604 for(j=0; j<p->nAction; j++){
605 if( p->aAction[j].lookahead==j+p->mnLookahead-i ) break;
606 }
607 if( j==p->nAction ){
608 break; /* Fits in empty slots */
609 }
610 }
611 }
612 }
drh8b582012003-10-21 13:16:03 +0000613 /* Insert transaction set at index i. */
614 for(j=0; j<p->nLookahead; j++){
615 k = p->aLookahead[j].lookahead - p->mnLookahead + i;
616 p->aAction[k] = p->aLookahead[j];
617 if( k>=p->nAction ) p->nAction = k+1;
618 }
619 p->nLookahead = 0;
620
621 /* Return the offset that is added to the lookahead in order to get the
622 ** index into yy_action of the action */
623 return i - p->mnLookahead;
624}
625
drh75897232000-05-29 14:26:00 +0000626/********************** From the file "build.c" *****************************/
627/*
628** Routines to construction the finite state machine for the LEMON
629** parser generator.
630*/
631
632/* Find a precedence symbol of every rule in the grammar.
633**
634** Those rules which have a precedence symbol coded in the input
635** grammar using the "[symbol]" construct will already have the
636** rp->precsym field filled. Other rules take as their precedence
637** symbol the first RHS symbol with a defined precedence. If there
638** are not RHS symbols with a defined precedence, the precedence
639** symbol field is left blank.
640*/
icculus9e44cf12010-02-14 17:14:22 +0000641void FindRulePrecedences(struct lemon *xp)
drh75897232000-05-29 14:26:00 +0000642{
643 struct rule *rp;
644 for(rp=xp->rule; rp; rp=rp->next){
645 if( rp->precsym==0 ){
drhfd405312005-11-06 04:06:59 +0000646 int i, j;
647 for(i=0; i<rp->nrhs && rp->precsym==0; i++){
648 struct symbol *sp = rp->rhs[i];
649 if( sp->type==MULTITERMINAL ){
650 for(j=0; j<sp->nsubsym; j++){
651 if( sp->subsym[j]->prec>=0 ){
652 rp->precsym = sp->subsym[j];
653 break;
654 }
655 }
656 }else if( sp->prec>=0 ){
drh75897232000-05-29 14:26:00 +0000657 rp->precsym = rp->rhs[i];
drh75897232000-05-29 14:26:00 +0000658 }
659 }
660 }
661 }
662 return;
663}
664
665/* Find all nonterminals which will generate the empty string.
666** Then go back and compute the first sets of every nonterminal.
667** The first set is the set of all terminal symbols which can begin
668** a string generated by that nonterminal.
669*/
icculus9e44cf12010-02-14 17:14:22 +0000670void FindFirstSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000671{
drhfd405312005-11-06 04:06:59 +0000672 int i, j;
drh75897232000-05-29 14:26:00 +0000673 struct rule *rp;
674 int progress;
675
676 for(i=0; i<lemp->nsymbol; i++){
drhaa9f1122007-08-23 02:50:56 +0000677 lemp->symbols[i]->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +0000678 }
679 for(i=lemp->nterminal; i<lemp->nsymbol; i++){
680 lemp->symbols[i]->firstset = SetNew();
681 }
682
683 /* First compute all lambdas */
684 do{
685 progress = 0;
686 for(rp=lemp->rule; rp; rp=rp->next){
687 if( rp->lhs->lambda ) continue;
688 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000689 struct symbol *sp = rp->rhs[i];
drhaa9f1122007-08-23 02:50:56 +0000690 if( sp->type!=TERMINAL || sp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000691 }
692 if( i==rp->nrhs ){
drhaa9f1122007-08-23 02:50:56 +0000693 rp->lhs->lambda = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +0000694 progress = 1;
695 }
696 }
697 }while( progress );
698
699 /* Now compute all first sets */
700 do{
701 struct symbol *s1, *s2;
702 progress = 0;
703 for(rp=lemp->rule; rp; rp=rp->next){
704 s1 = rp->lhs;
705 for(i=0; i<rp->nrhs; i++){
706 s2 = rp->rhs[i];
707 if( s2->type==TERMINAL ){
708 progress += SetAdd(s1->firstset,s2->index);
709 break;
drhfd405312005-11-06 04:06:59 +0000710 }else if( s2->type==MULTITERMINAL ){
711 for(j=0; j<s2->nsubsym; j++){
712 progress += SetAdd(s1->firstset,s2->subsym[j]->index);
713 }
714 break;
drh75897232000-05-29 14:26:00 +0000715 }else if( s1==s2 ){
drhaa9f1122007-08-23 02:50:56 +0000716 if( s1->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000717 }else{
718 progress += SetUnion(s1->firstset,s2->firstset);
drhaa9f1122007-08-23 02:50:56 +0000719 if( s2->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +0000720 }
721 }
722 }
723 }while( progress );
724 return;
725}
726
727/* Compute all LR(0) states for the grammar. Links
728** are added to between some states so that the LR(1) follow sets
729** can be computed later.
730*/
icculus9e44cf12010-02-14 17:14:22 +0000731PRIVATE struct state *getstate(struct lemon *); /* forward reference */
732void FindStates(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000733{
734 struct symbol *sp;
735 struct rule *rp;
736
737 Configlist_init();
738
739 /* Find the start symbol */
740 if( lemp->start ){
741 sp = Symbol_find(lemp->start);
742 if( sp==0 ){
743 ErrorMsg(lemp->filename,0,
744"The specified start symbol \"%s\" is not \
745in a nonterminal of the grammar. \"%s\" will be used as the start \
746symbol instead.",lemp->start,lemp->rule->lhs->name);
747 lemp->errorcnt++;
748 sp = lemp->rule->lhs;
749 }
750 }else{
751 sp = lemp->rule->lhs;
752 }
753
754 /* Make sure the start symbol doesn't occur on the right-hand side of
755 ** any rule. Report an error if it does. (YACC would generate a new
756 ** start symbol in this case.) */
757 for(rp=lemp->rule; rp; rp=rp->next){
758 int i;
759 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +0000760 if( rp->rhs[i]==sp ){ /* FIX ME: Deal with multiterminals */
drh75897232000-05-29 14:26:00 +0000761 ErrorMsg(lemp->filename,0,
762"The start symbol \"%s\" occurs on the \
763right-hand side of a rule. This will result in a parser which \
764does not work properly.",sp->name);
765 lemp->errorcnt++;
766 }
767 }
768 }
769
770 /* The basis configuration set for the first state
771 ** is all rules which have the start symbol as their
772 ** left-hand side */
773 for(rp=sp->rule; rp; rp=rp->nextlhs){
774 struct config *newcfp;
drhb4960992007-10-05 16:16:36 +0000775 rp->lhsStart = 1;
drh75897232000-05-29 14:26:00 +0000776 newcfp = Configlist_addbasis(rp,0);
777 SetAdd(newcfp->fws,0);
778 }
779
780 /* Compute the first state. All other states will be
781 ** computed automatically during the computation of the first one.
782 ** The returned pointer to the first state is not used. */
783 (void)getstate(lemp);
784 return;
785}
786
787/* Return a pointer to a state which is described by the configuration
788** list which has been built from calls to Configlist_add.
789*/
icculus9e44cf12010-02-14 17:14:22 +0000790PRIVATE void buildshifts(struct lemon *, struct state *); /* Forwd ref */
791PRIVATE struct state *getstate(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000792{
793 struct config *cfp, *bp;
794 struct state *stp;
795
796 /* Extract the sorted basis of the new state. The basis was constructed
797 ** by prior calls to "Configlist_addbasis()". */
798 Configlist_sortbasis();
799 bp = Configlist_basis();
800
801 /* Get a state with the same basis */
802 stp = State_find(bp);
803 if( stp ){
804 /* A state with the same basis already exists! Copy all the follow-set
805 ** propagation links from the state under construction into the
806 ** preexisting state, then return a pointer to the preexisting state */
807 struct config *x, *y;
808 for(x=bp, y=stp->bp; x && y; x=x->bp, y=y->bp){
809 Plink_copy(&y->bplp,x->bplp);
810 Plink_delete(x->fplp);
811 x->fplp = x->bplp = 0;
812 }
813 cfp = Configlist_return();
814 Configlist_eat(cfp);
815 }else{
816 /* This really is a new state. Construct all the details */
817 Configlist_closure(lemp); /* Compute the configuration closure */
818 Configlist_sort(); /* Sort the configuration closure */
819 cfp = Configlist_return(); /* Get a pointer to the config list */
820 stp = State_new(); /* A new state structure */
821 MemoryCheck(stp);
822 stp->bp = bp; /* Remember the configuration basis */
823 stp->cfp = cfp; /* Remember the configuration closure */
drhada354d2005-11-05 15:03:59 +0000824 stp->statenum = lemp->nstate++; /* Every state gets a sequence number */
drh75897232000-05-29 14:26:00 +0000825 stp->ap = 0; /* No actions, yet. */
826 State_insert(stp,stp->bp); /* Add to the state table */
827 buildshifts(lemp,stp); /* Recursively compute successor states */
828 }
829 return stp;
830}
831
drhfd405312005-11-06 04:06:59 +0000832/*
833** Return true if two symbols are the same.
834*/
icculus9e44cf12010-02-14 17:14:22 +0000835int same_symbol(struct symbol *a, struct symbol *b)
drhfd405312005-11-06 04:06:59 +0000836{
837 int i;
838 if( a==b ) return 1;
839 if( a->type!=MULTITERMINAL ) return 0;
840 if( b->type!=MULTITERMINAL ) return 0;
841 if( a->nsubsym!=b->nsubsym ) return 0;
842 for(i=0; i<a->nsubsym; i++){
843 if( a->subsym[i]!=b->subsym[i] ) return 0;
844 }
845 return 1;
846}
847
drh75897232000-05-29 14:26:00 +0000848/* Construct all successor states to the given state. A "successor"
849** state is any state which can be reached by a shift action.
850*/
icculus9e44cf12010-02-14 17:14:22 +0000851PRIVATE void buildshifts(struct lemon *lemp, struct state *stp)
drh75897232000-05-29 14:26:00 +0000852{
853 struct config *cfp; /* For looping thru the config closure of "stp" */
854 struct config *bcfp; /* For the inner loop on config closure of "stp" */
icculus9e44cf12010-02-14 17:14:22 +0000855 struct config *newcfg; /* */
drh75897232000-05-29 14:26:00 +0000856 struct symbol *sp; /* Symbol following the dot in configuration "cfp" */
857 struct symbol *bsp; /* Symbol following the dot in configuration "bcfp" */
858 struct state *newstp; /* A pointer to a successor state */
859
860 /* Each configuration becomes complete after it contibutes to a successor
861 ** state. Initially, all configurations are incomplete */
862 for(cfp=stp->cfp; cfp; cfp=cfp->next) cfp->status = INCOMPLETE;
863
864 /* Loop through all configurations of the state "stp" */
865 for(cfp=stp->cfp; cfp; cfp=cfp->next){
866 if( cfp->status==COMPLETE ) continue; /* Already used by inner loop */
867 if( cfp->dot>=cfp->rp->nrhs ) continue; /* Can't shift this config */
868 Configlist_reset(); /* Reset the new config set */
869 sp = cfp->rp->rhs[cfp->dot]; /* Symbol after the dot */
870
871 /* For every configuration in the state "stp" which has the symbol "sp"
872 ** following its dot, add the same configuration to the basis set under
873 ** construction but with the dot shifted one symbol to the right. */
874 for(bcfp=cfp; bcfp; bcfp=bcfp->next){
875 if( bcfp->status==COMPLETE ) continue; /* Already used */
876 if( bcfp->dot>=bcfp->rp->nrhs ) continue; /* Can't shift this one */
877 bsp = bcfp->rp->rhs[bcfp->dot]; /* Get symbol after dot */
drhfd405312005-11-06 04:06:59 +0000878 if( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */
drh75897232000-05-29 14:26:00 +0000879 bcfp->status = COMPLETE; /* Mark this config as used */
icculus9e44cf12010-02-14 17:14:22 +0000880 newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1);
881 Plink_add(&newcfg->bplp,bcfp);
drh75897232000-05-29 14:26:00 +0000882 }
883
884 /* Get a pointer to the state described by the basis configuration set
885 ** constructed in the preceding loop */
886 newstp = getstate(lemp);
887
888 /* The state "newstp" is reached from the state "stp" by a shift action
889 ** on the symbol "sp" */
drhfd405312005-11-06 04:06:59 +0000890 if( sp->type==MULTITERMINAL ){
891 int i;
892 for(i=0; i<sp->nsubsym; i++){
893 Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp);
894 }
895 }else{
896 Action_add(&stp->ap,SHIFT,sp,(char *)newstp);
897 }
drh75897232000-05-29 14:26:00 +0000898 }
899}
900
901/*
902** Construct the propagation links
903*/
icculus9e44cf12010-02-14 17:14:22 +0000904void FindLinks(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000905{
906 int i;
907 struct config *cfp, *other;
908 struct state *stp;
909 struct plink *plp;
910
911 /* Housekeeping detail:
912 ** Add to every propagate link a pointer back to the state to
913 ** which the link is attached. */
914 for(i=0; i<lemp->nstate; i++){
915 stp = lemp->sorted[i];
916 for(cfp=stp->cfp; cfp; cfp=cfp->next){
917 cfp->stp = stp;
918 }
919 }
920
921 /* Convert all backlinks into forward links. Only the forward
922 ** links are used in the follow-set computation. */
923 for(i=0; i<lemp->nstate; i++){
924 stp = lemp->sorted[i];
925 for(cfp=stp->cfp; cfp; cfp=cfp->next){
926 for(plp=cfp->bplp; plp; plp=plp->next){
927 other = plp->cfp;
928 Plink_add(&other->fplp,cfp);
929 }
930 }
931 }
932}
933
934/* Compute all followsets.
935**
936** A followset is the set of all symbols which can come immediately
937** after a configuration.
938*/
icculus9e44cf12010-02-14 17:14:22 +0000939void FindFollowSets(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000940{
941 int i;
942 struct config *cfp;
943 struct plink *plp;
944 int progress;
945 int change;
946
947 for(i=0; i<lemp->nstate; i++){
948 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
949 cfp->status = INCOMPLETE;
950 }
951 }
952
953 do{
954 progress = 0;
955 for(i=0; i<lemp->nstate; i++){
956 for(cfp=lemp->sorted[i]->cfp; cfp; cfp=cfp->next){
957 if( cfp->status==COMPLETE ) continue;
958 for(plp=cfp->fplp; plp; plp=plp->next){
959 change = SetUnion(plp->cfp->fws,cfp->fws);
960 if( change ){
961 plp->cfp->status = INCOMPLETE;
962 progress = 1;
963 }
964 }
965 cfp->status = COMPLETE;
966 }
967 }
968 }while( progress );
969}
970
icculus9e44cf12010-02-14 17:14:22 +0000971static int resolve_conflict(struct action *,struct action *, struct symbol *);
drh75897232000-05-29 14:26:00 +0000972
973/* Compute the reduce actions, and resolve conflicts.
974*/
icculus9e44cf12010-02-14 17:14:22 +0000975void FindActions(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +0000976{
977 int i,j;
978 struct config *cfp;
979 struct state *stp;
980 struct symbol *sp;
981 struct rule *rp;
982
983 /* Add all of the reduce actions
984 ** A reduce action is added for each element of the followset of
985 ** a configuration which has its dot at the extreme right.
986 */
987 for(i=0; i<lemp->nstate; i++){ /* Loop over all states */
988 stp = lemp->sorted[i];
989 for(cfp=stp->cfp; cfp; cfp=cfp->next){ /* Loop over all configurations */
990 if( cfp->rp->nrhs==cfp->dot ){ /* Is dot at extreme right? */
991 for(j=0; j<lemp->nterminal; j++){
992 if( SetFind(cfp->fws,j) ){
993 /* Add a reduce action to the state "stp" which will reduce by the
994 ** rule "cfp->rp" if the lookahead symbol is "lemp->symbols[j]" */
drh218dc692004-05-31 23:13:45 +0000995 Action_add(&stp->ap,REDUCE,lemp->symbols[j],(char *)cfp->rp);
drh75897232000-05-29 14:26:00 +0000996 }
997 }
998 }
999 }
1000 }
1001
1002 /* Add the accepting token */
1003 if( lemp->start ){
1004 sp = Symbol_find(lemp->start);
1005 if( sp==0 ) sp = lemp->rule->lhs;
1006 }else{
1007 sp = lemp->rule->lhs;
1008 }
1009 /* Add to the first state (which is always the starting state of the
1010 ** finite state machine) an action to ACCEPT if the lookahead is the
1011 ** start nonterminal. */
1012 Action_add(&lemp->sorted[0]->ap,ACCEPT,sp,0);
1013
1014 /* Resolve conflicts */
1015 for(i=0; i<lemp->nstate; i++){
1016 struct action *ap, *nap;
1017 struct state *stp;
1018 stp = lemp->sorted[i];
drhe9278182007-07-18 18:16:29 +00001019 /* assert( stp->ap ); */
drh75897232000-05-29 14:26:00 +00001020 stp->ap = Action_sort(stp->ap);
drhb59499c2002-02-23 18:45:13 +00001021 for(ap=stp->ap; ap && ap->next; ap=ap->next){
drh75897232000-05-29 14:26:00 +00001022 for(nap=ap->next; nap && nap->sp==ap->sp; nap=nap->next){
1023 /* The two actions "ap" and "nap" have the same lookahead.
1024 ** Figure out which one should be used */
1025 lemp->nconflict += resolve_conflict(ap,nap,lemp->errsym);
1026 }
1027 }
1028 }
1029
1030 /* Report an error for each rule that can never be reduced. */
drhaa9f1122007-08-23 02:50:56 +00001031 for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00001032 for(i=0; i<lemp->nstate; i++){
1033 struct action *ap;
1034 for(ap=lemp->sorted[i]->ap; ap; ap=ap->next){
drhaa9f1122007-08-23 02:50:56 +00001035 if( ap->type==REDUCE ) ap->x.rp->canReduce = LEMON_TRUE;
drh75897232000-05-29 14:26:00 +00001036 }
1037 }
1038 for(rp=lemp->rule; rp; rp=rp->next){
1039 if( rp->canReduce ) continue;
1040 ErrorMsg(lemp->filename,rp->ruleline,"This rule can not be reduced.\n");
1041 lemp->errorcnt++;
1042 }
1043}
1044
1045/* Resolve a conflict between the two given actions. If the
drh34ff57b2008-07-14 12:27:51 +00001046** conflict can't be resolved, return non-zero.
drh75897232000-05-29 14:26:00 +00001047**
1048** NO LONGER TRUE:
1049** To resolve a conflict, first look to see if either action
1050** is on an error rule. In that case, take the action which
1051** is not associated with the error rule. If neither or both
1052** actions are associated with an error rule, then try to
1053** use precedence to resolve the conflict.
1054**
1055** If either action is a SHIFT, then it must be apx. This
1056** function won't work if apx->type==REDUCE and apy->type==SHIFT.
1057*/
icculus9e44cf12010-02-14 17:14:22 +00001058static int resolve_conflict(
1059 struct action *apx,
1060 struct action *apy,
1061 struct symbol *errsym /* The error symbol (if defined. NULL otherwise) */
1062){
drh75897232000-05-29 14:26:00 +00001063 struct symbol *spx, *spy;
1064 int errcnt = 0;
1065 assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */
drhf0fa1c12006-12-14 01:06:22 +00001066 if( apx->type==SHIFT && apy->type==SHIFT ){
drh9892c5d2007-12-21 00:02:11 +00001067 apy->type = SSCONFLICT;
drhf0fa1c12006-12-14 01:06:22 +00001068 errcnt++;
1069 }
drh75897232000-05-29 14:26:00 +00001070 if( apx->type==SHIFT && apy->type==REDUCE ){
1071 spx = apx->sp;
1072 spy = apy->x.rp->precsym;
1073 if( spy==0 || spx->prec<0 || spy->prec<0 ){
1074 /* Not enough precedence information. */
drh9892c5d2007-12-21 00:02:11 +00001075 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001076 errcnt++;
drhdd7e9db2010-07-19 01:52:07 +00001077 }else if( spx->prec>spy->prec ){ /* higher precedence wins */
drh75897232000-05-29 14:26:00 +00001078 apy->type = RD_RESOLVED;
1079 }else if( spx->prec<spy->prec ){
1080 apx->type = SH_RESOLVED;
1081 }else if( spx->prec==spy->prec && spx->assoc==RIGHT ){ /* Use operator */
1082 apy->type = RD_RESOLVED; /* associativity */
1083 }else if( spx->prec==spy->prec && spx->assoc==LEFT ){ /* to break tie */
1084 apx->type = SH_RESOLVED;
1085 }else{
1086 assert( spx->prec==spy->prec && spx->assoc==NONE );
drh9892c5d2007-12-21 00:02:11 +00001087 apy->type = SRCONFLICT;
drh75897232000-05-29 14:26:00 +00001088 errcnt++;
1089 }
1090 }else if( apx->type==REDUCE && apy->type==REDUCE ){
1091 spx = apx->x.rp->precsym;
1092 spy = apy->x.rp->precsym;
1093 if( spx==0 || spy==0 || spx->prec<0 ||
1094 spy->prec<0 || spx->prec==spy->prec ){
drh9892c5d2007-12-21 00:02:11 +00001095 apy->type = RRCONFLICT;
drh75897232000-05-29 14:26:00 +00001096 errcnt++;
1097 }else if( spx->prec>spy->prec ){
1098 apy->type = RD_RESOLVED;
1099 }else if( spx->prec<spy->prec ){
1100 apx->type = RD_RESOLVED;
1101 }
1102 }else{
drhb59499c2002-02-23 18:45:13 +00001103 assert(
1104 apx->type==SH_RESOLVED ||
1105 apx->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001106 apx->type==SSCONFLICT ||
1107 apx->type==SRCONFLICT ||
1108 apx->type==RRCONFLICT ||
drhb59499c2002-02-23 18:45:13 +00001109 apy->type==SH_RESOLVED ||
1110 apy->type==RD_RESOLVED ||
drh9892c5d2007-12-21 00:02:11 +00001111 apy->type==SSCONFLICT ||
1112 apy->type==SRCONFLICT ||
1113 apy->type==RRCONFLICT
drhb59499c2002-02-23 18:45:13 +00001114 );
1115 /* The REDUCE/SHIFT case cannot happen because SHIFTs come before
1116 ** REDUCEs on the list. If we reach this point it must be because
1117 ** the parser conflict had already been resolved. */
drh75897232000-05-29 14:26:00 +00001118 }
1119 return errcnt;
1120}
1121/********************* From the file "configlist.c" *************************/
1122/*
1123** Routines to processing a configuration list and building a state
1124** in the LEMON parser generator.
1125*/
1126
1127static struct config *freelist = 0; /* List of free configurations */
1128static struct config *current = 0; /* Top of list of configurations */
1129static struct config **currentend = 0; /* Last on list of configs */
1130static struct config *basis = 0; /* Top of list of basis configs */
1131static struct config **basisend = 0; /* End of list of basis configs */
1132
1133/* Return a pointer to a new configuration */
1134PRIVATE struct config *newconfig(){
icculus9e44cf12010-02-14 17:14:22 +00001135 struct config *newcfg;
drh75897232000-05-29 14:26:00 +00001136 if( freelist==0 ){
1137 int i;
1138 int amt = 3;
drh9892c5d2007-12-21 00:02:11 +00001139 freelist = (struct config *)calloc( amt, sizeof(struct config) );
drh75897232000-05-29 14:26:00 +00001140 if( freelist==0 ){
1141 fprintf(stderr,"Unable to allocate memory for a new configuration.");
1142 exit(1);
1143 }
1144 for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1];
1145 freelist[amt-1].next = 0;
1146 }
icculus9e44cf12010-02-14 17:14:22 +00001147 newcfg = freelist;
drh75897232000-05-29 14:26:00 +00001148 freelist = freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00001149 return newcfg;
drh75897232000-05-29 14:26:00 +00001150}
1151
1152/* The configuration "old" is no longer used */
icculus9e44cf12010-02-14 17:14:22 +00001153PRIVATE void deleteconfig(struct config *old)
drh75897232000-05-29 14:26:00 +00001154{
1155 old->next = freelist;
1156 freelist = old;
1157}
1158
1159/* Initialized the configuration list builder */
1160void Configlist_init(){
1161 current = 0;
1162 currentend = &current;
1163 basis = 0;
1164 basisend = &basis;
1165 Configtable_init();
1166 return;
1167}
1168
1169/* Initialized the configuration list builder */
1170void Configlist_reset(){
1171 current = 0;
1172 currentend = &current;
1173 basis = 0;
1174 basisend = &basis;
1175 Configtable_clear(0);
1176 return;
1177}
1178
1179/* Add another configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001180struct config *Configlist_add(
1181 struct rule *rp, /* The rule */
1182 int dot /* Index into the RHS of the rule where the dot goes */
1183){
drh75897232000-05-29 14:26:00 +00001184 struct config *cfp, model;
1185
1186 assert( currentend!=0 );
1187 model.rp = rp;
1188 model.dot = dot;
1189 cfp = Configtable_find(&model);
1190 if( cfp==0 ){
1191 cfp = newconfig();
1192 cfp->rp = rp;
1193 cfp->dot = dot;
1194 cfp->fws = SetNew();
1195 cfp->stp = 0;
1196 cfp->fplp = cfp->bplp = 0;
1197 cfp->next = 0;
1198 cfp->bp = 0;
1199 *currentend = cfp;
1200 currentend = &cfp->next;
1201 Configtable_insert(cfp);
1202 }
1203 return cfp;
1204}
1205
1206/* Add a basis configuration to the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001207struct config *Configlist_addbasis(struct rule *rp, int dot)
drh75897232000-05-29 14:26:00 +00001208{
1209 struct config *cfp, model;
1210
1211 assert( basisend!=0 );
1212 assert( currentend!=0 );
1213 model.rp = rp;
1214 model.dot = dot;
1215 cfp = Configtable_find(&model);
1216 if( cfp==0 ){
1217 cfp = newconfig();
1218 cfp->rp = rp;
1219 cfp->dot = dot;
1220 cfp->fws = SetNew();
1221 cfp->stp = 0;
1222 cfp->fplp = cfp->bplp = 0;
1223 cfp->next = 0;
1224 cfp->bp = 0;
1225 *currentend = cfp;
1226 currentend = &cfp->next;
1227 *basisend = cfp;
1228 basisend = &cfp->bp;
1229 Configtable_insert(cfp);
1230 }
1231 return cfp;
1232}
1233
1234/* Compute the closure of the configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001235void Configlist_closure(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00001236{
1237 struct config *cfp, *newcfp;
1238 struct rule *rp, *newrp;
1239 struct symbol *sp, *xsp;
1240 int i, dot;
1241
1242 assert( currentend!=0 );
1243 for(cfp=current; cfp; cfp=cfp->next){
1244 rp = cfp->rp;
1245 dot = cfp->dot;
1246 if( dot>=rp->nrhs ) continue;
1247 sp = rp->rhs[dot];
1248 if( sp->type==NONTERMINAL ){
1249 if( sp->rule==0 && sp!=lemp->errsym ){
1250 ErrorMsg(lemp->filename,rp->line,"Nonterminal \"%s\" has no rules.",
1251 sp->name);
1252 lemp->errorcnt++;
1253 }
1254 for(newrp=sp->rule; newrp; newrp=newrp->nextlhs){
1255 newcfp = Configlist_add(newrp,0);
1256 for(i=dot+1; i<rp->nrhs; i++){
1257 xsp = rp->rhs[i];
1258 if( xsp->type==TERMINAL ){
1259 SetAdd(newcfp->fws,xsp->index);
1260 break;
drhfd405312005-11-06 04:06:59 +00001261 }else if( xsp->type==MULTITERMINAL ){
1262 int k;
1263 for(k=0; k<xsp->nsubsym; k++){
1264 SetAdd(newcfp->fws, xsp->subsym[k]->index);
1265 }
1266 break;
drh75897232000-05-29 14:26:00 +00001267 }else{
1268 SetUnion(newcfp->fws,xsp->firstset);
drhaa9f1122007-08-23 02:50:56 +00001269 if( xsp->lambda==LEMON_FALSE ) break;
drh75897232000-05-29 14:26:00 +00001270 }
1271 }
1272 if( i==rp->nrhs ) Plink_add(&cfp->fplp,newcfp);
1273 }
1274 }
1275 }
1276 return;
1277}
1278
1279/* Sort the configuration list */
1280void Configlist_sort(){
drh218dc692004-05-31 23:13:45 +00001281 current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp);
drh75897232000-05-29 14:26:00 +00001282 currentend = 0;
1283 return;
1284}
1285
1286/* Sort the basis configuration list */
1287void Configlist_sortbasis(){
drh218dc692004-05-31 23:13:45 +00001288 basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp);
drh75897232000-05-29 14:26:00 +00001289 basisend = 0;
1290 return;
1291}
1292
1293/* Return a pointer to the head of the configuration list and
1294** reset the list */
1295struct config *Configlist_return(){
1296 struct config *old;
1297 old = current;
1298 current = 0;
1299 currentend = 0;
1300 return old;
1301}
1302
1303/* Return a pointer to the head of the configuration list and
1304** reset the list */
1305struct config *Configlist_basis(){
1306 struct config *old;
1307 old = basis;
1308 basis = 0;
1309 basisend = 0;
1310 return old;
1311}
1312
1313/* Free all elements of the given configuration list */
icculus9e44cf12010-02-14 17:14:22 +00001314void Configlist_eat(struct config *cfp)
drh75897232000-05-29 14:26:00 +00001315{
1316 struct config *nextcfp;
1317 for(; cfp; cfp=nextcfp){
1318 nextcfp = cfp->next;
1319 assert( cfp->fplp==0 );
1320 assert( cfp->bplp==0 );
1321 if( cfp->fws ) SetFree(cfp->fws);
1322 deleteconfig(cfp);
1323 }
1324 return;
1325}
1326/***************** From the file "error.c" *********************************/
1327/*
1328** Code for printing error message.
1329*/
1330
drhf9a2e7b2003-04-15 01:49:48 +00001331void ErrorMsg(const char *filename, int lineno, const char *format, ...){
icculus15a2cec2010-02-16 16:07:28 +00001332 va_list ap;
icculus1c11f742010-02-15 00:01:04 +00001333 fprintf(stderr, "%s:%d: ", filename, lineno);
1334 va_start(ap, format);
1335 vfprintf(stderr,format,ap);
1336 va_end(ap);
1337 fprintf(stderr, "\n");
drh75897232000-05-29 14:26:00 +00001338}
1339/**************** From the file "main.c" ************************************/
1340/*
1341** Main program file for the LEMON parser generator.
1342*/
1343
1344/* Report an out-of-memory condition and abort. This function
1345** is used mostly by the "MemoryCheck" macro in struct.h
1346*/
1347void memory_error(){
1348 fprintf(stderr,"Out of memory. Aborting...\n");
1349 exit(1);
1350}
1351
drh6d08b4d2004-07-20 12:45:22 +00001352static int nDefine = 0; /* Number of -D options on the command line */
1353static char **azDefine = 0; /* Name of the -D macros */
1354
1355/* This routine is called with the argument to each -D command-line option.
1356** Add the macro defined to the azDefine array.
1357*/
1358static void handle_D_option(char *z){
1359 char **paz;
1360 nDefine++;
icculus9e44cf12010-02-14 17:14:22 +00001361 azDefine = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine);
drh6d08b4d2004-07-20 12:45:22 +00001362 if( azDefine==0 ){
1363 fprintf(stderr,"out of memory\n");
1364 exit(1);
1365 }
1366 paz = &azDefine[nDefine-1];
icculus9e44cf12010-02-14 17:14:22 +00001367 *paz = (char *) malloc( lemonStrlen(z)+1 );
drh6d08b4d2004-07-20 12:45:22 +00001368 if( *paz==0 ){
1369 fprintf(stderr,"out of memory\n");
1370 exit(1);
1371 }
1372 strcpy(*paz, z);
1373 for(z=*paz; *z && *z!='='; z++){}
1374 *z = 0;
1375}
1376
icculus3e143bd2010-02-14 00:48:49 +00001377static char *user_templatename = NULL;
1378static void handle_T_option(char *z){
icculus9e44cf12010-02-14 17:14:22 +00001379 user_templatename = (char *) malloc( lemonStrlen(z)+1 );
icculus3e143bd2010-02-14 00:48:49 +00001380 if( user_templatename==0 ){
1381 memory_error();
1382 }
1383 strcpy(user_templatename, z);
1384}
drh75897232000-05-29 14:26:00 +00001385
1386/* The main program. Parse the command line and do it... */
icculus9e44cf12010-02-14 17:14:22 +00001387int main(int argc, char **argv)
drh75897232000-05-29 14:26:00 +00001388{
1389 static int version = 0;
1390 static int rpflag = 0;
1391 static int basisflag = 0;
1392 static int compress = 0;
1393 static int quiet = 0;
1394 static int statistics = 0;
1395 static int mhflag = 0;
shane58543932008-12-10 20:10:04 +00001396 static int nolinenosflag = 0;
drhdd7e9db2010-07-19 01:52:07 +00001397 static int noResort = 0;
drh75897232000-05-29 14:26:00 +00001398 static struct s_options options[] = {
1399 {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
1400 {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
drh6d08b4d2004-07-20 12:45:22 +00001401 {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
icculus3e143bd2010-02-14 00:48:49 +00001402 {OPT_FSTR, "T", (char*)handle_T_option, "Specify a template file."},
drh75897232000-05-29 14:26:00 +00001403 {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
shane58543932008-12-10 20:10:04 +00001404 {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."},
1405 {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."},
drhf5c4e0f2010-07-18 11:35:53 +00001406 {OPT_FLAG, "p", (char*)&showPrecedenceConflict,
1407 "Show conflicts resolved by precedence rules"},
drh75897232000-05-29 14:26:00 +00001408 {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
drhdd7e9db2010-07-19 01:52:07 +00001409 {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"},
drh6d08b4d2004-07-20 12:45:22 +00001410 {OPT_FLAG, "s", (char*)&statistics,
1411 "Print parser stats to standard output."},
drh75897232000-05-29 14:26:00 +00001412 {OPT_FLAG, "x", (char*)&version, "Print the version number."},
1413 {OPT_FLAG,0,0,0}
1414 };
1415 int i;
icculus42585cf2010-02-14 05:19:56 +00001416 int exitcode;
drh75897232000-05-29 14:26:00 +00001417 struct lemon lem;
1418
drhb0c86772000-06-02 23:21:26 +00001419 OptInit(argv,options,stderr);
drh75897232000-05-29 14:26:00 +00001420 if( version ){
drhb19a2bc2001-09-16 00:13:26 +00001421 printf("Lemon version 1.0\n");
drh75897232000-05-29 14:26:00 +00001422 exit(0);
1423 }
drhb0c86772000-06-02 23:21:26 +00001424 if( OptNArgs()!=1 ){
drh75897232000-05-29 14:26:00 +00001425 fprintf(stderr,"Exactly one filename argument is required.\n");
1426 exit(1);
1427 }
drh954f6b42006-06-13 13:27:46 +00001428 memset(&lem, 0, sizeof(lem));
drh75897232000-05-29 14:26:00 +00001429 lem.errorcnt = 0;
1430
1431 /* Initialize the machine */
1432 Strsafe_init();
1433 Symbol_init();
1434 State_init();
1435 lem.argv0 = argv[0];
drhb0c86772000-06-02 23:21:26 +00001436 lem.filename = OptArg(0);
drh75897232000-05-29 14:26:00 +00001437 lem.basisflag = basisflag;
shane58543932008-12-10 20:10:04 +00001438 lem.nolinenosflag = nolinenosflag;
drh75897232000-05-29 14:26:00 +00001439 Symbol_new("$");
1440 lem.errsym = Symbol_new("error");
drhc4dd3fd2008-01-22 01:48:05 +00001441 lem.errsym->useCnt = 0;
drh75897232000-05-29 14:26:00 +00001442
1443 /* Parse the input file */
1444 Parse(&lem);
1445 if( lem.errorcnt ) exit(lem.errorcnt);
drh954f6b42006-06-13 13:27:46 +00001446 if( lem.nrule==0 ){
drh75897232000-05-29 14:26:00 +00001447 fprintf(stderr,"Empty grammar.\n");
1448 exit(1);
1449 }
1450
1451 /* Count and index the symbols of the grammar */
1452 lem.nsymbol = Symbol_count();
1453 Symbol_new("{default}");
1454 lem.symbols = Symbol_arrayof();
drh60d31652004-02-22 00:08:04 +00001455 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
icculus9e44cf12010-02-14 17:14:22 +00001456 qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*), Symbolcmpp);
drh75897232000-05-29 14:26:00 +00001457 for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
1458 for(i=1; isupper(lem.symbols[i]->name[0]); i++);
1459 lem.nterminal = i;
1460
1461 /* Generate a reprint of the grammar, if requested on the command line */
1462 if( rpflag ){
1463 Reprint(&lem);
1464 }else{
1465 /* Initialize the size for all follow and first sets */
drh9892c5d2007-12-21 00:02:11 +00001466 SetSize(lem.nterminal+1);
drh75897232000-05-29 14:26:00 +00001467
1468 /* Find the precedence for every production rule (that has one) */
1469 FindRulePrecedences(&lem);
1470
1471 /* Compute the lambda-nonterminals and the first-sets for every
1472 ** nonterminal */
1473 FindFirstSets(&lem);
1474
1475 /* Compute all LR(0) states. Also record follow-set propagation
1476 ** links so that the follow-set can be computed later */
1477 lem.nstate = 0;
1478 FindStates(&lem);
1479 lem.sorted = State_arrayof();
1480
1481 /* Tie up loose ends on the propagation links */
1482 FindLinks(&lem);
1483
1484 /* Compute the follow set of every reducible configuration */
1485 FindFollowSets(&lem);
1486
1487 /* Compute the action tables */
1488 FindActions(&lem);
1489
1490 /* Compress the action tables */
1491 if( compress==0 ) CompressTables(&lem);
1492
drhada354d2005-11-05 15:03:59 +00001493 /* Reorder and renumber the states so that states with fewer choices
drhdd7e9db2010-07-19 01:52:07 +00001494 ** occur at the end. This is an optimization that helps make the
1495 ** generated parser tables smaller. */
1496 if( noResort==0 ) ResortStates(&lem);
drhada354d2005-11-05 15:03:59 +00001497
drh75897232000-05-29 14:26:00 +00001498 /* Generate a report of the parser generated. (the "y.output" file) */
1499 if( !quiet ) ReportOutput(&lem);
1500
1501 /* Generate the source code for the parser */
1502 ReportTable(&lem, mhflag);
1503
1504 /* Produce a header file for use by the scanner. (This step is
1505 ** omitted if the "-m" option is used because makeheaders will
1506 ** generate the file for us.) */
1507 if( !mhflag ) ReportHeader(&lem);
1508 }
1509 if( statistics ){
1510 printf("Parser statistics: %d terminals, %d nonterminals, %d rules\n",
1511 lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
1512 printf(" %d states, %d parser table entries, %d conflicts\n",
1513 lem.nstate, lem.tablesize, lem.nconflict);
1514 }
icculus8e158022010-02-16 16:09:03 +00001515 if( lem.nconflict > 0 ){
1516 fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict);
icculus42585cf2010-02-14 05:19:56 +00001517 }
1518
1519 /* return 0 on success, 1 on failure. */
icculus8e158022010-02-16 16:09:03 +00001520 exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0;
icculus42585cf2010-02-14 05:19:56 +00001521 exit(exitcode);
1522 return (exitcode);
drh75897232000-05-29 14:26:00 +00001523}
1524/******************** From the file "msort.c" *******************************/
1525/*
1526** A generic merge-sort program.
1527**
1528** USAGE:
1529** Let "ptr" be a pointer to some structure which is at the head of
1530** a null-terminated list. Then to sort the list call:
1531**
1532** ptr = msort(ptr,&(ptr->next),cmpfnc);
1533**
1534** In the above, "cmpfnc" is a pointer to a function which compares
1535** two instances of the structure and returns an integer, as in
1536** strcmp. The second argument is a pointer to the pointer to the
1537** second element of the linked list. This address is used to compute
1538** the offset to the "next" field within the structure. The offset to
1539** the "next" field must be constant for all structures in the list.
1540**
1541** The function returns a new pointer which is the head of the list
1542** after sorting.
1543**
1544** ALGORITHM:
1545** Merge-sort.
1546*/
1547
1548/*
1549** Return a pointer to the next structure in the linked list.
1550*/
drhba99af52001-10-25 20:37:16 +00001551#define NEXT(A) (*(char**)(((unsigned long)A)+offset))
drh75897232000-05-29 14:26:00 +00001552
1553/*
1554** Inputs:
1555** a: A sorted, null-terminated linked list. (May be null).
1556** b: A sorted, null-terminated linked list. (May be null).
1557** cmp: A pointer to the comparison function.
1558** offset: Offset in the structure to the "next" field.
1559**
1560** Return Value:
1561** A pointer to the head of a sorted list containing the elements
1562** of both a and b.
1563**
1564** Side effects:
1565** The "next" pointers for elements in the lists a and b are
1566** changed.
1567*/
drhe9278182007-07-18 18:16:29 +00001568static char *merge(
1569 char *a,
1570 char *b,
1571 int (*cmp)(const char*,const char*),
1572 int offset
1573){
drh75897232000-05-29 14:26:00 +00001574 char *ptr, *head;
1575
1576 if( a==0 ){
1577 head = b;
1578 }else if( b==0 ){
1579 head = a;
1580 }else{
drhe594bc32009-11-03 13:02:25 +00001581 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001582 ptr = a;
1583 a = NEXT(a);
1584 }else{
1585 ptr = b;
1586 b = NEXT(b);
1587 }
1588 head = ptr;
1589 while( a && b ){
drhe594bc32009-11-03 13:02:25 +00001590 if( (*cmp)(a,b)<=0 ){
drh75897232000-05-29 14:26:00 +00001591 NEXT(ptr) = a;
1592 ptr = a;
1593 a = NEXT(a);
1594 }else{
1595 NEXT(ptr) = b;
1596 ptr = b;
1597 b = NEXT(b);
1598 }
1599 }
1600 if( a ) NEXT(ptr) = a;
1601 else NEXT(ptr) = b;
1602 }
1603 return head;
1604}
1605
1606/*
1607** Inputs:
1608** list: Pointer to a singly-linked list of structures.
1609** next: Pointer to pointer to the second element of the list.
1610** cmp: A comparison function.
1611**
1612** Return Value:
1613** A pointer to the head of a sorted list containing the elements
1614** orginally in list.
1615**
1616** Side effects:
1617** The "next" pointers for elements in list are changed.
1618*/
1619#define LISTSIZE 30
drhe9278182007-07-18 18:16:29 +00001620static char *msort(
1621 char *list,
1622 char **next,
1623 int (*cmp)(const char*,const char*)
1624){
drhba99af52001-10-25 20:37:16 +00001625 unsigned long offset;
drh75897232000-05-29 14:26:00 +00001626 char *ep;
1627 char *set[LISTSIZE];
1628 int i;
drhba99af52001-10-25 20:37:16 +00001629 offset = (unsigned long)next - (unsigned long)list;
drh75897232000-05-29 14:26:00 +00001630 for(i=0; i<LISTSIZE; i++) set[i] = 0;
1631 while( list ){
1632 ep = list;
1633 list = NEXT(list);
1634 NEXT(ep) = 0;
1635 for(i=0; i<LISTSIZE-1 && set[i]!=0; i++){
1636 ep = merge(ep,set[i],cmp,offset);
1637 set[i] = 0;
1638 }
1639 set[i] = ep;
1640 }
1641 ep = 0;
drhe594bc32009-11-03 13:02:25 +00001642 for(i=0; i<LISTSIZE; i++) if( set[i] ) ep = merge(set[i],ep,cmp,offset);
drh75897232000-05-29 14:26:00 +00001643 return ep;
1644}
1645/************************ From the file "option.c" **************************/
1646static char **argv;
1647static struct s_options *op;
1648static FILE *errstream;
1649
1650#define ISOPT(X) ((X)[0]=='-'||(X)[0]=='+'||strchr((X),'=')!=0)
1651
1652/*
1653** Print the command line with a carrot pointing to the k-th character
1654** of the n-th field.
1655*/
icculus9e44cf12010-02-14 17:14:22 +00001656static void errline(int n, int k, FILE *err)
drh75897232000-05-29 14:26:00 +00001657{
1658 int spcnt, i;
drh75897232000-05-29 14:26:00 +00001659 if( argv[0] ) fprintf(err,"%s",argv[0]);
drh87cf1372008-08-13 20:09:06 +00001660 spcnt = lemonStrlen(argv[0]) + 1;
drh75897232000-05-29 14:26:00 +00001661 for(i=1; i<n && argv[i]; i++){
1662 fprintf(err," %s",argv[i]);
drh87cf1372008-08-13 20:09:06 +00001663 spcnt += lemonStrlen(argv[i])+1;
drh75897232000-05-29 14:26:00 +00001664 }
1665 spcnt += k;
1666 for(; argv[i]; i++) fprintf(err," %s",argv[i]);
1667 if( spcnt<20 ){
1668 fprintf(err,"\n%*s^-- here\n",spcnt,"");
1669 }else{
1670 fprintf(err,"\n%*shere --^\n",spcnt-7,"");
1671 }
1672}
1673
1674/*
1675** Return the index of the N-th non-switch argument. Return -1
1676** if N is out of range.
1677*/
icculus9e44cf12010-02-14 17:14:22 +00001678static int argindex(int n)
drh75897232000-05-29 14:26:00 +00001679{
1680 int i;
1681 int dashdash = 0;
1682 if( argv!=0 && *argv!=0 ){
1683 for(i=1; argv[i]; i++){
1684 if( dashdash || !ISOPT(argv[i]) ){
1685 if( n==0 ) return i;
1686 n--;
1687 }
1688 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1689 }
1690 }
1691 return -1;
1692}
1693
1694static char emsg[] = "Command line syntax error: ";
1695
1696/*
1697** Process a flag command line argument.
1698*/
icculus9e44cf12010-02-14 17:14:22 +00001699static int handleflags(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001700{
1701 int v;
1702 int errcnt = 0;
1703 int j;
1704 for(j=0; op[j].label; j++){
drh87cf1372008-08-13 20:09:06 +00001705 if( strncmp(&argv[i][1],op[j].label,lemonStrlen(op[j].label))==0 ) break;
drh75897232000-05-29 14:26:00 +00001706 }
1707 v = argv[i][0]=='-' ? 1 : 0;
1708 if( op[j].label==0 ){
1709 if( err ){
1710 fprintf(err,"%sundefined option.\n",emsg);
1711 errline(i,1,err);
1712 }
1713 errcnt++;
1714 }else if( op[j].type==OPT_FLAG ){
1715 *((int*)op[j].arg) = v;
1716 }else if( op[j].type==OPT_FFLAG ){
icculus9e44cf12010-02-14 17:14:22 +00001717 (*(void(*)(int))(op[j].arg))(v);
drh6d08b4d2004-07-20 12:45:22 +00001718 }else if( op[j].type==OPT_FSTR ){
icculus9e44cf12010-02-14 17:14:22 +00001719 (*(void(*)(char *))(op[j].arg))(&argv[i][2]);
drh75897232000-05-29 14:26:00 +00001720 }else{
1721 if( err ){
1722 fprintf(err,"%smissing argument on switch.\n",emsg);
1723 errline(i,1,err);
1724 }
1725 errcnt++;
1726 }
1727 return errcnt;
1728}
1729
1730/*
1731** Process a command line switch which has an argument.
1732*/
icculus9e44cf12010-02-14 17:14:22 +00001733static int handleswitch(int i, FILE *err)
drh75897232000-05-29 14:26:00 +00001734{
1735 int lv = 0;
1736 double dv = 0.0;
1737 char *sv = 0, *end;
1738 char *cp;
1739 int j;
1740 int errcnt = 0;
1741 cp = strchr(argv[i],'=');
drh43617e92006-03-06 20:55:46 +00001742 assert( cp!=0 );
drh75897232000-05-29 14:26:00 +00001743 *cp = 0;
1744 for(j=0; op[j].label; j++){
1745 if( strcmp(argv[i],op[j].label)==0 ) break;
1746 }
1747 *cp = '=';
1748 if( op[j].label==0 ){
1749 if( err ){
1750 fprintf(err,"%sundefined option.\n",emsg);
1751 errline(i,0,err);
1752 }
1753 errcnt++;
1754 }else{
1755 cp++;
1756 switch( op[j].type ){
1757 case OPT_FLAG:
1758 case OPT_FFLAG:
1759 if( err ){
1760 fprintf(err,"%soption requires an argument.\n",emsg);
1761 errline(i,0,err);
1762 }
1763 errcnt++;
1764 break;
1765 case OPT_DBL:
1766 case OPT_FDBL:
1767 dv = strtod(cp,&end);
1768 if( *end ){
1769 if( err ){
1770 fprintf(err,"%sillegal character in floating-point argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001771 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001772 }
1773 errcnt++;
1774 }
1775 break;
1776 case OPT_INT:
1777 case OPT_FINT:
1778 lv = strtol(cp,&end,0);
1779 if( *end ){
1780 if( err ){
1781 fprintf(err,"%sillegal character in integer argument.\n",emsg);
drhba99af52001-10-25 20:37:16 +00001782 errline(i,((unsigned long)end)-(unsigned long)argv[i],err);
drh75897232000-05-29 14:26:00 +00001783 }
1784 errcnt++;
1785 }
1786 break;
1787 case OPT_STR:
1788 case OPT_FSTR:
1789 sv = cp;
1790 break;
1791 }
1792 switch( op[j].type ){
1793 case OPT_FLAG:
1794 case OPT_FFLAG:
1795 break;
1796 case OPT_DBL:
1797 *(double*)(op[j].arg) = dv;
1798 break;
1799 case OPT_FDBL:
icculus9e44cf12010-02-14 17:14:22 +00001800 (*(void(*)(double))(op[j].arg))(dv);
drh75897232000-05-29 14:26:00 +00001801 break;
1802 case OPT_INT:
1803 *(int*)(op[j].arg) = lv;
1804 break;
1805 case OPT_FINT:
icculus9e44cf12010-02-14 17:14:22 +00001806 (*(void(*)(int))(op[j].arg))((int)lv);
drh75897232000-05-29 14:26:00 +00001807 break;
1808 case OPT_STR:
1809 *(char**)(op[j].arg) = sv;
1810 break;
1811 case OPT_FSTR:
icculus9e44cf12010-02-14 17:14:22 +00001812 (*(void(*)(char *))(op[j].arg))(sv);
drh75897232000-05-29 14:26:00 +00001813 break;
1814 }
1815 }
1816 return errcnt;
1817}
1818
icculus9e44cf12010-02-14 17:14:22 +00001819int OptInit(char **a, struct s_options *o, FILE *err)
drh75897232000-05-29 14:26:00 +00001820{
1821 int errcnt = 0;
1822 argv = a;
1823 op = o;
1824 errstream = err;
1825 if( argv && *argv && op ){
1826 int i;
1827 for(i=1; argv[i]; i++){
1828 if( argv[i][0]=='+' || argv[i][0]=='-' ){
1829 errcnt += handleflags(i,err);
1830 }else if( strchr(argv[i],'=') ){
1831 errcnt += handleswitch(i,err);
1832 }
1833 }
1834 }
1835 if( errcnt>0 ){
1836 fprintf(err,"Valid command line options for \"%s\" are:\n",*a);
drhb0c86772000-06-02 23:21:26 +00001837 OptPrint();
drh75897232000-05-29 14:26:00 +00001838 exit(1);
1839 }
1840 return 0;
1841}
1842
drhb0c86772000-06-02 23:21:26 +00001843int OptNArgs(){
drh75897232000-05-29 14:26:00 +00001844 int cnt = 0;
1845 int dashdash = 0;
1846 int i;
1847 if( argv!=0 && argv[0]!=0 ){
1848 for(i=1; argv[i]; i++){
1849 if( dashdash || !ISOPT(argv[i]) ) cnt++;
1850 if( strcmp(argv[i],"--")==0 ) dashdash = 1;
1851 }
1852 }
1853 return cnt;
1854}
1855
icculus9e44cf12010-02-14 17:14:22 +00001856char *OptArg(int n)
drh75897232000-05-29 14:26:00 +00001857{
1858 int i;
1859 i = argindex(n);
1860 return i>=0 ? argv[i] : 0;
1861}
1862
icculus9e44cf12010-02-14 17:14:22 +00001863void OptErr(int n)
drh75897232000-05-29 14:26:00 +00001864{
1865 int i;
1866 i = argindex(n);
1867 if( i>=0 ) errline(i,0,errstream);
1868}
1869
drhb0c86772000-06-02 23:21:26 +00001870void OptPrint(){
drh75897232000-05-29 14:26:00 +00001871 int i;
1872 int max, len;
1873 max = 0;
1874 for(i=0; op[i].label; i++){
drh87cf1372008-08-13 20:09:06 +00001875 len = lemonStrlen(op[i].label) + 1;
drh75897232000-05-29 14:26:00 +00001876 switch( op[i].type ){
1877 case OPT_FLAG:
1878 case OPT_FFLAG:
1879 break;
1880 case OPT_INT:
1881 case OPT_FINT:
1882 len += 9; /* length of "<integer>" */
1883 break;
1884 case OPT_DBL:
1885 case OPT_FDBL:
1886 len += 6; /* length of "<real>" */
1887 break;
1888 case OPT_STR:
1889 case OPT_FSTR:
1890 len += 8; /* length of "<string>" */
1891 break;
1892 }
1893 if( len>max ) max = len;
1894 }
1895 for(i=0; op[i].label; i++){
1896 switch( op[i].type ){
1897 case OPT_FLAG:
1898 case OPT_FFLAG:
1899 fprintf(errstream," -%-*s %s\n",max,op[i].label,op[i].message);
1900 break;
1901 case OPT_INT:
1902 case OPT_FINT:
1903 fprintf(errstream," %s=<integer>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001904 (int)(max-lemonStrlen(op[i].label)-9),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001905 break;
1906 case OPT_DBL:
1907 case OPT_FDBL:
1908 fprintf(errstream," %s=<real>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001909 (int)(max-lemonStrlen(op[i].label)-6),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001910 break;
1911 case OPT_STR:
1912 case OPT_FSTR:
1913 fprintf(errstream," %s=<string>%*s %s\n",op[i].label,
drh87cf1372008-08-13 20:09:06 +00001914 (int)(max-lemonStrlen(op[i].label)-8),"",op[i].message);
drh75897232000-05-29 14:26:00 +00001915 break;
1916 }
1917 }
1918}
1919/*********************** From the file "parse.c" ****************************/
1920/*
1921** Input file parser for the LEMON parser generator.
1922*/
1923
1924/* The state of the parser */
icculus9e44cf12010-02-14 17:14:22 +00001925enum e_state {
1926 INITIALIZE,
1927 WAITING_FOR_DECL_OR_RULE,
1928 WAITING_FOR_DECL_KEYWORD,
1929 WAITING_FOR_DECL_ARG,
1930 WAITING_FOR_PRECEDENCE_SYMBOL,
1931 WAITING_FOR_ARROW,
1932 IN_RHS,
1933 LHS_ALIAS_1,
1934 LHS_ALIAS_2,
1935 LHS_ALIAS_3,
1936 RHS_ALIAS_1,
1937 RHS_ALIAS_2,
1938 PRECEDENCE_MARK_1,
1939 PRECEDENCE_MARK_2,
1940 RESYNC_AFTER_RULE_ERROR,
1941 RESYNC_AFTER_DECL_ERROR,
1942 WAITING_FOR_DESTRUCTOR_SYMBOL,
1943 WAITING_FOR_DATATYPE_SYMBOL,
1944 WAITING_FOR_FALLBACK_ID,
icculus9e44cf12010-02-14 17:14:22 +00001945 WAITING_FOR_WILDCARD_ID
1946};
drh75897232000-05-29 14:26:00 +00001947struct pstate {
1948 char *filename; /* Name of the input file */
1949 int tokenlineno; /* Linenumber at which current token starts */
1950 int errorcnt; /* Number of errors so far */
1951 char *tokenstart; /* Text of current token */
1952 struct lemon *gp; /* Global state vector */
icculus9e44cf12010-02-14 17:14:22 +00001953 enum e_state state; /* The state of the parser */
drh0bd1f4e2002-06-06 18:54:39 +00001954 struct symbol *fallback; /* The fallback token */
drh75897232000-05-29 14:26:00 +00001955 struct symbol *lhs; /* Left-hand side of current rule */
icculus9e44cf12010-02-14 17:14:22 +00001956 const char *lhsalias; /* Alias for the LHS */
drh75897232000-05-29 14:26:00 +00001957 int nrhs; /* Number of right-hand side symbols seen */
1958 struct symbol *rhs[MAXRHS]; /* RHS symbols */
icculus9e44cf12010-02-14 17:14:22 +00001959 const char *alias[MAXRHS]; /* Aliases for each RHS symbol (or NULL) */
drh75897232000-05-29 14:26:00 +00001960 struct rule *prevrule; /* Previous rule parsed */
icculus9e44cf12010-02-14 17:14:22 +00001961 const char *declkeyword; /* Keyword of a declaration */
drh75897232000-05-29 14:26:00 +00001962 char **declargslot; /* Where the declaration argument should be put */
drha5808f32008-04-27 22:19:44 +00001963 int insertLineMacro; /* Add #line before declaration insert */
drh4dc8ef52008-07-01 17:13:57 +00001964 int *decllinenoslot; /* Where to write declaration line number */
drh75897232000-05-29 14:26:00 +00001965 enum e_assoc declassoc; /* Assign this association to decl arguments */
1966 int preccounter; /* Assign this precedence to decl arguments */
1967 struct rule *firstrule; /* Pointer to first rule in the grammar */
1968 struct rule *lastrule; /* Pointer to the most recently parsed rule */
1969};
1970
1971/* Parse a single token */
icculus9e44cf12010-02-14 17:14:22 +00001972static void parseonetoken(struct pstate *psp)
drh75897232000-05-29 14:26:00 +00001973{
icculus9e44cf12010-02-14 17:14:22 +00001974 const char *x;
drh75897232000-05-29 14:26:00 +00001975 x = Strsafe(psp->tokenstart); /* Save the token permanently */
1976#if 0
1977 printf("%s:%d: Token=[%s] state=%d\n",psp->filename,psp->tokenlineno,
1978 x,psp->state);
1979#endif
1980 switch( psp->state ){
1981 case INITIALIZE:
1982 psp->prevrule = 0;
1983 psp->preccounter = 0;
1984 psp->firstrule = psp->lastrule = 0;
1985 psp->gp->nrule = 0;
1986 /* Fall thru to next case */
1987 case WAITING_FOR_DECL_OR_RULE:
1988 if( x[0]=='%' ){
1989 psp->state = WAITING_FOR_DECL_KEYWORD;
1990 }else if( islower(x[0]) ){
1991 psp->lhs = Symbol_new(x);
1992 psp->nrhs = 0;
1993 psp->lhsalias = 0;
1994 psp->state = WAITING_FOR_ARROW;
1995 }else if( x[0]=='{' ){
1996 if( psp->prevrule==0 ){
1997 ErrorMsg(psp->filename,psp->tokenlineno,
drh34ff57b2008-07-14 12:27:51 +00001998"There is no prior rule opon which to attach the code \
drh75897232000-05-29 14:26:00 +00001999fragment which begins on this line.");
2000 psp->errorcnt++;
2001 }else if( psp->prevrule->code!=0 ){
2002 ErrorMsg(psp->filename,psp->tokenlineno,
2003"Code fragment beginning on this line is not the first \
2004to follow the previous rule.");
2005 psp->errorcnt++;
2006 }else{
2007 psp->prevrule->line = psp->tokenlineno;
2008 psp->prevrule->code = &x[1];
2009 }
2010 }else if( x[0]=='[' ){
2011 psp->state = PRECEDENCE_MARK_1;
2012 }else{
2013 ErrorMsg(psp->filename,psp->tokenlineno,
2014 "Token \"%s\" should be either \"%%\" or a nonterminal name.",
2015 x);
2016 psp->errorcnt++;
2017 }
2018 break;
2019 case PRECEDENCE_MARK_1:
2020 if( !isupper(x[0]) ){
2021 ErrorMsg(psp->filename,psp->tokenlineno,
2022 "The precedence symbol must be a terminal.");
2023 psp->errorcnt++;
2024 }else if( psp->prevrule==0 ){
2025 ErrorMsg(psp->filename,psp->tokenlineno,
2026 "There is no prior rule to assign precedence \"[%s]\".",x);
2027 psp->errorcnt++;
2028 }else if( psp->prevrule->precsym!=0 ){
2029 ErrorMsg(psp->filename,psp->tokenlineno,
2030"Precedence mark on this line is not the first \
2031to follow the previous rule.");
2032 psp->errorcnt++;
2033 }else{
2034 psp->prevrule->precsym = Symbol_new(x);
2035 }
2036 psp->state = PRECEDENCE_MARK_2;
2037 break;
2038 case PRECEDENCE_MARK_2:
2039 if( x[0]!=']' ){
2040 ErrorMsg(psp->filename,psp->tokenlineno,
2041 "Missing \"]\" on precedence mark.");
2042 psp->errorcnt++;
2043 }
2044 psp->state = WAITING_FOR_DECL_OR_RULE;
2045 break;
2046 case WAITING_FOR_ARROW:
2047 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2048 psp->state = IN_RHS;
2049 }else if( x[0]=='(' ){
2050 psp->state = LHS_ALIAS_1;
2051 }else{
2052 ErrorMsg(psp->filename,psp->tokenlineno,
2053 "Expected to see a \":\" following the LHS symbol \"%s\".",
2054 psp->lhs->name);
2055 psp->errorcnt++;
2056 psp->state = RESYNC_AFTER_RULE_ERROR;
2057 }
2058 break;
2059 case LHS_ALIAS_1:
2060 if( isalpha(x[0]) ){
2061 psp->lhsalias = x;
2062 psp->state = LHS_ALIAS_2;
2063 }else{
2064 ErrorMsg(psp->filename,psp->tokenlineno,
2065 "\"%s\" is not a valid alias for the LHS \"%s\"\n",
2066 x,psp->lhs->name);
2067 psp->errorcnt++;
2068 psp->state = RESYNC_AFTER_RULE_ERROR;
2069 }
2070 break;
2071 case LHS_ALIAS_2:
2072 if( x[0]==')' ){
2073 psp->state = LHS_ALIAS_3;
2074 }else{
2075 ErrorMsg(psp->filename,psp->tokenlineno,
2076 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2077 psp->errorcnt++;
2078 psp->state = RESYNC_AFTER_RULE_ERROR;
2079 }
2080 break;
2081 case LHS_ALIAS_3:
2082 if( x[0]==':' && x[1]==':' && x[2]=='=' ){
2083 psp->state = IN_RHS;
2084 }else{
2085 ErrorMsg(psp->filename,psp->tokenlineno,
2086 "Missing \"->\" following: \"%s(%s)\".",
2087 psp->lhs->name,psp->lhsalias);
2088 psp->errorcnt++;
2089 psp->state = RESYNC_AFTER_RULE_ERROR;
2090 }
2091 break;
2092 case IN_RHS:
2093 if( x[0]=='.' ){
2094 struct rule *rp;
drh9892c5d2007-12-21 00:02:11 +00002095 rp = (struct rule *)calloc( sizeof(struct rule) +
2096 sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1);
drh75897232000-05-29 14:26:00 +00002097 if( rp==0 ){
2098 ErrorMsg(psp->filename,psp->tokenlineno,
2099 "Can't allocate enough memory for this rule.");
2100 psp->errorcnt++;
2101 psp->prevrule = 0;
2102 }else{
2103 int i;
2104 rp->ruleline = psp->tokenlineno;
2105 rp->rhs = (struct symbol**)&rp[1];
icculus9e44cf12010-02-14 17:14:22 +00002106 rp->rhsalias = (const char**)&(rp->rhs[psp->nrhs]);
drh75897232000-05-29 14:26:00 +00002107 for(i=0; i<psp->nrhs; i++){
2108 rp->rhs[i] = psp->rhs[i];
2109 rp->rhsalias[i] = psp->alias[i];
2110 }
2111 rp->lhs = psp->lhs;
2112 rp->lhsalias = psp->lhsalias;
2113 rp->nrhs = psp->nrhs;
2114 rp->code = 0;
2115 rp->precsym = 0;
2116 rp->index = psp->gp->nrule++;
2117 rp->nextlhs = rp->lhs->rule;
2118 rp->lhs->rule = rp;
2119 rp->next = 0;
2120 if( psp->firstrule==0 ){
2121 psp->firstrule = psp->lastrule = rp;
2122 }else{
2123 psp->lastrule->next = rp;
2124 psp->lastrule = rp;
2125 }
2126 psp->prevrule = rp;
2127 }
2128 psp->state = WAITING_FOR_DECL_OR_RULE;
2129 }else if( isalpha(x[0]) ){
2130 if( psp->nrhs>=MAXRHS ){
2131 ErrorMsg(psp->filename,psp->tokenlineno,
drhc4dd3fd2008-01-22 01:48:05 +00002132 "Too many symbols on RHS of rule beginning at \"%s\".",
drh75897232000-05-29 14:26:00 +00002133 x);
2134 psp->errorcnt++;
2135 psp->state = RESYNC_AFTER_RULE_ERROR;
2136 }else{
2137 psp->rhs[psp->nrhs] = Symbol_new(x);
2138 psp->alias[psp->nrhs] = 0;
2139 psp->nrhs++;
2140 }
drhfd405312005-11-06 04:06:59 +00002141 }else if( (x[0]=='|' || x[0]=='/') && psp->nrhs>0 ){
2142 struct symbol *msp = psp->rhs[psp->nrhs-1];
2143 if( msp->type!=MULTITERMINAL ){
2144 struct symbol *origsp = msp;
icculus9e44cf12010-02-14 17:14:22 +00002145 msp = (struct symbol *) calloc(1,sizeof(*msp));
drhfd405312005-11-06 04:06:59 +00002146 memset(msp, 0, sizeof(*msp));
2147 msp->type = MULTITERMINAL;
2148 msp->nsubsym = 1;
icculus9e44cf12010-02-14 17:14:22 +00002149 msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*));
drhfd405312005-11-06 04:06:59 +00002150 msp->subsym[0] = origsp;
2151 msp->name = origsp->name;
2152 psp->rhs[psp->nrhs-1] = msp;
2153 }
2154 msp->nsubsym++;
icculus9e44cf12010-02-14 17:14:22 +00002155 msp->subsym = (struct symbol **) realloc(msp->subsym,
2156 sizeof(struct symbol*)*msp->nsubsym);
drhfd405312005-11-06 04:06:59 +00002157 msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]);
2158 if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){
2159 ErrorMsg(psp->filename,psp->tokenlineno,
2160 "Cannot form a compound containing a non-terminal");
2161 psp->errorcnt++;
2162 }
drh75897232000-05-29 14:26:00 +00002163 }else if( x[0]=='(' && psp->nrhs>0 ){
2164 psp->state = RHS_ALIAS_1;
2165 }else{
2166 ErrorMsg(psp->filename,psp->tokenlineno,
2167 "Illegal character on RHS of rule: \"%s\".",x);
2168 psp->errorcnt++;
2169 psp->state = RESYNC_AFTER_RULE_ERROR;
2170 }
2171 break;
2172 case RHS_ALIAS_1:
2173 if( isalpha(x[0]) ){
2174 psp->alias[psp->nrhs-1] = x;
2175 psp->state = RHS_ALIAS_2;
2176 }else{
2177 ErrorMsg(psp->filename,psp->tokenlineno,
2178 "\"%s\" is not a valid alias for the RHS symbol \"%s\"\n",
2179 x,psp->rhs[psp->nrhs-1]->name);
2180 psp->errorcnt++;
2181 psp->state = RESYNC_AFTER_RULE_ERROR;
2182 }
2183 break;
2184 case RHS_ALIAS_2:
2185 if( x[0]==')' ){
2186 psp->state = IN_RHS;
2187 }else{
2188 ErrorMsg(psp->filename,psp->tokenlineno,
2189 "Missing \")\" following LHS alias name \"%s\".",psp->lhsalias);
2190 psp->errorcnt++;
2191 psp->state = RESYNC_AFTER_RULE_ERROR;
2192 }
2193 break;
2194 case WAITING_FOR_DECL_KEYWORD:
2195 if( isalpha(x[0]) ){
2196 psp->declkeyword = x;
2197 psp->declargslot = 0;
drh4dc8ef52008-07-01 17:13:57 +00002198 psp->decllinenoslot = 0;
drha5808f32008-04-27 22:19:44 +00002199 psp->insertLineMacro = 1;
drh75897232000-05-29 14:26:00 +00002200 psp->state = WAITING_FOR_DECL_ARG;
2201 if( strcmp(x,"name")==0 ){
2202 psp->declargslot = &(psp->gp->name);
drha5808f32008-04-27 22:19:44 +00002203 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002204 }else if( strcmp(x,"include")==0 ){
2205 psp->declargslot = &(psp->gp->include);
drh75897232000-05-29 14:26:00 +00002206 }else if( strcmp(x,"code")==0 ){
2207 psp->declargslot = &(psp->gp->extracode);
drh75897232000-05-29 14:26:00 +00002208 }else if( strcmp(x,"token_destructor")==0 ){
2209 psp->declargslot = &psp->gp->tokendest;
drh960e8c62001-04-03 16:53:21 +00002210 }else if( strcmp(x,"default_destructor")==0 ){
2211 psp->declargslot = &psp->gp->vardest;
drh75897232000-05-29 14:26:00 +00002212 }else if( strcmp(x,"token_prefix")==0 ){
2213 psp->declargslot = &psp->gp->tokenprefix;
drha5808f32008-04-27 22:19:44 +00002214 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002215 }else if( strcmp(x,"syntax_error")==0 ){
2216 psp->declargslot = &(psp->gp->error);
drh75897232000-05-29 14:26:00 +00002217 }else if( strcmp(x,"parse_accept")==0 ){
2218 psp->declargslot = &(psp->gp->accept);
drh75897232000-05-29 14:26:00 +00002219 }else if( strcmp(x,"parse_failure")==0 ){
2220 psp->declargslot = &(psp->gp->failure);
drh75897232000-05-29 14:26:00 +00002221 }else if( strcmp(x,"stack_overflow")==0 ){
2222 psp->declargslot = &(psp->gp->overflow);
drh75897232000-05-29 14:26:00 +00002223 }else if( strcmp(x,"extra_argument")==0 ){
2224 psp->declargslot = &(psp->gp->arg);
drha5808f32008-04-27 22:19:44 +00002225 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002226 }else if( strcmp(x,"token_type")==0 ){
2227 psp->declargslot = &(psp->gp->tokentype);
drha5808f32008-04-27 22:19:44 +00002228 psp->insertLineMacro = 0;
drh960e8c62001-04-03 16:53:21 +00002229 }else if( strcmp(x,"default_type")==0 ){
2230 psp->declargslot = &(psp->gp->vartype);
drha5808f32008-04-27 22:19:44 +00002231 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002232 }else if( strcmp(x,"stack_size")==0 ){
2233 psp->declargslot = &(psp->gp->stacksize);
drha5808f32008-04-27 22:19:44 +00002234 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002235 }else if( strcmp(x,"start_symbol")==0 ){
2236 psp->declargslot = &(psp->gp->start);
drha5808f32008-04-27 22:19:44 +00002237 psp->insertLineMacro = 0;
drh75897232000-05-29 14:26:00 +00002238 }else if( strcmp(x,"left")==0 ){
2239 psp->preccounter++;
2240 psp->declassoc = LEFT;
2241 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2242 }else if( strcmp(x,"right")==0 ){
2243 psp->preccounter++;
2244 psp->declassoc = RIGHT;
2245 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2246 }else if( strcmp(x,"nonassoc")==0 ){
2247 psp->preccounter++;
2248 psp->declassoc = NONE;
2249 psp->state = WAITING_FOR_PRECEDENCE_SYMBOL;
2250 }else if( strcmp(x,"destructor")==0 ){
2251 psp->state = WAITING_FOR_DESTRUCTOR_SYMBOL;
2252 }else if( strcmp(x,"type")==0 ){
2253 psp->state = WAITING_FOR_DATATYPE_SYMBOL;
drh0bd1f4e2002-06-06 18:54:39 +00002254 }else if( strcmp(x,"fallback")==0 ){
2255 psp->fallback = 0;
2256 psp->state = WAITING_FOR_FALLBACK_ID;
drhe09daa92006-06-10 13:29:31 +00002257 }else if( strcmp(x,"wildcard")==0 ){
2258 psp->state = WAITING_FOR_WILDCARD_ID;
drh75897232000-05-29 14:26:00 +00002259 }else{
2260 ErrorMsg(psp->filename,psp->tokenlineno,
2261 "Unknown declaration keyword: \"%%%s\".",x);
2262 psp->errorcnt++;
2263 psp->state = RESYNC_AFTER_DECL_ERROR;
2264 }
2265 }else{
2266 ErrorMsg(psp->filename,psp->tokenlineno,
2267 "Illegal declaration keyword: \"%s\".",x);
2268 psp->errorcnt++;
2269 psp->state = RESYNC_AFTER_DECL_ERROR;
2270 }
2271 break;
2272 case WAITING_FOR_DESTRUCTOR_SYMBOL:
2273 if( !isalpha(x[0]) ){
2274 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002275 "Symbol name missing after %%destructor keyword");
drh75897232000-05-29 14:26:00 +00002276 psp->errorcnt++;
2277 psp->state = RESYNC_AFTER_DECL_ERROR;
2278 }else{
icculusd286fa62010-03-03 17:06:32 +00002279 struct symbol *sp = Symbol_new(x);
2280 psp->declargslot = &sp->destructor;
2281 psp->decllinenoslot = &sp->destLineno;
2282 psp->insertLineMacro = 1;
2283 psp->state = WAITING_FOR_DECL_ARG;
drh75897232000-05-29 14:26:00 +00002284 }
2285 break;
2286 case WAITING_FOR_DATATYPE_SYMBOL:
2287 if( !isalpha(x[0]) ){
2288 ErrorMsg(psp->filename,psp->tokenlineno,
icculusd0d97b02010-02-17 20:22:10 +00002289 "Symbol name missing after %%type keyword");
drh75897232000-05-29 14:26:00 +00002290 psp->errorcnt++;
2291 psp->state = RESYNC_AFTER_DECL_ERROR;
2292 }else{
icculus866bf1e2010-02-17 20:31:32 +00002293 struct symbol *sp = Symbol_find(x);
2294 if((sp) && (sp->datatype)){
2295 ErrorMsg(psp->filename,psp->tokenlineno,
2296 "Symbol %%type \"%s\" already defined", x);
2297 psp->errorcnt++;
2298 psp->state = RESYNC_AFTER_DECL_ERROR;
2299 }else{
2300 if (!sp){
2301 sp = Symbol_new(x);
2302 }
2303 psp->declargslot = &sp->datatype;
2304 psp->insertLineMacro = 0;
2305 psp->state = WAITING_FOR_DECL_ARG;
2306 }
drh75897232000-05-29 14:26:00 +00002307 }
2308 break;
2309 case WAITING_FOR_PRECEDENCE_SYMBOL:
2310 if( x[0]=='.' ){
2311 psp->state = WAITING_FOR_DECL_OR_RULE;
2312 }else if( isupper(x[0]) ){
2313 struct symbol *sp;
2314 sp = Symbol_new(x);
2315 if( sp->prec>=0 ){
2316 ErrorMsg(psp->filename,psp->tokenlineno,
2317 "Symbol \"%s\" has already be given a precedence.",x);
2318 psp->errorcnt++;
2319 }else{
2320 sp->prec = psp->preccounter;
2321 sp->assoc = psp->declassoc;
2322 }
2323 }else{
2324 ErrorMsg(psp->filename,psp->tokenlineno,
2325 "Can't assign a precedence to \"%s\".",x);
2326 psp->errorcnt++;
2327 }
2328 break;
2329 case WAITING_FOR_DECL_ARG:
drha5808f32008-04-27 22:19:44 +00002330 if( x[0]=='{' || x[0]=='\"' || isalnum(x[0]) ){
icculus9e44cf12010-02-14 17:14:22 +00002331 const char *zOld, *zNew;
2332 char *zBuf, *z;
drha5808f32008-04-27 22:19:44 +00002333 int nOld, n, nLine, nNew, nBack;
drhb5bd49e2008-07-14 12:21:08 +00002334 int addLineMacro;
drha5808f32008-04-27 22:19:44 +00002335 char zLine[50];
2336 zNew = x;
2337 if( zNew[0]=='"' || zNew[0]=='{' ) zNew++;
drh87cf1372008-08-13 20:09:06 +00002338 nNew = lemonStrlen(zNew);
drha5808f32008-04-27 22:19:44 +00002339 if( *psp->declargslot ){
2340 zOld = *psp->declargslot;
2341 }else{
2342 zOld = "";
2343 }
drh87cf1372008-08-13 20:09:06 +00002344 nOld = lemonStrlen(zOld);
drha5808f32008-04-27 22:19:44 +00002345 n = nOld + nNew + 20;
shane58543932008-12-10 20:10:04 +00002346 addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro &&
drhb5bd49e2008-07-14 12:21:08 +00002347 (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0);
2348 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002349 for(z=psp->filename, nBack=0; *z; z++){
2350 if( *z=='\\' ) nBack++;
2351 }
2352 sprintf(zLine, "#line %d ", psp->tokenlineno);
drh87cf1372008-08-13 20:09:06 +00002353 nLine = lemonStrlen(zLine);
2354 n += nLine + lemonStrlen(psp->filename) + nBack;
drha5808f32008-04-27 22:19:44 +00002355 }
icculus9e44cf12010-02-14 17:14:22 +00002356 *psp->declargslot = (char *) realloc(*psp->declargslot, n);
2357 zBuf = *psp->declargslot + nOld;
drhb5bd49e2008-07-14 12:21:08 +00002358 if( addLineMacro ){
drha5808f32008-04-27 22:19:44 +00002359 if( nOld && zBuf[-1]!='\n' ){
2360 *(zBuf++) = '\n';
2361 }
2362 memcpy(zBuf, zLine, nLine);
2363 zBuf += nLine;
2364 *(zBuf++) = '"';
2365 for(z=psp->filename; *z; z++){
2366 if( *z=='\\' ){
2367 *(zBuf++) = '\\';
2368 }
2369 *(zBuf++) = *z;
2370 }
2371 *(zBuf++) = '"';
2372 *(zBuf++) = '\n';
2373 }
drh4dc8ef52008-07-01 17:13:57 +00002374 if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){
2375 psp->decllinenoslot[0] = psp->tokenlineno;
2376 }
drha5808f32008-04-27 22:19:44 +00002377 memcpy(zBuf, zNew, nNew);
2378 zBuf += nNew;
2379 *zBuf = 0;
2380 psp->state = WAITING_FOR_DECL_OR_RULE;
drh75897232000-05-29 14:26:00 +00002381 }else{
2382 ErrorMsg(psp->filename,psp->tokenlineno,
2383 "Illegal argument to %%%s: %s",psp->declkeyword,x);
2384 psp->errorcnt++;
2385 psp->state = RESYNC_AFTER_DECL_ERROR;
2386 }
2387 break;
drh0bd1f4e2002-06-06 18:54:39 +00002388 case WAITING_FOR_FALLBACK_ID:
2389 if( x[0]=='.' ){
2390 psp->state = WAITING_FOR_DECL_OR_RULE;
2391 }else if( !isupper(x[0]) ){
2392 ErrorMsg(psp->filename, psp->tokenlineno,
2393 "%%fallback argument \"%s\" should be a token", x);
2394 psp->errorcnt++;
2395 }else{
2396 struct symbol *sp = Symbol_new(x);
2397 if( psp->fallback==0 ){
2398 psp->fallback = sp;
2399 }else if( sp->fallback ){
2400 ErrorMsg(psp->filename, psp->tokenlineno,
2401 "More than one fallback assigned to token %s", x);
2402 psp->errorcnt++;
2403 }else{
2404 sp->fallback = psp->fallback;
2405 psp->gp->has_fallback = 1;
2406 }
2407 }
2408 break;
drhe09daa92006-06-10 13:29:31 +00002409 case WAITING_FOR_WILDCARD_ID:
2410 if( x[0]=='.' ){
2411 psp->state = WAITING_FOR_DECL_OR_RULE;
2412 }else if( !isupper(x[0]) ){
2413 ErrorMsg(psp->filename, psp->tokenlineno,
2414 "%%wildcard argument \"%s\" should be a token", x);
2415 psp->errorcnt++;
2416 }else{
2417 struct symbol *sp = Symbol_new(x);
2418 if( psp->gp->wildcard==0 ){
2419 psp->gp->wildcard = sp;
2420 }else{
2421 ErrorMsg(psp->filename, psp->tokenlineno,
2422 "Extra wildcard to token: %s", x);
2423 psp->errorcnt++;
2424 }
2425 }
2426 break;
drh75897232000-05-29 14:26:00 +00002427 case RESYNC_AFTER_RULE_ERROR:
2428/* if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2429** break; */
2430 case RESYNC_AFTER_DECL_ERROR:
2431 if( x[0]=='.' ) psp->state = WAITING_FOR_DECL_OR_RULE;
2432 if( x[0]=='%' ) psp->state = WAITING_FOR_DECL_KEYWORD;
2433 break;
2434 }
2435}
2436
drh34ff57b2008-07-14 12:27:51 +00002437/* Run the preprocessor over the input file text. The global variables
drh6d08b4d2004-07-20 12:45:22 +00002438** azDefine[0] through azDefine[nDefine-1] contains the names of all defined
2439** macros. This routine looks for "%ifdef" and "%ifndef" and "%endif" and
2440** comments them out. Text in between is also commented out as appropriate.
2441*/
danielk1977940fac92005-01-23 22:41:37 +00002442static void preprocess_input(char *z){
drh6d08b4d2004-07-20 12:45:22 +00002443 int i, j, k, n;
2444 int exclude = 0;
rse38514a92007-09-20 11:34:17 +00002445 int start = 0;
drh6d08b4d2004-07-20 12:45:22 +00002446 int lineno = 1;
rse38514a92007-09-20 11:34:17 +00002447 int start_lineno = 1;
drh6d08b4d2004-07-20 12:45:22 +00002448 for(i=0; z[i]; i++){
2449 if( z[i]=='\n' ) lineno++;
2450 if( z[i]!='%' || (i>0 && z[i-1]!='\n') ) continue;
2451 if( strncmp(&z[i],"%endif",6)==0 && isspace(z[i+6]) ){
2452 if( exclude ){
2453 exclude--;
2454 if( exclude==0 ){
2455 for(j=start; j<i; j++) if( z[j]!='\n' ) z[j] = ' ';
2456 }
2457 }
2458 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2459 }else if( (strncmp(&z[i],"%ifdef",6)==0 && isspace(z[i+6]))
2460 || (strncmp(&z[i],"%ifndef",7)==0 && isspace(z[i+7])) ){
2461 if( exclude ){
2462 exclude++;
2463 }else{
2464 for(j=i+7; isspace(z[j]); j++){}
2465 for(n=0; z[j+n] && !isspace(z[j+n]); n++){}
2466 exclude = 1;
2467 for(k=0; k<nDefine; k++){
drh87cf1372008-08-13 20:09:06 +00002468 if( strncmp(azDefine[k],&z[j],n)==0 && lemonStrlen(azDefine[k])==n ){
drh6d08b4d2004-07-20 12:45:22 +00002469 exclude = 0;
2470 break;
2471 }
2472 }
2473 if( z[i+3]=='n' ) exclude = !exclude;
2474 if( exclude ){
2475 start = i;
2476 start_lineno = lineno;
2477 }
2478 }
2479 for(j=i; z[j] && z[j]!='\n'; j++) z[j] = ' ';
2480 }
2481 }
2482 if( exclude ){
2483 fprintf(stderr,"unterminated %%ifdef starting on line %d\n", start_lineno);
2484 exit(1);
2485 }
2486}
2487
drh75897232000-05-29 14:26:00 +00002488/* In spite of its name, this function is really a scanner. It read
2489** in the entire input file (all at once) then tokenizes it. Each
2490** token is passed to the function "parseonetoken" which builds all
2491** the appropriate data structures in the global state vector "gp".
2492*/
icculus9e44cf12010-02-14 17:14:22 +00002493void Parse(struct lemon *gp)
drh75897232000-05-29 14:26:00 +00002494{
2495 struct pstate ps;
2496 FILE *fp;
2497 char *filebuf;
2498 int filesize;
2499 int lineno;
2500 int c;
2501 char *cp, *nextcp;
2502 int startline = 0;
2503
rse38514a92007-09-20 11:34:17 +00002504 memset(&ps, '\0', sizeof(ps));
drh75897232000-05-29 14:26:00 +00002505 ps.gp = gp;
2506 ps.filename = gp->filename;
2507 ps.errorcnt = 0;
2508 ps.state = INITIALIZE;
2509
2510 /* Begin by reading the input file */
2511 fp = fopen(ps.filename,"rb");
2512 if( fp==0 ){
2513 ErrorMsg(ps.filename,0,"Can't open this file for reading.");
2514 gp->errorcnt++;
2515 return;
2516 }
2517 fseek(fp,0,2);
2518 filesize = ftell(fp);
2519 rewind(fp);
2520 filebuf = (char *)malloc( filesize+1 );
2521 if( filebuf==0 ){
2522 ErrorMsg(ps.filename,0,"Can't allocate %d of memory to hold this file.",
2523 filesize+1);
2524 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002525 fclose(fp);
drh75897232000-05-29 14:26:00 +00002526 return;
2527 }
2528 if( fread(filebuf,1,filesize,fp)!=filesize ){
2529 ErrorMsg(ps.filename,0,"Can't read in all %d bytes of this file.",
2530 filesize);
2531 free(filebuf);
2532 gp->errorcnt++;
drhe0a59cf2011-08-30 00:58:58 +00002533 fclose(fp);
drh75897232000-05-29 14:26:00 +00002534 return;
2535 }
2536 fclose(fp);
2537 filebuf[filesize] = 0;
2538
drh6d08b4d2004-07-20 12:45:22 +00002539 /* Make an initial pass through the file to handle %ifdef and %ifndef */
2540 preprocess_input(filebuf);
2541
drh75897232000-05-29 14:26:00 +00002542 /* Now scan the text of the input file */
2543 lineno = 1;
2544 for(cp=filebuf; (c= *cp)!=0; ){
2545 if( c=='\n' ) lineno++; /* Keep track of the line number */
2546 if( isspace(c) ){ cp++; continue; } /* Skip all white space */
2547 if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments */
2548 cp+=2;
2549 while( (c= *cp)!=0 && c!='\n' ) cp++;
2550 continue;
2551 }
2552 if( c=='/' && cp[1]=='*' ){ /* Skip C style comments */
2553 cp+=2;
2554 while( (c= *cp)!=0 && (c!='/' || cp[-1]!='*') ){
2555 if( c=='\n' ) lineno++;
2556 cp++;
2557 }
2558 if( c ) cp++;
2559 continue;
2560 }
2561 ps.tokenstart = cp; /* Mark the beginning of the token */
2562 ps.tokenlineno = lineno; /* Linenumber on which token begins */
2563 if( c=='\"' ){ /* String literals */
2564 cp++;
2565 while( (c= *cp)!=0 && c!='\"' ){
2566 if( c=='\n' ) lineno++;
2567 cp++;
2568 }
2569 if( c==0 ){
2570 ErrorMsg(ps.filename,startline,
2571"String starting on this line is not terminated before the end of the file.");
2572 ps.errorcnt++;
2573 nextcp = cp;
2574 }else{
2575 nextcp = cp+1;
2576 }
2577 }else if( c=='{' ){ /* A block of C code */
2578 int level;
2579 cp++;
2580 for(level=1; (c= *cp)!=0 && (level>1 || c!='}'); cp++){
2581 if( c=='\n' ) lineno++;
2582 else if( c=='{' ) level++;
2583 else if( c=='}' ) level--;
2584 else if( c=='/' && cp[1]=='*' ){ /* Skip comments */
2585 int prevc;
2586 cp = &cp[2];
2587 prevc = 0;
2588 while( (c= *cp)!=0 && (c!='/' || prevc!='*') ){
2589 if( c=='\n' ) lineno++;
2590 prevc = c;
2591 cp++;
2592 }
2593 }else if( c=='/' && cp[1]=='/' ){ /* Skip C++ style comments too */
2594 cp = &cp[2];
2595 while( (c= *cp)!=0 && c!='\n' ) cp++;
2596 if( c ) lineno++;
2597 }else if( c=='\'' || c=='\"' ){ /* String a character literals */
2598 int startchar, prevc;
2599 startchar = c;
2600 prevc = 0;
2601 for(cp++; (c= *cp)!=0 && (c!=startchar || prevc=='\\'); cp++){
2602 if( c=='\n' ) lineno++;
2603 if( prevc=='\\' ) prevc = 0;
2604 else prevc = c;
2605 }
2606 }
2607 }
2608 if( c==0 ){
drh960e8c62001-04-03 16:53:21 +00002609 ErrorMsg(ps.filename,ps.tokenlineno,
drh75897232000-05-29 14:26:00 +00002610"C code starting on this line is not terminated before the end of the file.");
2611 ps.errorcnt++;
2612 nextcp = cp;
2613 }else{
2614 nextcp = cp+1;
2615 }
2616 }else if( isalnum(c) ){ /* Identifiers */
2617 while( (c= *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2618 nextcp = cp;
2619 }else if( c==':' && cp[1]==':' && cp[2]=='=' ){ /* The operator "::=" */
2620 cp += 3;
2621 nextcp = cp;
drhfd405312005-11-06 04:06:59 +00002622 }else if( (c=='/' || c=='|') && isalpha(cp[1]) ){
2623 cp += 2;
2624 while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++;
2625 nextcp = cp;
drh75897232000-05-29 14:26:00 +00002626 }else{ /* All other (one character) operators */
2627 cp++;
2628 nextcp = cp;
2629 }
2630 c = *cp;
2631 *cp = 0; /* Null terminate the token */
2632 parseonetoken(&ps); /* Parse the token */
2633 *cp = c; /* Restore the buffer */
2634 cp = nextcp;
2635 }
2636 free(filebuf); /* Release the buffer after parsing */
2637 gp->rule = ps.firstrule;
2638 gp->errorcnt = ps.errorcnt;
2639}
2640/*************************** From the file "plink.c" *********************/
2641/*
2642** Routines processing configuration follow-set propagation links
2643** in the LEMON parser generator.
2644*/
2645static struct plink *plink_freelist = 0;
2646
2647/* Allocate a new plink */
2648struct plink *Plink_new(){
icculus9e44cf12010-02-14 17:14:22 +00002649 struct plink *newlink;
drh75897232000-05-29 14:26:00 +00002650
2651 if( plink_freelist==0 ){
2652 int i;
2653 int amt = 100;
drh9892c5d2007-12-21 00:02:11 +00002654 plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) );
drh75897232000-05-29 14:26:00 +00002655 if( plink_freelist==0 ){
2656 fprintf(stderr,
2657 "Unable to allocate memory for a new follow-set propagation link.\n");
2658 exit(1);
2659 }
2660 for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1];
2661 plink_freelist[amt-1].next = 0;
2662 }
icculus9e44cf12010-02-14 17:14:22 +00002663 newlink = plink_freelist;
drh75897232000-05-29 14:26:00 +00002664 plink_freelist = plink_freelist->next;
icculus9e44cf12010-02-14 17:14:22 +00002665 return newlink;
drh75897232000-05-29 14:26:00 +00002666}
2667
2668/* Add a plink to a plink list */
icculus9e44cf12010-02-14 17:14:22 +00002669void Plink_add(struct plink **plpp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002670{
icculus9e44cf12010-02-14 17:14:22 +00002671 struct plink *newlink;
2672 newlink = Plink_new();
2673 newlink->next = *plpp;
2674 *plpp = newlink;
2675 newlink->cfp = cfp;
drh75897232000-05-29 14:26:00 +00002676}
2677
2678/* Transfer every plink on the list "from" to the list "to" */
icculus9e44cf12010-02-14 17:14:22 +00002679void Plink_copy(struct plink **to, struct plink *from)
drh75897232000-05-29 14:26:00 +00002680{
2681 struct plink *nextpl;
2682 while( from ){
2683 nextpl = from->next;
2684 from->next = *to;
2685 *to = from;
2686 from = nextpl;
2687 }
2688}
2689
2690/* Delete every plink on the list */
icculus9e44cf12010-02-14 17:14:22 +00002691void Plink_delete(struct plink *plp)
drh75897232000-05-29 14:26:00 +00002692{
2693 struct plink *nextpl;
2694
2695 while( plp ){
2696 nextpl = plp->next;
2697 plp->next = plink_freelist;
2698 plink_freelist = plp;
2699 plp = nextpl;
2700 }
2701}
2702/*********************** From the file "report.c" **************************/
2703/*
2704** Procedures for generating reports and tables in the LEMON parser generator.
2705*/
2706
2707/* Generate a filename with the given suffix. Space to hold the
2708** name comes from malloc() and must be freed by the calling
2709** function.
2710*/
icculus9e44cf12010-02-14 17:14:22 +00002711PRIVATE char *file_makename(struct lemon *lemp, const char *suffix)
drh75897232000-05-29 14:26:00 +00002712{
2713 char *name;
2714 char *cp;
2715
icculus9e44cf12010-02-14 17:14:22 +00002716 name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(suffix) + 5 );
drh75897232000-05-29 14:26:00 +00002717 if( name==0 ){
2718 fprintf(stderr,"Can't allocate space for a filename.\n");
2719 exit(1);
2720 }
2721 strcpy(name,lemp->filename);
2722 cp = strrchr(name,'.');
2723 if( cp ) *cp = 0;
2724 strcat(name,suffix);
2725 return name;
2726}
2727
2728/* Open a file with a name based on the name of the input file,
2729** but with a different (specified) suffix, and return a pointer
2730** to the stream */
icculus9e44cf12010-02-14 17:14:22 +00002731PRIVATE FILE *file_open(
2732 struct lemon *lemp,
2733 const char *suffix,
2734 const char *mode
2735){
drh75897232000-05-29 14:26:00 +00002736 FILE *fp;
2737
2738 if( lemp->outname ) free(lemp->outname);
2739 lemp->outname = file_makename(lemp, suffix);
2740 fp = fopen(lemp->outname,mode);
2741 if( fp==0 && *mode=='w' ){
2742 fprintf(stderr,"Can't open file \"%s\".\n",lemp->outname);
2743 lemp->errorcnt++;
2744 return 0;
2745 }
2746 return fp;
2747}
2748
2749/* Duplicate the input file without comments and without actions
2750** on rules */
icculus9e44cf12010-02-14 17:14:22 +00002751void Reprint(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002752{
2753 struct rule *rp;
2754 struct symbol *sp;
2755 int i, j, maxlen, len, ncolumns, skip;
2756 printf("// Reprint of input file \"%s\".\n// Symbols:\n",lemp->filename);
2757 maxlen = 10;
2758 for(i=0; i<lemp->nsymbol; i++){
2759 sp = lemp->symbols[i];
drh87cf1372008-08-13 20:09:06 +00002760 len = lemonStrlen(sp->name);
drh75897232000-05-29 14:26:00 +00002761 if( len>maxlen ) maxlen = len;
2762 }
2763 ncolumns = 76/(maxlen+5);
2764 if( ncolumns<1 ) ncolumns = 1;
2765 skip = (lemp->nsymbol + ncolumns - 1)/ncolumns;
2766 for(i=0; i<skip; i++){
2767 printf("//");
2768 for(j=i; j<lemp->nsymbol; j+=skip){
2769 sp = lemp->symbols[j];
2770 assert( sp->index==j );
2771 printf(" %3d %-*.*s",j,maxlen,maxlen,sp->name);
2772 }
2773 printf("\n");
2774 }
2775 for(rp=lemp->rule; rp; rp=rp->next){
2776 printf("%s",rp->lhs->name);
drhfd405312005-11-06 04:06:59 +00002777 /* if( rp->lhsalias ) printf("(%s)",rp->lhsalias); */
drh75897232000-05-29 14:26:00 +00002778 printf(" ::=");
2779 for(i=0; i<rp->nrhs; i++){
drhfd405312005-11-06 04:06:59 +00002780 sp = rp->rhs[i];
2781 printf(" %s", sp->name);
2782 if( sp->type==MULTITERMINAL ){
2783 for(j=1; j<sp->nsubsym; j++){
2784 printf("|%s", sp->subsym[j]->name);
2785 }
2786 }
2787 /* if( rp->rhsalias[i] ) printf("(%s)",rp->rhsalias[i]); */
drh75897232000-05-29 14:26:00 +00002788 }
2789 printf(".");
2790 if( rp->precsym ) printf(" [%s]",rp->precsym->name);
drhfd405312005-11-06 04:06:59 +00002791 /* if( rp->code ) printf("\n %s",rp->code); */
drh75897232000-05-29 14:26:00 +00002792 printf("\n");
2793 }
2794}
2795
icculus9e44cf12010-02-14 17:14:22 +00002796void ConfigPrint(FILE *fp, struct config *cfp)
drh75897232000-05-29 14:26:00 +00002797{
2798 struct rule *rp;
drhfd405312005-11-06 04:06:59 +00002799 struct symbol *sp;
2800 int i, j;
drh75897232000-05-29 14:26:00 +00002801 rp = cfp->rp;
2802 fprintf(fp,"%s ::=",rp->lhs->name);
2803 for(i=0; i<=rp->nrhs; i++){
2804 if( i==cfp->dot ) fprintf(fp," *");
2805 if( i==rp->nrhs ) break;
drhfd405312005-11-06 04:06:59 +00002806 sp = rp->rhs[i];
2807 fprintf(fp," %s", sp->name);
2808 if( sp->type==MULTITERMINAL ){
2809 for(j=1; j<sp->nsubsym; j++){
2810 fprintf(fp,"|%s",sp->subsym[j]->name);
2811 }
2812 }
drh75897232000-05-29 14:26:00 +00002813 }
2814}
2815
2816/* #define TEST */
drhfd405312005-11-06 04:06:59 +00002817#if 0
drh75897232000-05-29 14:26:00 +00002818/* Print a set */
2819PRIVATE void SetPrint(out,set,lemp)
2820FILE *out;
2821char *set;
2822struct lemon *lemp;
2823{
2824 int i;
2825 char *spacer;
2826 spacer = "";
2827 fprintf(out,"%12s[","");
2828 for(i=0; i<lemp->nterminal; i++){
2829 if( SetFind(set,i) ){
2830 fprintf(out,"%s%s",spacer,lemp->symbols[i]->name);
2831 spacer = " ";
2832 }
2833 }
2834 fprintf(out,"]\n");
2835}
2836
2837/* Print a plink chain */
2838PRIVATE void PlinkPrint(out,plp,tag)
2839FILE *out;
2840struct plink *plp;
2841char *tag;
2842{
2843 while( plp ){
drhada354d2005-11-05 15:03:59 +00002844 fprintf(out,"%12s%s (state %2d) ","",tag,plp->cfp->stp->statenum);
drh75897232000-05-29 14:26:00 +00002845 ConfigPrint(out,plp->cfp);
2846 fprintf(out,"\n");
2847 plp = plp->next;
2848 }
2849}
2850#endif
2851
2852/* Print an action to the given file descriptor. Return FALSE if
2853** nothing was actually printed.
2854*/
2855int PrintAction(struct action *ap, FILE *fp, int indent){
2856 int result = 1;
2857 switch( ap->type ){
2858 case SHIFT:
drhada354d2005-11-05 15:03:59 +00002859 fprintf(fp,"%*s shift %d",indent,ap->sp->name,ap->x.stp->statenum);
drh75897232000-05-29 14:26:00 +00002860 break;
2861 case REDUCE:
2862 fprintf(fp,"%*s reduce %d",indent,ap->sp->name,ap->x.rp->index);
2863 break;
2864 case ACCEPT:
2865 fprintf(fp,"%*s accept",indent,ap->sp->name);
2866 break;
2867 case ERROR:
2868 fprintf(fp,"%*s error",indent,ap->sp->name);
2869 break;
drh9892c5d2007-12-21 00:02:11 +00002870 case SRCONFLICT:
2871 case RRCONFLICT:
drh75897232000-05-29 14:26:00 +00002872 fprintf(fp,"%*s reduce %-3d ** Parsing conflict **",
2873 indent,ap->sp->name,ap->x.rp->index);
2874 break;
drh9892c5d2007-12-21 00:02:11 +00002875 case SSCONFLICT:
drhdd7e9db2010-07-19 01:52:07 +00002876 fprintf(fp,"%*s shift %-3d ** Parsing conflict **",
drh9892c5d2007-12-21 00:02:11 +00002877 indent,ap->sp->name,ap->x.stp->statenum);
2878 break;
drh75897232000-05-29 14:26:00 +00002879 case SH_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00002880 if( showPrecedenceConflict ){
drhdd7e9db2010-07-19 01:52:07 +00002881 fprintf(fp,"%*s shift %-3d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00002882 indent,ap->sp->name,ap->x.stp->statenum);
2883 }else{
2884 result = 0;
2885 }
2886 break;
drh75897232000-05-29 14:26:00 +00002887 case RD_RESOLVED:
drhf5c4e0f2010-07-18 11:35:53 +00002888 if( showPrecedenceConflict ){
drhdd7e9db2010-07-19 01:52:07 +00002889 fprintf(fp,"%*s reduce %-3d -- dropped by precedence",
drhf5c4e0f2010-07-18 11:35:53 +00002890 indent,ap->sp->name,ap->x.rp->index);
2891 }else{
2892 result = 0;
2893 }
2894 break;
drh75897232000-05-29 14:26:00 +00002895 case NOT_USED:
2896 result = 0;
2897 break;
2898 }
2899 return result;
2900}
2901
2902/* Generate the "y.output" log file */
icculus9e44cf12010-02-14 17:14:22 +00002903void ReportOutput(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00002904{
2905 int i;
2906 struct state *stp;
2907 struct config *cfp;
2908 struct action *ap;
2909 FILE *fp;
2910
drh2aa6ca42004-09-10 00:14:04 +00002911 fp = file_open(lemp,".out","wb");
drh75897232000-05-29 14:26:00 +00002912 if( fp==0 ) return;
drh75897232000-05-29 14:26:00 +00002913 for(i=0; i<lemp->nstate; i++){
2914 stp = lemp->sorted[i];
drhada354d2005-11-05 15:03:59 +00002915 fprintf(fp,"State %d:\n",stp->statenum);
drh75897232000-05-29 14:26:00 +00002916 if( lemp->basisflag ) cfp=stp->bp;
2917 else cfp=stp->cfp;
2918 while( cfp ){
2919 char buf[20];
2920 if( cfp->dot==cfp->rp->nrhs ){
2921 sprintf(buf,"(%d)",cfp->rp->index);
2922 fprintf(fp," %5s ",buf);
2923 }else{
2924 fprintf(fp," ");
2925 }
2926 ConfigPrint(fp,cfp);
2927 fprintf(fp,"\n");
drhfd405312005-11-06 04:06:59 +00002928#if 0
drh75897232000-05-29 14:26:00 +00002929 SetPrint(fp,cfp->fws,lemp);
2930 PlinkPrint(fp,cfp->fplp,"To ");
2931 PlinkPrint(fp,cfp->bplp,"From");
2932#endif
2933 if( lemp->basisflag ) cfp=cfp->bp;
2934 else cfp=cfp->next;
2935 }
2936 fprintf(fp,"\n");
2937 for(ap=stp->ap; ap; ap=ap->next){
2938 if( PrintAction(ap,fp,30) ) fprintf(fp,"\n");
2939 }
2940 fprintf(fp,"\n");
2941 }
drhe9278182007-07-18 18:16:29 +00002942 fprintf(fp, "----------------------------------------------------\n");
2943 fprintf(fp, "Symbols:\n");
2944 for(i=0; i<lemp->nsymbol; i++){
2945 int j;
2946 struct symbol *sp;
2947
2948 sp = lemp->symbols[i];
2949 fprintf(fp, " %3d: %s", i, sp->name);
2950 if( sp->type==NONTERMINAL ){
2951 fprintf(fp, ":");
2952 if( sp->lambda ){
2953 fprintf(fp, " <lambda>");
2954 }
2955 for(j=0; j<lemp->nterminal; j++){
2956 if( sp->firstset && SetFind(sp->firstset, j) ){
2957 fprintf(fp, " %s", lemp->symbols[j]->name);
2958 }
2959 }
2960 }
2961 fprintf(fp, "\n");
2962 }
drh75897232000-05-29 14:26:00 +00002963 fclose(fp);
2964 return;
2965}
2966
2967/* Search for the file "name" which is in the same directory as
2968** the exacutable */
icculus9e44cf12010-02-14 17:14:22 +00002969PRIVATE char *pathsearch(char *argv0, char *name, int modemask)
drh75897232000-05-29 14:26:00 +00002970{
icculus9e44cf12010-02-14 17:14:22 +00002971 const char *pathlist;
2972 char *pathbufptr;
2973 char *pathbuf;
drh75897232000-05-29 14:26:00 +00002974 char *path,*cp;
2975 char c;
drh75897232000-05-29 14:26:00 +00002976
2977#ifdef __WIN32__
2978 cp = strrchr(argv0,'\\');
2979#else
2980 cp = strrchr(argv0,'/');
2981#endif
2982 if( cp ){
2983 c = *cp;
2984 *cp = 0;
drh87cf1372008-08-13 20:09:06 +00002985 path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 );
drh75897232000-05-29 14:26:00 +00002986 if( path ) sprintf(path,"%s/%s",argv0,name);
2987 *cp = c;
2988 }else{
drh75897232000-05-29 14:26:00 +00002989 pathlist = getenv("PATH");
2990 if( pathlist==0 ) pathlist = ".:/bin:/usr/bin";
icculus9e44cf12010-02-14 17:14:22 +00002991 pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 );
drh87cf1372008-08-13 20:09:06 +00002992 path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 );
icculus9e44cf12010-02-14 17:14:22 +00002993 if( (pathbuf != 0) && (path!=0) ){
2994 pathbufptr = pathbuf;
2995 strcpy(pathbuf, pathlist);
2996 while( *pathbuf ){
2997 cp = strchr(pathbuf,':');
2998 if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)];
drh75897232000-05-29 14:26:00 +00002999 c = *cp;
3000 *cp = 0;
icculus9e44cf12010-02-14 17:14:22 +00003001 sprintf(path,"%s/%s",pathbuf,name);
drh75897232000-05-29 14:26:00 +00003002 *cp = c;
icculus9e44cf12010-02-14 17:14:22 +00003003 if( c==0 ) pathbuf[0] = 0;
3004 else pathbuf = &cp[1];
drh75897232000-05-29 14:26:00 +00003005 if( access(path,modemask)==0 ) break;
3006 }
icculus9e44cf12010-02-14 17:14:22 +00003007 free(pathbufptr);
drh75897232000-05-29 14:26:00 +00003008 }
3009 }
3010 return path;
3011}
3012
3013/* Given an action, compute the integer value for that action
3014** which is to be put in the action table of the generated machine.
3015** Return negative if no action should be generated.
3016*/
icculus9e44cf12010-02-14 17:14:22 +00003017PRIVATE int compute_action(struct lemon *lemp, struct action *ap)
drh75897232000-05-29 14:26:00 +00003018{
3019 int act;
3020 switch( ap->type ){
drhada354d2005-11-05 15:03:59 +00003021 case SHIFT: act = ap->x.stp->statenum; break;
drh75897232000-05-29 14:26:00 +00003022 case REDUCE: act = ap->x.rp->index + lemp->nstate; break;
3023 case ERROR: act = lemp->nstate + lemp->nrule; break;
3024 case ACCEPT: act = lemp->nstate + lemp->nrule + 1; break;
3025 default: act = -1; break;
3026 }
3027 return act;
3028}
3029
3030#define LINESIZE 1000
3031/* The next cluster of routines are for reading the template file
3032** and writing the results to the generated parser */
3033/* The first function transfers data from "in" to "out" until
3034** a line is seen which begins with "%%". The line number is
3035** tracked.
3036**
3037** if name!=0, then any word that begin with "Parse" is changed to
3038** begin with *name instead.
3039*/
icculus9e44cf12010-02-14 17:14:22 +00003040PRIVATE void tplt_xfer(char *name, FILE *in, FILE *out, int *lineno)
drh75897232000-05-29 14:26:00 +00003041{
3042 int i, iStart;
3043 char line[LINESIZE];
3044 while( fgets(line,LINESIZE,in) && (line[0]!='%' || line[1]!='%') ){
3045 (*lineno)++;
3046 iStart = 0;
3047 if( name ){
3048 for(i=0; line[i]; i++){
3049 if( line[i]=='P' && strncmp(&line[i],"Parse",5)==0
3050 && (i==0 || !isalpha(line[i-1]))
3051 ){
3052 if( i>iStart ) fprintf(out,"%.*s",i-iStart,&line[iStart]);
3053 fprintf(out,"%s",name);
3054 i += 4;
3055 iStart = i+1;
3056 }
3057 }
3058 }
3059 fprintf(out,"%s",&line[iStart]);
3060 }
3061}
3062
3063/* The next function finds the template file and opens it, returning
3064** a pointer to the opened file. */
icculus9e44cf12010-02-14 17:14:22 +00003065PRIVATE FILE *tplt_open(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003066{
3067 static char templatename[] = "lempar.c";
3068 char buf[1000];
3069 FILE *in;
3070 char *tpltname;
3071 char *cp;
3072
icculus3e143bd2010-02-14 00:48:49 +00003073 /* first, see if user specified a template filename on the command line. */
3074 if (user_templatename != 0) {
3075 if( access(user_templatename,004)==-1 ){
3076 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3077 user_templatename);
3078 lemp->errorcnt++;
3079 return 0;
3080 }
3081 in = fopen(user_templatename,"rb");
3082 if( in==0 ){
3083 fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename);
3084 lemp->errorcnt++;
3085 return 0;
3086 }
3087 return in;
3088 }
3089
drh75897232000-05-29 14:26:00 +00003090 cp = strrchr(lemp->filename,'.');
3091 if( cp ){
drh8b582012003-10-21 13:16:03 +00003092 sprintf(buf,"%.*s.lt",(int)(cp-lemp->filename),lemp->filename);
drh75897232000-05-29 14:26:00 +00003093 }else{
3094 sprintf(buf,"%s.lt",lemp->filename);
3095 }
3096 if( access(buf,004)==0 ){
3097 tpltname = buf;
drh960e8c62001-04-03 16:53:21 +00003098 }else if( access(templatename,004)==0 ){
3099 tpltname = templatename;
drh75897232000-05-29 14:26:00 +00003100 }else{
3101 tpltname = pathsearch(lemp->argv0,templatename,0);
3102 }
3103 if( tpltname==0 ){
3104 fprintf(stderr,"Can't find the parser driver template file \"%s\".\n",
3105 templatename);
3106 lemp->errorcnt++;
3107 return 0;
3108 }
drh2aa6ca42004-09-10 00:14:04 +00003109 in = fopen(tpltname,"rb");
drh75897232000-05-29 14:26:00 +00003110 if( in==0 ){
3111 fprintf(stderr,"Can't open the template file \"%s\".\n",templatename);
3112 lemp->errorcnt++;
3113 return 0;
3114 }
3115 return in;
3116}
3117
drhaf805ca2004-09-07 11:28:25 +00003118/* Print a #line directive line to the output file. */
icculus9e44cf12010-02-14 17:14:22 +00003119PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename)
drhaf805ca2004-09-07 11:28:25 +00003120{
3121 fprintf(out,"#line %d \"",lineno);
3122 while( *filename ){
3123 if( *filename == '\\' ) putc('\\',out);
3124 putc(*filename,out);
3125 filename++;
3126 }
3127 fprintf(out,"\"\n");
3128}
3129
drh75897232000-05-29 14:26:00 +00003130/* Print a string to the file and keep the linenumber up to date */
icculus9e44cf12010-02-14 17:14:22 +00003131PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno)
drh75897232000-05-29 14:26:00 +00003132{
3133 if( str==0 ) return;
drh75897232000-05-29 14:26:00 +00003134 while( *str ){
drh75897232000-05-29 14:26:00 +00003135 putc(*str,out);
shane58543932008-12-10 20:10:04 +00003136 if( *str=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003137 str++;
3138 }
drh9db55df2004-09-09 14:01:21 +00003139 if( str[-1]!='\n' ){
3140 putc('\n',out);
3141 (*lineno)++;
3142 }
shane58543932008-12-10 20:10:04 +00003143 if (!lemp->nolinenosflag) {
3144 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3145 }
drh75897232000-05-29 14:26:00 +00003146 return;
3147}
3148
3149/*
3150** The following routine emits code for the destructor for the
3151** symbol sp
3152*/
icculus9e44cf12010-02-14 17:14:22 +00003153void emit_destructor_code(
3154 FILE *out,
3155 struct symbol *sp,
3156 struct lemon *lemp,
3157 int *lineno
3158){
drhcc83b6e2004-04-23 23:38:42 +00003159 char *cp = 0;
drh75897232000-05-29 14:26:00 +00003160
drh75897232000-05-29 14:26:00 +00003161 if( sp->type==TERMINAL ){
3162 cp = lemp->tokendest;
3163 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003164 fprintf(out,"{\n"); (*lineno)++;
drh960e8c62001-04-03 16:53:21 +00003165 }else if( sp->destructor ){
drh75897232000-05-29 14:26:00 +00003166 cp = sp->destructor;
drha5808f32008-04-27 22:19:44 +00003167 fprintf(out,"{\n"); (*lineno)++;
shane58543932008-12-10 20:10:04 +00003168 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); }
drh960e8c62001-04-03 16:53:21 +00003169 }else if( lemp->vardest ){
3170 cp = lemp->vardest;
3171 if( cp==0 ) return;
drha5808f32008-04-27 22:19:44 +00003172 fprintf(out,"{\n"); (*lineno)++;
drhcc83b6e2004-04-23 23:38:42 +00003173 }else{
3174 assert( 0 ); /* Cannot happen */
drh75897232000-05-29 14:26:00 +00003175 }
3176 for(; *cp; cp++){
3177 if( *cp=='$' && cp[1]=='$' ){
3178 fprintf(out,"(yypminor->yy%d)",sp->dtnum);
3179 cp++;
3180 continue;
3181 }
shane58543932008-12-10 20:10:04 +00003182 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003183 fputc(*cp,out);
3184 }
shane58543932008-12-10 20:10:04 +00003185 fprintf(out,"\n"); (*lineno)++;
3186 if (!lemp->nolinenosflag) {
3187 (*lineno)++; tplt_linedir(out,*lineno,lemp->outname);
3188 }
3189 fprintf(out,"}\n"); (*lineno)++;
drh75897232000-05-29 14:26:00 +00003190 return;
3191}
3192
3193/*
drh960e8c62001-04-03 16:53:21 +00003194** Return TRUE (non-zero) if the given symbol has a destructor.
drh75897232000-05-29 14:26:00 +00003195*/
icculus9e44cf12010-02-14 17:14:22 +00003196int has_destructor(struct symbol *sp, struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00003197{
3198 int ret;
3199 if( sp->type==TERMINAL ){
3200 ret = lemp->tokendest!=0;
3201 }else{
drh960e8c62001-04-03 16:53:21 +00003202 ret = lemp->vardest!=0 || sp->destructor!=0;
drh75897232000-05-29 14:26:00 +00003203 }
3204 return ret;
3205}
3206
drh0bb132b2004-07-20 14:06:51 +00003207/*
3208** Append text to a dynamically allocated string. If zText is 0 then
3209** reset the string to be empty again. Always return the complete text
3210** of the string (which is overwritten with each call).
drh7ac25c72004-08-19 15:12:26 +00003211**
3212** n bytes of zText are stored. If n==0 then all of zText up to the first
3213** \000 terminator is stored. zText can contain up to two instances of
3214** %d. The values of p1 and p2 are written into the first and second
3215** %d.
3216**
3217** If n==-1, then the previous character is overwritten.
drh0bb132b2004-07-20 14:06:51 +00003218*/
icculus9e44cf12010-02-14 17:14:22 +00003219PRIVATE char *append_str(const char *zText, int n, int p1, int p2){
3220 static char empty[1] = { 0 };
drh0bb132b2004-07-20 14:06:51 +00003221 static char *z = 0;
3222 static int alloced = 0;
3223 static int used = 0;
drhaf805ca2004-09-07 11:28:25 +00003224 int c;
drh0bb132b2004-07-20 14:06:51 +00003225 char zInt[40];
drh0bb132b2004-07-20 14:06:51 +00003226 if( zText==0 ){
3227 used = 0;
3228 return z;
3229 }
drh7ac25c72004-08-19 15:12:26 +00003230 if( n<=0 ){
3231 if( n<0 ){
3232 used += n;
3233 assert( used>=0 );
3234 }
drh87cf1372008-08-13 20:09:06 +00003235 n = lemonStrlen(zText);
drh7ac25c72004-08-19 15:12:26 +00003236 }
drhdf609712010-11-23 20:55:27 +00003237 if( (int) (n+sizeof(zInt)*2+used) >= alloced ){
drh0bb132b2004-07-20 14:06:51 +00003238 alloced = n + sizeof(zInt)*2 + used + 200;
icculus9e44cf12010-02-14 17:14:22 +00003239 z = (char *) realloc(z, alloced);
drh0bb132b2004-07-20 14:06:51 +00003240 }
icculus9e44cf12010-02-14 17:14:22 +00003241 if( z==0 ) return empty;
drh0bb132b2004-07-20 14:06:51 +00003242 while( n-- > 0 ){
3243 c = *(zText++);
drh50489622006-10-13 12:25:29 +00003244 if( c=='%' && n>0 && zText[0]=='d' ){
drh0bb132b2004-07-20 14:06:51 +00003245 sprintf(zInt, "%d", p1);
3246 p1 = p2;
3247 strcpy(&z[used], zInt);
drh87cf1372008-08-13 20:09:06 +00003248 used += lemonStrlen(&z[used]);
drh0bb132b2004-07-20 14:06:51 +00003249 zText++;
3250 n--;
3251 }else{
3252 z[used++] = c;
3253 }
3254 }
3255 z[used] = 0;
3256 return z;
3257}
3258
3259/*
3260** zCode is a string that is the action associated with a rule. Expand
3261** the symbols in this string so that the refer to elements of the parser
drhaf805ca2004-09-07 11:28:25 +00003262** stack.
drh0bb132b2004-07-20 14:06:51 +00003263*/
drhaf805ca2004-09-07 11:28:25 +00003264PRIVATE void translate_code(struct lemon *lemp, struct rule *rp){
drh0bb132b2004-07-20 14:06:51 +00003265 char *cp, *xp;
3266 int i;
3267 char lhsused = 0; /* True if the LHS element has been used */
3268 char used[MAXRHS]; /* True for each RHS element which is used */
3269
3270 for(i=0; i<rp->nrhs; i++) used[i] = 0;
3271 lhsused = 0;
3272
drh19c9e562007-03-29 20:13:53 +00003273 if( rp->code==0 ){
icculus9e44cf12010-02-14 17:14:22 +00003274 static char newlinestr[2] = { '\n', '\0' };
3275 rp->code = newlinestr;
drh19c9e562007-03-29 20:13:53 +00003276 rp->line = rp->ruleline;
3277 }
3278
drh0bb132b2004-07-20 14:06:51 +00003279 append_str(0,0,0,0);
icculus9e44cf12010-02-14 17:14:22 +00003280
3281 /* This const cast is wrong but harmless, if we're careful. */
3282 for(cp=(char *)rp->code; *cp; cp++){
drh0bb132b2004-07-20 14:06:51 +00003283 if( isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')) ){
3284 char saved;
3285 for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++);
3286 saved = *xp;
3287 *xp = 0;
3288 if( rp->lhsalias && strcmp(cp,rp->lhsalias)==0 ){
drh7ac25c72004-08-19 15:12:26 +00003289 append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
drh0bb132b2004-07-20 14:06:51 +00003290 cp = xp;
3291 lhsused = 1;
3292 }else{
3293 for(i=0; i<rp->nrhs; i++){
3294 if( rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0 ){
drh7ac25c72004-08-19 15:12:26 +00003295 if( cp!=rp->code && cp[-1]=='@' ){
3296 /* If the argument is of the form @X then substituted
3297 ** the token number of X, not the value of X */
3298 append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
3299 }else{
drhfd405312005-11-06 04:06:59 +00003300 struct symbol *sp = rp->rhs[i];
3301 int dtnum;
3302 if( sp->type==MULTITERMINAL ){
3303 dtnum = sp->subsym[0]->dtnum;
3304 }else{
3305 dtnum = sp->dtnum;
3306 }
3307 append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, dtnum);
drh7ac25c72004-08-19 15:12:26 +00003308 }
drh0bb132b2004-07-20 14:06:51 +00003309 cp = xp;
3310 used[i] = 1;
3311 break;
3312 }
3313 }
3314 }
3315 *xp = saved;
3316 }
3317 append_str(cp, 1, 0, 0);
3318 } /* End loop */
3319
3320 /* Check to make sure the LHS has been used */
3321 if( rp->lhsalias && !lhsused ){
3322 ErrorMsg(lemp->filename,rp->ruleline,
3323 "Label \"%s\" for \"%s(%s)\" is never used.",
3324 rp->lhsalias,rp->lhs->name,rp->lhsalias);
3325 lemp->errorcnt++;
3326 }
3327
3328 /* Generate destructor code for RHS symbols which are not used in the
3329 ** reduce code */
3330 for(i=0; i<rp->nrhs; i++){
3331 if( rp->rhsalias[i] && !used[i] ){
3332 ErrorMsg(lemp->filename,rp->ruleline,
3333 "Label %s for \"%s(%s)\" is never used.",
3334 rp->rhsalias[i],rp->rhs[i]->name,rp->rhsalias[i]);
3335 lemp->errorcnt++;
3336 }else if( rp->rhsalias[i]==0 ){
3337 if( has_destructor(rp->rhs[i],lemp) ){
drh639efd02008-08-13 20:04:29 +00003338 append_str(" yy_destructor(yypParser,%d,&yymsp[%d].minor);\n", 0,
drh0bb132b2004-07-20 14:06:51 +00003339 rp->rhs[i]->index,i-rp->nrhs+1);
3340 }else{
3341 /* No destructor defined for this term */
3342 }
3343 }
3344 }
drh61e339a2007-01-16 03:09:02 +00003345 if( rp->code ){
3346 cp = append_str(0,0,0,0);
3347 rp->code = Strsafe(cp?cp:"");
3348 }
drh0bb132b2004-07-20 14:06:51 +00003349}
3350
drh75897232000-05-29 14:26:00 +00003351/*
3352** Generate code which executes when the rule "rp" is reduced. Write
3353** the code to "out". Make sure lineno stays up-to-date.
3354*/
icculus9e44cf12010-02-14 17:14:22 +00003355PRIVATE void emit_code(
3356 FILE *out,
3357 struct rule *rp,
3358 struct lemon *lemp,
3359 int *lineno
3360){
3361 const char *cp;
drh75897232000-05-29 14:26:00 +00003362
3363 /* Generate code to do the reduce action */
3364 if( rp->code ){
shane58543932008-12-10 20:10:04 +00003365 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); }
drhaf805ca2004-09-07 11:28:25 +00003366 fprintf(out,"{%s",rp->code);
drh75897232000-05-29 14:26:00 +00003367 for(cp=rp->code; *cp; cp++){
shane58543932008-12-10 20:10:04 +00003368 if( *cp=='\n' ) (*lineno)++;
drh75897232000-05-29 14:26:00 +00003369 } /* End loop */
shane58543932008-12-10 20:10:04 +00003370 fprintf(out,"}\n"); (*lineno)++;
3371 if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); }
drh75897232000-05-29 14:26:00 +00003372 } /* End if( rp->code ) */
3373
drh75897232000-05-29 14:26:00 +00003374 return;
3375}
3376
3377/*
3378** Print the definition of the union used for the parser's data stack.
3379** This union contains fields for every possible data type for tokens
3380** and nonterminals. In the process of computing and printing this
3381** union, also set the ".dtnum" field of every terminal and nonterminal
3382** symbol.
3383*/
icculus9e44cf12010-02-14 17:14:22 +00003384void print_stack_union(
3385 FILE *out, /* The output stream */
3386 struct lemon *lemp, /* The main info structure for this parser */
3387 int *plineno, /* Pointer to the line number */
3388 int mhflag /* True if generating makeheaders output */
3389){
drh75897232000-05-29 14:26:00 +00003390 int lineno = *plineno; /* The line number of the output */
3391 char **types; /* A hash table of datatypes */
3392 int arraysize; /* Size of the "types" array */
3393 int maxdtlength; /* Maximum length of any ".datatype" field. */
3394 char *stddt; /* Standardized name for a datatype */
3395 int i,j; /* Loop counters */
3396 int hash; /* For hashing the name of a type */
icculus9e44cf12010-02-14 17:14:22 +00003397 const char *name; /* Name of the parser */
drh75897232000-05-29 14:26:00 +00003398
3399 /* Allocate and initialize types[] and allocate stddt[] */
3400 arraysize = lemp->nsymbol * 2;
drh9892c5d2007-12-21 00:02:11 +00003401 types = (char**)calloc( arraysize, sizeof(char*) );
drh070d4222011-06-02 15:48:51 +00003402 if( types==0 ){
3403 fprintf(stderr,"Out of memory.\n");
3404 exit(1);
3405 }
drh75897232000-05-29 14:26:00 +00003406 for(i=0; i<arraysize; i++) types[i] = 0;
3407 maxdtlength = 0;
drh960e8c62001-04-03 16:53:21 +00003408 if( lemp->vartype ){
drh87cf1372008-08-13 20:09:06 +00003409 maxdtlength = lemonStrlen(lemp->vartype);
drh960e8c62001-04-03 16:53:21 +00003410 }
drh75897232000-05-29 14:26:00 +00003411 for(i=0; i<lemp->nsymbol; i++){
3412 int len;
3413 struct symbol *sp = lemp->symbols[i];
3414 if( sp->datatype==0 ) continue;
drh87cf1372008-08-13 20:09:06 +00003415 len = lemonStrlen(sp->datatype);
drh75897232000-05-29 14:26:00 +00003416 if( len>maxdtlength ) maxdtlength = len;
3417 }
3418 stddt = (char*)malloc( maxdtlength*2 + 1 );
drh070d4222011-06-02 15:48:51 +00003419 if( stddt==0 ){
drh75897232000-05-29 14:26:00 +00003420 fprintf(stderr,"Out of memory.\n");
3421 exit(1);
3422 }
3423
3424 /* Build a hash table of datatypes. The ".dtnum" field of each symbol
3425 ** is filled in with the hash index plus 1. A ".dtnum" value of 0 is
drh960e8c62001-04-03 16:53:21 +00003426 ** used for terminal symbols. If there is no %default_type defined then
3427 ** 0 is also used as the .dtnum value for nonterminals which do not specify
3428 ** a datatype using the %type directive.
3429 */
drh75897232000-05-29 14:26:00 +00003430 for(i=0; i<lemp->nsymbol; i++){
3431 struct symbol *sp = lemp->symbols[i];
3432 char *cp;
3433 if( sp==lemp->errsym ){
3434 sp->dtnum = arraysize+1;
3435 continue;
3436 }
drh960e8c62001-04-03 16:53:21 +00003437 if( sp->type!=NONTERMINAL || (sp->datatype==0 && lemp->vartype==0) ){
drh75897232000-05-29 14:26:00 +00003438 sp->dtnum = 0;
3439 continue;
3440 }
3441 cp = sp->datatype;
drh960e8c62001-04-03 16:53:21 +00003442 if( cp==0 ) cp = lemp->vartype;
drh75897232000-05-29 14:26:00 +00003443 j = 0;
3444 while( isspace(*cp) ) cp++;
3445 while( *cp ) stddt[j++] = *cp++;
3446 while( j>0 && isspace(stddt[j-1]) ) j--;
3447 stddt[j] = 0;
drh02368c92009-04-05 15:18:02 +00003448 if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){
drh32c4d742008-07-01 16:34:49 +00003449 sp->dtnum = 0;
3450 continue;
3451 }
drh75897232000-05-29 14:26:00 +00003452 hash = 0;
3453 for(j=0; stddt[j]; j++){
3454 hash = hash*53 + stddt[j];
3455 }
drh3b2129c2003-05-13 00:34:21 +00003456 hash = (hash & 0x7fffffff)%arraysize;
drh75897232000-05-29 14:26:00 +00003457 while( types[hash] ){
3458 if( strcmp(types[hash],stddt)==0 ){
3459 sp->dtnum = hash + 1;
3460 break;
3461 }
3462 hash++;
3463 if( hash>=arraysize ) hash = 0;
3464 }
3465 if( types[hash]==0 ){
3466 sp->dtnum = hash + 1;
drh87cf1372008-08-13 20:09:06 +00003467 types[hash] = (char*)malloc( lemonStrlen(stddt)+1 );
drh75897232000-05-29 14:26:00 +00003468 if( types[hash]==0 ){
3469 fprintf(stderr,"Out of memory.\n");
3470 exit(1);
3471 }
3472 strcpy(types[hash],stddt);
3473 }
3474 }
3475
3476 /* Print out the definition of YYTOKENTYPE and YYMINORTYPE */
3477 name = lemp->name ? lemp->name : "Parse";
3478 lineno = *plineno;
3479 if( mhflag ){ fprintf(out,"#if INTERFACE\n"); lineno++; }
3480 fprintf(out,"#define %sTOKENTYPE %s\n",name,
3481 lemp->tokentype?lemp->tokentype:"void*"); lineno++;
3482 if( mhflag ){ fprintf(out,"#endif\n"); lineno++; }
3483 fprintf(out,"typedef union {\n"); lineno++;
drh15b024c2008-12-11 02:20:43 +00003484 fprintf(out," int yyinit;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003485 fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++;
3486 for(i=0; i<arraysize; i++){
3487 if( types[i]==0 ) continue;
3488 fprintf(out," %s yy%d;\n",types[i],i+1); lineno++;
3489 free(types[i]);
3490 }
drhc4dd3fd2008-01-22 01:48:05 +00003491 if( lemp->errsym->useCnt ){
3492 fprintf(out," int yy%d;\n",lemp->errsym->dtnum); lineno++;
3493 }
drh75897232000-05-29 14:26:00 +00003494 free(stddt);
3495 free(types);
3496 fprintf(out,"} YYMINORTYPE;\n"); lineno++;
3497 *plineno = lineno;
3498}
3499
drhb29b0a52002-02-23 19:39:46 +00003500/*
3501** Return the name of a C datatype able to represent values between
drh8b582012003-10-21 13:16:03 +00003502** lwr and upr, inclusive.
drhb29b0a52002-02-23 19:39:46 +00003503*/
drh8b582012003-10-21 13:16:03 +00003504static const char *minimum_size_type(int lwr, int upr){
3505 if( lwr>=0 ){
3506 if( upr<=255 ){
3507 return "unsigned char";
3508 }else if( upr<65535 ){
3509 return "unsigned short int";
3510 }else{
3511 return "unsigned int";
3512 }
3513 }else if( lwr>=-127 && upr<=127 ){
3514 return "signed char";
3515 }else if( lwr>=-32767 && upr<32767 ){
3516 return "short";
drhb29b0a52002-02-23 19:39:46 +00003517 }else{
drh8b582012003-10-21 13:16:03 +00003518 return "int";
drhb29b0a52002-02-23 19:39:46 +00003519 }
3520}
3521
drhfdbf9282003-10-21 16:34:41 +00003522/*
3523** Each state contains a set of token transaction and a set of
3524** nonterminal transactions. Each of these sets makes an instance
3525** of the following structure. An array of these structures is used
3526** to order the creation of entries in the yy_action[] table.
3527*/
3528struct axset {
3529 struct state *stp; /* A pointer to a state */
3530 int isTkn; /* True to use tokens. False for non-terminals */
3531 int nAction; /* Number of actions */
drhe594bc32009-11-03 13:02:25 +00003532 int iOrder; /* Original order of action sets */
drhfdbf9282003-10-21 16:34:41 +00003533};
3534
3535/*
3536** Compare to axset structures for sorting purposes
3537*/
3538static int axset_compare(const void *a, const void *b){
3539 struct axset *p1 = (struct axset*)a;
3540 struct axset *p2 = (struct axset*)b;
drhe594bc32009-11-03 13:02:25 +00003541 int c;
3542 c = p2->nAction - p1->nAction;
3543 if( c==0 ){
3544 c = p2->iOrder - p1->iOrder;
3545 }
3546 assert( c!=0 || p1==p2 );
3547 return c;
drhfdbf9282003-10-21 16:34:41 +00003548}
3549
drhc4dd3fd2008-01-22 01:48:05 +00003550/*
3551** Write text on "out" that describes the rule "rp".
3552*/
3553static void writeRuleText(FILE *out, struct rule *rp){
3554 int j;
3555 fprintf(out,"%s ::=", rp->lhs->name);
3556 for(j=0; j<rp->nrhs; j++){
3557 struct symbol *sp = rp->rhs[j];
3558 fprintf(out," %s", sp->name);
3559 if( sp->type==MULTITERMINAL ){
3560 int k;
3561 for(k=1; k<sp->nsubsym; k++){
3562 fprintf(out,"|%s",sp->subsym[k]->name);
3563 }
3564 }
3565 }
3566}
3567
3568
drh75897232000-05-29 14:26:00 +00003569/* Generate C source code for the parser */
icculus9e44cf12010-02-14 17:14:22 +00003570void ReportTable(
3571 struct lemon *lemp,
3572 int mhflag /* Output in makeheaders format if true */
3573){
drh75897232000-05-29 14:26:00 +00003574 FILE *out, *in;
3575 char line[LINESIZE];
3576 int lineno;
3577 struct state *stp;
3578 struct action *ap;
3579 struct rule *rp;
drh8b582012003-10-21 13:16:03 +00003580 struct acttab *pActtab;
icculusa3191192010-02-17 05:40:34 +00003581 int i, j, n;
icculus9e44cf12010-02-14 17:14:22 +00003582 const char *name;
drh8b582012003-10-21 13:16:03 +00003583 int mnTknOfst, mxTknOfst;
3584 int mnNtOfst, mxNtOfst;
drhfdbf9282003-10-21 16:34:41 +00003585 struct axset *ax;
drh75897232000-05-29 14:26:00 +00003586
3587 in = tplt_open(lemp);
3588 if( in==0 ) return;
drh2aa6ca42004-09-10 00:14:04 +00003589 out = file_open(lemp,".c","wb");
drh75897232000-05-29 14:26:00 +00003590 if( out==0 ){
3591 fclose(in);
3592 return;
3593 }
3594 lineno = 1;
3595 tplt_xfer(lemp->name,in,out,&lineno);
3596
3597 /* Generate the include code, if any */
drha5808f32008-04-27 22:19:44 +00003598 tplt_print(out,lemp,lemp->include,&lineno);
drh75897232000-05-29 14:26:00 +00003599 if( mhflag ){
3600 char *name = file_makename(lemp, ".h");
3601 fprintf(out,"#include \"%s\"\n", name); lineno++;
3602 free(name);
3603 }
3604 tplt_xfer(lemp->name,in,out,&lineno);
3605
3606 /* Generate #defines for all tokens */
3607 if( mhflag ){
icculus9e44cf12010-02-14 17:14:22 +00003608 const char *prefix;
drh75897232000-05-29 14:26:00 +00003609 fprintf(out,"#if INTERFACE\n"); lineno++;
3610 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
3611 else prefix = "";
3612 for(i=1; i<lemp->nterminal; i++){
3613 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
3614 lineno++;
3615 }
3616 fprintf(out,"#endif\n"); lineno++;
3617 }
3618 tplt_xfer(lemp->name,in,out,&lineno);
3619
3620 /* Generate the defines */
drh75897232000-05-29 14:26:00 +00003621 fprintf(out,"#define YYCODETYPE %s\n",
drh8a415d32009-06-12 13:53:51 +00003622 minimum_size_type(0, lemp->nsymbol+1)); lineno++;
drh75897232000-05-29 14:26:00 +00003623 fprintf(out,"#define YYNOCODE %d\n",lemp->nsymbol+1); lineno++;
3624 fprintf(out,"#define YYACTIONTYPE %s\n",
drh8b582012003-10-21 13:16:03 +00003625 minimum_size_type(0, lemp->nstate+lemp->nrule+5)); lineno++;
drhe09daa92006-06-10 13:29:31 +00003626 if( lemp->wildcard ){
3627 fprintf(out,"#define YYWILDCARD %d\n",
3628 lemp->wildcard->index); lineno++;
3629 }
drh75897232000-05-29 14:26:00 +00003630 print_stack_union(out,lemp,&lineno,mhflag);
drhca44b5a2007-02-22 23:06:58 +00003631 fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003632 if( lemp->stacksize ){
drh75897232000-05-29 14:26:00 +00003633 fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++;
3634 }else{
3635 fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++;
3636 }
drhca44b5a2007-02-22 23:06:58 +00003637 fprintf(out, "#endif\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003638 if( mhflag ){
3639 fprintf(out,"#if INTERFACE\n"); lineno++;
3640 }
3641 name = lemp->name ? lemp->name : "Parse";
3642 if( lemp->arg && lemp->arg[0] ){
3643 int i;
drh87cf1372008-08-13 20:09:06 +00003644 i = lemonStrlen(lemp->arg);
drhb1edd012000-06-02 18:52:12 +00003645 while( i>=1 && isspace(lemp->arg[i-1]) ) i--;
3646 while( i>=1 && (isalnum(lemp->arg[i-1]) || lemp->arg[i-1]=='_') ) i--;
drh1f245e42002-03-11 13:55:50 +00003647 fprintf(out,"#define %sARG_SDECL %s;\n",name,lemp->arg); lineno++;
3648 fprintf(out,"#define %sARG_PDECL ,%s\n",name,lemp->arg); lineno++;
3649 fprintf(out,"#define %sARG_FETCH %s = yypParser->%s\n",
3650 name,lemp->arg,&lemp->arg[i]); lineno++;
3651 fprintf(out,"#define %sARG_STORE yypParser->%s = %s\n",
3652 name,&lemp->arg[i],&lemp->arg[i]); lineno++;
drh75897232000-05-29 14:26:00 +00003653 }else{
drh1f245e42002-03-11 13:55:50 +00003654 fprintf(out,"#define %sARG_SDECL\n",name); lineno++;
3655 fprintf(out,"#define %sARG_PDECL\n",name); lineno++;
3656 fprintf(out,"#define %sARG_FETCH\n",name); lineno++;
3657 fprintf(out,"#define %sARG_STORE\n",name); lineno++;
drh75897232000-05-29 14:26:00 +00003658 }
3659 if( mhflag ){
3660 fprintf(out,"#endif\n"); lineno++;
3661 }
3662 fprintf(out,"#define YYNSTATE %d\n",lemp->nstate); lineno++;
3663 fprintf(out,"#define YYNRULE %d\n",lemp->nrule); lineno++;
drhc4dd3fd2008-01-22 01:48:05 +00003664 if( lemp->errsym->useCnt ){
3665 fprintf(out,"#define YYERRORSYMBOL %d\n",lemp->errsym->index); lineno++;
3666 fprintf(out,"#define YYERRSYMDT yy%d\n",lemp->errsym->dtnum); lineno++;
3667 }
drh0bd1f4e2002-06-06 18:54:39 +00003668 if( lemp->has_fallback ){
3669 fprintf(out,"#define YYFALLBACK 1\n"); lineno++;
3670 }
drh75897232000-05-29 14:26:00 +00003671 tplt_xfer(lemp->name,in,out,&lineno);
3672
drh8b582012003-10-21 13:16:03 +00003673 /* Generate the action table and its associates:
drh75897232000-05-29 14:26:00 +00003674 **
drh8b582012003-10-21 13:16:03 +00003675 ** yy_action[] A single table containing all actions.
3676 ** yy_lookahead[] A table containing the lookahead for each entry in
3677 ** yy_action. Used to detect hash collisions.
3678 ** yy_shift_ofst[] For each state, the offset into yy_action for
3679 ** shifting terminals.
3680 ** yy_reduce_ofst[] For each state, the offset into yy_action for
3681 ** shifting non-terminals after a reduce.
3682 ** yy_default[] Default action for each state.
drh75897232000-05-29 14:26:00 +00003683 */
drh75897232000-05-29 14:26:00 +00003684
drh8b582012003-10-21 13:16:03 +00003685 /* Compute the actions on all states and count them up */
icculus9e44cf12010-02-14 17:14:22 +00003686 ax = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0]));
drhfdbf9282003-10-21 16:34:41 +00003687 if( ax==0 ){
3688 fprintf(stderr,"malloc failed\n");
3689 exit(1);
3690 }
drh75897232000-05-29 14:26:00 +00003691 for(i=0; i<lemp->nstate; i++){
drh75897232000-05-29 14:26:00 +00003692 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003693 ax[i*2].stp = stp;
3694 ax[i*2].isTkn = 1;
3695 ax[i*2].nAction = stp->nTknAct;
3696 ax[i*2+1].stp = stp;
3697 ax[i*2+1].isTkn = 0;
3698 ax[i*2+1].nAction = stp->nNtAct;
drh75897232000-05-29 14:26:00 +00003699 }
drh8b582012003-10-21 13:16:03 +00003700 mxTknOfst = mnTknOfst = 0;
3701 mxNtOfst = mnNtOfst = 0;
3702
drhfdbf9282003-10-21 16:34:41 +00003703 /* Compute the action table. In order to try to keep the size of the
3704 ** action table to a minimum, the heuristic of placing the largest action
3705 ** sets first is used.
drh8b582012003-10-21 13:16:03 +00003706 */
drhe594bc32009-11-03 13:02:25 +00003707 for(i=0; i<lemp->nstate*2; i++) ax[i].iOrder = i;
drhfdbf9282003-10-21 16:34:41 +00003708 qsort(ax, lemp->nstate*2, sizeof(ax[0]), axset_compare);
drh8b582012003-10-21 13:16:03 +00003709 pActtab = acttab_alloc();
drhfdbf9282003-10-21 16:34:41 +00003710 for(i=0; i<lemp->nstate*2 && ax[i].nAction>0; i++){
3711 stp = ax[i].stp;
3712 if( ax[i].isTkn ){
3713 for(ap=stp->ap; ap; ap=ap->next){
3714 int action;
3715 if( ap->sp->index>=lemp->nterminal ) continue;
3716 action = compute_action(lemp, ap);
3717 if( action<0 ) continue;
3718 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003719 }
drhfdbf9282003-10-21 16:34:41 +00003720 stp->iTknOfst = acttab_insert(pActtab);
3721 if( stp->iTknOfst<mnTknOfst ) mnTknOfst = stp->iTknOfst;
3722 if( stp->iTknOfst>mxTknOfst ) mxTknOfst = stp->iTknOfst;
3723 }else{
3724 for(ap=stp->ap; ap; ap=ap->next){
3725 int action;
3726 if( ap->sp->index<lemp->nterminal ) continue;
3727 if( ap->sp->index==lemp->nsymbol ) continue;
3728 action = compute_action(lemp, ap);
3729 if( action<0 ) continue;
3730 acttab_action(pActtab, ap->sp->index, action);
drh8b582012003-10-21 13:16:03 +00003731 }
drhfdbf9282003-10-21 16:34:41 +00003732 stp->iNtOfst = acttab_insert(pActtab);
3733 if( stp->iNtOfst<mnNtOfst ) mnNtOfst = stp->iNtOfst;
3734 if( stp->iNtOfst>mxNtOfst ) mxNtOfst = stp->iNtOfst;
drh8b582012003-10-21 13:16:03 +00003735 }
3736 }
drhfdbf9282003-10-21 16:34:41 +00003737 free(ax);
drh8b582012003-10-21 13:16:03 +00003738
3739 /* Output the yy_action table */
drh8b582012003-10-21 13:16:03 +00003740 n = acttab_size(pActtab);
drhf16371d2009-11-03 19:18:31 +00003741 fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++;
3742 fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003743 for(i=j=0; i<n; i++){
3744 int action = acttab_yyaction(pActtab, i);
drhe0479212007-01-12 23:09:23 +00003745 if( action<0 ) action = lemp->nstate + lemp->nrule + 2;
drhfdbf9282003-10-21 16:34:41 +00003746 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003747 fprintf(out, " %4d,", action);
3748 if( j==9 || i==n-1 ){
3749 fprintf(out, "\n"); lineno++;
3750 j = 0;
3751 }else{
3752 j++;
3753 }
3754 }
3755 fprintf(out, "};\n"); lineno++;
3756
3757 /* Output the yy_lookahead table */
drh57196282004-10-06 15:41:16 +00003758 fprintf(out,"static const YYCODETYPE yy_lookahead[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003759 for(i=j=0; i<n; i++){
3760 int la = acttab_yylookahead(pActtab, i);
3761 if( la<0 ) la = lemp->nsymbol;
drhfdbf9282003-10-21 16:34:41 +00003762 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003763 fprintf(out, " %4d,", la);
3764 if( j==9 || i==n-1 ){
3765 fprintf(out, "\n"); lineno++;
3766 j = 0;
3767 }else{
3768 j++;
3769 }
3770 }
3771 fprintf(out, "};\n"); lineno++;
3772
3773 /* Output the yy_shift_ofst[] table */
3774 fprintf(out, "#define YY_SHIFT_USE_DFLT (%d)\n", mnTknOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003775 n = lemp->nstate;
3776 while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003777 fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++;
3778 fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++;
3779 fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003780 fprintf(out, "static const %s yy_shift_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003781 minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003782 for(i=j=0; i<n; i++){
3783 int ofst;
3784 stp = lemp->sorted[i];
3785 ofst = stp->iTknOfst;
3786 if( ofst==NO_OFFSET ) ofst = mnTknOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003787 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003788 fprintf(out, " %4d,", ofst);
3789 if( j==9 || i==n-1 ){
3790 fprintf(out, "\n"); lineno++;
3791 j = 0;
3792 }else{
3793 j++;
3794 }
3795 }
3796 fprintf(out, "};\n"); lineno++;
3797
3798 /* Output the yy_reduce_ofst[] table */
3799 fprintf(out, "#define YY_REDUCE_USE_DFLT (%d)\n", mnNtOfst-1); lineno++;
drhada354d2005-11-05 15:03:59 +00003800 n = lemp->nstate;
3801 while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--;
drhf16371d2009-11-03 19:18:31 +00003802 fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++;
3803 fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++;
3804 fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++;
drh57196282004-10-06 15:41:16 +00003805 fprintf(out, "static const %s yy_reduce_ofst[] = {\n",
drh8b582012003-10-21 13:16:03 +00003806 minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++;
drh8b582012003-10-21 13:16:03 +00003807 for(i=j=0; i<n; i++){
3808 int ofst;
3809 stp = lemp->sorted[i];
3810 ofst = stp->iNtOfst;
3811 if( ofst==NO_OFFSET ) ofst = mnNtOfst - 1;
drhfdbf9282003-10-21 16:34:41 +00003812 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003813 fprintf(out, " %4d,", ofst);
3814 if( j==9 || i==n-1 ){
3815 fprintf(out, "\n"); lineno++;
3816 j = 0;
3817 }else{
3818 j++;
3819 }
3820 }
3821 fprintf(out, "};\n"); lineno++;
3822
3823 /* Output the default action table */
drh57196282004-10-06 15:41:16 +00003824 fprintf(out, "static const YYACTIONTYPE yy_default[] = {\n"); lineno++;
drh8b582012003-10-21 13:16:03 +00003825 n = lemp->nstate;
3826 for(i=j=0; i<n; i++){
3827 stp = lemp->sorted[i];
drhfdbf9282003-10-21 16:34:41 +00003828 if( j==0 ) fprintf(out," /* %5d */ ", i);
drh8b582012003-10-21 13:16:03 +00003829 fprintf(out, " %4d,", stp->iDflt);
3830 if( j==9 || i==n-1 ){
3831 fprintf(out, "\n"); lineno++;
3832 j = 0;
3833 }else{
3834 j++;
3835 }
3836 }
3837 fprintf(out, "};\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003838 tplt_xfer(lemp->name,in,out,&lineno);
3839
drh0bd1f4e2002-06-06 18:54:39 +00003840 /* Generate the table of fallback tokens.
3841 */
3842 if( lemp->has_fallback ){
drh1441f3e2009-06-12 12:50:50 +00003843 int mx = lemp->nterminal - 1;
3844 while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; }
3845 for(i=0; i<=mx; i++){
drh0bd1f4e2002-06-06 18:54:39 +00003846 struct symbol *p = lemp->symbols[i];
3847 if( p->fallback==0 ){
3848 fprintf(out, " 0, /* %10s => nothing */\n", p->name);
3849 }else{
3850 fprintf(out, " %3d, /* %10s => %s */\n", p->fallback->index,
3851 p->name, p->fallback->name);
3852 }
3853 lineno++;
3854 }
3855 }
3856 tplt_xfer(lemp->name, in, out, &lineno);
3857
3858 /* Generate a table containing the symbolic name of every symbol
3859 */
drh75897232000-05-29 14:26:00 +00003860 for(i=0; i<lemp->nsymbol; i++){
3861 sprintf(line,"\"%s\",",lemp->symbols[i]->name);
3862 fprintf(out," %-15s",line);
3863 if( (i&3)==3 ){ fprintf(out,"\n"); lineno++; }
3864 }
3865 if( (i&3)!=0 ){ fprintf(out,"\n"); lineno++; }
3866 tplt_xfer(lemp->name,in,out,&lineno);
3867
drh0bd1f4e2002-06-06 18:54:39 +00003868 /* Generate a table containing a text string that describes every
drh34ff57b2008-07-14 12:27:51 +00003869 ** rule in the rule set of the grammar. This information is used
drh0bd1f4e2002-06-06 18:54:39 +00003870 ** when tracing REDUCE actions.
3871 */
3872 for(i=0, rp=lemp->rule; rp; rp=rp->next, i++){
3873 assert( rp->index==i );
drhc4dd3fd2008-01-22 01:48:05 +00003874 fprintf(out," /* %3d */ \"", i);
3875 writeRuleText(out, rp);
drh0bd1f4e2002-06-06 18:54:39 +00003876 fprintf(out,"\",\n"); lineno++;
3877 }
3878 tplt_xfer(lemp->name,in,out,&lineno);
3879
drh75897232000-05-29 14:26:00 +00003880 /* Generate code which executes every time a symbol is popped from
3881 ** the stack while processing errors or while destroying the parser.
drh0bd1f4e2002-06-06 18:54:39 +00003882 ** (In other words, generate the %destructor actions)
3883 */
drh75897232000-05-29 14:26:00 +00003884 if( lemp->tokendest ){
drh4dc8ef52008-07-01 17:13:57 +00003885 int once = 1;
drh75897232000-05-29 14:26:00 +00003886 for(i=0; i<lemp->nsymbol; i++){
3887 struct symbol *sp = lemp->symbols[i];
3888 if( sp==0 || sp->type!=TERMINAL ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003889 if( once ){
3890 fprintf(out, " /* TERMINAL Destructor */\n"); lineno++;
3891 once = 0;
3892 }
drhc53eed12009-06-12 17:46:19 +00003893 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh75897232000-05-29 14:26:00 +00003894 }
3895 for(i=0; i<lemp->nsymbol && lemp->symbols[i]->type!=TERMINAL; i++);
3896 if( i<lemp->nsymbol ){
3897 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3898 fprintf(out," break;\n"); lineno++;
3899 }
3900 }
drh8d659732005-01-13 23:54:06 +00003901 if( lemp->vardest ){
3902 struct symbol *dflt_sp = 0;
drh4dc8ef52008-07-01 17:13:57 +00003903 int once = 1;
drh8d659732005-01-13 23:54:06 +00003904 for(i=0; i<lemp->nsymbol; i++){
3905 struct symbol *sp = lemp->symbols[i];
3906 if( sp==0 || sp->type==TERMINAL ||
3907 sp->index<=0 || sp->destructor!=0 ) continue;
drh4dc8ef52008-07-01 17:13:57 +00003908 if( once ){
3909 fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++;
3910 once = 0;
3911 }
drhc53eed12009-06-12 17:46:19 +00003912 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh8d659732005-01-13 23:54:06 +00003913 dflt_sp = sp;
3914 }
3915 if( dflt_sp!=0 ){
3916 emit_destructor_code(out,dflt_sp,lemp,&lineno);
drh8d659732005-01-13 23:54:06 +00003917 }
drh4dc8ef52008-07-01 17:13:57 +00003918 fprintf(out," break;\n"); lineno++;
drh8d659732005-01-13 23:54:06 +00003919 }
drh75897232000-05-29 14:26:00 +00003920 for(i=0; i<lemp->nsymbol; i++){
3921 struct symbol *sp = lemp->symbols[i];
3922 if( sp==0 || sp->type==TERMINAL || sp->destructor==0 ) continue;
drh75013012009-06-12 15:47:34 +00003923 fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003924
3925 /* Combine duplicate destructors into a single case */
3926 for(j=i+1; j<lemp->nsymbol; j++){
3927 struct symbol *sp2 = lemp->symbols[j];
3928 if( sp2 && sp2->type!=TERMINAL && sp2->destructor
3929 && sp2->dtnum==sp->dtnum
3930 && strcmp(sp->destructor,sp2->destructor)==0 ){
drhc53eed12009-06-12 17:46:19 +00003931 fprintf(out," case %d: /* %s */\n",
3932 sp2->index, sp2->name); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003933 sp2->destructor = 0;
3934 }
3935 }
3936
drh75897232000-05-29 14:26:00 +00003937 emit_destructor_code(out,lemp->symbols[i],lemp,&lineno);
3938 fprintf(out," break;\n"); lineno++;
3939 }
drh75897232000-05-29 14:26:00 +00003940 tplt_xfer(lemp->name,in,out,&lineno);
3941
3942 /* Generate code which executes whenever the parser stack overflows */
drha5808f32008-04-27 22:19:44 +00003943 tplt_print(out,lemp,lemp->overflow,&lineno);
drh75897232000-05-29 14:26:00 +00003944 tplt_xfer(lemp->name,in,out,&lineno);
3945
3946 /* Generate the table of rule information
3947 **
3948 ** Note: This code depends on the fact that rules are number
3949 ** sequentually beginning with 0.
3950 */
3951 for(rp=lemp->rule; rp; rp=rp->next){
3952 fprintf(out," { %d, %d },\n",rp->lhs->index,rp->nrhs); lineno++;
3953 }
3954 tplt_xfer(lemp->name,in,out,&lineno);
3955
3956 /* Generate code which execution during each REDUCE action */
3957 for(rp=lemp->rule; rp; rp=rp->next){
drh61e339a2007-01-16 03:09:02 +00003958 translate_code(lemp, rp);
drh0bb132b2004-07-20 14:06:51 +00003959 }
drhc53eed12009-06-12 17:46:19 +00003960 /* First output rules other than the default: rule */
drh0bb132b2004-07-20 14:06:51 +00003961 for(rp=lemp->rule; rp; rp=rp->next){
drhc53eed12009-06-12 17:46:19 +00003962 struct rule *rp2; /* Other rules with the same action */
drh0bb132b2004-07-20 14:06:51 +00003963 if( rp->code==0 ) continue;
drhc53eed12009-06-12 17:46:19 +00003964 if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */
drhc4dd3fd2008-01-22 01:48:05 +00003965 fprintf(out," case %d: /* ", rp->index);
3966 writeRuleText(out, rp);
3967 fprintf(out, " */\n"); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003968 for(rp2=rp->next; rp2; rp2=rp2->next){
3969 if( rp2->code==rp->code ){
drhc4dd3fd2008-01-22 01:48:05 +00003970 fprintf(out," case %d: /* ", rp2->index);
3971 writeRuleText(out, rp2);
drh8a415d32009-06-12 13:53:51 +00003972 fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++;
drh0bb132b2004-07-20 14:06:51 +00003973 rp2->code = 0;
3974 }
3975 }
drh75897232000-05-29 14:26:00 +00003976 emit_code(out,rp,lemp,&lineno);
3977 fprintf(out," break;\n"); lineno++;
drhc53eed12009-06-12 17:46:19 +00003978 rp->code = 0;
drh75897232000-05-29 14:26:00 +00003979 }
drhc53eed12009-06-12 17:46:19 +00003980 /* Finally, output the default: rule. We choose as the default: all
3981 ** empty actions. */
3982 fprintf(out," default:\n"); lineno++;
3983 for(rp=lemp->rule; rp; rp=rp->next){
3984 if( rp->code==0 ) continue;
3985 assert( rp->code[0]=='\n' && rp->code[1]==0 );
3986 fprintf(out," /* (%d) ", rp->index);
3987 writeRuleText(out, rp);
3988 fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); lineno++;
3989 }
3990 fprintf(out," break;\n"); lineno++;
drh75897232000-05-29 14:26:00 +00003991 tplt_xfer(lemp->name,in,out,&lineno);
3992
3993 /* Generate code which executes if a parse fails */
drha5808f32008-04-27 22:19:44 +00003994 tplt_print(out,lemp,lemp->failure,&lineno);
drh75897232000-05-29 14:26:00 +00003995 tplt_xfer(lemp->name,in,out,&lineno);
3996
3997 /* Generate code which executes when a syntax error occurs */
drha5808f32008-04-27 22:19:44 +00003998 tplt_print(out,lemp,lemp->error,&lineno);
drh75897232000-05-29 14:26:00 +00003999 tplt_xfer(lemp->name,in,out,&lineno);
4000
4001 /* Generate code which executes when the parser accepts its input */
drha5808f32008-04-27 22:19:44 +00004002 tplt_print(out,lemp,lemp->accept,&lineno);
drh75897232000-05-29 14:26:00 +00004003 tplt_xfer(lemp->name,in,out,&lineno);
4004
4005 /* Append any addition code the user desires */
drha5808f32008-04-27 22:19:44 +00004006 tplt_print(out,lemp,lemp->extracode,&lineno);
drh75897232000-05-29 14:26:00 +00004007
4008 fclose(in);
4009 fclose(out);
4010 return;
4011}
4012
4013/* Generate a header file for the parser */
icculus9e44cf12010-02-14 17:14:22 +00004014void ReportHeader(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004015{
4016 FILE *out, *in;
icculus9e44cf12010-02-14 17:14:22 +00004017 const char *prefix;
drh75897232000-05-29 14:26:00 +00004018 char line[LINESIZE];
4019 char pattern[LINESIZE];
4020 int i;
4021
4022 if( lemp->tokenprefix ) prefix = lemp->tokenprefix;
4023 else prefix = "";
drh2aa6ca42004-09-10 00:14:04 +00004024 in = file_open(lemp,".h","rb");
drh75897232000-05-29 14:26:00 +00004025 if( in ){
4026 for(i=1; i<lemp->nterminal && fgets(line,LINESIZE,in); i++){
4027 sprintf(pattern,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4028 if( strcmp(line,pattern) ) break;
4029 }
4030 fclose(in);
4031 if( i==lemp->nterminal ){
4032 /* No change in the file. Don't rewrite it. */
4033 return;
4034 }
4035 }
drh2aa6ca42004-09-10 00:14:04 +00004036 out = file_open(lemp,".h","wb");
drh75897232000-05-29 14:26:00 +00004037 if( out ){
4038 for(i=1; i<lemp->nterminal; i++){
4039 fprintf(out,"#define %s%-30s %2d\n",prefix,lemp->symbols[i]->name,i);
4040 }
4041 fclose(out);
4042 }
4043 return;
4044}
4045
4046/* Reduce the size of the action tables, if possible, by making use
4047** of defaults.
4048**
drhb59499c2002-02-23 18:45:13 +00004049** In this version, we take the most frequent REDUCE action and make
drhe09daa92006-06-10 13:29:31 +00004050** it the default. Except, there is no default if the wildcard token
4051** is a possible look-ahead.
drh75897232000-05-29 14:26:00 +00004052*/
icculus9e44cf12010-02-14 17:14:22 +00004053void CompressTables(struct lemon *lemp)
drh75897232000-05-29 14:26:00 +00004054{
4055 struct state *stp;
drhb59499c2002-02-23 18:45:13 +00004056 struct action *ap, *ap2;
4057 struct rule *rp, *rp2, *rbest;
4058 int nbest, n;
drh75897232000-05-29 14:26:00 +00004059 int i;
drhe09daa92006-06-10 13:29:31 +00004060 int usesWildcard;
drh75897232000-05-29 14:26:00 +00004061
4062 for(i=0; i<lemp->nstate; i++){
4063 stp = lemp->sorted[i];
drhb59499c2002-02-23 18:45:13 +00004064 nbest = 0;
4065 rbest = 0;
drhe09daa92006-06-10 13:29:31 +00004066 usesWildcard = 0;
drh75897232000-05-29 14:26:00 +00004067
drhb59499c2002-02-23 18:45:13 +00004068 for(ap=stp->ap; ap; ap=ap->next){
drhe09daa92006-06-10 13:29:31 +00004069 if( ap->type==SHIFT && ap->sp==lemp->wildcard ){
4070 usesWildcard = 1;
4071 }
drhb59499c2002-02-23 18:45:13 +00004072 if( ap->type!=REDUCE ) continue;
4073 rp = ap->x.rp;
drhb4960992007-10-05 16:16:36 +00004074 if( rp->lhsStart ) continue;
drhb59499c2002-02-23 18:45:13 +00004075 if( rp==rbest ) continue;
4076 n = 1;
4077 for(ap2=ap->next; ap2; ap2=ap2->next){
4078 if( ap2->type!=REDUCE ) continue;
4079 rp2 = ap2->x.rp;
4080 if( rp2==rbest ) continue;
4081 if( rp2==rp ) n++;
4082 }
4083 if( n>nbest ){
4084 nbest = n;
4085 rbest = rp;
drh75897232000-05-29 14:26:00 +00004086 }
4087 }
drhb59499c2002-02-23 18:45:13 +00004088
4089 /* Do not make a default if the number of rules to default
drhe09daa92006-06-10 13:29:31 +00004090 ** is not at least 1 or if the wildcard token is a possible
4091 ** lookahead.
4092 */
4093 if( nbest<1 || usesWildcard ) continue;
drh75897232000-05-29 14:26:00 +00004094
drhb59499c2002-02-23 18:45:13 +00004095
4096 /* Combine matching REDUCE actions into a single default */
4097 for(ap=stp->ap; ap; ap=ap->next){
4098 if( ap->type==REDUCE && ap->x.rp==rbest ) break;
4099 }
drh75897232000-05-29 14:26:00 +00004100 assert( ap );
4101 ap->sp = Symbol_new("{default}");
4102 for(ap=ap->next; ap; ap=ap->next){
drhb59499c2002-02-23 18:45:13 +00004103 if( ap->type==REDUCE && ap->x.rp==rbest ) ap->type = NOT_USED;
drh75897232000-05-29 14:26:00 +00004104 }
4105 stp->ap = Action_sort(stp->ap);
4106 }
4107}
drhb59499c2002-02-23 18:45:13 +00004108
drhada354d2005-11-05 15:03:59 +00004109
4110/*
4111** Compare two states for sorting purposes. The smaller state is the
4112** one with the most non-terminal actions. If they have the same number
4113** of non-terminal actions, then the smaller is the one with the most
4114** token actions.
4115*/
4116static int stateResortCompare(const void *a, const void *b){
4117 const struct state *pA = *(const struct state**)a;
4118 const struct state *pB = *(const struct state**)b;
4119 int n;
4120
4121 n = pB->nNtAct - pA->nNtAct;
4122 if( n==0 ){
4123 n = pB->nTknAct - pA->nTknAct;
drhe594bc32009-11-03 13:02:25 +00004124 if( n==0 ){
4125 n = pB->statenum - pA->statenum;
4126 }
drhada354d2005-11-05 15:03:59 +00004127 }
drhe594bc32009-11-03 13:02:25 +00004128 assert( n!=0 );
drhada354d2005-11-05 15:03:59 +00004129 return n;
4130}
4131
4132
4133/*
4134** Renumber and resort states so that states with fewer choices
4135** occur at the end. Except, keep state 0 as the first state.
4136*/
icculus9e44cf12010-02-14 17:14:22 +00004137void ResortStates(struct lemon *lemp)
drhada354d2005-11-05 15:03:59 +00004138{
4139 int i;
4140 struct state *stp;
4141 struct action *ap;
4142
4143 for(i=0; i<lemp->nstate; i++){
4144 stp = lemp->sorted[i];
4145 stp->nTknAct = stp->nNtAct = 0;
4146 stp->iDflt = lemp->nstate + lemp->nrule;
4147 stp->iTknOfst = NO_OFFSET;
4148 stp->iNtOfst = NO_OFFSET;
4149 for(ap=stp->ap; ap; ap=ap->next){
4150 if( compute_action(lemp,ap)>=0 ){
4151 if( ap->sp->index<lemp->nterminal ){
4152 stp->nTknAct++;
4153 }else if( ap->sp->index<lemp->nsymbol ){
4154 stp->nNtAct++;
4155 }else{
4156 stp->iDflt = compute_action(lemp, ap);
4157 }
4158 }
4159 }
4160 }
4161 qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]),
4162 stateResortCompare);
4163 for(i=0; i<lemp->nstate; i++){
4164 lemp->sorted[i]->statenum = i;
4165 }
4166}
4167
4168
drh75897232000-05-29 14:26:00 +00004169/***************** From the file "set.c" ************************************/
4170/*
4171** Set manipulation routines for the LEMON parser generator.
4172*/
4173
4174static int size = 0;
4175
4176/* Set the set size */
icculus9e44cf12010-02-14 17:14:22 +00004177void SetSize(int n)
drh75897232000-05-29 14:26:00 +00004178{
4179 size = n+1;
4180}
4181
4182/* Allocate a new set */
4183char *SetNew(){
4184 char *s;
drh9892c5d2007-12-21 00:02:11 +00004185 s = (char*)calloc( size, 1);
drh75897232000-05-29 14:26:00 +00004186 if( s==0 ){
4187 extern void memory_error();
4188 memory_error();
4189 }
drh75897232000-05-29 14:26:00 +00004190 return s;
4191}
4192
4193/* Deallocate a set */
icculus9e44cf12010-02-14 17:14:22 +00004194void SetFree(char *s)
drh75897232000-05-29 14:26:00 +00004195{
4196 free(s);
4197}
4198
4199/* Add a new element to the set. Return TRUE if the element was added
4200** and FALSE if it was already there. */
icculus9e44cf12010-02-14 17:14:22 +00004201int SetAdd(char *s, int e)
drh75897232000-05-29 14:26:00 +00004202{
4203 int rv;
drh9892c5d2007-12-21 00:02:11 +00004204 assert( e>=0 && e<size );
drh75897232000-05-29 14:26:00 +00004205 rv = s[e];
4206 s[e] = 1;
4207 return !rv;
4208}
4209
4210/* Add every element of s2 to s1. Return TRUE if s1 changes. */
icculus9e44cf12010-02-14 17:14:22 +00004211int SetUnion(char *s1, char *s2)
drh75897232000-05-29 14:26:00 +00004212{
4213 int i, progress;
4214 progress = 0;
4215 for(i=0; i<size; i++){
4216 if( s2[i]==0 ) continue;
4217 if( s1[i]==0 ){
4218 progress = 1;
4219 s1[i] = 1;
4220 }
4221 }
4222 return progress;
4223}
4224/********************** From the file "table.c" ****************************/
4225/*
4226** All code in this file has been automatically generated
4227** from a specification in the file
4228** "table.q"
4229** by the associative array code building program "aagen".
4230** Do not edit this file! Instead, edit the specification
4231** file, then rerun aagen.
4232*/
4233/*
4234** Code for processing tables in the LEMON parser generator.
4235*/
4236
icculus9e44cf12010-02-14 17:14:22 +00004237PRIVATE int strhash(const char *x)
drh75897232000-05-29 14:26:00 +00004238{
4239 int h = 0;
4240 while( *x) h = h*13 + *(x++);
4241 return h;
4242}
4243
4244/* Works like strdup, sort of. Save a string in malloced memory, but
4245** keep strings in a table so that the same string is not in more
4246** than one place.
4247*/
icculus9e44cf12010-02-14 17:14:22 +00004248const char *Strsafe(const char *y)
drh75897232000-05-29 14:26:00 +00004249{
icculus9e44cf12010-02-14 17:14:22 +00004250 const char *z;
4251 char *cpy;
drh75897232000-05-29 14:26:00 +00004252
drh916f75f2006-07-17 00:19:39 +00004253 if( y==0 ) return 0;
drh75897232000-05-29 14:26:00 +00004254 z = Strsafe_find(y);
icculus9e44cf12010-02-14 17:14:22 +00004255 if( z==0 && (cpy=(char *)malloc( lemonStrlen(y)+1 ))!=0 ){
4256 strcpy(cpy,y);
4257 z = cpy;
drh75897232000-05-29 14:26:00 +00004258 Strsafe_insert(z);
4259 }
4260 MemoryCheck(z);
4261 return z;
4262}
4263
4264/* There is one instance of the following structure for each
4265** associative array of type "x1".
4266*/
4267struct s_x1 {
4268 int size; /* The number of available slots. */
4269 /* Must be a power of 2 greater than or */
4270 /* equal to 1 */
4271 int count; /* Number of currently slots filled */
4272 struct s_x1node *tbl; /* The data stored here */
4273 struct s_x1node **ht; /* Hash table for lookups */
4274};
4275
4276/* There is one instance of this structure for every data element
4277** in an associative array of type "x1".
4278*/
4279typedef struct s_x1node {
icculus9e44cf12010-02-14 17:14:22 +00004280 const char *data; /* The data */
drh75897232000-05-29 14:26:00 +00004281 struct s_x1node *next; /* Next entry with the same hash */
4282 struct s_x1node **from; /* Previous link */
4283} x1node;
4284
4285/* There is only one instance of the array, which is the following */
4286static struct s_x1 *x1a;
4287
4288/* Allocate a new associative array */
4289void Strsafe_init(){
4290 if( x1a ) return;
4291 x1a = (struct s_x1*)malloc( sizeof(struct s_x1) );
4292 if( x1a ){
4293 x1a->size = 1024;
4294 x1a->count = 0;
4295 x1a->tbl = (x1node*)malloc(
4296 (sizeof(x1node) + sizeof(x1node*))*1024 );
4297 if( x1a->tbl==0 ){
4298 free(x1a);
4299 x1a = 0;
4300 }else{
4301 int i;
4302 x1a->ht = (x1node**)&(x1a->tbl[1024]);
4303 for(i=0; i<1024; i++) x1a->ht[i] = 0;
4304 }
4305 }
4306}
4307/* Insert a new record into the array. Return TRUE if successful.
4308** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004309int Strsafe_insert(const char *data)
drh75897232000-05-29 14:26:00 +00004310{
4311 x1node *np;
4312 int h;
4313 int ph;
4314
4315 if( x1a==0 ) return 0;
4316 ph = strhash(data);
4317 h = ph & (x1a->size-1);
4318 np = x1a->ht[h];
4319 while( np ){
4320 if( strcmp(np->data,data)==0 ){
4321 /* An existing entry with the same key is found. */
4322 /* Fail because overwrite is not allows. */
4323 return 0;
4324 }
4325 np = np->next;
4326 }
4327 if( x1a->count>=x1a->size ){
4328 /* Need to make the hash table bigger */
4329 int i,size;
4330 struct s_x1 array;
4331 array.size = size = x1a->size*2;
4332 array.count = x1a->count;
4333 array.tbl = (x1node*)malloc(
4334 (sizeof(x1node) + sizeof(x1node*))*size );
4335 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4336 array.ht = (x1node**)&(array.tbl[size]);
4337 for(i=0; i<size; i++) array.ht[i] = 0;
4338 for(i=0; i<x1a->count; i++){
4339 x1node *oldnp, *newnp;
4340 oldnp = &(x1a->tbl[i]);
4341 h = strhash(oldnp->data) & (size-1);
4342 newnp = &(array.tbl[i]);
4343 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4344 newnp->next = array.ht[h];
4345 newnp->data = oldnp->data;
4346 newnp->from = &(array.ht[h]);
4347 array.ht[h] = newnp;
4348 }
4349 free(x1a->tbl);
4350 *x1a = array;
4351 }
4352 /* Insert the new data */
4353 h = ph & (x1a->size-1);
4354 np = &(x1a->tbl[x1a->count++]);
4355 np->data = data;
4356 if( x1a->ht[h] ) x1a->ht[h]->from = &(np->next);
4357 np->next = x1a->ht[h];
4358 x1a->ht[h] = np;
4359 np->from = &(x1a->ht[h]);
4360 return 1;
4361}
4362
4363/* Return a pointer to data assigned to the given key. Return NULL
4364** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004365const char *Strsafe_find(const char *key)
drh75897232000-05-29 14:26:00 +00004366{
4367 int h;
4368 x1node *np;
4369
4370 if( x1a==0 ) return 0;
4371 h = strhash(key) & (x1a->size-1);
4372 np = x1a->ht[h];
4373 while( np ){
4374 if( strcmp(np->data,key)==0 ) break;
4375 np = np->next;
4376 }
4377 return np ? np->data : 0;
4378}
4379
4380/* Return a pointer to the (terminal or nonterminal) symbol "x".
4381** Create a new symbol if this is the first time "x" has been seen.
4382*/
icculus9e44cf12010-02-14 17:14:22 +00004383struct symbol *Symbol_new(const char *x)
drh75897232000-05-29 14:26:00 +00004384{
4385 struct symbol *sp;
4386
4387 sp = Symbol_find(x);
4388 if( sp==0 ){
drh9892c5d2007-12-21 00:02:11 +00004389 sp = (struct symbol *)calloc(1, sizeof(struct symbol) );
drh75897232000-05-29 14:26:00 +00004390 MemoryCheck(sp);
4391 sp->name = Strsafe(x);
4392 sp->type = isupper(*x) ? TERMINAL : NONTERMINAL;
4393 sp->rule = 0;
drh0bd1f4e2002-06-06 18:54:39 +00004394 sp->fallback = 0;
drh75897232000-05-29 14:26:00 +00004395 sp->prec = -1;
4396 sp->assoc = UNK;
4397 sp->firstset = 0;
drhaa9f1122007-08-23 02:50:56 +00004398 sp->lambda = LEMON_FALSE;
drh75897232000-05-29 14:26:00 +00004399 sp->destructor = 0;
drh4dc8ef52008-07-01 17:13:57 +00004400 sp->destLineno = 0;
drh75897232000-05-29 14:26:00 +00004401 sp->datatype = 0;
drhc4dd3fd2008-01-22 01:48:05 +00004402 sp->useCnt = 0;
drh75897232000-05-29 14:26:00 +00004403 Symbol_insert(sp,sp->name);
4404 }
drhc4dd3fd2008-01-22 01:48:05 +00004405 sp->useCnt++;
drh75897232000-05-29 14:26:00 +00004406 return sp;
4407}
4408
drh60d31652004-02-22 00:08:04 +00004409/* Compare two symbols for working purposes
4410**
4411** Symbols that begin with upper case letters (terminals or tokens)
4412** must sort before symbols that begin with lower case letters
4413** (non-terminals). Other than that, the order does not matter.
4414**
4415** We find experimentally that leaving the symbols in their original
4416** order (the order they appeared in the grammar file) gives the
4417** smallest parser tables in SQLite.
4418*/
icculus9e44cf12010-02-14 17:14:22 +00004419int Symbolcmpp(const void *_a, const void *_b)
4420{
4421 const struct symbol **a = (const struct symbol **) _a;
4422 const struct symbol **b = (const struct symbol **) _b;
drh60d31652004-02-22 00:08:04 +00004423 int i1 = (**a).index + 10000000*((**a).name[0]>'Z');
4424 int i2 = (**b).index + 10000000*((**b).name[0]>'Z');
drhe594bc32009-11-03 13:02:25 +00004425 assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 );
drh60d31652004-02-22 00:08:04 +00004426 return i1-i2;
drh75897232000-05-29 14:26:00 +00004427}
4428
4429/* There is one instance of the following structure for each
4430** associative array of type "x2".
4431*/
4432struct s_x2 {
4433 int size; /* The number of available slots. */
4434 /* Must be a power of 2 greater than or */
4435 /* equal to 1 */
4436 int count; /* Number of currently slots filled */
4437 struct s_x2node *tbl; /* The data stored here */
4438 struct s_x2node **ht; /* Hash table for lookups */
4439};
4440
4441/* There is one instance of this structure for every data element
4442** in an associative array of type "x2".
4443*/
4444typedef struct s_x2node {
icculus9e44cf12010-02-14 17:14:22 +00004445 struct symbol *data; /* The data */
4446 const char *key; /* The key */
drh75897232000-05-29 14:26:00 +00004447 struct s_x2node *next; /* Next entry with the same hash */
4448 struct s_x2node **from; /* Previous link */
4449} x2node;
4450
4451/* There is only one instance of the array, which is the following */
4452static struct s_x2 *x2a;
4453
4454/* Allocate a new associative array */
4455void Symbol_init(){
4456 if( x2a ) return;
4457 x2a = (struct s_x2*)malloc( sizeof(struct s_x2) );
4458 if( x2a ){
4459 x2a->size = 128;
4460 x2a->count = 0;
4461 x2a->tbl = (x2node*)malloc(
4462 (sizeof(x2node) + sizeof(x2node*))*128 );
4463 if( x2a->tbl==0 ){
4464 free(x2a);
4465 x2a = 0;
4466 }else{
4467 int i;
4468 x2a->ht = (x2node**)&(x2a->tbl[128]);
4469 for(i=0; i<128; i++) x2a->ht[i] = 0;
4470 }
4471 }
4472}
4473/* Insert a new record into the array. Return TRUE if successful.
4474** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004475int Symbol_insert(struct symbol *data, const char *key)
drh75897232000-05-29 14:26:00 +00004476{
4477 x2node *np;
4478 int h;
4479 int ph;
4480
4481 if( x2a==0 ) return 0;
4482 ph = strhash(key);
4483 h = ph & (x2a->size-1);
4484 np = x2a->ht[h];
4485 while( np ){
4486 if( strcmp(np->key,key)==0 ){
4487 /* An existing entry with the same key is found. */
4488 /* Fail because overwrite is not allows. */
4489 return 0;
4490 }
4491 np = np->next;
4492 }
4493 if( x2a->count>=x2a->size ){
4494 /* Need to make the hash table bigger */
4495 int i,size;
4496 struct s_x2 array;
4497 array.size = size = x2a->size*2;
4498 array.count = x2a->count;
4499 array.tbl = (x2node*)malloc(
4500 (sizeof(x2node) + sizeof(x2node*))*size );
4501 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4502 array.ht = (x2node**)&(array.tbl[size]);
4503 for(i=0; i<size; i++) array.ht[i] = 0;
4504 for(i=0; i<x2a->count; i++){
4505 x2node *oldnp, *newnp;
4506 oldnp = &(x2a->tbl[i]);
4507 h = strhash(oldnp->key) & (size-1);
4508 newnp = &(array.tbl[i]);
4509 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4510 newnp->next = array.ht[h];
4511 newnp->key = oldnp->key;
4512 newnp->data = oldnp->data;
4513 newnp->from = &(array.ht[h]);
4514 array.ht[h] = newnp;
4515 }
4516 free(x2a->tbl);
4517 *x2a = array;
4518 }
4519 /* Insert the new data */
4520 h = ph & (x2a->size-1);
4521 np = &(x2a->tbl[x2a->count++]);
4522 np->key = key;
4523 np->data = data;
4524 if( x2a->ht[h] ) x2a->ht[h]->from = &(np->next);
4525 np->next = x2a->ht[h];
4526 x2a->ht[h] = np;
4527 np->from = &(x2a->ht[h]);
4528 return 1;
4529}
4530
4531/* Return a pointer to data assigned to the given key. Return NULL
4532** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004533struct symbol *Symbol_find(const char *key)
drh75897232000-05-29 14:26:00 +00004534{
4535 int h;
4536 x2node *np;
4537
4538 if( x2a==0 ) return 0;
4539 h = strhash(key) & (x2a->size-1);
4540 np = x2a->ht[h];
4541 while( np ){
4542 if( strcmp(np->key,key)==0 ) break;
4543 np = np->next;
4544 }
4545 return np ? np->data : 0;
4546}
4547
4548/* Return the n-th data. Return NULL if n is out of range. */
icculus9e44cf12010-02-14 17:14:22 +00004549struct symbol *Symbol_Nth(int n)
drh75897232000-05-29 14:26:00 +00004550{
4551 struct symbol *data;
4552 if( x2a && n>0 && n<=x2a->count ){
4553 data = x2a->tbl[n-1].data;
4554 }else{
4555 data = 0;
4556 }
4557 return data;
4558}
4559
4560/* Return the size of the array */
4561int Symbol_count()
4562{
4563 return x2a ? x2a->count : 0;
4564}
4565
4566/* Return an array of pointers to all data in the table.
4567** The array is obtained from malloc. Return NULL if memory allocation
4568** problems, or if the array is empty. */
4569struct symbol **Symbol_arrayof()
4570{
4571 struct symbol **array;
4572 int i,size;
4573 if( x2a==0 ) return 0;
4574 size = x2a->count;
drh9892c5d2007-12-21 00:02:11 +00004575 array = (struct symbol **)calloc(size, sizeof(struct symbol *));
drh75897232000-05-29 14:26:00 +00004576 if( array ){
4577 for(i=0; i<size; i++) array[i] = x2a->tbl[i].data;
4578 }
4579 return array;
4580}
4581
4582/* Compare two configurations */
icculus9e44cf12010-02-14 17:14:22 +00004583int Configcmp(const char *_a,const char *_b)
drh75897232000-05-29 14:26:00 +00004584{
icculus9e44cf12010-02-14 17:14:22 +00004585 const struct config *a = (struct config *) _a;
4586 const struct config *b = (struct config *) _b;
drh75897232000-05-29 14:26:00 +00004587 int x;
4588 x = a->rp->index - b->rp->index;
4589 if( x==0 ) x = a->dot - b->dot;
4590 return x;
4591}
4592
4593/* Compare two states */
icculus9e44cf12010-02-14 17:14:22 +00004594PRIVATE int statecmp(struct config *a, struct config *b)
drh75897232000-05-29 14:26:00 +00004595{
4596 int rc;
4597 for(rc=0; rc==0 && a && b; a=a->bp, b=b->bp){
4598 rc = a->rp->index - b->rp->index;
4599 if( rc==0 ) rc = a->dot - b->dot;
4600 }
4601 if( rc==0 ){
4602 if( a ) rc = 1;
4603 if( b ) rc = -1;
4604 }
4605 return rc;
4606}
4607
4608/* Hash a state */
icculus9e44cf12010-02-14 17:14:22 +00004609PRIVATE int statehash(struct config *a)
drh75897232000-05-29 14:26:00 +00004610{
4611 int h=0;
4612 while( a ){
4613 h = h*571 + a->rp->index*37 + a->dot;
4614 a = a->bp;
4615 }
4616 return h;
4617}
4618
4619/* Allocate a new state structure */
4620struct state *State_new()
4621{
icculus9e44cf12010-02-14 17:14:22 +00004622 struct state *newstate;
4623 newstate = (struct state *)calloc(1, sizeof(struct state) );
4624 MemoryCheck(newstate);
4625 return newstate;
drh75897232000-05-29 14:26:00 +00004626}
4627
4628/* There is one instance of the following structure for each
4629** associative array of type "x3".
4630*/
4631struct s_x3 {
4632 int size; /* The number of available slots. */
4633 /* Must be a power of 2 greater than or */
4634 /* equal to 1 */
4635 int count; /* Number of currently slots filled */
4636 struct s_x3node *tbl; /* The data stored here */
4637 struct s_x3node **ht; /* Hash table for lookups */
4638};
4639
4640/* There is one instance of this structure for every data element
4641** in an associative array of type "x3".
4642*/
4643typedef struct s_x3node {
4644 struct state *data; /* The data */
4645 struct config *key; /* The key */
4646 struct s_x3node *next; /* Next entry with the same hash */
4647 struct s_x3node **from; /* Previous link */
4648} x3node;
4649
4650/* There is only one instance of the array, which is the following */
4651static struct s_x3 *x3a;
4652
4653/* Allocate a new associative array */
4654void State_init(){
4655 if( x3a ) return;
4656 x3a = (struct s_x3*)malloc( sizeof(struct s_x3) );
4657 if( x3a ){
4658 x3a->size = 128;
4659 x3a->count = 0;
4660 x3a->tbl = (x3node*)malloc(
4661 (sizeof(x3node) + sizeof(x3node*))*128 );
4662 if( x3a->tbl==0 ){
4663 free(x3a);
4664 x3a = 0;
4665 }else{
4666 int i;
4667 x3a->ht = (x3node**)&(x3a->tbl[128]);
4668 for(i=0; i<128; i++) x3a->ht[i] = 0;
4669 }
4670 }
4671}
4672/* Insert a new record into the array. Return TRUE if successful.
4673** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004674int State_insert(struct state *data, struct config *key)
drh75897232000-05-29 14:26:00 +00004675{
4676 x3node *np;
4677 int h;
4678 int ph;
4679
4680 if( x3a==0 ) return 0;
4681 ph = statehash(key);
4682 h = ph & (x3a->size-1);
4683 np = x3a->ht[h];
4684 while( np ){
4685 if( statecmp(np->key,key)==0 ){
4686 /* An existing entry with the same key is found. */
4687 /* Fail because overwrite is not allows. */
4688 return 0;
4689 }
4690 np = np->next;
4691 }
4692 if( x3a->count>=x3a->size ){
4693 /* Need to make the hash table bigger */
4694 int i,size;
4695 struct s_x3 array;
4696 array.size = size = x3a->size*2;
4697 array.count = x3a->count;
4698 array.tbl = (x3node*)malloc(
4699 (sizeof(x3node) + sizeof(x3node*))*size );
4700 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4701 array.ht = (x3node**)&(array.tbl[size]);
4702 for(i=0; i<size; i++) array.ht[i] = 0;
4703 for(i=0; i<x3a->count; i++){
4704 x3node *oldnp, *newnp;
4705 oldnp = &(x3a->tbl[i]);
4706 h = statehash(oldnp->key) & (size-1);
4707 newnp = &(array.tbl[i]);
4708 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4709 newnp->next = array.ht[h];
4710 newnp->key = oldnp->key;
4711 newnp->data = oldnp->data;
4712 newnp->from = &(array.ht[h]);
4713 array.ht[h] = newnp;
4714 }
4715 free(x3a->tbl);
4716 *x3a = array;
4717 }
4718 /* Insert the new data */
4719 h = ph & (x3a->size-1);
4720 np = &(x3a->tbl[x3a->count++]);
4721 np->key = key;
4722 np->data = data;
4723 if( x3a->ht[h] ) x3a->ht[h]->from = &(np->next);
4724 np->next = x3a->ht[h];
4725 x3a->ht[h] = np;
4726 np->from = &(x3a->ht[h]);
4727 return 1;
4728}
4729
4730/* Return a pointer to data assigned to the given key. Return NULL
4731** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004732struct state *State_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004733{
4734 int h;
4735 x3node *np;
4736
4737 if( x3a==0 ) return 0;
4738 h = statehash(key) & (x3a->size-1);
4739 np = x3a->ht[h];
4740 while( np ){
4741 if( statecmp(np->key,key)==0 ) break;
4742 np = np->next;
4743 }
4744 return np ? np->data : 0;
4745}
4746
4747/* Return an array of pointers to all data in the table.
4748** The array is obtained from malloc. Return NULL if memory allocation
4749** problems, or if the array is empty. */
4750struct state **State_arrayof()
4751{
4752 struct state **array;
4753 int i,size;
4754 if( x3a==0 ) return 0;
4755 size = x3a->count;
4756 array = (struct state **)malloc( sizeof(struct state *)*size );
4757 if( array ){
4758 for(i=0; i<size; i++) array[i] = x3a->tbl[i].data;
4759 }
4760 return array;
4761}
4762
4763/* Hash a configuration */
icculus9e44cf12010-02-14 17:14:22 +00004764PRIVATE int confighash(struct config *a)
drh75897232000-05-29 14:26:00 +00004765{
4766 int h=0;
4767 h = h*571 + a->rp->index*37 + a->dot;
4768 return h;
4769}
4770
4771/* There is one instance of the following structure for each
4772** associative array of type "x4".
4773*/
4774struct s_x4 {
4775 int size; /* The number of available slots. */
4776 /* Must be a power of 2 greater than or */
4777 /* equal to 1 */
4778 int count; /* Number of currently slots filled */
4779 struct s_x4node *tbl; /* The data stored here */
4780 struct s_x4node **ht; /* Hash table for lookups */
4781};
4782
4783/* There is one instance of this structure for every data element
4784** in an associative array of type "x4".
4785*/
4786typedef struct s_x4node {
4787 struct config *data; /* The data */
4788 struct s_x4node *next; /* Next entry with the same hash */
4789 struct s_x4node **from; /* Previous link */
4790} x4node;
4791
4792/* There is only one instance of the array, which is the following */
4793static struct s_x4 *x4a;
4794
4795/* Allocate a new associative array */
4796void Configtable_init(){
4797 if( x4a ) return;
4798 x4a = (struct s_x4*)malloc( sizeof(struct s_x4) );
4799 if( x4a ){
4800 x4a->size = 64;
4801 x4a->count = 0;
4802 x4a->tbl = (x4node*)malloc(
4803 (sizeof(x4node) + sizeof(x4node*))*64 );
4804 if( x4a->tbl==0 ){
4805 free(x4a);
4806 x4a = 0;
4807 }else{
4808 int i;
4809 x4a->ht = (x4node**)&(x4a->tbl[64]);
4810 for(i=0; i<64; i++) x4a->ht[i] = 0;
4811 }
4812 }
4813}
4814/* Insert a new record into the array. Return TRUE if successful.
4815** Prior data with the same key is NOT overwritten */
icculus9e44cf12010-02-14 17:14:22 +00004816int Configtable_insert(struct config *data)
drh75897232000-05-29 14:26:00 +00004817{
4818 x4node *np;
4819 int h;
4820 int ph;
4821
4822 if( x4a==0 ) return 0;
4823 ph = confighash(data);
4824 h = ph & (x4a->size-1);
4825 np = x4a->ht[h];
4826 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004827 if( Configcmp((const char *) np->data,(const char *) data)==0 ){
drh75897232000-05-29 14:26:00 +00004828 /* An existing entry with the same key is found. */
4829 /* Fail because overwrite is not allows. */
4830 return 0;
4831 }
4832 np = np->next;
4833 }
4834 if( x4a->count>=x4a->size ){
4835 /* Need to make the hash table bigger */
4836 int i,size;
4837 struct s_x4 array;
4838 array.size = size = x4a->size*2;
4839 array.count = x4a->count;
4840 array.tbl = (x4node*)malloc(
4841 (sizeof(x4node) + sizeof(x4node*))*size );
4842 if( array.tbl==0 ) return 0; /* Fail due to malloc failure */
4843 array.ht = (x4node**)&(array.tbl[size]);
4844 for(i=0; i<size; i++) array.ht[i] = 0;
4845 for(i=0; i<x4a->count; i++){
4846 x4node *oldnp, *newnp;
4847 oldnp = &(x4a->tbl[i]);
4848 h = confighash(oldnp->data) & (size-1);
4849 newnp = &(array.tbl[i]);
4850 if( array.ht[h] ) array.ht[h]->from = &(newnp->next);
4851 newnp->next = array.ht[h];
4852 newnp->data = oldnp->data;
4853 newnp->from = &(array.ht[h]);
4854 array.ht[h] = newnp;
4855 }
4856 free(x4a->tbl);
4857 *x4a = array;
4858 }
4859 /* Insert the new data */
4860 h = ph & (x4a->size-1);
4861 np = &(x4a->tbl[x4a->count++]);
4862 np->data = data;
4863 if( x4a->ht[h] ) x4a->ht[h]->from = &(np->next);
4864 np->next = x4a->ht[h];
4865 x4a->ht[h] = np;
4866 np->from = &(x4a->ht[h]);
4867 return 1;
4868}
4869
4870/* Return a pointer to data assigned to the given key. Return NULL
4871** if no such key. */
icculus9e44cf12010-02-14 17:14:22 +00004872struct config *Configtable_find(struct config *key)
drh75897232000-05-29 14:26:00 +00004873{
4874 int h;
4875 x4node *np;
4876
4877 if( x4a==0 ) return 0;
4878 h = confighash(key) & (x4a->size-1);
4879 np = x4a->ht[h];
4880 while( np ){
icculus9e44cf12010-02-14 17:14:22 +00004881 if( Configcmp((const char *) np->data,(const char *) key)==0 ) break;
drh75897232000-05-29 14:26:00 +00004882 np = np->next;
4883 }
4884 return np ? np->data : 0;
4885}
4886
4887/* Remove all data from the table. Pass each data to the function "f"
4888** as it is removed. ("f" may be null to avoid this step.) */
icculus9e44cf12010-02-14 17:14:22 +00004889void Configtable_clear(int(*f)(struct config *))
drh75897232000-05-29 14:26:00 +00004890{
4891 int i;
4892 if( x4a==0 || x4a->count==0 ) return;
4893 if( f ) for(i=0; i<x4a->count; i++) (*f)(x4a->tbl[i].data);
4894 for(i=0; i<x4a->size; i++) x4a->ht[i] = 0;
4895 x4a->count = 0;
4896 return;
4897}