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