问题描述
我尝试按照以下方式报告错误.
I tried error reporting in following manner.
@members{
public String getErrorMessage(RecognitionException e,String[] tokenNames)
{
List stack=getRuleInvocationStack(e,this.getClass().getName());
String msg=null;
if(e instanceof NoViableAltException){
<some code>
}
else{
msg=super.getErrorMessage(e,tokenNames);
}
String[] inputLines = e.input.toString().split("\r\n");
String line = "";
if(e.token.getCharPositionInLine()==0)
line = "at \"" + inputLines[e.token.getLine() - 2];
else if(e.token.getCharPositionInLine()>0)
line = "at \"" + inputLines[e.token.getLine() - 1];
return ": " + msg.split("at")[0] + line + "\" => [" + stack.get(stack.size() - 1) + "]";
}
public String getTokenErrorDisplay(Token t){
return t.toString();
}
}
现在错误显示如下.
line 6:7 : missing CLOSSB at "int a[6;" => [var_declaration]
line 8:0 : missing SEMICOL at "int p" => [var_declaration]
line 8:5 : missing CLOSB at "get(2;" => [call]
我有2个问题.
1)有正确的方法来做我做过的同样的事情吗?
1) Is there a proper way to do the same thing I have done?
2)我想用其真实符号替换CLOSSB,SEMICOL,CLOSB等.如何使用.g文件中的地图来做到这一点?
2) I want to replace CLOSSB, SEMICOL, CLOSB etc. with their real symbols. How can I do that using the map in .g file?
谢谢.
推荐答案
* 1)是否有正确的方法来完成我做过的同样的事情?
*1) Is there a proper way to do the same thing I have done?
没有单一的方法可以做到这一点.请注意,正确的错误处理和报告非常棘手.特伦斯·帕尔(Terence Parr)在权威性ANTLR参考(该章10).我建议您拿一份副本并阅读.
There is no single way to do this. Note that proper error-handling and reporting is tricky. Terence Parr spends a whole chapter on this in The Definitive ANTLR Reference (chapter 10). I recommend you get hold of a copy and read it.
2)我想用其真实符号替换CLOSSB,SEMICOL,CLOSB等.如何使用.g文件中的地图来做到这一点?
不能.对于SEMICOL
,这似乎很容易做到,但是您如何获取诸如FOO
这样的令牌的信息:
You can't. For SEMICOL
this may seem easy to do, but how would you get this information for a token like FOO
:
FOO : (X | Y)+;
fragment X : '4'..'6';
fragment Y : 'a' | 'bc' | . ;
这篇关于ANTLR3处理错误的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!