我正在尝试从ANTLR获取错误消息,但我很困惑

我在reference question中替换了标准的ErrorListener

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


并且我在Main类中得到errorMsg,如下所示:

...
lexer.removeErrorListeners();
lexer.addErrorListener(MyAntlrErrorListener.INSTANCE);
parser.removeErrorListeners();
parser.addErrorListener(MyAntlrErrorListener.INSTANCE);

...

return MyAntlrErrorListener.INSTANCE.toString();

09-05 08:58