byaccj1.15/0000755000076500000240000000000011112722207011772 5ustar thurkastaffbyaccj1.15/docs/0000755000076500000240000000000011112722207012722 5ustar thurkastaffbyaccj1.15/docs/ACKNOWLEDGEMEN0000755000076500000240000000140307441711573014747 0ustar thurkastaff Berkeley Yacc owes much to the unflagging efforts of Keith Bostic. His badgering kept me working on it long after I was ready to quit. Berkeley Yacc is based on the excellent algorithm for computing LALR(1) lookaheads developed by Tom Pennello and Frank DeRemer. The algorithm is described in their almost impenetrable article in TOPLAS 4,4. Finally, much of the credit for the latest version must go to those who pointed out deficiencies of my earlier releases. Among the most prolific contributors were Benson I. Margulies Dave Gentzel Antoine Verheijen Peter S. Housel Dale Smith Ozan Yigit John Campbell Bill Sommerfeld Paul Hilfinger Gary Bridgewater Dave Bakken Dan Lanciani Richard Sargent Parag Patel byaccj1.15/docs/tf.y0000755000076500000240000000447607441711573013561 0ustar thurkastaff%{ import java.lang.Math; import java.io.*; import java.util.StringTokenizer; %} /* YACC Declarations */ %token NUM %left '-' '+' %left '*' '/' %left NEG /* negation--unary minus */ %right '^' /* exponentiation */ /* Grammar follows */ %% input: /* empty string */ | input line ; line: '\n' | exp '\n' { System.out.println(" " + $1 + " "); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = $1 + $3; } | exp '-' exp { $$ = $1 - $3; } | exp '*' exp { $$ = $1 * $3; } | exp '/' exp { $$ = $1 / $3; } | '-' exp %prec NEG { $$ = -$2; } | exp '^' exp { $$ = Math.pow($1, $3); } | '(' exp ')' { $$ = $2; } ; %% String ins; StringTokenizer st; void yyerror(String s) { System.out.println("par:"+s); } boolean newline; int yylex() { String s; int tok; Double d; //System.out.print("yylex "); if (!st.hasMoreTokens()) if (!newline) { newline=true; return '\n'; //So we look like classic YACC example } else return 0; s = st.nextToken(); //System.out.println("tok:"+s); try { d = Double.valueOf(s);/*this may fail*/ yylval = d.doubleValue(); tok = NUM; } catch (Exception e) { tok = s.charAt(0);/*if not float, return char*/ } return tok; } void dotest() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("BYACC/Java Calculator Demo"); System.out.println("Note: Since this example uses the StringTokenizer"); System.out.println("for simplicity, you will need to separate the items"); System.out.println("with spaces, i.e.: '( 3 + 5 ) * 2'"); while (true) { System.out.print("expression:"); try { ins = in.readLine(); } catch (Exception e) { } st = new StringTokenizer(ins); newline=false; yyparse(); } } public static void main(String args[]) { parser par = new parser(false); par.dotest(); } byaccj1.15/docs/yacc.cat0000755000076500000240000000562507441711573014363 0ustar thurkastaff YACC(1) USER COMMANDS YACC(1) NAME Yacc - an LALR(1) parser generator SYNOPSIS yacc [ -dlrtv ] [ -b _p_r_e_f_i_x ] _f_i_l_e_n_a_m_e DESCRIPTION _Y_a_c_c reads the grammar specification in the file _f_i_l_e_n_a_m_e and generates an LR(1) parser for it. The parsers consist of a set of LALR(1) parsing tables and a driver routine written in the C programming language. _Y_a_c_c normally writes the parse tables and the driver routine to the file _y._t_a_b._c. The following options are available: -b _p_r_e_f_i_x The -b option changes the prefix prepended to the output file names to the string denoted by _p_r_e_f_i_x. The default prefix is the character _y. -d The -d option causes the header file _y._t_a_b._h to be written. -l If the -l option is not specified, _y_a_c_c will insert #line directives in the generated code. The #line directives let the C compiler relate errors in the generated code to the user's origi- nal code. If the -l option is specified, _y_a_c_c will not insert the #line directives. #line directives specified by the user will be retained. -r The -r option causes _y_a_c_c to produce separate files for code and tables. The code file is named _y._c_o_d_e._c, and the tables file is named _y._t_a_b._c. -t The -t option changes the preprocessor directives generated by _y_a_c_c so that debugging statements will be incorporated in the compiled code. -v The -v option causes a human-readable description of the generated parser to be written to the file _y._o_u_t_p_u_t. If the environment variable TMPDIR is set, the string denoted by TMPDIR will be used as the name of the directory where the temporary files are created. FILES _y._c_o_d_e._c _y._t_a_b._c _y._t_a_b._h _y._o_u_t_p_u_t Sun Release 4.1 Last change: July 15, 1990 1 YACC(1) USER COMMANDS YACC(1) /_t_m_p/_y_a_c_c._a_X_X_X_X_X_X /_t_m_p/_y_a_c_c._t_X_X_X_X_X_X /_t_m_p/_y_a_c_c._u_X_X_X_X_X_X DIAGNOSTICS If there are rules that are never reduced, the number of such rules is reported on standard error. If there are any LALR(1) conflicts, the number of conflicts is reported on standard error. Sun Release 4.1 Last change: July 15, 1990 2 byaccj1.15/packme.sh0000755000076500000240000000064511111765224013603 0ustar thurkastaff#!/bin/sh VER=byaccj1.15 /bin/rm -rf ${VER} mkdir ${VER} mkdir ${VER}/src cp src/*.c ${VER}/src cp src/*.h ${VER}/src cp src/Makefile ${VER}/src cp src/Makefile.bcc ${VER}/src cp src/README ${VER} cp src/yacc.exe ${VER} cp src/yacc.irix ${VER} cp src/yacc.linux ${VER} cp src/yacc.solaris ${VER} chmod -R 777 ${VER} tar cvf - ${VER} | gzip > ${VER}.tar.gz jar cMvf ${VER}.zip ${VER} chmod 777 ${VER}.tar.gz ${VER}.zip byaccj1.15/src/0000755000076500000240000000000011112722214012557 5ustar thurkastaffbyaccj1.15/src/closure.c0000755000076500000240000000766307441711570014433 0ustar thurkastaff#include #include "defs.h" short *itemset; short *itemsetend; unsigned *ruleset; static unsigned *first_derives; static unsigned *EFF; void set_EFF(void) { unsigned *row; int symbol; short *sp; int rowsize; int i; int rule; rowsize = WORDSIZE(nvars); EFF = NEW2(nvars * rowsize, unsigned); row = EFF; for (i = start_symbol; i < nsyms; i++) { sp = derives[i]; for (rule = *sp; rule > 0; rule = *++sp) { symbol = ritem[rrhs[rule]]; if (ISVAR(symbol)) { symbol -= start_symbol; SETBIT(row, symbol); } } row += rowsize; } reflexive_transitive_closure(EFF, nvars); #ifdef DEBUG print_EFF(); #endif } void set_first_derives(void) { unsigned *rrow; unsigned *vrow; int j; unsigned mask; unsigned cword; short *rp; int rule; int i; int rulesetsize; int varsetsize; rulesetsize = WORDSIZE(nrules); varsetsize = WORDSIZE(nvars); first_derives = NEW2(nvars * rulesetsize, unsigned) - ntokens * rulesetsize; set_EFF(); rrow = first_derives + ntokens * rulesetsize; for (i = start_symbol; i < nsyms; i++) { vrow = EFF + ((i - ntokens) * varsetsize); cword = *vrow++; mask = 1; for (j = start_symbol; j < nsyms; j++) { if (cword & mask) { rp = derives[j]; while ((rule = *rp++) >= 0) { SETBIT(rrow, rule); } } mask <<= 1; if (mask == 0) { cword = *vrow++; mask = 1; } } vrow += varsetsize; rrow += rulesetsize; } #ifdef DEBUG print_first_derives(); #endif FREE(EFF); } void closure(short *nucleus,int n) { int ruleno; unsigned word; unsigned mask; short *csp; unsigned *dsp; unsigned *rsp; int rulesetsize; short *csend; unsigned *rsend; int symbol; int itemno; rulesetsize = WORDSIZE(nrules); rsp = ruleset; rsend = ruleset + rulesetsize; for (rsp = ruleset; rsp < rsend; rsp++) *rsp = 0; csend = nucleus + n; for (csp = nucleus; csp < csend; ++csp) { symbol = ritem[*csp]; if (ISVAR(symbol)) { dsp = first_derives + symbol * rulesetsize; rsp = ruleset; while (rsp < rsend) *rsp++ |= *dsp++; } } ruleno = 0; itemsetend = itemset; csp = nucleus; for (rsp = ruleset; rsp < rsend; ++rsp) { word = *rsp; if (word == 0) ruleno += BITS_PER_WORD; else { mask = 1; while (mask) { if (word & mask) { itemno = rrhs[ruleno]; while (csp < csend && *csp < itemno) *itemsetend++ = *csp++; *itemsetend++ = itemno; while (csp < csend && *csp == itemno) ++csp; } mask <<= 1; ++ruleno; } } } while (csp < csend) *itemsetend++ = *csp++; #ifdef DEBUG print_closure(n); #endif } void finalize_closure(void) { FREE(itemset); FREE(ruleset); FREE(first_derives + ntokens * WORDSIZE(nrules)); } #ifdef DEBUG void print_closure(int n) { int isp; printf("\n\nn = %d\n\n", n); for (isp = itemset; isp < itemsetend; isp++) printf(" %d\n", *isp); } void print_EFF(void) { int i, j, k; unsigned *rowp; unsigned word; unsigned mask; printf("\n\nEpsilon Free Firsts\n"); for (i = start_symbol; i < nsyms; i++) { printf("\n%s", symbol_name[i]); rowp = EFF + ((i - start_symbol) * WORDSIZE(nvars)); word = *rowp++; mask = 1; for (j = 0; j < nvars; j++) { if (word & mask) printf(" %s", symbol_name[start_symbol + j]); mask <<= 1; if (mask == 0) { word = *rowp++; mask = 1; } } } } void print_first_derives(void) { int i; int j; unsigned *rp; unsigned cword; unsigned mask; printf("\n\n\nFirst Derives\n"); for (i = start_symbol; i < nsyms; i++) { printf("\n%s derives\n", symbol_name[i]); rp = first_derives + i * WORDSIZE(nrules); cword = *rp++; mask = 1; for (j = 0; j <= nrules; j++) { if (cword & mask) printf(" %d\n", j); mask <<= 1; if (mask == 0) { cword = *rp++; mask = 1; } } } fflush(stdout); } #endif byaccj1.15/src/course.y0000755000076500000240000002256607441711570014304 0ustar thurkastaff%{ /* Do not delete this line! */ /************************************************************************** ** file: course.y ** ** does: Profides course file ".crs" file parsing for ICAT ** ** date: 950715 ** ** author: R. Jamison ** *************************************************************************** ** notes: ** ** *************************************************************************** ** history: ** ** date engr remarks ** ------ ----------------- ----------------------------- ** ...... . . ** **************************************************************************/ #include /*Standard C i/o */ #include #include /*Added C functions */ #include "course.h" /*Our include */ #include "config.h" #define TRUE 1 #define FALSE 0 course *par,*lsn,*exer,*sav; course *cs; config *cf; char verbuf[CRSSTRLEN+1]; char titlebuf[CRSSTRLEN+1]; char descbuf[CRSSTRLEN+1]; char codebuf[CRSSTRLEN+1]; char *abstract; char filebuf[CRSSTRLEN+1]; extern char yytext[]; extern long crs_line; extern char *crs_text; #define MAX_CSTACK 20 course *c_stack[MAX_CSTACK]; int c_depth; int c_push(course *c) { if (c_depth>=MAX_CSTACK) return 0; c_stack[c_depth++]=c; return 1; } course *c_pop(void) { if (c_depth<=0) return NULL; return c_stack[--c_depth]; } #define VCPY(a,b) strncpy(a,b,CRSSTRLEN) #define VSTR(a) strncpy(a,yytext,CRSSTRLEN) #define VASTR(a) if (a) free(a); a=strdup(crs_text) #define VQSTR(a) strncpy(a,crs_text,CRSSTRLEN) %} %token FLOAT %token VERSION LB RB QSTR DESCRIPTION TITLE DESC ABSTRACT CODE %token LESSON EXERCISE FILE_W DIR FILENAME %token CONFIG KEY STR INT PROGRAM %token ICAT DATA SOUNDS HTML_TOOL AUTHOR_TOOL MODEL_TOOL %% crsfile: VERSION { VSTR(verbuf); } coursedef { } ; coursedef: description lessonlist exerlist { } | description config lessonlist exerlist { } ; /*+++DESCRIPTION+++*/ description : DESCRIPTION LB title { VQSTR(titlebuf); } desc { VQSTR(descbuf); } code abstract { VASTR(abstract); } RB { cs = crs_add_course(NULL,verbuf,titlebuf,descbuf,codebuf,abstract); par=cs; /* printf(":%s:%s:%s:%s:%s:\n",verbuf,titlebuf,descbuf,codebuf,abstract); */ } ; title: TITLE QSTR { } ; desc: DESC QSTR { } ; abstract: ABSTRACT QSTR { } ; /*+++CONFIG+++*/ config: CONFIG LB cfglist RB { } ; cfglist: /*Nil*/ | cfgitem cfglist { } ; cfgitem: ICAT LB icatlist RB | AUTHOR_TOOL LB authorlist RB | SOUNDS LB sounditem RB | HTML_TOOL LB htmllist RB | MODEL_TOOL LB modellist RB ; icatlist: /*Null*/ | icatlist icatitem ; icatitem: DATA FILENAME { VQSTR(cf->icat_data); } | DATA QSTR { VQSTR(cf->icat_data); } ; authorlist: /*Null*/ | authorlist authoritem ; authoritem: PROGRAM FILENAME { VQSTR(cf->author_tool); } | PROGRAM QSTR { VQSTR(cf->author_tool); } | FILE_W FILENAME { VQSTR(cf->author_file); } | FILE_W QSTR { VQSTR(cf->author_file); } ; htmllist: /*Null*/ | htmlitem htmllist ; htmlitem: PROGRAM FILENAME { VQSTR(cf->html_tool); } | PROGRAM QSTR { VQSTR(cf->html_tool); } | FILE_W FILENAME { VQSTR(cf->html_file); } | FILE_W QSTR { VQSTR(cf->html_file); } ; modellist: /*Null*/ | modelitem modellist ; modelitem: PROGRAM FILENAME { VQSTR(cf->model_tool); } | PROGRAM QSTR { VQSTR(cf->model_tool); } | FILE_W FILENAME { VQSTR(cf->model_file); } | FILE_W QSTR { VQSTR(cf->model_file); } ; sounditem: DIR FILENAME { VQSTR(cf->sound_dir); } /*+++LESSONS+++*/ /*Following recursive definition means 'zero to many'*/ lessonlist: /*nil*/ | lesson lessonlist { } ; exerlist: /*nil*/ | exercise exerlist { } ; lesson: LESSON LB title { VQSTR(titlebuf); } desc { VQSTR(descbuf); } code abstract { VASTR(abstract); /*printf("lesson\n");*/ lsn = crs_add_lesson(par,titlebuf, descbuf,codebuf,abstract); c_push(par); par=lsn; /*allow a recurse*/} lessonlist exerlist { par=c_pop(); } RB { } ; exercise: EXERCISE LB title { VQSTR(titlebuf); } desc { VQSTR(descbuf); } code { VQSTR(codebuf); } abstract { VASTR(abstract); } filename { VQSTR(filebuf); } RB { /*printf("exercise\n");*/ exer = crs_add_exercise(par,titlebuf, descbuf,codebuf,abstract,filebuf); } ; /*Not recursive. Zero or one*/ code: /*Nil*/ { codebuf[0]=0; } | CODE QSTR { VQSTR(codebuf); } ; filename: FILE_W QSTR { } ; %% /************************************************************************** * function: yyerror * does : Reports a YACC error * inputs : String to report error * outputs : TRUE if successful, else FALSE **************************************************************************/ int yyerror(char *str) /**/ { printf("YACC:%ld:%s\n",crs_line,str); return FALSE; /*Return success */ } /*** end of func *********************************************************/ /************************************************************************** * function: crs_parse * does : Parses a file * inputs : File pointer * outputs : course * if successful, else NULL **************************************************************************/ course *crs_parse(FILE *f,config *cfg) /*//*/ { cs=NULL; if (!f) /*Bad file?(Just in case) */ { return FALSE; } crsin(f); cf=cfg; c_depth=0; abstract=0; if (yyparse()!=0) return NULL; return cs; /*Return success */ } /*** end of func *********************************************************/ /************************************************************************** * function: crs_parsefile * does : Parses a named file * inputs : File name pointer * outputs : course * if successful, else NULL **************************************************************************/ course *crs_parsefile(char *fname,config *cfg) /*//*/ { FILE *f; course *ret; f=fopen(fname,"r"); /*Open the file? */ if (!f) { /*printf("Could not open %s for reading\n",fname);*/ return FALSE; } ret=crs_parse(f,cfg); fclose(f); /*Close the file */ return ret; /*Return success */ } /*** end of func *********************************************************/ /************************************************************************** * function: crs_load * does : Loads the course description file * inputs : None * outputs : course * if successful, else NULL **************************************************************************/ course *crs_load(config *cfg) /*//*/ { char path[256]; char *e; course *ret; if (!cfg_defaults(cfg)) return NULL; e=getenv(CRS_PATH1); if (e) { sprintf(path,"%s%s%s",e,CRS_SEP,CRSNAME); ret=crs_parsefile(path,cfg); if (ret) return ret; } e=getenv(CRS_PATH2); if (e) { sprintf(path,"%s%s%s",e,CRS_SEP,CRSNAME); ret=crs_parsefile(path,cfg); if (ret) return ret; } sprintf(path,".%s%s",CRS_SEP,CRSNAME); ret=crs_parsefile(path,cfg); return ret; /*Return failure */ } /*** end of func *********************************************************/ #ifdef TEST /************************************************************************** * function: main * does : * inputs : * outputs : **************************************************************************/ int main(int argc,char **argv) /**/ { FILE *f; int ret; config cfg; if (argc!=2) { printf("usage:%s filename\n",argv[0]); return FALSE; } if (!crs_parsefile(argv[1],&cfg)) { printf("Parse of file failed\n"); return FALSE; } return TRUE; /*Return success */ } /*** end of func *********************************************************/ #endif /*TEST*/ /**** end of file ********************************************************/ byaccj1.15/src/defs.h0000755000076500000240000003010607444075776013707 0ustar thurkastaff#include #include #include #include /* machine-dependent definitions */ /* the following definitions are for the Tahoe */ /* they might have to be changed for other machines */ /* MAXCHAR is the largest unsigned character value */ /* MAXSHORT is the largest value of a C short */ /* MINSHORT is the most negative value of a C short */ /* MAXTABLE is the maximum table size */ /* BITS_PER_WORD is the number of bits in a C unsigned */ /* WORDSIZE computes the number of words needed to */ /* store n bits */ /* BIT returns the value of the n-th bit starting */ /* from r (0-indexed) */ /* SETBIT sets the n-th bit starting from r */ #define MAXCHAR 255 #define MAXSHORT 32767 #define MINSHORT -32768 #define MAXTABLE 32500 #define BITS_PER_WORD 32 #define WORDSIZE(n) (((n)+(BITS_PER_WORD-1))/BITS_PER_WORD) #define BIT(r, n) ((((r)[(n)>>5])>>((n)&31))&1) #define SETBIT(r, n) ((r)[(n)>>5]|=((unsigned)1<<((n)&31))) /* yio 20020304: for boolean parameters */ #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif /* character names */ #define NUL '\0' /* the null character */ #define NEWLINE '\n' /* line feed */ #define SP ' ' /* space */ #define BS '\b' /* backspace */ #define HT '\t' /* horizontal tab */ #define VT '\013' /* vertical tab */ #define CR '\r' /* carriage return */ #define FF '\f' /* form feed */ #define QUOTE '\'' /* single quote */ #define DOUBLE_QUOTE '\"' /* double quote */ #define BACKSLASH '\\' /* backslash */ /* defines for constructing filenames */ #define CODE_SUFFIX ".code.c" #define DEFINES_SUFFIX ".tab.h" #define OUTPUT_SUFFIX ".tab.c" #define JAVA_OUTPUT_SUFFIX ".java" /*rwj*/ #define JAVA_INTERFACE_SUFFIX "Tokens" /*rwj*/ #define VERBOSE_SUFFIX ".output" /* keyword codes */ #define TOKEN 0 #define LEFT 1 #define RIGHT 2 #define NONASSOC 3 #define MARK 4 #define TEXT 5 #define TYPE 6 #define START 7 #define UNION 8 #define IDENT 9 #define JAVA_ARG 10 /* yio 20020304: added for specifying java arguments in grammar */ /* symbol classes */ #define UNKNOWN 0 #define TERM 1 #define NONTERM 2 /* the undefined value */ #define UNDEFINED (-1) /* action codes */ #define SHIFT 1 #define REDUCE 2 /* character macros */ #define IS_IDENT(c) (isalnum(c) || (c) == '_' || (c) == '.' || (c) == '$') #define IS_OCTAL(c) ((c) >= '0' && (c) <= '7') #define NUMERIC_VALUE(c) ((c) - '0') /* symbol macros */ #define ISTOKEN(s) ((s) < start_symbol) #define ISVAR(s) ((s) >= start_symbol) /* storage allocation macros */ #define CALLOC(k,n) (calloc((unsigned)(k),(unsigned)(n))) #define FREE(x) (free((char*)(x))) #define MALLOC(n) (malloc((unsigned)(n))) #define NEW(t) ((t*)allocate(sizeof(t))) #define NEW2(n,t) ((t*)allocate((unsigned)((n)*sizeof(t)))) #define REALLOC(p,n) (realloc((char*)(p),(unsigned)(n))) /* the structure of a symbol table entry */ typedef struct bucket bucket; struct bucket { struct bucket *link; struct bucket *next; char *name; char *tag; short value; short index; short prec; char class; char assoc; }; /* the structure of the LR(0) state machine */ typedef struct core core; struct core { struct core *next; struct core *link; short number; short accessing_symbol; short nitems; short items[1]; }; /* the structure used to record shifts */ typedef struct shifts shifts; struct shifts { struct shifts *next; short number; short nshifts; short shift[1]; }; /* the structure used to store reductions */ typedef struct reductions reductions; struct reductions { struct reductions *next; short number; short nreds; short rules[1]; }; /* the structure used to represent parser actions */ typedef struct action action; struct action { struct action *next; short symbol; short number; short prec; char action_code; char assoc; char suppressed; }; /* global variables */ extern char dflag; extern char lflag; extern char rflag; extern char tflag; extern char vflag; extern char *myname; extern char *cptr; extern char *line; extern int lineno; extern int outline; extern char *banner[]; extern char *tables[]; extern char *header[]; extern char *body[]; extern char *trailer[]; /*#### Java Things ####*/ extern char jflag; extern char *jbanner[]; extern char *jtables[]; extern char *jheader[]; extern char *jbody_a[]; /* yio 20020304: split to allow 'jthrows' parameter */ extern char *jbody_b[]; extern char *jtrailer[]; extern char jrun; extern char jconstruct; extern char *jclass_name; extern char *jpackage_name; extern char *jextend_name; extern char *jimplement_name; extern char *jsemantic_type; extern int jstack_size; /* yio 20020304 */ extern char *jbody_nodebug_a[]; extern char *jbody_nodebug_b[]; extern char *jtrailer_nodebug[]; extern char *jyyparse_throws; extern int jdebug; extern int jfinal_class; extern char *action_file_name; extern char *code_file_name; extern char *defines_file_name; extern char *input_file_name; extern char *output_file_name; extern char *text_file_name; extern char *union_file_name; extern char *verbose_file_name; extern FILE *action_file; extern FILE *code_file; extern FILE *defines_file; extern FILE *input_file; extern FILE *output_file; extern FILE *text_file; extern FILE *union_file; extern FILE *verbose_file; extern int nitems; extern int nrules; extern int nsyms; extern int ntokens; extern int nvars; extern int ntags; extern char unionized; extern char line_format[]; extern char jline_format[];/*rwj*/ extern int start_symbol; extern char **symbol_name; extern short *symbol_value; extern short *symbol_prec; extern char *symbol_assoc; extern short *ritem; extern short *rlhs; extern short *rrhs; extern short *rprec; extern char *rassoc; extern short **derives; extern char *nullable; extern bucket *first_symbol; extern bucket *last_symbol; extern int nstates; extern core *first_state; extern shifts *first_shift; extern reductions *first_reduction; extern short *accessing_symbol; extern core **state_table; extern shifts **shift_table; extern reductions **reduction_table; extern unsigned *LA; extern short *LAruleno; extern short *lookaheads; extern short *goto_map; extern short *from_state; extern short *to_state; extern action **parser; extern int SRtotal; extern int RRtotal; extern short *SRconflicts; extern short *RRconflicts; extern short *defred; extern short *rules_used; extern short nunused; extern short final_state; /* system variables */ extern int errno; /************************ ## PROTOTYPES ************************/ /*in warshall.c*/ void transitive_closure(unsigned *R, int n); void reflexive_transitive_closure(unsigned *R, int n); /*in verbose.c*/ void verbose(void); void log_unused(void); void log_conflicts(void); void print_state(int state); void print_conflicts(int state); void print_core(int state); void print_nulls(int state); void print_actions(int stateno); void print_shifts(action *p); void print_reductions(action *p,int defred); void print_gotos(int stateno); /*in closure.c*/ void set_EFF(void); void set_first_derives(void); void closure(short *nucleus,int n); void finalize_closure(void); void print_closure(int n); void print_EFF(void); void print_first_derives(void); /*in error.c*/ void fatal(char *msg); void no_space(void); void open_error(char *filename); void unexpected_EOF(void); void print_pos(char *st_line,char *st_cptr); void syntax_error(int st_lineno,char *st_line,char *st_cptr); void unterminated_comment(int c_lineno,char *c_line,char *c_cptr); void unterminated_string(int s_lineno,char *s_line,char *s_cptr); void unterminated_text(int t_lineno,char *t_line,char *t_cptr); void unterminated_union(int u_lineno,char *u_line,char *u_cptr); void over_unionized(char *u_cptr); void illegal_tag(int t_lineno,char *t_line,char *t_cptr); void illegal_character(char *c_cptr); void used_reserved(char *s); void tokenized_start(char *s); void retyped_warning(char *s); void reprec_warning(char *s); void revalued_warning(char *s); void terminal_start(char *s); void restarted_warning(void); void no_grammar(void); void terminal_lhs(int s_lineno); void prec_redeclared(void); void unterminated_action(int a_lineno,char *a_line,char *a_cptr); void dollar_warning(int a_lineno,int i); void dollar_error(int a_lineno,char *a_line,char *a_cptr); void untyped_lhs(void); void untyped_rhs(int i,char *s); void unknown_rhs(int i); void default_action_warning(void); void undefined_goal(char *s); void undefined_symbol_warning(char *s); /*in skeleton.c*/ void write_section(char *section[]); /*in symtab.c*/ int hash(char *name); bucket *make_bucket(char *name); bucket *lookup(char *name); void create_symbol_table(void); void free_symbol_table(void); void free_symbols(void); /*in reader.c*/ void cachec(int c); void get_line(void); char *dup_line(void); void skip_comment(void); int nextc(void); int keyword(void); void copy_ident(void); void copy_text(void); void copy_union(void); int hexval(int c); bucket *get_literal(void); int is_reserved(char *name); bucket *get_name(void); int get_number(void); char *get_tag(void); void declare_tokens(int assoc); void declare_types(void); void declare_start(void); void read_declarations(void); void initialize_grammar(void); void expand_items(void); void expand_rules(void); void advance_to_start(void); void start_rule(bucket *bp,int s_lineno); void end_rule(void); void insert_empty_rule(void); void add_symbol(void); void copy_action(void); int mark_symbol(void); void read_grammar(void); void free_tags(void); void pack_names(void); void check_symbols(void); void pack_symbols(void); void pack_grammar(void); void print_grammar(void); void reader(void); /*in output.c*/ void output(void); void output_rule_data(void) ; void output_yydefred(void); void output_actions(void); void token_actions(void); void goto_actions(void); int default_goto(int symbol); void save_column(int symbol,int default_state); void sort_actions(void); void pack_table(void); int matching_vector(int vector); int pack_vector(int vector); void output_base(void); void output_table(void); void output_check(void); int is_C_identifier(char *name); void output_defines(void); void output_stored_text(void); void output_debug(void); void output_stype(void); void output_trailing_text(void); void output_semantic_actions(void); void free_itemsets(void); void free_shifts(void); void free_reductions(void); /*in mkpar.c*/ void make_parser(void); action *parse_actions(int stateno); action *get_shifts(int stateno); action *add_reductions(int stateno,action *actions); action *add_reduce(action *actions,int ruleno,int symbol); void find_final_state(void); void unused_rules(void); void remove_conflicts(void); void total_conflicts(void); int sole_reduction(int stateno); void defreds(void); void free_action_row(action *p); void free_parser(void); /*in lr0.c*/ void allocate_itemsets(void); void allocate_storage(void); void append_states(void); void free_storage(void); void generate_states(void); int get_state(int symbol); void initialize_states(void); void new_itemsets(void); core *new_state(int symbol); void show_cores(void); void show_ritems(void); void show_rrhs(void); void show_shifts(void); void save_shifts(void); void save_reductions(void); void set_derives(void); void free_derives(void); void print_derives(void); void set_nullable(void); void free_nullable(void); void lr0(void); /*in lalr.c*/ void lalr(void); void set_state_table(void); void set_accessing_symbol(void); void set_shift_table(void); void set_reduction_table(void); void set_maxrhs(void); void initialize_LA(void); void set_goto_map(void); int map_goto(int state,int symbol); void initialize_F(void); void build_relations(void); void add_lookback_edge(int stateno,int ruleno,int gotono); short **transpose(short **R,int n); void compute_FOLLOWS(void); void compute_lookaheads(void); void digraph(short **relation); void traverse(int i); /*in main.c*/ void done(int k); void onintr(int); void set_signals(void); void usage(void); void getargs(int argc,char **argv); char *allocate(unsigned n); void create_file_names(void); void open_files(void); void getJavaArg(char *option); /* yio 20020304 */ int main(int argc,char **argv); byaccj1.15/src/error.c0000755000076500000240000001363607441711570014105 0ustar thurkastaff/* routines for printing error messages */ #include #include "defs.h" void fatal(char *msg) { fprintf(stderr, "%s: f - %s\n", myname, msg); done(2); } void no_space(void) { fprintf(stderr, "%s: f - out of space\n", myname); done(2); } void open_error(char *filename) { fprintf(stderr, "%s: f - cannot open \"%s\"\n", myname, filename); done(2); } void unexpected_EOF(void) { fprintf(stderr, "%s: e - line %d of \"%s\", unexpected end-of-file\n", myname, lineno, input_file_name); done(1); } void print_pos(char *st_line,char *st_cptr) { char *s; if (st_line == 0) return; for (s = st_line; *s != '\n'; ++s) { if (isprint(*s) || *s == '\t') putc(*s, stderr); else putc('?', stderr); } putc('\n', stderr); for (s = st_line; s < st_cptr; ++s) { if (*s == '\t') putc('\t', stderr); else putc(' ', stderr); } putc('^', stderr); putc('\n', stderr); } void syntax_error(int st_lineno,char *st_line,char *st_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", syntax error\n", myname, st_lineno, input_file_name); print_pos(st_line, st_cptr); done(1); } void unterminated_comment(int c_lineno,char *c_line,char *c_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", unmatched /*\n", myname, c_lineno, input_file_name); print_pos(c_line, c_cptr); done(1); } void unterminated_string(int s_lineno,char *s_line,char *s_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", unterminated string\n", myname, s_lineno, input_file_name); print_pos(s_line, s_cptr); done(1); } void unterminated_text(int t_lineno,char *t_line,char *t_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", unmatched %%{\n", myname, t_lineno, input_file_name); print_pos(t_line, t_cptr); done(1); } void unterminated_union(int u_lineno,char *u_line,char *u_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", unterminated %%union declaration\n", myname, u_lineno, input_file_name); print_pos(u_line, u_cptr); done(1); } void over_unionized(char *u_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", too many %%union declarations\n", myname, lineno, input_file_name); print_pos(line, u_cptr); done(1); } void illegal_tag(int t_lineno,char *t_line,char *t_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", illegal tag\n", myname, t_lineno, input_file_name); print_pos(t_line, t_cptr); done(1); } void illegal_character(char *c_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", illegal character\n", myname, lineno, input_file_name); print_pos(line, c_cptr); done(1); } void used_reserved(char *s) { fprintf(stderr, "%s: e - line %d of \"%s\", illegal use of reserved symbol %s\n", myname, lineno, input_file_name, s); done(1); } void tokenized_start(char *s) { fprintf(stderr, "%s: e - line %d of \"%s\", the start symbol %s cannot be declared to be a token\n", myname, lineno, input_file_name, s); done(1); } void retyped_warning(char *s) { fprintf(stderr, "%s: w - line %d of \"%s\", the type of %s has been redeclared\n", myname, lineno, input_file_name, s); } void reprec_warning(char *s) { fprintf(stderr, "%s: w - line %d of \"%s\", the precedence of %s has been redeclared\n", myname, lineno, input_file_name, s); } void revalued_warning(char *s) { fprintf(stderr, "%s: w - line %d of \"%s\", the value of %s has been redeclared\n", myname, lineno, input_file_name, s); } void terminal_start(char *s) { fprintf(stderr, "%s: e - line %d of \"%s\", the start symbol %s is a token\n", myname, lineno, input_file_name, s); done(1); } void restarted_warning(void) { fprintf(stderr, "%s: w - line %d of \"%s\", the start symbol has been redeclared\n", myname, lineno, input_file_name); } void no_grammar(void) { fprintf(stderr, "%s: e - line %d of \"%s\", no grammar has been specified\n", myname, lineno, input_file_name); done(1); } void terminal_lhs(int s_lineno) { fprintf(stderr, "%s: e - line %d of \"%s\", a token appears on the lhs of a production\n", myname, s_lineno, input_file_name); done(1); } void prec_redeclared(void) { fprintf(stderr, "%s: w - line %d of \"%s\", conflicting %%prec specifiers\n", myname, lineno, input_file_name); } void unterminated_action(int a_lineno,char *a_line,char *a_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", unterminated action\n", myname, a_lineno, input_file_name); print_pos(a_line, a_cptr); done(1); } void dollar_warning(int a_lineno,int i) { fprintf(stderr, "%s: w - line %d of \"%s\", $%d references beyond the end of the current rule\n", myname, a_lineno, input_file_name, i); } void dollar_error(int a_lineno,char *a_line,char *a_cptr) { fprintf(stderr, "%s: e - line %d of \"%s\", illegal $-name\n", myname, a_lineno, input_file_name); print_pos(a_line, a_cptr); done(1); } void untyped_lhs(void) { fprintf(stderr, "%s: e - line %d of \"%s\", $$ is untyped\n", myname, lineno, input_file_name); done(1); } void untyped_rhs(int i,char *s) { fprintf(stderr, "%s: e - line %d of \"%s\", $%d (%s) is untyped\n", myname, lineno, input_file_name, i, s); done(1); } void unknown_rhs(int i) { fprintf(stderr, "%s: e - line %d of \"%s\", $%d is untyped\n", myname, lineno, input_file_name, i); done(1); } void default_action_warning(void) { fprintf(stderr, "%s: w - line %d of \"%s\", the default action assigns an undefined value to $$\n", myname, lineno, input_file_name); } void undefined_goal(char *s) { fprintf(stderr, "%s: e - the start symbol %s is undefined\n", myname, s); done(1); } void undefined_symbol_warning(char *s) { fprintf(stderr, "%s: w - the symbol %s is undefined\n", myname, s); } byaccj1.15/src/lalr.c0000755000076500000240000002237007444073365013707 0ustar thurkastaff#include #include "defs.h" typedef struct shorts { struct shorts *next; short value; } shorts; int tokensetsize; short *lookaheads; short *LAruleno; unsigned *LA; short *accessing_symbol; core **state_table; shifts **shift_table; reductions **reduction_table; short *goto_map; short *from_state; short *to_state; static int infinity; static int maxrhs; static int ngotos; static unsigned *F; static short **includes; static shorts **lookback; static short **R; static short *INDEX; static short *VERTICES; static int top; void lalr(void) { tokensetsize = WORDSIZE(ntokens); set_state_table(); set_accessing_symbol(); set_shift_table(); set_reduction_table(); set_maxrhs(); initialize_LA(); set_goto_map(); initialize_F(); build_relations(); compute_FOLLOWS(); compute_lookaheads(); } void set_state_table(void) { core *sp; state_table = NEW2(nstates, core *); for (sp = first_state; sp; sp = sp->next) state_table[sp->number] = sp; } void set_accessing_symbol(void) { core *sp; accessing_symbol = NEW2(nstates, short); for (sp = first_state; sp; sp = sp->next) accessing_symbol[sp->number] = sp->accessing_symbol; } void set_shift_table(void) { shifts *sp; shift_table = NEW2(nstates, shifts *); for (sp = first_shift; sp; sp = sp->next) shift_table[sp->number] = sp; } void set_reduction_table(void) { reductions *rp; reduction_table = NEW2(nstates, reductions *); for (rp = first_reduction; rp; rp = rp->next) reduction_table[rp->number] = rp; } void set_maxrhs(void) { short *itemp; short *item_end; int length; int max; length = 0; max = 0; item_end = ritem + nitems; for (itemp = ritem; itemp < item_end; itemp++) { if (*itemp >= 0) { length++; } else { if (length > max) max = length; length = 0; } } maxrhs = max; } void initialize_LA(void) { int i, j, k; reductions *rp; lookaheads = NEW2(nstates + 1, short); k = 0; for (i = 0; i < nstates; i++) { lookaheads[i] = k; rp = reduction_table[i]; if (rp) k += rp->nreds; } lookaheads[nstates] = k; LA = NEW2(k * tokensetsize, unsigned); LAruleno = NEW2(k, short); lookback = NEW2(k, shorts *); k = 0; for (i = 0; i < nstates; i++) { rp = reduction_table[i]; if (rp) { for (j = 0; j < rp->nreds; j++) { LAruleno[k] = rp->rules[j]; k++; } } } } void set_goto_map(void) { shifts *sp; int i; int symbol; int k; short *temp_map; int state2; int state1; goto_map = NEW2(nvars + 1, short) - ntokens; temp_map = NEW2(nvars + 1, short) - ntokens; ngotos = 0; for (sp = first_shift; sp; sp = sp->next) { for (i = sp->nshifts - 1; i >= 0; i--) { symbol = accessing_symbol[sp->shift[i]]; if (ISTOKEN(symbol)) break; if (ngotos == MAXSHORT) fatal("too many gotos"); ngotos++; goto_map[symbol]++; } } k = 0; for (i = ntokens; i < nsyms; i++) { temp_map[i] = k; k += goto_map[i]; } for (i = ntokens; i < nsyms; i++) goto_map[i] = temp_map[i]; goto_map[nsyms] = ngotos; temp_map[nsyms] = ngotos; from_state = NEW2(ngotos, short); to_state = NEW2(ngotos, short); for (sp = first_shift; sp; sp = sp->next) { state1 = sp->number; for (i = sp->nshifts - 1; i >= 0; i--) { state2 = sp->shift[i]; symbol = accessing_symbol[state2]; if (ISTOKEN(symbol)) break; k = temp_map[symbol]++; from_state[k] = state1; to_state[k] = state2; } } FREE(temp_map + ntokens); } /* Map_goto maps a state/symbol pair into its numeric representation. */ int map_goto(int state,int symbol) { int high; int low; int middle; int s; low = goto_map[symbol]; high = goto_map[symbol + 1]; for (;;) { assert(low <= high); middle = (low + high) >> 1; s = from_state[middle]; if (s == state) return (middle); else if (s < state) low = middle + 1; else high = middle - 1; } } void initialize_F(void) { int i; int j; int k; shifts *sp; short *edge; unsigned *rowp; short *rp; short **reads; int nedges; int stateno; int symbol; int nwords; nwords = ngotos * tokensetsize; F = NEW2(nwords, unsigned); reads = NEW2(ngotos, short *); edge = NEW2(ngotos + 1, short); nedges = 0; rowp = F; for (i = 0; i < ngotos; i++) { stateno = to_state[i]; sp = shift_table[stateno]; if (sp) { k = sp->nshifts; for (j = 0; j < k; j++) { symbol = accessing_symbol[sp->shift[j]]; if (ISVAR(symbol)) break; SETBIT(rowp, symbol); } for (; j < k; j++) { symbol = accessing_symbol[sp->shift[j]]; if (nullable[symbol]) edge[nedges++] = map_goto(stateno, symbol); } if (nedges) { reads[i] = rp = NEW2(nedges + 1, short); for (j = 0; j < nedges; j++) rp[j] = edge[j]; rp[nedges] = -1; nedges = 0; } } rowp += tokensetsize; } SETBIT(F, 0); digraph(reads); for (i = 0; i < ngotos; i++) { if (reads[i]) FREE(reads[i]); } FREE(reads); FREE(edge); } void build_relations(void) { int i; int j; int k; short *rulep; short *rp; shifts *sp; int length; int nedges; int done; int state1; int stateno; int symbol1; int symbol2; short *shortp; short *edge; short *states; short **new_includes; includes = NEW2(ngotos, short *); edge = NEW2(ngotos + 1, short); states = NEW2(maxrhs + 1, short); for (i = 0; i < ngotos; i++) { nedges = 0; state1 = from_state[i]; symbol1 = accessing_symbol[to_state[i]]; for (rulep = derives[symbol1]; *rulep >= 0; rulep++) { length = 1; states[0] = state1; stateno = state1; for (rp = ritem + rrhs[*rulep]; *rp >= 0; rp++) { symbol2 = *rp; sp = shift_table[stateno]; k = sp->nshifts; for (j = 0; j < k; j++) { stateno = sp->shift[j]; if (accessing_symbol[stateno] == symbol2) break; } states[length++] = stateno; } add_lookback_edge(stateno, *rulep, i); length--; done = 0; while (!done) { done = 1; rp--; if (ISVAR(*rp)) { stateno = states[--length]; edge[nedges++] = map_goto(stateno, *rp); if (nullable[*rp] && length > 0) done = 0; } } } if (nedges) { includes[i] = shortp = NEW2(nedges + 1, short); for (j = 0; j < nedges; j++) shortp[j] = edge[j]; shortp[nedges] = -1; } } new_includes = transpose(includes, ngotos); for (i = 0; i < ngotos; i++) if (includes[i]) FREE(includes[i]); FREE(includes); includes = new_includes; FREE(edge); FREE(states); } void add_lookback_edge(int stateno,int ruleno,int gotono) { int i, k; int found; shorts *sp; i = lookaheads[stateno]; k = lookaheads[stateno + 1]; found = 0; while (!found && i < k) { if (LAruleno[i] == ruleno) found = 1; else ++i; } assert(found); sp = NEW(shorts); sp->next = lookback[i]; sp->value = gotono; lookback[i] = sp; } short **transpose(short **R,int n) { short **new_R; short **temp_R; short *nedges; short *sp; int i; int k; nedges = NEW2(n, short); for (i = 0; i < n; i++) { sp = R[i]; if (sp) { while (*sp >= 0) nedges[*sp++]++; } } new_R = NEW2(n, short *); temp_R = NEW2(n, short *); for (i = 0; i < n; i++) { k = nedges[i]; if (k > 0) { sp = NEW2(k + 1, short); new_R[i] = sp; temp_R[i] = sp; sp[k] = -1; } } FREE(nedges); for (i = 0; i < n; i++) { sp = R[i]; if (sp) { while (*sp >= 0) *temp_R[*sp++]++ = i; } } FREE(temp_R); return (new_R); } void compute_FOLLOWS(void) { digraph(includes); } void compute_lookaheads(void) { int i, n; unsigned *fp1, *fp2, *fp3; shorts *sp, *next; unsigned *rowp; rowp = LA; n = lookaheads[nstates]; for (i = 0; i < n; i++) { fp3 = rowp + tokensetsize; for (sp = lookback[i]; sp; sp = sp->next) { fp1 = rowp; fp2 = F + tokensetsize * sp->value; while (fp1 < fp3) *fp1++ |= *fp2++; } rowp = fp3; } for (i = 0; i < n; i++) for (sp = lookback[i]; sp; sp = next) { next = sp->next; FREE(sp); } FREE(lookback); FREE(F); } void digraph(short **relation) { int i; infinity = ngotos + 2; INDEX = NEW2(ngotos + 1, short); VERTICES = NEW2(ngotos + 1, short); top = 0; R = relation; for (i = 0; i < ngotos; i++) INDEX[i] = 0; for (i = 0; i < ngotos; i++) { if (INDEX[i] == 0 && R[i]) traverse(i); } FREE(INDEX); FREE(VERTICES); } void traverse(int i) { unsigned *fp1; unsigned *fp2; unsigned *fp3; int j; short *rp; int height; unsigned *base; VERTICES[++top] = i; INDEX[i] = height = top; base = F + i * tokensetsize; fp3 = base + tokensetsize; rp = R[i]; if (rp) { while ((j = *rp++) >= 0) { if (INDEX[j] == 0) traverse(j); if (INDEX[i] > INDEX[j]) INDEX[i] = INDEX[j]; fp1 = base; fp2 = F + j * tokensetsize; while (fp1 < fp3) *fp1++ |= *fp2++; } } if (INDEX[i] == height) { for (;;) { j = VERTICES[top--]; INDEX[j] = infinity; if (i == j) break; fp1 = base; fp2 = F + j * tokensetsize; while (fp1 < fp3) *fp2++ = *fp1++; } } } byaccj1.15/src/lr0.c0000755000076500000240000002167307444073365013457 0ustar thurkastaff#include #include "defs.h" extern short *itemset; extern short *itemsetend; extern unsigned *ruleset; int nstates; core *first_state; shifts *first_shift; reductions *first_reduction; int get_state(); core *new_state(); static core **state_set; static core *this_state; static core *last_state; static shifts *last_shift; static reductions *last_reduction; static int nshifts; static short *shift_symbol; static short *redset; static short *shiftset; static short **kernel_base; static short **kernel_end; static short *kernel_items; void allocate_itemsets(void) { short *itemp; short *item_end; int symbol; int i; int count; int max; short *symbol_count; count = 0; symbol_count = NEW2(nsyms, short); item_end = ritem + nitems; for (itemp = ritem; itemp < item_end; itemp++) { symbol = *itemp; if (symbol >= 0) { count++; symbol_count[symbol]++; } } kernel_base = NEW2(nsyms, short *); kernel_items = NEW2(count, short); count = 0; max = 0; for (i = 0; i < nsyms; i++) { kernel_base[i] = kernel_items + count; count += symbol_count[i]; if (max < symbol_count[i]) max = symbol_count[i]; } shift_symbol = symbol_count; kernel_end = NEW2(nsyms, short *); } void allocate_storage(void) { allocate_itemsets(); shiftset = NEW2(nsyms, short); redset = NEW2(nrules + 1, short); state_set = NEW2(nitems, core *); } void append_states(void) { int i; int j; int symbol; #ifdef TRACE fprintf(stderr, "Entering append_states()\n"); #endif for (i = 1; i < nshifts; i++) { symbol = shift_symbol[i]; j = i; while (j > 0 && shift_symbol[j - 1] > symbol) { shift_symbol[j] = shift_symbol[j - 1]; j--; } shift_symbol[j] = symbol; } for (i = 0; i < nshifts; i++) { symbol = shift_symbol[i]; shiftset[i] = get_state(symbol); } } void free_storage(void) { FREE(shift_symbol); FREE(redset); FREE(shiftset); FREE(kernel_base); FREE(kernel_end); FREE(kernel_items); FREE(state_set); } void generate_states(void) { allocate_storage(); itemset = NEW2(nitems, short); ruleset = NEW2(WORDSIZE(nrules), unsigned); set_first_derives(); initialize_states(); while (this_state) { closure(this_state->items, this_state->nitems); save_reductions(); new_itemsets(); append_states(); if (nshifts > 0) save_shifts(); this_state = this_state->next; } finalize_closure(); free_storage(); } int get_state(int symbol) { int key; short *isp1; short *isp2; short *iend; core *sp; int found; int n; #ifdef TRACE fprintf(stderr, "Entering get_state(%d)\n", symbol); #endif isp1 = kernel_base[symbol]; iend = kernel_end[symbol]; n = iend - isp1; key = *isp1; assert(0 <= key && key < nitems); sp = state_set[key]; if (sp) { found = 0; while (!found) { if (sp->nitems == n) { found = 1; isp1 = kernel_base[symbol]; isp2 = sp->items; while (found && isp1 < iend) { if (*isp1++ != *isp2++) found = 0; } } if (!found) { if (sp->link) { sp = sp->link; } else { sp = sp->link = new_state(symbol); found = 1; } } } } else { state_set[key] = sp = new_state(symbol); } return (sp->number); } void initialize_states(void) { int i; short *start_derives; core *p; start_derives = derives[start_symbol]; for (i = 0; start_derives[i] >= 0; ++i) continue; p = (core *) MALLOC(sizeof(core) + i*sizeof(short)); if (p == 0) no_space(); p->next = 0; p->link = 0; p->number = 0; p->accessing_symbol = 0; p->nitems = i; for (i = 0; start_derives[i] >= 0; ++i) p->items[i] = rrhs[start_derives[i]]; first_state = last_state = this_state = p; nstates = 1; } void new_itemsets(void) { int i; int shiftcount; short *isp; short *ksp; int symbol; for (i = 0; i < nsyms; i++) kernel_end[i] = 0; shiftcount = 0; isp = itemset; while (isp < itemsetend) { i = *isp++; symbol = ritem[i]; if (symbol > 0) { ksp = kernel_end[symbol]; if (!ksp) { shift_symbol[shiftcount++] = symbol; ksp = kernel_base[symbol]; } *ksp++ = i + 1; kernel_end[symbol] = ksp; } } nshifts = shiftcount; } core *new_state(int symbol) { int n; core *p; short *isp1; short *isp2; short *iend; #ifdef TRACE fprintf(stderr, "Entering new_state(%d)\n", symbol); #endif if (nstates >= MAXSHORT) fatal("too many states"); isp1 = kernel_base[symbol]; iend = kernel_end[symbol]; n = iend - isp1; p = (core *) allocate((unsigned) (sizeof(core) + (n - 1) * sizeof(short))); p->accessing_symbol = symbol; p->number = nstates; p->nitems = n; isp2 = p->items; while (isp1 < iend) *isp2++ = *isp1++; last_state->next = p; last_state = p; nstates++; return (p); } /* show_cores is used for debugging */ void show_cores(void) { core *p; int i, j, k, n; int itemno; k = 0; for (p = first_state; p; ++k, p = p->next) { if (k) printf("\n"); printf("state %d, number = %d, accessing symbol = %s\n", k, p->number, symbol_name[p->accessing_symbol]); n = p->nitems; for (i = 0; i < n; ++i) { itemno = p->items[i]; printf("%4d ", itemno); j = itemno; while (ritem[j] >= 0) ++j; printf("%s :", symbol_name[rlhs[-ritem[j]]]); j = rrhs[-ritem[j]]; while (j < itemno) printf(" %s", symbol_name[ritem[j++]]); printf(" ."); while (ritem[j] >= 0) printf(" %s", symbol_name[ritem[j++]]); printf("\n"); fflush(stdout); } } } /* show_ritems is used for debugging */ void show_ritems(void) { int i; for (i = 0; i < nitems; ++i) printf("ritem[%d] = %d\n", i, ritem[i]); } /* show_rrhs is used for debugging */ void show_rrhs(void) { int i; for (i = 0; i < nrules; ++i) printf("rrhs[%d] = %d\n", i, rrhs[i]); } /* show_shifts is used for debugging */ void show_shifts(void) { shifts *p; int i, j, k; k = 0; for (p = first_shift; p; ++k, p = p->next) { if (k) printf("\n"); printf("shift %d, number = %d, nshifts = %d\n", k, p->number,p->nshifts); j = p->nshifts; for (i = 0; i < j; ++i) printf("\t%d\n", p->shift[i]); } } void save_shifts(void) { shifts *p; short *sp1; short *sp2; short *send; p = (shifts *) allocate((unsigned) (sizeof(shifts) + (nshifts - 1) * sizeof(short))); p->number = this_state->number; p->nshifts = nshifts; sp1 = shiftset; sp2 = p->shift; send = shiftset + nshifts; while (sp1 < send) *sp2++ = *sp1++; if (last_shift) { last_shift->next = p; last_shift = p; } else { first_shift = p; last_shift = p; } } void save_reductions(void) { short *isp; short *rp1; short *rp2; int item; int count; reductions *p; short *rend; count = 0; for (isp = itemset; isp < itemsetend; isp++) { item = ritem[*isp]; if (item < 0) { redset[count++] = -item; } } if (count) { p = (reductions *) allocate((unsigned) (sizeof(reductions) + (count - 1) * sizeof(short))); p->number = this_state->number; p->nreds = count; rp1 = redset; rp2 = p->rules; rend = rp1 + count; while (rp1 < rend) *rp2++ = *rp1++; if (last_reduction) { last_reduction->next = p; last_reduction = p; } else { first_reduction = p; last_reduction = p; } } } void set_derives(void) { int i, k; int lhs; short *rules; derives = NEW2(nsyms, short *); rules = NEW2(nvars + nrules, short); k = 0; for (lhs = start_symbol; lhs < nsyms; lhs++) { derives[lhs] = rules + k; for (i = 0; i < nrules; i++) { if (rlhs[i] == lhs) { rules[k] = i; k++; } } rules[k] = -1; k++; } #ifdef DEBUG print_derives(); #endif } void free_derives(void) { FREE(derives[start_symbol]); FREE(derives); } #ifdef DEBUG void print_derives(void) { int i; short *sp; printf("\nDERIVES\n\n"); for (i = start_symbol; i < nsyms; i++) { printf("%s derives ", symbol_name[i]); for (sp = derives[i]; *sp >= 0; sp++) { printf(" %d", *sp); } putchar('\n'); } putchar('\n'); } #endif void set_nullable(void) { int i, j; int empty; int done; nullable = MALLOC(nsyms); if (nullable == 0) no_space(); for (i = 0; i < nsyms; ++i) nullable[i] = 0; done = 0; while (!done) { done = 1; for (i = 1; i < nitems; i++) { empty = 1; while ((j = ritem[i]) >= 0) { if (!nullable[j]) empty = 0; ++i; } if (empty) { j = rlhs[-j]; if (!nullable[j]) { nullable[j] = 1; done = 0; } } } } #ifdef DEBUG for (i = 0; i < nsyms; i++) { if (nullable[i]) printf("%s is nullable\n", symbol_name[i]); else printf("%s is not nullable\n", symbol_name[i]); } #endif } void free_nullable(void) { FREE(nullable); } void lr0(void) { set_derives(); set_nullable(); generate_states(); } byaccj1.15/src/main.c0000755000076500000240000003257210514746160013676 0ustar thurkastaff#include #include #include #ifndef __WIN32__ /*rwj -- make portable*/ #include #else #include #endif #include "defs.h" char dflag; char lflag; char rflag; char tflag; char vflag; /*##### JAVA FLAGS ####*/ char jflag; /* Are we generating Java? Yes/No */ char *jclass_name; /* Class name of this parser. Default = "Parser" */ char *jpackage_name; /* Value of "package XXXXX;" Default = none */ char *jextend_name; /* Value of "extends XXXXX" Default = none */ char *jimplement_name; /* Value of "implements XXXXX" Default = none */ char *jsemantic_type; /* Class name of semantic value */ char jrun; /* Do we provide a run()? Yes/No Default y */ char jconstruct; /* Do we provide constructors? Yes/No Default y */ int jstack_size; /* Semantic value stack size */ /* yio 20020304 */ int jdebug; int jfinal_class; char *jyyparse_throws; char *file_prefix = "y"; char *myname = "yacc"; char *temp_form = "yacc.XXXXXXX"; int lineno; int outline; char *action_file_name; char *code_file_name; char *defines_file_name; char *input_file_name = ""; char *output_file_name; char *text_file_name; char *union_file_name; char *verbose_file_name; FILE *action_file; /* a temp file, used to save actions associated */ /* with rules until the parser is written */ FILE *code_file; /* y.code.c (used when the -r option is specified) */ FILE *defines_file; /* y.tab.h */ FILE *input_file; /* the input file */ FILE *output_file; /* y.tab.c */ FILE *text_file; /* a temp file, used to save text until all */ /* symbols have been defined */ FILE *union_file; /* a temp file, used to save the union */ /* definition until all symbol have been */ /* defined */ FILE *verbose_file; /* y.output */ int nitems; int nrules; int nsyms; int ntokens; int nvars; int start_symbol; char **symbol_name; short *symbol_value; short *symbol_prec; char *symbol_assoc; short *ritem; short *rlhs; short *rrhs; short *rprec; char *rassoc; short **derives; char *nullable; void done(int k) { if (action_file) { fclose(action_file); unlink(action_file_name); } if (text_file) { fclose(text_file); unlink(text_file_name); } if (union_file) { fclose(union_file); unlink(union_file_name); } exit(k); } void onintr(int flag) { done(1); } void set_signals(void) { #ifndef __WIN32__ /*rwj -- make portable*/ if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, onintr); if (signal(SIGTERM, SIG_IGN) != SIG_IGN) signal(SIGTERM, onintr); if (signal(SIGHUP, SIG_IGN) != SIG_IGN) signal(SIGHUP, onintr); #endif } void usage(void) { fprintf(stderr, "usage:\n %s [-dlrtvj] [-b file_prefix] [-Joption] filename\n", myname); fprintf(stderr," where -Joption is one or more of:\n"); fprintf(stderr," -J\n"); fprintf(stderr," -Jclass=className\n"); fprintf(stderr," -Jvalue=valueClassName (avoids automatic value class creation)\n"); fprintf(stderr," -Jpackage=packageName\n"); fprintf(stderr," -Jextends=extendName\n"); fprintf(stderr," -Jimplements=implementsName\n"); fprintf(stderr," -Jsemantic=semanticType\n"); fprintf(stderr," -Jnorun\n"); fprintf(stderr," -Jnoconstruct\n"); fprintf(stderr," -Jstack=SIZE (default 500)\n"); fprintf(stderr," -Jnodebug (omits debugging code for better performance)\n"); fprintf(stderr," -Jfinal (makes generated class final)\n"); fprintf(stderr," -Jthrows (declares thrown exceptions for yyparse() method)\n"); exit(1); } void setJavaDefaults(void) { jflag =0; jclass_name ="Parser"; /* Class name of this parser. Default = "Parser" */ jpackage_name =""; /* Value of "package XXXXX;" Default = none */ jextend_name =""; /* Value of "extends XXXXX" Default = none */ jimplement_name=""; /* Value of "implements XXXXX" Default = none */ jsemantic_type =""; /* Type of semantic value Default = none */ jrun =1; /* Provide a default run method */ jconstruct =1; /* Provide default constructors */ jstack_size =500; /* Default stack size */ /* yio 20020304: added new flags */ jdebug = TRUE; /* include debugging code in parser? */ jfinal_class = FALSE; /* Make the class final? */ jyyparse_throws = ""; /* Which exceptions yyparse() throws */ } void getJavaArg(char *option) { int len; jflag=1; if (!option || !(*option)) return; len=strlen(option); if (strncmp("class=",option,6)==0 && len>6) jclass_name=&(option[6]); else if (strncmp("package=",option,8)==0 && len>8) jpackage_name=&(option[8]); else if (strncmp("extends=",option,8)==0 && len>8) jextend_name=&(option[8]); else if (strncmp("implements=",option,11)==0 && len>11) jimplement_name=&(option[11]); else if (strncmp("semantic=",option,9)==0 && len>9) jsemantic_type=&(option[9]); else if (strcmp("norun",option)==0) jrun=0; else if (strcmp("noconstruct",option)==0) jconstruct=0; else if (strncmp("stack=",option,6)==0 && len>6) jstack_size=atoi(&(option[6])); /* yio 20020304: added two new flags */ else if (strncmp("nodebug",option,7)==0) jdebug=FALSE; else if (strncmp("final",option,5)==0) jfinal_class=TRUE; else if (strncmp("throws=",option,6)==0 && len>6) jyyparse_throws=&(option[7]); } void getargs(int argc,char **argv) { int i; char *s; setJavaDefaults(); /* rwj */ if (argc > 0) myname = argv[0]; for (i = 1; i < argc; ++i) { s = argv[i]; if (*s != '-') break; switch (*++s) { case '\0': input_file = stdin; if (i + 1 < argc) usage(); return; case '-': ++i; goto no_more_options; case 'b': if (*++s) file_prefix = s; else if (++i < argc) file_prefix = argv[i]; else usage(); continue; case 'd': dflag = 1; break; case 'l': lflag = 1; break; case 'r': rflag = 1; break; case 't': tflag = 1; break; case 'v': vflag = 1; break; case 'J': /* rwj -- for Java! */ jflag = 1; getJavaArg(&(s[1])); continue; default: usage(); } for (;;) /*single letter options ex: yacc -iJr file.y */ { switch (*++s) { case '\0': goto end_of_option; case 'd': dflag = 1; break; case 'l': lflag = 1; break; case 'r': rflag = 1; break; case 't': tflag = 1; break; case 'v': vflag = 1; break; case 'J': /* rwj -- for java*/ jflag = 1; break; default: usage(); } } end_of_option:; } no_more_options:; if (i + 1 != argc) usage(); input_file_name = argv[i]; } char *allocate(unsigned n) { char *p; p = NULL; if (n) { p = CALLOC(1, n); if (!p) no_space(); } return (p); } void create_file_names(void) { int i, len, jclass_len; char *tmpdir; tmpdir = getenv("TMPDIR"); #ifdef __WIN32__ /*rwj -- make portable*/ if (tmpdir == 0) tmpdir = "."; #else if (tmpdir == 0) tmpdir = "/tmp"; #endif len = strlen(tmpdir); i = len + 13; if (len && tmpdir[len-1] != '/') ++i; action_file_name = MALLOC(i); if (action_file_name == 0) no_space(); text_file_name = MALLOC(i); if (text_file_name == 0) no_space(); union_file_name = MALLOC(i); if (union_file_name == 0) no_space(); output_file_name = MALLOC(i); /* yio */ if (output_file_name == 0) no_space(); strcpy(action_file_name, tmpdir); strcpy(text_file_name, tmpdir); strcpy(union_file_name, tmpdir); strcpy(output_file_name, tmpdir); if (len && tmpdir[len - 1] != '/') { action_file_name[len] = '/'; text_file_name[len] = '/'; union_file_name[len] = '/'; output_file_name[len] = '/'; ++len; } strcpy(action_file_name + len, temp_form); strcpy(text_file_name + len, temp_form); strcpy(union_file_name + len, temp_form); strcpy(output_file_name + len, temp_form); action_file_name[len + 5] = 'a'; text_file_name[len + 5] = 't'; union_file_name[len + 5] = 'u'; output_file_name[len + 5] = 'o'; mktemp(action_file_name); mktemp(text_file_name); mktemp(union_file_name); mktemp(output_file_name); len = strlen(file_prefix); if (rflag) { code_file_name = MALLOC(len + strlen(CODE_SUFFIX) + 1); if (code_file_name == 0) no_space(); strcpy(code_file_name, file_prefix); strcpy(code_file_name + len, CODE_SUFFIX); } else code_file_name = output_file_name; if (dflag) { if (jflag) { jclass_len = strlen(jclass_name); defines_file_name = MALLOC(jclass_len + strlen(JAVA_INTERFACE_SUFFIX JAVA_OUTPUT_SUFFIX) + 1);/*rwj for 'Tokens.java\0' */ if (defines_file_name == 0) no_space(); strcpy(defines_file_name, jclass_name); strcpy(defines_file_name + jclass_len, JAVA_INTERFACE_SUFFIX JAVA_OUTPUT_SUFFIX); if (jimplement_name && strlen(jimplement_name)>0) { char *impl_name=MALLOC(strlen(jimplement_name)+jclass_len + strlen(JAVA_INTERFACE_SUFFIX)+2); if (impl_name == 0) no_space(); strcpy(impl_name,jimplement_name); jimplement_name=impl_name; strcat(jimplement_name,","); strcat(jimplement_name,jclass_name); strcat(jimplement_name,JAVA_INTERFACE_SUFFIX); } else { jimplement_name = MALLOC(jclass_len + strlen(JAVA_INTERFACE_SUFFIX)+1); if (jimplement_name == 0) no_space(); strcpy(jimplement_name,jclass_name); strcpy(jimplement_name + jclass_len, JAVA_INTERFACE_SUFFIX); } } else { defines_file_name = MALLOC(len + strlen(DEFINES_SUFFIX) + 1); if (defines_file_name == 0) no_space(); strcpy(defines_file_name, file_prefix); strcpy(defines_file_name + len, DEFINES_SUFFIX); } } if (vflag) { verbose_file_name = MALLOC(len + strlen(VERBOSE_SUFFIX) + 1); if (verbose_file_name == 0) no_space(); strcpy(verbose_file_name, file_prefix); strcpy(verbose_file_name + len, VERBOSE_SUFFIX); } } /* yio 20020304: copy the output from the temporary file to the * final output file. */ void write_temporary_output(void) { int len; char buf[8192]; char *temp_output_file_name; FILE *temp_output_file; temp_output_file = output_file; temp_output_file_name = output_file_name; fclose(temp_output_file); temp_output_file = fopen(temp_output_file_name,"r"); if (temp_output_file == 0) open_error(temp_output_file_name); /* construct the filename of the final output file */ if (jflag)/*rwj*/ { len = strlen(jclass_name); output_file_name = MALLOC(len + strlen(JAVA_OUTPUT_SUFFIX) + 1);/*rwj for '.java\0' */ if (output_file_name == 0) no_space(); strcpy(output_file_name, jclass_name); strcpy(output_file_name + len, JAVA_OUTPUT_SUFFIX); } else { len = strlen(file_prefix); output_file_name = MALLOC(len + strlen(OUTPUT_SUFFIX) + 1); if (output_file_name == 0) no_space(); strcpy(output_file_name, file_prefix); strcpy(output_file_name + len, OUTPUT_SUFFIX); } output_file = fopen(output_file_name, "w"); if (output_file == 0) open_error(output_file_name); if (!rflag) { code_file_name = output_file_name; code_file = output_file; } /* copy the output from the temp file to the output file */ do { len = fread(buf,sizeof(char),8192,temp_output_file); fwrite(buf,sizeof(char),len,output_file); } while (len > 0 && !feof(temp_output_file)); fclose(temp_output_file); unlink(temp_output_file_name); FREE(temp_output_file_name); } void open_files(void) { create_file_names(); if (input_file == 0) { input_file = fopen(input_file_name, "r"); if (input_file == 0) open_error(input_file_name); } action_file = fopen(action_file_name, "w"); if (action_file == 0) open_error(action_file_name); text_file = fopen(text_file_name, "w"); if (text_file == 0) open_error(text_file_name); if (vflag) { verbose_file = fopen(verbose_file_name, "w"); if (verbose_file == 0) open_error(verbose_file_name); } if (dflag) { defines_file = fopen(defines_file_name, "w"); if (defines_file == 0) open_error(defines_file_name); union_file = fopen(union_file_name, "w"); if (union_file == 0) open_error(union_file_name); } output_file = fopen(output_file_name, "w"); if (output_file == 0) open_error(output_file_name); if (rflag) { code_file = fopen(code_file_name, "w"); if (code_file == 0) open_error(code_file_name); } else code_file = output_file; } int main(int argc,char **argv) { set_signals(); getargs(argc, argv); open_files(); reader(); /* yio 20020304: write the output we stored in the temporary output file * so that we could read arguments from the grammar file that may affect * the name of the output file. */ write_temporary_output(); lr0(); lalr(); make_parser(); verbose(); output(); done(0); /*NOTREACHED*/ return 1; } byaccj1.15/src/Makefile0000755000076500000240000000423211112464236014232 0ustar thurkastaff################################################# ## Makefile for Byacc/Java ## Date: 06 Aug 00 ## Author: Bob Jamison ################################################# CC = gcc CFLAGS = -O -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -mmacosx-version-min=10.4 LDFLAGS = -static -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk TAR = tar GZIP = gzip VERS = byaccj1.15 JAVA = /usr/java ZIP = zip INC = -I. OBJ = closure.o \ error.o \ lalr.o \ lr0.o \ main.o \ mkpar.o \ output.o \ reader.o \ skeleton.o \ symtab.o \ verbose.o \ warshall.o irix: yacc mv yacc yacc.irix linux: yacc mv yacc yacc.linux solaris: yacc mv yacc yacc.solaris all: yacc dist: ( \ cd .. ; \ /bin/rm -rf $(VERS) ; \ /bin/mkdir -p $(VERS) ; \ /bin/mkdir -p dist ; \ /bin/cp -r docs $(VERS) ; \ /bin/mkdir -p $(VERS)/src ; \ /bin/cp src/*.c $(VERS)/src ; \ /bin/cp src/*.h $(VERS)/src ; \ /bin/cp src/Makefile $(VERS)/src ; \ /bin/cp src/Makefile.bcc $(VERS)/src ; \ /bin/cp -f src/yacc.irix $(VERS) ; \ /bin/cp -f src/yacc.solaris $(VERS) ; \ /bin/cp -f src/yacc.linux $(VERS) ; \ /bin/cp -f src/yacc.exe $(VERS) ; \ /bin/cp src/README $(VERS) ; \ $(TAR) -cvf - $(VERS) | $(GZIP) > dist/$(VERS).tar.gz ;\ $(ZIP) dist/$(VERS).zip $(VERS) \ ) SRCS = closure.c \ error.c \ lalr.c \ lr0.c \ main.c \ mkpar.c \ output.c \ reader.c \ skeleton.c \ symtab.c \ verbose.c \ warshall.c %.o : %.c $(CC) -c $(CFLAGS) $(INC) $< -o $@ yacc: $(OBJ) $(CC) -o yacc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -mmacosx-version-min=10.4 $(OBJ) @echo "done" clean: /bin/rm -rf *.o *.obj yacc y.tab.c *.java *.class /bin/rm -rf yacc.linux yacc.irix yacc.solaris yacc.exe (cd .. ; /bin/rm -rf $(VERS) ; /bin/rm -rf dist ) ### Dependencies closure.o: closure.c defs.h error.o: error.c defs.h lalr.o: lalr.c defs.h lr0.o: lr0.c defs.h main.o: main.c defs.h mkpar.o: mkpar.c defs.h output.o: output.c defs.h reader.o: reader.c defs.h skeleton.o: skeleton.c defs.h symtab.o: symtab.c defs.h verbose.o: verbose.c defs.h warshall.o: warshall.c defs.h byaccj1.15/src/Makefile.bcc0000755000076500000240000000204111111765265014761 0ustar thurkastaff################################################# ## Borland C++ 5 Makefile for Byacc/Java ## Date: 01 Jan 01 ## Author: Bob Jamison ################################################# CC = bcc32 CFLAGS = -O -WC -w-8004 -w-8057 TAR = /bin/tar GZIP = /usr/sbin/gzip VERS = byaccj1.15 OBJ = closure.obj \ error.obj \ lalr.obj \ lr0.obj \ main.obj \ mkpar.obj \ output.obj \ reader.obj \ skeleton.obj \ symtab.obj \ verbose.obj \ warshall.obj all: yacc.exe SRCS = closure.c \ error.c \ lalr.c \ lr0.c \ main.c \ mkpar.c \ output.c \ reader.c \ skeleton.c \ symtab.c \ verbose.c \ warshall.c yacc.exe: $(OBJ) bcc32 -eyacc.exe $(OBJ) clean: del /q *.obj *.exe y.tab.c *.java *.class ### closure.obj: closure.c defs.h error.obj: error.c defs.h lalr.obj: lalr.c defs.h lr0.obj: lr0.c defs.h main.obj: main.c defs.h mkpar.obj: mkpar.c defs.h output.obj: output.c defs.h reader.obj: reader.c defs.h skeleton.obj: skeleton.c defs.h symtab.obj: symtab.c defs.h verbose.obj: verbose.c defs.h warshall.obj: warshall.c defs.h byaccj1.15/src/mkpar.c0000755000076500000240000001352107444073365014065 0ustar thurkastaff#include #include "defs.h" action **parser; int SRtotal; int RRtotal; short *SRconflicts; short *RRconflicts; short *defred; short *rules_used; short nunused; short final_state; static int SRcount; static int RRcount; extern action *parse_actions(); extern action *get_shifts(); extern action *add_reductions(); extern action *add_reduce(); void make_parser(void) { int i; parser = NEW2(nstates, action *); for (i = 0; i < nstates; i++) parser[i] = parse_actions(i); find_final_state(); remove_conflicts(); unused_rules(); if (SRtotal + RRtotal > 0) total_conflicts(); defreds(); } action *parse_actions(int stateno) { action *actions; actions = get_shifts(stateno); actions = add_reductions(stateno, actions); return (actions); } action *get_shifts(int stateno) { action *actions, *temp; shifts *sp; short *to_state; int i, k; int symbol; actions = 0; sp = shift_table[stateno]; if (sp) { to_state = sp->shift; for (i = sp->nshifts - 1; i >= 0; i--) { k = to_state[i]; symbol = accessing_symbol[k]; if (ISTOKEN(symbol)) { temp = NEW(action); temp->next = actions; temp->symbol = symbol; temp->number = k; temp->prec = symbol_prec[symbol]; temp->action_code = SHIFT; temp->assoc = symbol_assoc[symbol]; actions = temp; } } } return (actions); } action *add_reductions(int stateno,action *actions) { int i, j, m, n; int ruleno, tokensetsize; unsigned *rowp; tokensetsize = WORDSIZE(ntokens); m = lookaheads[stateno]; n = lookaheads[stateno + 1]; for (i = m; i < n; i++) { ruleno = LAruleno[i]; rowp = LA + i * tokensetsize; for (j = ntokens - 1; j >= 0; j--) { if (BIT(rowp, j)) actions = add_reduce(actions, ruleno, j); } } return (actions); } action *add_reduce(action *actions,int ruleno,int symbol) { action *temp, *prev, *next; prev = 0; for (next = actions; next && next->symbol < symbol; next = next->next) prev = next; while (next && next->symbol == symbol && next->action_code == SHIFT) { prev = next; next = next->next; } while (next && next->symbol == symbol && next->action_code == REDUCE && next->number < ruleno) { prev = next; next = next->next; } temp = NEW(action); temp->next = next; temp->symbol = symbol; temp->number = ruleno; temp->prec = rprec[ruleno]; temp->action_code = REDUCE; temp->assoc = rassoc[ruleno]; if (prev) prev->next = temp; else actions = temp; return (actions); } void find_final_state(void) { int goal, i; short *to_state; shifts *p; p = shift_table[0]; to_state = p->shift; goal = ritem[1]; for (i = p->nshifts - 1; i >= 0; --i) { final_state = to_state[i]; if (accessing_symbol[final_state] == goal) break; } } void unused_rules(void) { int i; action *p; rules_used = (short *) MALLOC(nrules*sizeof(short)); if (rules_used == 0) no_space(); for (i = 0; i < nrules; ++i) rules_used[i] = 0; for (i = 0; i < nstates; ++i) { for (p = parser[i]; p; p = p->next) { if (p->action_code == REDUCE && p->suppressed == 0) rules_used[p->number] = 1; } } nunused = 0; for (i = 3; i < nrules; ++i) if (!rules_used[i]) ++nunused; if (nunused) if (nunused == 1) fprintf(stderr, "%s: 1 rule never reduced\n", myname); else fprintf(stderr, "%s: %d rules never reduced\n", myname, nunused); } void remove_conflicts(void) { register int i; register int symbol; register action *p, *pref; SRtotal = 0; RRtotal = 0; SRconflicts = NEW2(nstates, short); RRconflicts = NEW2(nstates, short); for (i = 0; i < nstates; i++) { SRcount = 0; RRcount = 0; symbol = -1; for (p = parser[i]; p; p = p->next) { if (p->symbol != symbol) { pref = p; symbol = p->symbol; } else if (i == final_state && symbol == 0) { SRcount++; p->suppressed = 1; } else if (pref->action_code == SHIFT) { if (pref->prec > 0 && p->prec > 0) { if (pref->prec < p->prec) { pref->suppressed = 2; pref = p; } else if (pref->prec > p->prec) { p->suppressed = 2; } else if (pref->assoc == LEFT) { pref->suppressed = 2; pref = p; } else if (pref->assoc == RIGHT) { p->suppressed = 2; } else { pref->suppressed = 2; p->suppressed = 2; } } else { SRcount++; p->suppressed = 1; } } else { RRcount++; p->suppressed = 1; } } SRtotal += SRcount; RRtotal += RRcount; SRconflicts[i] = SRcount; RRconflicts[i] = RRcount; } } void total_conflicts(void) { fprintf(stderr, "%s: ", myname); if (SRtotal == 1) fprintf(stderr, "1 shift/reduce conflict"); else if (SRtotal > 1) fprintf(stderr, "%d shift/reduce conflicts", SRtotal); if (SRtotal && RRtotal) fprintf(stderr, ", "); if (RRtotal == 1) fprintf(stderr, "1 reduce/reduce conflict"); else if (RRtotal > 1) fprintf(stderr, "%d reduce/reduce conflicts", RRtotal); fprintf(stderr, ".\n"); } int sole_reduction(int stateno) { int count, ruleno; action *p; count = 0; ruleno = 0; for (p = parser[stateno]; p; p = p->next) { if (p->action_code == SHIFT && p->suppressed == 0) return (0); else if (p->action_code == REDUCE && p->suppressed == 0) { if (ruleno > 0 && p->number != ruleno) return (0); if (p->symbol != 1) ++count; ruleno = p->number; } } if (count == 0) return (0); return (ruleno); } void defreds(void) { int i; defred = NEW2(nstates, short); for (i = 0; i < nstates; i++) defred[i] = sole_reduction(i); } void free_action_row(action *p) { action *q; while (p) { q = p->next; FREE(p); p = q; } } void free_parser(void) { int i; for (i = 0; i < nstates; i++) free_action_row(parser[i]); FREE(parser); } byaccj1.15/src/new_features0000755000076500000240000000677611111765660015227 0ustar thurkastaffNew features in version 1.15: ----------------------------- Bug #1638577 (stack corruption when generating a java parser) fixed Bug #1630851 (Targets with empty right-hand side problematic in Java mode) fixed New features in version 1.14: ----------------------------- generics can be now used in semantic type Bug #1598776 ('-Jnodebug' option is broken) fixed Bug #1600683 (error recovery throws ArrayIndexOutOfBoundsException: -1) fixed fixed problem with the name of verbose file New features in version 1.13: ----------------------------- Bug #1506924 (ArrayIndexOutOfBoundException in yyparse() ) fixed src/t.y example fixed New features in version 1.12: ----------------------------- Bug #1406129 (-Jclass=X12345678 -> Segmentation fault) fixed New features in version 1.11: ----------------------------- -d is now supported with -J. It creates interface with token constants Workaround for problem when static class initializer of the generated Parser is larger than 64KB. Improved performance by removing some unused code and making use of exceptions Added "-Jnodebug" option to omit debugging code for further better performance Added "-Jfinal" option to make generated class final Added "-Jthrows" option to declares thrown exceptions for yyparse() method Added the ability to specify options within the grammar file New features in version 1.1: ---------------------------- Added the option -Jstack=NNN to allow users to set the semantic stack size New features in version 1.0: ---------------------------- The -r option has been implemented. The -r option tells Yacc to put the read-only tables in y.tab.c and the code and variables in y.code.c. Keith Bostic asked for this option so that :yyfix could be eliminated. The -l and -t options have been implemented. The -l option tells Yacc not to include #line directives in the code it produces. The -t option causes debugging code to be included in the compiled parser. The code for error recovery has been changed to implement the same algorithm as AT&T Yacc. There will still be differences in the way error recovery works because AT&T Yacc uses more default reductions than Berkeley Yacc. The environment variable TMPDIR determines the directory where temporary files will be created. If TMPDIR is defined, temporary files will be created in the directory whose pathname is the value of TMPDIR. By default, temporary files are created in /tmp. The keywords are now case-insensitive. For example, %nonassoc, %NONASSOC, %NonAssoc, and %nOnAsSoC are all equivalent. Commas and semicolons that are not part of C code are treated as commentary. Line-end comments, as in BCPL, are permitted. Line-end comments begin with // and end at the next end-of-line. Line-end comments are permitted in C code; they are converted to C comments on output. The form of y.output files has been changed to look more like those produced by AT&T Yacc. A new kind of declaration has been added. The form of the declaration is %ident string where string is a sequence of characters begining with a double quote and ending with either a double quote or the next end-of-line, whichever comes first. The declaration will cause a #ident directive to be written near the start of the output file. If a parser has been compiled with debugging code, that code can be enabled by setting an environment variable. If the environment variable YYDEBUG is set to 0, debugging output is suppressed. If it is set to 1, debugging output is written to standard output. byaccj1.15/src/no_warranty0000755000076500000240000000023407441711572015066 0ustar thurkastaff Berkeley Yacc is distributed with no warranty whatever. The author and any other contributors take no responsibility for the consequences of its use. byaccj1.15/src/._output.c0000755000076500000240000000025311107241030014477 0ustar thurkastaffMac OS X  2y«ATTR—ÒM«œœcom.apple.TextEncodingUTF-8;134217984byaccj1.15/src/output.c0000755000076500000240000010211511107241030014262 0ustar thurkastaff#include #include #include "defs.h" static int nvectors; static int nentries; static short **froms; static short **tos; static short *tally; static short *width; static short *state_count; static short *order; static short *base; static short *pos; static int maxtable; static short *table; static short *check; static int lowzero; static int high; void output(void) { free_itemsets(); free_shifts(); free_reductions(); output_stored_text(); if (jflag) /*rwj*/ { write_section(jheader); output_stype(); } output_defines(); output_rule_data(); output_yydefred(); output_actions(); free_parser(); output_debug(); if (!jflag) /*rwj*/ output_stype(); if (rflag) write_section(tables); if (!jflag) /*rwj*/ write_section(header); output_trailing_text(); if (jflag) { /*rwj*/ /* yio 20020304: nodebug and throws options */ if (jdebug == TRUE) { write_section(jbody_a); if (strlen(jyyparse_throws)>0) fprintf(code_file,"throws %s\n",jyyparse_throws); write_section(jbody_b); } else { write_section(jbody_nodebug_a); if (strlen(jyyparse_throws)>0) fprintf(code_file,"throws %s\n",jyyparse_throws); write_section(jbody_nodebug_b); } } else write_section(body); output_semantic_actions(); if (jflag) { /*rwj*/ /* yio 20020304: nodebug option */ if (jdebug == TRUE) write_section(jtrailer); else write_section(jtrailer_nodebug); } else write_section(trailer); } void output_rule_data(void) { int i; int j; if (jflag) /*rwj*/ fprintf(output_file, "final static short yylhs[] = {%29d,", symbol_value[start_symbol]); else fprintf(output_file, "short yylhs[] = {%42d,", symbol_value[start_symbol]); j = 10; for (i = 3; i < nrules; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; fprintf(output_file, "%5d,", symbol_value[rlhs[i]]); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); if (jflag) /*rwj*/ fprintf(output_file, "final static short yylen[] = {%29d,",2); else fprintf(output_file, "short yylen[] = {%42d,", 2); j = 10; for (i = 3; i < nrules; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else j++; fprintf(output_file, "%5d,", rrhs[i + 1] - rrhs[i] - 1); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); } void output_yydefred(void) { int i, j; if (jflag) fprintf(output_file, "final static short yydefred[] = {%26d,", (defred[0] ? defred[0] - 2 : 0)); else fprintf(output_file, "short yydefred[] = {%39d,", (defred[0] ? defred[0] - 2 : 0)); j = 10; for (i = 1; i < nstates; i++) { if (j < 10) ++j; else { if (!rflag) ++outline; putc('\n', output_file); j = 1; } fprintf(output_file, "%5d,", (defred[i] ? defred[i] - 2 : 0)); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); } void output_actions(void) { nvectors = 2*nstates + nvars; froms = NEW2(nvectors, short *); tos = NEW2(nvectors, short *); tally = NEW2(nvectors, short); width = NEW2(nvectors, short); token_actions(); FREE(lookaheads); FREE(LA); FREE(LAruleno); FREE(accessing_symbol); goto_actions(); FREE(goto_map + ntokens); FREE(from_state); FREE(to_state); sort_actions(); pack_table(); output_base(); output_table(); output_check(); } void token_actions(void) { int i, j; int shiftcount, reducecount; int max, min; short *actionrow, *r, *s; action *p; actionrow = NEW2(2*ntokens, short); for (i = 0; i < nstates; ++i) { if (parser[i]) { for (j = 0; j < 2*ntokens; ++j) actionrow[j] = 0; shiftcount = 0; reducecount = 0; for (p = parser[i]; p; p = p->next) { if (p->suppressed == 0) { if (p->action_code == SHIFT) { ++shiftcount; actionrow[p->symbol] = p->number; } else if (p->action_code == REDUCE && p->number != defred[i]) { ++reducecount; actionrow[p->symbol + ntokens] = p->number; } } } tally[i] = shiftcount; tally[nstates+i] = reducecount; width[i] = 0; width[nstates+i] = 0; if (shiftcount > 0) { froms[i] = r = NEW2(shiftcount, short); tos[i] = s = NEW2(shiftcount, short); min = MAXSHORT; max = 0; for (j = 0; j < ntokens; ++j) { if (actionrow[j]) { if (min > symbol_value[j]) min = symbol_value[j]; if (max < symbol_value[j]) max = symbol_value[j]; *r++ = symbol_value[j]; *s++ = actionrow[j]; } } width[i] = max - min + 1; } if (reducecount > 0) { froms[nstates+i] = r = NEW2(reducecount, short); tos[nstates+i] = s = NEW2(reducecount, short); min = MAXSHORT; max = 0; for (j = 0; j < ntokens; ++j) { if (actionrow[ntokens+j]) { if (min > symbol_value[j]) min = symbol_value[j]; if (max < symbol_value[j]) max = symbol_value[j]; *r++ = symbol_value[j]; *s++ = actionrow[ntokens+j] - 2; } } width[nstates+i] = max - min + 1; } } } FREE(actionrow); } void goto_actions(void) { register int i, j, k; state_count = NEW2(nstates, short); k = default_goto(start_symbol + 1); if (jflag) /*rwj*/ fprintf(output_file, "final static short yydgoto[] = {%27d,",k); else fprintf(output_file, "short yydgoto[] = {%40d,", k); save_column(start_symbol + 1, k); j = 10; for (i = start_symbol + 2; i < nsyms; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; k = default_goto(i); fprintf(output_file, "%5d,", k); save_column(i, k); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); FREE(state_count); } int default_goto(int symbol) { int i; int m; int n; int default_state; int max; m = goto_map[symbol]; n = goto_map[symbol + 1]; if (m == n) return (0); for (i = 0; i < nstates; i++) state_count[i] = 0; for (i = m; i < n; i++) state_count[to_state[i]]++; max = 0; default_state = 0; for (i = 0; i < nstates; i++) { if (state_count[i] > max) { max = state_count[i]; default_state = i; } } return (default_state); } void save_column(int symbol,int default_state) { int i; int m; int n; short *sp; short *sp1; short *sp2; int count; int symno; m = goto_map[symbol]; n = goto_map[symbol + 1]; count = 0; for (i = m; i < n; i++) { if (to_state[i] != default_state) ++count; } if (count == 0) return; symno = symbol_value[symbol] + 2*nstates; froms[symno] = sp1 = sp = NEW2(count, short); tos[symno] = sp2 = NEW2(count, short); for (i = m; i < n; i++) { if (to_state[i] != default_state) { *sp1++ = from_state[i]; *sp2++ = to_state[i]; } } tally[symno] = count; width[symno] = sp1[-1] - sp[0] + 1; } void sort_actions(void) { int i; int j; int k; int t; int w; order = NEW2(nvectors, short); nentries = 0; for (i = 0; i < nvectors; i++) { if (tally[i] > 0) { t = tally[i]; w = width[i]; j = nentries - 1; while (j >= 0 && (width[order[j]] < w)) j--; while (j >= 0 && (width[order[j]] == w) && (tally[order[j]] < t)) j--; for (k = nentries - 1; k > j; k--) order[k + 1] = order[k]; order[j + 1] = i; nentries++; } } } void pack_table(void) { int i; int place; int state; base = NEW2(nvectors, short); pos = NEW2(nentries, short); maxtable = 1000; table = NEW2(maxtable, short); check = NEW2(maxtable, short); lowzero = 0; high = 0; for (i = 0; i < maxtable; i++) check[i] = -1; for (i = 0; i < nentries; i++) { state = matching_vector(i); if (state < 0) place = pack_vector(i); else place = base[state]; pos[i] = place; base[order[i]] = place; } for (i = 0; i < nvectors; i++) { if (froms[i]) FREE(froms[i]); if (tos[i]) FREE(tos[i]); } FREE(froms); FREE(tos); FREE(pos); } /* The function matching_vector determines if the vector specified by */ /* the input parameter matches a previously considered vector. The */ /* test at the start of the function checks if the vector represents */ /* a row of shifts over terminal symbols or a row of reductions, or a */ /* column of shifts over a nonterminal symbol. Berkeley Yacc does not */ /* check if a column of shifts over a nonterminal symbols matches a */ /* previously considered vector. Because of the nature of LR parsing */ /* tables, no two columns can match. Therefore, the only possible */ /* match would be between a row and a column. Such matches are */ /* unlikely. Therefore, to save time, no attempt is made to see if a */ /* column matches a previously considered vector. */ /* */ /* Matching_vector is poorly designed. The test could easily be made */ /* faster. Also, it depends on the vectors being in a specific */ /* order. */ int matching_vector(int vector) { int i; int j; int k; int t; int w; int match; int prev; i = order[vector]; if (i >= 2*nstates) return (-1); t = tally[i]; w = width[i]; for (prev = vector - 1; prev >= 0; prev--) { j = order[prev]; if (width[j] != w || tally[j] != t) return (-1); match = 1; for (k = 0; match && k < t; k++) { if (tos[j][k] != tos[i][k] || froms[j][k] != froms[i][k]) match = 0; } if (match) return (j); } return (-1); } int pack_vector(int vector) { int i, j, k, l; int t; int loc; int ok; short *from; short *to; int newmax; i = order[vector]; t = tally[i]; assert(t); from = froms[i]; to = tos[i]; j = lowzero - from[0]; for (k = 1; k < t; ++k) if (lowzero - from[k] > j) j = lowzero - from[k]; for (;; ++j) { if (j == 0) continue; ok = 1; for (k = 0; ok && k < t; k++) { loc = j + from[k]; if (loc >= maxtable) { if (loc >= MAXTABLE) fatal("maximum table size exceeded"); newmax = maxtable; do { newmax += 200; } while (newmax <= loc); table = (short *) REALLOC(table, newmax*sizeof(short)); if (table == 0) no_space(); check = (short *) REALLOC(check, newmax*sizeof(short)); if (check == 0) no_space(); for (l = maxtable; l < newmax; ++l) { table[l] = 0; check[l] = -1; } maxtable = newmax; } if (check[loc] != -1) ok = 0; } for (k = 0; ok && k < vector; k++) { if (pos[k] == j) ok = 0; } if (ok) { for (k = 0; k < t; k++) { loc = j + from[k]; table[loc] = to[k]; check[loc] = from[k]; if (loc > high) high = loc; } while (check[lowzero] != -1) ++lowzero; return (j); } } } void output_base(void) { int i, j; if (jflag) /*rwj*/ fprintf(output_file, "final static short yysindex[] = {%26d,",base[0]); else fprintf(output_file, "short yysindex[] = {%39d,", base[0]); j = 10; for (i = 1; i < nstates; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; fprintf(output_file, "%5d,", base[i]); } if (!rflag) outline += 2; if (jflag) /*rwj*/ fprintf(output_file, "\n};\nfinal static short yyrindex[] = {%26d,", base[nstates]); else fprintf(output_file, "\n};\nshort yyrindex[] = {%39d,", base[nstates]); j = 10; for (i = nstates + 1; i < 2*nstates; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; fprintf(output_file, "%5d,", base[i]); } if (!rflag) outline += 2; if (jflag)/*rwj*/ fprintf(output_file, "\n};\nfinal static short yygindex[] = {%26d,", base[2*nstates]); else fprintf(output_file, "\n};\nshort yygindex[] = {%39d,", base[2*nstates]); j = 10; for (i = 2*nstates + 1; i < nvectors - 1; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; fprintf(output_file, "%5d,", base[i]); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); FREE(base); } void output_table(void) { int i; int j; ++outline; if (jflag) /*rwj*/ { fprintf(code_file, "final static int YYTABLESIZE=%d;\n", high); fprintf(output_file, "static short yytable[];\nstatic { yytable();}\nstatic void yytable(){\nyytable = new short[]{%27d,", table[0]); } else { fprintf(code_file, "#define YYTABLESIZE %d\n", high); fprintf(output_file, "short yytable[] = {%40d,", table[0]); } j = 10; for (i = 1; i <= high; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; fprintf(output_file, "%5d,", table[i]); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); if (jflag) fprintf(output_file, "}\n"); FREE(table); } void output_check(void) { register int i; register int j; if (jflag) /*rwj*/ fprintf(output_file, "static short yycheck[];\nstatic { yycheck(); }\nstatic void yycheck() {\nyycheck = new short[] {%27d,",check[0]); else fprintf(output_file, "short yycheck[] = {%40d,", check[0]); j = 10; for (i = 1; i <= high; i++) { if (j >= 10) { if (!rflag) ++outline; putc('\n', output_file); j = 1; } else ++j; fprintf(output_file, "%5d,", check[i]); } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); if (jflag) fprintf(output_file, "}\n"); FREE(check); } int is_C_identifier(char *name) { char *s; int c; s = name; c = *s; if (c == '"') { c = *++s; if (!isalpha(c) && c != '_' && c != '$') return (0); while ((c = *++s) != '"') { if (!isalnum(c) && c != '_' && c != '$') return (0); } return (1); } if (!isalpha(c) && c != '_' && c != '$') return (0); while ((c = *++s)!=0) { if (!isalnum(c) && c != '_' && c != '$') return (0); } return (1); } void output_defines(void) { int c, i; char *s; if (jflag && dflag) { if (jpackage_name && strlen(jpackage_name)>0) fprintf(defines_file,"package %s;\n",jpackage_name); fprintf(defines_file, "public interface %s%s {\n",jclass_name,JAVA_INTERFACE_SUFFIX); } for (i = 2; i < ntokens; ++i) { s = symbol_name[i]; if (is_C_identifier(s)) { if (jflag) /*rwj*/ fprintf(dflag?defines_file:code_file, "public final static short "); else { fprintf(code_file, "#define "); if (dflag) fprintf(defines_file, "#define "); } c = *s; if (c == '"') { while ((c = *++s) != '"') { if (!jflag || (jflag && !dflag)) putc(c, code_file); if (dflag) putc(c, defines_file); } } else { do { if (!jflag || (jflag && !dflag)) putc(c, code_file); if (dflag) putc(c, defines_file); } while ((c = *++s)!=0); } ++outline; if (jflag) /*rwj*/ fprintf(dflag?defines_file:code_file, "=%d;\n", symbol_value[i]); else { fprintf(code_file, " %d\n", symbol_value[i]); if (dflag) fprintf(defines_file, " %d\n", symbol_value[i]); } } } ++outline; if (jflag) /*rwj*/ fprintf(code_file, "public final static short YYERRCODE=%d;\n", symbol_value[1]); else fprintf(code_file, "#define YYERRCODE %d\n", symbol_value[1]); if (dflag && unionized) { fclose(union_file); union_file = fopen(union_file_name, "r"); if (union_file == NULL) open_error(union_file_name); while ((c = getc(union_file)) != EOF) putc(c, defines_file); fprintf(defines_file, " YYSTYPE;\nextern YYSTYPE yylval;\n"); } if (jflag && dflag) fprintf(defines_file, "}\n",jclass_name,JAVA_INTERFACE_SUFFIX); } void output_stored_text(void) { int c; FILE *in, *out; fclose(text_file); text_file = fopen(text_file_name, "r"); if (text_file == NULL) open_error(text_file_name); in = text_file; if ((c = getc(in)) == EOF) return; out = code_file; if (c == '\n') ++outline; putc(c, out); while ((c = getc(in)) != EOF) { if (c == '\n') ++outline; putc(c, out); } if (!lflag) if (jflag)/*rwj*/ fprintf(out, jline_format, ++outline + 1, code_file_name); else fprintf(out, line_format, ++outline + 1, code_file_name); } void output_debug(void) { int i, j, k, max; char **symnam, *s; ++outline; if (jflag) /*rwj*/ fprintf(code_file, "final static short YYFINAL=%d;\n", final_state); else fprintf(code_file, "#define YYFINAL %d\n", final_state); outline += 3; if (!jflag)/*rwj*/ fprintf(code_file, "#ifndef YYDEBUG\n#define YYDEBUG %d\n#endif\n", tflag); if (rflag) fprintf(output_file, "#ifndef YYDEBUG\n#define YYDEBUG %d\n#endif\n", tflag); max = 0; for (i = 2; i < ntokens; ++i) if (symbol_value[i] > max) max = symbol_value[i]; ++outline; if (jflag) /*rjw*/ fprintf(code_file, "final static short YYMAXTOKEN=%d;\n", max); else fprintf(code_file, "#define YYMAXTOKEN %d\n", max); symnam = (char **) MALLOC((max+1)*sizeof(char *)); if (symnam == 0) no_space(); /* Note that it is not necessary to initialize the element */ /* symnam[max]. */ for (i = 0; i < max; ++i) symnam[i] = 0; for (i = ntokens - 1; i >= 2; --i) symnam[symbol_value[i]] = symbol_name[i]; symnam[0] = "end-of-file"; if (!rflag) ++outline; if (jflag)/*rwj*/ fprintf(output_file, "final static String yyname[] = {"); else fprintf(output_file, "#if YYDEBUG\nchar *yyname[] = {"); j = 80; for (i = 0; i <= max; ++i) { if ((s = symnam[i])!=0) { if (s[0] == '"') { k = 7; while (*++s != '"') { ++k; if (*s == '\\') { k += 2; if (*++s == '\\') ++k; } } j += k; if (j > 80) { if (!rflag) ++outline; putc('\n', output_file); j = k; } fprintf(output_file, "\"\\\""); s = symnam[i]; while (*++s != '"') { if (*s == '\\') { fprintf(output_file, "\\\\"); if (*++s == '\\') fprintf(output_file, "\\\\"); else putc(*s, output_file); } else putc(*s, output_file); } fprintf(output_file, "\\\"\","); } else if (s[0] == '\'') { if (s[1] == '"') { j += 7; if (j > 80) { if (!rflag) ++outline; putc('\n', output_file); j = 7; } fprintf(output_file, "\"'\\\"'\","); } else { k = 5; while (*++s != '\'') { ++k; if (*s == '\\') { k += 2; if (*++s == '\\') ++k; } } j += k; if (j > 80) { if (!rflag) ++outline; putc('\n', output_file); j = k; } fprintf(output_file, "\"'"); s = symnam[i]; while (*++s != '\'') { if (*s == '\\') { fprintf(output_file, "\\\\"); if (*++s == '\\') fprintf(output_file, "\\\\"); else putc(*s, output_file); } else putc(*s, output_file); } fprintf(output_file, "'\","); } } else { k = strlen(s) + 3; j += k; if (j > 80) { if (!rflag) ++outline; putc('\n', output_file); j = k; } putc('"', output_file); do { putc(*s, output_file); } while (*++s); fprintf(output_file, "\","); } } else { if (jflag)/*rwj -- null strings should be 'null'*/ { j += 5; if (j > 80) { if (!rflag) ++outline; putc('\n', output_file); j = 5; } fprintf(output_file, "null,"); } else /*rwj -- not jflag, output a 0*/ { j += 2; if (j > 80) { if (!rflag) ++outline; putc('\n', output_file); j = 2; } fprintf(output_file, "0,"); } } } if (!rflag) outline += 2; fprintf(output_file, "\n};\n"); FREE(symnam); if (!rflag) ++outline; if (jflag)/*rwj*/ fprintf(output_file, "final static String yyrule[] = {\n"); else fprintf(output_file, "char *yyrule[] = {\n"); for (i = 2; i < nrules; ++i) { fprintf(output_file, "\"%s :", symbol_name[rlhs[i]]); for (j = rrhs[i]; ritem[j] > 0; ++j) { s = symbol_name[ritem[j]]; if (s[0] == '"') { fprintf(output_file, " \\\""); while (*++s != '"') { if (*s == '\\') { if (s[1] == '\\') fprintf(output_file, "\\\\\\\\"); else fprintf(output_file, "\\\\%c", s[1]); ++s; } else putc(*s, output_file); } fprintf(output_file, "\\\""); } else if (s[0] == '\'') { if (s[1] == '"') fprintf(output_file, " '\\\"'"); else if (s[1] == '\\') { if (s[2] == '\\') fprintf(output_file, " '\\\\\\\\"); else fprintf(output_file, " '\\\\%c", s[2]); s += 2; while (*++s != '\'') putc(*s, output_file); putc('\'', output_file); } else fprintf(output_file, " '%c'", s[1]); } else fprintf(output_file, " %s", s); } if (!rflag) ++outline; fprintf(output_file, "\",\n"); } if (!rflag) outline += 2; if (jflag)/*rwj*/ fprintf(output_file, "};\n\n"); else fprintf(output_file, "};\n#endif\n"); } void output_stype(void) { int prim; /*is the Java semantic type a primitive?*/ char filenam[128]; char *jvalclass; /* either [Parser]Val or a user-defined class */ FILE *f; if (jflag)/*rwj*/ { jvalclass = (char *) MALLOC(strlen(jclass_name) + 4); /* Val\0 */ sprintf(jvalclass,"%sVal",jclass_name); if (jsemantic_type && strlen(jsemantic_type)>0)/*specific type requested*/ { char *raw_type=jsemantic_type; if (strcmp(jsemantic_type,"byte")==0 || strcmp(jsemantic_type,"short")==0 || strcmp(jsemantic_type,"char")==0 || strcmp(jsemantic_type,"int")==0 || strcmp(jsemantic_type,"long")==0 || strcmp(jsemantic_type,"float")==0 || strcmp(jsemantic_type,"double")==0) { prim=1; } else { prim=0; char *end=strchr(jsemantic_type,'<'); if (end!=NULL) { raw_type=(char *)CALLOC(end-jsemantic_type+1,sizeof(char)); strncpy(raw_type,jsemantic_type,end-jsemantic_type); } } fprintf(code_file,"\n\n//########## SEMANTIC VALUES ##########\n"); fprintf(code_file,"//## **user defined:%s\n",jsemantic_type); fprintf(code_file,"String yytext;//user variable to return contextual strings\n"); fprintf(code_file,"%s yyval; //used to return semantic vals from action routines\n", jsemantic_type); fprintf(code_file,"%s yylval;//the 'lval' (result) I got from yylex()\n", jsemantic_type); fprintf(code_file,"%s valstk[] = new %s[YYSTACKSIZE];\n", jsemantic_type,raw_type); fprintf(code_file,"int valptr;\n"); fprintf(code_file,"//###############################################################\n"); fprintf(code_file,"// methods: value stack push,pop,drop,peek.\n"); fprintf(code_file,"//###############################################################\n"); fprintf(code_file,"final void val_init()\n"); fprintf(code_file,"{\n"); if (prim) { fprintf(code_file," yyval=(%s)0;\n",jsemantic_type); fprintf(code_file," yylval=(%s)0;\n",jsemantic_type); } else { fprintf(code_file," yyval=new %s();\n",jsemantic_type); /*fix 980108*/ fprintf(code_file," yylval=new %s();\n",jsemantic_type); /* ditto */ } fprintf(code_file," valptr=-1;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"final void val_push(%s val)\n",jsemantic_type); fprintf(code_file,"{\n"); fprintf(code_file," try {\n"); fprintf(code_file," valptr++;\n"); fprintf(code_file," valstk[valptr]=val;\n"); fprintf(code_file," }\n"); fprintf(code_file," catch (ArrayIndexOutOfBoundsException e) {\n"); fprintf(code_file," int oldsize = valstk.length;\n"); fprintf(code_file," int newsize = oldsize*2;\n"); fprintf(code_file," %s[] newstack = new %s[newsize];\n",jsemantic_type,raw_type); fprintf(code_file," System.arraycopy(valstk,0,newstack,0,oldsize);\n"); fprintf(code_file," valstk = newstack;\n"); fprintf(code_file," valstk[valptr]=val;\n"); fprintf(code_file," }\n"); fprintf(code_file,"}\n"); fprintf(code_file,"final %s val_pop()\n",jsemantic_type); fprintf(code_file,"{\n"); fprintf(code_file," return valstk[valptr--];\n"); fprintf(code_file,"}\n"); fprintf(code_file,"final void val_drop(int cnt)\n"); fprintf(code_file,"{\n"); fprintf(code_file," valptr -= cnt;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"final %s val_peek(int relative)\n",jsemantic_type); fprintf(code_file,"{\n"); fprintf(code_file," return valstk[valptr-relative];\n"); fprintf(code_file,"}\n"); fprintf(code_file,"final %s dup_yyval(%s val)\n",jsemantic_type,jsemantic_type); fprintf(code_file,"{\n"); fprintf(code_file," return val;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"//#### end semantic value section ####\n"); } else /*no definition -- use our semantic class*/ { fprintf(code_file,"\n\n//########## SEMANTIC VALUES ##########\n"); fprintf(code_file,"//public class %s is defined in %s.java\n\n\n", jvalclass,jvalclass); sprintf(filenam,"%s.java",jvalclass); f=fopen(filenam,"w"); if (!f) return; fprintf(f,"//#############################################\n"); fprintf(f,"//## file: %s.java\n",jclass_name); fprintf(f,"//## Generated by Byacc/j\n"); fprintf(f,"//#############################################\n"); if (jpackage_name && strlen(jpackage_name)>0) fprintf(f,"package %s;\n\n",jpackage_name); fprintf(f,"/**\n"); fprintf(f," * BYACC/J Semantic Value for parser: %s\n",jclass_name); fprintf(f," * This class provides some of the functionality\n"); fprintf(f," * of the yacc/C 'union' directive\n"); fprintf(f," */\n"); /* yio 20020304: option to make the class final */ if (jfinal_class == TRUE) fprintf(f,"final "); fprintf(f,"public class %s\n",jvalclass); fprintf(f,"{\n"); fprintf(f,"/**\n"); fprintf(f," * integer value of this 'union'\n"); fprintf(f," */\n"); fprintf(f,"public int ival;\n"); fprintf(f,"\n"); fprintf(f,"/**\n"); fprintf(f," * double value of this 'union'\n"); fprintf(f," */\n"); fprintf(f,"public double dval;\n"); fprintf(f,"\n"); fprintf(f,"/**\n"); fprintf(f," * string value of this 'union'\n"); fprintf(f," */\n"); fprintf(f,"public String sval;\n"); fprintf(f,"\n"); fprintf(f,"/**\n"); fprintf(f," * object value of this 'union'\n"); fprintf(f," */\n"); fprintf(f,"public Object obj;\n"); fprintf(f,"\n"); fprintf(f,"//#############################################\n"); fprintf(f,"//## C O N S T R U C T O R S\n"); fprintf(f,"//#############################################\n"); fprintf(f,"/**\n"); fprintf(f," * Initialize me without a value\n"); fprintf(f," */\n"); fprintf(f,"public %s()\n",jvalclass); fprintf(f,"{\n"); fprintf(f,"}\n"); fprintf(f,"/**\n"); fprintf(f," * Initialize me as an int\n"); fprintf(f," */\n"); fprintf(f,"public %s(int val)\n",jvalclass); fprintf(f,"{\n"); fprintf(f," ival=val;\n"); fprintf(f,"}\n"); fprintf(f,"\n"); fprintf(f,"/**\n"); fprintf(f," * Initialize me as a double\n"); fprintf(f," */\n"); fprintf(f,"public %s(double val)\n",jvalclass); fprintf(f,"{\n"); fprintf(f," dval=val;\n"); fprintf(f,"}\n"); fprintf(f,"\n"); fprintf(f,"/**\n"); fprintf(f," * Initialize me as a string\n"); fprintf(f," */\n"); fprintf(f,"public %s(String val)\n",jvalclass); fprintf(f,"{\n"); fprintf(f," sval=val;\n"); fprintf(f,"}\n"); fprintf(f,"\n"); fprintf(f,"/**\n"); fprintf(f," * Initialize me as an Object\n"); fprintf(f," */\n"); fprintf(f,"public %s(Object val)\n",jvalclass); fprintf(f,"{\n"); fprintf(f," obj=val;\n"); fprintf(f,"}\n"); fprintf(f,"}//end class\n\n"); fprintf(f,"//#############################################\n"); fprintf(f,"//## E N D O F F I L E\n"); fprintf(f,"//#############################################\n"); fclose(f); fprintf(code_file,"String yytext;//user variable to return contextual strings\n"); fprintf(code_file,"%s yyval; //used to return semantic vals from action routines\n",jvalclass); fprintf(code_file,"%s yylval;//the 'lval' (result) I got from yylex()\n",jvalclass); fprintf(code_file,"%s valstk[];\n",jvalclass); fprintf(code_file,"int valptr;\n"); fprintf(code_file,"//###############################################################\n"); fprintf(code_file,"// methods: value stack push,pop,drop,peek.\n"); fprintf(code_file,"//###############################################################\n"); fprintf(code_file,"void val_init()\n"); fprintf(code_file,"{\n"); fprintf(code_file," valstk=new %s[YYSTACKSIZE];\n",jvalclass); fprintf(code_file," yyval=new %s();\n",jvalclass); fprintf(code_file," yylval=new %s();\n",jvalclass); fprintf(code_file," valptr=-1;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"void val_push(%s val)\n",jvalclass); fprintf(code_file,"{\n"); fprintf(code_file," if (valptr>=YYSTACKSIZE)\n"); fprintf(code_file," return;\n"); fprintf(code_file," valstk[++valptr]=val;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"%s val_pop()\n",jvalclass); fprintf(code_file,"{\n"); fprintf(code_file," if (valptr<0)\n"); fprintf(code_file," return new %s();\n",jvalclass); fprintf(code_file," return valstk[valptr--];\n"); fprintf(code_file,"}\n"); fprintf(code_file,"void val_drop(int cnt)\n"); fprintf(code_file,"{\n"); fprintf(code_file,"int ptr;\n"); fprintf(code_file," ptr=valptr-cnt;\n"); fprintf(code_file," if (ptr<0)\n"); fprintf(code_file," return;\n"); fprintf(code_file," valptr = ptr;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"%s val_peek(int relative)\n",jvalclass); fprintf(code_file,"{\n"); fprintf(code_file,"int ptr;\n"); fprintf(code_file," ptr=valptr-relative;\n"); fprintf(code_file," if (ptr<0)\n"); fprintf(code_file," return new %s();\n",jvalclass); fprintf(code_file," return valstk[ptr];\n"); fprintf(code_file,"}\n"); fprintf(code_file,"final %s dup_yyval(%s val)\n",jvalclass,jvalclass); fprintf(code_file,"{\n"); fprintf(code_file," %s dup = new %s();\n",jvalclass,jvalclass); fprintf(code_file," dup.ival = val.ival;\n"); fprintf(code_file," dup.dval = val.dval;\n"); fprintf(code_file," dup.sval = val.sval;\n"); fprintf(code_file," dup.obj = val.obj;\n"); fprintf(code_file," return dup;\n"); fprintf(code_file,"}\n"); fprintf(code_file,"//#### end semantic value section ####\n"); } } else /*normal stuff -- rwj*/ { if (!unionized && ntags == 0) { outline += 3; fprintf(code_file, "#ifndef YYSTYPE\ntypedef int YYSTYPE;\n#endif\n"); } } } void output_trailing_text(void) { int c, last; FILE *in, *out; if (line == 0) return; in = input_file; out = code_file; c = *cptr; if (c == '\n') { ++lineno; if ((c = getc(in)) == EOF) return; if (!lflag) { ++outline; if (jflag) fprintf(out, jline_format, lineno, input_file_name); else fprintf(out, line_format, lineno, input_file_name); } if (c == '\n') ++outline; putc(c, out); last = c; } else { if (!lflag) { ++outline; if (jflag)/*rwj*/ fprintf(out, jline_format, lineno, input_file_name); else fprintf(out, line_format, lineno, input_file_name); } do { putc(c, out); } while ((c = *++cptr) != '\n'); ++outline; putc('\n', out); last = '\n'; } while ((c = getc(in)) != EOF) { if (c == '\n') ++outline; putc(c, out); last = c; } if (last != '\n') { ++outline; putc('\n', out); } if (!lflag) if (jflag) fprintf(out, jline_format, ++outline + 1, code_file_name); else fprintf(out, line_format, ++outline + 1, code_file_name); } void output_semantic_actions(void) { int c, last; FILE *out; fclose(action_file); action_file = fopen(action_file_name, "r"); if (action_file == NULL) open_error(action_file_name); if ((c = getc(action_file)) == EOF) return; out = code_file; last = c; if (c == '\n') ++outline; putc(c, out); while ((c = getc(action_file)) != EOF) { if (c == '\n') ++outline; putc(c, out); last = c; } if (last != '\n') { ++outline; putc('\n', out); } if (!lflag) if (jflag)/*rwj*/ fprintf(out, jline_format, ++outline + 1, code_file_name); else fprintf(out, line_format, ++outline + 1, code_file_name); } void free_itemsets(void) { core *cp, *next; FREE(state_table); for (cp = first_state; cp; cp = next) { next = cp->next; FREE(cp); } } void free_shifts(void) { shifts *sp, *next; FREE(shift_table); for (sp = first_shift; sp; sp = next) { next = sp->next; FREE(sp); } } void free_reductions(void) { reductions *rp, *next; FREE(reduction_table); for (rp = first_reduction; rp; rp = next) { next = rp->next; FREE(rp); } } byaccj1.15/src/reader.c0000755000076500000240000007615307444073365014227 0ustar thurkastaff#include #include #include "defs.h" /* The line size must be a positive integer. One hundred was chosen */ /* because few lines in Yacc input grammars exceed 100 characters. */ /* Note that if a line exceeds LINESIZE characters, the line buffer */ /* will be expanded to accomodate it. */ #define LINESIZE 100 char *cache; int cinc, cache_size; int ntags, tagmax; char **tag_table; char saw_eof, unionized; char *cptr, *line; int linesize; bucket *goal; int prec; int gensym; char last_was_action; int maxitems; bucket **pitem; int maxrules; bucket **plhs; int name_pool_size; char *name_pool; char line_format[] = "#line %d \"%s\"\n"; char jline_format[] = "//#line %d \"%s\"\n"; void cachec(int c) { assert(cinc >= 0); if (cinc >= cache_size) { cache_size += 256; cache = REALLOC(cache, cache_size); if (cache == 0) no_space(); } cache[cinc] = c; ++cinc; } void get_line(void) { FILE *f = input_file; int c; int i; if (saw_eof || (c = getc(f)) == EOF) { if (line) { FREE(line); line = 0; } cptr = 0; saw_eof = 1; return; } if (line == 0 || linesize != (LINESIZE + 1)) { if (line) FREE(line); linesize = LINESIZE + 1; line = MALLOC(linesize); if (line == 0) no_space(); } i = 0; ++lineno; for (;;) { line[i] = c; if (c == '\n') { cptr = line; return; } if (++i >= linesize) { linesize += LINESIZE; line = REALLOC(line, linesize); if (line == 0) no_space(); } c = getc(f); if (c == EOF) { line[i] = '\n'; saw_eof = 1; cptr = line; return; } } } char *dup_line(void) { char *p, *s, *t; if (line == 0) return (0); s = line; while (*s != '\n') ++s; p = MALLOC(s - line + 1); if (p == 0) no_space(); s = line; t = p; while ((*t++ = *s++) != '\n') continue; return (p); } void skip_comment(void) { char *s; int st_lineno = lineno; char *st_line = dup_line(); char *st_cptr = st_line + (cptr - line); s = cptr + 2; for (;;) { if (*s == '*' && s[1] == '/') { cptr = s + 2; FREE(st_line); return; } if (*s == '\n') { get_line(); if (line == 0) unterminated_comment(st_lineno, st_line, st_cptr); s = cptr; } else ++s; } } int nextc(void) { char *s; if (line == 0) { get_line(); if (line == 0) return (EOF); } s = cptr; for (;;) { switch (*s) { case '\n': get_line(); if (line == 0) return (EOF); s = cptr; break; case ' ': case '\t': case '\f': case '\r': case '\v': case ',': case ';': ++s; break; case '\\': cptr = s; return ('%'); case '/': if (s[1] == '*') { cptr = s; skip_comment(); s = cptr; break; } else if (s[1] == '/') { get_line(); if (line == 0) return (EOF); s = cptr; break; } /* fall through */ default: cptr = s; return (*s); } } } int keyword(void) { int c; char *t_cptr = cptr; c = *++cptr; if (isalpha(c)) { cinc = 0; for (;;) { if (isalpha(c)) { if (isupper(c)) c = tolower(c); cachec(c); } else if (isdigit(c) || c == '_' || c == '.' || c == '$') cachec(c); else break; c = *++cptr; } cachec(NUL); if (strcmp(cache, "token") == 0 || strcmp(cache, "term") == 0) return (TOKEN); if (strcmp(cache, "type") == 0) return (TYPE); if (strcmp(cache, "left") == 0) return (LEFT); if (strcmp(cache, "right") == 0) return (RIGHT); if (strcmp(cache, "nonassoc") == 0 || strcmp(cache, "binary") == 0) return (NONASSOC); if (strcmp(cache, "start") == 0) return (START); if (strcmp(cache, "union") == 0) return (UNION); if (strcmp(cache, "ident") == 0) return (IDENT); } else { ++cptr; if (c == '{') return (TEXT); if (c == '%' || c == '\\') return (MARK); if (c == '<') return (LEFT); if (c == '>') return (RIGHT); if (c == '0') return (TOKEN); if (c == '2') return (NONASSOC); } syntax_error(lineno, line, t_cptr); /*NOTREACHED*/ return -1; } void copy_ident(void) { int c; FILE *f = output_file; c = nextc(); if (c == EOF) unexpected_EOF(); if (c != '"') syntax_error(lineno, line, cptr); ++outline; fprintf(f, "#ident \""); for (;;) { c = *++cptr; if (c == '\n') { fprintf(f, "\"\n"); return; } putc(c, f); if (c == '"') { putc('\n', f); ++cptr; return; } } } void copy_text(void) { int c; int quote; FILE *f = text_file; int need_newline = 0; int t_lineno = lineno; char *t_line = dup_line(); char *t_cptr = t_line + (cptr - line - 2); if (*cptr == '\n') { get_line(); if (line == 0) unterminated_text(t_lineno, t_line, t_cptr); } if (!lflag)/*rwj*/ if (jflag) fprintf(f, jline_format, lineno, input_file_name); else fprintf(f, line_format, lineno, input_file_name); loop: c = *cptr++; switch (c) { case '\n': next_line: putc('\n', f); need_newline = 0; get_line(); if (line) goto loop; unterminated_text(t_lineno, t_line, t_cptr); case '\'': case '"': { int s_lineno = lineno; char *s_line = dup_line(); char *s_cptr = s_line + (cptr - line - 1); quote = c; putc(c, f); for (;;) { c = *cptr++; putc(c, f); if (c == quote) { need_newline = 1; FREE(s_line); goto loop; } if (c == '\n') unterminated_string(s_lineno, s_line, s_cptr); if (c == '\\') { c = *cptr++; putc(c, f); if (c == '\n') { get_line(); if (line == 0) unterminated_string(s_lineno, s_line, s_cptr); } } } } case '/': putc(c, f); need_newline = 1; c = *cptr; if (c == '/') { putc('*', f); while ((c = *++cptr) != '\n') { if (c == '*' && cptr[1] == '/') fprintf(f, "* "); else putc(c, f); } fprintf(f, "*/"); goto next_line; } if (c == '*') { int c_lineno = lineno; char *c_line = dup_line(); char *c_cptr = c_line + (cptr - line - 1); putc('*', f); ++cptr; for (;;) { c = *cptr++; putc(c, f); if (c == '*' && *cptr == '/') { putc('/', f); ++cptr; FREE(c_line); goto loop; } if (c == '\n') { get_line(); if (line == 0) unterminated_comment(c_lineno, c_line, c_cptr); } } } need_newline = 1; goto loop; case '%': case '\\': if (*cptr == '}') { if (need_newline) putc('\n', f); ++cptr; FREE(t_line); return; } /* fall through */ default: putc(c, f); need_newline = 1; goto loop; } } void copy_union(void) { int c; int quote; int depth; int u_lineno = lineno; char *u_line = dup_line(); char *u_cptr = u_line + (cptr - line - 6); if (unionized) over_unionized(cptr - 6); unionized = 1; if (!lflag) if (jflag) fprintf(text_file, jline_format, lineno, input_file_name); else fprintf(text_file, line_format, lineno, input_file_name); fprintf(text_file, "typedef union"); if (dflag) fprintf(union_file, "typedef union"); depth = 0; loop: c = *cptr++; putc(c, text_file); if (dflag) putc(c, union_file); switch (c) { case '\n': next_line: get_line(); if (line == 0) unterminated_union(u_lineno, u_line, u_cptr); goto loop; case '{': ++depth; goto loop; case '}': if (--depth == 0) { fprintf(text_file, " YYSTYPE;\n"); FREE(u_line); return; } goto loop; case '\'': case '"': { int s_lineno = lineno; char *s_line = dup_line(); char *s_cptr = s_line + (cptr - line - 1); quote = c; for (;;) { c = *cptr++; putc(c, text_file); if (dflag) putc(c, union_file); if (c == quote) { FREE(s_line); goto loop; } if (c == '\n') unterminated_string(s_lineno, s_line, s_cptr); if (c == '\\') { c = *cptr++; putc(c, text_file); if (dflag) putc(c, union_file); if (c == '\n') { get_line(); if (line == 0) unterminated_string(s_lineno, s_line, s_cptr); } } } } case '/': c = *cptr; if (c == '/') { putc('*', text_file); if (dflag) putc('*', union_file); while ((c = *++cptr) != '\n') { if (c == '*' && cptr[1] == '/') { fprintf(text_file, "* "); if (dflag) fprintf(union_file, "* "); } else { putc(c, text_file); if (dflag) putc(c, union_file); } } fprintf(text_file, "*/\n"); if (dflag) fprintf(union_file, "*/\n"); goto next_line; } if (c == '*') { int c_lineno = lineno; char *c_line = dup_line(); char *c_cptr = c_line + (cptr - line - 1); putc('*', text_file); if (dflag) putc('*', union_file); ++cptr; for (;;) { c = *cptr++; putc(c, text_file); if (dflag) putc(c, union_file); if (c == '*' && *cptr == '/') { putc('/', text_file); if (dflag) putc('/', union_file); ++cptr; FREE(c_line); goto loop; } if (c == '\n') { get_line(); if (line == 0) unterminated_comment(c_lineno, c_line, c_cptr); } } } goto loop; default: goto loop; } } int hexval(int c) { if (c >= '0' && c <= '9') return (c - '0'); if (c >= 'A' && c <= 'F') return (c - 'A' + 10); if (c >= 'a' && c <= 'f') return (c - 'a' + 10); return (-1); } bucket *get_literal(void) { int c, quote; int i; int n; char *s; bucket *bp; int s_lineno = lineno; char *s_line = dup_line(); char *s_cptr = s_line + (cptr - line); quote = *cptr++; cinc = 0; for (;;) { c = *cptr++; if (c == quote) break; if (c == '\n') unterminated_string(s_lineno, s_line, s_cptr); if (c == '\\') { char *c_cptr = cptr - 1; c = *cptr++; switch (c) { case '\n': get_line(); if (line == 0) unterminated_string(s_lineno, s_line, s_cptr); continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': n = c - '0'; c = *cptr; if (IS_OCTAL(c)) { n = (n << 3) + (c - '0'); c = *++cptr; if (IS_OCTAL(c)) { n = (n << 3) + (c - '0'); ++cptr; } } if (n > MAXCHAR) illegal_character(c_cptr); c = n; break; case 'x': c = *cptr++; n = hexval(c); if (n < 0 || n >= 16) illegal_character(c_cptr); for (;;) { c = *cptr; i = hexval(c); if (i < 0 || i >= 16) break; ++cptr; n = (n << 4) + i; if (n > MAXCHAR) illegal_character(c_cptr); } c = n; break; case 'a': c = 7; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; } } cachec(c); } FREE(s_line); n = cinc; s = MALLOC(n); if (s == 0) no_space(); for (i = 0; i < n; ++i) s[i] = cache[i]; cinc = 0; if (n == 1) cachec('\''); else cachec('"'); for (i = 0; i < n; ++i) { c = ((unsigned char *)s)[i]; if (c == '\\' || c == cache[0]) { cachec('\\'); cachec(c); } else if (isprint(c)) cachec(c); else { cachec('\\'); switch (c) { case 7: cachec('a'); break; case '\b': cachec('b'); break; case '\f': cachec('f'); break; case '\n': cachec('n'); break; case '\r': cachec('r'); break; case '\t': cachec('t'); break; case '\v': cachec('v'); break; default: cachec(((c >> 6) & 7) + '0'); cachec(((c >> 3) & 7) + '0'); cachec((c & 7) + '0'); break; } } } if (n == 1) cachec('\''); else cachec('"'); cachec(NUL); bp = lookup(cache); bp->class = TERM; if (n == 1 && bp->value == UNDEFINED) bp->value = *(unsigned char *)s; FREE(s); return (bp); } int is_reserved(char *name) { char *s; if (strcmp(name, ".") == 0 || strcmp(name, "$accept") == 0 || strcmp(name, "$end") == 0) return (1); if (name[0] == '$' && name[1] == '$' && isdigit(name[2])) { s = name + 3; while (isdigit(*s)) ++s; if (*s == NUL) return (1); } return (0); } bucket *get_name(void) { int c; cinc = 0; for (c = *cptr; IS_IDENT(c); c = *++cptr) cachec(c); cachec(NUL); if (is_reserved(cache)) used_reserved(cache); return (lookup(cache)); } int get_number(void) { int c; int n; n = 0; for (c = *cptr; isdigit(c); c = *++cptr) n = 10*n + (c - '0'); return (n); } char *get_tag(void) { int c; int i; char *s; int t_lineno = lineno; char *t_line = dup_line(); char *t_cptr = t_line + (cptr - line); ++cptr; c = nextc(); if (c == EOF) unexpected_EOF(); if (!isalpha(c) && c != '_' && c != '$') illegal_tag(t_lineno, t_line, t_cptr); cinc = 0; do { cachec(c); c = *++cptr; } while (IS_IDENT(c)); cachec(NUL); c = nextc(); if (c == EOF) unexpected_EOF(); if (c != '>') illegal_tag(t_lineno, t_line, t_cptr); ++cptr; for (i = 0; i < ntags; ++i) { if (strcmp(cache, tag_table[i]) == 0) return (tag_table[i]); } if (ntags >= tagmax) { tagmax += 16; tag_table = (char **) (tag_table ? REALLOC(tag_table, tagmax*sizeof(char *)) : MALLOC(tagmax*sizeof(char *))); if (tag_table == 0) no_space(); } s = MALLOC(cinc); if (s == 0) no_space(); strcpy(s, cache); tag_table[ntags] = s; ++ntags; FREE(t_line); return (s); } void declare_tokens(int assoc) { int c; bucket *bp; int value; char *tag = 0; if (assoc != TOKEN) ++prec; c = nextc(); if (c == EOF) unexpected_EOF(); if (c == '<') { tag = get_tag(); c = nextc(); if (c == EOF) unexpected_EOF(); } for (;;) { if (isalpha(c) || c == '_' || c == '.' || c == '$') bp = get_name(); else if (c == '\'' || c == '"') bp = get_literal(); else return; if (bp == goal) tokenized_start(bp->name); bp->class = TERM; if (tag) { if (bp->tag && tag != bp->tag) retyped_warning(bp->name); bp->tag = tag; } if (assoc != TOKEN) { if (bp->prec && prec != bp->prec) reprec_warning(bp->name); bp->assoc = assoc; bp->prec = prec; } c = nextc(); if (c == EOF) unexpected_EOF(); value = UNDEFINED; if (isdigit(c)) { value = get_number(); if (bp->value != UNDEFINED && value != bp->value) revalued_warning(bp->name); bp->value = value; c = nextc(); if (c == EOF) unexpected_EOF(); } } } void declare_types(void) { int c; bucket *bp; char *tag; c = nextc(); if (c == EOF) unexpected_EOF(); if (c != '<') syntax_error(lineno, line, cptr); tag = get_tag(); for (;;) { c = nextc(); if (isalpha(c) || c == '_' || c == '.' || c == '$') bp = get_name(); else if (c == '\'' || c == '"') bp = get_literal(); else return; if (bp->tag && tag != bp->tag) retyped_warning(bp->name); bp->tag = tag; } } void declare_start(void) { int c; bucket *bp; c = nextc(); if (c == EOF) unexpected_EOF(); if (!isalpha(c) && c != '_' && c != '.' && c != '$') syntax_error(lineno, line, cptr); bp = get_name(); if (bp->class == TERM) terminal_start(bp->name); if (goal && goal != bp) restarted_warning(); goal = bp; } /* yio 20020304: read a java argument from the grammar file. * The argument is of the form: %jthrow [whitespace] SAXException * To parse this, we convert the whitespace to '=' and pass it * along to getJavaArg(). */ void declare_java_arg() { int c; /* read the keyword, skipping the inital '%j' */ cptr += 2; c = *cptr; cinc = 0; while (!isspace(c)) { cachec(c); c = *++cptr; } /* skip the whitespace */ for (;;) { if (c == '/' && cptr[1] == '*') { cptr += 2; skip_comment(); c = *cptr; } if (c == '\n') { cachec(NUL); getJavaArg(strdup(cache)); return; } else if (!isspace(c)) break; else c = *++cptr; } cachec('='); while (c != '\n') { if (c == '/' && cptr[1] == '*') { cptr += 2; skip_comment(); c = *cptr; } cachec(c); c = *++cptr; } cachec(NUL); getJavaArg(strdup(cache)); } void read_declarations(void) { int c, k; cache_size = 256; cache = MALLOC(cache_size); if (cache == 0) no_space(); for (;;) { c = nextc(); if (c == EOF) unexpected_EOF(); if (c != '%') syntax_error(lineno, line, cptr); /* yio 20020304: is this a java argument? */ if (cptr[1] == 'j' || cptr[1] == 'J') declare_java_arg(); else { switch (k = keyword()) { case MARK: return; case IDENT: copy_ident(); break; case TEXT: copy_text(); break; case UNION: copy_union(); break; case TOKEN: case LEFT: case RIGHT: case NONASSOC: declare_tokens(k); break; case TYPE: declare_types(); break; case START: declare_start(); break; } } } } void initialize_grammar(void) { nitems = 4; maxitems = 300; pitem = (bucket **) MALLOC(maxitems*sizeof(bucket *)); if (pitem == 0) no_space(); pitem[0] = 0; pitem[1] = 0; pitem[2] = 0; pitem[3] = 0; nrules = 3; maxrules = 100; plhs = (bucket **) MALLOC(maxrules*sizeof(bucket *)); if (plhs == 0) no_space(); plhs[0] = 0; plhs[1] = 0; plhs[2] = 0; rprec = (short *) MALLOC(maxrules*sizeof(short)); if (rprec == 0) no_space(); rprec[0] = 0; rprec[1] = 0; rprec[2] = 0; rassoc = (char *) MALLOC(maxrules*sizeof(char)); if (rassoc == 0) no_space(); rassoc[0] = TOKEN; rassoc[1] = TOKEN; rassoc[2] = TOKEN; } void expand_items(void) { maxitems += 300; pitem = (bucket **) REALLOC(pitem, maxitems*sizeof(bucket *)); if (pitem == 0) no_space(); } void expand_rules(void) { maxrules += 100; plhs = (bucket **) REALLOC(plhs, maxrules*sizeof(bucket *)); if (plhs == 0) no_space(); rprec = (short *) REALLOC(rprec, maxrules*sizeof(short)); if (rprec == 0) no_space(); rassoc = (char *) REALLOC(rassoc, maxrules*sizeof(char)); if (rassoc == 0) no_space(); } void advance_to_start(void) { register int c; register bucket *bp; char *s_cptr; int s_lineno; for (;;) { c = nextc(); if (c != '%') break; s_cptr = cptr; switch (keyword()) { case MARK: no_grammar(); case TEXT: copy_text(); break; case START: declare_start(); break; default: syntax_error(lineno, line, s_cptr); } } c = nextc(); if (!isalpha(c) && c != '_' && c != '.' && c != '_') syntax_error(lineno, line, cptr); bp = get_name(); if (goal == 0) { if (bp->class == TERM) terminal_start(bp->name); goal = bp; } s_lineno = lineno; c = nextc(); if (c == EOF) unexpected_EOF(); if (c != ':') syntax_error(lineno, line, cptr); start_rule(bp, s_lineno); ++cptr; } void start_rule(bucket *bp,int s_lineno) { if (bp->class == TERM) terminal_lhs(s_lineno); bp->class = NONTERM; if (nrules >= maxrules) expand_rules(); plhs[nrules] = bp; rprec[nrules] = UNDEFINED; rassoc[nrules] = TOKEN; } void end_rule(void) { int i; if (!last_was_action && plhs[nrules]->tag) { for (i = nitems - 1; pitem[i]; --i) continue; if (pitem[i+1] == 0 || pitem[i+1]->tag != plhs[nrules]->tag) default_action_warning(); } last_was_action = 0; if (nitems >= maxitems) expand_items(); pitem[nitems] = 0; ++nitems; ++nrules; } void insert_empty_rule(void) { bucket *bp, **bpp; assert(cache); sprintf(cache, "$$%d", ++gensym); bp = make_bucket(cache); last_symbol->next = bp; last_symbol = bp; bp->tag = plhs[nrules]->tag; bp->class = NONTERM; if ((nitems += 2) > maxitems) expand_items(); bpp = pitem + nitems - 1; *bpp-- = bp; while ((bpp[0] = bpp[-1])!=0) --bpp; if (++nrules >= maxrules) expand_rules(); plhs[nrules] = plhs[nrules-1]; plhs[nrules-1] = bp; rprec[nrules] = rprec[nrules-1]; rprec[nrules-1] = 0; rassoc[nrules] = rassoc[nrules-1]; rassoc[nrules-1] = TOKEN; } void add_symbol(void) { int c; bucket *bp; int s_lineno = lineno; c = *cptr; if (c == '\'' || c == '"') bp = get_literal(); else bp = get_name(); c = nextc(); if (c == ':') { end_rule(); start_rule(bp, s_lineno); ++cptr; return; } if (last_was_action) insert_empty_rule(); last_was_action = 0; if (++nitems > maxitems) expand_items(); pitem[nitems-1] = bp; } void copy_action(void) { int c; int i, n; int depth; int quote; char *tag; FILE *f = action_file; int a_lineno = lineno; char *a_line = dup_line(); char *a_cptr = a_line + (cptr - line); if (last_was_action) insert_empty_rule(); last_was_action = 1; fprintf(f, "case %d:\n", nrules - 2); if (!lflag)/*rwj*/ if (jflag) fprintf(f, jline_format, lineno, input_file_name); else fprintf(f, line_format, lineno, input_file_name); if (*cptr == '=') ++cptr; n = 0; for (i = nitems - 1; pitem[i]; --i) ++n; depth = 0; loop: c = *cptr; if (c == '$') { if (cptr[1] == '<') { int d_lineno = lineno; char *d_line = dup_line(); char *d_cptr = d_line + (cptr - line); ++cptr; tag = get_tag(); c = *cptr; if (c == '$') { fprintf(f, "yyval.%s", tag); ++cptr; FREE(d_line); goto loop; } else if (isdigit(c)) { i = get_number(); if (i > n) dollar_warning(d_lineno, i); if (jflag) /*rwj*/ fprintf(f, "val_peek(%d).%s", n - i, tag); else fprintf(f, "yyvsp[%d].%s", i - n, tag); FREE(d_line); goto loop; } else if (c == '-' && isdigit(cptr[1])) { ++cptr; i = -get_number() - n; if (jflag) /*rwj*/ fprintf(f, "val_peek(%d).%s", -i, tag); else fprintf(f, "yyvsp[%d].%s", i, tag); FREE(d_line); goto loop; } else dollar_error(d_lineno, d_line, d_cptr); } else if (cptr[1] == '$') { if (ntags) { tag = plhs[nrules]->tag; if (tag == 0) untyped_lhs(); fprintf(f, "yyval.%s", tag); } else fprintf(f, "yyval"); cptr += 2; goto loop; } else if (isdigit(cptr[1])) { ++cptr; i = get_number(); if (ntags) { if (i <= 0 || i > n) unknown_rhs(i); tag = pitem[nitems + i - n - 1]->tag; if (tag == 0) untyped_rhs(i, pitem[nitems + i - n - 1]->name); if (jflag) /*rwj*/ fprintf(f, "val_peek(%d).%s", n - i, tag); else fprintf(f, "yyvsp[%d].%s", i - n, tag); } else { if (i > n) dollar_warning(lineno, i); if (jflag)/*rwj*/ fprintf(f, "val_peek(%d)", n - i); else fprintf(f, "yyvsp[%d]", i - n); } goto loop; } else if (cptr[1] == '-') { cptr += 2; i = get_number(); if (ntags) unknown_rhs(-i); if (jflag)/*rwj*/ fprintf(f, "val_peek(%d)", i + n); else fprintf(f, "yyvsp[%d]", -i - n); goto loop; } } if (isalpha(c) || c == '_' || c == '$') { do { putc(c, f); c = *++cptr; } while (isalnum(c) || c == '_' || c == '$'); goto loop; } putc(c, f); ++cptr; switch (c) { case '\n': next_line: get_line(); if (line) goto loop; unterminated_action(a_lineno, a_line, a_cptr); case ';': if (depth > 0) goto loop; fprintf(f, "\nbreak;\n"); return; case '{': ++depth; goto loop; case '}': if (--depth > 0) goto loop; fprintf(f, "\nbreak;\n"); return; case '\'': case '"': { int s_lineno = lineno; char *s_line = dup_line(); char *s_cptr = s_line + (cptr - line - 1); quote = c; for (;;) { c = *cptr++; putc(c, f); if (c == quote) { FREE(s_line); goto loop; } if (c == '\n') unterminated_string(s_lineno, s_line, s_cptr); if (c == '\\') { c = *cptr++; putc(c, f); if (c == '\n') { get_line(); if (line == 0) unterminated_string(s_lineno, s_line, s_cptr); } } } } case '/': c = *cptr; if (c == '/') { putc('*', f); while ((c = *++cptr) != '\n') { if (c == '*' && cptr[1] == '/') fprintf(f, "* "); else putc(c, f); } fprintf(f, "*/\n"); goto next_line; } if (c == '*') { int c_lineno = lineno; char *c_line = dup_line(); char *c_cptr = c_line + (cptr - line - 1); putc('*', f); ++cptr; for (;;) { c = *cptr++; putc(c, f); if (c == '*' && *cptr == '/') { putc('/', f); ++cptr; FREE(c_line); goto loop; } if (c == '\n') { get_line(); if (line == 0) unterminated_comment(c_lineno, c_line, c_cptr); } } } goto loop; default: goto loop; } } int mark_symbol(void) { int c; bucket *bp; c = cptr[1]; if (c == '%' || c == '\\') { cptr += 2; return (1); } if (c == '=') cptr += 2; else if ((c == 'p' || c == 'P') && ((c = cptr[2]) == 'r' || c == 'R') && ((c = cptr[3]) == 'e' || c == 'E') && ((c = cptr[4]) == 'c' || c == 'C') && ((c = cptr[5], !IS_IDENT(c)))) cptr += 5; else syntax_error(lineno, line, cptr); c = nextc(); if (isalpha(c) || c == '_' || c == '.' || c == '$') bp = get_name(); else if (c == '\'' || c == '"') bp = get_literal(); else { syntax_error(lineno, line, cptr); /*NOTREACHED*/ } if (rprec[nrules] != UNDEFINED && bp->prec != rprec[nrules]) prec_redeclared(); rprec[nrules] = bp->prec; rassoc[nrules] = bp->assoc; return (0); } void read_grammar(void) { int c; initialize_grammar(); advance_to_start(); for (;;) { c = nextc(); if (c == EOF) break; if (isalpha(c) || c == '_' || c == '.' || c == '$' || c == '\'' || c == '"') add_symbol(); else if (c == '{' || c == '=') copy_action(); else if (c == '|') { end_rule(); start_rule(plhs[nrules-1], 0); ++cptr; } else if (c == '%') { if (mark_symbol()) break; } else syntax_error(lineno, line, cptr); } end_rule(); } void free_tags(void) { int i; if (tag_table == 0) return; for (i = 0; i < ntags; ++i) { assert(tag_table[i]); FREE(tag_table[i]); } FREE(tag_table); } void pack_names(void) { bucket *bp; char *p, *s, *t; name_pool_size = 13; /* 13 == sizeof("$end") + sizeof("$accept") */ for (bp = first_symbol; bp; bp = bp->next) name_pool_size += strlen(bp->name) + 1; name_pool = MALLOC(name_pool_size); if (name_pool == 0) no_space(); strcpy(name_pool, "$accept"); strcpy(name_pool+8, "$end"); t = name_pool + 13; for (bp = first_symbol; bp; bp = bp->next) { p = t; s = bp->name; while ((*t++ = *s++)!=0) continue; FREE(bp->name); bp->name = p; } } void check_symbols(void) { bucket *bp; if (goal->class == UNKNOWN) undefined_goal(goal->name); for (bp = first_symbol; bp; bp = bp->next) { if (bp->class == UNKNOWN) { undefined_symbol_warning(bp->name); bp->class = TERM; } } } void pack_symbols(void) { bucket *bp; bucket **v; int i, j, k, n; nsyms = 2; ntokens = 1; for (bp = first_symbol; bp; bp = bp->next) { ++nsyms; if (bp->class == TERM) ++ntokens; } start_symbol = ntokens; nvars = nsyms - ntokens; symbol_name = (char **) MALLOC(nsyms*sizeof(char *)); if (symbol_name == 0) no_space(); symbol_value = (short *) MALLOC(nsyms*sizeof(short)); if (symbol_value == 0) no_space(); symbol_prec = (short *) MALLOC(nsyms*sizeof(short)); if (symbol_prec == 0) no_space(); symbol_assoc = MALLOC(nsyms); if (symbol_assoc == 0) no_space(); v = (bucket **) MALLOC(nsyms*sizeof(bucket *)); if (v == 0) no_space(); v[0] = 0; v[start_symbol] = 0; i = 1; j = start_symbol + 1; for (bp = first_symbol; bp; bp = bp->next) { if (bp->class == TERM) v[i++] = bp; else v[j++] = bp; } assert(i == ntokens && j == nsyms); for (i = 1; i < ntokens; ++i) v[i]->index = i; goal->index = start_symbol + 1; k = start_symbol + 2; while (++i < nsyms) if (v[i] != goal) { v[i]->index = k; ++k; } goal->value = 0; k = 1; for (i = start_symbol + 1; i < nsyms; ++i) { if (v[i] != goal) { v[i]->value = k; ++k; } } k = 0; for (i = 1; i < ntokens; ++i) { n = v[i]->value; if (n > 256) { for (j = k++; j > 0 && symbol_value[j-1] > n; --j) symbol_value[j] = symbol_value[j-1]; symbol_value[j] = n; } } if (v[1]->value == UNDEFINED) v[1]->value = 256; j = 0; n = 257; for (i = 2; i < ntokens; ++i) { if (v[i]->value == UNDEFINED) { while (j < k && n == symbol_value[j]) { while (++j < k && n == symbol_value[j]) continue; ++n; } v[i]->value = n; ++n; } } symbol_name[0] = name_pool + 8; symbol_value[0] = 0; symbol_prec[0] = 0; symbol_assoc[0] = TOKEN; for (i = 1; i < ntokens; ++i) { symbol_name[i] = v[i]->name; symbol_value[i] = v[i]->value; symbol_prec[i] = v[i]->prec; symbol_assoc[i] = v[i]->assoc; } symbol_name[start_symbol] = name_pool; symbol_value[start_symbol] = -1; symbol_prec[start_symbol] = 0; symbol_assoc[start_symbol] = TOKEN; for (++i; i < nsyms; ++i) { k = v[i]->index; symbol_name[k] = v[i]->name; symbol_value[k] = v[i]->value; symbol_prec[k] = v[i]->prec; symbol_assoc[k] = v[i]->assoc; } FREE(v); } void pack_grammar(void) { int i, j; int assoc, prec; ritem = (short *) MALLOC(nitems*sizeof(short)); if (ritem == 0) no_space(); rlhs = (short *) MALLOC(nrules*sizeof(short)); if (rlhs == 0) no_space(); rrhs = (short *) MALLOC((nrules+1)*sizeof(short)); if (rrhs == 0) no_space(); rprec = (short *) REALLOC(rprec, nrules*sizeof(short)); if (rprec == 0) no_space(); rassoc = REALLOC(rassoc, nrules); if (rassoc == 0) no_space(); ritem[0] = -1; ritem[1] = goal->index; ritem[2] = 0; ritem[3] = -2; rlhs[0] = 0; rlhs[1] = 0; rlhs[2] = start_symbol; rrhs[0] = 0; rrhs[1] = 0; rrhs[2] = 1; j = 4; for (i = 3; i < nrules; ++i) { rlhs[i] = plhs[i]->index; rrhs[i] = j; assoc = TOKEN; prec = 0; while (pitem[j]) { ritem[j] = pitem[j]->index; if (pitem[j]->class == TERM) { prec = pitem[j]->prec; assoc = pitem[j]->assoc; } ++j; } ritem[j] = -i; ++j; if (rprec[i] == UNDEFINED) { rprec[i] = prec; rassoc[i] = assoc; } } rrhs[i] = j; FREE(plhs); FREE(pitem); } void print_grammar(void) { int i, j, k; int spacing; FILE *f = verbose_file; if (!vflag) return; k = 1; for (i = 2; i < nrules; ++i) { if (rlhs[i] != rlhs[i-1]) { if (i != 2) fprintf(f, "\n"); fprintf(f, "%4d %s :", i - 2, symbol_name[rlhs[i]]); spacing = strlen(symbol_name[rlhs[i]]) + 1; } else { fprintf(f, "%4d ", i - 2); j = spacing; while (--j >= 0) putc(' ', f); putc('|', f); } while (ritem[k] >= 0) { fprintf(f, " %s", symbol_name[ritem[k]]); ++k; } ++k; putc('\n', f); } } void reader(void) { if (jflag) /*rwj*/ write_section(jbanner); else write_section(banner); create_symbol_table(); read_declarations(); read_grammar(); free_symbol_table(); free_tags(); pack_names(); check_symbols(); pack_symbols(); pack_grammar(); free_symbols(); print_grammar(); } byaccj1.15/src/README0000755000076500000240000000016510267363246013464 0ustar thurkastaff1. The documentation for this code is found at: http://byaccj.sourceforge.net It is also in the ./doc directory. byaccj1.15/src/._skeleton.c0000755000076500000240000000025311111765352015000 0ustar thurkastaffMac OS X  2y«ATTR—ÒR«œœcom.apple.TextEncodingUTF-8;134217984byaccj1.15/src/skeleton.c0000755000076500000240000010015111111765352014561 0ustar thurkastaff#include #include #include "defs.h" #define JAVA_PACKAGE "@JAVA_PACKAGE@" #define JAVA_CLASS_DECL "@JAVA_CLASS_DECL@" #define JAVA_RUN "@JAVA_RUN@" #define JAVA_CONSTRUCT "@JAVA_CONSTRUCT@" #define JAVA_STACK "@JAVA_STACK@" /* The banner used here should be replaced with an #ident directive */ /* if the target C compiler supports #ident directives. */ /* */ /* If the skeleton is changed, the banner should be changed so that */ /* the altered version can easily be distinguished from the original. */ char *banner[] = { "#ifndef lint", "static char yysccsid[] = \"@(#)yaccpar 1.8 (Berkeley) 01/20/90\";", "#endif", "#define YYBYACC 1", 0 }; char *jbanner[] = { "//### This file created by BYACC 1.8(/Java extension 1.15)", "//### Java capabilities added 7 Jan 97, Bob Jamison", "//### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten", "//### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor", "//### 01 Jun 99 -- Bob Jamison -- added Runnable support", "//### 06 Aug 00 -- Bob Jamison -- made state variables class-global", "//### 03 Jan 01 -- Bob Jamison -- improved flags, tracing", "//### 16 May 01 -- Bob Jamison -- added custom stack sizing", "//### 04 Mar 02 -- Yuval Oren -- improved java performance, added options", "//### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround", "//### Please send bug reports to tom@hukatronic.cz", "//### static char yysccsid[] = \"@(#)yaccpar 1.8 (Berkeley) 01/20/90\";", "\n\n", JAVA_PACKAGE, "\n\n", 0 }; char *tables[] = { "extern short yylhs[];", "extern short yylen[];", "extern short yydefred[];", "extern short yydgoto[];", "extern short yysindex[];", "extern short yyrindex[];", "extern short yygindex[];", "extern short yytable[];", "extern short yycheck[];", "#if YYDEBUG", "extern char *yyname[];", "extern char *yyrule[];", "#endif", 0 }; char *jtables[] = { "extern short yylhs[];", 0 }; char *header[] = { "#define yyclearin (yychar=(-1))", "#define yyerrok (yyerrflag=0)", "#ifdef YYSTACKSIZE", "#ifndef YYMAXDEPTH", "#define YYMAXDEPTH YYSTACKSIZE", "#endif", "#else", "#ifdef YYMAXDEPTH", "#define YYSTACKSIZE YYMAXDEPTH", "#else", "#define YYSTACKSIZE 500", "#define YYMAXDEPTH 500", "#endif", "#endif", "int yydebug;", "int yynerrs;", "int yyerrflag;", "int yychar;", "short *yyssp;", "YYSTYPE *yyvsp;", "YYSTYPE yyval;", "YYSTYPE yylval;", "short yyss[YYSTACKSIZE];", "YYSTYPE yyvs[YYSTACKSIZE];", "#define yystacksize YYSTACKSIZE", 0 }; /* yio 20011121: eliminated a bit of unnecessary code for better performance */ char *jheader[] = { "\n\n\n", JAVA_CLASS_DECL, "{\n", "boolean yydebug; //do I want debug output?", "int yynerrs; //number of errors so far", "int yyerrflag; //was there an error?", "int yychar; //the current working character", "\n//########## MESSAGES ##########", "//###############################################################", "// method: debug", "//###############################################################", "void debug(String msg)", "{", " if (yydebug)", " System.out.println(msg);", "}", "\n//########## STATE STACK ##########", JAVA_STACK, "\nint statestk[] = new int[YYSTACKSIZE]; //state stack", "int stateptr;", "int stateptrmax; //highest index of stackptr", "int statemax; //state when highest index reached", "//###############################################################", "// methods: state stack push,pop,drop,peek", "//###############################################################", "final void state_push(int state)", "{", " try {", " stateptr++;", " statestk[stateptr]=state;", " }", " catch (ArrayIndexOutOfBoundsException e) {", " int oldsize = statestk.length;", " int newsize = oldsize * 2;", " int[] newstack = new int[newsize];", " System.arraycopy(statestk,0,newstack,0,oldsize);", " statestk = newstack;", " statestk[stateptr]=state;", " }", "}", "final int state_pop()", "{", " return statestk[stateptr--];", "}", "final void state_drop(int cnt)", "{", " stateptr -= cnt; ", "}", "final int state_peek(int relative)", "{", " return statestk[stateptr-relative];", "}", "//###############################################################", "// method: init_stacks : allocate and prepare stacks", "//###############################################################", "final boolean init_stacks()", "{", " stateptr = -1;", " val_init();", " return true;", "}", "//###############################################################", "// method: dump_stacks : show n levels of the stacks", "//###############################################################", "void dump_stacks(int count)", "{", "int i;", " System.out.println(\"=index==state====value= s:\"+stateptr+\" v:\"+valptr);", " for (i=0;i= '0' && yyn <= '9')", " yydebug = yyn - '0';", " }", "#endif", "", " yynerrs = 0;", " yyerrflag = 0;", " yychar = (-1);", "", " yyssp = yyss;", " yyvsp = yyvs;", " *yyssp = yystate = 0;", "", "yyloop:", " if (yyn = yydefred[yystate]) goto yyreduce;", " if (yychar < 0)", " {", " if ((yychar = yylex()) < 0) yychar = 0;", "#if YYDEBUG", " if (yydebug)", " {", " yys = 0;", " if (yychar <= YYMAXTOKEN) yys = yyname[yychar];", " if (!yys) yys = \"illegal-symbol\";", " printf(\"yydebug: state %d, reading %d (%s)\\n\", yystate,", " yychar, yys);", " }", "#endif", " }", " if ((yyn = yysindex[yystate]) && (yyn += yychar) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yychar)", " {", "#if YYDEBUG", " if (yydebug)", " printf(\"yydebug: state %d, shifting to state %d (%s)\\n\",", " yystate, yytable[yyn],yyrule[yyn]);", "#endif", " if (yyssp >= yyss + yystacksize - 1)", " {", " goto yyoverflow;", " }", " *++yyssp = yystate = yytable[yyn];", " *++yyvsp = yylval;", " yychar = (-1);", " if (yyerrflag > 0) --yyerrflag;", " goto yyloop;", " }", " if ((yyn = yyrindex[yystate]) && (yyn += yychar) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yychar)", " {", " yyn = yytable[yyn];", " goto yyreduce;", " }", " if (yyerrflag) goto yyinrecovery;", "#ifdef lint", " goto yynewerror;", "#endif", "yynewerror:", " yyerror(\"syntax error\");", "#ifdef lint", " goto yyerrlab;", "#endif", "yyerrlab:", " ++yynerrs;", "yyinrecovery:", " if (yyerrflag < 3)", " {", " yyerrflag = 3;", " for (;;)", " {", " if ((yyn = yysindex[*yyssp]) && (yyn += YYERRCODE) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE)", " {", "#if YYDEBUG", " if (yydebug)", " printf(\"yydebug: state %d, error recovery shifting\\", " to state %d\\n\", *yyssp, yytable[yyn]);", "#endif", " if (yyssp >= yyss + yystacksize - 1)", " {", " goto yyoverflow;", " }", " *++yyssp = yystate = yytable[yyn];", " *++yyvsp = yylval;", " goto yyloop;", " }", " else", " {", "#if YYDEBUG", " if (yydebug)", " printf(\"yydebug: error recovery discarding state %d\ \\n\",", " *yyssp);", "#endif", " if (yyssp <= yyss) goto yyabort;", " --yyssp;", " --yyvsp;", " }", " }", " }", " else", " {", " if (yychar == 0) goto yyabort;", "#if YYDEBUG", " if (yydebug)", " {", " yys = 0;", " if (yychar <= YYMAXTOKEN) yys = yyname[yychar];", " if (!yys) yys = \"illegal-symbol\";", " printf(\"yydebug: state %d, error recovery discards token %d\ (%s)\\n\",", " yystate, yychar, yys);", " }", "#endif", " yychar = (-1);", " goto yyloop;", " }", "yyreduce:", "#if YYDEBUG", " if (yydebug)", " printf(\"yydebug: state %d, reducing by rule %d (%s)\\n\",", " yystate, yyn, yyrule[yyn]);", "#endif", " yym = yylen[yyn];", " yyval = yyvsp[1-yym];", " switch (yyn)", " {", 0 }; /* yio 20011121: eliminated a bit of unnecessary code for better performance */ char *jbody_a[] = { "//###############################################################", "// method: yylexdebug : check lexer state", "//###############################################################", "void yylexdebug(int state,int ch)", "{", "String s=null;", " if (ch < 0) ch=0;", " if (ch <= YYMAXTOKEN) //check index bounds", " s = yyname[ch]; //now get it", " if (s==null)", " s = \"illegal-symbol\";", " debug(\"state \"+state+\", reading \"+ch+\" (\"+s+\")\");", "}\n\n\n", "\n", "//The following are now global, to aid in error reporting", "int yyn; //next next thing to do", "int yym; //", "int yystate; //current parsing state from state table", "String yys; //current token string", "\n", "//###############################################################", "// method: yyparse : parse input and execute indicated items", "//###############################################################", "int yyparse()", 0 }; /* yio 20020304: thrown exceptions can be inserted between body sections a and b */ char *jbody_b[] = { "{", "boolean doaction;", " init_stacks();", " yynerrs = 0;", " yyerrflag = 0;", " yychar = -1; //impossible char forces a read", " yystate=0; //initial state", " state_push(yystate); //save it", " val_push(yylval); //save empty value", " while (true) //until parsing is done, either correctly, or w/error", " {", " doaction=true;", " if (yydebug) debug(\"loop\"); ", " //#### NEXT ACTION (from reduction table)", " for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate])", " {", " if (yydebug) debug(\"yyn:\"+yyn+\" state:\"+yystate+\" yychar:\"+yychar);", " if (yychar < 0) //we want a char?", " {", " yychar = yylex(); //get next token", " if (yydebug) debug(\" next yychar:\"+yychar);", " //#### ERROR CHECK ####", " if (yychar < 0) //it it didn't work/error", " {", " yychar = 0; //change it to default string (no -1!)", " if (yydebug)", " yylexdebug(yystate,yychar);", " }", " }//yychar<0", " yyn = yysindex[yystate]; //get amount to shift by (shift index)", " if ((yyn != 0) && (yyn += yychar) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yychar)", " {", " if (yydebug)", " debug(\"state \"+yystate+\", shifting to state \"+yytable[yyn]);", " //#### NEXT STATE ####", " yystate = yytable[yyn];//we are in a new state", " state_push(yystate); //save it", " val_push(yylval); //push our lval as the input for next rule", " yychar = -1; //since we have 'eaten' a token, say we need another", " if (yyerrflag > 0) //have we recovered an error?", " --yyerrflag; //give ourselves credit", " doaction=false; //but don't process yet", " break; //quit the yyn=0 loop", " }", "", " yyn = yyrindex[yystate]; //reduce", " if ((yyn !=0 ) && (yyn += yychar) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yychar)", " { //we reduced!", " if (yydebug) debug(\"reduce\");", " yyn = yytable[yyn];", " doaction=true; //get ready to execute", " break; //drop down to actions", " }", " else //ERROR RECOVERY", " {", " if (yyerrflag==0)", " {", " yyerror(\"syntax error\");", " yynerrs++;", " }", " if (yyerrflag < 3) //low error count?", " {", " yyerrflag = 3;", " while (true) //do until break", " {", " if (stateptr<0) //check for under & overflow here", " {", " yyerror(\"stack underflow. aborting...\"); //note lower case 's'", " return 1;", " }", " yyn = yysindex[state_peek(0)];", " if ((yyn != 0) && (yyn += YYERRCODE) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE)", " {", " if (yydebug)", " debug(\"state \"+state_peek(0)+\", error recovery shifting to state \"+yytable[yyn]+\" \");", " yystate = yytable[yyn];", " state_push(yystate);", " val_push(yylval);", " doaction=false;", " break;", " }", " else", " {", " if (yydebug)", " debug(\"error recovery discarding state \"+state_peek(0)+\" \");", " if (stateptr<0) //check for under & overflow here", " {", " yyerror(\"Stack underflow. aborting...\"); //capital 'S'", " return 1;", " }", " state_pop();", " val_pop();", " }", " }", " }", " else //discard this token", " {", " if (yychar == 0)", " return 1; //yyabort", " if (yydebug)", " {", " yys = null;", " if (yychar <= YYMAXTOKEN) yys = yyname[yychar];", " if (yys == null) yys = \"illegal-symbol\";", " debug(\"state \"+yystate+\", error recovery discards token \"+yychar+\" (\"+yys+\")\");", " }", " yychar = -1; //read another", " }", " }//end error recovery", " }//yyn=0 loop", " if (!doaction) //any reason not to proceed?", " continue; //skip action", " yym = yylen[yyn]; //get count of terminals on rhs", " if (yydebug)", " debug(\"state \"+yystate+\", reducing \"+yym+\" by rule \"+yyn+\" (\"+yyrule[yyn]+\")\");", " if (yym>0) //if count of rhs not 'nil'", " yyval = val_peek(yym-1); //get current semantic value", " yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value", " switch(yyn)", " {", "//########## USER-SUPPLIED ACTIONS ##########", 0 }; /* yio 20011121: this version never checks debug flag for better performance */ char *jbody_nodebug_a[] = { "//###############################################################", "// method: yylexdebug : check lexer state", "//###############################################################", "void yylexdebug(int state,int ch)", "{", "String s=null;", " if (ch < 0) ch=0;", " if (ch <= YYMAXTOKEN) //check index bounds", " s = yyname[ch]; //now get it", " if (s==null)", " s = \"illegal-symbol\";", " debug(\"state \"+state+\", reading \"+ch+\" (\"+s+\")\");", "}\n\n\n", "\n", "//The following are now global, to aid in error reporting", "int yyn; //next next thing to do", "int yym; //", "int yystate; //current parsing state from state table", "String yys; //current token string", "\n", "//###############################################################", "// method: yyparse : parse input and execute indicated items", "//###############################################################", "int yyparse()", 0 }; /* yio 20020304: thrown exceptions can be inserted between body sections a and b */ char *jbody_nodebug_b[] = { "{", "boolean doaction;", " init_stacks();", " yynerrs = 0;", " yyerrflag = 0;", " yychar = -1; //impossible char forces a read", " yystate=0; //initial state", " state_push(yystate); //save it", " val_push(yylval); //save empty value", " while (true) //until parsing is done, either correctly, or w/error", " {", " doaction=true;", " //if (yydebug) debug(\"loop\"); ", " //#### NEXT ACTION (from reduction table)", " for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate])", " {", " //if (yydebug) debug(\"yyn:\"+yyn+\" state:\"+yystate+\" yychar:\"+yychar);", " if (yychar < 0) //we want a char?", " {", " yychar = yylex(); //get next token", " //if (yydebug) debug(\" next yychar:\"+yychar);", " //#### ERROR CHECK ####", " if (yychar < 0) //it it didn't work/error", " {", " yychar = 0; //change it to default string (no -1!)", " //if (yydebug)", " // yylexdebug(yystate,yychar);", " }", " }//yychar<0", " yyn = yysindex[yystate]; //get amount to shift by (shift index)", " if ((yyn != 0) && (yyn += yychar) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yychar)", " {", " //if (yydebug)", " //debug(\"state \"+yystate+\", shifting to state \"+yytable[yyn]);", " //#### NEXT STATE ####", " yystate = yytable[yyn];//we are in a new state", " state_push(yystate); //save it", " val_push(yylval); //push our lval as the input for next rule", " yychar = -1; //since we have 'eaten' a token, say we need another", " if (yyerrflag > 0) //have we recovered an error?", " --yyerrflag; //give ourselves credit", " doaction=false; //but don't process yet", " break; //quit the yyn=0 loop", " }", "", " yyn = yyrindex[yystate]; //reduce", " if ((yyn !=0 ) && (yyn += yychar) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yychar)", " { //we reduced!", " //if (yydebug) debug(\"reduce\");", " yyn = yytable[yyn];", " doaction=true; //get ready to execute", " break; //drop down to actions", " }", " else //ERROR RECOVERY", " {", " if (yyerrflag==0)", " {", " yyerror(\"syntax error\");", " yynerrs++;", " }", " if (yyerrflag < 3) //low error count?", " {", " yyerrflag = 3;", " while (true) //do until break", " {", " if (stateptr<0) //check for under & overflow here", " {", " yyerror(\"stack underflow. aborting...\"); //note lower case 's'", " return 1;", " }", " yyn = yysindex[state_peek(0)];", " if ((yyn != 0) && (yyn += YYERRCODE) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE)", " {", " //if (yydebug)", " //debug(\"state \"+state_peek(0)+\", error recovery shifting to state \"+yytable[yyn]+\" \");", " yystate = yytable[yyn];", " state_push(yystate);", " val_push(yylval);", " doaction=false;", " break;", " }", " else", " {", " //if (yydebug)", " //debug(\"error recovery discarding state \"+state_peek(0)+\" \");", " if (stateptr<0) //check for under & overflow here", " {", " yyerror(\"Stack underflow. aborting...\"); //capital 'S'", " return 1;", " }", " state_pop();", " val_pop();", " }", " }", " }", " else //discard this token", " {", " if (yychar == 0)", " return 1; //yyabort", " //if (yydebug)", " //{", " //yys = null;", " //if (yychar <= YYMAXTOKEN) yys = yyname[yychar];", " //if (yys == null) yys = \"illegal-symbol\";", " //debug(\"state \"+yystate+\", error recovery discards token \"+yychar+\" (\"+yys+\")\");", " //}", " yychar = -1; //read another", " }", " }//end error recovery", " }//yyn=0 loop", " if (!doaction) //any reason not to proceed?", " continue; //skip action", " yym = yylen[yyn]; //get count of terminals on rhs", " //if (yydebug)", " //debug(\"state \"+yystate+\", reducing \"+yym+\" by rule \"+yyn+\" (\"+yyrule[yyn]+\")\");", " if (yym>0) //if count of rhs not 'nil'", " yyval = val_peek(yym-1); //get current semantic value", " yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value", " switch(yyn)", " {", "//########## USER-SUPPLIED ACTIONS ##########", 0 }; char *trailer[] = { " }", " yyssp -= yym;", " yystate = *yyssp;", " yyvsp -= yym;", " yym = yylhs[yyn];", " if (yystate == 0 && yym == 0)", " {", "#if YYDEBUG", " if (yydebug)", " printf(\"yydebug: after reduction, shifting from state 0 to\\", " state %d\\n\", YYFINAL);", "#endif", " yystate = YYFINAL;", " *++yyssp = YYFINAL;", " *++yyvsp = yyval;", " if (yychar < 0)", " {", " if ((yychar = yylex()) < 0) yychar = 0;", "#if YYDEBUG", " if (yydebug)", " {", " yys = 0;", " if (yychar <= YYMAXTOKEN) yys = yyname[yychar];", " if (!yys) yys = \"illegal-symbol\";", " printf(\"yydebug: state %d, reading %d (%s)\\n\",", " YYFINAL, yychar, yys);", " }", "#endif", " }", " if (yychar == 0) goto yyaccept;", " goto yyloop;", " }", " if ((yyn = yygindex[yym]) && (yyn += yystate) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yystate)", " yystate = yytable[yyn];", " else", " yystate = yydgoto[yym];", "#if YYDEBUG", " if (yydebug)", " printf(\"yydebug: after reduction, shifting from state %d \\", "to state %d\\n\", *yyssp, yystate);", "#endif", " if (yyssp >= yyss + yystacksize - 1)", " {", " goto yyoverflow;", " }", " *++yyssp = yystate;", " *++yyvsp = yyval;", " goto yyloop;", "yyoverflow:", " yyerror(\"yacc stack overflow\");", "yyabort:", " return (1);", "yyaccept:", " return (0);", "}", 0 }; char *jtrailer[] = { "//########## END OF USER-SUPPLIED ACTIONS ##########", " }//switch", " //#### Now let's reduce... ####", " if (yydebug) debug(\"reduce\");", " state_drop(yym); //we just reduced yylen states", " yystate = state_peek(0); //get new state", " val_drop(yym); //corresponding value drop", " yym = yylhs[yyn]; //select next TERMINAL(on lhs)", " if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL", " {", " if (yydebug) debug(\"After reduction, shifting from state 0 to state \"+YYFINAL+\"\");", " yystate = YYFINAL; //explicitly say we're done", " state_push(YYFINAL); //and save it", " val_push(yyval); //also save the semantic value of parsing", " if (yychar < 0) //we want another character?", " {", " yychar = yylex(); //get next character", " if (yychar<0) yychar=0; //clean, if necessary", " if (yydebug)", " yylexdebug(yystate,yychar);", " }", " if (yychar == 0) //Good exit (if lex returns 0 ;-)", " break; //quit the loop--all DONE", " }//if yystate", " else //else not done yet", " { //get next state and push, for next yydefred[]", " yyn = yygindex[yym]; //find out where to go", " if ((yyn != 0) && (yyn += yystate) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yystate)", " yystate = yytable[yyn]; //get new state", " else", " yystate = yydgoto[yym]; //else go to new defred", " if (yydebug) debug(\"after reduction, shifting from state \"+state_peek(0)+\" to state \"+yystate+\"\");", " state_push(yystate); //going again, so push state & val...", " val_push(yyval); //for next action", " }", " }//main loop", " return 0;//yyaccept!!", "}", "//## end of method parse() ######################################", "\n\n", "//## run() --- for Thread #######################################", JAVA_RUN, "//## end of method run() ########################################", "\n\n", "//## Constructors ###############################################", JAVA_CONSTRUCT, "//###############################################################", "\n\n", "}", "//################### END OF CLASS ##############################", 0 }; /* yio 20011121: this version never checks debug flag for better performance */ char *jtrailer_nodebug[] = { "//########## END OF USER-SUPPLIED ACTIONS ##########", " }//switch", " //#### Now let's reduce... ####", " //if (yydebug) debug(\"reduce\");", " state_drop(yym); //we just reduced yylen states", " yystate = state_peek(0); //get new state", " val_drop(yym); //corresponding value drop", " yym = yylhs[yyn]; //select next TERMINAL(on lhs)", " if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL", " {", " //if (yydebug) debug(\"After reduction, shifting from state 0 to state \"+YYFINAL+\"\");", " yystate = YYFINAL; //explicitly say we're done", " state_push(YYFINAL); //and save it", " val_push(yyval); //also save the semantic value of parsing", " if (yychar < 0) //we want another character?", " {", " yychar = yylex(); //get next character", " if (yychar<0) yychar=0; //clean, if necessary", " //if (yydebug)", " //yylexdebug(yystate,yychar);", " }", " if (yychar == 0) //Good exit (if lex returns 0 ;-)", " break; //quit the loop--all DONE", " }//if yystate", " else //else not done yet", " { //get next state and push, for next yydefred[]", " yyn = yygindex[yym]; //find out where to go", " if ((yyn != 0) && (yyn += yystate) >= 0 &&", " yyn <= YYTABLESIZE && yycheck[yyn] == yystate)", " yystate = yytable[yyn]; //get new state", " else", " yystate = yydgoto[yym]; //else go to new defred", " //if (yydebug) debug(\"after reduction, shifting from state \"+state_peek(0)+\" to state \"+yystate+\"\");", " state_push(yystate); //going again, so push state & val...", " val_push(yyval); //for next action", " }", " }//main loop", " return 0;//yyaccept!!", "}", "//## end of method parse() ######################################", "\n\n", "//## run() --- for Thread #######################################", JAVA_RUN, "//## end of method run() ########################################", "\n\n", "//## Constructors ###############################################", JAVA_CONSTRUCT, "//###############################################################", "\n\n", "}", "//################### END OF CLASS ##############################", 0 }; void write_section(char **section) { int i; FILE *fp; fp = code_file; for (i = 0; section[i]; ++i) { ++outline; if (strcmp(section[i],JAVA_PACKAGE)==0) /*Java package name, if any*/ { if (jpackage_name && strlen(jpackage_name)>0) fprintf(fp,"package %s;\n",jpackage_name); } else if (strcmp(section[i],JAVA_CLASS_DECL)==0) { if (jclass_name && strlen(jclass_name)>0) fprintf(fp,"public class %s\n",jclass_name); else fprintf(fp,"public class Parser\n"); if (jextend_name && strlen(jextend_name)>0) fprintf(fp," extends %s\n",jextend_name); if (jimplement_name && strlen(jimplement_name)>0) fprintf(fp," implements %s\n",jimplement_name); } else if (strcmp(section[i],JAVA_RUN)==0) { if (jrun) { fprintf(fp,"/**\n"); fprintf(fp," * A default run method, used for operating this parser\n"); fprintf(fp," * object in the background. It is intended for extending Thread\n"); fprintf(fp," * or implementing Runnable. Turn off with -Jnorun .\n"); fprintf(fp," */\n"); fprintf(fp,"public void run()\n"); fprintf(fp,"{\n"); fprintf(fp," yyparse();\n"); fprintf(fp,"}\n"); } else { fprintf(fp,"//## The -Jnorun option was used ##\n"); } } else if (strcmp(section[i],JAVA_CONSTRUCT)==0) { if (jconstruct) { fprintf(fp,"/**\n"); fprintf(fp," * Default constructor. Turn off with -Jnoconstruct .\n\n"); fprintf(fp," */\n"); fprintf(fp,"public %s()\n",jclass_name); fprintf(fp,"{\n"); fprintf(fp," //nothing to do\n"); fprintf(fp,"}\n"); fprintf(fp,"\n\n"); fprintf(fp,"/**\n"); fprintf(fp," * Create a parser, setting the debug to true or false.\n"); fprintf(fp," * @param debugMe true for debugging, false for no debug.\n"); fprintf(fp," */\n"); fprintf(fp,"public %s(boolean debugMe)\n",jclass_name); fprintf(fp,"{\n"); fprintf(fp," yydebug=debugMe;\n"); fprintf(fp,"}\n"); } else { fprintf(fp,"//## The -Jnoconstruct option was used ##\n"); } } else if (strcmp(section[i],JAVA_STACK)==0) { fprintf(fp, "final static int YYSTACKSIZE = %d; //maximum stack size", jstack_size); } else fprintf(fp, "%s\n", section[i]); } } byaccj1.15/src/symtab.c0000755000076500000240000000331107444073365014246 0ustar thurkastaff#include #include #include "defs.h" /* TABLE_SIZE is the number of entries in the symbol table. */ /* TABLE_SIZE must be a power of two. */ #define TABLE_SIZE 1024 bucket **symbol_table; bucket *first_symbol; bucket *last_symbol; int hash(char *name) { char *s; int c, k; assert(name && *name); s = name; k = *s; while ((c = (int)*(++s))!=0) k = (31*k + c) & (TABLE_SIZE - 1); return (k); } bucket *make_bucket(char *name) { bucket *bp; assert(name); bp = (bucket *) MALLOC(sizeof(bucket)); if (bp == 0) no_space(); bp->link = 0; bp->next = 0; bp->name = MALLOC(strlen(name) + 1); if (bp->name == 0) no_space(); bp->tag = 0; bp->value = UNDEFINED; bp->index = 0; bp->prec = 0; bp-> class = UNKNOWN; bp->assoc = TOKEN; if (bp->name == 0) no_space(); strcpy(bp->name, name); return (bp); } bucket *lookup(char *name) { bucket *bp, **bpp; bpp = symbol_table + hash(name); bp = *bpp; while (bp) { if (strcmp(name, bp->name) == 0) return (bp); bpp = &bp->link; bp = *bpp; } *bpp = bp = make_bucket(name); last_symbol->next = bp; last_symbol = bp; return (bp); } void create_symbol_table(void) { int i; bucket *bp; symbol_table = (bucket **) MALLOC(TABLE_SIZE*sizeof(bucket *)); if (symbol_table == 0) no_space(); for (i = 0; i < TABLE_SIZE; i++) symbol_table[i] = 0; bp = make_bucket("error"); bp->index = 1; bp->class = TERM; first_symbol = bp; last_symbol = bp; symbol_table[hash("error")] = bp; } void free_symbol_table(void) { FREE(symbol_table); symbol_table = 0; } void free_symbols(void) { bucket *p, *q; for (p = first_symbol; p; p = q) { q = p->next; FREE(p); } } byaccj1.15/src/t.y0000755000076500000240000000452110443440533013230 0ustar thurkastaff%{ import java.lang.Math; import java.io.*; import java.util.StringTokenizer; %} /* YACC Declarations */ %token NUM %left '-' '+' %left '*' '/' %left NEG /* negation--unary minus */ %right '^' /* exponentiation */ /* Grammar follows */ %% input: /* empty string */ | input line ; line: '\n' | exp '\n' { System.out.println(" " + $1.dval + " "); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = new ParserVal($1.dval + $3.dval); } | exp '-' exp { $$ = new ParserVal($1.dval - $3.dval); } | exp '*' exp { $$ = new ParserVal($1.dval * $3.dval); } | exp '/' exp { $$ = new ParserVal($1.dval / $3.dval); } | '-' exp %prec NEG { $$ = new ParserVal(-$2.dval); } | exp '^' exp { $$ = new ParserVal(Math.pow($1.dval, $3.dval)); } | '(' exp ')' { $$ = $2; } ; %% String ins; StringTokenizer st; void yyerror(String s) { System.out.println("par:"+s); } boolean newline; int yylex() { String s; int tok; Double d; //System.out.print("yylex "); if (!st.hasMoreTokens()) if (!newline) { newline=true; return '\n'; //So we look like classic YACC example } else return 0; s = st.nextToken(); //System.out.println("tok:"+s); try { d = Double.valueOf(s);/*this may fail*/ yylval = new ParserVal(d.doubleValue()); tok = NUM; } catch (Exception e) { tok = s.charAt(0);/*if not float, return char*/ } return tok; } void dotest() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("BYACC/Java Calculator Demo"); System.out.println("Note: Since this example uses the StringTokenizer"); System.out.println("for simplicity, you will need to separate the items"); System.out.println("with spaces, i.e.: '( 3 + 5 ) * 2'"); while (true) { System.out.print("expression:"); try { ins = in.readLine(); } catch (Exception e) { } st = new StringTokenizer(ins); newline=false; if (yyparse()!=0) { System.out.println("error"); } } } public static void main(String args[]) { Parser par = new Parser(true); par.dotest(); } byaccj1.15/src/tf.y0000755000076500000240000000447607441711567013423 0ustar thurkastaff%{ import java.lang.Math; import java.io.*; import java.util.StringTokenizer; %} /* YACC Declarations */ %token NUM %left '-' '+' %left '*' '/' %left NEG /* negation--unary minus */ %right '^' /* exponentiation */ /* Grammar follows */ %% input: /* empty string */ | input line ; line: '\n' | exp '\n' { System.out.println(" " + $1 + " "); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = $1 + $3; } | exp '-' exp { $$ = $1 - $3; } | exp '*' exp { $$ = $1 * $3; } | exp '/' exp { $$ = $1 / $3; } | '-' exp %prec NEG { $$ = -$2; } | exp '^' exp { $$ = Math.pow($1, $3); } | '(' exp ')' { $$ = $2; } ; %% String ins; StringTokenizer st; void yyerror(String s) { System.out.println("par:"+s); } boolean newline; int yylex() { String s; int tok; Double d; //System.out.print("yylex "); if (!st.hasMoreTokens()) if (!newline) { newline=true; return '\n'; //So we look like classic YACC example } else return 0; s = st.nextToken(); //System.out.println("tok:"+s); try { d = Double.valueOf(s);/*this may fail*/ yylval = d.doubleValue(); tok = NUM; } catch (Exception e) { tok = s.charAt(0);/*if not float, return char*/ } return tok; } void dotest() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("BYACC/Java Calculator Demo"); System.out.println("Note: Since this example uses the StringTokenizer"); System.out.println("for simplicity, you will need to separate the items"); System.out.println("with spaces, i.e.: '( 3 + 5 ) * 2'"); while (true) { System.out.print("expression:"); try { ins = in.readLine(); } catch (Exception e) { } st = new StringTokenizer(ins); newline=false; yyparse(); } } public static void main(String args[]) { parser par = new parser(false); par.dotest(); } byaccj1.15/src/tt.y0000755000076500000240000000466107441711567013435 0ustar thurkastaff%{ import java.lang.Math; import java.io.*; import java.util.StringTokenizer; %} /* YACC Declarations */ %token NUM %left '-' '+' %left '*' '/' %left NEG /* negation--unary minus */ %right '^' /* exponentiation */ /* Grammar follows */ %% input: /* empty string */ | input line ; line: '\n' | exp '\n' { System.out.println(" " + $1.dval + " "); } ; exp: NUM { $$ = $1; } | exp '+' exp { $$.dval = $1.dval + $3.dval; } | exp '-' exp { $$.dval = $1.dval - $3.dval; } | exp '*' exp { $$.dval = $1.dval * $3.dval; } | exp '/' exp { $$.dval = $1.dval / $3.dval; } | '-' exp %prec NEG { $$.dval = -$2.dval; } | exp '^' exp { $$.dval = Math.pow($1.dval, $3.dval); } | '(' exp ')' { $$.dval = $2.dval; } ; %% String ins; StringTokenizer st; void yyerror(String s) { System.out.println("par:"+s); } boolean newline; int yylex() { String s; int tok; Double d; //System.out.print("yylex "); if (!st.hasMoreTokens()) if (!newline) { newline=true; return '\n'; //So we look like classic YACC example } else return 0; s = st.nextToken(); //System.out.println("tok:"+s); try { d = Double.valueOf(s);/*this may fail*/ yylval = new parserval(d.doubleValue()); tok = NUM; } catch (Exception e) { tok = s.charAt(0);/*if not float, return char*/ } return tok; } void dotest() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("BYACC/Java Calculator Demo"); System.out.println("Note: Since this example uses the StringTokenizer"); System.out.println("for simplicity, you will need to separate the items"); System.out.println("with spaces, i.e.: '( 3 + 5 ) * 2'"); while (true) { System.out.print("expression:"); try { ins = in.readLine(); } catch (Exception e) { } st = new StringTokenizer(ins); newline=false; yyparse(); } } public static void main(String args[]) { parser par = new parser(false); par.dotest(); } byaccj1.15/src/verbose.c0000755000076500000240000001362507444073365014425 0ustar thurkastaff#include #include "defs.h" static short *null_rules; void verbose(void) { int i; if (!vflag) return; null_rules = (short *) MALLOC(nrules*sizeof(short)); if (null_rules == 0) no_space(); fprintf(verbose_file, "\f\n"); for (i = 0; i < nstates; i++) print_state(i); FREE(null_rules); if (nunused) log_unused(); if (SRtotal || RRtotal) log_conflicts(); fprintf(verbose_file, "\n\n%d terminals, %d nonterminals\n", ntokens,nvars); fprintf(verbose_file, "%d grammar rules, %d states\n", nrules - 2, nstates); } void log_unused(void) { int i; short *p; fprintf(verbose_file, "\n\nRules never reduced:\n"); for (i = 3; i < nrules; ++i) { if (!rules_used[i]) { fprintf(verbose_file, "\t%s :", symbol_name[rlhs[i]]); for (p = ritem + rrhs[i]; *p >= 0; ++p) fprintf(verbose_file, " %s", symbol_name[*p]); fprintf(verbose_file, " (%d)\n", i - 2); } } } void log_conflicts(void) { int i; fprintf(verbose_file, "\n\n"); for (i = 0; i < nstates; i++) { if (SRconflicts[i] || RRconflicts[i]) { fprintf(verbose_file, "State %d contains ", i); if (SRconflicts[i] == 1) fprintf(verbose_file, "1 shift/reduce conflict"); else if (SRconflicts[i] > 1) fprintf(verbose_file, "%d shift/reduce conflicts",SRconflicts[i]); if (SRconflicts[i] && RRconflicts[i]) fprintf(verbose_file, ", "); if (RRconflicts[i] == 1) fprintf(verbose_file, "1 reduce/reduce conflict"); else if (RRconflicts[i] > 1) fprintf(verbose_file, "%d reduce/reduce conflicts",RRconflicts[i]); fprintf(verbose_file, ".\n"); } } } void print_state(int state) { if (state) fprintf(verbose_file, "\n\n"); if (SRconflicts[state] || RRconflicts[state]) print_conflicts(state); fprintf(verbose_file, "state %d\n", state); print_core(state); print_nulls(state); print_actions(state); } void print_conflicts(int state) { int symbol, act, number; action *p; symbol = -1; for (p = parser[state]; p; p = p->next) { if (p->suppressed == 2) continue; if (p->symbol != symbol) { symbol = p->symbol; number = p->number; if (p->action_code == SHIFT) act = SHIFT; else act = REDUCE; } else if (p->suppressed == 1) { if (state == final_state && symbol == 0) { fprintf(verbose_file, "%d: shift/reduce conflict (accept, reduce %d) on $end\n", state, p->number - 2); } else { if (act == SHIFT) { fprintf(verbose_file, "%d: shift/reduce conflict (shift %d, reduce %d) on %s\n", state, number, p->number - 2,symbol_name[symbol]); } else { fprintf(verbose_file, "%d: reduce/reduce conflict (reduce %d, reduce %d) on %s\n", state, number - 2, p->number - 2,symbol_name[symbol]); } } } } } void print_core(int state) { int i; int k; int rule; core *statep; short *sp; short *sp1; statep = state_table[state]; k = statep->nitems; for (i = 0; i < k; i++) { sp1 = sp = ritem + statep->items[i]; while (*sp >= 0) ++sp; rule = -(*sp); fprintf(verbose_file, "\t%s : ", symbol_name[rlhs[rule]]); for (sp = ritem + rrhs[rule]; sp < sp1; sp++) fprintf(verbose_file, "%s ", symbol_name[*sp]); putc('.', verbose_file); while (*sp >= 0) { fprintf(verbose_file, " %s", symbol_name[*sp]); sp++; } fprintf(verbose_file, " (%d)\n", -2 - *sp); } } void print_nulls(int state) { action *p; int i, j, k, nnulls; nnulls = 0; for (p = parser[state]; p; p = p->next) { if (p->action_code == REDUCE && (p->suppressed == 0 || p->suppressed == 1)) { i = p->number; if (rrhs[i] + 1 == rrhs[i+1]) { for (j = 0; j < nnulls && i > null_rules[j]; ++j) continue; if (j == nnulls) { ++nnulls; null_rules[j] = i; } else if (i != null_rules[j]) { ++nnulls; for (k = nnulls - 1; k > j; --k) null_rules[k] = null_rules[k-1]; null_rules[j] = i; } } } } for (i = 0; i < nnulls; ++i) { j = null_rules[i]; fprintf(verbose_file, "\t%s : . (%d)\n", symbol_name[rlhs[j]],j - 2); } fprintf(verbose_file, "\n"); } void print_actions(int stateno) { action *p; shifts *sp; int as; if (stateno == final_state)fprintf(verbose_file, "\t$end accept\n"); p = parser[stateno]; if (p) { print_shifts(p); print_reductions(p, defred[stateno]); } sp = shift_table[stateno]; if (sp && sp->nshifts > 0) { as = accessing_symbol[sp->shift[sp->nshifts - 1]]; if (ISVAR(as)) print_gotos(stateno); } } void print_shifts(action *p) { int count; action *q; count = 0; for (q = p; q; q = q->next) { if (q->suppressed < 2 && q->action_code == SHIFT) ++count; } if (count > 0) { for (; p; p = p->next) { if (p->action_code == SHIFT && p->suppressed == 0) fprintf(verbose_file, "\t%s shift %d\n",symbol_name[p->symbol], p->number); } } } void print_reductions(action *p,int defred) { int k, anyreds; action *q; anyreds = 0; for (q = p; q ; q = q->next) { if (q->action_code == REDUCE && q->suppressed < 2) { anyreds = 1; break; } } if (anyreds == 0) fprintf(verbose_file, "\t. error\n"); else { for (; p; p = p->next) { if (p->action_code == REDUCE && p->number != defred) { k = p->number - 2; if (p->suppressed == 0) fprintf(verbose_file, "\t%s reduce %d\n",symbol_name[p->symbol], k); } } if (defred > 0) fprintf(verbose_file, "\t. reduce %d\n", defred - 2); } } void print_gotos(int stateno) { int i, k; int as; short *to_state; shifts *sp; putc('\n', verbose_file); sp = shift_table[stateno]; to_state = sp->shift; for (i = 0; i < sp->nshifts; ++i) { k = to_state[i]; as = accessing_symbol[k]; if (ISVAR(as)) fprintf(verbose_file, "\t%s goto %d\n", symbol_name[as], k); } } byaccj1.15/src/warshall.c0000755000076500000240000000201107441711572014554 0ustar thurkastaff#include "defs.h" void transitive_closure(unsigned *R, int n) { int rowsize; unsigned mask; unsigned *rowj; unsigned *rp; unsigned *rend; unsigned *ccol; unsigned *relend; unsigned *cword; unsigned *rowi; rowsize = WORDSIZE(n); relend = R + n*rowsize; cword = R; mask = 1; rowi = R; while (rowi < relend) { ccol = cword; rowj = R; while (rowj < relend) { if (*ccol & mask) { rp = rowi; rend = rowj + rowsize; while (rowj < rend) *rowj++ |= *rp++; } else { rowj += rowsize; } ccol += rowsize; } mask <<= 1; if (mask == 0) { mask = 1; cword++; } rowi += rowsize; } } void reflexive_transitive_closure(unsigned *R, int n) { int rowsize; unsigned mask; unsigned *rp; unsigned *relend; transitive_closure(R, n); rowsize = WORDSIZE(n); relend = R + n*rowsize; mask = 1; rp = R; while (rp < relend) { *rp |= mask; mask <<= 1; if (mask == 0) { mask = 1; rp++; } rp += rowsize; } } byaccj1.15/src/x.y0000755000076500000240000001066107441711566013251 0ustar thurkastaff%{ /* Do not delete this line! */ /************************************************************************** ** file: course.y ** ** does: Profides course file ".crs" file parsing for ICAT ** ** date: 950715 ** ** author: R. Jamison ** *************************************************************************** ** notes: ** ** *************************************************************************** ** history: ** ** date engr remarks ** ------ ----------------- ----------------------------- ** ...... . . ** **************************************************************************/ /**** put your Java field declarations here ****/ %} %token FLOAT %token VERSION LB RB QSTR DESCRIPTION TITLE DESC ABSTRACT CODE %token LESSON EXERCISE FILE_W DIR FILENAME %token CONFIG KEY STR INT PROGRAM %token ICAT DATA SOUNDS HTML_TOOL AUTHOR_TOOL MODEL_TOOL %% crsfile: VERSION { /*VSTR(verbuf);*/ } coursedef { } ; coursedef: description lessonlist exerlist { } | description config lessonlist exerlist { } ; /*+++DESCRIPTION+++*/ description : DESCRIPTION LB title { /*VQSTR(titlebuf);*/ } desc { /*VQSTR(descbuf);*/ } code abstract { /*VASTR(abstract);*/ } RB { /*cs = crs_add_course(NULL,verbuf,titlebuf,descbuf,codebuf,abstract); par=cs;*/ /* printf(":%s:%s:%s:%s:%s:\n",verbuf,titlebuf,descbuf,codebuf,abstract); */ } ; title: TITLE QSTR { } ; desc: DESC QSTR { } ; abstract: ABSTRACT QSTR { } ; /*+++CONFIG+++*/ config: CONFIG LB cfglist RB { } ; cfglist: /*Nil*/ | cfgitem cfglist { } ; cfgitem: ICAT LB icatlist RB | AUTHOR_TOOL LB authorlist RB | SOUNDS LB sounditem RB | HTML_TOOL LB htmllist RB | MODEL_TOOL LB modellist RB ; icatlist: /*Null*/ | icatlist icatitem ; icatitem: DATA FILENAME { /*VQSTR(cf->icat_data);*/ } | DATA QSTR { /*VQSTR(cf->icat_data);*/ } ; authorlist: /*Null*/ | authorlist authoritem ; authoritem: PROGRAM FILENAME { /*VQSTR(cf->author_tool);*/ } | PROGRAM QSTR { /*VQSTR(cf->author_tool);*/ } | FILE_W FILENAME { /*VQSTR(cf->author_file);*/ } | FILE_W QSTR { /*VQSTR(cf->author_file);*/ } ; htmllist: /*Null*/ | htmlitem htmllist ; htmlitem: PROGRAM FILENAME { /*VQSTR(cf->html_tool);*/ } | PROGRAM QSTR { /*VQSTR(cf->html_tool);*/ } | FILE_W FILENAME { /*VQSTR(cf->html_file);*/ } | FILE_W QSTR { /*VQSTR(cf->html_file);*/ } ; modellist: /*Null*/ | modelitem modellist ; modelitem: PROGRAM FILENAME { /*VQSTR(cf->model_tool);*/ } | PROGRAM QSTR { /*VQSTR(cf->model_tool);*/ } | FILE_W FILENAME { /*VQSTR(cf->model_file);*/ } | FILE_W QSTR { /*VQSTR(cf->model_file);*/ } ; sounditem: DIR FILENAME { /*VQSTR(cf->sound_dir);*/ } /*+++LESSONS+++*/ /*Following recursive definition means 'zero to many'*/ lessonlist: /*nil*/ | lesson lessonlist { } ; exerlist: /*nil*/ | exercise exerlist { } ; lesson: LESSON LB title { } desc { } code abstract { } lessonlist exerlist { } RB { } ; exercise: EXERCISE LB title { } desc {} code { } abstract { } filename { } RB { } ; /*Not recursive. Zero or one*/ code: /*Nil*/ { } | CODE QSTR { } ; filename: FILE_W QSTR { } ; %% /**** put your Java methods here ****/ int yylex() { return 1; } /**** end of file ********************************************************/ byaccj1.15/src/yacc.10000755000076500000240000000411407441711567013606 0ustar thurkastaff.\" %W% %R% (Berkeley) %E% .\" .TH YACC 1 "July\ 15,\ 1990" .UC 6 .SH NAME Yacc \- an LALR(1) parser generator .SH SYNOPSIS .B yacc [ -dlrtv ] [ -b .I prefix .B ] .I filename .SH DESCRIPTION .I Yacc reads the grammar specification in the file .I filename and generates an LR(1) parser for it. The parsers consist of a set of LALR(1) parsing tables and a driver routine written in the C programming language. .I Yacc normally writes the parse tables and the driver routine to the file .IR y.tab.c. .PP The following options are available: .RS .TP \fB-b \fIprefix\fR The .B -b option changes the prefix prepended to the output file names to the string denoted by .IR prefix. The default prefix is the character .IR y. .TP .B -d The \fB-d\fR option causes the header file .IR y.tab.h to be written. .TP .B -l If the .B -l option is not specified, .I yacc will insert \#line directives in the generated code. The \#line directives let the C compiler relate errors in the generated code to the user's original code. If the \fB-l\fR option is specified, .I yacc will not insert the \#line directives. \&\#line directives specified by the user will be retained. .TP .B -r The .B -r option causes .I yacc to produce separate files for code and tables. The code file is named .IR y.code.c, and the tables file is named .IR y.tab.c. .TP .B -t The .B -t option changes the preprocessor directives generated by .I yacc so that debugging statements will be incorporated in the compiled code. .TP .B -v The .B -v option causes a human-readable description of the generated parser to be written to the file .IR y.output. .RE .PP If the environment variable TMPDIR is set, the string denoted by TMPDIR will be used as the name of the directory where the temporary files are created. .SH FILES .IR y.code.c .br .IR y.tab.c .br .IR y.tab.h .br .IR y.output .br .IR /tmp/yacc.aXXXXXX .br .IR /tmp/yacc.tXXXXXX .br .IR /tmp/yacc.uXXXXXX .SH DIAGNOSTICS If there are rules that are never reduced, the number of such rules is reported on standard error. If there are any LALR(1) conflicts, the number of conflicts is reported on standard error. byaccj1.15/tarit0000755000076500000240000000036307441711566013065 0ustar thurkastafftar cvf byaccj_src.tar \ src/Makefile src/Makefile.bcc \ src/defs.h src/warshall.c src/verbose.c src/symtab.c src/skeleton.c src/reader.c src/output.c \ src/mkpar.c src/main.c src/lr0.c src/lalr.c src/error.c src/closure.c gzip byaccj_src.tar byaccj1.15/test/0000755000076500000240000000000011112722207012751 5ustar thurkastaffbyaccj1.15/test/bug.y0000755000076500000240000000576407441711573013755 0ustar thurkastaff %{ import java.io.*; import java.util.StringTokenizer; %} %token ITEM %token NAME %token REPLACE %token OVERRIDE %token TERMINATOR %token DONE %type identifier %type mode %start defn %% defn : ITEM identifier mode DONE '\n' { System.out.println( "Item definition" ); System.out.println( " Name = " + $2 ); System.out.println( " mode = " + $3 ); } identifier : NAME { $$ = $1; } mode : /* empty */ { $$ = OVERRIDE; } | REPLACE { $$ = REPLACE; } | OVERRIDE { $$ = OVERRIDE; } ; %% // Code cut from the byacc demo page and modified to take // first arg as input file name String ins; StringTokenizer st; void yyerror(String s) { System.out.println("par:"+s); } boolean newline; int yylex() { String s; int tok; String tokstr; Double d; //System.out.print("yylex "); if (!st.hasMoreTokens()) if (!newline) { newline=true; System.out.println("tok: \\n"); return '\n'; //So we look like classic YACC example } else return 0; s = st.nextToken(); try { if ( s.equalsIgnoreCase("ITEM") ) { tok = ITEM; System.out.println("tok: ITEM"); } else if ( s.equalsIgnoreCase("REPLACE") ) { tok = REPLACE; System.out.println("tok: REPLACE"); } else if ( s.equalsIgnoreCase("DONE") ) { tok = DONE; System.out.println("tok: DONE"); } else if ( s.equalsIgnoreCase("OVERRIDE")) { tok = OVERRIDE; System.out.println("tok: OVERRIDE"); } else { yylval = new parserval( s ); tok = NAME; System.out.println("tok: NAME -> " + s); } } catch ( Throwable e ) { return 0; } return tok; } void dotest( String filepath ) throws java.io.FileNotFoundException { BufferedReader in = new BufferedReader(new FileReader(filepath)); // AS per the calculator demo System.out.println("Note: you will need to separate the items"); System.out.println("with spaces, i.e.: 'ITEM hello override"); while (true) { System.out.print("example item:"); try { ins = in.readLine(); } catch (Exception e) { } st = new StringTokenizer(ins); newline=false; yyparse(); } } public static void main(String args[]) throws java.io.FileNotFoundException { parser par = new parser(); par.yydebug = true; System.out.println( "parse input file: " + args[0] ); par.dotest(args[0]); } // Invoke this code with // java parser test.input // where test.input is the file containing the input text byaccj1.15/test/parser.java0000755000076500000240000004102007441711573015126 0ustar thurkastaff//### This file created by BYACC 1.8(/Java extension 0.92) //### Java capabilities added 7 Jan 97, Bob Jamison //### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten //### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor //### 01 Jun 99 -- Bob Jamison -- added Runnable support //### Please send bug reports to rjamison@lincom-asg.com //### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90"; //#line 3 "bug.y" import java.io.*; import java.util.StringTokenizer; //#line 13 "parser.java" //##################################################################### // class: parser // does : encapsulates yacc() parser functionality in a Java // class for quick code development //##################################################################### public class parser { boolean yydebug; //do I want debug output? int yynerrs; //number of errors so far int yyerrflag; //was there an error? int yychar; //the current working character //########## MESSAGES ########## //############################################################### // method: debug //############################################################### void debug(String msg) { if (yydebug) System.out.println(msg); } //########## STATE STACK ########## final static int YYSTACKSIZE = 500; //maximum stack size int statestk[],stateptr; //state stack //############################################################### // methods: state stack push,pop,drop,peek //############################################################### void state_push(int state) { if (stateptr>=YYSTACKSIZE) //overflowed? return; statestk[++stateptr]=state; } int state_pop() { if (stateptr<0) //underflowed? return -1; return statestk[stateptr--]; } void state_drop(int cnt) { int ptr; ptr=stateptr-cnt; if (ptr<0) return; stateptr = ptr; } int state_peek(int relative) { int ptr; ptr=stateptr-relative; if (ptr<0) return -1; return statestk[ptr]; } //############################################################### // method: init_stacks : allocate and prepare stacks //############################################################### boolean init_stacks() { statestk = new int[YYSTACKSIZE]; stateptr = -1; val_init(); return true; } //############################################################### // method: dump_stacks : show n levels of the stacks //############################################################### void dump_stacks(int count) { int i; System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr); for (i=0;i=YYSTACKSIZE) return; valstk[++valptr]=val; } parserval val_pop() { if (valptr<0) return new parserval(-1); return valstk[valptr--]; } void val_drop(int cnt) { int ptr; ptr=valptr-cnt; if (ptr<0) return; valptr = ptr; } parserval val_peek(int relative) { int ptr; ptr=valptr-relative; if (ptr<0) return new parserval(-1); return valstk[ptr]; } //#### end semantic value section #### public final static short ITEM=257; public final static short NAME=258; public final static short REPLACE=259; public final static short OVERRIDE=260; public final static short TERMINATOR=261; public final static short DONE=262; public final static short YYERRCODE=256; final static short yylhs[] = { -1, 0, 1, 2, 2, 2, }; final static short yylen[] = { 2, 5, 1, 0, 1, 1, }; final static short yydefred[] = { 0, 0, 0, 2, 0, 4, 5, 0, 0, 1, }; final static short yydgoto[] = { 2, 4, 7, }; final static short yysindex[] = { -255, -254, 0, 0, -259, 0, 0, -257, -7, 0, }; final static short yyrindex[] = { 0, 0, 0, 0, -256, 0, 0, 0, 0, 0, }; final static short yygindex[] = { 0, 0, 0, }; final static int YYTABLESIZE=6; final static short yytable[] = { 5, 6, 1, 9, 3, 8, 3, }; final static short yycheck[] = { 259, 260, 257, 10, 258, 262, 262, }; final static short YYFINAL=2; final static short YYMAXTOKEN=262; final static String yyname[] = { "end-of-file",null,null,null,null,null,null,null,null,null,"'\\n'",null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,"ITEM","NAME","REPLACE","OVERRIDE","TERMINATOR","DONE", }; final static String yyrule[] = { "$accept : defn", "defn : ITEM identifier mode DONE '\\n'", "identifier : NAME", "mode :", "mode : REPLACE", "mode : OVERRIDE", }; //#line 37 "bug.y" // Code cut from the byacc demo page and modified to take // first arg as input file name String ins; StringTokenizer st; void yyerror(String s) { System.out.println("par:"+s); } boolean newline; int yylex() { String s; int tok; String tokstr; Double d; //System.out.print("yylex "); if (!st.hasMoreTokens()) if (!newline) { newline=true; System.out.println("tok: \\n"); return '\n'; //So we look like classic YACC example } else return 0; s = st.nextToken(); try { if ( s.equalsIgnoreCase("ITEM") ) { tok = ITEM; System.out.println("tok: ITEM"); } else if ( s.equalsIgnoreCase("REPLACE") ) { tok = REPLACE; System.out.println("tok: REPLACE"); } else if ( s.equalsIgnoreCase("DONE") ) { tok = DONE; System.out.println("tok: DONE"); } else if ( s.equalsIgnoreCase("OVERRIDE")) { tok = OVERRIDE; System.out.println("tok: OVERRIDE"); } else { yylval = new parserval( s ); tok = NAME; System.out.println("tok: NAME -> " + s); } } catch ( Throwable e ) { return 0; } return tok; } void dotest( String filepath ) throws java.io.FileNotFoundException { BufferedReader in = new BufferedReader(new FileReader(filepath)); // AS per the calculator demo System.out.println("Note: you will need to separate the items"); System.out.println("with spaces, i.e.: 'ITEM hello override"); while (true) { System.out.print("example item:"); try { ins = in.readLine(); } catch (Exception e) { } st = new StringTokenizer(ins); newline=false; yyparse(); } } public static void main(String args[]) throws java.io.FileNotFoundException { parser par = new parser(); par.yydebug = true; System.out.println( "parse input file: " + args[0] ); par.dotest(args[0]); } // Invoke this code with // java parser test.input // where test.input is the file containing the input text //#line 277 "parser.java" //############################################################### // method: yylexdebug : check lexer state //############################################################### void yylexdebug(int state,int ch) { String s=null; if (ch < 0) ch=0; if (ch <= YYMAXTOKEN) //check index bounds s = yyname[ch]; //now get it if (s==null) s = "illegal-symbol"; debug("state "+state+", reading "+ch+" ("+s+")"); } //############################################################### // method: yyparse : parse input and execute indicated items //############################################################### int yyparse() { int yyn; //next next thing to do int yym; // int yystate; //current parsing state from state table String yys; //current token string boolean doaction; init_stacks(); yynerrs = 0; yyerrflag = 0; yychar = -1; //impossible char forces a read yystate=0; //initial state state_push(yystate); //save it while (true) //until parsing is done, either correctly, or w/error { doaction=true; if (yydebug) debug("loop"); //#### NEXT ACTION (from reduction table) for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate]) { if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" char:"+yychar); if (yychar < 0) //we want a char? { yychar = yylex(); //get next token //#### ERROR CHECK #### if (yychar < 0) //it it didn't work/error { yychar = 0; //change it to default string (no -1!) if (yydebug) yylexdebug(yystate,yychar); } }//yychar<0 yyn = yysindex[yystate]; //get amount to shift by (shift index) if ((yyn != 0) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { if (yydebug) debug("state "+yystate+", shifting to state "+yytable[yyn]+""); //#### NEXT STATE #### yystate = yytable[yyn];//we are in a new state state_push(yystate); //save it val_push(yylval); //push our lval as the input for next rule yychar = -1; //since we have 'eaten' a token, say we need another if (yyerrflag > 0) //have we recovered an error? --yyerrflag; //give ourselves credit doaction=false; //but don't process yet break; //quit the yyn=0 loop } yyn = yyrindex[yystate]; //reduce if ((yyn !=0 ) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { //we reduced! if (yydebug) debug("reduce"); yyn = yytable[yyn]; doaction=true; //get ready to execute break; //drop down to actions } else //ERROR RECOVERY { if (yyerrflag==0) { yyerror("syntax error"); yynerrs++; } if (yyerrflag < 3) //low error count? { yyerrflag = 3; while (true) //do until break { if (stateptr<0) //check for under & overflow here { yyerror("stack underflow. aborting..."); //note lower case 's' return 1; } yyn = yysindex[state_peek(0)]; if ((yyn != 0) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { if (yydebug) debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" "); yystate = yytable[yyn]; state_push(yystate); val_push(yylval); doaction=false; break; } else { if (yydebug) debug("error recovery discarding state "+state_peek(0)+" "); if (stateptr<0) //check for under & overflow here { yyerror("Stack underflow. aborting..."); //capital 'S' return 1; } state_pop(); val_pop(); } } } else //discard this token { if (yychar == 0) return 1; //yyabort if (yydebug) { yys = null; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (yys == null) yys = "illegal-symbol"; debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")"); } yychar = -1; //read another } }//end error recovery }//yyn=0 loop if (!doaction) //any reason not to proceed? continue; //skip action yym = yylen[yyn]; //get count of terminals on rhs if (yydebug) debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")"); if (yym>0) //if count of rhs not 'nil' yyval = val_peek(yym-1); //get current semantic value switch(yyn) { //########## USER-SUPPLIED ACTIONS ########## case 1: //#line 23 "bug.y" { System.out.println( "Item definition" ); System.out.println( " Name = " + val_peek(3).sval ); System.out.println( " mode = " + val_peek(2).ival ); } break; case 2: //#line 29 "bug.y" { yyval.sval = val_peek(0).sval; } break; case 3: //#line 31 "bug.y" { yyval.ival = OVERRIDE; } break; case 4: //#line 32 "bug.y" { yyval.ival = REPLACE; } break; case 5: //#line 33 "bug.y" { yyval.ival = OVERRIDE; } break; //#line 444 "parser.java" //########## END OF USER-SUPPLIED ACTIONS ########## }//switch //#### Now let's reduce... #### if (yydebug) debug("reduce"); state_drop(yym); //we just reduced yylen states yystate = state_peek(0); //get new state val_drop(yym); //corresponding value drop yym = yylhs[yyn]; //select next TERMINAL(on lhs) if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL { debug("After reduction, shifting from state 0 to state "+YYFINAL+""); yystate = YYFINAL; //explicitly say we're done state_push(YYFINAL); //and save it val_push(yyval); //also save the semantic value of parsing if (yychar < 0) //we want another character? { yychar = yylex(); //get next character if (yychar<0) yychar=0; //clean, if necessary if (yydebug) yylexdebug(yystate,yychar); } if (yychar == 0) //Good exit (if lex returns 0 ;-) break; //quit the loop--all DONE }//if yystate else //else not done yet { //get next state and push, for next yydefred[] yyn = yygindex[yym]; //find out where to go if ((yyn != 0) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; //get new state else yystate = yydgoto[yym]; //else go to new defred debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+""); state_push(yystate); //going again, so push state & val... val_push(yyval); //for next action } }//main loop return 0;//yyaccept!! } //## end of method parse() ###################################### } //################### END OF CLASS yaccpar ###################### byaccj1.15/test/parserval.java0000755000076500000240000000054607441711573015641 0ustar thurkastaff //########## SEMANTIC VALUES ########## public class parserval { public int ival; public double dval; public String sval; public Object obj; public parserval(int val) { ival=val; } public parserval(double val) { dval=val; } public parserval(String val) { sval=val; } public parserval(Object val) { obj=val; } }//end class byaccj1.15/test/test.input0000755000076500000240000000015607441711573015034 0ustar thurkastaffITEM thisisok OVERRIDE DONE ITEM thisisoktoo REPLACE DONE ITEM thisisnt DONE ITEM thisis REPLACE DONE