001 /*
002 @license.text@
003 */
004 package biz.hammurapi.antlr;
005
006 import org.w3c.dom.Document;
007 import org.w3c.dom.Element;
008
009 import antlr.collections.AST;
010
011 /**
012 * Serializes AST to DOM
013 * @author Pavel Vlasov
014 */
015 public class AstUtil {
016 /**
017 * Serializes AST, its children and its siblings to DOM.
018 * @param node
019 * @param tokenNames
020 * @param holder
021 */
022 public static void toDom(antlr.collections.AST node, String[] tokenNames, Element holder) {
023 for (AST ast=node; ast!=null; ast=ast.getNextSibling()) {
024 holder.appendChild(toDom(ast, tokenNames, holder.getOwnerDocument()));
025 }
026 }
027
028 /**
029 * Serializes AST and its children to DOM.
030 * @param node
031 * @param tokenNames
032 * @param owner
033 */
034 public static Element toDom(antlr.collections.AST node, String[] tokenNames, Document owner) {
035 Element ret=owner.createElement("ast");
036 ret.setAttribute("type", tokenNames[node.getType()]);
037 if (node.getText()!=null) {
038 ret.appendChild(owner.createTextNode(node.getText()));
039 }
040 for (AST child=node.getFirstChild(); child!=null; child=child.getNextSibling()) {
041 ret.appendChild(toDom(child, tokenNames, owner));
042 }
043 return ret;
044 }
045
046 private static String tabs(int t) {
047 StringBuffer sb=new StringBuffer();
048 for (int i=0; i<t; i++) {
049 sb.append("....");
050 }
051 return sb.toString();
052 }
053
054 /**
055 * Dumps node and siblings
056 * @param node
057 * @param tokenNames
058 */
059 public static void dumpAll(antlr.collections.AST node, String[] tokenNames) {
060 System.out.println("=== AST Dump ===");
061 while (node!=null) {
062 dump(node, tokenNames, 0);
063 node=node.getNextSibling();
064 }
065 }
066
067 /**
068 * Dumps this node and its children
069 * @param node
070 */
071 public static void dump(antlr.collections.AST node, String[] tokenNames) {
072 dump(node, tokenNames, 0);
073 }
074
075 private static void dump(antlr.collections.AST node, String[] tokenNames, int tab) {
076 System.out.print(tabs(tab));
077 System.out.print(tokenNames[node.getType()]);
078 if (node.getText()!=null) {
079 System.out.println(" '"+node.getText()+"'");
080 }
081 for (AST child=node.getFirstChild(); child!=null; child=child.getNextSibling()) {
082 dump(child, tokenNames, tab+1);
083 }
084 }
085 }