我试图从 ANTLR 获取错误消息,但我很困惑
我替换了标准错误侦听器,就像这个参考问题一样
public String runAntlr(String sqlFile){
ANTLRErrorListener error = new BaseErrorListener();
ANTLRInputStream input;
try {
input = new ANTLRFileStream(sqlFile);
} catch (Exception e) {
return e.toString();
}
tsqlLexer lexer = new tsqlLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
tsqlParser parser = new tsqlParser(tokens);
parser.removeErrorListeners();
lexer.removeErrorListeners();
parser.addErrorListener(error);
lexer.addErrorListener(error);
ParseTree tree = parser.tsql_file();
new MyTsqlVisitor().visit(tree);
System.out.println(error);
return "Analysis successful";
}
这是运行后控制台中的文本:
run:
line 2:16 mismatched input 'as' expecting '.'
line 2:19 no viable alternative at input 'date'
line 5:38 mismatched input 'where' expecting {EXCEPT, INTERSECT, UNION, ')'}
BUILD SUCCESSFUL (total time: 5 seconds)
添加ANTLRErrorListener
后
run:
org.antlr.v4.runtime.BaseErrorListener@4507ed
BUILD SUCCESSFUL (total time: 4 seconds)
我是否正确实施了ANTLRErrorListener
?
它现在可以工作了,这是我的解决方案:
首先,我的MyAntlrErrorListener实现:
public static MyAntlrErrorListener INSTANCE = new MyAntlrErrorListener();
//When the value is false, the syntaxError method returns without displaying errors.
private static final boolean REPORT_SYNTAX_ERRORS = true;
private String errorMsg = "";
@Override
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line,
int charPositionInLine,
String msg,
RecognitionException re) {
if (!REPORT_SYNTAX_ERRORS) {
return;
}
String sourceName = recognizer.getInputStream().getSourceName();
if (!sourceName.isEmpty()) {
sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine);
}
System.err.println(sourceName+"line "+line+":"+charPositionInLine+" "+msg);
errorMsg = errorMsg + "n" + sourceName+"line "+line+":"+charPositionInLine+" "+msg;
}
@Override
public String toString() {
return errorMsg;
}
我在我的主类中得到错误Msg,如下所示:
...
lexer.removeErrorListeners();
lexer.addErrorListener(MyAntlrErrorListener.INSTANCE);
parser.removeErrorListeners();
parser.addErrorListener(MyAntlrErrorListener.INSTANCE);
...
return MyAntlrErrorListener.INSTANCE.toString();