[antlr-interest] Manually raising recognition error

Jim Idle jimi at temporal-wave.com
Wed Jul 25 07:15:38 PDT 2012


Don't think of errors as having to cone from the parser.

First, I think that it is a good idea to program the grammar to cater for errors like this specifically. You cannot always do so as sometimes adding the error productions causes too much ambiguity in the grammar. 

Next, you should be overriding displayRecognitionError and unlike the built in sample, you are usually better off adding error messages to a collection that is used for the whole run of your tool chain. The lever adds messages if it needs to, then the parser, then your tree walkers and so on. You then report all the errors at the end. 

You create some functions to form these messages from raw information, tokens, tree nodes and anything else you need. 

Now in your empty alt, you just call one of the methods

{
  error(E_MISSING_THINGY, line, col);
}

And it will be duly reported. The built in mechanism isn't called but you don't need it here. 

Also, read the article on custom error recovery in the wiki for some magic error recovery methods. 

Remember that the built in error system is just a few function calls that you can override. 

Jim

On Jul 25, 2012, at 2:19 AM, Mike Lischke <mike at lischke-online.de> wrote:

> Hi list,
> 
> similar questions have been asked already, but I couldn't find any answer (neither in MarkMail nor Google). Given a rule like this:
> 
> a:
>    b (c | d)
> ;
> 
> I would like to report more precisely if both c and d are missing. Letting the default handling process this I often get errors that don't really address the actual problem. So I tried:
> 
> a:
>    b
>    (
>        c
>        | d
>        | -> ^(MISSING_TOKEN)
>    )
> ;
> 
> which works very well, except that now I don't get any error at all and would need to parse the tree to know that there was a missing token. So my wish is to also raise an error in addition.
> 
> I guess raising an error is specific to the parser target, so I'd be especially interested in a C target solution.
> 
> Mike
> -- 
> www.soft-gems.net
> 
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address


More information about the antlr-interest mailing list