TypeResolver.cs 16 KB

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