TypeResolver.cs 15 KB

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