Ambiguous ANTLR parser rule

爷,独闯天下 提交于 2019-12-11 02:13:12

问题


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.

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.

Thanks, Busi


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/29368402/ambiguous-antlr-parser-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!