package mjc.analysis;

import mjc.node.EOF;
import mjc.node.Node;
import mjc.node.Start;
import mjc.node.Token;

/**
 * Simple visitor to print AST in GraphViz format on standard output.
 */
public class ASTGraphPrinter extends DepthFirstAdapter {

    public void print(Start tree) {
        tree.apply(this);
    }

    @Override
    public void inStart(final Start node) {
        System.out.println("digraph G {");
        System.out.println("Start" + node.hashCode() + "[label=Start];");
    }

    @Override
    public void outStart(final Start node) {
        System.out.println("}");
    }

    @Override
    public void defaultIn(final Node node) {
        printNode(node, node.getClass().getSimpleName());
    }

    @Override
    public void defaultCase(Node node) {
        if (!(node instanceof EOF))
            printNode(node, ((Token) node).getText());
    }

    private void printNode(Node node, String label) {
        System.out.println(uniqueName(node) + "[label=" + label + "];");
        if (node.parent() != null)
            printEdge(node.parent(), node);
    }

    private void printEdge(Node from, Node to) {
        System.out.println(uniqueName(from) + " -> " + uniqueName(to) + ";");
    }

    private String uniqueName(Node node) {
        return node.getClass().getSimpleName() + node.hashCode();
    }
}

@@ -240,16 +240,51 @@
 dapter %7B
+%0A    private StringBuilder builder;
 %0A%0A    pu
@@ -412,34 +412,69 @@
         
-System.out.println
+builder = new StringBuilder();%0A        builder.append
 (%22digrap
@@ -478,16 +478,18 @@
 raph G %7B
+%5Cn
 %22);%0A    
@@ -496,71 +496,55 @@
     
-System.out.println(%22Start%22 + node.hashCode() + %22%5Blabel=Start%5D;%22
+printNode(node, node.getClass().getSimpleName()
 );%0A 
@@ -620,30 +620,74 @@
     
-System.out.println(%22%7D%22
+builder.append(%22%7D%5Cn%22);%0A        System.out.print(builder.toString()
 );%0A 
@@ -1035,70 +1035,80 @@
     
-System.out.println(uniqueName(node) + %22%5Blabel=%22 + label + %22%5D;%22
+builder.append(String.format(%22%25s%5Blabel=%25s%5D;%5Cn%22, uniqueName(node), label)
 );%0A 
@@ -1253,26 +1253,22 @@
     
-System.out.println
+builder.append
 (uni
@@ -1311,16 +1311,18 @@
 to) + %22;
+%5Cn
 %22);%0A    

Use StringBuilder in ASTGraphPrinter.