本文介绍了在 Java 和 ANTLRWorks Debugger 中捕获 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) 意外使用了一些已知标记,在这种情况下,我们将收到类似 line 5:36 no可行替代方案的输入 ','

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 代码中都不会抛出此异常;但它仅在 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 Debugger 中捕获 ANTLR 的 NoViableAltException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:45