From d560c23241c9ae35e17e8fec9edb351d3af86449 Mon Sep 17 00:00:00 2001 From: Kam Date: Thu, 22 Jan 2026 22:01:13 -0500 Subject: [PATCH] @ParamName support for Hook Definitions in Overlay Scripts --- .../npcs/controllers/HookDefinition.java | 63 ++++++++++ .../java/noppes/npcs/janino/JaninoScript.java | 116 +++++++++++++++++- 2 files changed, 177 insertions(+), 2 deletions(-) diff --git a/src/main/java/noppes/npcs/controllers/HookDefinition.java b/src/main/java/noppes/npcs/controllers/HookDefinition.java index b5a61ceab..9d8c34fa6 100644 --- a/src/main/java/noppes/npcs/controllers/HookDefinition.java +++ b/src/main/java/noppes/npcs/controllers/HookDefinition.java @@ -2,6 +2,10 @@ package noppes.npcs.controllers; import cpw.mods.fml.common.eventhandler.Cancelable; import noppes.npcs.api.handler.IHookDefinition; +import noppes.npcs.janino.annotations.ParamName; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; /** * Implementation of {@link IHookDefinition} with a fluent builder API. @@ -121,6 +125,65 @@ public class HookDefinition implements IHookDefinition { return new Builder(hookName); } + /** + * Create a hook definition from an interface method. + * Automatically extracts metadata from the method signature and @ParamName annotations. + * This provides backward compatibility with the annotation-based hook definition approach. + * + * @param hookName The hook name (may differ from method name) + * @param method The method to extract metadata from + * @return A hook definition with extracted metadata + */ + public static HookDefinition fromMethod(String hookName, Method method) { + Builder builder = builder(hookName); + + // Extract event type from first parameter + if (method.getParameterCount() > 0) { + Class eventType = method.getParameterTypes()[0]; + builder.eventClass(eventType); + + // Auto-detect cancelable from event class + if (eventType.isAnnotationPresent(Cancelable.class)) { + builder.cancelable(true); + } + + // Build required imports from event type + String importName = getImportForClass(eventType); + if (importName != null) { + builder.requiredImports(importName); + } + } + + // Extract parameter names from @ParamName annotations + Parameter[] params = method.getParameters(); + if (params.length > 0) { + String[] names = new String[params.length]; + for (int i = 0; i < params.length; i++) { + ParamName annotation = params[i].getAnnotation(ParamName.class); + if (annotation != null) { + names[i] = annotation.value(); + } else { + // Fallback: use lowercase simple type name + names[i] = Character.toLowerCase(params[i].getType().getSimpleName().charAt(0)) + + params[i].getType().getSimpleName().substring(1); + } + } + builder.paramNames(names); + } + + return builder.build(); + } + + /** + * Create a hook definition from a method using its name as the hook name. + * + * @param method The method to extract metadata from + * @return A hook definition with extracted metadata + */ + public static HookDefinition fromMethod(Method method) { + return fromMethod(method.getName(), method); + } + /** * Get the import statement needed for a class. * For nested classes, returns the enclosing class. diff --git a/src/main/java/noppes/npcs/janino/JaninoScript.java b/src/main/java/noppes/npcs/janino/JaninoScript.java index 1deda1a94..46d0bf164 100644 --- a/src/main/java/noppes/npcs/janino/JaninoScript.java +++ b/src/main/java/noppes/npcs/janino/JaninoScript.java @@ -8,6 +8,8 @@ import noppes.npcs.CustomNpcs; import noppes.npcs.NBTTags; import noppes.npcs.api.handler.IHookDefinition; import noppes.npcs.config.ConfigScript; +import noppes.npcs.controllers.HookDefinition; +import noppes.npcs.janino.annotations.ParamName; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; @@ -17,6 +19,8 @@ import org.codehaus.commons.compiler.InternalCompilerException; import org.codehaus.commons.compiler.Sandbox; import java.lang.invoke.MethodHandle; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.security.Permissions; import java.security.PrivilegedAction; import java.util.*; @@ -256,15 +260,29 @@ public abstract class JaninoScript implements IScriptUnit { } public List getHookList() { + Set hooks = new LinkedHashSet<>(); + + // 1. Add hooks from ScriptHookController (new system) String context = getHookContext(); if (context != null && !context.isEmpty() && ScriptHookController.Instance != null) { - return ScriptHookController.Instance.getAllHooks(context); + hooks.addAll(ScriptHookController.Instance.getAllHooks(context)); } - return Collections.emptyList(); + + // 2. Add methods from interface type (backward compatibility with @ParamName) + if (type != null) { + for (Method m : type.getDeclaredMethods()) { + if (!Modifier.isFinal(m.getModifiers()) && !hooks.contains(m.getName())) { + hooks.add(m.getName()); + } + } + } + + return new ArrayList<>(hooks); } @Override public String generateHookStub(String hookName, Object hookData) { + // 1. Try HookDefinition from registry (new system) IHookDefinition def = getHookDefinition(hookName); if (def != null) { String typeName = def.getUsableTypeName(); @@ -276,9 +294,103 @@ public abstract class JaninoScript implements IScriptUnit { def.hookName(), typeName, paramName); } } + + // 2. Fallback: Try interface method with @ParamName (backward compatibility) + Method method = findInterfaceMethod(hookName); + if (method != null) { + return generateMethodStub(method); + } + + // 3. Final fallback: generic stub return String.format("public void %s(Object event) {\n \n}\n", hookName); } + /** + * Find a method in the type interface by name. + */ + private Method findInterfaceMethod(String methodName) { + if (type == null || methodName == null) return null; + + for (Method m : type.getDeclaredMethods()) { + if (m.getName().equals(methodName) && !Modifier.isFinal(m.getModifiers())) { + return m; + } + } + return null; + } + + /** + * Generate a method stub from a Method, supporting @ParamName annotations. + * Provides backward compatibility with interface-based hook definitions. + */ + public static String generateMethodStub(Method method) { + String mods = Modifier.toString(method.getModifiers()); + mods = mods.replace("abstract ", "").replace("abstract", "") + .replace("default ", "").replace("default", "").trim(); + if (!mods.isEmpty()) mods += " "; + + String returnTypeStr = getUsableTypeName(method.getReturnType()); + String name = method.getName(); + + Map typeCount = new HashMap<>(); + StringBuilder params = new StringBuilder(); + for (int i = 0; i < method.getParameters().length; i++) { + java.lang.reflect.Parameter p = method.getParameters()[i]; + String typeName = getUsableTypeName(p.getType()); + + // Check for @ParamName annotation first + ParamName annotation = p.getAnnotation(ParamName.class); + String paramName; + if (annotation != null) { + paramName = annotation.value(); + } else { + // Fallback to generated name + String baseName = Character.toLowerCase(p.getType().getSimpleName().charAt(0)) + + p.getType().getSimpleName().substring(1); + int count = typeCount.getOrDefault(baseName, 0) + 1; + typeCount.put(baseName, count); + paramName = count == 1 ? baseName : baseName + (count - 1); + } + + if (i > 0) params.append(", "); + params.append(typeName).append(" ").append(paramName); + } + + String body; + Class returnType = method.getReturnType(); + if (returnType == void.class) { + body = ""; + } else if (returnType.isPrimitive()) { + if (returnType == boolean.class) body = " return false;"; + else if (returnType == char.class) body = " return '\\0';"; + else body = " return 0;"; + } else { + body = " return null;"; + } + + return String.format("%s%s %s(%s) {\n%s\n}\n", mods, returnTypeStr, name, params, body); + } + + /** + * Gets a usable type name for stub generation. + * For nested classes, returns "OuterClass.InnerClass" format. + */ + private static String getUsableTypeName(Class type) { + if (type.isPrimitive() || type.getEnclosingClass() == null) { + return type.getSimpleName(); + } + + // Build the nested class chain + StringBuilder sb = new StringBuilder(); + Class current = type; + while (current != null) { + if (sb.length() > 0) sb.insert(0, "."); + sb.insert(0, current.getSimpleName()); + current = current.getEnclosingClass(); + } + return sb.toString(); + } + // ==================== IScriptUnit ==================== @Override public String getScript() { return script; }