TypeResolver.cs 16 KB

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