/* * This is the basic expression grammar for four function * Expressions. The grammar support the plus (+), minus (-) * multiply (*), and divide (/) operations. * * See Calc1.jack for the bare grammar (without embedded Java code) * * Example grammar written 11/1/96 by Chuck McManis (cmcmanis@netcom.com) */ options { LOOKAHEAD=1; } PARSER_BEGIN(Calc1i) public class Calc1i { static int total; static java.util.Stack argStack = new java.util.Stack(); public static void main(String args[]) throws ParseError { Calc1i parser = new Calc1i(System.in); while (true) { System.out.print("Enter Expression: "); System.out.flush(); try { switch (parser.one_line()) { case -1: System.exit(0); case 0: break; case 1: int x = ((Integer) argStack.pop()).intValue(); System.out.println("Total = " + x); break; } } catch (ParseError x) { System.out.println("Exiting."); throw x; } } } } PARSER_END(Calc1i) IGNORE_IN_BNF : {} { " " | "\r" | "\t" } TOKEN : { } { < EOL: "\n" > } TOKEN : /* OPERATORS */ { } { < PLUS: "+" > | < MINUS: "-" > | < MULTIPLY: "*" > | < DIVIDE: "/" > } TOKEN : { } { < CONSTANT: ( )+ > | < #DIGIT: ["0" - "9"] > } int one_line() : {} { sum() { return 1; } | { return 0; } | { return -1; } } void sum() : {Token x;} { term() ( ( x = | x = ) term() { int a = ((Integer) argStack.pop()).intValue(); int b = ((Integer) argStack.pop()).intValue(); if ( x.kind == PLUS ) argStack.push(new Integer(b + a)); else argStack.push(new Integer(b - a)); } )* } void term() : {Token x;} { unary() ( ( x = | x = ) unary() { int a = ((Integer) argStack.pop()).intValue(); int b = ((Integer) argStack.pop()).intValue(); if ( x.kind == MULTIPLY ) argStack.push(new Integer(b * a)); else argStack.push(new Integer(b / a)); } )* } void unary() : { } { element() { int a = ((Integer) argStack.pop()).intValue(); argStack.push(new Integer(- a)); } | element() } void element() : {} { { try { int x = Integer.parseInt(token.image); argStack.push(new Integer(x)); } catch (NumberFormatException ee) { argStack.push(new Integer(0)); } } | "(" sum() ")" }