Search code examples
c++parsingantlr4grammar

ANTLR4 parse tree doesn't contain rule names


ANTLR4 doesn't show rule names in parse tree.

For example, 1 + 2 is printed as:

Simple expression's tree

Code in main:

    std::string test = "1 + 2";
    ANTLRInputStream input(test);
    GrammarLexer lexer(&input);
    CommonTokenStream tokens(&lexer);
    GrammarParser parser(&tokens);

    auto *tree = parser.expression();

    std::cout << tree->toStringTree(true) << "\n";

Solution

  • I dived into ANTLR's C++ runtime source code and found these 2 functions:

    /// Print out a whole tree, not just a node, in LISP format
    /// {@code (root child1 .. childN)}. Print just a node if this is a leaf.
    virtual std::string toStringTree(bool pretty = false) = 0;
    
    /// Specialize toStringTree so that it can print out more information
    /// based upon the parser.
    virtual std::string toStringTree(Parser *parser, bool pretty = false) = 0;
    

    So, to fix the "error", replace

    tree->toStringTree(true)
    

    with

    tree->toStringTree(&parser, true)