如何获取antlr4错误输出?

hyrbngr7  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(490)

堆栈溢出!
我使用antlr4来解析输入。我有我的x.g4语法文件和antlr4maven插件生成了一些解析器代码。我正在用以下代码分析输入:

XXXXParser parser = new XXXXParser(new CommonTokenStream(
            new XXXXLexer(new ANTLRInputStream(currentInput))));
parser.command();

在上面的代码中,“command”是语法中规则的名称。每次启动此代码时,如果currentinput字符串不符合语法,我会在控制台中收到一条错误消息。我希望能够捕捉这些信息并使用它们。问题是如何做到这一点?

c0vxltue

c0vxltue1#

您可以编写一个实现 IAntlrErrorListener<T> 然后打电话 parser.AddErrorListener() 并传入自定义错误列表。下面是一个来自我自己代码的示例(我实际上是从 DiagnosticErrorListener ):

public class CustomErrorListener : DiagnosticErrorListener
{
    private readonly List<string> _errorMessages = new List<string>();
    public IList<string> ErrorMessages { get { return _errorMessages; } }

    private readonly List<string> _warningMessages = new List<string>();
    public IList<string> WarningMessages { get { return _warningMessages; } }

    public bool HasErrors { get { return _errorMessages.Count > 0; } }
    public bool HasWarnings { get { return _warningMessages.Count > 0; } }

    private readonly bool _captureDiagnostics;

    public CustomErrorListener(bool captureDiagnosticWarnings)
    {
        _captureDiagnostics = captureDiagnosticWarnings;
    }

    public override void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
    {
        _errorMessages.Add(string.Format("line {0}:{1} {2} at: {3}", line, charPositionInLine, msg, offendingSymbol.Text));
    }

    public override void ReportAmbiguity(Parser recognizer, Antlr4.Runtime.Dfa.DFA dfa, int startIndex, int stopIndex, bool exact, Sharpen.BitSet ambigAlts, Antlr4.Runtime.Atn.ATNConfigSet configs)
    {
        if (_captureDiagnostics)
        {
            _warningMessages.Add(string.Format("reportAmbiguity d={0}: ambigAlts={1}, input='{2}'", GetDecisionDescription(recognizer, dfa), GetConflictingAlts(ambigAlts, configs), ((ITokenStream)recognizer.InputStream).GetText(Interval.Of(startIndex, stopIndex))));
        }
    }

    public override void ReportAttemptingFullContext(Parser recognizer, Antlr4.Runtime.Dfa.DFA dfa, int startIndex, int stopIndex, Sharpen.BitSet conflictingAlts, Antlr4.Runtime.Atn.SimulatorState conflictState)
    {
        if (_captureDiagnostics)
        {
            _warningMessages.Add(string.Format("reportAttemptingFullContext d={0}, input='{1}'", GetDecisionDescription(recognizer, dfa), ((ITokenStream)recognizer.InputStream).GetText(Interval.Of(startIndex, stopIndex))));
        }
    }

    public override void ReportContextSensitivity(Parser recognizer, Antlr4.Runtime.Dfa.DFA dfa, int startIndex, int stopIndex, int prediction, Antlr4.Runtime.Atn.SimulatorState acceptState)
    {
        if (_captureDiagnostics)
        {
            _warningMessages.Add(string.Format("reportContextSensitivity d={0}, input='{1}'", GetDecisionDescription(recognizer, dfa), ((ITokenStream)recognizer.InputStream).GetText(Interval.Of(startIndex, stopIndex))));
        }
    }
}

然后你可以这样写代码:

XXXXParser parser = new XXXXParser(new CommonTokenStream(
            new XXXXLexer(new ANTLRInputStream(currentInput))));
CustomErrorListener errorListener = new CustomErrorListener(false);
parser.AddErrorListener(errorListener);
parser.command();

相关问题