54 lines
2.4 KiB
Java
54 lines
2.4 KiB
Java
package io.gitlab.jfronny.respackopts.gson;
|
|
|
|
import io.gitlab.jfronny.commons.serialize.MalformedDataException;
|
|
import io.gitlab.jfronny.commons.serialize.SerializeReader;
|
|
import io.gitlab.jfronny.commons.serialize.SerializeWriter;
|
|
import io.gitlab.jfronny.commons.serialize.Token;
|
|
import io.gitlab.jfronny.commons.serialize.databind.api.SerializerFor;
|
|
import io.gitlab.jfronny.commons.serialize.databind.api.TypeAdapter;
|
|
import io.gitlab.jfronny.muscript.ast.Expr;
|
|
import io.gitlab.jfronny.muscript.parser.Parser;
|
|
import io.gitlab.jfronny.muscript.parser.StarScriptIngester;
|
|
import io.gitlab.jfronny.muscript.serialize.Decompiler;
|
|
import io.gitlab.jfronny.respackopts.muscript.ScopeVersion;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
@SerializerFor(targets = Expr.class)
|
|
public class ExprDeserializer extends TypeAdapter<Expr> {
|
|
public static final ExprDeserializer INSTANCE = new ExprDeserializer();
|
|
private static final Map<String, Expr> compiledScripts = new HashMap<>();
|
|
|
|
@Override
|
|
public <TEx extends Exception, Writer extends SerializeWriter<TEx, Writer>> void serialize(Expr expr, Writer writer) throws TEx, MalformedDataException {
|
|
writer.value(Decompiler.decompile(expr));
|
|
}
|
|
|
|
@Override
|
|
public <TEx extends Exception, Reader extends SerializeReader<TEx, Reader>> Expr deserialize(Reader reader) throws TEx, MalformedDataException {
|
|
if (reader.peek() == Token.STRING) {
|
|
return parse(reader.nextString());
|
|
} else if (reader.peek() == Token.BEGIN_OBJECT) {
|
|
throw new MalformedDataException("Could not parse script: Expected string but got object (did you forget to migrate this rpo to muScript?)");
|
|
} else {
|
|
throw new MalformedDataException("Could not parse script: Expected string");
|
|
}
|
|
}
|
|
|
|
public Expr parse(String source) throws MalformedDataException {
|
|
if (compiledScripts.containsKey(source))
|
|
return compiledScripts.get(source);
|
|
try {
|
|
int v = AttachmentHolder.getAttachedVersion();
|
|
Expr expr = Parser.parse(ScopeVersion.by(v).muScriptVersion, v <= 7
|
|
? StarScriptIngester.starScriptToMu(source)
|
|
: source);
|
|
compiledScripts.put(source, expr);
|
|
return expr;
|
|
} catch (Parser.ParseException e) {
|
|
throw new MalformedDataException("Could not create script", e);
|
|
}
|
|
}
|
|
}
|