/src/LinFu.AOP/InstructionSwapper.cs

http://github.com/philiplaureano/LinFu · C# · 51 lines · 26 code · 4 blank · 21 comment · 1 complexity · a13ac3025a4f492910e26d2e7cb97959 MD5 · raw file

  1. using System.Collections.Generic;
  2. using LinFu.AOP.Cecil.Interfaces;
  3. using Mono.Cecil;
  4. using Mono.Cecil.Cil;
  5. namespace LinFu.AOP.Cecil
  6. {
  7. /// <summary>
  8. /// Provides the basic functionality for the <see cref="IMethodRewriter" /> interface.
  9. /// </summary>
  10. public abstract class InstructionSwapper : BaseMethodRewriter
  11. {
  12. /// <summary>
  13. /// Rewrites the instructions in the target method body.
  14. /// </summary>
  15. /// <param name="method">The target method.</param>
  16. /// <param name="IL">The <see cref="ILProcessor" /> instance that represents the method body.</param>
  17. /// <param name="oldInstructions">The IL instructions of the original method body.</param>
  18. protected override void RewriteMethodBody(MethodDefinition method, ILProcessor IL,
  19. IEnumerable<Instruction> oldInstructions)
  20. {
  21. var newInstructions = new Queue<Instruction>();
  22. foreach (var instruction in oldInstructions)
  23. {
  24. if (!ShouldReplace(instruction, method))
  25. {
  26. IL.Append(instruction);
  27. continue;
  28. }
  29. Replace(instruction, method, IL);
  30. }
  31. }
  32. /// <summary>
  33. /// Determines whether or not the method rewriter should replace the <paramref name="oldInstruction" />.
  34. /// </summary>
  35. /// <param name="oldInstruction">The instruction that is currently being evaluated.</param>
  36. /// <param name="hostMethod">The method that hosts the current instruction.</param>
  37. /// <returns><c>true</c> if the method should be replaced; otherwise, it should return <c>false</c>.</returns>
  38. protected abstract bool ShouldReplace(Instruction oldInstruction, MethodDefinition hostMethod);
  39. /// <summary>
  40. /// Replaces the <paramref name="oldInstruction" /> with a new set of <paramref name="IL" /> instructions..
  41. /// </summary>
  42. /// <param name="oldInstruction">The instruction currently being evaluated.</param>
  43. /// <param name="hostMethod">The method that contains the target instruction.</param>
  44. /// <param name="IL">The ILProcessor for the target method body.</param>
  45. protected abstract void Replace(Instruction oldInstruction, MethodDefinition hostMethod, ILProcessor IL);
  46. }
  47. }