本文介绍了如何在Antlr4中的解析器给出的运行时期间收集错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从Antlr 3升级到Antlr 4.我使用这个代码来捕获异常使用这个代码。但这不适用于Antlr 4.

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);
    }
}

这是出现的错误

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

在Antlr 4中,在输入流中发生的累积错误的预期方式是什么。我无法找到一种方法来实现这个在网上。请提供一些指导。

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.

编辑:

我已经实现了XParser如下

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?

推荐答案

您需要实施。如果你想要的是报告错误,像你有以上,那么你应该关注 SyntaxError 方法。





  • ConsoleErrorListener
  • BaseErrorListener
  • DiagnosticErrorListener

错误侦听器通过调用 parser.AddErrorListener(listener)

编辑:您需要创建一个新类,错误侦听器接口。然后将侦听器附加到解析器。解析器本身不会实现错误侦听器接口。

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.

这篇关于如何在Antlr4中的解析器给出的运行时期间收集错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 13:20