[antlr-interest] C# Error Recovery

Gavin Lambert antlr at mirality.co.nz
Wed Apr 16 13:46:47 PDT 2008


I have a rule like this in my grammar (C# target, latest interim 
build):

tag[String name]
	:	WS? t=TAG { $t.text.Equals("<" + $name + ">") }? NL
	;
catch [FailedPredicateException ex] { throw new 
RecognitionException("Expected <" + $name + "> but found " + 
$t.text, ex, Input); }

The intent should be clear -- I want to validate that I'm 
receiving the tag I'm expecting to get at that point in the input, 
but I want to give it a custom error message.

I want all the normal ANTLR backtracking and recovery mechanisms 
to take effect, which basically seems to mean that I need to be 
throwing a RecognitionException or derived class thereof.

The problem lies in BaseRecognizer.GetErrorMessage, which 
completely ignores the Message of the incoming exception and uses 
a series of type-specific tests to construct a new message; 
leaving it blank if a base RecognitionException is thrown.  I can 
work around this by deriving a new exception from 
RecognitionException and overriding GetErrorMessage to deal with 
that appropriately, but I shouldn't need to.

Proposed fixes:

1. At minimum, the first line of GetErrorMessage should be changed 
to assign "e.Message" as the default message, not null.

2. Preferably, *all* the type specific code in GetErrorMessage 
should be removed, and the exception Message should be set to the 
equivalent when the exception is thrown in the first place (in 
their constructors).  It just seems silly to try to "fix it up" 
after the fact.



More information about the antlr-interest mailing list