package io.gitlab.jfronny.muscript.compiler; import java.io.Closeable; import java.io.IOException; import java.util.stream.Collectors; public class ExprWriter implements Appendable, Closeable { private final Appendable target; private int indent = 0; public ExprWriter(Appendable target) { this.target = target; } @Override public ExprWriter append(CharSequence csq) throws IOException { target.append(csq.toString().lines().collect(Collectors.joining("\n" + indent()))); return this; } @Override public ExprWriter append(CharSequence csq, int start, int end) throws IOException { return append(csq.subSequence(start, end)); } @Override public ExprWriter append(char c) throws IOException { if (c == '\n' || c == '\r') target.append("\n").append(indent()); else target.append(c); return this; } private String indent() { return " ".repeat(indent); } public ExprWriter increaseIndent() { indent += 2; return this; } public ExprWriter decreaseIndent() { if (indent <= 1) throw new IllegalStateException("Attempted to decrease indent lower than 0"); indent -= 2; return this; } @Override public void close() { if (indent != 0) throw new IllegalStateException("Attempted to close ExprWriter before end"); } }