import java.io.*; import AST; public class CalcAST { private static StreamTokenizer tokens; private static int ahead; public static void main(String argv[]) throws IOException { InputStreamReader reader = new InputStreamReader(System.in); tokens = new StreamTokenizer(reader); tokens.ordinaryChar('.'); tokens.ordinaryChar('-'); tokens.ordinaryChar('/'); get(); AST ast = expr(); if (ahead == (int)'$') ast.toLisp(); else System.out.println("Syntax error"); } private static void get() throws IOException { ahead = tokens.nextToken(); } private static AST expr() throws IOException { AST subtotal = term(); return term_tail(subtotal); } private static AST term_tail(AST subtotal) throws IOException { if (ahead == (int)'+') { get(); AST termvalue = term(); return term_tail(new AST('+', subtotal, termvalue)); } else if (ahead == (int)'-') { get(); AST termvalue = term(); return term_tail(new AST('-', subtotal, termvalue)); } else return subtotal; } private static AST term() throws IOException { AST subtotal = factor(); return factor_tail(subtotal); } private static AST factor_tail(AST subtotal) throws IOException { if (ahead == (int)'*') { get(); AST factorvalue = factor(); return factor_tail(new AST('*', subtotal, factorvalue)); } else if (ahead == (int)'/') { get(); AST factorvalue = factor(); return factor_tail(new AST('/', subtotal, factorvalue)); } else return subtotal; } private static AST factor() throws IOException { if (ahead == (int)'(') { get(); AST ast = expr(); if (ahead == (int)')') get(); else System.out.println("closing ) expected"); return ast; } else if (ahead == (int)'-') { get(); return new AST('%', factor()); } else if (ahead == tokens.TT_WORD) { get(); return new AST(0); } else if (ahead == tokens.TT_NUMBER) { get(); return new AST((int)tokens.nval); } else { System.out.println("factor expected"); return new AST(0); } } }