Skip to content

Commit

Permalink
ServiceLoader is cool
Browse files Browse the repository at this point in the history
  • Loading branch information
ZZZank committed Aug 2, 2024
1 parent 2117e6e commit 769de91
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public CompilerEnvirons() {
this.strictMode = false;
this.warningAsError = false;
this.allowSharpComments = false;
this.optimizationLevel = RhinoProperties.INSTANCE.optimizationLevel;
this.optimizationLevel = RhinoProperties.get().optimizationLevel;
}

public void initFromContext(Context cx) {
Expand Down
4 changes: 2 additions & 2 deletions common/src/main/java/dev/latvian/mods/rhino/Context.java
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ protected Context(ContextFactory factory) {
}
this.factory = factory;
maximumInterpreterStackDepth = Integer.MAX_VALUE;
optimizationLevel = RhinoProperties.INSTANCE.optimizationLevel;
optimizationLevel = RhinoProperties.get().optimizationLevel;
remapper = null;
customProperties = new HashMap<>();
}
Expand Down Expand Up @@ -2116,7 +2116,7 @@ private ScriptNode parse(String sourceString,
}

private Evaluator createCompiler() {
if(!RhinoProperties.INSTANCE.enableCompiler) {
if(!RhinoProperties.get().enableCompiler) {
return createInterpreter();
}
Evaluator result = null;
Expand Down
34 changes: 16 additions & 18 deletions common/src/main/java/dev/latvian/mods/rhino/ScriptableObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.*;

/**
* This is the default implementation of the Scriptable interface. This
Expand Down Expand Up @@ -1223,8 +1219,9 @@ static <T extends Scriptable> BaseFunction buildClassCtor(Scriptable scope, Clas
&& parmTypes[0] == ScriptRuntime.ContextClass
&& parmTypes[1] == ScriptRuntime.ScriptableClass
&& parmTypes[2] == Boolean.TYPE
&& Modifier.isStatic(method.getModifiers())) {
Object[] args = {Context.getContext(), scope, sealed ? Boolean.TRUE : Boolean.FALSE};
&& Modifier.isStatic(method.getModifiers())
) {
Object[] args = {Context.getContext(), scope, Boolean.valueOf(sealed)};
method.invoke(null, args);
return null;
}
Expand Down Expand Up @@ -1377,7 +1374,7 @@ static <T extends Scriptable> BaseFunction buildClassCtor(Scriptable scope, Clas
names.add(propName);
name = propName;

if (annotation instanceof JSGetter || prefix == getterPrefix) {
if (annotation instanceof JSGetter || Objects.equals(prefix, getterPrefix)) {
if (!(proto instanceof ScriptableObject)) {
throw Context.reportRuntimeError2("msg.extend.scriptable", proto.getClass().toString(), name);
}
Expand Down Expand Up @@ -1453,19 +1450,20 @@ private static String getPropertyName(String methodName, String prefix, Annotati
String propName = null;
if (annotation instanceof JSGetter) {
propName = ((JSGetter) annotation).value();
if (propName == null || propName.length() == 0) {
if (methodName.length() > 3 && methodName.startsWith("get")) {
propName = methodName.substring(3);
if (Character.isUpperCase(propName.charAt(0))) {
if (propName.length() == 1) {
propName = propName.toLowerCase();
} else if (!Character.isUpperCase(propName.charAt(1))) {
propName = Character.toLowerCase(propName.charAt(0)) + propName.substring(1);
}
if ((propName == null || propName.length() == 0)
&& methodName.length() > 3
&& methodName.startsWith("get")
) {
propName = methodName.substring(3);
if (Character.isUpperCase(propName.charAt(0))) {
if (propName.length() == 1) {
propName = propName.toLowerCase();
} else if (!Character.isUpperCase(propName.charAt(1))) {
propName = Character.toLowerCase(propName.charAt(0)) + propName.substring(1);
}
}
}
} else if (annotation instanceof JSFunction) {
} else if (annotation instanceof JSFunction jsFn) {
propName = ((JSFunction) annotation).value();
} else if (annotation instanceof JSStaticFunction) {
propName = ((JSStaticFunction) annotation).value();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package dev.latvian.mods.rhino.mod;

import dev.architectury.injectables.annotations.ExpectPlatform;
import dev.latvian.mods.rhino.mod.remapper.MappingIO;
import org.jetbrains.annotations.Contract;
import dev.latvian.mods.rhino.util.Lazy;
import org.jetbrains.annotations.NotNull;

import java.io.InputStream;
Expand All @@ -12,42 +11,30 @@
import java.nio.file.Path;
import java.util.Properties;

/**
* @see dev.latvian.mods.rhino.mod.forge.RhinoPropertiesImpl
* @see dev.latvian.mods.rhino.mod.fabric.RhinoPropertiesImpl
*/
public class RhinoProperties {
public abstract class RhinoProperties {

public static final RhinoProperties INSTANCE = new RhinoProperties();
private static final Lazy<RhinoProperties> implementation = Lazy.serviceLoader(RhinoProperties.class);

public static RhinoProperties get() {
return implementation.get();
}

public boolean generateMapping;
public boolean enableCompiler;
public int optimizationLevel;

@ExpectPlatform
@Contract(value = " -> _", pure = true)
public static Path getGameDir() {
throw new AssertionError();
}
public abstract Path getGameDir();

@ExpectPlatform
@Contract(value = " -> _", pure = true)
public static boolean isDev() {
throw new AssertionError();
}
public abstract boolean isDev();

@ExpectPlatform
@NotNull
@Contract(value = " -> _", pure = true)
public static InputStream openResource(String path) throws Exception {
throw new AssertionError();
}
public abstract InputStream openResource(String path) throws Exception;

private final Properties properties;
// public boolean forceLocalMappings;
private boolean writeProperties;

RhinoProperties() {
public RhinoProperties() {
this.properties = new Properties();

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,13 @@ private RhizoRemapper() {
}

private static InputStream locateMappingFile() {
val cfgPath = RhinoProperties.getGameDir().resolve("config/" + RhizoMappingGen.MAPPING_FILENAME);
val cfgPath = RhinoProperties.get().getGameDir().resolve("config/" + RhizoMappingGen.MAPPING_FILENAME);
try {
if (Files.exists(cfgPath)) {
MappingIO.LOGGER.info("Found Rhizo mapping file from config/{}.", RhizoMappingGen.MAPPING_FILENAME);
return new GZIPInputStream(Files.newInputStream(cfgPath));
}
val in = new GZIPInputStream(RhinoProperties.openResource(RhizoMappingGen.MAPPING_FILENAME));
val in = new GZIPInputStream(RhinoProperties.get().openResource(RhizoMappingGen.MAPPING_FILENAME));
MappingIO.LOGGER.info("Found Rhizo mapping file from Rhizo mod jar.");
return in;
} catch (Exception e) {
Expand Down
58 changes: 58 additions & 0 deletions common/src/main/java/dev/latvian/mods/rhino/util/Lazy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package dev.latvian.mods.rhino.util;

import java.util.ServiceLoader;
import java.util.function.Supplier;

/**
* @author ZZZank
*/
public class Lazy<T> implements Supplier<T> {
public static <T> Lazy<T> of(Supplier<T> supplier) {
return new Lazy<>(supplier, -1L);
}

public static <T> Lazy<T> of(Supplier<T> supplier, long expiresInMs) {
return new Lazy<>(supplier, System.currentTimeMillis() + expiresInMs);
}

public static <T> Lazy<T> serviceLoader(Class<T> type) {
return of(() -> {
var loaded = ServiceLoader.load(type).iterator();
if (loaded.hasNext()) {
return loaded.next();
}
throw new RuntimeException(String.format(
"Could not find platform implementation for %s!",
type.getSimpleName()
));
});
}

private final Supplier<T> factory;
private T value;
private boolean cached;
private final long expires;

private Lazy(Supplier<T> factory, long expires) {
this.factory = factory;
this.expires = expires;
}

@Override
public T get() {
if (expires >= 0L && System.currentTimeMillis() > expires) {
cached = false;
} else if (cached) {
return value;
}

value = factory.get();
cached = true;
return value;
}

public void forget() {
value = null;
cached = false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
import com.github.bsideup.jabel.Desugar;
import dev.latvian.mods.rhino.mod.RhinoProperties;
import dev.latvian.mods.rhino.mod.remapper.RhizoMappingGen;
import dev.latvian.mods.rhino.mod.remapper.RhizoRemapper;
import dev.latvian.mods.rhino.mod.remapper.info.Clazz;
import dev.latvian.mods.rhino.util.remapper.AnnotatedRemapper;
import dev.latvian.mods.rhino.util.remapper.DualRemapper;
import dev.latvian.mods.rhino.util.remapper.RemapperManager;
import lombok.val;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.impl.launch.FabricLauncherBase;
Expand All @@ -23,7 +19,7 @@ public class RhinoModFabric implements ModInitializer {

@Override
public void onInitialize() {
if (RhinoProperties.INSTANCE.generateMapping) {
if (RhinoProperties.get().generateMapping) {
RhizoMappingGen.generate(
"1.16.5",
new RenameOnlyMappingLoader(loadNativeMappingClassMap())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.latvian.mods.rhino.mod.fabric;

import dev.latvian.mods.rhino.mod.RhinoProperties;
import net.fabricmc.loader.api.FabricLoader;
import org.jetbrains.annotations.NotNull;

Expand All @@ -10,17 +11,17 @@
/**
* @see dev.latvian.mods.rhino.mod.RhinoProperties
*/
public class RhinoPropertiesImpl {
public static Path getGameDir() {
public class RhinoPropertiesImpl extends RhinoProperties {
public Path getGameDir() {
return FabricLoader.getInstance().getGameDir();
}

public static boolean isDev() {
public boolean isDev() {
return FabricLoader.getInstance().isDevelopmentEnvironment();
}

@NotNull
public static InputStream openResource(String path) throws Exception {
public InputStream openResource(String path) throws Exception {
return Files.newInputStream(FabricLoader.getInstance().getModContainer("rhino").get().findPath(path).get());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public RhinoModForge() {

@SubscribeEvent
public static void onCommonSetup(FMLCommonSetupEvent event) {
if (RhinoProperties.INSTANCE.generateMapping) {
if (RhinoProperties.get().generateMapping) {
Thread t = new Thread(() -> RhizoMappingGen.generate(
"1.16.5",
(mcVersion, vanillaMapping) -> IMappingFile.load(MappingIO.getUrlConnection(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.latvian.mods.rhino.mod.forge;

import dev.latvian.mods.rhino.mod.RhinoProperties;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLLoader;
import org.jetbrains.annotations.NotNull;
Expand All @@ -11,17 +12,17 @@
/**
* @see dev.latvian.mods.rhino.mod.RhinoProperties
*/
public class RhinoPropertiesImpl {
public static Path getGameDir() {
public class RhinoPropertiesImpl extends RhinoProperties {
public Path getGameDir() {
return FMLLoader.getGamePath();
}

public static boolean isDev() {
public boolean isDev() {
return !FMLLoader.isProduction();
}

@NotNull
public static InputStream openResource(String path) throws Exception {
public InputStream openResource(String path) throws Exception {
return Files.newInputStream(ModList.get().getModFileById("rhino").getFile().findResource(path));
}
}

0 comments on commit 769de91

Please sign in to comment.