TypeResolver.cs 12 KB

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