package noppes.npcs.janino; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.janino.annotations.ScriptHook; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.stream.Collectors; /** * Resolves script hook methods for a given interface type using runtime * argument values. Resolution favors exact matches and then the "closest" * assignable parameter types (measured by inheritance distance). * * The resolver keeps simple caches for previously resolved signatures and * supports mapping enum-based hook names (via the {@code @ScriptHook} * annotation) to methods. * *

Dynamic Hook Support

* This resolver supports two modes: * * Use {@link #resolveHookMethod(String, Object[], Object)} to search the compiled instance. */ public final class JaninoHookResolver { private final Class interfaceType; /* Methods explicitly mapped from EnumScriptType via @ScriptHook */ private final Map enumHookLookup = new HashMap<>(); /** * Cache for resolved hook methods. Keys are generated by {@link #buildSignatureKey} * and represent the unique combination of hook name and runtime argument types. * This avoids expensive recursive reflection lookups on every hook call. */ private final Map signatureCache = new HashMap<>(); /** * Cache for methods found on compiled classes (keyed by class + signature). * Separate from signatureCache to handle recompilation. */ private final Map compiledClassCache = new HashMap<>(); /** * Track which compiled class we've cached methods for. * If the class changes (recompilation), we clear the cache. */ private Class lastCompiledClass; /* Lazily built list of available hooks and a mapping for display names */ private boolean hookListInitialized; /* List of names displayed in GUI hooks list (accounts for overload names) */ private final List displayHookList = new ArrayList<>(); /* Display name -> Method map */ private final Map displayHookMethods = new HashMap<>(); /** * Create a resolver for the provided script interface type. * @param interfaceType non-null interface class that scripts implement */ public JaninoHookResolver(Class interfaceType) { this.interfaceType = Objects.requireNonNull(interfaceType, "interfaceType"); initializeEnumHookMethods(); } /** * Clears internal resolution caches so future calls perform fresh * method resolution. Call when scripts or available methods change. */ public void clearResolutionCaches() { signatureCache.clear(); compiledClassCache.clear(); lastCompiledClass = null; } /** * Resolve a hook method by name and runtime argument values (interface-only mode). * * This first checks any enum-mapped methods (via {@code @ScriptHook}), * then a signature-based cache and finally attempts full candidate * resolution using {@link #resolveHookMethodInternal}. * * @param hookName hook method name (or enum function name) * @param args runtime arguments to use for overload resolution * @return the resolved {@link Method} or {@code null} if none matched */ public Method resolveHookMethod(String hookName, Object[] args) { return resolveHookMethod(hookName, args, null); } /** * Resolve a hook method by name, searching both the compiled class and interface. * *

This enables dynamic hook support: users can define methods for any hook * (Forge events, addon hooks, etc.) without needing them in the interface definition.

* *

Resolution order:

*
    *
  1. Enum-mapped methods (via {@code @ScriptHook})
  2. *
  3. Compiled class methods (user-defined, including custom hooks)
  4. *
  5. Interface methods (base hooks with defaults)
  6. *
  7. Fallback to no-arg versions
  8. *
* *

Performance: Method lookups are cached. First call per hook does reflection * (~microseconds), subsequent calls use cache (essentially free).

* * @param hookName hook method name (or enum function name) * @param args runtime arguments to use for overload resolution * @param compiledInstance the compiled script instance (or null for interface-only) * @return the resolved {@link Method} or {@code null} if none matched */ public Method resolveHookMethod(String hookName, Object[] args, Object compiledInstance) { if (hookName == null || hookName.isEmpty()) return null; // 1. Check enum-mapped methods first (fastest path) Method method = enumHookLookup.get(hookName); if (method != null) return method; Object[] safeArgs = args == null ? new Object[0] : args; String signatureKey = buildSignatureKey(hookName, safeArgs); // 2. If we have a compiled instance, search its class first if (compiledInstance != null) { Class compiledClass = compiledInstance.getClass(); // Clear cache if compiled class changed (recompilation) if (lastCompiledClass != compiledClass) { compiledClassCache.clear(); lastCompiledClass = compiledClass; } // Check compiled class cache method = compiledClassCache.get(signatureKey); if (method != null) return method; // Search compiled class for matching method method = resolveHookMethodInternal(compiledClass, hookName, safeArgs); if (method != null) { compiledClassCache.put(signatureKey, method); return method; } // Try no-arg version on compiled class String noArgKey = buildSignatureKey(hookName, new Object[0]); method = compiledClassCache.get(noArgKey); if (method != null) return method; method = resolveHookMethodInternal(compiledClass, hookName, new Object[0]); if (method != null) { compiledClassCache.put(noArgKey, method); return method; } } // 3. Fall back to interface-only search method = signatureCache.get(signatureKey); if (method != null) return method; method = resolveHookMethodInternal(interfaceType, hookName, safeArgs); if (method != null) { signatureCache.put(signatureKey, method); return method; } String noArgSignatureKey = buildSignatureKey(hookName, new Object[0]); method = signatureCache.get(noArgSignatureKey); if (method != null) return method; method = resolveHookMethodInternal(interfaceType, hookName, new Object[0]); if (method != null) { signatureCache.put(noArgSignatureKey, method); return method; } return null; } /** * Returns an immutable copy of the available hook display names. */ public List getDisplayHookList() { ensureHookListCreated(); return new ArrayList<>(displayHookList); } public Method getMethodForDisplayName(String displayName) { if (displayName == null || displayName.isEmpty()) return null; ensureHookListCreated(); return displayHookMethods.get(displayName); } /** * Builds the human-readable hook list and display-name -> Method map. * The list is computed lazily on first access and cached. */ private void ensureHookListCreated() { if (hookListInitialized) return; Map> grouped = Arrays.stream(interfaceType.getDeclaredMethods()) .collect(Collectors.groupingBy(Method::getName)); for (Map.Entry> entry : grouped.entrySet()) { List methods = entry.getValue(); methods.sort(Comparator.comparingInt(Method::getParameterCount)); boolean first = true; for (Method m : methods) { if (Modifier.isFinal(m.getModifiers())) continue; String displayName = first ? m.getName() : m.getName() + "(" + Arrays.stream(m.getParameterTypes()) .map(Class::getSimpleName) .collect(Collectors.joining(", ")) + ")"; displayHookList.add(displayName); displayHookMethods.put(displayName, m); first = false; } } hookListInitialized = true; } /** * Maps EnumScriptType common names to their respective methods using * the {@code @ScriptHook} annotation. */ private void initializeEnumHookMethods() { for (Method method : interfaceType.getDeclaredMethods()) { ScriptHook annotation = method.getAnnotation(ScriptHook.class); if (annotation == null) continue; for (EnumScriptType hookType : annotation.value()) { enumHookLookup.put(hookType.function, method); } } } /** * Build a cache key for a hook name and runtime argument list. This key * encodes the runtime classes of the provided arguments and is used for * quick cache lookups. Note: keys are based on concrete runtime classes * which may cause fragmentation when many subclasses are used. * * @param hookName hook name * @param args runtime arguments * @return a string key representing the hook signature */ public static String buildSignatureKey(String hookName, Object[] args) { StringBuilder sb = new StringBuilder(); sb.append(hookName).append('#'); if (args == null || args.length == 0) return sb.append('0').toString(); sb.append(args.length).append(':'); for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (i > 0) sb.append(','); sb.append(arg == null ? "null" : arg.getClass().getName()); } return sb.toString(); } /** * Internal resolution routine. Attempts to find the best matching method * on the provided class by comparing parameter counts and a simple * match scoring function (see {@link #scoreMethodMatch}). * *

This searches all public methods (including inherited) to support * both interface-defined hooks and user-defined custom methods.

* * @param targetClass the class to search (interface or compiled class) * @param hookName the method name to find * @param args runtime arguments for overload resolution * @return the best matching method, or null if none found */ private static Method resolveHookMethodInternal(Class targetClass, String hookName, Object[] args) { Object[] safeArgs = args == null ? new Object[0] : args; Method best = null; int bestScore = Integer.MAX_VALUE; // Use getMethods() to include inherited methods (important for compiled classes) for (Method method : targetClass.getMethods()) { if (!method.getName().equals(hookName)) continue; // Skip final methods and Object methods if (Modifier.isFinal(method.getModifiers())) continue; if (method.getDeclaringClass() == Object.class) continue; Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length != safeArgs.length) continue; int score = scoreMethodMatch(paramTypes, safeArgs); if (score == Integer.MAX_VALUE) continue; if (score < bestScore) { bestScore = score; best = method; if (score == 0) return best; } } return best; } /** * Score how well a method's parameter types match the provided runtime * arguments. Lower scores are better; {@link Integer#MAX_VALUE} indicates * an incompatible parameter. * * @param paramTypes method parameter types * @param args runtime argument values * @return score (lower is better) or Integer.MAX_VALUE for no match */ private static int scoreMethodMatch(Class[] paramTypes, Object[] args) { int score = 0; for (int i = 0; i < paramTypes.length; i++) { Class paramType = paramTypes[i]; Object arg = args[i]; if (arg == null) { if (paramType.isPrimitive()) return Integer.MAX_VALUE; score += 1; continue; } Class argType = arg.getClass(); Class boxedParam = boxType(paramType); if (boxedParam.equals(argType)) continue; if (boxedParam.isAssignableFrom(argType)) { score += inheritanceDistance(argType, boxedParam); continue; } return Integer.MAX_VALUE; } return score; } private static Class boxType(Class type) { if (!type.isPrimitive()) return type; if (type == boolean.class) return Boolean.class; if (type == byte.class) return Byte.class; if (type == short.class) return Short.class; if (type == int.class) return Integer.class; if (type == long.class) return Long.class; if (type == float.class) return Float.class; if (type == double.class) return Double.class; if (type == char.class) return Character.class; return type; } /** * Compute a simple inheritance distance between a child and parent class * by walking superclasses. Returns a large value if {@code parent} is * not assignable from {@code child}. * * Note: the matching algorithm uses superclass traversal to compute a * distance metric; interface inheritance is not explored which can make * matches against interfaces less optimal. Consider improving * `inheritanceDistance` if interface-based scoring is required. */ private static int inheritanceDistance(Class child, Class parent) { if (child.equals(parent)) return 0; if (!parent.isAssignableFrom(child)) return 1000; int distance = 0; Class current = child; while (current != null && !current.equals(parent)) { current = current.getSuperclass(); distance++; } return distance; } }