我需要打印antlrv4中的错误,使用antlrv4的书的示例,但只打印消息
line 1:11标记识别错误:'!'
在我的代码中,我要打印堆栈并显示这一行,这是我的代码
import org.antlr.v4.runtime.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
public class TestE_Listener extends JFrame{
public static class DialogListener extends BaseErrorListener {
@Override
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line, int charPositionInLine,
String msg,
RecognitionException e)
{
List<String> stack = ((Parser)recognizer).getRuleInvocationStack();
Collections.reverse(stack);
StringBuilder buf = new StringBuilder();
buf.append("rule stack: "+stack+" ");
buf.append(" show the line "+line+":"+charPositionInLine+" at "+
offendingSymbol+": "+msg);
JDialog dialog = new JDialog();
Container contentPane = dialog.getContentPane();
contentPane.add(new JLabel(buf.toString()));
contentPane.setBackground(Color.white);
dialog.setTitle("Syntax error");
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
}
public static void main(String[] args) throws Exception {
ANTLRInputStream input = new ANTLRInputStream("hello world!");
HelloLexer lexer = new HelloLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new DialogListener());
parser.r();
}
}
这是我的语法
grammar Hello;
r : 'hello' ID ; // match keyword hello followed by an identifier
ID : [a-z]+ ; // match lower-case identifiers
WS : [ trn]+ -> skip ; // skip spaces, tabs, newlines
token recognition error
是词法分析器错误。
需要使用Recognizer#addErrorListener(ANTLRErrorListener listener)
(也)添加词法分析器错误侦听器。注意,Lexer
扩展了Recognizer