Girish
Girish

Reputation: 81

How to Customize ANTLR exception in C#

I am using ANTLR 3

I am trying to custom the exception message raised from Praser.

Expression which I am using :-

2+*3

Error message recived from ANTLR is :

no viable alternative at input '*' line 1:3

I want to custom this exception message to

 Invalid Expression Term line 1:3

I tried to override GetErrorMessage(RecognitionException e, string[] tokenNames) method of parser but not able to figure out how to customize this description. Similar to these I've to customize other exception message also.

Can anyone provide me some initial guidance how to proceed with this issue.

I am using c# 4.0

Upvotes: 1

Views: 240

Answers (3)

Girish
Girish

Reputation: 81

I've implemented in this way probably it may benifit others also :-

In my parser class :-

public override string GetErrorMessage(RecognitionException e, string[] tokenNames)
    {
            String msg = string.Empty;
            if (e is NoViableAltException)
            {
                msg = "Invalid Expression Term";
            }
            else if (e is UnwantedTokenException)
            {
                msg = "Bracket Mismatch";
            }
            else if (e is MissingTokenException)
            {
                msg = "Invalid Parameter";
            }
            else
            {
                base.GetErrorMessage(e, tokenNames);
            }
            return msg;
    }

Upvotes: 0

Sam Harwell
Sam Harwell

Reputation: 99869

You can model your implementation of GetErrorMessage after the one in BaseRecognizer. All of the message templates are included in this method.

https://github.com/antlr/antlr3/blob/master/runtime/CSharp3/Sources/Antlr3.Runtime/BaseRecognizer.cs#L275

Upvotes: 2

Lex Li
Lex Li

Reputation: 63183

Catch the NoViableAltException and any other RecognitionException derived exceptions and throw out your own exception. The line number and column number can be picked up from RecognitionException.Line and RecognitionException.CharPositionInLine.

Upvotes: 1

Related Questions