/
pretty.pil
48 lines (45 loc) · 1.34 KB
/
pretty.pil
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
45
46
47
48
import "ast.pil"
import gel
import gel::util
import gelly
String stripEndSpaces(String str, Int n) {
var m = new MutableString(str);
for(Int i = str.length-1; i > 0 && n > 0; i--) {
if(str[i] != ' ') {
return m.as<String>;
}
m.remove(i);
n--;
}
return m.as<String>;
}
String gelly::pretty(Term t, Int indentLevel) {
if(t instanceof GroupTerm) {
var gt = t.as<GroupTerm>;
if(gt.type == '(') {
return "(" + pretty(gt.group, indentLevel+1) + ")";
} else if(gt.type == '[') {
return "[" + pretty(gt.group, indentLevel+1) + "]";
} else if(gt.type == '{') {
return "{\n" + spaces(indentLevel+1) + stripEndSpaces(pretty(gt.group, indentLevel+1), 2) + "}";
}
} else if(t instanceof OpTerm) {
var ot = t.as<OpTerm>;
if(ot.op == ";") {
return pretty(ot.left, indentLevel) + ";\n" + spaces(indentLevel) + pretty(ot.right, indentLevel);
}
if(ot.op == "_") {
return pretty(ot.left, indentLevel) + " " + pretty(ot.right, indentLevel);
}
if(ot.isPrefix()) {
return ot.op + pretty(ot.right, indentLevel);
}
if(ot.isPostfix()) {
return pretty(ot.left, indentLevel) + ot.op;
}
return pretty(ot.left, indentLevel) + " " + ot.op + " " + pretty(ot.right, indentLevel);
} else if(t instanceof EmptyTerm) {
return "";
}
return t.as<String>;
}