根据条件删除AST中的节点

时间:2013-05-15 08:57:48

标签: java antlr abstract-syntax-tree

我是新手使用ANTLR。我有一个创建AST的ANTLR语法。我想检查一下,如果ComparisonExpr包含FuzzyExpr,那么我想从AST中删除此ComparisonExpr节点和此ComparisonExpr(如果有)前面的连接(“和”,“或”)。请建议我怎么做。我不知道我可以通过ANTLR的正常重写规则做到吗?

例如

Given the input: where $GPA = #high and age = 25
I want the output like this: where age = 25
(delete the conjunction "and" and ComparisonExpr=>"$GPA = #high") because it has the FuzzyExpr=>"#hight")

这是我语法的一部分。

grammar Test;
options{
output=AST;
ASTLabelType=CommonTree;
}

WhereClause      :="where" ExprSingle;
ExprSingle       :OrExpr;
OrExpr           :AndExpr ("or" AndExpr)*;
AndExpr          :ComparisonExpr ("and" ComparisonExpr)*;
ComparisonExpr   :ValueExpr((ValueComp)ValueExpr)?;
ValueExpr        :ValidateExpr
                 |PathExpr 
                 |ExtensionExpr 
                 |FuzzyExpr;
FuzzyExpr        :"#" Literal;

谢谢。 Pannipa

1 个答案:

答案 0 :(得分:0)

您可以执行此重写规则。这是一个草图,假设您使用操作员根植树:

^(OR e1=expr e2=expr) 
 -> {isFuzzy($e1) && isFuzzy($e2)}? /* empty */
 -> {isFuzzy($e1)}?                 $e2
 -> {isFuzzy($e2)}?                 $e1
 ->                                 ^(OR $e1 $e2)
;

您将语义谓词放在树构建语句的前面。匹配的第一个谓词将选择写入哪个树。如果没有匹配,将使用最后一个。

相关问题