91 lines
3.8 KiB
Java
91 lines
3.8 KiB
Java
package io.gitlab.jfronny.muscript;
|
|
|
|
import io.gitlab.jfronny.commons.log.*;
|
|
|
|
import java.util.*;
|
|
import java.util.stream.*;
|
|
|
|
public class StarScriptIngester {
|
|
private static final Logger LOGGER = Logger.forName("MuScript");
|
|
/** Naive conversion of starscript syntax to muscript */
|
|
public static String starScriptToMu(String source) {
|
|
StringBuilder result = new StringBuilder();
|
|
StringBuilder currbuf = new StringBuilder();
|
|
State state = State.Surrounding;
|
|
for (char c : source.toCharArray()) {
|
|
switch (state) {
|
|
case Surrounding -> {
|
|
if (c == '{') {
|
|
if (!currbuf.isEmpty()) {
|
|
if (!result.isEmpty()) result.append(" || ");
|
|
result.append(enquote(currbuf.toString()));
|
|
}
|
|
currbuf = new StringBuilder();
|
|
state = State.UnquotedInner;
|
|
} else currbuf.append(c);
|
|
}
|
|
case UnquotedInner -> {
|
|
switch (c) {
|
|
case '}' -> {
|
|
if (!currbuf.isEmpty()) {
|
|
if (!result.isEmpty()) result.append(" || ");
|
|
result.append("(").append(currbuf).append(")");
|
|
}
|
|
currbuf = new StringBuilder();
|
|
state = State.Surrounding;
|
|
}
|
|
case '\'' -> {
|
|
currbuf.append(c);
|
|
state = State.SingleQuoteInner;
|
|
}
|
|
case '"' -> {
|
|
currbuf.append(c);
|
|
state = State.DoubleQuoteInner;
|
|
}
|
|
default -> currbuf.append(c);
|
|
}
|
|
}
|
|
case SingleQuoteInner -> {
|
|
currbuf.append(c);
|
|
if (c == '\'') state = State.UnquotedInner;
|
|
}
|
|
case DoubleQuoteInner -> {
|
|
currbuf.append(c);
|
|
if (c == '"') state = State.UnquotedInner;
|
|
}
|
|
}
|
|
}
|
|
if (!currbuf.isEmpty() && !result.isEmpty()) result.append(" || ");
|
|
switch (state) {
|
|
case Surrounding -> {
|
|
if (!currbuf.isEmpty()) result.append(enquote(currbuf.toString()));
|
|
}
|
|
case UnquotedInner -> {
|
|
LOGGER.warn("Starscript code segment improperly closed, closing automatically");
|
|
if (!currbuf.isEmpty()) result.append("(").append(currbuf).append(")");
|
|
}
|
|
case SingleQuoteInner -> {
|
|
LOGGER.warn("Quote in starscript swallows ending, completing with closing quote");
|
|
if (!currbuf.isEmpty()) result.append("(").append(currbuf).append("')");
|
|
}
|
|
case DoubleQuoteInner -> {
|
|
LOGGER.warn("Quote in starscript swallows ending, completing with closing quote");
|
|
if (!currbuf.isEmpty()) result.append("(").append(currbuf).append("\")");
|
|
}
|
|
}
|
|
return result.toString();
|
|
}
|
|
|
|
/** Creates quotes around a string, supports strings containing quotes */
|
|
private 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(" || \"'\" || "));
|
|
}
|
|
|
|
enum State {
|
|
Surrounding, UnquotedInner, SingleQuoteInner, DoubleQuoteInner
|
|
}
|
|
}
|