[antlr-interest] NoViableAltException in ()? rule

Terence Parr parrt at cs.usfca.edu
Thu Dec 2 09:52:50 PST 2004



On Dec 2, 2004, at 2:35 PM, Ingo Maier wrote:

>
> Hi,
>
> for a (x)? the generated code seems not only to check if an x comes
> next, but also what can come after (or instead of) that x. If such a
>

Yes, because it tries to find errors as soon as possible.

> token doesn't follow it throws a NoViableAltException.
>
> For example in the java grammar:
>
> tryBlock: "try"^ compoundStatement (handler)* (finallyClause)?;
>
> If no finally clause comes next, it also checks for possibly following
> tokens in the generated typeBlock() method:
>
> switch ( LA(1)) {
>   case LITERAL_finally:
>   {
>     ...
>   }
>   case FINAL:
>   case ABSTRACT:
>    ...
>      break;
>
>
> Why? Those following tokens have nothing to do with the rule tryBlock
> itself, but only with the enclosing grammar, right?

Yes, but it is fine to check that lookahead, right?

> As a consequence java snippets followed by some non-java text cannot be
> parsed without an exception:
>
> try { /*...*/ } catch(Exception e) { /*...*/ } /* no finally clause */
> here comes some text...
>
> When I call tryBlock(), "here" is not expected because of the generated
> switch block as pasted above. However, "here" should have nothing to do
> with the tryBlock() rule.

Well, you get an error because that text is not part of the grammar and 
ANTLR wants you to know. ;)

You are actually asking a different question, which is "how do I handle 
island grammars in ANTLR?"  Meaning that you want ANTLR to only match a 
part of the text.  Given input:

> try { /*...*/ } catch(Exception e) { /*...*/ } /* no finally clause */
> here comes some text...

I think you'll be hard pressed even by hand to figure out when Java is 
not coming next.  For example, here's a valid definition:

here comes;

depending on the type definitions.  You need a sentinel like JSP has or 
other island grammars to indicate what is what.

:)

Ter
--
CS Professor & Grad Director, University of San Francisco
Creator, ANTLR Parser Generator, http://www.antlr.org
Cofounder, http://www.jguru.com
Cofounder, http://www.knowspam.net enjoy email again!





 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
    antlr-interest-unsubscribe at yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 





More information about the antlr-interest mailing list