I have question that considers ANTLR4 and its grammar(productions).
NOTE:I won’t go into details of my example because my doubt is of a technical nature.
I have the following productions:
prog
: stat '.'+
;
stat
: word+
;
word
: WORD1
| WORD2
;
WORD1 : some regular expression
WORD2 : some regular expression
WS : [ \t\r\n]+ -> skip;
So, my grammar has to recognize multiple sentences that are seperated with ‘.’ and every sentence has one or more words(WORD1 or WORD2). Also, as you can see when I come on space, tab or new line I have to skip them. So my problem is that this grammar only recognizes first sentence and prints some word that I’ve given when stat production is finished. But it does not continue to other sentences. I don’t understand why because for main rule(prog) we have stat’.’+.
If someone could clear this one for me would be very thankful.
>Solution :
What prog : stat '.'+; means is this: match a single stat, followed by one or more '.'‘s. What you probably want it this:
prog : (stat '.')+;
The fact that the parser does not consume all tokens (or tries to do so) is because you did not "anchor" your start-production with the EOF token. Try this:
prog : (stat '.')+ EOF;
which will force ANTLR to consume all tokens (or produce an error when it cannot consume all tokens).