我想用 antlr3 创建一个简单的标准表达式解析器
更新:单独的 AND OR 表达式规则以支持 AND/OR 不同的层次结构,但还有另一个问题: 如果表达式类似于:a = 1 and b = 2 and c = 3 根据当前实现,树应如下所示:
= =
(a = 1)(b = 2)(c = 3)
But I want to generate it as follows:
= =
(a = 1)(b = 2)
(c = 3)
First "and" should be higher priority than another, because I want to parse all the expression as left exp and right exp.
我想我需要在“subcond”中重新编写规则以使a = 1 and b = 2 and c = 3 -> (a = 1 and b = 2) and c = 3
但尝试了很多次都没有运气。有没有人知道如何实现它?谢谢。
我的目标是解析某种 SQL where 子句样式的句子,并构建一个 AST 来遍历。
例如:
a = 1 and (b = 2 or c = 3) //This one can parse correctly.
a = 1 and ((b = 2 or c = 3) or d = 4) //This one cannot parse correctly, missing last d = 4 in the tree.
//Tree is not correct.
我当前的语法文件无法解析上述复杂条件。因为我是 antlr 的新手,不知道如何修改我的语法以更正确地实现上述方法。有人可以帮忙吗?!任何建议或意见表示赞赏。
我的语法如下(根据评论更新。警告问题已解决。):
grammar CriteriaExpression;
options {
output = AST;
ASTLabelType = CommonTree;
language = Java;
}
tokens {
AND = 'and';
OR = 'or';
LPAREN = '(';
RPAREN = ')';
}
@lexer::header {
package com.antlr;
}
@parser::header {
package com.antlr;
}
eval
:
expression
;
表达式:andExp (OR^ andExp)* ;
andExp : subcond (AND^ subcond)* ;
subcond : LPAREN 表达式 RPAREN |atom ;
atom
:
EXPR OPERATOR EXPR
;
OPERATOR
:
'='| '<>'| '!='| '<='| '!>'| '<'| '>='| '!<'| '>'| 'like'
;
EXPR
:
('a'..'z'| 'A'..'Z'| '0'..'9')+
;
WILDCARD
:
'%'
;
WS
:
('\t'| ' '| '\r'| '\n'| '\u000C')*
{$channel = HIDDEN;}
;
((a=1))
a = 1 和 ((b = 2 或 c = 3) 或 d = 4)