TypeResolver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. // If one property hides another (e.g., by public new), the derived property is returned.
  276. if (property is not null
  277. && p.DeclaringType is not null
  278. && property.DeclaringType is not null
  279. && property.DeclaringType.IsSubclassOf(p.DeclaringType))
  280. {
  281. continue;
  282. }
  283. property = p;
  284. break;
  285. }
  286. }
  287. }
  288. }
  289. return property;
  290. }
  291. property = GetProperty(type);
  292. if (property is null && type.IsInterface)
  293. {
  294. // check inherited interfaces
  295. foreach (var iface in type.GetInterfaces())
  296. {
  297. property = GetProperty(iface);
  298. if (property is not null)
  299. {
  300. break;
  301. }
  302. }
  303. }
  304. if (property is not null)
  305. {
  306. accessor = new PropertyAccessor(property, indexerToTry);
  307. return true;
  308. }
  309. // look for a field
  310. FieldInfo? field = null;
  311. foreach (var f in type.GetFields(bindingFlags))
  312. {
  313. if (!Filter(engine, type, f))
  314. {
  315. continue;
  316. }
  317. foreach (var name in typeResolverMemberNameCreator(f))
  318. {
  319. if (memberNameComparer.Equals(name, memberName))
  320. {
  321. field = f;
  322. break;
  323. }
  324. }
  325. }
  326. if (field is not null)
  327. {
  328. accessor = new FieldAccessor(field, indexerToTry);
  329. return true;
  330. }
  331. // if no properties were found then look for a method
  332. List<MethodInfo>? methods = null;
  333. void AddMethod(MethodInfo m)
  334. {
  335. if (!Filter(engine, type, m))
  336. {
  337. return;
  338. }
  339. foreach (var name in typeResolverMemberNameCreator(m))
  340. {
  341. if (memberNameComparer.Equals(name, memberName))
  342. {
  343. methods ??= new List<MethodInfo>();
  344. methods.Add(m);
  345. }
  346. }
  347. }
  348. foreach (var m in type.GetMethods(bindingFlags))
  349. {
  350. AddMethod(m);
  351. }
  352. foreach (var iface in type.GetInterfaces())
  353. {
  354. foreach (var m in iface.GetMethods())
  355. {
  356. AddMethod(m);
  357. }
  358. }
  359. // TPC: need to grab the extension methods here - for overloads
  360. if (engine._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  361. {
  362. foreach (var methodInfo in extensionMethods)
  363. {
  364. AddMethod(methodInfo);
  365. }
  366. }
  367. // Add Object methods to interface
  368. if (type.IsInterface)
  369. {
  370. foreach (var m in typeof(object).GetMethods(bindingFlags))
  371. {
  372. AddMethod(m);
  373. }
  374. }
  375. if (methods?.Count > 0)
  376. {
  377. accessor = new MethodAccessor(type, MethodDescriptor.Build(methods));
  378. return true;
  379. }
  380. // look for nested type
  381. var nestedType = type.GetNestedType(memberName, bindingFlags);
  382. if (nestedType != null)
  383. {
  384. var typeReference = TypeReference.CreateTypeReference(engine, nestedType);
  385. accessor = new NestedTypeAccessor(typeReference);
  386. return true;
  387. }
  388. accessor = default;
  389. return false;
  390. }
  391. private sealed class DefaultMemberNameComparer : StringComparer
  392. {
  393. public static readonly StringComparer Instance = new DefaultMemberNameComparer();
  394. public override int Compare(string? x, string? y)
  395. {
  396. throw new NotImplementedException();
  397. }
  398. public override bool Equals(string? x, string? y)
  399. {
  400. if (ReferenceEquals(x, y))
  401. {
  402. return true;
  403. }
  404. if (x == null || y == null)
  405. {
  406. return false;
  407. }
  408. if (x.Length != y.Length)
  409. {
  410. return false;
  411. }
  412. var equals = false;
  413. if (x.Length > 0)
  414. {
  415. equals = char.ToLowerInvariant(x[0]) == char.ToLowerInvariant(y[0]);
  416. }
  417. if (equals && x.Length > 1)
  418. {
  419. #if SUPPORTS_SPAN_PARSE
  420. equals = x.AsSpan(1).SequenceEqual(y.AsSpan(1));
  421. #else
  422. equals = string.Equals(x.Substring(1), y.Substring(1), StringComparison.Ordinal);
  423. #endif
  424. }
  425. return equals;
  426. }
  427. public override int GetHashCode(string obj)
  428. {
  429. throw new NotImplementedException();
  430. }
  431. }
  432. }