/* CalcParser.java Implementes a simple expression language parser Uses java.io.StreamTokenizer and recursive descent parsing Compile: javac CalcParser.java Execute: java CalcParser */ import java.io.*; public class CalcParser { private static StreamTokenizer tokens; private static int ahead; public static void main(String argv[]) throws IOException { FileInputStream stream = new FileInputStream(argv[0]); InputStreamReader reader = new InputStreamReader(stream); tokens = new StreamTokenizer(reader); tokens.ordinaryChar('.'); tokens.ordinaryChar('-'); tokens.ordinaryChar('/'); get(); expr(); if (ahead == (int)'$') System.out.println("Syntax ok"); else System.out.println("Syntax error"); stream.close(); } private static void get() throws IOException { ahead = tokens.nextToken(); } private static void expr() throws IOException { term(); term_tail(); } private static void term_tail() throws IOException { if (ahead == (int)'+' || ahead == (int)'-') { add_op(); term(); term_tail(); } } private static void term() throws IOException { factor(); factor_tail(); } private static void factor_tail() throws IOException { if (ahead == (int)'*' || ahead == (int)'/') { mult_op(); factor(); factor_tail(); } } private static void factor() throws IOException { if (ahead == (int)'(') { get(); expr(); if (ahead == (int)')') get(); else System.out.println("closing ) expected"); } else if (ahead == (int)'-') { get(); factor(); } else if (ahead == tokens.TT_WORD) get(); else if (ahead == tokens.TT_NUMBER) get(); else System.out.println("factor expected"); } private static void add_op() throws IOException { if (ahead == (int)'+' || ahead == (int)'-') get(); } private static void mult_op() throws IOException { if (ahead == (int)'*' || ahead == (int)'/') get(); } }