/* * This is the basic expression grammar for four function * Expressions. The grammar support the plus (+), minus (-) * multiply (*), and divide (/) operations. * * See Calc1i.jack for a grammar that parses and implements * the functions. * * Example grammar written 11/1/96 by Chuck McManis (cmcmanis@netcom.com) */ options { LOOKAHEAD=1; } PARSER_BEGIN(Calc1) public class Calc1 { public static void main(String args[]) throws ParseError { Calc1 parser = new Calc1(System.in); while (true) { System.out.print("Enter Expression: "); System.out.flush(); try { switch (parser.one_line()) { case -1: System.exit(0); default: break; } } catch (ParseError x) { System.out.println("Exiting."); throw x; } } } } PARSER_END(Calc1) 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() : { } { term() (( | ) term())* } void term() : { } { unary() (( | ) unary())* } void unary() : { } { element() | element() } void element() : {} { | "(" sum() ")" }