2
votes

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
How are you generating the graphs? The second example isn't valid according to your grammar, as prog is only a single event.Adrian Leonhard
Hi Adrian, thank for your comment. I use AntlWorks2 to generate the graphs. tunnelvisionlabs.com/products/demo/antlrworksbaruchl

2 Answers

1
votes

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.

0
votes

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.