Transpilers.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Reflection.Emit;
  5. namespace Harmony
  6. {
  7. public static class Transpilers
  8. {
  9. public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
  10. {
  11. if (from == null)
  12. throw new ArgumentException("Unexpected null argument", nameof(from));
  13. if (to == null)
  14. throw new ArgumentException("Unexpected null argument", nameof(to));
  15. foreach (var instruction in instructions)
  16. {
  17. var method = instruction.operand as MethodBase;
  18. if (method == from)
  19. {
  20. instruction.opcode = to.IsConstructor ? OpCodes.Newobj : OpCodes.Call;
  21. instruction.operand = to;
  22. }
  23. yield return instruction;
  24. }
  25. }
  26. public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
  27. {
  28. yield return new CodeInstruction(OpCodes.Ldstr, text);
  29. yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
  30. foreach (var instruction in instructions) yield return instruction;
  31. }
  32. // more added soon
  33. }
  34. }