TypeResolver.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. // properties and fields cannot be numbers
  101. if (!isInteger
  102. && TryFindMemberAccessor(engine, type, memberName, bindingFlags: null, indexer, out var temp)
  103. && (!mustBeReadable || temp.Readable)
  104. && (!mustBeWritable || temp.Writable))
  105. {
  106. return temp;
  107. }
  108. if (typeof(DynamicObject).IsAssignableFrom(type))
  109. {
  110. return new DynamicObjectAccessor();
  111. }
  112. var typeResolverMemberNameComparer = MemberNameComparer;
  113. var typeResolverMemberNameCreator = MemberNameCreator;
  114. if (!isInteger)
  115. {
  116. // try to find a single explicit property implementation
  117. List<PropertyInfo>? list = null;
  118. foreach (var iface in type.GetInterfaces())
  119. {
  120. foreach (var iprop in iface.GetProperties())
  121. {
  122. if (!Filter(engine, type, iprop))
  123. {
  124. continue;
  125. }
  126. if (string.Equals(iprop.Name, "Item", StringComparison.Ordinal) && iprop.GetIndexParameters().Length == 1)
  127. {
  128. // never take indexers, should use the actual indexer
  129. continue;
  130. }
  131. foreach (var name in typeResolverMemberNameCreator(iprop))
  132. {
  133. if (typeResolverMemberNameComparer.Equals(name, memberName))
  134. {
  135. list ??= new List<PropertyInfo>();
  136. list.Add(iprop);
  137. }
  138. }
  139. }
  140. }
  141. if (list?.Count == 1)
  142. {
  143. return new PropertyAccessor(list[0]);
  144. }
  145. // try to find explicit method implementations
  146. List<MethodInfo>? explicitMethods = null;
  147. foreach (var iface in type.GetInterfaces())
  148. {
  149. foreach (var imethod in iface.GetMethods())
  150. {
  151. if (!Filter(engine, type, imethod))
  152. {
  153. continue;
  154. }
  155. foreach (var name in typeResolverMemberNameCreator(imethod))
  156. {
  157. if (typeResolverMemberNameComparer.Equals(name, memberName))
  158. {
  159. explicitMethods ??= new List<MethodInfo>();
  160. explicitMethods.Add(imethod);
  161. }
  162. }
  163. }
  164. }
  165. if (explicitMethods?.Count > 0)
  166. {
  167. return new MethodAccessor(type, MethodDescriptor.Build(explicitMethods));
  168. }
  169. }
  170. // if no methods are found check if target implemented indexing
  171. var score = int.MaxValue;
  172. if (indexerAccessor != null)
  173. {
  174. var parameter = indexerAccessor.FirstIndexParameter;
  175. score = CalculateIndexerScore(parameter, isInteger);
  176. }
  177. if (score != 0)
  178. {
  179. // try to find explicit indexer implementations that has a better score than earlier
  180. foreach (var interfaceType in type.GetInterfaces())
  181. {
  182. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  183. {
  184. // ensure that original type is allowed against indexer
  185. if (!Filter(engine, type, accessor.Indexer))
  186. {
  187. continue;
  188. }
  189. var parameter = accessor.FirstIndexParameter;
  190. var newScore = CalculateIndexerScore(parameter, isInteger);
  191. if (newScore < score)
  192. {
  193. // found a better one
  194. indexerAccessor = accessor;
  195. score = newScore;
  196. }
  197. }
  198. }
  199. }
  200. // use the best indexer we were able to find
  201. if (indexerAccessor != null)
  202. {
  203. return indexerAccessor;
  204. }
  205. if (!isInteger && engine._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  206. {
  207. var matches = new List<MethodInfo>();
  208. foreach (var method in extensionMethods)
  209. {
  210. if (!Filter(engine, type, method))
  211. {
  212. continue;
  213. }
  214. foreach (var name in typeResolverMemberNameCreator(method))
  215. {
  216. if (typeResolverMemberNameComparer.Equals(name, memberName))
  217. {
  218. matches.Add(method);
  219. }
  220. }
  221. }
  222. if (matches.Count > 0)
  223. {
  224. return new MethodAccessor(type, MethodDescriptor.Build(matches));
  225. }
  226. }
  227. if (engine.Options.Interop.ThrowOnUnresolvedMember)
  228. {
  229. throw new MissingMemberException($"Cannot access property '{memberName}' on type '{type.FullName}");
  230. }
  231. return ConstantValueAccessor.NullAccessor;
  232. }
  233. private static int CalculateIndexerScore(ParameterInfo parameter, bool isInteger)
  234. {
  235. var paramType = parameter.ParameterType;
  236. if (paramType == typeof(int))
  237. {
  238. return isInteger ? 0 : 10;
  239. }
  240. if (paramType == typeof(string))
  241. {
  242. return 1;
  243. }
  244. return 5;
  245. }
  246. internal bool TryFindMemberAccessor(
  247. Engine engine,
  248. [DynamicallyAccessedMembers(InteropHelper.DefaultDynamicallyAccessedMemberTypes | DynamicallyAccessedMemberTypes.Interfaces)] Type type,
  249. string memberName,
  250. BindingFlags? bindingFlags,
  251. PropertyInfo? indexerToTry,
  252. [NotNullWhen(true)] out ReflectionAccessor? accessor)
  253. {
  254. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  255. PropertyInfo? property = null;
  256. var memberNameComparer = MemberNameComparer;
  257. var typeResolverMemberNameCreator = MemberNameCreator;
  258. PropertyInfo? GetProperty([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type t)
  259. {
  260. foreach (var p in t.GetProperties(bindingFlags ?? engine.Options.Interop.ObjectWrapperReportedPropertyBindingFlags))
  261. {
  262. if (!Filter(engine, type, p))
  263. {
  264. continue;
  265. }
  266. // only if it's not an indexer, we can do case-ignoring matches
  267. var isStandardIndexer = string.Equals(p.Name, "Item", StringComparison.Ordinal) && p.GetIndexParameters().Length == 1;
  268. if (!isStandardIndexer)
  269. {
  270. foreach (var name in typeResolverMemberNameCreator(p))
  271. {
  272. if (memberNameComparer.Equals(name, memberName))
  273. {
  274. // If one property hides another (e.g., by public new), the derived property is returned.
  275. if (property is not null
  276. && p.DeclaringType is not null
  277. && property.DeclaringType is not null
  278. && property.DeclaringType.IsSubclassOf(p.DeclaringType))
  279. {
  280. continue;
  281. }
  282. property = p;
  283. break;
  284. }
  285. }
  286. }
  287. }
  288. return property;
  289. }
  290. property = GetProperty(type);
  291. if (property is null && type.IsInterface)
  292. {
  293. // check inherited interfaces
  294. foreach (var iface in type.GetInterfaces())
  295. {
  296. property = GetProperty(iface);
  297. if (property is not null)
  298. {
  299. break;
  300. }
  301. }
  302. }
  303. if (property is not null)
  304. {
  305. accessor = new PropertyAccessor(property, indexerToTry);
  306. return true;
  307. }
  308. // look for a field
  309. FieldInfo? field = null;
  310. foreach (var f in type.GetFields(bindingFlags ?? engine.Options.Interop.ObjectWrapperReportedFieldBindingFlags))
  311. {
  312. if (!Filter(engine, type, f))
  313. {
  314. continue;
  315. }
  316. foreach (var name in typeResolverMemberNameCreator(f))
  317. {
  318. if (memberNameComparer.Equals(name, memberName))
  319. {
  320. field = f;
  321. break;
  322. }
  323. }
  324. }
  325. if (field is not null)
  326. {
  327. accessor = new FieldAccessor(field, indexerToTry);
  328. return true;
  329. }
  330. // if no properties were found then look for a method
  331. List<MethodInfo>? methods = null;
  332. void AddMethod(MethodInfo m)
  333. {
  334. if (!Filter(engine, type, m))
  335. {
  336. return;
  337. }
  338. foreach (var name in typeResolverMemberNameCreator(m))
  339. {
  340. if (memberNameComparer.Equals(name, memberName))
  341. {
  342. methods ??= new List<MethodInfo>();
  343. methods.Add(m);
  344. }
  345. }
  346. }
  347. foreach (var m in type.GetMethods(bindingFlags ?? engine.Options.Interop.ObjectWrapperReportedMethodBindingFlags))
  348. {
  349. AddMethod(m);
  350. }
  351. foreach (var iface in type.GetInterfaces())
  352. {
  353. foreach (var m in iface.GetMethods())
  354. {
  355. AddMethod(m);
  356. }
  357. }
  358. // TPC: need to grab the extension methods here - for overloads
  359. if (engine._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  360. {
  361. foreach (var methodInfo in extensionMethods)
  362. {
  363. AddMethod(methodInfo);
  364. }
  365. }
  366. // Add Object methods to interface
  367. if (type.IsInterface)
  368. {
  369. foreach (var m in typeof(object).GetMethods(bindingFlags ?? engine.Options.Interop.ObjectWrapperReportedMethodBindingFlags))
  370. {
  371. AddMethod(m);
  372. }
  373. }
  374. if (methods?.Count > 0)
  375. {
  376. accessor = new MethodAccessor(type, MethodDescriptor.Build(methods));
  377. return true;
  378. }
  379. // look for nested type
  380. var nestedType = type.GetNestedType(memberName, bindingFlags ?? BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
  381. if (nestedType != null)
  382. {
  383. var typeReference = TypeReference.CreateTypeReference(engine, nestedType);
  384. accessor = new NestedTypeAccessor(typeReference);
  385. return true;
  386. }
  387. accessor = default;
  388. return false;
  389. }
  390. private sealed class DefaultMemberNameComparer : StringComparer
  391. {
  392. public static readonly StringComparer Instance = new DefaultMemberNameComparer();
  393. public override int Compare(string? x, string? y)
  394. {
  395. throw new NotImplementedException();
  396. }
  397. public override bool Equals(string? x, string? y)
  398. {
  399. if (ReferenceEquals(x, y))
  400. {
  401. return true;
  402. }
  403. if (x == null || y == null)
  404. {
  405. return false;
  406. }
  407. if (x.Length != y.Length)
  408. {
  409. return false;
  410. }
  411. var equals = false;
  412. if (x.Length > 0)
  413. {
  414. equals = char.ToLowerInvariant(x[0]) == char.ToLowerInvariant(y[0]);
  415. }
  416. if (equals && x.Length > 1)
  417. {
  418. #if SUPPORTS_SPAN_PARSE
  419. equals = x.AsSpan(1).SequenceEqual(y.AsSpan(1));
  420. #else
  421. equals = string.Equals(x.Substring(1), y.Substring(1), StringComparison.Ordinal);
  422. #endif
  423. }
  424. return equals;
  425. }
  426. public override int GetHashCode(string obj)
  427. {
  428. throw new NotImplementedException();
  429. }
  430. }
  431. }