TypeResolver.cs 12 KB

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