TypeResolver.cs 16 KB

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