zoukankan      html  css  js  c++  java
  • 如何获取antlr解析的错误消息?(完美)

    网上现存解决方法:

    • 实现接口 ANTLRErrorListener 。您可以为此扩展 BaseErrorListener 。收集错误并将它们附加到列表中。
    • 调用 parser.removeErrorListeners()删除默认侦听器
    • 调用 parser.addErrorListener(yourListenerInstance)添加自己的监听器

    本文:

    上面是灭有多大问题,但是必须对解析器所有执行这个操作,否者解析功能得到的不完全。

    public static class UnderLineListener extends BaseErrorListener {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer,
                                Object offendingSymbol,
                                int line, int charPositionInLine,
                                String msg,
                                RecognitionException e)
        {
            System.err.println("line "+line+":"+charPositionInLine+" "+msg);
            UnderLineError(recognizer, (Token)offendingSymbol, line, charPositionInLine);
    
        }
    X0Parser 
    lexer都需要
    lexer = new X0Lexer(CharStreams.fromString(input));
                CommonTokenStream tokens = new CommonTokenStream(lexer);
                X0Parser parser = new X0Parser(tokens);
                lexer.removeErrorListeners();
                lexer.addErrorListener(new VerboseListener());
                parser.removeErrorListeners();
                parser.addErrorListener(new VerboseListener());
                X0Parser.ProgramContext tree = parser.program();
                if (parser.getNumberOfSyntaxErrors() > 0) {
                    //throw new RuntimeException("Parse failed!");
                    String output = getFileOutput("./tmpOutput");
                    textShow.append(output+"\n");
                }
                Action visitor = new Action(parser);
                visitor.visit(tree);
  • 相关阅读:
    KMP的next[]数组
    [Gauss]HDOJ3976 Electric resistance
    [Gauss]POJ2065 SETI
    [Gauss]POJ2947 Widget Factory
    更好的 SQL 模式的 10 条规则
    BZOJ2460: [BeiJing2011]元素
    BZOJ2115: [Wc2011] Xor
    洛谷P3164 [CQOI2014]和谐矩阵
    POJ1222熄灯问题
    POJ1830开关问题
  • 原文地址:https://www.cnblogs.com/dgwblog/p/15717546.html
Copyright © 2011-2022 走看看