Respackopts/src/main/java/io/gitlab/jfronny/respackopts/muscript/MuScriptScope.java

66 lines
3.0 KiB
Java

package io.gitlab.jfronny.respackopts.muscript;
import io.gitlab.jfronny.muscript.StandardLib;
import io.gitlab.jfronny.muscript.compiler.Parser;
import io.gitlab.jfronny.muscript.compiler.SourceFS;
import io.gitlab.jfronny.muscript.data.Scope;
import io.gitlab.jfronny.muscript.data.Script;
import io.gitlab.jfronny.muscript.data.dynamic.DList;
import io.gitlab.jfronny.muscript.data.dynamic.Dynamic;
import io.gitlab.jfronny.muscript.data.dynamic.additional.DFinal;
import io.gitlab.jfronny.muscript.gson.GsonLib;
import io.gitlab.jfronny.respackopts.model.cache.CacheKey;
import io.gitlab.jfronny.respackopts.model.cache.CachedPackState;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.VersionParsingException;
import net.fabricmc.loader.api.metadata.version.VersionPredicate;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static io.gitlab.jfronny.muscript.data.dynamic.additional.DFinal.of;
public class MuScriptScope {
private static final Scope SCOPE_12;
private static final Scope SCOPE_13;
static {
SCOPE_12 = StandardLib.createScope().set("version", args -> {
if (args.size() != 2) throw new IllegalArgumentException("Expected 2 arguments on version but got " + args.size());
VersionPredicate predicate;
try {
predicate = VersionPredicate.parse(args.get(1).asString().getValue());
} catch (VersionParsingException e) {
throw new IllegalArgumentException("Could not parse version predicate", e);
}
return DFinal.of(FabricLoader.getInstance().getModContainer(args.get(0).asString().getValue())
.map(c -> predicate.test(c.getMetadata().getVersion()))
.orElse(false));
});
SCOPE_13 = GsonLib.addTo(SCOPE_12.fork());
}
public static Scope fork(int version) {
if (version <= 12) return SCOPE_12.fork();
else return SCOPE_13.fork();
}
public static Scope configureFS(Scope scope, CachedPackState state, SourceFS fs) {
int version = state.metadata().version;
if (version <= 12) return scope;
else return scope.set("readString", args -> {
if (args.size() != 1) throw new IllegalArgumentException("Invalid number of arguments for readString: expected 1 but got " + args.size());
return DFinal.of(state.cachedFiles().computeIfAbsent(args.get(0).asString().getValue(), fs::read));
}).set("runScript", args -> {
if (args.isEmpty()) throw new IllegalArgumentException("Invalid number of arguments for evaluateScript: expected 1 or more but got " + args.size());
Script script = state.cachedScripts().computeIfAbsent(
args.get(0).asString().getValue(),
sourceFile -> Parser.parseMultiScript(sourceFile, fs)
);
List<? extends Dynamic> l = args.getValue();
DList innerArgs = of(l.subList(1, l.size()));
return script.bindTo(scope).call(innerArgs);
});
}
}