DumpTree.jrag 1.68 KB
Newer Older
Johannes Mey's avatar
Johannes Mey committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
aspect DumpTree {
  private static final String ASTNode.DUMP_TREE_INDENT = "  ";

  public String ASTNode.dumpTree() {
    java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
    dumpTree(new java.io.PrintStream(bytes));
    return bytes.toString();
  }

  public void ASTNode.dumpTree(java.io.PrintStream out) {
    dumpTree(out, "");
    out.flush();
  }

  public void ASTNode.dumpTree(java.io.PrintStream out, String indent) {
    out.print(indent + getClass().getSimpleName());
    out.print(getTokens());
    String extra = extraDumpInfo();
    if (!extra.isEmpty()) {
      out.print(" " + extra);
    }
    out.println();
    String childIndent = indent + DUMP_TREE_INDENT;
24
    for (ASTNode<?> child : astChildren()) {
Johannes Mey's avatar
Johannes Mey committed
25
26
27
28
29
30
31
32
33
34
35
      if (child == null) {
        out.println(childIndent + "null");
      } else {
        child.dumpTree(out, childIndent);
      }
    }
  }

  public String ASTNode.extraDumpInfo() { return ""; }

  public String ASTNode.getTokens() {
Johannes Mey's avatar
Johannes Mey committed
36
    java.util.TreeSet<java.lang.reflect.Method> methods = new java.util.TreeSet<>(java.util.Comparator.comparing(java.lang.reflect.Method::getName));
Johannes Mey's avatar
Johannes Mey committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

    methods.addAll(java.util.Arrays.asList(getClass().getMethods()));

    StringBuilder result = new StringBuilder();
    for (java.lang.reflect.Method method : methods) {
      ASTNodeAnnotation.Token token = method.getAnnotation(ASTNodeAnnotation.Token.class);
      if (token != null) {
        try {
          result.append(String.format(" %s=\"%s\"", token.name(), method.invoke(this)));
        } catch (IllegalAccessException  ignored) {
        } catch (java.lang.reflect.InvocationTargetException ignored) {
        }
      }
    }
    return result.toString();
  }
}