ReflectionUtil.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. internal static Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method) =>
  107. GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageBool(method);
  108. internal static Func<IMessage, bool> CreateIsInitializedCaller(Type msg) =>
  109. ((IExtensionSetReflector)Activator.CreateInstance(typeof(ExtensionSetReflector<>).MakeGenericType(msg))).CreateIsInitializedCaller();
  110. /// <summary>
  111. /// Creates a delegate which will execute the given method after casting the first argument to
  112. /// the type that declares the method, and the second argument to the first parameter type of the method.
  113. /// </summary>
  114. internal static IExtensionReflectionHelper CreateExtensionHelper(Extension extension) =>
  115. (IExtensionReflectionHelper)Activator.CreateInstance(typeof(ExtensionReflectionHelper<,>).MakeGenericType(extension.TargetType, extension.GetType().GenericTypeArguments[1]), extension);
  116. /// <summary>
  117. /// Creates a reflection helper for the given type arguments. Currently these are created on demand
  118. /// rather than cached; this will be "busy" when initially loading a message's descriptor, but after that
  119. /// they can be garbage collected. We could cache them by type if that proves to be important, but creating
  120. /// an object is pretty cheap.
  121. /// </summary>
  122. private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) =>
  123. (IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2));
  124. // Non-generic interface allowing us to use an instance of ReflectionHelper<T1, T2> without statically
  125. // knowing the types involved.
  126. private interface IReflectionHelper
  127. {
  128. Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method);
  129. Action<IMessage> CreateActionIMessage(MethodInfo method);
  130. Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method);
  131. Action<IMessage, object> CreateActionIMessageObject(MethodInfo method);
  132. Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method);
  133. }
  134. internal interface IExtensionReflectionHelper
  135. {
  136. object GetExtension(IMessage message);
  137. void SetExtension(IMessage message, object value);
  138. bool HasExtension(IMessage message);
  139. void ClearExtension(IMessage message);
  140. }
  141. private interface IExtensionSetReflector
  142. {
  143. Func<IMessage, bool> CreateIsInitializedCaller();
  144. }
  145. private class ReflectionHelper<T1, T2> : IReflectionHelper
  146. {
  147. public Func<IMessage, int> CreateFuncIMessageInt32(MethodInfo method)
  148. {
  149. // On pleasant runtimes, we can create a Func<int> from a method returning
  150. // an enum based on an int. That's the fast path.
  151. if (CanConvertEnumFuncToInt32Func)
  152. {
  153. var del = (Func<T1, int>) method.CreateDelegate(typeof(Func<T1, int>));
  154. return message => del((T1) message);
  155. }
  156. else
  157. {
  158. // On some runtimes (e.g. old Mono) the return type has to be exactly correct,
  159. // so we go via boxing. Reflection is already fairly inefficient, and this is
  160. // only used for one-of case checking, fortunately.
  161. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
  162. return message => (int) (object) del((T1) message);
  163. }
  164. }
  165. public Action<IMessage> CreateActionIMessage(MethodInfo method)
  166. {
  167. var del = (Action<T1>) method.CreateDelegate(typeof(Action<T1>));
  168. return message => del((T1) message);
  169. }
  170. public Func<IMessage, object> CreateFuncIMessageObject(MethodInfo method)
  171. {
  172. var del = (Func<T1, T2>) method.CreateDelegate(typeof(Func<T1, T2>));
  173. return message => del((T1) message);
  174. }
  175. public Action<IMessage, object> CreateActionIMessageObject(MethodInfo method)
  176. {
  177. var del = (Action<T1, T2>) method.CreateDelegate(typeof(Action<T1, T2>));
  178. return (message, arg) => del((T1) message, (T2) arg);
  179. }
  180. public Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method)
  181. {
  182. var del = (Func<T1, bool>)method.CreateDelegate(typeof(Func<T1, bool>));
  183. return message => del((T1)message);
  184. }
  185. }
  186. private class ExtensionReflectionHelper<T1, T3> : IExtensionReflectionHelper
  187. where T1 : IExtendableMessage<T1>
  188. {
  189. private readonly Extension extension;
  190. public ExtensionReflectionHelper(Extension extension)
  191. {
  192. this.extension = extension;
  193. }
  194. public object GetExtension(IMessage message)
  195. {
  196. if (!(message is T1))
  197. {
  198. throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
  199. }
  200. T1 extensionMessage = (T1)message;
  201. if (extension is Extension<T1, T3>)
  202. {
  203. return extensionMessage.GetExtension(extension as Extension<T1, T3>);
  204. }
  205. else if (extension is RepeatedExtension<T1, T3>)
  206. {
  207. return extensionMessage.GetOrInitializeExtension(extension as RepeatedExtension<T1, T3>);
  208. }
  209. else
  210. {
  211. throw new InvalidCastException("The provided extension is not a valid extension identifier type");
  212. }
  213. }
  214. public bool HasExtension(IMessage message)
  215. {
  216. if (!(message is T1))
  217. {
  218. throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
  219. }
  220. T1 extensionMessage = (T1)message;
  221. if (extension is Extension<T1, T3>)
  222. {
  223. return extensionMessage.HasExtension(extension as Extension<T1, T3>);
  224. }
  225. else if (extension is RepeatedExtension<T1, T3>)
  226. {
  227. throw new InvalidOperationException("HasValue is not implemented for repeated extensions");
  228. }
  229. else
  230. {
  231. throw new InvalidCastException("The provided extension is not a valid extension identifier type");
  232. }
  233. }
  234. public void SetExtension(IMessage message, object value)
  235. {
  236. if (!(message is T1))
  237. {
  238. throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
  239. }
  240. T1 extensionMessage = (T1)message;
  241. if (extension is Extension<T1, T3>)
  242. {
  243. extensionMessage.SetExtension(extension as Extension<T1, T3>, (T3)value);
  244. }
  245. else if (extension is RepeatedExtension<T1, T3>)
  246. {
  247. throw new InvalidOperationException("SetValue is not implemented for repeated extensions");
  248. }
  249. else
  250. {
  251. throw new InvalidCastException("The provided extension is not a valid extension identifier type");
  252. }
  253. }
  254. public void ClearExtension(IMessage message)
  255. {
  256. if (!(message is T1))
  257. {
  258. throw new InvalidCastException("Cannot access extension on message that isn't IExtensionMessage");
  259. }
  260. T1 extensionMessage = (T1)message;
  261. if (extension is Extension<T1, T3>)
  262. {
  263. extensionMessage.ClearExtension(extension as Extension<T1, T3>);
  264. }
  265. else if (extension is RepeatedExtension<T1, T3>)
  266. {
  267. extensionMessage.GetExtension(extension as RepeatedExtension<T1, T3>).Clear();
  268. }
  269. else
  270. {
  271. throw new InvalidCastException("The provided extension is not a valid extension identifier type");
  272. }
  273. }
  274. }
  275. private class ExtensionSetReflector<T1> : IExtensionSetReflector where T1 : IExtendableMessage<T1>
  276. {
  277. public Func<IMessage, bool> CreateIsInitializedCaller()
  278. {
  279. var prop = typeof(T1).GetTypeInfo().GetDeclaredProperty("_Extensions");
  280. #if NET35
  281. var getFunc = (Func<T1, ExtensionSet<T1>>)prop.GetGetMethod(true).CreateDelegate(typeof(Func<T1, ExtensionSet<T1>>));
  282. #else
  283. var getFunc = (Func<T1, ExtensionSet<T1>>)prop.GetMethod.CreateDelegate(typeof(Func<T1, ExtensionSet<T1>>));
  284. #endif
  285. var initializedFunc = (Func<ExtensionSet<T1>, bool>)
  286. typeof(ExtensionSet<T1>)
  287. .GetTypeInfo()
  288. .GetDeclaredMethod("IsInitialized")
  289. .CreateDelegate(typeof(Func<ExtensionSet<T1>, bool>));
  290. return (m) => {
  291. var set = getFunc((T1)m);
  292. return set == null || initializedFunc(set);
  293. };
  294. }
  295. }
  296. // Runtime compatibility checking code - see ReflectionHelper<T1, T2>.CreateFuncIMessageInt32 for
  297. // details about why we're doing this.
  298. // Deliberately not inside the generic type. We only want to check this once.
  299. private static bool CanConvertEnumFuncToInt32Func { get; } = CheckCanConvertEnumFuncToInt32Func();
  300. private static bool CheckCanConvertEnumFuncToInt32Func()
  301. {
  302. try
  303. {
  304. // Try to do the conversion using reflection, so we can see whether it's supported.
  305. MethodInfo method = typeof(ReflectionUtil).GetMethod(nameof(SampleEnumMethod));
  306. // If this passes, we're in a reasonable runtime.
  307. method.CreateDelegate(typeof(Func<int>));
  308. return true;
  309. }
  310. catch (ArgumentException)
  311. {
  312. return false;
  313. }
  314. }
  315. public enum SampleEnum
  316. {
  317. X
  318. }
  319. // Public to make the reflection simpler.
  320. public static SampleEnum SampleEnumMethod() => SampleEnum.X;
  321. }
  322. }