/* * In this second modification to the Calc grammar, we now add * "Identifiers" to the token list so that we can parse functions. * Functions are specified in the function() production. * * Further, we've added some logical operations, &, |, and ^ to the * existing mathematical ones. * * The grammar now supports the plus (+), minus (-) * multiply (*), divide (/) and exponentiation operations. * * See Calc3i.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(Calc3) public class Calc3 { public static void main(String args[]) throws ParseError { Calc3 parser = new Calc3(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(Calc3) IGNORE_IN_BNF : {} { " " | "\r" | "\t" } TOKEN : { } { < EOL: "\n" > } TOKEN : /* OPERATORS */ { } { < PLUS: "+" > | < MINUS: "-" > | < MULTIPLY: "*" > | < DIVIDE: "/" > | < EXP: "**" > | < AND: "&" > | < OR: "|" > | < XOR: "^" > } TOKEN : /* Numeric Constants */ { } { < CONSTANT: | ( ["e","E"] ([ "-","+"])? )? > | < #FLOAT: | ( "." )? | "." > | < #INTEGER: ( )+ > | < #DIGIT: ["0" - "9"] > } TOKEN : /* Function names */ { } { < ID: ( )+ ( | )* > | < #LETTER: ["a"-"z", "A"-"Z"] > } int one_line() : {} { logical() { return 1; } | { return 0; } | { return -1; } } void logical() : { } { sum() (( | | ) sum())* } void sum() : { } { term() (( | ) term())* } void term() : { } { exp() (( | ) exp())* } void exp() : { } { unary() ( LOOKAHEAD( ) exp() )* } void unary() : { } { element() | element() } void element() : {} { | function() | "(" logical() ")" } void function() : { } { "(" [ logical() ( "," logical() )* ] ")" }