PARSER_BEGIN(calc)
public class calc {
public static void main(String args[]) throws ParseException {
int result;
calc parser = new calc(System.in);
result = parser.complete_expression();
System.out.println("Expression value = " + result);
}
}
PARSER_END(calc)
SKIP :
{
" "
}
TOKEN :
{
< INTEGER_LITERAL: (["0"-"9"])+ >
| < PLUS: "+" >
| < MINUS: "-" >
| < MULTIPLY: "*">
| < DIVIDE: "/" >
| < LPAREN: "(" >
| < RPAREN: ")" >
| < EOL: "\n" >
}
int complete_expression():
{ int result; }
{
result = expression() <EOL> { return result; }
}
int expression():
{Token t; int result; int rhs;}
{
result = term() ((t = <PLUS> |t = <MINUS>) rhs = term()
{ if (t.kind == PLUS)
result = result + rhs;
else
result = result - rhs;
}
)* { return result; }
}
int term():
{Token t; int result; int rhs;}
{
result = factor() ( (t = <MULTIPLY> | t = <DIVIDE>) rhs = factor()
{ if (t.kind == MULTIPLY)
result = result * rhs;
else
result = result / rhs;
}
)*
{ return result; }
}
int factor():
{int value; Token t;}
{
<MINUS> value = factor() { return 0 - value; }
| t = <INTEGER_LITERAL> { return Integer.parseInt(t.image); }
| <LPAREN> value = expression() <RPAREN> { return value; }
}