我无法在antlrv4 java中显示错误

时间:2016-11-08 05:04:12

标签: java antlr4

我需要在antlrv4中打印错误,使用antlrv4这本书的例子,但只打印消息

  

第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 : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

1 个答案:

答案 0 :(得分:0)

token recognition error是词法分析器错误。

需要使用Recognizer#addErrorListener(ANTLRErrorListener listener)来(也)添加词法错误侦听器。请注意,Lexer扩展了Recognizer