gpt4 book ai didi

java - ANTLR ErrorListener 获取错误消息

转载 作者:行者123 更新时间:2023-11-30 07:35:48 26 4
gpt4 key购买 nike

我试图从 ANTLR 获取错误消息,但我很困惑

我像这样替换了标准的ErrorListener reference question

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

我在主类中收到如下错误消息:

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

...

return MyAntlrErrorListener.INSTANCE.toString();

关于java - ANTLR ErrorListener 获取错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com