/* * This is the first modification to the basic expression grammar. * There are two changes, first the type of 'constant' supported is * now a floating point number. This definition for the Token CONSTANT * Gained a few levels of complexity, but they are still pretty straight * forward. The second change was that we added a 'right associative' * operator, exponentiation. This operator is '**' () and the * right associtivity is expressed using a right-recursive grammar * specification. The LOOKAHEAD specification tells Jack to look ahead * for an token, otherwise the right match won't be taken. * * The grammar now supports the plus (+), minus (-) * multiply (*), divide (/) and exponentiation operations. * * See Calc2i.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(Calc2) public class Calc2 { public static void main(String args[]) throws ParseError { Calc2 parser = new Calc2(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(Calc2) IGNORE_IN_BNF : {} { " " | "\r" | "\t" } TOKEN : { } { < EOL: "\n" > } TOKEN : /* OPERATORS */ { } { < PLUS: "+" > | < MINUS: "-" > | < MULTIPLY: "*" > | < DIVIDE: "/" > | } TOKEN : { } { < CONSTANT: | ( ["e","E"] ([ "-","+"])? )? > | < #FLOAT: | ( "." )? | "." > | < #INTEGER: ( )+ > | < #DIGIT: ["0" - "9"] > } int one_line() : {} { sum() { return 1; } | { return 0; } | { return -1; } } void sum() : { } { term() (( | ) term())* } void term() : { } { exp() (( | ) exp())* } void exp() : { } { unary() ( LOOKAHEAD( ) exp() )* } void unary() : { } { element() | element() } void element() : {} { | "(" sum() ")" }