如何覆盖antlr4的c ++目标中的错误报告?

时间:2017-06-13 07:50:06

标签: antlr4

要在antlr4-java目标中以不同方式报告错误,我们执行以下操作:

(1)定义一个新的监听器:

class DescriptiveErrorListener extends BaseErrorListener {
    public static DescriptiveErrorListener INSTANCE =
        new DescriptiveErrorListener();
    @Override
    public void syntaxError(Recognizer<?, ?> recognizer,
            Object offendingSymbol,
                        int line, int charPositionInLine,
                        String msg, RecognitionException e)
    {
        String printMsg = String.format("ERR: %s:%d:%d: %s",
            recognizer.getInputStream().getSourceName(), line,
            charPositionInLine+1, msg);
        System.err.println(printMsg);
    }
}

(2)覆盖词法分析器和解析器的记者:

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

c ++目标中的相应代码是什么?

1 个答案:

答案 0 :(得分:0)

在C ++中,它几乎完全相同(除了语言特定方面)。我使用的代码:

struct MySQLParserContextImpl : public MySQLParserContext {
  ANTLRInputStream input;
  MySQLLexer lexer;
  CommonTokenStream tokens;
  MySQLParser parser;
  LexerErrorListener lexerErrorListener;
  ParserErrorListener parserErrorListener;
  ...    
  MySQLParserContextImpl(...)
    : lexer(&input), tokens(&lexer), parser(&tokens), lexerErrorListener(this), parserErrorListener(this),... {

  ...    
    lexer.removeErrorListeners();
    lexer.addErrorListener(&lexerErrorListener);

    parser.removeParseListeners();
    parser.removeErrorListeners();
    parser.addErrorListener(&parserErrorListener);
  }

  ...
}

和听众:

class LexerErrorListener : public BaseErrorListener {
public:
  MySQLParserContextImpl *owner;

  LexerErrorListener(MySQLParserContextImpl *aOwner) : owner(aOwner) {}

  virtual void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line, size_t charPositionInLine,
                           const std::string &msg, std::exception_ptr e) override;
 };

class ParserErrorListener : public BaseErrorListener {
public:
  MySQLParserContextImpl *owner;

  ParserErrorListener(MySQLParserContextImpl *aOwner) : owner(aOwner) {}

  virtual void syntaxError(Recognizer *recognizer, Token *offendingSymbol, size_t line, size_t charPositionInLine,
                           const std::string &msg, std::exception_ptr e) override;
};