Ambiguous ANTLR parser rule

2019-07-23 22:02发布

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.

Here is the grammar:

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);

First text example:

#define EVT_EX1

Second text example:

#define EVT_EX1
#define EVT_EX2

So, the first example is parsed correctly.

enter image description here

However, the second example doesn't work, as the eventNameRule matches the next "#define ..." and the parse tree is incorrect

enter image description here

Appreciate any help to change the grammar to parse this correctly.

Thanks, Busi

2条回答
老娘就宠你
2楼-- · 2019-07-23 22:43

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-23 23:00

As Adrian pointed out, my main mistake here is that in the initial rule (prog) I used "event" and not "event+" this will solve the issue.

Thanks Adrian.

查看更多
登录 后发表回答