[antlr-interest] Lexer error handling,

Jim Idle jimi at temporal-wave.com
Thu Jul 17 13:37:34 PDT 2008


On Thu, 2008-07-17 at 22:15 +0200, Craig Main wrote:
> Hi,
> 
>  
> 
> I have made the necessary override and @rulecatch changes to ensure
> that my parser throws the first error it encounters out to my catch
> block.
> 
> I followed the instructions in the book “Exiting the recogniser upon
> first error”.



>  
> 
> From examining the source it would appear that @lexer::rulecatch is
> not supported?
> 
> How do I get the lexer to bail on first error?


It is probably better to construct a lexer that cannot fail. Get all
your real rules working then as the last rule add:

ERRCHAR : . { throw somethignAntlrDoesntCatch; } ;

However are you sure you want to do that, or bail out on the first
parser error? Usually a developer likes to see as many errors as
possible in one hit, so you can fix as many as make sense before an
other compile. This is the same for things like batch submissions -
there is nothing more frustrating than submitting something, getting an
error back, fixing that, and resubmitting to find that the next line is
in error too - only beaten by early lisp compilers saying Yes or
No ;-). 

The only time it seems to be useful to bail out early is because the
program isn't using a tree parser, so it is trying to do all the work in
the parser and a syntax error causes later action code to fail badly,
which points to a design flaw really. If your parser does the minimum it
needs to check syntax, then it will be pretty quick and would normally
be better design. That said, there are probably situations where it
makes sense.

Rather than error out, your lexer can say:

ERRCHAR : . {Console.Writeline("Invalid character at....");  $channel =
HIDDEN; } ;

And this will give the parser a reasonable chance of being able to
ignore that character and verify the syntax.

Anyway, that should be the info you need. You could also override the
display error message in the lexer and throw your exception there, but
that is probably less obvious to the eye.

Jim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080717/a290c636/attachment.html 


More information about the antlr-interest mailing list