Java AntlErrorListener获取错误消息
我试图从ANTLR获取错误消息,但我感到困惑 我像这样替换了标准的ErrorListener 这是运行后我的控制台中的文本:Java AntlErrorListener获取错误消息,java,antlr4,Java,Antlr4,我试图从ANTLR获取错误消息,但我感到困惑 我像这样替换了标准的ErrorListener 这是运行后我的控制台中的文本: 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 SUCCE
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)
添加antlErrorListener
run:
org.antlr.v4.runtime.BaseErrorListener@4507ed
BUILD SUCCESSFUL (total time: 4 seconds)
我是否实现了
antlErrorListener
正确 它正在工作,下面是我的解决方案:
首先是MyantlErrorListener的实现:
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;
}
错误。toString()
不起作用。您是否实现了它?error只是BaseErrorListener的一个实例,如果调用正确,它是由antlr使用空方法生成的?我实现了接口AntlErrorListener
,从parser
和lexer
中删除ErrorListener
并添加新的,然后请粘贴已实现的BaseErrorListener类的代码好吗?否则很难说什么是错的…我没有实现BaseErrorListener
,它是来自
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;
}
...
lexer.removeErrorListeners();
lexer.addErrorListener(MyAntlrErrorListener.INSTANCE);
parser.removeErrorListeners();
parser.addErrorListener(MyAntlrErrorListener.INSTANCE);
...
return MyAntlrErrorListener.INSTANCE.toString();