TypeResolver.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Dynamic;
  4. using System.Reflection;
  5. using System.Threading;
  6. using Jint.Runtime.Interop.Reflection;
  7. namespace Jint.Runtime.Interop
  8. {
  9. /// <summary>
  10. /// Interop strategy for resolving types and members.
  11. /// </summary>
  12. public sealed class TypeResolver
  13. {
  14. public static readonly TypeResolver Default = new TypeResolver();
  15. private Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor> _reflectionAccessors = new();
  16. /// <summary>
  17. /// Registers a filter that determines whether given member is wrapped to interop or returned as undefined.
  18. /// </summary>
  19. public Predicate<MemberInfo> MemberFilter { get; set; } = _ => true;
  20. /// <summary>
  21. /// Sets member name comparison strategy when finding CLR objects members.
  22. /// By default member's first character casing is ignored and rest of the name is compared with strict equality.
  23. /// </summary>
  24. public StringComparer MemberNameComparer { get; set; } = DefaultMemberNameComparer.Instance;
  25. internal ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func<ReflectionAccessor> accessorFactory = null)
  26. {
  27. var key = new ClrPropertyDescriptorFactoriesKey(type, member);
  28. var factories = _reflectionAccessors;
  29. if (factories.TryGetValue(key, out var accessor))
  30. {
  31. return accessor;
  32. }
  33. accessor = accessorFactory?.Invoke() ?? ResolvePropertyDescriptorFactory(engine, type, member);
  34. // racy, we don't care, worst case we'll catch up later
  35. Interlocked.CompareExchange(ref _reflectionAccessors,
  36. new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(factories)
  37. {
  38. [key] = accessor
  39. }, factories);
  40. return accessor;
  41. }
  42. private ReflectionAccessor ResolvePropertyDescriptorFactory(
  43. Engine engine,
  44. Type type,
  45. string memberName)
  46. {
  47. var isNumber = uint.TryParse(memberName, out _);
  48. // we can always check indexer if there's one, and then fall back to properties if indexer returns null
  49. IndexerAccessor.TryFindIndexer(engine, type, memberName, out var indexerAccessor, out var indexer);
  50. const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public;
  51. // properties and fields cannot be numbers
  52. if (!isNumber && TryFindMemberAccessor(type, memberName, bindingFlags, indexer, out var temp))
  53. {
  54. return temp;
  55. }
  56. if (typeof(DynamicObject).IsAssignableFrom(type))
  57. {
  58. return new DynamicObjectAccessor(type, memberName);
  59. }
  60. // if no methods are found check if target implemented indexing
  61. if (indexerAccessor != null)
  62. {
  63. return indexerAccessor;
  64. }
  65. // try to find a single explicit property implementation
  66. List<PropertyInfo> list = null;
  67. var typeResolverMemberNameComparer = MemberNameComparer;
  68. foreach (var iface in type.GetInterfaces())
  69. {
  70. foreach (var iprop in iface.GetProperties())
  71. {
  72. if (!MemberFilter(iprop))
  73. {
  74. continue;
  75. }
  76. if (iprop.Name == "Item" && iprop.GetIndexParameters().Length == 1)
  77. {
  78. // never take indexers, should use the actual indexer
  79. continue;
  80. }
  81. if (typeResolverMemberNameComparer.Equals(iprop.Name, memberName))
  82. {
  83. list ??= new List<PropertyInfo>();
  84. list.Add(iprop);
  85. }
  86. }
  87. }
  88. if (list?.Count == 1)
  89. {
  90. return new PropertyAccessor(memberName, list[0]);
  91. }
  92. // try to find explicit method implementations
  93. List<MethodInfo> explicitMethods = null;
  94. foreach (var iface in type.GetInterfaces())
  95. {
  96. foreach (var imethod in iface.GetMethods())
  97. {
  98. if (!MemberFilter(imethod))
  99. {
  100. continue;
  101. }
  102. if (typeResolverMemberNameComparer.Equals(imethod.Name, memberName))
  103. {
  104. explicitMethods ??= new List<MethodInfo>();
  105. explicitMethods.Add(imethod);
  106. }
  107. }
  108. }
  109. if (explicitMethods?.Count > 0)
  110. {
  111. return new MethodAccessor(MethodDescriptor.Build(explicitMethods));
  112. }
  113. // try to find explicit indexer implementations
  114. foreach (var interfaceType in type.GetInterfaces())
  115. {
  116. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  117. {
  118. return accessor;
  119. }
  120. }
  121. if (engine.Options._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  122. {
  123. var matches = new List<MethodInfo>();
  124. foreach (var method in extensionMethods)
  125. {
  126. if (!MemberFilter(method))
  127. {
  128. continue;
  129. }
  130. if (typeResolverMemberNameComparer.Equals(method.Name, memberName))
  131. {
  132. matches.Add(method);
  133. }
  134. }
  135. if (matches.Count > 0)
  136. {
  137. return new MethodAccessor(MethodDescriptor.Build(matches));
  138. }
  139. }
  140. return ConstantValueAccessor.NullAccessor;
  141. }
  142. internal bool TryFindMemberAccessor(
  143. Type type,
  144. string memberName,
  145. BindingFlags bindingFlags,
  146. PropertyInfo indexerToTry,
  147. out ReflectionAccessor accessor)
  148. {
  149. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  150. PropertyInfo property = null;
  151. foreach (var p in type.GetProperties(bindingFlags))
  152. {
  153. if (!MemberFilter(p))
  154. {
  155. continue;
  156. }
  157. // only if it's not an indexer, we can do case-ignoring matches
  158. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  159. if (!isStandardIndexer && MemberNameComparer.Equals(p.Name, memberName))
  160. {
  161. property = p;
  162. break;
  163. }
  164. }
  165. if (property != null)
  166. {
  167. accessor = new PropertyAccessor(memberName, property, indexerToTry);
  168. return true;
  169. }
  170. // look for a field
  171. FieldInfo field = null;
  172. foreach (var f in type.GetFields(bindingFlags))
  173. {
  174. if (!MemberFilter(f))
  175. {
  176. continue;
  177. }
  178. if (MemberNameComparer.Equals(f.Name, memberName))
  179. {
  180. field = f;
  181. break;
  182. }
  183. }
  184. if (field != null)
  185. {
  186. accessor = new FieldAccessor(field, memberName, indexerToTry);
  187. return true;
  188. }
  189. // if no properties were found then look for a method
  190. List<MethodInfo> methods = null;
  191. foreach (var m in type.GetMethods(bindingFlags))
  192. {
  193. if (!MemberFilter(m))
  194. {
  195. continue;
  196. }
  197. if (MemberNameComparer.Equals(m.Name, memberName))
  198. {
  199. methods ??= new List<MethodInfo>();
  200. methods.Add(m);
  201. }
  202. }
  203. if (methods?.Count > 0)
  204. {
  205. accessor = new MethodAccessor(MethodDescriptor.Build(methods));
  206. return true;
  207. }
  208. accessor = default;
  209. return false;
  210. }
  211. private sealed class DefaultMemberNameComparer : StringComparer
  212. {
  213. public static readonly StringComparer Instance = new DefaultMemberNameComparer();
  214. public override int Compare(string x, string y)
  215. {
  216. throw new NotImplementedException();
  217. }
  218. public override bool Equals(string x, string y)
  219. {
  220. if (ReferenceEquals(x, y))
  221. {
  222. return true;
  223. }
  224. if (x == null || y == null)
  225. {
  226. return false;
  227. }
  228. if (x.Length != y.Length)
  229. {
  230. return false;
  231. }
  232. var equals = false;
  233. if (x.Length > 0)
  234. {
  235. equals = char.ToLowerInvariant(x[0]) == char.ToLowerInvariant(y[0]);
  236. }
  237. if (equals && x.Length > 1)
  238. {
  239. #if NETSTANDARD2_1
  240. equals = x.AsSpan(1).SequenceEqual(y.AsSpan(1));
  241. #else
  242. equals = x.Substring(1) == y.Substring(1);
  243. #endif
  244. }
  245. return equals;
  246. }
  247. public override int GetHashCode(string obj)
  248. {
  249. throw new NotImplementedException();
  250. }
  251. }
  252. }
  253. }