Catching ANTLR's NoViableAltException in Java and ANTLRWorks Debugger

人走茶凉 提交于 2019-12-01 08:38:57

问题


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: There are two cases when this exception appears:

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

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.

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 ...
}

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.

I'm using antlr 3.5.

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


回答1:


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




回答2:


You need to add the following as the very last rule in your lexer. It will create a token for the invalid character(s) and send it to the parser where the error will be properly reported.

ANYCHAR : . ;


来源:https://stackoverflow.com/questions/15384800/catching-antlrs-noviablealtexception-in-java-and-antlrworks-debugger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!