java-commons/muscript/src/main/java/io/gitlab/jfronny/muscript/compiler/ExprWriter.java

67 lines
1.9 KiB
Java

package io.gitlab.jfronny.muscript.compiler;
import java.io.Closeable;
import java.io.IOException;
public class ExprWriter implements Appendable, Closeable {
private final Appendable target;
private final boolean compact;
private int indent = 0;
public ExprWriter(Appendable target, boolean compact) {
this.target = target;
this.compact = compact;
}
@Override
public ExprWriter append(CharSequence csq) throws IOException {
target.append(csq.toString().replace("\r", "").replace("\n", compact ? " " : "\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 {
switch (c) {
case '\r' -> {}
case '\n' -> {
if (compact) target.append(" ");
else target.append("\n").append(indent());
}
default -> target.append(c);
}
return this;
}
public ExprWriter appendLiteral(String s) throws IOException {
if (!Lexer.isValidId(s)) {
if (s.contains("`")) throw new IllegalArgumentException("Not a valid literal: " + s);
else return append('`').append(s).append('`');
} else return append(s);
}
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");
}
}