Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

c# 4.0 - How to collect errors during run time given by a parser in Antlr4

I have upgraded from Antlr 3 to Antlr 4. I was using this code to catch exceptions using this code. But this is not working for Antlr 4.

partial class XParser
{
    public override void ReportError(RecognitionException e)
    {
        base.ReportError(e);
        Console.WriteLine("Error in Parser at line " + ":" + e.OffendingToken.Column + e.OffendingToken.Line + e.Message);
    }
}

This is the error that appears

'Parser.ReportError(Antlr4.Runtime.RecognitionException)': no suitable method found to override

In Antlr 4 what is the expected way of accumulating errors that occurs in the input stream. I was unable to find a way to achieve this on the net. Please provide me some guidelines.

EDIT:

I have implemented the XParser as below

partial class XParser : IAntlrErrorListener<IToken>
{
    public void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
    {
        Console.WriteLine("Error in parser at line " + ":" + e.OffendingToken.Column + e.OffendingToken.Line + e.Message);
    }
}

As you said I can extend this parser class using any of the mentioned classes. But I was unable to register this listener, in the main program I am confused with passing argument as the listener. Please help me with the registering.

As I can see these classes has the capability of producing more meaningful error messages don't they?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to implement IAntlrErrorListener<IToken>. If all you want to is report errors like you have above, then you should focus on the SyntaxError method. Several base classes are available if you want to extend one.

The error listener is attached to the parser instance by calling parser.AddErrorListener(listener).

Edit: You need to create a new class which implements the error listener interface. You then attach the listener to the parser. The parser itself will not implement the error listener interface.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...