Skip to content

Commit

Permalink
Add LDC constant helper methods (#51)
Browse files Browse the repository at this point in the history
Add buildLdcInsnNode for dealing with specific number types
Add ldcInsnClassToString to get LDC constants class names
  • Loading branch information
Jonathing authored Oct 13, 2024
1 parent d4eca3c commit deac494
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/main/java/net/minecraftforge/coremod/api/ASMAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.ListIterator;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

/**
* Helper methods for working with ASM.
Expand Down Expand Up @@ -68,6 +69,37 @@ public static MethodInsnNode buildMethodCall(final String ownerName, final Strin
return new MethodInsnNode(type.toOpcode(), ownerName, methodName, methodDescriptor, type==MethodType.INTERFACE);
}

/**
* Signifies the type of number constant for a {@link LdcNumberType}.
*/
public enum LdcNumberType {
INTEGER(Number::intValue),
FLOAT(Number::floatValue),
LONG(Number::longValue),
DOUBLE(Number::doubleValue);

private final Function<Number, Object> mapper;

LdcNumberType(Function<Number, Object> mapper) {
this.mapper = mapper;
}

public Object map(Number number) {
return mapper.apply(number);
}
}

/**
* Builds a new {@link LdcInsnNode} with the given number value and type.
*
* @param value The number value
* @param type The type of the number
* @return The built LDC node
*/
public static LdcInsnNode buildNumberLdcInsnNode(final Number value, final LdcNumberType type) {
return new LdcInsnNode(type.map(value));
}

/**
* Maps a method from the given SRG name to the mapped name at deobfuscated runtime.
*
Expand Down Expand Up @@ -430,6 +462,16 @@ public static String methodNodeToString(MethodNode node) {
return toString(text);
}

/**
* Gets the LDC constant's class name as a string. Useful for debugging existing LDC instructions.
*
* @param insn The LDC instruction.
* @return The class name of the LDC constant.
*/
public static String ldcInsnClassToString(LdcInsnNode insn) {
return insn.cst.getClass().toString();
}

private static String toString(Textifier text) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Expand Down

0 comments on commit deac494

Please sign in to comment.