ANTLR4:布尔表达式的解析器
我正在尝试解析以下类型的布尔表达式 B1=p&A4=p | A6=p&(~A5=c) 我想要一棵树,我可以用它来计算上面的表达式。所以我在Antlr3中尝试了这个方法,并在 它在Antlr3中起作用。现在我想对Antlr 4做同样的事情。我找到了下面的语法,并进行了编译。但是我在编写Java代码时遇到了困难 Antlr4语法的开始ANTLR4:布尔表达式的解析器,antlr4,Antlr4,我正在尝试解析以下类型的布尔表达式 B1=p&A4=p | A6=p&(~A5=c) 我想要一棵树,我可以用它来计算上面的表达式。所以我在Antlr3中尝试了这个方法,并在 它在Antlr3中起作用。现在我想对Antlr 4做同样的事情。我找到了下面的语法,并进行了编译。但是我在编写Java代码时遇到了困难 Antlr4语法的开始 我已经编写了Java代码(下面的代码片段),用于获取表达式“B1=p&A4=p | A6=p&(~A5=c)”的树。我期待着&和孩子们B1=p和|。子运算符将有子A
我已经编写了Java代码(下面的代码片段),用于获取表达式“B1=p&A4=p | A6=p&(~A5=c)”的树。我期待着&和孩子们B1=p和|。子运算符将有子A4=p和A6=p&(~A5=c)。等等 这是Java代码,但我一直在试图弄清楚如何获得树。我在Antlr 3中能够做到这一点 Java代码 下面是get Children方法。但这似乎并没有提取任何代币
public void getChildren(ParseTree tree, TestAntlr4Parser parser ) {
for (int i=0; i<tree.getChildCount(); i++){
System.out.println(" Child i= " + i);
System.out.println(" expression = <" + tree.toStringTree(parser) + ">");
if ( tree.getChild(i).getChildCount() != 0 ) {
this.getChildren(tree.getChild(i), parser);
}
}
}
public void getChildren(ParseTree树,TestAntlr4Parser解析器){
对于(int i=0;i,ANTLR 4中删除了output=AST
选项,以及语法中使用的^
和!
运算符。ANTLR 4生成解析树而不是AST,因此规则生成的树的根是规则本身。例如,给定以下规则:
and : not (AND not)*;
您将得到一个和context
树,其中分别包含NotContext
和TerminalNode
子节点,用于not
和引用。为了更容易使用这些树,和context
将包含一个生成的方法not()
返回通过调用not
规则返回的上下文对象列表(返回类型list我对ANTLR不熟悉,我仍在试图找出如何获取表达式B1=p&A4=p中的节点。我需要结果B1=p,另一个子节点为A4=p,以便对其求值。请您进一步解释我如何使用一些代码打印节点。@AshwiniBhandary,我不需要手动遍历树,而是建议您使用ANTLR4的内置功能来执行此操作。请参阅:或
public void getChildren(ParseTree tree, TestAntlr4Parser parser ) {
for (int i=0; i<tree.getChildCount(); i++){
System.out.println(" Child i= " + i);
System.out.println(" expression = <" + tree.toStringTree(parser) + ">");
if ( tree.getChild(i).getChildCount() != 0 ) {
this.getChildren(tree.getChild(i), parser);
}
}
}
and : not (AND not)*;