-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrettyPrinter.java
44 lines (39 loc) · 1.4 KB
/
PrettyPrinter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public final class PrettyPrinter {
private PrettyPrinter() { }
public static String printAST(Main.Stmt ast) {
int tabs = 0;
final StringBuilder sb = new StringBuilder();
if (ast != null)
printStmt(ast, tabs, sb);
return sb.toString().trim();
}
private static void printStmt(Main.Stmt stmt, final int tabs, final StringBuilder sb) {
sb.append(getTabsString(tabs));
sb.append("+--");
sb.append(stmt.getLabel());
sb.append("\n");
stmt.children.forEach(c -> {
if (c instanceof Main.Expr)
printExpr((Main.Expr) c, tabs + 1, sb);
else
printStmt((Main.Stmt) c, tabs + 1, sb);
});
}
private static void printExpr(Main.Expr expr, final int tabs, final StringBuilder sb) {
sb.append(getTabsString(tabs));
sb.append("*--");
sb.append(expr.getLabel());
sb.append("\n");
if (!expr.getChildren().isEmpty()) {
expr.getChildren().forEach(child -> {
if (child instanceof Main.Expr)
printExpr((Main.Expr) child, tabs + 1, sb);
else if (child instanceof Main.Stmt)
printStmt((Main.Stmt) child, tabs, sb);
});
}
}
private static String getTabsString(final int tabs) {
return "| ".repeat(Math.max(0, tabs));
}
}