有没有办法在ANTLR中创建/扩展默认模板以生成.dot文件?
我的节点中有一些我希望在树上可视化的自定义属性,而不是每次都要将它们打印到控制台。
我目前只具备StringTemplate(V3)的基本工作知识。
感谢。
答案 0 :(得分:0)
你能做的是:
DOTTreeGenerator
并更改构造函数中的(静态)节点模板getNodeST
并将自定义属性添加到模板演示如何添加每棵树的子计数的演示:
// Original source of DOTTreeGenerator:
// https://github.com/antlr/antlr3/blob/master/runtime/Java/src/main/java/org/antlr/runtime/tree/DOTTreeGenerator.java
class MyDOTTreeGenerator extends DOTTreeGenerator {
public MyDOTTreeGenerator() {
// added ", childCount=$childCount$"
DOTTreeGenerator._nodeST = new StringTemplate("$name$ [label=\"text=$text$, childCount=$childCount$\"];\n");
}
@Override
protected StringTemplate getNodeST(TreeAdaptor adaptor, Object t) {
// cast "t" to your own tree implementation
CommonTree tree = (CommonTree)t;
String text = adaptor.getText(t);
StringTemplate nodeST = _nodeST.getInstanceOf();
String uniqueName = "n"+getNodeNumber(t);
nodeST.setAttribute("name", uniqueName);
// set the "childCount" attribute
nodeST.setAttribute("childCount", tree.getChildCount());
nodeST.setAttribute("text", fixString(text));
return nodeST;
}
}
像这样使用:
TLexer lexer = new TLexer(new ANTLRStringStream("..."));
TParser parser = new TParser(new CommonTokenStream(lexer));
CommonTree root = parser...
MyDOTTreeGenerator gen = new MyDOTTreeGenerator();
System.out.println(gen.toDOT(root));