%{ import java.io.InputStreamReader; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Vector; import ck.Node; /** recognizes, stores, and evaluates arithmetic expressions using a parser generated with jay. */ public class Expression { /** reads lines from standard input, parses, and evaluates them or writes them as a Vector to standard output if -c is set. @param args if -c is specified, a Vector is written, if 0..3 is specified, there is animation, if something else is specified, there is a trace. */ public static void main (String args []) { boolean cflag = false; jay.yydebug.yyDebug debug = null; if (args != null && args.length > 0) { int a = 0; if (args[0].equals("-c")) { ++ a; cflag = true; } if (a < args.length) try { debug = new jay.yydebug.yyAnim("Anim", Integer.parseInt(args[a])); } catch (NumberFormatException e) { debug = new jay.yydebug.yyDebugAdapter(); } } try { Vector v = (Vector)new Expression() .yyparse(new Scanner(new InputStreamReader(System.in)), debug); if (v != null) if (cflag) { ObjectOutputStream out = new ObjectOutputStream(System.out); out.writeObject(v); out.close(); } else for (int n = 0; n < v.size(); ++ n) System.out.println(((Number)v.elementAt(n)).floatValue()); } catch (IOException e) { System.err.println(e); } catch (yyException e) { System.err.println(e); } } %} %token Constant %type lines %type sum, product, term %% lines : /* null */ { $$ = new Vector(); } | lines sum '\n' { $1.addElement($2); } | lines '\n' // $$ = $1 | lines error '\n' // $$ = $1 sum : product // $$ = $1 | sum '+' product { $$ = new Node.Add($1, $3); } | sum '-' product { $$ = new Node.Sub($1, $3); } product : term // $$ = $1 | product '*' term { $$ = new Node.Mul($1, $3); } | product '/' term { $$ = new Node.Div($1, $3); } | product '%' term { $$ = new Node.Mod($1, $3); } term : '+' term { $$ = $2; } | '-' term { $$ = new Node.Minus($2); } | '(' sum ')' { $$ = $2; } | Constant // $$ = $1 %% }