[antlr-interest] customizing error messages for syntactic predicates
Gavin Lambert
antlr at mirality.co.nz
Sat Jan 24 13:43:20 PST 2009
At 08:49 25/01/2009, Carter Cheng wrote:
>I apologize for the potential double post. But I meant something
>like this where I am trying to throw an error when a condition
is
>met.
>
>LPAREN LBRACE { $LPAREN.index == $LBRACE.index - 1 }?
>arrayElementList? RBRACE RPAREN { $RBRACE.index == $RPAREN.index
-
>1 }?
When I needed to do something like this, I used the following
method (C# code, but should be similar for Java):
tag[String name]
: TAB? t=TAG { $t.text.Equals("<" + $name + ">") }? NL
;
catch [FailedPredicateException ex] { throw new
CustomRecognitionException("Expected <" + $name + "> but found " +
$t.text, ex, Input); }
Note: CustomRecognitionException is exactly what it sounds like --
a new exception class derived from RecognitionException. This is
required because the standard implementation of GetErrorMessage in
the parser completely ignores the text in the exception. And yes,
this is completely dumb. Because of that, I also had to use this
override:
public override string GetErrorMessage(RecognitionException e,
string[] tokenNames)
{
if (e is CustomRecognitionException) {
return e.Message;
}
return base.GetErrorMessage(e, tokenNames);
}
More information about the antlr-interest
mailing list