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 {
    private StringBuilder builder;

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

    @Override
    public void inStart(final Start node) {
        builder = new StringBuilder();
        builder.append("digraph G {\n");
        printNode(node, node.getClass().getSimpleName());
    }

    @Override
    public void outStart(final Start node) {
        builder.append("}\n");
        System.out.print(builder.toString());
    }

    @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) {
        builder.append(String.format("%s[label=\"%s\"];\n", uniqueName(node), label));
        if (node.parent() != null)
            printEdge(node.parent(), node);
    }

    private void printEdge(Node from, Node to) {
        builder.append(uniqueName(from) + " -> " + uniqueName(to) + ";\n");
    }

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

@@ -886,10 +886,8 @@
  if 
-(!
 (nod
@@ -903,18 +903,704 @@
 eof EOF)
-)
 %0A
+            return;%0A%0A        final Token token = (Token) node;%0A        switch (token.getText()) %7B%0A            case %22=%22:%0A            case %22!=%22:%0A            case %22&&%22:%0A            case %22%7C%7C%22:%0A            case %22%3C%22:%0A            case %22%3C=%22:%0A            case %22%3E%22:%0A            case %22%3E=%22:%0A            case %22length%22:%0A            case %22new%22:%0A            case %22if%22:%0A            case %22else%22:%0A            case %22%5B%22:%0A            case %22*%22:%0A            case %22+%22:%0A            case %22-%22:%0A            case %22int%22:%0A            case %22long%22:%0A            case %22int%5B%5D%22:%0A            case %22long%5B%5D%22:%0A            case %22boolean%22:%0A                break; // Some noise in our AST that we can skip.%0A            default:%0A    
         
@@ -1642,24 +1642,34 @@
 getText());%0A
+        %7D%0A
     %7D%0A%0A    p

Exclude some noise tokens in ASTGraphPrinter.