JavaCC简单试用

 JavaCC是一个一个java版的语法分析生成器,根据具体内容请参考官网,另:JavaCC本身只支持自顶向下,但通过JJTree,可以实现自底向上。下面是我利用LL语法实现四则运算的简单试用:

1、Cal.jj文件:

options {
 STATIC = false;
}
PARSER_BEGIN(MyCalc)
import java.io.StringReader;

public class MyCalc {

  public static void main(String args[]) {    
    try {
      MyCalc parser = new MyCalc(new StringReader("1+2*3/2"));
      System.out.println(parser.exp());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

PARSER_END(MyCalc)

SKIP :
{
  " "|"\t"|"\n"|"\r"
}

TOKEN :
{
  <ADD: "+">
| <SUB: "-">
| <MUL: "*">
| <DIV: "/">
| <LBRACE: "(">
| <RBRACE: ")">
| <NUMBER: (["0"-"9"])+>
  
}

int exp() :
{
  int temp;
  int v1;
  int v2;
}
{
  v1 = term(){temp = v1;}
  (<ADD>v2 = term(){temp = v1+v2;}
  |<SUB>v2 = term(){temp = v1-v2;})*<EOF>
  {return temp;}
}

int term() :
{
  int temp;
  int v1;
  int v2;
}
{
  v1 = factor(){temp = v1;}
  (<MUL>v2 = factor(){temp = v1*v2;}
  |<DIV>v2 = factor(){temp = v1/v2;})*
  {return temp;}
}

int factor() :
{
  int temp;
  Token token;
}
{
  (token = <NUMBER>{temp = Integer.parseInt(token.image);}
  |<LBRACE>temp = exp()<RBRACE>)
  {return temp;}
}

   

2、通过JavaCC命令生成相关文件:

E:\jdev\jxls\javacc-4.2\examples\SimpleExamples>javacc Cal.jj
Java Compiler Compiler Version 4.2 (Parser Generator)
(type "javacc" with no arguments for help)
Reading from file Cal.jj . . .
File "TokenMgrError.java" does not exist.  Will create one.
File "ParseException.java" does not exist.  Will create one.
File "Token.java" does not exist.  Will create one.
File "SimpleCharStream.java" does not exist.  Will create one.
Parser generated successfully.

 上面命令生成了如下7个JAVA文件:

E:\jdev\jxls\javacc-4.2\examples\SimpleExamples>ls *.java
MyCalc.java           MyCalcTokenManager.java  SimpleCharStream.java  TokenMgrError.java
MyCalcConstants.java  ParseException.java      Token.java

 

 

3、运行:

如果test.txt中的内容为“1+2*(3-4/2)”,则得到“3”,

如果test.txt中的内容为“1+2*3/2”,则也得到“3”。

 

4、相关说明:

由于采用的是自顶向下,所以上面的四则运算只是DEMO性质的,并不具有实用价值,如“1+2*3/2”得到的计算结果就是“3”,这显然错误,这也是LL语法的缺陷。

 

你可能感兴趣的:(java)