[antlr-interest] Customizing errors in antlr3

David Holroyd dave at badgers-in-foil.co.uk
Sun Jan 7 08:23:21 PST 2007


On Sun, Jan 07, 2007 at 10:58:01AM -0500, Benoit Miller wrote:
> What is the best way to customize reported errors in antlr3?
> 
> For example, in the following snippet:
> 
> start
>     :   forwardDecl* objectDecl*
>     ;
> 
> forwardDecl
>     :   classOrStruct IDENTIFIER ';'
>         -> ^(classOrStruct IDENTIFIER)
>     ;
> 
> objectDecl
>     :   attrList? classOrStruct IDENTIFIER '{' property* '}' ';'
>         -> ^(classOrStruct IDENTIFIER attrList? property*)
>     ;
> 
> [unedited snippet, so this time it should be representative :)]
> 
> Given an input such as "[foo] class Bar;", I want to report to the tool 
> user something like "cannot specify attributes on forward declarations", 
> but it's unclear to me how to do this.
> 
> I tried using a syntactic predicate to throw my error from the parser:
> 
> objectDecl
>     :   attrList? classOrStruct IDENTIFIER
>         ( {input.LA(1)==';'}? { throw new Exception("foo"); }
>         | '{' property* '}' ';'
>           -> ^(classOrStruct IDENTIFIER attrList? property*)
>         )
>     ;
> 
> ..but that didn't work, the parser still throws a NoViableAlt exception 
> instead of my own:
> 
> [objectDecl]: line 1:20  state 0 (decision=5) no viable alt; 
> token=[@7,20:20=';',<30>,1:20]

Not sure if I'm right here, but maybe try creating a named token and
doing

  {input.LA(1)==SEMI}?

or look at the token text.

  {input.LT(1).getText().equals(";")}

because as it is, I suspect that predicate is equivalent to

  {input.LA(1)==59}?

(59 being the ASCII code point for ';').


ta,
dave

-- 
http://david.holroyd.me.uk/


More information about the antlr-interest mailing list