[antlr-interest] NoViableAltException but do not know why

Clifford Heath clifford.heath at gmail.com
Wed Oct 31 14:50:06 PDT 2007


OJAY78 at gmx.de wrote:
> I have the following rule in my grammar.
> justifyStrFunction returns[String value]
> 	:	'justify' '(' parameter '|' ('left' | 'center' | 'right')('|' ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')* )? ')' 
> 	;
> If I try the command: justify("test"|left|4); in the ANTLRWorks Interpreter it works and I see the parser tree for that command. But if I try more than one digit like this command justify("test"|left|44); it resolves in a NoViableAltException. 
> Can anyone explain me why this happens??

I believe I just did in my message "Puzzle, and solution."
Try temporarily adding a rule:

junk: justifyStrFunction EOF;

to your grammar, and you'll find it might just work.

The function generated for your grammar rule won't 
match until it looks ahead past the input it matches
to see that the following token is one of the tokens
that could validly follow that rule in any part of
your grammar. It sees EOF in this case, and if there's
no way that can be valid in your grammar, it fails.
Adding the temporary rule opens the possibility that
EOF is a valid following token, so it passes.

It seems to me possible that it doesn't need to look
ahead in this case, since after seeing the ')' there's
nothing else that it can consume, but I suspect it's a
detail of how the LL(*) algorithm works that it always
needs to look anyhow. Perhaps Terrence can elaborate.

Clifford Heath.



More information about the antlr-interest mailing list