2017-06-13 67 views
0

要在antlr4的Java对象以不同的方式报告错误,我们做到以下几点:如何覆盖antlr4的C++目标中的错误报告?

(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++ target中的相应代码是什么?

回答

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; 
};