本文介绍了如何在 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);
    }
}

正如你所说,我可以使用任何提到的类来扩展这个解析器类.但是我无法注册这个监听器,在主程序中我对将参数作为 listener 传递感到困惑.请帮我注册.

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?

推荐答案

你需要实现 IAntlrErrorListener.如果您只想像上面那样报告错误,那么您应该关注 SyntaxError 方法.如果您想扩展一个基类,可以使用多个基类.

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.

错误监听器通过调用parser.AddErrorListener(listener)附加到解析器实例.

The error listener is attached to the parser instance by calling 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:21