TypeResolver.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. if (engine.Options.Interop.ThrowOnUnresolvedMember)
  230. {
  231. throw new MissingMemberException($"Cannot access property '{memberName}' on type '{type.FullName}");
  232. }
  233. return ConstantValueAccessor.NullAccessor;
  234. }
  235. private static int CalculateIndexerScore(ParameterInfo parameter, bool isInteger)
  236. {
  237. var paramType = parameter.ParameterType;
  238. if (paramType == typeof(int))
  239. {
  240. return isInteger ? 0 : 10;
  241. }
  242. if (paramType == typeof(string))
  243. {
  244. return 1;
  245. }
  246. return 5;
  247. }
  248. internal bool TryFindMemberAccessor(
  249. Engine engine,
  250. [DynamicallyAccessedMembers(InteropHelper.DefaultDynamicallyAccessedMemberTypes | DynamicallyAccessedMemberTypes.Interfaces)] Type type,
  251. string memberName,
  252. BindingFlags bindingFlags,
  253. PropertyInfo? indexerToTry,
  254. [NotNullWhen(true)] out ReflectionAccessor? accessor)
  255. {
  256. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  257. PropertyInfo? property = null;
  258. var memberNameComparer = MemberNameComparer;
  259. var typeResolverMemberNameCreator = MemberNameCreator;
  260. PropertyInfo? GetProperty([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type t)
  261. {
  262. foreach (var p in t.GetProperties(bindingFlags))
  263. {
  264. if (!Filter(engine, type, p))
  265. {
  266. continue;
  267. }
  268. // only if it's not an indexer, we can do case-ignoring matches
  269. var isStandardIndexer = string.Equals(p.Name, "Item", StringComparison.Ordinal) && p.GetIndexParameters().Length == 1;
  270. if (!isStandardIndexer)
  271. {
  272. foreach (var name in typeResolverMemberNameCreator(p))
  273. {
  274. if (memberNameComparer.Equals(name, memberName))
  275. {
  276. property = p;
  277. break;
  278. }
  279. }
  280. }
  281. }
  282. return property;
  283. }
  284. property = GetProperty(type);
  285. if (property is null && type.IsInterface)
  286. {
  287. // check inherited interfaces
  288. foreach (var iface in type.GetInterfaces())
  289. {
  290. property = GetProperty(iface);
  291. if (property is not null)
  292. {
  293. break;
  294. }
  295. }
  296. }
  297. if (property is not null)
  298. {
  299. accessor = new PropertyAccessor(property, indexerToTry);
  300. return true;
  301. }
  302. // look for a field
  303. FieldInfo? field = null;
  304. foreach (var f in type.GetFields(bindingFlags))
  305. {
  306. if (!Filter(engine, type, f))
  307. {
  308. continue;
  309. }
  310. foreach (var name in typeResolverMemberNameCreator(f))
  311. {
  312. if (memberNameComparer.Equals(name, memberName))
  313. {
  314. field = f;
  315. break;
  316. }
  317. }
  318. }
  319. if (field is not null)
  320. {
  321. accessor = new FieldAccessor(field, indexerToTry);
  322. return true;
  323. }
  324. // if no properties were found then look for a method
  325. List<MethodInfo>? methods = null;
  326. void AddMethod(MethodInfo m)
  327. {
  328. if (!Filter(engine, type, m))
  329. {
  330. return;
  331. }
  332. foreach (var name in typeResolverMemberNameCreator(m))
  333. {
  334. if (memberNameComparer.Equals(name, memberName))
  335. {
  336. methods ??= new List<MethodInfo>();
  337. methods.Add(m);
  338. }
  339. }
  340. }
  341. foreach (var m in type.GetMethods(bindingFlags))
  342. {
  343. AddMethod(m);
  344. }
  345. foreach (var iface in type.GetInterfaces())
  346. {
  347. foreach (var m in iface.GetMethods())
  348. {
  349. AddMethod(m);
  350. }
  351. }
  352. // TPC: need to grab the extension methods here - for overloads
  353. if (engine._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  354. {
  355. foreach (var methodInfo in extensionMethods)
  356. {
  357. AddMethod(methodInfo);
  358. }
  359. }
  360. // Add Object methods to interface
  361. if (type.IsInterface)
  362. {
  363. foreach (var m in typeof(object).GetMethods(bindingFlags))
  364. {
  365. AddMethod(m);
  366. }
  367. }
  368. if (methods?.Count > 0)
  369. {
  370. accessor = new MethodAccessor(type, MethodDescriptor.Build(methods));
  371. return true;
  372. }
  373. // look for nested type
  374. var nestedType = type.GetNestedType(memberName, bindingFlags);
  375. if (nestedType != null)
  376. {
  377. var typeReference = TypeReference.CreateTypeReference(engine, nestedType);
  378. accessor = new NestedTypeAccessor(typeReference);
  379. return true;
  380. }
  381. accessor = default;
  382. return false;
  383. }
  384. private sealed class DefaultMemberNameComparer : StringComparer
  385. {
  386. public static readonly StringComparer Instance = new DefaultMemberNameComparer();
  387. public override int Compare(string? x, string? y)
  388. {
  389. throw new NotImplementedException();
  390. }
  391. public override bool Equals(string? x, string? y)
  392. {
  393. if (ReferenceEquals(x, y))
  394. {
  395. return true;
  396. }
  397. if (x == null || y == null)
  398. {
  399. return false;
  400. }
  401. if (x.Length != y.Length)
  402. {
  403. return false;
  404. }
  405. var equals = false;
  406. if (x.Length > 0)
  407. {
  408. equals = char.ToLowerInvariant(x[0]) == char.ToLowerInvariant(y[0]);
  409. }
  410. if (equals && x.Length > 1)
  411. {
  412. #if SUPPORTS_SPAN_PARSE
  413. equals = x.AsSpan(1).SequenceEqual(y.AsSpan(1));
  414. #else
  415. equals = string.Equals(x.Substring(1), y.Substring(1), StringComparison.Ordinal);
  416. #endif
  417. }
  418. return equals;
  419. }
  420. public override int GetHashCode(string obj)
  421. {
  422. throw new NotImplementedException();
  423. }
  424. }
  425. }
  426. }