/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2001 Gerwin Klein * * All rights reserved. * * * * This is a modified version of the example from * * http://www.lincom-asg.com/~rjamison/byacc/ * * * * Thanks to Larry Bell and Bob Jamison for suggestions and comments. * * * * License: BSD * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ %{ import java.io.*; %} %token NL /* newline */ %token NUM /* a number as a string */ %token PLUS MINUS TIMES DIV /* operators */ %token LPAR RPAR /* parethesis */ %type exp %left MINUS PLUS %left TIMES DIV %left NEG /* negation--unary minus */ %type line %start line %% line: exp { strExp=$1; $$=$1; } ; exp: NUM { $$ = $1; } | exp PLUS exp { $$ = "(add "+$1+" "+$3+")"; } | exp MINUS exp { $$ = "(sub "+$1+" "+$3+")"; } | exp TIMES exp { $$ = "(mul "+$1+" "+$3+")"; } | exp DIV exp { $$ = "(div "+$1+" "+$3+")"; } | MINUS exp %prec NEG { $$ = "-"+$2; } | LPAR exp RPAR { $$ = $2; } ; %% public String strExp; private Yylex lexer; private int yylex () { int yyl_return = -1; try { yylval = new ParserVal(0); yyl_return = lexer.yylex(); } catch (IOException e) { System.err.println("IO error :"+e); } return yyl_return; } public void yyerror (String error) { System.err.println ("Error: " + error); } public Parser(Reader r) { lexer = new Yylex(r, this); } /* public static void main(String args[]) throws IOException { //System.out.println("BYACC/Java with JFlex Calculator Demo"); Parser yyparser; yyparser = new Parser(new InputStreamReader(System.in)); yyparser.yyparse(); } */