ANTLR4 解析树不包含规则名称

ANTLR4 parse tree doesn't contain rule names

ANTLR4 不在解析树中显示规则名称。

例如,1 + 2打印为:

主要代码:

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

我深入研究了 ANTLR 的 C++ 运行时源代码,发现了这两个函数:

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

因此,要修复“错误”,请替换

tree->toStringTree(true)

tree->toStringTree(&parser, true)