[antlr-interest] How to get ANTLR 3.2 to exit upon first error?

Dan Becker db19606 at gmail.com
Mon Mar 15 19:48:39 PDT 2010


Thanks, Andrew! That works for the parser.

For the lexer, it apparently isn't so simple in java, because
reportError() doesn't declare any exceptions. There's a wiki page that
explains what to do for the lexer:

http://www.antlr.org/wiki/pages/viewpage.action?pageId=5341217

The quick summary is either (1) override nextToken() to throw a
Recognition Exception instead of call reportError() (2) use sneaky
java tricks to let you throw RecognitionException anyway (3) throw the
RecognitionException wrapped in a RuntimeException.

Dan

On Mon, Mar 15, 2010 at 4:25 PM, Andrew Haritonkin <thikone at gmail.com> wrote:
> On Mon, Mar 15, 2010 at 9:41 PM, Kirby Bohling <kirby.bohling at gmail.com> wrote:
>> You need to repeat some of that for the lexer.  Using the
>> @lexer::members syntax if you're going to do it as a combined
>> lexer/parser grammar (I always separate mine to keep my mental working
>> set smaller).  If you don't do the lexer, you can have a lex error and
>> recover from it, but this should catch all of the parse errors.
>>
>> Kirby
>>
>>
>> On Mon, Mar 15, 2010 at 3:32 PM, Andrew Haritonkin <thikone at gmail.com> wrote:
>>> For Java and C# target add this in the beginning of the grammar but
>>> after grammar statement:
>>>
>>> grammar grammar1;
>>>
>>> @members {
>>> protected override object RecoverFromMismatchedToken(IIntStream input,
>>> int ttype, BitSet follow)
>>> {
>>>        throw new MismatchedTokenException(ttype, input);
>>> }
>>> public override object RecoverFromMismatchedSet(IIntStream input,
>>> RecognitionException e, BitSet follow)
>>> {
>>>        throw e;
>>> }
>>> }
>>>
>>> @rulecatch {
>>> catch (RecognitionException e)
>>> {
>>>    throw e;
>>> }
>>> }
>>>
>>> Hope it helps,
>>> Andrew
>>>
>
> Indeed, forgot about lexer... So, the full code which you need to add
> to the grammar for C# target would be:
>
> grammar grammar1;
>
> @lexer::members {
> public override void ReportError(RecognitionException e)
> {
>        throw e;
> }
> }
>
> @parser::members {
> protected override object RecoverFromMismatchedToken(IIntStream input,
> int ttype, BitSet follow)
> {
>        throw new MismatchedTokenException(ttype, input);
> }
> public override object RecoverFromMismatchedSet(IIntStream input,
> RecognitionException e, BitSet follow)
> {
>        throw e;
> }
> }
>
> @rulecatch {
> catch (RecognitionException e)
> {
>    throw e;
> }
> }
>
> Similar should be for Java target, only naming convention is different.
>
> Andrew
>



-- 
Dan Becker
303/497-6824


More information about the antlr-interest mailing list