aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/shedlang/compiler/treetext/TreeSerializer.java
blob: d232d6b8ede9d5e0af423861ff36ff1e91b52043 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package org.shedlang.compiler.treetext;

import static org.shedlang.compiler.util.Iterables.forEachInterspersed;

public class TreeSerializer {
    private TreeSerializer() {}

    public static void serializeTree(Tree tree, StringBuilder builder, int indentation) {
        switch (tree) {
            case TreeIdentifier identifier -> {
                builder.append(identifier.name());
            }
            case TreeInt treeInt -> {
                builder.append(treeInt.value());
            }
            case TreeList list -> {
                builder.append("(");
                forEachInterspersed(
                    list.children(),
                    child -> serializeTree(child, builder, indentation),
                    () -> builder.append(" ")
                );
                builder.append(")");
            }
            case TreeListIndented list -> {
                builder.append("(");
                forEachInterspersed(
                    list.children(),
                    child -> {
                        newLine(indentation + 1, builder);
                        serializeTree(child, builder, indentation + 1);
                    },
                    () -> {}
                );
                newLine(indentation, builder);
                builder.append(")");
            }
            case TreeNamed named -> {
                builder.append(named.name());
                builder.append("=");
                serializeTree(named.value(), builder, indentation);
            }
            case TreeString string -> {
                builder.append("\"");
                var escapedValue = string.value()
                    .replace("\\", "\\\\")
                    .replace("\b", "\\b")
                    .replace("\t", "\\t")
                    .replace("\n", "\\n")
                    .replace("\f", "\\f")
                    .replace("\r", "\\r")
                    .replace("\"", "\\\"");
                builder.append(escapedValue);
                builder.append("\"");
            }
        }
    }

    private static void newLine(int indentation, StringBuilder builder) {
        builder.append("\n");
        for (var i = 0; i < indentation; i++) {
            builder.append("    ");
        }
    }
}