Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method overloading support in script api #5242

Merged
merged 4 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,32 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Pseudo
@Mixin(targets = "com/oracle/truffle/host/HostClassDesc$Members")
public abstract class MixinHostClassDesc {

@Unique
private static Method mergeMethod;

@Unique
private static Method getMergeMethod() {
if (mergeMethod == null) {
try {
Class<?> hostMethodDescClass = Class.forName("com.oracle.truffle.host.HostMethodDesc");
mergeMethod = Class.forName("com.oracle.truffle.host.HostClassDesc$Members")
.getDeclaredMethod("merge", hostMethodDescClass, hostMethodDescClass);
mergeMethod.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException("Failed to get merge method", e);
}
}
return mergeMethod;
}

@Shadow(remap = false)
@Final
Map<String, Object> methods;
Expand All @@ -53,16 +72,76 @@ public abstract class MixinHostClassDesc {
@Final
Map<String, Object> staticMethods;


@Inject(method = "<init>", at = @At("RETURN"), remap = false)
private void remapClassDesc(CallbackInfo ci) {
remapEntries(methods, this::getMethod);
remapEntries(fields, this::getField);
remapEntries(staticFields, this::getField);
remapEntries(staticMethods, this::getMethod);
remapFieldEntries(fields, this::getField);
remapFieldEntries(staticFields, this::getField);

remapMethodEntries(methods);
remapMethodEntries(staticMethods);
}

@Unique
private void remapMethodEntries(Map<String, Object> map) {
final var entries = new HashMap<>(map).entrySet();

for (var entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
try {
// this is a bit more complicated than fields because of overloads

final var methodsToRemap = new ArrayList<Method>();

try {
// value instanceof HostMethodDesc.SingleMethod
methodsToRemap.add(getReflectionMethodFromSingleMethod(value));
} catch (NoSuchMethodException _ignored) {
// value instanceof HostMethodDesc.OverloadedMethod
// which probably should not happen because intermediary names have no overloads?
final Method getOverloads = value.getClass().getDeclaredMethod("getOverloads");
getOverloads.setAccessible(true);
final var overloads = (Object[]) getOverloads.invoke(value);

for (final var overload : overloads) {
methodsToRemap.add(getReflectionMethodFromSingleMethod(overload));
}
}

for (final Method method : methodsToRemap) {
final String remappedName = remapDescriptor(method);

if (remappedName != null) {
if (map.containsKey(remappedName)) {
final Object mergedMethod = getMergeMethod().invoke(null, map.get(remappedName), value);
map.remove(key);
map.put(remappedName, mergedMethod);

} else {
map.remove(key);
map.put(remappedName, value);
}
}
}


} catch (Exception e) {
ClientUtilsKt.getLogger().error("Failed to remap method: {}", key, e);
}
}
}

@Unique
private void remapEntries(Map<String, Object> map, MemberRetriever retriever) {
private static Method getReflectionMethodFromSingleMethod(Object value)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
final Method descMethod = value.getClass().getDeclaredMethod("getReflectionMethod");
descMethod.setAccessible(true);
return (Method) descMethod.invoke(value);
}

@Unique
private void remapFieldEntries(Map<String, Object> map, MemberRetriever retriever) {
var entries = new HashMap<>(map).entrySet();

for (var entry : entries) {
Expand All @@ -74,7 +153,7 @@ private void remapEntries(Map<String, Object> map, MemberRetriever retriever) {
Member member = retriever.getMember(value);
remapped = remapDescriptor(member);
} catch (ReflectiveOperationException e) {
ClientUtilsKt.getLogger().error("Failed to remap: {}", key, e);
ClientUtilsKt.getLogger().error("Failed to remap field: {}", key, e);
continue;
}

Expand All @@ -85,28 +164,6 @@ private void remapEntries(Map<String, Object> map, MemberRetriever retriever) {
}
}

@Unique
private Member getMethod(Object o) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
try {
// If this works, it is likely a SingleMethod instance
Method descMethod = o.getClass().getDeclaredMethod("getReflectionMethod");

descMethod.setAccessible(true);
return (Member) descMethod.invoke(o);
} catch (NoSuchMethodException ignored) {
try {
var getOverloads = o.getClass().getDeclaredMethod("getOverloads");
var overloads = (Object[]) getOverloads.invoke(o);

return getMethod(overloads[0]);
} catch (NoSuchMethodException ignored2) {
ClientUtilsKt.getLogger().error("Unsupported method type: {}", o.getClass().getName());
}

return null;
}
}

@Unique
private Member getField(Object o) throws IllegalAccessException, NoSuchFieldException {
var descField = o.getClass().getDeclaredField("field");
Expand Down
76 changes: 44 additions & 32 deletions src/main/kotlin/net/ccbluex/liquidbounce/config/types/Value.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ import net.ccbluex.liquidbounce.utils.client.logger
import net.ccbluex.liquidbounce.utils.client.toLowerCamelCase
import net.ccbluex.liquidbounce.utils.input.HumanInputDeserializer
import net.ccbluex.liquidbounce.utils.input.InputBind
import net.ccbluex.liquidbounce.utils.input.inputByName
import net.ccbluex.liquidbounce.utils.inventory.findBlocksEndingWith
import net.ccbluex.liquidbounce.utils.kotlin.mapArray
import net.minecraft.client.util.InputUtil
import net.minecraft.registry.Registries
import net.minecraft.util.Identifier
import java.awt.Color
import java.util.*
import java.util.function.Supplier
import kotlin.reflect.KProperty
Expand All @@ -59,7 +65,8 @@ open class Value<T : Any>(
@Exclude @ProtocolExclude var independentDescription: Boolean = false
) {

@SerializedName("value") internal var inner: T = defaultValue
@SerializedName("value")
internal var inner: T = defaultValue

internal val loweredName
get() = name.lowercase()
Expand Down Expand Up @@ -163,6 +170,10 @@ open class Value<T : Any>(
(a.first().toFloat()..a.last().toFloat()) as T
}

is InputUtil.Key -> {
inputByName(t.asString()) as T
}

is IntRange -> {
val a = t.`as`(Array<Int>::class.java)
require(a.size == 2)
Expand All @@ -178,7 +189,7 @@ open class Value<T : Any>(
}
)
}.onFailure {
logger.error("Could not set value ${this.inner}")
logger.error("Could not set value, old value: ${this.inner}, throwable: $it")
}

fun get() = inner
Expand Down Expand Up @@ -252,41 +263,42 @@ open class Value<T : Any>(
open fun deserializeFrom(gson: Gson, element: JsonElement) {
val currValue = this.inner

set(when (currValue) {
is List<*> -> {
@Suppress("UNCHECKED_CAST") element.asJsonArray.mapTo(
mutableListOf()
) { gson.fromJson(it, this.listType.type!!) } as T
}

is HashSet<*> -> {
@Suppress("UNCHECKED_CAST") element.asJsonArray.mapTo(
HashSet()
) { gson.fromJson(it, this.listType.type!!) } as T
}
set(
when (currValue) {
is List<*> -> {
@Suppress("UNCHECKED_CAST") element.asJsonArray.mapTo(
mutableListOf()
) { gson.fromJson(it, this.listType.type!!) } as T
}

is Set<*> -> {
@Suppress("UNCHECKED_CAST") element.asJsonArray.mapTo(
TreeSet()
) { gson.fromJson(it, this.listType.type!!) } as T
}
is HashSet<*> -> {
@Suppress("UNCHECKED_CAST") element.asJsonArray.mapTo(
HashSet()
) { gson.fromJson(it, this.listType.type!!) } as T
}

else -> {
var clazz: Class<*>? = currValue.javaClass
var r: T? = null
is Set<*> -> {
@Suppress("UNCHECKED_CAST") element.asJsonArray.mapTo(
TreeSet()
) { gson.fromJson(it, this.listType.type!!) } as T
}

while (clazz != null && clazz != Any::class.java) {
try {
r = gson.fromJson(element, clazz) as T?
break
} catch (@Suppress("SwallowedException") e: ClassCastException) {
clazz = clazz.superclass
else -> {
var clazz: Class<*>? = currValue.javaClass
var r: T? = null

while (clazz != null && clazz != Any::class.java) {
try {
r = gson.fromJson(element, clazz) as T?
break
} catch (@Suppress("SwallowedException") e: ClassCastException) {
clazz = clazz.superclass
}
}
}

r ?: error("Failed to deserialize value")
}
})
r ?: error("Failed to deserialize value")
}
})
}

open fun setByString(string: String) {
Expand Down
Loading