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

44 lines
1.4 KiB
Java

package io.gitlab.jfronny.muscript.compiler;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
public abstract class Decompilable {
public final Order order;
protected Decompilable(Order order) {
this.order = order;
}
public abstract void decompile(ExprWriter writer) throws IOException;
protected void parenthesize(Decompilable val, ExprWriter writer, boolean parenEqualOrder) throws IOException {
boolean wrap = !parenEqualOrder ? val.order.ordinal() > this.order.ordinal() : val.order.ordinal() >= this.order.ordinal();
if (wrap) writer.append('(');
val.decompile(writer);
if (wrap) writer.append(')');
}
/**
* Creates quotes around a string, supports strings containing quotes
*/
public static String enquote(String literalText) {
if (!literalText.contains("'")) return "'" + literalText + "'";
if (!literalText.contains("\"")) return "\"" + literalText + "\"";
return Arrays.stream(literalText.split("'")).map(s -> "'" + s + "'")
.collect(Collectors.joining(" || \"'\" || "));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
try (ExprWriter ew = new ExprWriter(sb)) {
decompile(ew);
} catch (IOException e) {
throw new RuntimeException("Could not decompile", e);
}
return sb.toString();
}
}