我正在使用antlr编写语法,并且我有一个主要函数来测试语法接受的程序。主要功能是:
package compiler;
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
public class runner {
public static void main(String[] args) throws Exception {
ANTLRInputStream input = new ANTLRInputStream(System.in);
SmallCLexer lexer = new SmallCLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SmallCParser parser = new SmallCParser(tokens);
SmallCParser.program_return result = parser.program();
String tree = result.tree.toStringTree();
System.out.println(tree);
}
}
我的问题是它无法识别 toStringTree() 命令,我想知道是否有人能明白为什么?
我发现了这个: http://www.antlr.org/api/Java/interfaceorg_1_1antlr_1_1runtime_1_1tree_1_1_tree.html
它声称该函数包含在 BaseTree 中。
我还编辑了代码以使用 org.antlr.runtime.* 导入所有 antlr 文件,但这仍然无法解决此问题。我只是不明白为什么它不能识别它。
最佳答案
首先添加导入:
import org.antlr.runtime.tree.CommonTree;
然后试试这个:
CommonTree tree = (CommonTree)parser.program().getTree();
System.out.println(tree.toStringTree());
请注意,只有当您的解析器语法中有以下选项时,这才有效:
options {
output=AST;
}
关于java - ANTLR toStringTree() 未被识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316554/