【发布时间】:2012-05-04 12:44:55
【问题描述】:
我需要一个小技巧来让我的解析器完全工作。 我使用 antlr 来解析布尔查询。
查询由元素组成,通过 ands、ors 和 nots 链接在一起。
所以我可以有类似的东西:
"(P or not Q or R) or (( not A and B) or C)"
问题是,一个元素可以很长,一般是这样的:
a an_operator b
例如:
"New-York matches NY"
诡计,其中一个 an_operator 是“不像”
所以我想修改我的词法分析器,以便 not 检查它后面是否没有 like,以避免解析包含“not like”运算符的元素。
我现在的语法在这里:
// save it in a file called Logic.g
grammar Logic;
options {
output=AST;
}
// parser/production rules start with a lower case letter
parse
: expression EOF! // omit the EOF token
;
expression
: orexp
;
orexp
: andexp ('or'^ andexp)* // make `or` the root
;
andexp
: notexp ('and'^ notexp)* // make `and` the root
;
notexp
: 'not'^ atom // make `not` the root
| atom
;
atom
: ID
| '('! expression ')'! // omit both `(` andexp `)`
;
// lexer/terminal rules start with an upper case letter
ID : ('a'..'z' | 'A'..'Z')+;
Space : (' ' | '\t' | '\r' | '\n')+ {$channel=HIDDEN;};
任何帮助将不胜感激。 谢谢!
【问题讨论】:
-
我说 lex 和 yacc,不是 Antlr。 lex 中的典型解决方案是显式识别关键字和运算符;解析器规范没有。在 Antlr 中,你能不能不写一个像“'not like'^ atom”这样的产生式?
-
@DavidGorsline,我不会让
not like像not这样的一元运算符。not通常否定布尔表达式,而not like比较 2 个值(表达式的左侧和右侧)。此外,创建与'not like'匹配的标记会在中间有更多空格时导致问题,或者当词法分析器偶然发现'not likes'或'not lik'之类的输入时(这将导致词法分析器跳闸,就像 gnu-lex会的,我相信,但我不会说那个太流利:))
标签: java parsing antlr grammar lexer