我正在尝试从ANTLR获取错误信息,但我很困惑
我替换了这个reference question
中的标准ErrorListenerpublic 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
权利?
答案 0 :(得分:1)
现在正在运作,这是我的解决方案:
首先我的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;
}
我在我的Main类中得到了errorMsg,如下所示:
...
lexer.removeErrorListeners();
lexer.addErrorListener(MyAntlrErrorListener.INSTANCE);
parser.removeErrorListeners();
parser.addErrorListener(MyAntlrErrorListener.INSTANCE);
...
return MyAntlrErrorListener.INSTANCE.toString();