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(" "); } } }