[antlr-interest] Customizing errors in antlr3

Jim Idle jimi at intersystems.com
Mon Jan 8 10:40:39 PST 2007


Ben,

In general it is best to override the error reporting routine itself and print out something more useful to the context in which you are compiling. In general, I override displayRecognitionError (in the C target, but that should be the same in any other target I would think). You can use the existing routine as your template and can then of course code for specific contexts. 

However, this is not that useful in the case you are tying to cover, whereby for instance you know that a common mistake is leaving out a ';', or adding an extra + or something akin to this. At one point, Ter discussed adding some constructs that would cover this sort of thing, whereby you could say 'Here is a syntax you might see, but it is an error", but I can’t find the emails we had about it nor remember the conclusion. I believe that this sort of thing would be very useful in structuring error recovery and so on, and I seem to remember that Ter did also.

Jim

-----Original Message-----
From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-bounces at antlr.org] On Behalf Of Benoit Miller
Sent: Sunday, January 07, 2007 7:58 AM
To: ANTLR Interest
Subject: [antlr-interest] Customizing errors in antlr3

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]

Any suggestions?

Thanks,
Ben.

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.7/619 - Release Date: 1/7/2007 6:29 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.7/619 - Release Date: 1/7/2007 6:29 PM
 


More information about the antlr-interest mailing list