import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.Reader; import java.util.Vector; import java_cup.runtime.Symbol; import ck.Node; parser code {: /** lexical analyzer. */ protected Scanner scanner; /** creates a parser and a scanner. */ public Expression (Reader in) { scanner = new Scanner(in); } /** 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. */ public static void main (String args []) { boolean cflag = args.length > 0 && args[0].equals("-c"); try { Symbol s = new Expression(new InputStreamReader(System.in)).parse(); if (s != null && s.value != null) if (cflag) { ObjectOutputStream out = new ObjectOutputStream(System.out); out.writeObject(s.value); out.close(); } else for (int n = 0; n < ((Vector)s.value).size(); ++ n) System.out.println(((Number)((Vector)s.value).elementAt(n)) .floatValue()); } catch (Exception e) { System.err.println(e); } } :}; scan with {: return scanner.token(); :}; terminal NL, ADD, SUB, MUL, DIV, MOD, LPAR, RPAR; terminal Number CONSTANT; non terminal Number sum, product, term; non terminal Vector lines; lines ::= /* null */ {: RESULT = new Vector(); :} | lines:l sum:s NL {: l.addElement(s); RESULT = l; :} | lines:l NL {: RESULT = l; :} | lines:l error NL {: RESULT = l; :} ; sum ::= product:p {: RESULT = p; :} | sum:s ADD product:p {: RESULT = new Node.Add(s, p); :} | sum:s SUB product:p {: RESULT = new Node.Sub(s, p); :} ; product ::= term:t {: RESULT = t; :} | product:p MUL term:t {: RESULT = new Node.Mul(p, t); :} | product:p DIV term:t {: RESULT = new Node.Div(p, t); :} | product:p MOD term:t {: RESULT = new Node.Mod(p, t); :} ; term ::= ADD term:t {: RESULT = t; :} | SUB term:t {: RESULT = new Node.Minus(t); :} | LPAR sum:s RPAR {: RESULT = s; :} | CONSTANT:c {: RESULT = c; :} ;