ObjectWrapper.cs 17 KB

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