本文介绍了在Java和ANTLRWorks调试器中捕获ANTLR的NoViableAltException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我们尝试将一些不正确的输入文本提供给某些语法(例如包含一些未知标记的文本)。在解释期间的 ANTLRWorks 中,我们将在图表中看到 NoViableAltException

Consider we try to feed some incorrect input text to some grammar (e.g. text which contains some unknown token). In ANTLRWorks during interpretation we will see NoViableAltException in graph.

UPD:出现此异常时有两种情况:

UPD: There are two cases when this exception appears:

1)意外使用某些已知令牌,在这种情况下我们会收到类似第5:36行的输入','

1) Unexpected using of some known token, in this case we will receive something like line 5:36 no viable alternative at input ','

2)使用未知的令牌类型。例如,语法对标记一无所知,标记以 @ 符号开头。我们正在尝试将带有此类标记的文本提供给我们的语法。

2) Using unknown token type. For example grammar doesn't know anything about tokens, which start with @ symbol. And we are trying to feed text with such token to our grammar.

不幸的是如果情况(2)此异常未被抛出 ANTLRWorks 调试器,既不在生成的Java代码中;也不在生成的Java代码中。但只能在 ANTLRWorks 解释器的结果图中看到。

Unfortunately in case (2) this exception isn't thrown neither in ANTLRWorks debugger, neither in generated Java code; but it is seen only in ANTLRWorks interpreter's result graph.

我还尝试添加以下标准代码我的语法:

I've tried also to add the following standard code to my grammar:

@parser::members {
    private IErrorReporter errorReporter = null;
    public void setErrorReporter(IErrorReporter errorReporter) {
        this.errorReporter = errorReporter;
    }
    public void emitErrorMessage(String msg) {
        errorReporter.reportError(msg);
    }
}
@lexer::members {
    ... the same code as above ...
}

此构造成功捕获类型(1)的解析错误(例如,有关令牌的意外使用的错误:第5:36行输入',')的可行替代方案。但是如果使用未知令牌进行不可行输入,解析器只会在顶部 CommonTree 对象中生成 children == null 任何错误报告。

This construction successfully catches parsing errors of type (1) (e.g. errors about unexpected using of token: line 5:36 no viable alternative at input ','). But in case of not-viable-input with unknown tokens parser generates just children == null in top CommonTree object without any error reporting.

我正在使用 antlr 3.5

问题:是否可以在生成的Java代码中描述的情况下捕获 NoViableAltException 以及如何?

The question: is it possible to catch NoViableAltException in described situation in generated Java code and how?

推荐答案

那么,由提供给我的解决了这两个问题。所以,这是正确的答案。

Well, this answer given by 280Z28 to my second part of this question solves both problems well. So, this is the proper answer.

这篇关于在Java和ANTLRWorks调试器中捕获ANTLR的NoViableAltException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!