ANTLR4 doesn't show rule names in parse tree.
For example, 1 2
is printed as:
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";
CodePudding user response:
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)