/Test/Mono.Cecil.Tests/ILProcessorTests.cs

http://github.com/jbevain/cecil · C# · 103 lines · 76 code · 27 blank · 0 comment · 2 complexity · 4a22cca0703e1e2310f1e647a5c219b8 MD5 · raw file

  1. using System;
  2. using System.Linq;
  3. using Mono.Cecil;
  4. using Mono.Cecil.Cil;
  5. using NUnit.Framework;
  6. namespace Mono.Cecil.Tests {
  7. [TestFixture]
  8. public class ILProcessorTests : BaseTestFixture {
  9. [Test]
  10. public void Append ()
  11. {
  12. var method = CreateTestMethod ();
  13. var il = method.GetILProcessor ();
  14. var ret = il.Create (OpCodes.Ret);
  15. il.Append (ret);
  16. AssertOpCodeSequence (new [] { OpCodes.Ret }, method);
  17. }
  18. [Test]
  19. public void InsertBefore ()
  20. {
  21. var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
  22. var il = method.GetILProcessor ();
  23. var ldloc_2 = method.Instructions.Where (i => i.OpCode == OpCodes.Ldloc_2).First ();
  24. il.InsertBefore (
  25. ldloc_2,
  26. il.Create (OpCodes.Ldloc_1));
  27. AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
  28. }
  29. [Test]
  30. public void InsertAfter ()
  31. {
  32. var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
  33. var il = method.GetILProcessor ();
  34. var ldloc_0 = method.Instructions.First ();
  35. il.InsertAfter (
  36. ldloc_0,
  37. il.Create (OpCodes.Ldloc_1));
  38. AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
  39. }
  40. [Test]
  41. public void InsertAfterUsingIndex ()
  42. {
  43. var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
  44. var il = method.GetILProcessor ();
  45. il.InsertAfter (
  46. 0,
  47. il.Create (OpCodes.Ldloc_1));
  48. AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
  49. }
  50. [Test]
  51. public void ReplaceUsingIndex ()
  52. {
  53. var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
  54. var il = method.GetILProcessor ();
  55. il.Replace (1, il.Create (OpCodes.Nop));
  56. AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_3 }, method);
  57. }
  58. static void AssertOpCodeSequence (OpCode [] expected, MethodBody body)
  59. {
  60. var opcodes = body.Instructions.Select (i => i.OpCode).ToArray ();
  61. Assert.AreEqual (expected.Length, opcodes.Length);
  62. for (int i = 0; i < opcodes.Length; i++)
  63. Assert.AreEqual (expected [i], opcodes [i]);
  64. }
  65. static MethodBody CreateTestMethod (params OpCode [] opcodes)
  66. {
  67. var method = new MethodDefinition {
  68. Name = "function",
  69. };
  70. var il = method.Body.GetILProcessor ();
  71. foreach (var opcode in opcodes)
  72. il.Emit (opcode);
  73. return method.Body;
  74. }
  75. }
  76. }