ReflectionUtil.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. #if NET35
  36. using Google.Protobuf.Compatibility;
  37. #endif
  38. namespace Google.Protobuf.Reflection
  39. {
  40. /// <summary>
  41. /// The methods in this class are somewhat evil, and should not be tampered with lightly.
  42. /// Basically they allow the creation of relatively weakly typed delegates from MethodInfos
  43. /// which are more strongly typed. They do this by creating an appropriate strongly typed
  44. /// delegate from the MethodInfo, and then calling that within an anonymous method.
  45. /// Mind-bending stuff (at least to your humble narrator) but the resulting delegates are
  46. /// very fast compared with calling Invoke later on.
  47. /// </summary>
  48. internal static class ReflectionUtil
  49. {
  50. static ReflectionUtil()
  51. {
  52. ForceInitialize<string>(); // Handles all reference types
  53. ForceInitialize<int>();
  54. ForceInitialize<long>();
  55. ForceInitialize<uint>();
  56. ForceInitialize<ulong>();
  57. ForceInitialize<float>();
  58. ForceInitialize<double>();
  59. ForceInitialize<bool>();
  60. ForceInitialize<int?>();
  61. ForceInitialize<long?>();
  62. ForceInitialize<uint?>();
  63. ForceInitialize<ulong?>();
  64. ForceInitialize<float?>();
  65. ForceInitialize<double?>();
  66. ForceInitialize<bool?>();
  67. ForceInitialize<SampleEnum>();
  68. SampleEnumMethod();
  69. }
  70. internal static void ForceInitialize<T>() => new ReflectionHelper<IMessage, T>();
  71. /// <summary>
  72. /// Empty Type[] used when calling GetProperty to force property instead of indexer fetching.
  73. /// </summary>
  74. internal static readonly Type[] EmptyTypes = new Type[0];
  75. /// <summary>
  76. /// Creates a delegate which will cast the argument to the type that declares the method,
  77. /// call the method on it, then convert the result to object.
  78. /// </summary>
  79. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  80. /// implementation.</param>
  81. internal static Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method) =>
  82. GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageObject(method);
  83. /// <summary>
  84. /// Creates a delegate which will cast the argument to the type that declares the method,
  85. /// call the method on it, then convert the result to the specified type. The method is expected
  86. /// to actually return an enum (because of where we're calling it - for oneof cases). Sometimes that
  87. /// means we need some extra work to perform conversions.
  88. /// </summary>
  89. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  90. /// implementation.</param>
  91. internal static Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method) =>
  92. GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageInt32(method);
  93. /// <summary>
  94. /// Creates a delegate which will execute the given method after casting the first argument to
  95. /// the type that declares the method, and the second argument to the first parameter type of the method.
  96. /// </summary>
  97. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  98. /// implementation.</param>
  99. internal static Action<IMessage, object> CreateActionIMessageObject(MethodInfo method) =>
  100. GetReflectionHelper(method.DeclaringType, method.GetParameters()[0].ParameterType).CreateActionIMessageObject(method);
  101. /// <summary>
  102. /// Creates a delegate which will execute the given method after casting the first argument to
  103. /// type that declares the method.
  104. /// </summary>
  105. /// <param name="method">The method to create a delegate for, which must be declared in an IMessage
  106. /// implementation.</param>
  107. internal static Action<IMessage> CreateActionIMessage(MethodInfo method) =>
  108. GetReflectionHelper(method.DeclaringType, typeof(object)).CreateActionIMessage(method);
  109. /// <summary>
  110. /// Creates a reflection helper for the given type arguments. Currently these are created on demand
  111. /// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that
  112. /// they can be garbage collected. We could cache them by type if that proves to be important, but creating
  113. /// an object is pretty cheap.
  114. /// </summary>
  115. private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) =>
  116. (IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2));
  117. // Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically
  118. // knowing the types involved.
  119. private interface IReflectionHelper
  120. {
  121. Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method);
  122. Action<IMessage> CreateActionIMessage(MethodInfo method);
  123. Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method);
  124. Action<IMessage, object> CreateActionIMessageObject(MethodInfo method);
  125. }
  126. private class ReflectionHelper<T1, T2> : IReflectionHelper
  127. {
  128. public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method)
  129. {
  130. // On pleasant runtimes, we can create a Func<int> from a method returning
  131. // an enum based on an int. That's the fast path.
  132. if (CanConvertEnumFuncToInt32Func)
  133. {
  134. var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>));
  135. return message => del((T1) message);
  136. }
  137. else
  138. {
  139. // On some runtimes (e.g. old Mono) the return type has to be exactly correct,
  140. // so we go via boxing. Reflection is already fairly inefficient, and this is
  141. // only used for one-of case checking, fortunately.
  142. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
  143. return message => (int) (object) del((T1) message);
  144. }
  145. }
  146. public Action<IMessage> CreateActionIMessage(MethodInfo method)
  147. {
  148. var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>));
  149. return message => del((T1) message);
  150. }
  151. public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method)
  152. {
  153. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
  154. return message => del((T1) message);
  155. }
  156. public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method)
  157. {
  158. var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>));
  159. return (message, arg) => del((T1) message, (T2) arg);
  160. }
  161. }
  162. // Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for
  163. // details about why we're doing this.
  164. // Deliberately not inside the generic type. We only want to check this once.
  165. private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func();
  166. private static bool CheckCanConvertEnumFuncToInt32Func()
  167. {
  168. try
  169. {
  170. // Try to do the conversion using reflection, so we can see whether it's supported.
  171. MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod));
  172. // If this passes, we're in a reasonable runtime.
  173. method.CreateDelegate(typeof(Func<int>));
  174. return true;
  175. }
  176. catch (ArgumentException)
  177. {
  178. return false;
  179. }
  180. }
  181. public enum SampleEnum
  182. {
  183. X
  184. }
  185. // Public to make the reflection simpler.
  186. public static SampleEnum SampleEnumMethod() => SampleEnum.X;
  187. }
  188. }