问题描述
我有一个非常简单的示例文本,我想用ANTLR进行解析,但是由于规则的定义不明确,我得到了错误的结果.
I have a very simple example text which I want to parse with ANTLR, and yet I'm getting wrong results due to ambiguous definition of the rule.
这是语法:
grammar SimpleExampleGrammar;
prog : event EOF;
event : DEFINE EVT_HEADER eventName=eventNameRule;
eventNameRule : DIGIT+;
DEFINE : '#define';
EVT_HEADER : 'EVT_';
DIGIT : [0-9a-zA-Z_];
WS : ('' | ' ' | '\r' | '\n' | '\t') -> channel(HIDDEN);
第一个文本示例:
#define EVT_EX1
第二个文本示例:
#define EVT_EX1
#define EVT_EX2
因此,第一个示例已正确解析.
So, the first example is parsed correctly.
但是,第二个示例不起作用,因为eventNameRule匹配下一个"#define ..."并且解析树不正确
However, the second example doesn't work, as the eventNameRule matches the next "#define ..." and the parse tree is incorrect
感谢帮助更改语法以正确解析语法的任何帮助.
Appreciate any help to change the grammar to parse this correctly.
谢谢,Busi
推荐答案
除了缺少的循环说明符之外,您的WS规则也存在问题.第一个alt匹配任何东西.删除那个.顺便说一句,给您的DIGIT规则起一个不同的名字.它不仅可以匹配数字.
Beside the missing loop specifier you also have a problem in your WS rule. The first alt matches anything. Remove that. And, btw, give your DIGIT rule a different name. It matches more than just digits.
这篇关于模棱两可的ANTLR解析器规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!