ReflectionUtil.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using Google.Protobuf.Compatibility;
  33. using System;
  34. using System.Reflection;
  35. namespace Google.Protobuf.Reflection
  36. {
  37. /// <summary>
  38. /// The methods in this class are somewhat evil, and should not be tampered with lightly.
  39. /// Basically they allow the creation of relatively weakly typed delegates from MethodInfos
  40. /// which are more strongly typed. They do this by creating an appropriate strongly typed
  41. /// delegate from the MethodInfo, and then calling that within an anonymous method.
  42. /// Mind-bending stuff (at least to your humble narrator) but the resulting delegates are
  43. /// very fast compared with calling Invoke later on.
  44. /// </summary>
  45. internal static class ReflectionUtil
  46. {
  47. static ReflectionUtil()
  48. {
  49. ForceInitialize<string>(); // Handles all reference types
  50. ForceInitialize<int>();
  51. ForceInitialize<long>();
  52. ForceInitialize<uint>();
  53. ForceInitialize<ulong>();
  54. ForceInitialize<float>();
  55. ForceInitialize<double>();
  56. ForceInitialize<bool>();
  57. ForceInitialize<int?>();
  58. ForceInitialize<long?>();
  59. ForceInitialize<uint?>();
  60. ForceInitialize<ulong?>();
  61. ForceInitialize<float?>();
  62. ForceInitialize<double?>();
  63. ForceInitialize<bool?>();
  64. ForceInitialize<SampleEnum>();
  65. SampleEnumMethod();
  66. }
  67. internal static void ForceInitialize<T>() => new ReflectionHelper<IMessage, T>();
  68. /// <summary>
  69. /// Empty Type[] used when calling GetProperty to force property instead of indexer fetching.
  70. /// </summary>
  71. internal static readonly Type[] EmptyTypes = new Type[0];
  72. /// <summary>
  73. /// Creates a delegate which will cast the argument to the type that declares the method,
  74. /// call the method on it, then convert the result to object.
  75. /// </summary>
  76. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  77. /// implementation.</param>
  78. internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) =>
  79. GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageObject(method);
  80. /// <summary>
  81. /// Creates a delegate which will cast the argument to the type that declares the method,
  82. /// call the method on it, then convert the result to the specified type. The method is expected
  83. /// to actually return an enum (because of where we're calling it - for oneof cases). Sometimes that
  84. /// means we need some extra work to perform conversions.
  85. /// </summary>
  86. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  87. /// implementation.</param>
  88. internal static Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) =>
  89. GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageInt32(method);
  90. /// <summary>
  91. /// Creates a delegate which will execute the given method after casting the first argument to
  92. /// the type that declares the method, and the second argument to the first parameter type of the method.
  93. /// </summary>
  94. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  95. /// implementation.</param>
  96. internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) =>
  97. GetReflectionHelper(method.DeclaringType, method.GetParameters()[0].ParameterType).CreateActionIMessageObject(method);
  98. /// <summary>
  99. /// Creates a delegate which will execute the given method after casting the first argument to
  100. /// type that declares the method.
  101. /// </summary>
  102. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  103. /// implementation.</param>
  104. internal static Action<IMessage> CreateActionIMessage(MethodInfo method) =>
  105. GetReflectionHelper(method.DeclaringType, typeof(object)).CreateActionIMessage(method);
  106. /// <summary>
  107. /// Creates a reflection helper for the given type arguments. Currently these are created on demand
  108. /// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that
  109. /// they can be garbage collected. We could cache them by type if that proves to be important, but creating
  110. /// an object is pretty cheap.
  111. /// </summary>
  112. private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) =>
  113. (IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2));
  114. // Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically
  115. // knowing the types involved.
  116. private interface IReflectionHelper
  117. {
  118. Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method);
  119. Action<IMessage> CreateActionIMessage(MethodInfo method);
  120. Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method);
  121. Action<IMessage, object> CreateActionIMessageObject(MethodInfo method);
  122. }
  123. private class ReflectionHelper<T1, T2> : IReflectionHelper
  124. {
  125. public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method)
  126. {
  127. // On pleasant runtimes, we can create a Func<int> from a method returning
  128. // an enum based on an int. That's the fast path.
  129. if (CanConvertEnumFuncToInt32Func)
  130. {
  131. var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>));
  132. return message => del((T1) message);
  133. }
  134. else
  135. {
  136. // On some runtimes (e.g. old Mono) the return type has to be exactly correct,
  137. // so we go via boxing. Reflection is already fairly inefficient, and this is
  138. // only used for one-of case checking, fortunately.
  139. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
  140. return message => (int) (object) del((T1) message);
  141. }
  142. }
  143. public Action<IMessage> CreateActionIMessage(MethodInfo method)
  144. {
  145. var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>));
  146. return message => del((T1) message);
  147. }
  148. public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method)
  149. {
  150. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
  151. return message => del((T1) message);
  152. }
  153. public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method)
  154. {
  155. var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>));
  156. return (message, arg) => del((T1) message, (T2) arg);
  157. }
  158. }
  159. // Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for
  160. // details about why we're doing this.
  161. // Deliberately not inside the generic type. We only want to check this once.
  162. private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func();
  163. private static bool CheckCanConvertEnumFuncToInt32Func()
  164. {
  165. try
  166. {
  167. // Try to do the conversion using reflection, so we can see whether it's supported.
  168. MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod));
  169. // If this passes, we're in a reasonable runtime.
  170. method.CreateDelegate(typeof(Func<int>));
  171. return true;
  172. }
  173. catch (ArgumentException)
  174. {
  175. return false;
  176. }
  177. }
  178. public enum SampleEnum
  179. {
  180. X
  181. }
  182. // Public to make the reflection simpler.
  183. public static SampleEnum SampleEnumMethod() => SampleEnum.X;
  184. }
  185. }