DumpTree.jrag 1.9 KB
Newer Older
Niklas Fors's avatar
Niklas Fors committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;

// We have been careful to not import many types here because the imports are added for
// _ALL_ AST nodes and can cause collisions in the abstract grammar namespace.

aspect DumpTree {
	private static final String ASTNode.DUMP_TREE_INDENT = "  ";

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

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

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

Niklas Fors's avatar
Niklas Fors committed
40
41
	public String ASTNode.extraDumpInfo() { return ""; }

Niklas Fors's avatar
Niklas Fors committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
	public String ASTNode.getTokens() {
		java.util.TreeSet<java.lang.reflect.Method> methods = new java.util.TreeSet<>(
				new java.util.Comparator<java.lang.reflect.Method>() {
					public int compare(java.lang.reflect.Method m1, java.lang.reflect.Method m2) {
						return m1.getName().compareTo(m2.getName());
					}
				});

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

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