2017-06-13 4 views
0

、私たちは、次の操作を行いますantlr4のC++ターゲットでエラー報告を上書きする方法は? 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); 

対応するコードはどのようになりますか?

答えて

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