Skip to content

Commit 9478a16

Browse files
authored
Add insertInsn() methods to ASMAPI (#62)
Sisters to insertInsnList(), but used for single instructions as opposed to entire lists
1 parent c95067a commit 9478a16

File tree

1 file changed

+42
-0
lines changed
  • src/main/java/net/minecraftforge/coremod/api

1 file changed

+42
-0
lines changed

src/main/java/net/minecraftforge/coremod/api/ASMAPI.java

+42
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,48 @@ public static boolean insertInsnList(MethodNode method, AbstractInsnNode insn, I
508508
return true;
509509
}
510510

511+
/**
512+
* Inserts/replaces an instruction after/before first {@link MethodInsnNode} that matches the parameters of these
513+
* functions in the method provided. Only the first node matching is targeted, all other matches are ignored.
514+
*
515+
* @param method The method where you want to find the node
516+
* @param type The type of the old method node
517+
* @param owner The owner of the old method node
518+
* @param name The name of the old method node (you may want to use {@link #mapMethod(String)} if this is a srg
519+
* name)
520+
* @param desc The desc of the old method node
521+
* @param toInsert The instruction that should be inserted
522+
* @param mode How the given code should be inserted
523+
* @return True if the node was found and the list was inserted, false otherwise
524+
*/
525+
public static boolean insertInsn(MethodNode method, MethodType type, String owner, String name, String desc, AbstractInsnNode toInsert, InsertMode mode) {
526+
var insn = findFirstMethodCall(method, type, owner, name, desc);
527+
if (insn == null) return false;
528+
529+
return insertInsn(method, insn, toInsert, mode);
530+
}
531+
532+
/**
533+
* Inserts/replaces an instruction after/before the given instruction.
534+
*
535+
* @param method The method where you want to insert the list
536+
* @param insn The instruction where the new instruction should be inserted into
537+
* @param toInsert The instruction that should be inserted
538+
* @param mode How the given code should be inserted
539+
* @return True if the list was inserted, false otherwise
540+
*/
541+
public static boolean insertInsn(MethodNode method, AbstractInsnNode insn, AbstractInsnNode toInsert, InsertMode mode) {
542+
if (!method.instructions.contains(insn)) return false;
543+
544+
switch (mode) {
545+
case INSERT_BEFORE -> method.instructions.insertBefore(insn, toInsert);
546+
case INSERT_AFTER -> method.instructions.insert(insn, toInsert);
547+
case REMOVE_ORIGINAL -> method.instructions.set(insn, toInsert);
548+
}
549+
550+
return true;
551+
}
552+
511553
/**
512554
* Builds a new {@link InsnList} out of the specified {@link AbstractInsnNode}s.
513555
*

0 commit comments

Comments
 (0)