[antlr-interest] robust error recovery

Jim Idle jimi at temporal-wave.com
Wed Aug 19 12:15:23 PDT 2009


Greg Smolyn wrote:
> Hi,
>
> I've been using ANTLR quite successfully in a number of places in a  
> fairly large product-- mainly for parsing CSS and Javascript.
>
> However, I've recently tried to make my grammars more resilient to  
> errors and recover a bit more gracefully, and I've encountered a lot  
> of difficulty in finding information both in the ANTLR book (which  
> pretty much only describes how to _print_ errors) and in the mailing  
> list archives.  Mainly, I'd like to be able to catch a parsing  
> exception, skip it, but _continue_ to parse the rest of the rule.   
> Unfortunately, the way the exceptions are structured, there is no way  
> to catch an exception in a rule and carry on-- you're already outside  
> the main loop of that rule.
>
> Here's a scenario I've encountered-- I'll use CSS as an example.
>
> Say you're given a CSS ruleset with a bad property:
>
> a {
>       margin: 100px;
>      *margin: 200px;
>      background: foo.gif;
> }
>
> What I'd like to do is have it throw the exception and skip the  
> property, but continue along with the next one.  I am stymied by how  
> to do this, however.
>   
Download the JavaFX source code and look at how I did error recovery 
from situations like this in that parser. Basically, you catch the 
exception in the appropriate rule and then resync to the appropriate 
follow/start set, which you can make available on the follow stack with 
a trick empty rule with actions only.

This technique allows you to resync within rules that would otherwise 
drop all the way out, such as class and method definitions where you 
have things like 'class' '{' classElement+ '}'


Jim


More information about the antlr-interest mailing list