AnimancerReflection.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using System.Runtime.Serialization;
  6. using System.Text;
  7. using UnityEngine;
  8. namespace Animancer
  9. {
  10. /// <summary>Reflection utilities used throughout Animancer.</summary>
  11. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerReflection
  12. public static class AnimancerReflection
  13. {
  14. /************************************************************************************************************************/
  15. /// <summary>Commonly used <see cref="BindingFlags"/> combinations.</summary>
  16. public const BindingFlags
  17. AnyAccessBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
  18. InstanceBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
  19. StaticBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  20. /************************************************************************************************************************/
  21. /// <summary>
  22. /// Creates a new instance of the `type` using its parameterless constructor if it has one or a fully
  23. /// uninitialized object if it doesn't. Or returns <c>null</c> if the <see cref="Type.IsAbstract"/>.
  24. /// </summary>
  25. public static object CreateDefaultInstance(Type type)
  26. {
  27. if (type == null ||
  28. type.IsAbstract)
  29. return default;
  30. var constructor = type.GetConstructor(InstanceBindings, null, Type.EmptyTypes, null);
  31. if (constructor != null)
  32. return constructor.Invoke(null);
  33. return FormatterServices.GetUninitializedObject(type);
  34. }
  35. /// <summary>
  36. /// Creates a <typeparamref name="T"/> using its parameterless constructor if it has one or a fully
  37. /// uninitialized object if it doesn't. Or returns <c>null</c> if the <see cref="Type.IsAbstract"/>.
  38. /// </summary>
  39. public static T CreateDefaultInstance<T>()
  40. => (T)CreateDefaultInstance(typeof(T));
  41. /************************************************************************************************************************/
  42. /// <summary>[Animancer Extension]
  43. /// Returns the first <typeparamref name="TAttribute"/> attribute on the `member`
  44. /// or <c>null</c> if there is none.
  45. /// </summary>
  46. public static TAttribute GetAttribute<TAttribute>(
  47. this ICustomAttributeProvider member,
  48. bool inherit = false)
  49. where TAttribute : class
  50. {
  51. var type = typeof(TAttribute);
  52. return member.IsDefined(type, inherit)
  53. ? (TAttribute)member.GetCustomAttributes(type, inherit)[0]
  54. : null;
  55. }
  56. /************************************************************************************************************************/
  57. /// <summary>Invokes a method with the specified `methodName` if it exists on the `obj`.</summary>
  58. [Obfuscation(Exclude = true)]// Obfuscation seems to break IL2CPP Android builds here.
  59. public static object TryInvoke(
  60. object obj,
  61. string methodName,
  62. BindingFlags bindings = InstanceBindings | BindingFlags.FlattenHierarchy,
  63. Type[] parameterTypes = null,
  64. object[] parameters = null)
  65. {
  66. if (obj == null)
  67. return null;
  68. parameterTypes ??= Type.EmptyTypes;
  69. var method = obj.GetType().GetMethod(methodName, bindings, null, parameterTypes, null);
  70. return method?.Invoke(obj, parameters);
  71. }
  72. /************************************************************************************************************************/
  73. #region Delegates
  74. /************************************************************************************************************************/
  75. /// <summary>Returns a string describing the details of the `method`.</summary>
  76. public static string ToStringDetailed<T>(
  77. this T method,
  78. bool includeType = false)
  79. where T : Delegate
  80. {
  81. var text = StringBuilderPool.Instance.Acquire();
  82. text.AppendDelegate(method, includeType);
  83. return text.ReleaseToString();
  84. }
  85. /// <summary>Appends the details of the `method` to the `text`.</summary>
  86. public static StringBuilder AppendDelegate<T>(
  87. this StringBuilder text,
  88. T method,
  89. bool includeType = false)
  90. where T : Delegate
  91. {
  92. var type = method != null
  93. ? method.GetType()
  94. : typeof(T);
  95. if (method == null)
  96. {
  97. return includeType
  98. ? text.Append("Null(")
  99. .Append(type.GetNameCS())
  100. .Append(')')
  101. : text.Append("Null");
  102. }
  103. if (includeType)
  104. text.Append(type.GetNameCS())
  105. .Append('(');
  106. if (method.Target != null)
  107. text.Append("Method: ");
  108. text.Append(method.Method.DeclaringType.GetNameCS())
  109. .Append('.')
  110. .Append(method.Method.Name);
  111. if (method.Target != null)
  112. text.Append(", Target: '")
  113. .Append(method.Target)
  114. .Append("'");
  115. if (includeType)
  116. text.Append(')');
  117. return text;
  118. }
  119. /************************************************************************************************************************/
  120. /// <summary>Returns the `method`'s <c>DeclaringType.Name</c>.</summary>
  121. public static string GetFullName(MethodInfo method)
  122. => $"{method.DeclaringType.Name}.{method.Name}";
  123. /************************************************************************************************************************/
  124. private static FieldInfo _DelegatesField;
  125. private static bool _GotDelegatesField;
  126. /// <summary>
  127. /// Uses reflection to achieve the same as <see cref="Delegate.GetInvocationList"/> without allocating
  128. /// garbage every time.
  129. /// <list type="bullet">
  130. /// <item>If the delegate is <c>null</c> or , this method returns <c>false</c> and outputs <c>null</c>.</item>
  131. /// <item>If the underlying <c>delegate</c> field was not found, this method returns <c>false</c> and outputs <c>null</c>.</item>
  132. /// <item>If the delegate is not multicast, this method this method returns <c>true</c> and outputs <c>null</c>.</item>
  133. /// <item>If the delegate is multicast, this method this method returns <c>true</c> and outputs its invocation list.</item>
  134. /// </list>
  135. /// </summary>
  136. public static bool TryGetInvocationListNonAlloc(MulticastDelegate multicast, out Delegate[] delegates)
  137. {
  138. if (multicast == null)
  139. {
  140. delegates = null;
  141. return false;
  142. }
  143. if (!_GotDelegatesField)
  144. {
  145. const string FieldName = "delegates";
  146. _GotDelegatesField = true;
  147. _DelegatesField = typeof(MulticastDelegate).GetField("delegates",
  148. BindingFlags.Public |
  149. BindingFlags.NonPublic |
  150. BindingFlags.Instance);
  151. if (_DelegatesField != null && _DelegatesField.FieldType != typeof(Delegate[]))
  152. _DelegatesField = null;
  153. if (_DelegatesField == null)
  154. Debug.LogError($"Unable to find {nameof(MulticastDelegate)}.{FieldName} field.");
  155. }
  156. if (_DelegatesField == null)
  157. {
  158. delegates = null;
  159. return false;
  160. }
  161. else
  162. {
  163. delegates = (Delegate[])_DelegatesField.GetValue(multicast);
  164. return true;
  165. }
  166. }
  167. /************************************************************************************************************************/
  168. /// <summary>
  169. /// Tries to use <see cref="TryGetInvocationListNonAlloc"/>.
  170. /// Otherwise uses the regular <see cref="MulticastDelegate.GetInvocationList"/>.
  171. /// </summary>
  172. public static Delegate[] GetInvocationList(MulticastDelegate multicast)
  173. => TryGetInvocationListNonAlloc(multicast, out var delegates) && delegates != null
  174. ? delegates
  175. : multicast?.GetInvocationList();
  176. /************************************************************************************************************************/
  177. #endregion
  178. /************************************************************************************************************************/
  179. #region Type Names
  180. /************************************************************************************************************************/
  181. private static readonly Dictionary<Type, string>
  182. TypeNames = new()
  183. {
  184. { typeof(object), "object" },
  185. { typeof(void), "void" },
  186. { typeof(bool), "bool" },
  187. { typeof(byte), "byte" },
  188. { typeof(sbyte), "sbyte" },
  189. { typeof(char), "char" },
  190. { typeof(string), "string" },
  191. { typeof(short), "short" },
  192. { typeof(int), "int" },
  193. { typeof(long), "long" },
  194. { typeof(ushort), "ushort" },
  195. { typeof(uint), "uint" },
  196. { typeof(ulong), "ulong" },
  197. { typeof(float), "float" },
  198. { typeof(double), "double" },
  199. { typeof(decimal), "decimal" },
  200. };
  201. private static readonly Dictionary<Type, string>
  202. FullTypeNames = new(TypeNames);
  203. /************************************************************************************************************************/
  204. /// <summary>Returns the name of the `type` as it would appear in C# code.</summary>
  205. /// <remarks>
  206. /// Returned values are stored in a dictionary to speed up repeated use.
  207. /// <para></para>
  208. /// <strong>Example:</strong>
  209. /// <para></para>
  210. /// <c>typeof(List&lt;float&gt;).FullName</c> would give you:
  211. /// <para></para>
  212. /// <c>System.Collections.Generic.List`1[[System.Single, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</c>
  213. /// <para></para>
  214. /// This method would instead return <c>System.Collections.Generic.List&lt;float&gt;</c> if `fullName` is <c>true</c>, or
  215. /// just <c>List&lt;float&gt;</c> if it is <c>false</c>.
  216. /// </remarks>
  217. public static string GetNameCS(this Type type, bool fullName = true)
  218. {
  219. if (type == null)
  220. return "null";
  221. // Check if we have already got the name for that type.
  222. var names = fullName
  223. ? FullTypeNames
  224. : TypeNames;
  225. if (names.TryGetValue(type, out var name))
  226. return name;
  227. var text = StringBuilderPool.Instance.Acquire();
  228. if (type.IsArray)// Array = TypeName[].
  229. {
  230. text.Append(type.GetElementType().GetNameCS(fullName));
  231. text.Append('[');
  232. var dimensions = type.GetArrayRank();
  233. while (dimensions-- > 1)
  234. text.Append(',');
  235. text.Append(']');
  236. goto Return;
  237. }
  238. if (type.IsPointer)// Pointer = TypeName*.
  239. {
  240. text.Append(type.GetElementType().GetNameCS(fullName));
  241. text.Append('*');
  242. goto Return;
  243. }
  244. if (type.IsGenericParameter)// Generic Parameter = TypeName (for unspecified generic parameters).
  245. {
  246. text.Append(type.Name);
  247. goto Return;
  248. }
  249. var underlyingType = Nullable.GetUnderlyingType(type);
  250. if (underlyingType != null)// Nullable = TypeName != null ?
  251. {
  252. text.Append(underlyingType.GetNameCS(fullName));
  253. text.Append('?');
  254. goto Return;
  255. }
  256. // Other Type = Namespace.NestedTypes.TypeName<GenericArguments>.
  257. if (fullName && type.Namespace != null)// Namespace.
  258. {
  259. text.Append(type.Namespace);
  260. text.Append('.');
  261. }
  262. var genericArguments = 0;
  263. if (type.DeclaringType != null)// Account for Nested Types.
  264. {
  265. // Count the nesting level.
  266. var nesting = 1;
  267. var declaringType = type.DeclaringType;
  268. while (declaringType.DeclaringType != null)
  269. {
  270. declaringType = declaringType.DeclaringType;
  271. nesting++;
  272. }
  273. // Append the name of each outer type, starting from the outside.
  274. while (nesting-- > 0)
  275. {
  276. // Walk out to the current nesting level.
  277. // This avoids the need to make a list of types in the nest or to insert type names instead of appending them.
  278. declaringType = type;
  279. for (int i = nesting; i >= 0; i--)
  280. declaringType = declaringType.DeclaringType;
  281. // Nested Type Name.
  282. genericArguments = AppendNameAndGenericArguments(text, declaringType, fullName, genericArguments);
  283. text.Append('.');
  284. }
  285. }
  286. // Type Name.
  287. AppendNameAndGenericArguments(text, type, fullName, genericArguments);
  288. Return:// Remember and return the name.
  289. name = text.ReleaseToString();
  290. names.Add(type, name);
  291. return name;
  292. }
  293. /************************************************************************************************************************/
  294. /// <summary>Appends the generic arguments of `type` (after skipping the specified number).</summary>
  295. public static int AppendNameAndGenericArguments(StringBuilder text, Type type, bool fullName = true, int skipGenericArguments = 0)
  296. {
  297. var name = type.Name;
  298. text.Append(name);
  299. if (type.IsGenericType)
  300. {
  301. var backQuote = name.IndexOf('`');
  302. if (backQuote >= 0)
  303. {
  304. text.Length -= name.Length - backQuote;
  305. var genericArguments = type.GetGenericArguments();
  306. if (skipGenericArguments < genericArguments.Length)
  307. {
  308. text.Append('<');
  309. var firstArgument = genericArguments[skipGenericArguments];
  310. skipGenericArguments++;
  311. if (firstArgument.IsGenericParameter)
  312. {
  313. while (skipGenericArguments < genericArguments.Length)
  314. {
  315. text.Append(',');
  316. skipGenericArguments++;
  317. }
  318. }
  319. else
  320. {
  321. text.Append(firstArgument.GetNameCS(fullName));
  322. while (skipGenericArguments < genericArguments.Length)
  323. {
  324. text.Append(", ");
  325. text.Append(genericArguments[skipGenericArguments].GetNameCS(fullName));
  326. skipGenericArguments++;
  327. }
  328. }
  329. text.Append('>');
  330. }
  331. }
  332. }
  333. return skipGenericArguments;
  334. }
  335. /************************************************************************************************************************/
  336. #endregion
  337. /************************************************************************************************************************/
  338. }
  339. }