From 31fefe1c6eb8289866b033c60e8d183c9e189b30 Mon Sep 17 00:00:00 2001 From: Kvachuk Grigorii Date: Mon, 3 Dec 2018 22:58:43 +0300 Subject: [PATCH] Fix try/catch/finally il code generation --- src/Pose/IL/MethodRewriter.cs | 16 +++++++-------- test/Pose.Tests/IL/MethodRewriterTests.cs | 24 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/Pose/IL/MethodRewriter.cs b/src/Pose/IL/MethodRewriter.cs index 48546d3..848a62f 100644 --- a/src/Pose/IL/MethodRewriter.cs +++ b/src/Pose/IL/MethodRewriter.cs @@ -169,14 +169,6 @@ private void EmitILForExceptionHandlers(ILGenerator ilGenerator, Instruction ins ilGenerator.BeginExceptionBlock(); } - foreach (var handler in handlers.Where(h => h.HandlerStart == instruction.Offset)) - { - if (handler.Flag == "Clause") - ilGenerator.BeginCatchBlock(handler.CatchType); - else if (handler.Flag == "Finally") - ilGenerator.BeginFinallyBlock(); - } - foreach (var handler in handlers.Where(h => h.HandlerEnd == instruction.Offset)) { if (handler.Flag == "Clause") @@ -190,6 +182,14 @@ private void EmitILForExceptionHandlers(ILGenerator ilGenerator, Instruction ins ilGenerator.EndExceptionBlock(); } + + foreach (var handler in handlers.Where(h => h.HandlerStart == instruction.Offset)) + { + if (handler.Flag == "Clause") + ilGenerator.BeginCatchBlock(handler.CatchType); + else if (handler.Flag == "Finally") + ilGenerator.BeginFinallyBlock(); + } } private void EmitILForInlineNone(ILGenerator ilGenerator, Instruction instruction) diff --git a/test/Pose.Tests/IL/MethodRewriterTests.cs b/test/Pose.Tests/IL/MethodRewriterTests.cs index e617b5f..6712e97 100644 --- a/test/Pose.Tests/IL/MethodRewriterTests.cs +++ b/test/Pose.Tests/IL/MethodRewriterTests.cs @@ -50,5 +50,29 @@ public void TestConstructorRewrite() Assert.AreEqual(typeof(void), dynamicMethod.ReturnType); Assert.AreEqual(typeof(List), dynamicMethod.GetParameters()[0].ParameterType); } + + [TestMethod] + public void TestExceptionHandlersRewrite() + { + MethodInfo methodInfo = typeof(MethodRewriterTests).GetMethod("ExceptionHandlersRewriteMethod"); + MethodRewriter methodRewriter = MethodRewriter.CreateRewriter(methodInfo); + DynamicMethod dynamicMethod = methodRewriter.Rewrite() as DynamicMethod; + + Delegate func = dynamicMethod.CreateDelegate(typeof(Func)); + Assert.AreEqual(1, (int)func.DynamicInvoke()); + } + + public static int ExceptionHandlersRewriteMethod() + { + try + { + return 1; + } + catch + { + return 0; + } + finally {} + } } } \ No newline at end of file