TypeResolver.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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();
  15. private readonly record struct ClrPropertyDescriptorFactoriesKey(Type Type, Key PropertyName);
  16. private Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor> _reflectionAccessors = new();
  17. /// <summary>
  18. /// Registers a filter that determines whether given member is wrapped to interop or returned as undefined.
  19. /// By default allows all but will also be limited by <see cref="InteropOptions.AllowGetType"/> configuration.
  20. /// </summary>
  21. /// <seealso cref="InteropOptions.AllowGetType"/>
  22. public Predicate<MemberInfo> MemberFilter { get; set; } = _ => true;
  23. internal bool Filter(Engine engine, MemberInfo m)
  24. {
  25. return (engine.Options.Interop.AllowGetType || m.Name != nameof(GetType)) && MemberFilter(m);
  26. }
  27. /// <summary>
  28. /// Gives the exposed names for a member. Allows to expose C# convention following member like IsSelected
  29. /// as more JS idiomatic "selected" for example. Defaults to returning the <see cref="MemberInfo.Name"/> as-is.
  30. /// </summary>
  31. public Func<MemberInfo, IEnumerable<string>> MemberNameCreator { get; set; } = NameCreator;
  32. private static IEnumerable<string> NameCreator(MemberInfo info)
  33. {
  34. yield return info.Name;
  35. }
  36. /// <summary>
  37. /// Sets member name comparison strategy when finding CLR objects members.
  38. /// By default member's first character casing is ignored and rest of the name is compared with strict equality.
  39. /// </summary>
  40. public StringComparer MemberNameComparer { get; set; } = DefaultMemberNameComparer.Instance;
  41. internal ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func<ReflectionAccessor> accessorFactory = null)
  42. {
  43. var key = new ClrPropertyDescriptorFactoriesKey(type, member);
  44. var factories = _reflectionAccessors;
  45. if (factories.TryGetValue(key, out var accessor))
  46. {
  47. return accessor;
  48. }
  49. accessor = accessorFactory?.Invoke() ?? ResolvePropertyDescriptorFactory(engine, type, member);
  50. // racy, we don't care, worst case we'll catch up later
  51. Interlocked.CompareExchange(ref _reflectionAccessors,
  52. new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(factories)
  53. {
  54. [key] = accessor
  55. }, factories);
  56. return accessor;
  57. }
  58. private ReflectionAccessor ResolvePropertyDescriptorFactory(
  59. Engine engine,
  60. Type type,
  61. string memberName)
  62. {
  63. var isNumber = uint.TryParse(memberName, out _);
  64. // we can always check indexer if there's one, and then fall back to properties if indexer returns null
  65. IndexerAccessor.TryFindIndexer(engine, type, memberName, out var indexerAccessor, out var indexer);
  66. const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public;
  67. // properties and fields cannot be numbers
  68. if (!isNumber && TryFindMemberAccessor(engine, type, memberName, bindingFlags, indexer, out var temp))
  69. {
  70. return temp;
  71. }
  72. if (typeof(DynamicObject).IsAssignableFrom(type))
  73. {
  74. return new DynamicObjectAccessor(type, memberName);
  75. }
  76. // if no methods are found check if target implemented indexing
  77. if (indexerAccessor != null)
  78. {
  79. return indexerAccessor;
  80. }
  81. // try to find a single explicit property implementation
  82. List<PropertyInfo> list = null;
  83. var typeResolverMemberNameComparer = MemberNameComparer;
  84. var typeResolverMemberNameCreator = MemberNameCreator;
  85. foreach (var iface in type.GetInterfaces())
  86. {
  87. foreach (var iprop in iface.GetProperties())
  88. {
  89. if (!Filter(engine, iprop))
  90. {
  91. continue;
  92. }
  93. if (iprop.Name == "Item" && iprop.GetIndexParameters().Length == 1)
  94. {
  95. // never take indexers, should use the actual indexer
  96. continue;
  97. }
  98. foreach (var name in typeResolverMemberNameCreator(iprop))
  99. {
  100. if (typeResolverMemberNameComparer.Equals(name, memberName))
  101. {
  102. list ??= new List<PropertyInfo>();
  103. list.Add(iprop);
  104. }
  105. }
  106. }
  107. }
  108. if (list?.Count == 1)
  109. {
  110. return new PropertyAccessor(memberName, list[0]);
  111. }
  112. // try to find explicit method implementations
  113. List<MethodInfo> explicitMethods = null;
  114. foreach (var iface in type.GetInterfaces())
  115. {
  116. foreach (var imethod in iface.GetMethods())
  117. {
  118. if (!Filter(engine, imethod))
  119. {
  120. continue;
  121. }
  122. foreach (var name in typeResolverMemberNameCreator(imethod))
  123. {
  124. if (typeResolverMemberNameComparer.Equals(name, memberName))
  125. {
  126. explicitMethods ??= new List<MethodInfo>();
  127. explicitMethods.Add(imethod);
  128. }
  129. }
  130. }
  131. }
  132. if (explicitMethods?.Count > 0)
  133. {
  134. return new MethodAccessor(MethodDescriptor.Build(explicitMethods));
  135. }
  136. // try to find explicit indexer implementations
  137. foreach (var interfaceType in type.GetInterfaces())
  138. {
  139. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  140. {
  141. return accessor;
  142. }
  143. }
  144. if (engine._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  145. {
  146. var matches = new List<MethodInfo>();
  147. foreach (var method in extensionMethods)
  148. {
  149. if (!Filter(engine, method))
  150. {
  151. continue;
  152. }
  153. foreach (var name in typeResolverMemberNameCreator(method))
  154. {
  155. if (typeResolverMemberNameComparer.Equals(name, memberName))
  156. {
  157. matches.Add(method);
  158. }
  159. }
  160. }
  161. if (matches.Count > 0)
  162. {
  163. return new MethodAccessor(MethodDescriptor.Build(matches));
  164. }
  165. }
  166. return ConstantValueAccessor.NullAccessor;
  167. }
  168. internal bool TryFindMemberAccessor(
  169. Engine engine,
  170. Type type,
  171. string memberName,
  172. BindingFlags bindingFlags,
  173. PropertyInfo indexerToTry,
  174. out ReflectionAccessor accessor)
  175. {
  176. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  177. PropertyInfo property = null;
  178. var memberNameComparer = MemberNameComparer;
  179. var typeResolverMemberNameCreator = MemberNameCreator;
  180. foreach (var p in type.GetProperties(bindingFlags))
  181. {
  182. if (!Filter(engine, p))
  183. {
  184. continue;
  185. }
  186. // only if it's not an indexer, we can do case-ignoring matches
  187. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  188. if (!isStandardIndexer)
  189. {
  190. foreach (var name in typeResolverMemberNameCreator(p))
  191. {
  192. if (memberNameComparer.Equals(name, memberName))
  193. {
  194. property = p;
  195. break;
  196. }
  197. }
  198. }
  199. }
  200. if (property != null)
  201. {
  202. accessor = new PropertyAccessor(memberName, property, indexerToTry);
  203. return true;
  204. }
  205. // look for a field
  206. FieldInfo field = null;
  207. foreach (var f in type.GetFields(bindingFlags))
  208. {
  209. if (!Filter(engine, f))
  210. {
  211. continue;
  212. }
  213. foreach (var name in typeResolverMemberNameCreator(f))
  214. {
  215. if (memberNameComparer.Equals(name, memberName))
  216. {
  217. field = f;
  218. break;
  219. }
  220. }
  221. }
  222. if (field != null)
  223. {
  224. accessor = new FieldAccessor(field, memberName, indexerToTry);
  225. return true;
  226. }
  227. // if no properties were found then look for a method
  228. List<MethodInfo> methods = null;
  229. foreach (var m in type.GetMethods(bindingFlags))
  230. {
  231. if (!Filter(engine, m))
  232. {
  233. continue;
  234. }
  235. foreach (var name in typeResolverMemberNameCreator(m))
  236. {
  237. if (memberNameComparer.Equals(name, memberName))
  238. {
  239. methods ??= new List<MethodInfo>();
  240. methods.Add(m);
  241. }
  242. }
  243. }
  244. // TPC: need to grab the extension methods here - for overloads
  245. MethodInfo[] extensionMethods;
  246. if (engine._extensionMethods.TryGetExtensionMethods(type, out extensionMethods))
  247. {
  248. foreach (var methodInfo in extensionMethods)
  249. {
  250. if (memberNameComparer.Equals(methodInfo.Name, memberName))
  251. {
  252. methods ??= new List<MethodInfo>();
  253. methods.Add(methodInfo);
  254. }
  255. }
  256. }
  257. if (methods?.Count > 0)
  258. {
  259. accessor = new MethodAccessor(MethodDescriptor.Build(methods));
  260. return true;
  261. }
  262. accessor = default;
  263. return false;
  264. }
  265. private sealed class DefaultMemberNameComparer : StringComparer
  266. {
  267. public static readonly StringComparer Instance = new DefaultMemberNameComparer();
  268. public override int Compare(string x, string y)
  269. {
  270. throw new NotImplementedException();
  271. }
  272. public override bool Equals(string x, string y)
  273. {
  274. if (ReferenceEquals(x, y))
  275. {
  276. return true;
  277. }
  278. if (x == null || y == null)
  279. {
  280. return false;
  281. }
  282. if (x.Length != y.Length)
  283. {
  284. return false;
  285. }
  286. var equals = false;
  287. if (x.Length > 0)
  288. {
  289. equals = char.ToLowerInvariant(x[0]) == char.ToLowerInvariant(y[0]);
  290. }
  291. if (equals && x.Length > 1)
  292. {
  293. #if NETSTANDARD2_1
  294. equals = x.AsSpan(1).SequenceEqual(y.AsSpan(1));
  295. #else
  296. equals = x.Substring(1) == y.Substring(1);
  297. #endif
  298. }
  299. return equals;
  300. }
  301. public override int GetHashCode(string obj)
  302. {
  303. throw new NotImplementedException();
  304. }
  305. }
  306. }
  307. }