mirror of
https://github.com/GTNewHorizons/GTNHLib.git
synced 2026-11-26 06:43:00 +00:00
Improve edge cases of @EventBusSubscriber (#448)
Co-authored-by: RecursivePineapple <[email protected]>
This commit is contained in:
1 parent
c5b3bfbd7e
commit
0d985efa1e
4 files changed
+75
-33
No files matched your search
+25
-5
@@ -43,7 +43,7 @@ public class EventBusSubTransformer implements IClassTransformer {
|
||||
private static final List<String> ANNOTATIONS = Arrays
|
||||
.asList(OPTIONAL_DESC, SIDEONLY_DESC, SUBSCRIBE_DESC, CONDITION_DESC);
|
||||
private static final String CURRENT_SIDE = FMLLaunchHandler.side().name();
|
||||
private static final ObjectSet<String> classesToVisit = EventBusUtil.getClassesToVisit();
|
||||
private static final ObjectSet<String> classesToVisit = EventBusUtil.classesToVisit;
|
||||
|
||||
@Override
|
||||
public byte[] transform(String name, String transformedName, byte[] basicClass) {
|
||||
@@ -75,7 +75,7 @@ public class EventBusSubTransformer implements IClassTransformer {
|
||||
boolean condition = usableAnnotations.containsKey(CONDITION_DESC);
|
||||
if ((mn.access & Opcodes.ACC_STATIC) == 0) {
|
||||
if (!condition && subscribe != null) {
|
||||
EventBusUtil.getInvalidMethods()
|
||||
EventBusUtil.invalidMethods
|
||||
.add("Encountered unexpected non-static method: " + getMethodKey(transformedName, mn));
|
||||
}
|
||||
continue;
|
||||
@@ -83,14 +83,21 @@ public class EventBusSubTransformer implements IClassTransformer {
|
||||
|
||||
if (condition) {
|
||||
if (mn.desc.equals("()Z")) {
|
||||
EventBusUtil.getConditionsToCheck().put(transformedName, mn.name + mn.desc);
|
||||
EventBusUtil.conditionsToCheck.put(transformedName, mn.name + mn.desc);
|
||||
changed |= changeAccess(transformedName, mn);
|
||||
} else {
|
||||
EventBusUtil.getInvalidMethods().add(
|
||||
EventBusUtil.invalidMethods.add(
|
||||
"Invalid condition method: " + getMethodKey(transformedName, mn)
|
||||
+ ". Condition method must have no parameters and return a boolean.");
|
||||
}
|
||||
continue;
|
||||
} else {
|
||||
if (!isValidDesc(mn.desc)) {
|
||||
EventBusUtil.invalidMethods.add(
|
||||
"Invalid event handler method: " + getMethodKey(transformedName, mn)
|
||||
+ ". Event handler method must have exactly one Event parameter and return void.");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (subscribe == null) {
|
||||
@@ -124,7 +131,7 @@ public class EventBusSubTransformer implements IClassTransformer {
|
||||
}
|
||||
}
|
||||
|
||||
EventBusUtil.getMethodsToSubscribe().computeIfAbsent(transformedName, k -> new ObjectOpenHashSet<>())
|
||||
EventBusUtil.methodsToSubscribe.computeIfAbsent(transformedName, k -> new ObjectOpenHashSet<>())
|
||||
.add(methodInfo);
|
||||
if (DEBUG_EVENT_BUS) {
|
||||
LOGGER.info("Found subscribed method {}", methodInfo.getKey());
|
||||
@@ -201,4 +208,17 @@ public class EventBusSubTransformer implements IClassTransformer {
|
||||
private static String getMethodKey(String className, MethodNode mn) {
|
||||
return className + " " + mn.name + mn.desc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this method descriptor is a possible descriptor for an event handler method. Specifically, it
|
||||
* checks that the method takes one non-literal parameter and returns void. Does not check whether that parameter is
|
||||
* a valid Event method, since that would require class-loading
|
||||
*
|
||||
* @param desc The descriptor of the static method.
|
||||
* @return True if the method could potentially be an event handler method, false if the method is guaranteed to be
|
||||
* an invalid event handler method.
|
||||
*/
|
||||
private static boolean isValidDesc(String desc) {
|
||||
return desc.startsWith("(L") && desc.endsWith(";)V") && desc.lastIndexOf(';', desc.length() - 4) == -1;
|
||||
}
|
||||
}
|
||||
@@ -38,19 +38,20 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectList;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectSet;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class AutoEventBus {
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger("GTNHLib EventBus");
|
||||
private static final DummyEvent INVALID_EVENT = new DummyEvent();
|
||||
private static final Object2ObjectMap<String, Event> eventCache = new Object2ObjectOpenHashMap<>();
|
||||
private static final Object2BooleanMap<String> optionalMods = new Object2BooleanOpenHashMap<>();
|
||||
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
|
||||
private static final MethodType CONDITION_TYPE = MethodType.methodType(boolean.class);
|
||||
|
||||
private static final DummyEvent INVALID_EVENT = new DummyEvent();
|
||||
private static final DummyEvent NOT_AN_EVENT = new DummyEvent();
|
||||
|
||||
private AutoEventBus() {}
|
||||
|
||||
private enum EventBusType {
|
||||
|
||||
FORGE(MinecraftForge.EVENT_BUS, AutoEventBus::isForgeEvent),
|
||||
@@ -87,15 +88,15 @@ public class AutoEventBus {
|
||||
for (String className : entry.getValue()) {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(className, false, Loader.instance().getModClassLoader());
|
||||
String conditionToCheck = EventBusUtil.getConditionsToCheck().get(className);
|
||||
String conditionToCheck = EventBusUtil.conditionsToCheck.get(className);
|
||||
if (conditionToCheck != null && !isConditionMet(clazz, conditionToCheck)) {
|
||||
if (DEBUG_EVENT_BUS) {
|
||||
LOGGER.info("Skipping registration for {}, condition not met", clazz.getSimpleName());
|
||||
LOGGER.info("Skipping registration for {}, condition not met", className);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
ObjectSet<MethodInfo> methods = EventBusUtil.getMethodsToSubscribe().get(className);
|
||||
ObjectSet<MethodInfo> methods = EventBusUtil.methodsToSubscribe.get(className);
|
||||
if (methods == null || methods.isEmpty()) continue;
|
||||
register(entry.getKey(), clazz, methods);
|
||||
} catch (ClassNotFoundException e) {
|
||||
@@ -105,15 +106,14 @@ public class AutoEventBus {
|
||||
}
|
||||
|
||||
if (phase == Phase.INIT) {
|
||||
ObjectList<String> invalidMethods = EventBusUtil.getInvalidMethods();
|
||||
ObjectList<String> invalidMethods = EventBusUtil.invalidMethods;
|
||||
if (invalidMethods.size() == 1) {
|
||||
throw new IllegalArgumentException(invalidMethods.get(0));
|
||||
} else if (invalidMethods.size() > 1) {
|
||||
int i;
|
||||
for (i = 0; i < invalidMethods.size() - 1; i++) {
|
||||
LOGGER.error(invalidMethods.get(i));
|
||||
}
|
||||
throw new IllegalArgumentException("Encountered" + i + "invalid methods. " + invalidMethods.get(i));
|
||||
throw new IllegalArgumentException(
|
||||
"Encountered " + invalidMethods.size()
|
||||
+ " invalid methods.\n - "
|
||||
+ String.join("\n - ", invalidMethods));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,17 @@ public class AutoEventBus {
|
||||
}
|
||||
|
||||
Event event = getCachedEvent(EventBusUtil.getParameterClassName(method.desc));
|
||||
if (INVALID_EVENT.equals(event)) continue;
|
||||
if (event == INVALID_EVENT) {
|
||||
continue;
|
||||
} else if (event == NOT_AN_EVENT) {
|
||||
EventBusUtil.invalidMethods.add(
|
||||
"Invalid event handler method: " + method.declaringClass
|
||||
+ " "
|
||||
+ method.name
|
||||
+ method.desc
|
||||
+ ". The parameter of an event handler method must extend cpw.mods.fml.common.eventhandler.Event");
|
||||
continue;
|
||||
}
|
||||
|
||||
StaticASMEventHandler listener = new StaticASMEventHandler(method);
|
||||
for (EventBusType bus : EventBusType.VALUES) {
|
||||
@@ -153,6 +163,9 @@ public class AutoEventBus {
|
||||
return eventCache.computeIfAbsent(eventClass, e -> {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(eventClass, false, Loader.instance().getModClassLoader());
|
||||
|
||||
if (!Event.class.isAssignableFrom(clazz)) return NOT_AN_EVENT;
|
||||
|
||||
return (Event) ConstructorUtils.invokeConstructor(clazz);
|
||||
} catch (NoClassDefFoundError | ExceptionInInitializerError | Exception ex) {
|
||||
// Event was likely for a mod that is not loaded or an invalid side.
|
||||
@@ -168,6 +181,10 @@ public class AutoEventBus {
|
||||
try {
|
||||
MethodHandle handle = MethodHandles.publicLookup()
|
||||
.findStatic(clazz, condition.substring(0, condition.indexOf("(")), CONDITION_TYPE);
|
||||
|
||||
// Note: `LambdaMetafactory` allows us to run the method without loading the full class, so if any of the
|
||||
// event handlers use event classes that are not present on the class path, we don't crash the game by
|
||||
// loading them before testing the `@EventBusSubscriber.Condition`.
|
||||
CallSite call = LambdaMetafactory.metafactory(
|
||||
LOOKUP,
|
||||
"getAsBoolean",
|
||||
|
||||
@@ -17,21 +17,16 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectList;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectSet;
|
||||
import lombok.Getter;
|
||||
|
||||
public final class EventBusUtil {
|
||||
|
||||
public static final Boolean DEBUG_EVENT_BUS = Boolean.getBoolean("gtnhlib.debug.eventbus");
|
||||
public static final boolean DEBUG_EVENT_BUS = Boolean.getBoolean("gtnhlib.debug.eventbus");
|
||||
private static final String CURRENT_SIDE = FMLLaunchHandler.side().name();
|
||||
|
||||
@Getter
|
||||
private static final ObjectSet<String> classesToVisit = new ObjectOpenHashSet<>();
|
||||
@Getter
|
||||
private static final Object2ObjectMap<String, ObjectSet<MethodInfo>> methodsToSubscribe = new Object2ObjectOpenHashMap<>();
|
||||
@Getter
|
||||
private static final Object2ObjectMap<String, String> conditionsToCheck = new Object2ObjectOpenHashMap<>();
|
||||
@Getter
|
||||
private static final ObjectList<String> invalidMethods = new ObjectArrayList<>();
|
||||
public static final ObjectSet<String> classesToVisit = new ObjectOpenHashSet<>();
|
||||
public static final Object2ObjectMap<String, ObjectSet<MethodInfo>> methodsToSubscribe = new Object2ObjectOpenHashMap<>();
|
||||
public static final Object2ObjectMap<String, String> conditionsToCheck = new Object2ObjectOpenHashMap<>();
|
||||
public static final ObjectList<String> invalidMethods = new ObjectArrayList<>();
|
||||
|
||||
static String getParameterClassInternal(String desc) {
|
||||
return desc.substring(desc.indexOf("(") + 2, desc.indexOf(";"));
|
||||
@@ -47,7 +42,7 @@ public final class EventBusUtil {
|
||||
|
||||
public static void harvestData(ASMDataTable table) {
|
||||
Set<ASMDataTable.ASMData> asmData = table.getAll(EventBusSubscriber.class.getName());
|
||||
ObjectSet<String> excludedClasses = getExcludedClasses(table);;
|
||||
ObjectSet<String> excludedClasses = getExcludedClasses(table);
|
||||
for (ASMDataTable.ASMData data : asmData) {
|
||||
Map<String, Object> info = data.getAnnotationInfo();
|
||||
String className = data.getClassName();
|
||||
@@ -99,4 +94,5 @@ public final class EventBusUtil {
|
||||
|
||||
return !StringUtils.containsIgnoreCase(className, "client") && !side.equals("CLIENT");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
package com.gtnewhorizon.gtnhlib.eventbus;
|
||||
|
||||
import static org.objectweb.asm.Opcodes.*;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_SUPER;
|
||||
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||
import static org.objectweb.asm.Opcodes.CHECKCAST;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V1_6;
|
||||
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
@@ -9,7 +16,6 @@ import org.objectweb.asm.Type;
|
||||
import cpw.mods.fml.common.eventhandler.Event;
|
||||
import cpw.mods.fml.common.eventhandler.EventPriority;
|
||||
import cpw.mods.fml.common.eventhandler.IEventListener;
|
||||
import lombok.Getter;
|
||||
|
||||
public class StaticASMEventHandler implements IEventListener {
|
||||
|
||||
@@ -22,7 +28,6 @@ public class StaticASMEventHandler implements IEventListener {
|
||||
private final IEventListener handler;
|
||||
private final String readable;
|
||||
private final boolean receiveCanceled;
|
||||
@Getter
|
||||
private final EventPriority priority;
|
||||
|
||||
StaticASMEventHandler(MethodInfo method) throws Exception {
|
||||
@@ -88,6 +93,10 @@ public class StaticASMEventHandler implements IEventListener {
|
||||
EventBusUtil.getSimpleClassName(param));
|
||||
}
|
||||
|
||||
public EventPriority getPriority() {
|
||||
return this.priority;
|
||||
}
|
||||
|
||||
private static class ASMClassLoader extends ClassLoader {
|
||||
|
||||
private ASMClassLoader() {
|
||||
|
||||
Reference in new issue
Block a user