/* In this parser spec, we use an unambiguous LALR(1) grammar */ import java_cup.runtime.*; import java.io.*; parser code {: String intext; Yylex scanner; :}; init with {: try { BufferedReader lineinput = new BufferedReader(new InputStreamReader(System.in)); intext = lineinput.readLine(); } catch (Exception ee) {} scanner = new Yylex(new StringReader(intext)); :}; scan with {: return scanner.next_token(); :}; /* grammar symbols and associated semantic value */ terminal PLUS, MINUS, TIMES, DIVIDE, LPAREN, RPAREN, DOT; terminal Double NUM; non terminal Double Line; non terminal Double Ex; non terminal Double Tx; non terminal Double Fx; /* grammar production rules */ Line ::= Ex:v1 {: RESULT = v1; System.out.println("Result = "+v1); :}; Ex ::= Ex:v1 PLUS Tx:v2 {: RESULT = (double)v1 + (double)v2; :} | Ex:v1 MINUS Tx:v2 {: RESULT = (double)v1 - (double)v2; :} | Tx:v1 {: RESULT = v1; :}; Tx ::= Tx:v1 TIMES Fx:v2 {: RESULT = (double)v1 * (double)v2; :} | Tx:v1 DIVIDE Fx:v2 {: if ((double)v2 == 0) throw new Error("watch division by zero you bonehead!"); else RESULT = (double)v1 / (double)v2; :} | Fx:v1 {: RESULT = v1; :}; Fx ::= LPAREN Ex:v1 RPAREN {: RESULT = v1; :} | NUM:v1 {: RESULT = v1; :};