%{ import java.io.*; import java.util.*; /* All of the below productions that do not have associated actions are using the DEFAULT action -- $$ = $1 */ %} %token PLUS TIMES CR RPAREN LPAREN EQUAL %token ID %token INT %type term expr factor %% lines : lines line | line ; line : expr CR {System.out.println("= " + $1+ "\n"); } | ID EQUAL expr CR { assign($1,$3); } ; expr : expr PLUS term {$$= $1+ $3; } | term ; term : term TIMES factor {$$= $1* $3; } | factor ; factor : LPAREN expr RPAREN {$$ = $2;} | INT | ID {$$ = lookup($1); } %% /* Byacc/J expects a member method int yylex(). We need to provide one through this mechanism. See the jflex manual for more information. */ /* reference to the lexer object */ private scanner lexer; /* A simple symbol table */ private HashMap symbol_table = new HashMap(); /* interface to the lexer */ private int yylex() { int retVal = -1; try { retVal = lexer.yylex(); } catch (IOException e) { System.err.println("IO Error:" + e); } return retVal; } /* error reporting */ public void yyerror (String error) { System.err.println("Error : " + error + " at line " + lexer.getLine()); } /* constructor taking in File Input */ public Parser (Reader r) { lexer = new scanner (r, this); } /* this method stores an id on the symbol table with its associated value */ public void assign (String id, int value) { symbol_table.put (id, new Integer(value)); } public int lookup (String id) { return ((Integer)symbol_table.get(id)).intValue(); } public static void main (String [] args) throws IOException { Parser yyparser = new Parser(new FileReader(args[0])); yyparser.yyparse(); }