TypeResolver.cs 18 KB

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