JAVACC 實作四則運算
Simple.JJ檔案
options
{
STATIC = false;
DEBUG_PARSER = true;
}
PARSER_BEGIN(Simple)
package cn.com.XXX.test.simple4;
public class Simple
{
public static void main(String [] args) throws ParseException, TokenMgrError
{
Simple parser = new Simple(System.in);
System.out.println(parser.start());
}
}
PARSER_END(Simple)
SKIP :
{
" "
}
SKIP :
{
"\n"
| "\r"
| "\r\n"
}
TOKEN :
{
< PLUS : "+" >
| < MINUS : "-" >
| < TIMES : "*" >
| < DIVES : "/" >
}
TOKEN :
{
< NUMBER : ([ "0"-"9" ])+ >
}
TOKEN :
{
< END : "=" >
}
// start --> expression()< EOF>
// expression --> term() ( + term() | - term() )
// term() --> primite() ( * primite() | / primite() )
// primite() --> < NUMBER>
int start():
{
int rtn = 0;
}
{
rtn = term()< END>
{
return rtn;
}
}
int expression () :
{
int value1 = 0;
int value2 = 0;
}
{
value1 = term()
(
< PLUS> value2 = term() {value1 = value1+value2; }
|
<MINUS> value2 = term() { value1 = value1 - value2; }
)*
{
return value1;
}
}
int term() :
{
int value1 = 0;
int value2;
}
{
value1 = primite()
(
< TIMES> value2 = primite() {value1 = value1* value2; }
| < DIVES> value2 = primite() {value1 = value1 / value2;}
)*
{
return value1;
}
}
int primite():
{
Token t;
int sum = 0;
}
{
t= < NUMBER > { return Integer.parseInt(t.image);}
| "(" sum = expression() { return sum;} ")"
}
幾年前為做示範,現場寫的一個簡單的四則運算,當然存在很多瑕疵,但隻是用來展現使用方式足夠了。
今天無意中發現了,感覺都有點生疏了,記錄一下。