Skip to content

Commit

Permalink
Fix generated event handlers for events on interfaces.
Browse files Browse the repository at this point in the history
  • Loading branch information
LexManos committed Dec 31, 2024
1 parent 913fb17 commit e0e273a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright (c) Forge Development LLC
* SPDX-License-Identifier: LGPL-2.1-only
*/

package net.minecraftforge.eventbus.test.general;

import java.util.function.Consumer;
import java.util.function.Supplier;

import net.minecraftforge.eventbus.api.BusBuilder;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.eventbus.test.ITestHandler;

import static org.junit.jupiter.api.Assertions.*;

public class InterfaceEventHandler implements ITestHandler {
private static boolean hit = false;

public InterfaceEventHandler(boolean hasTransformer) {
}

@Override
public void test(Consumer<Class<?>> validator, Supplier<BusBuilder> builder) {
var bus = builder.get().build();
assertDoesNotThrow(() -> bus.register(STATIC.class));
testCall(bus, true, "STATIC");
assertDoesNotThrow(() -> bus.register(new INSTANCE() {}));
testCall(bus, true, "STATIC");
}

private void testCall(IEventBus bus, boolean expected, String name) {
hit = false;
bus.post(new Event());
assertEquals(expected, hit, name + " did not behave correctly");
}

public interface STATIC {
@SubscribeEvent
static void handler(Event e) {
hit = true;
}
}

public interface INSTANCE {
@SubscribeEvent
default void handler(Event e) {
hit = true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ protected static void transformNode(String name, Method callback, ClassNode targ
MethodVisitor mv;

boolean isStatic = Modifier.isStatic(callback.getModifiers());
boolean isInterface = Modifier.isInterface(callback.getDeclaringClass().getModifiers());
String desc = name.replace('.', '/');
String instType = Type.getInternalName(callback.getDeclaringClass());
String eventType = Type.getInternalName(callback.getParameterTypes()[0]);
Expand Down Expand Up @@ -95,7 +96,14 @@ protected static void transformNode(String name, Method callback, ClassNode targ
}
mv.visitVarInsn(ALOAD, 1);
mv.visitTypeInsn(CHECKCAST, eventType);
mv.visitMethodInsn(isStatic ? INVOKESTATIC : INVOKEVIRTUAL, instType, callback.getName(), Type.getMethodDescriptor(callback), false);

var opcode = INVOKEVIRTUAL;
if (isStatic)
opcode = INVOKESTATIC;
else if (isInterface)
opcode = INVOKEINTERFACE;

mv.visitMethodInsn(opcode, instType, callback.getName(), Type.getMethodDescriptor(callback), isInterface);
mv.visitInsn(RETURN);
mv.visitMaxs(2, 2);
mv.visitEnd();
Expand Down

0 comments on commit e0e273a

Please sign in to comment.