PageRenderTime 19ms CodeModel.GetById 15ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/src/LinFu.AOP/Emitters/SaveReturnValue.cs

http://github.com/philiplaureano/LinFu
C# | 46 lines | 27 code | 7 blank | 12 comment | 6 complexity | 174b513676503edf25a9ad7f37b4489c MD5 | raw file
 1using LinFu.AOP.Cecil.Interfaces;
 2using LinFu.Reflection.Emit;
 3using Mono.Cecil;
 4using Mono.Cecil.Cil;
 5
 6namespace LinFu.AOP.Cecil
 7{
 8    /// <summary>
 9    ///     Represents an instruction emitter that saves the return value from a given method call.
10    /// </summary>
11    public class SaveReturnValue : IInstructionEmitter
12    {
13        private readonly TypeReference _returnType;
14        private readonly VariableDefinition _returnValue;
15
16        /// <summary>
17        ///     Initializes a new instance of the <see cref="SaveReturnValue" /> class.
18        /// </summary>
19        /// <param name="returnType">The return type.</param>
20        /// <param name="returnValue">The return value.</param>
21        public SaveReturnValue(TypeReference returnType, VariableDefinition returnValue)
22        {
23            _returnType = returnType;
24            _returnValue = returnValue;
25        }
26
27
28        /// <summary>
29        ///     Saves the return value from a given method call.
30        /// </summary>
31        /// <param name="IL">The <see cref="ILProcessor" /> pointing to the target method body.</param>
32        public void Emit(ILProcessor IL)
33        {
34            var module = IL.Body.Method.DeclaringType.Module;
35            
36            var voidType = module.ImportType(typeof(void));
37            var returnTypeIsValueType = _returnType != voidType && _returnType.IsValueType;
38
39            if (_returnType is GenericParameter || returnTypeIsValueType)
40                IL.Create(OpCodes.Box, _returnType);
41
42            if (_returnType != voidType)
43                IL.Create(OpCodes.Stloc, _returnValue);
44        }
45    }
46}