ObjectWrapper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Reflection;
  6. using System.Threading;
  7. using Jint.Native;
  8. using Jint.Native.Object;
  9. using Jint.Native.Symbol;
  10. using Jint.Runtime.Descriptors;
  11. using Jint.Runtime.Interop.Reflection;
  12. namespace Jint.Runtime.Interop
  13. {
  14. /// <summary>
  15. /// Wraps a CLR instance
  16. /// </summary>
  17. public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper
  18. {
  19. private readonly TypeDescriptor _typeDescriptor;
  20. public ObjectWrapper(Engine engine, object obj)
  21. : base(engine)
  22. {
  23. Target = obj;
  24. _typeDescriptor = TypeDescriptor.Get(obj.GetType());
  25. if (_typeDescriptor.IsArrayLike)
  26. {
  27. // create a forwarder to produce length from Count or Length if one of them is present
  28. var lengthProperty = obj.GetType().GetProperty("Count") ?? obj.GetType().GetProperty("Length");
  29. if (lengthProperty is null)
  30. {
  31. return;
  32. }
  33. var functionInstance = new ClrFunctionInstance(engine, "length", (_, _) => JsNumber.Create((int) lengthProperty.GetValue(obj)));
  34. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  35. SetProperty(KnownKeys.Length, descriptor);
  36. }
  37. }
  38. public object Target { get; }
  39. public override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  40. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexedArray;
  41. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  42. {
  43. // check if we can take shortcuts for empty object, no need to generate properties
  44. if (property is JsString stringKey)
  45. {
  46. var member = stringKey.ToString();
  47. if (_properties is null || !_properties.ContainsKey(member))
  48. {
  49. // can try utilize fast path
  50. var accessor = GetAccessor(_engine, Target.GetType(), member);
  51. // CanPut logic
  52. if (!accessor.Writable || !_engine.Options._IsClrWriteAllowed)
  53. {
  54. return false;
  55. }
  56. accessor.SetValue(_engine, Target, value);
  57. return true;
  58. }
  59. }
  60. return SetSlow(property, value);
  61. }
  62. private bool SetSlow(JsValue property, JsValue value)
  63. {
  64. if (!CanPut(property))
  65. {
  66. return false;
  67. }
  68. var ownDesc = GetOwnProperty(property);
  69. if (ownDesc == null)
  70. {
  71. return false;
  72. }
  73. ownDesc.Value = value;
  74. return true;
  75. }
  76. public override JsValue Get(JsValue property, JsValue receiver)
  77. {
  78. if (property.IsInteger() && Target is IList list)
  79. {
  80. var index = (int) ((JsNumber) property)._value;
  81. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  82. }
  83. if (property.IsSymbol() && property != GlobalSymbolRegistry.Iterator)
  84. {
  85. // wrapped objects cannot have symbol properties
  86. return Undefined;
  87. }
  88. if (property is JsString stringKey)
  89. {
  90. var member = stringKey.ToString();
  91. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  92. if (result is not null)
  93. {
  94. return result;
  95. }
  96. if (_properties is null || !_properties.ContainsKey(member))
  97. {
  98. // can try utilize fast path
  99. var accessor = GetAccessor(_engine, Target.GetType(), member);
  100. var value = accessor.GetValue(_engine, Target);
  101. if (value is not null)
  102. {
  103. return FromObject(_engine, value);
  104. }
  105. }
  106. }
  107. return base.Get(property, receiver);
  108. }
  109. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  110. {
  111. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  112. }
  113. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  114. {
  115. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  116. {
  117. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  118. }
  119. }
  120. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  121. {
  122. var basePropertyKeys = base.GetOwnPropertyKeys(types);
  123. // prefer object order, add possible other properties after
  124. var processed = basePropertyKeys.Count > 0 ? new HashSet<JsValue>() : null;
  125. var includeStrings = (types & Types.String) != 0;
  126. if (Target is IDictionary dictionary && includeStrings)
  127. {
  128. // we take values exposed as dictionary keys only
  129. foreach (var key in dictionary.Keys)
  130. {
  131. if (_engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out var stringKey))
  132. {
  133. var jsString = JsString.Create((string) stringKey);
  134. processed?.Add(jsString);
  135. yield return jsString;
  136. }
  137. }
  138. }
  139. else if (includeStrings)
  140. {
  141. // we take public properties and fields
  142. var type = Target.GetType();
  143. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  144. {
  145. var indexParameters = p.GetIndexParameters();
  146. if (indexParameters.Length == 0)
  147. {
  148. var jsString = JsString.Create(p.Name);
  149. processed?.Add(jsString);
  150. yield return jsString;
  151. }
  152. }
  153. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  154. {
  155. var jsString = JsString.Create(f.Name);
  156. processed?.Add(jsString);
  157. yield return jsString;
  158. }
  159. }
  160. if (processed != null)
  161. {
  162. // we have base keys
  163. for (var i = 0; i < basePropertyKeys.Count; i++)
  164. {
  165. var key = basePropertyKeys[i];
  166. if (processed.Add(key))
  167. {
  168. yield return key;
  169. }
  170. }
  171. }
  172. }
  173. public override PropertyDescriptor GetOwnProperty(JsValue property)
  174. {
  175. if (TryGetProperty(property, out var x))
  176. {
  177. return x;
  178. }
  179. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator)
  180. {
  181. var iteratorFunction = new ClrFunctionInstance(Engine, "iterator", (thisObject, arguments) => _engine.Iterator.Construct(this), 1, PropertyFlag.Configurable);
  182. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  183. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  184. return iteratorProperty;
  185. }
  186. var member = property.ToString();
  187. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  188. if (result is not null)
  189. {
  190. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  191. }
  192. var accessor = GetAccessor(_engine, Target.GetType(), member);
  193. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target);
  194. SetProperty(member, descriptor);
  195. return descriptor;
  196. }
  197. private static ReflectionAccessor GetAccessor(Engine engine, Type type, string member)
  198. {
  199. var key = new ClrPropertyDescriptorFactoriesKey(type, member);
  200. var factories = Engine.ReflectionAccessors;
  201. if (factories.TryGetValue(key, out var accessor))
  202. {
  203. return accessor;
  204. }
  205. var factory = ResolvePropertyDescriptorFactory(engine, type, member);
  206. // racy, we don't care, worst case we'll catch up later
  207. Interlocked.CompareExchange(ref Engine.ReflectionAccessors,
  208. new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(factories)
  209. {
  210. [key] = factory
  211. }, factories);
  212. return factory;
  213. }
  214. private static ReflectionAccessor ResolvePropertyDescriptorFactory(Engine engine, Type type, string memberName)
  215. {
  216. var isNumber = uint.TryParse(memberName, out _);
  217. // we can always check indexer if there's one, and then fall back to properties if indexer returns null
  218. IndexerAccessor.TryFindIndexer(engine, type, memberName, out var indexerAccessor, out var indexer);
  219. // properties and fields cannot be numbers
  220. if (!isNumber && TryFindStringPropertyAccessor(type, memberName, indexer, out var temp))
  221. {
  222. return temp;
  223. }
  224. // if no methods are found check if target implemented indexing
  225. if (indexerAccessor != null)
  226. {
  227. return indexerAccessor;
  228. }
  229. // try to find a single explicit property implementation
  230. List<PropertyInfo> list = null;
  231. foreach (Type iface in type.GetInterfaces())
  232. {
  233. foreach (var iprop in iface.GetProperties())
  234. {
  235. if (EqualsIgnoreCasing(iprop.Name, memberName))
  236. {
  237. list ??= new List<PropertyInfo>();
  238. list.Add(iprop);
  239. }
  240. }
  241. }
  242. if (list?.Count == 1)
  243. {
  244. return new PropertyAccessor(memberName, list[0]);
  245. }
  246. // try to find explicit method implementations
  247. List<MethodInfo> explicitMethods = null;
  248. foreach (Type iface in type.GetInterfaces())
  249. {
  250. foreach (var imethod in iface.GetMethods())
  251. {
  252. if (EqualsIgnoreCasing(imethod.Name, memberName))
  253. {
  254. explicitMethods ??= new List<MethodInfo>();
  255. explicitMethods.Add(imethod);
  256. }
  257. }
  258. }
  259. if (explicitMethods?.Count > 0)
  260. {
  261. return new MethodAccessor(MethodDescriptor.Build(explicitMethods));
  262. }
  263. // try to find explicit indexer implementations
  264. foreach (var interfaceType in type.GetInterfaces())
  265. {
  266. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  267. {
  268. return accessor;
  269. }
  270. }
  271. if (engine.Options._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  272. {
  273. var matches = new List<MethodInfo>();
  274. foreach (var method in extensionMethods)
  275. {
  276. if (EqualsIgnoreCasing(method.Name, memberName))
  277. {
  278. matches.Add(method);
  279. }
  280. }
  281. return new MethodAccessor(MethodDescriptor.Build(matches));
  282. }
  283. return ConstantValueAccessor.NullAccessor;
  284. }
  285. private static bool TryFindStringPropertyAccessor(
  286. Type type,
  287. string memberName,
  288. PropertyInfo indexerToTry,
  289. out ReflectionAccessor wrapper)
  290. {
  291. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  292. PropertyInfo property = null;
  293. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  294. {
  295. // only if it's not an indexer, we can do case-ignoring matches
  296. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  297. if (!isStandardIndexer && EqualsIgnoreCasing(p.Name, memberName))
  298. {
  299. property = p;
  300. break;
  301. }
  302. }
  303. if (property != null)
  304. {
  305. wrapper = new PropertyAccessor(memberName, property, indexerToTry);
  306. return true;
  307. }
  308. // look for a field
  309. FieldInfo field = null;
  310. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  311. {
  312. if (EqualsIgnoreCasing(f.Name, memberName))
  313. {
  314. field = f;
  315. break;
  316. }
  317. }
  318. if (field != null)
  319. {
  320. wrapper = new FieldAccessor(field, memberName, indexerToTry);
  321. return true;
  322. }
  323. // if no properties were found then look for a method
  324. List<MethodInfo> methods = null;
  325. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  326. {
  327. if (EqualsIgnoreCasing(m.Name, memberName))
  328. {
  329. methods ??= new List<MethodInfo>();
  330. methods.Add(m);
  331. }
  332. }
  333. if (methods?.Count > 0)
  334. {
  335. wrapper = new MethodAccessor(MethodDescriptor.Build(methods));
  336. return true;
  337. }
  338. wrapper = default;
  339. return false;
  340. }
  341. private static bool EqualsIgnoreCasing(string s1, string s2)
  342. {
  343. if (s1.Length != s2.Length)
  344. {
  345. return false;
  346. }
  347. var equals = false;
  348. if (s1.Length > 0)
  349. {
  350. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  351. }
  352. if (@equals && s1.Length > 1)
  353. {
  354. #if NETSTANDARD2_1
  355. equals = s1.AsSpan(1).SequenceEqual(s2.AsSpan(1));
  356. #else
  357. equals = s1.Substring(1) == s2.Substring(1);
  358. #endif
  359. }
  360. return equals;
  361. }
  362. }
  363. }