ObjectWrapper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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(
  193. Engine, "iterator",
  194. (thisObject, arguments) => _engine.Realm.Intrinsics.ArrayIteratorPrototype.Construct(this, intrinsics => intrinsics.IteratorPrototype),
  195. 1,
  196. PropertyFlag.Configurable);
  197. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  198. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  199. return iteratorProperty;
  200. }
  201. var member = property.ToString();
  202. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  203. if (result is not null)
  204. {
  205. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  206. }
  207. var accessor = GetAccessor(_engine, Target.GetType(), member);
  208. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target);
  209. SetProperty(member, descriptor);
  210. return descriptor;
  211. }
  212. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  213. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  214. {
  215. // fast path which uses slow search if not found for some reason
  216. ReflectionAccessor Factory()
  217. {
  218. return member switch
  219. {
  220. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  221. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  222. FieldInfo fi => new FieldAccessor(fi),
  223. _ => null
  224. };
  225. }
  226. return GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  227. }
  228. private static ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func<ReflectionAccessor> accessorFactory = null)
  229. {
  230. var key = new ClrPropertyDescriptorFactoriesKey(type, member);
  231. var factories = Engine.ReflectionAccessors;
  232. if (factories.TryGetValue(key, out var accessor))
  233. {
  234. return accessor;
  235. }
  236. accessor = accessorFactory?.Invoke() ?? ResolvePropertyDescriptorFactory(engine, type, member);
  237. // racy, we don't care, worst case we'll catch up later
  238. Interlocked.CompareExchange(ref Engine.ReflectionAccessors,
  239. new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(factories)
  240. {
  241. [key] = accessor
  242. }, factories);
  243. return accessor;
  244. }
  245. private static ReflectionAccessor ResolvePropertyDescriptorFactory(Engine engine, Type type, string memberName)
  246. {
  247. var isNumber = uint.TryParse(memberName, out _);
  248. // we can always check indexer if there's one, and then fall back to properties if indexer returns null
  249. IndexerAccessor.TryFindIndexer(engine, type, memberName, out var indexerAccessor, out var indexer);
  250. // properties and fields cannot be numbers
  251. if (!isNumber && TryFindStringPropertyAccessor(type, memberName, indexer, out var temp))
  252. {
  253. return temp;
  254. }
  255. if (typeof(DynamicObject).IsAssignableFrom(type))
  256. {
  257. return new DynamicObjectAccessor(type, memberName);
  258. }
  259. // if no methods are found check if target implemented indexing
  260. if (indexerAccessor != null)
  261. {
  262. return indexerAccessor;
  263. }
  264. // try to find a single explicit property implementation
  265. List<PropertyInfo> list = null;
  266. foreach (Type iface in type.GetInterfaces())
  267. {
  268. foreach (var iprop in iface.GetProperties())
  269. {
  270. if (iprop.Name == "Item" && iprop.GetIndexParameters().Length == 1)
  271. {
  272. // never take indexers, should use the actual indexer
  273. continue;
  274. }
  275. if (EqualsIgnoreCasing(iprop.Name, memberName))
  276. {
  277. list ??= new List<PropertyInfo>();
  278. list.Add(iprop);
  279. }
  280. }
  281. }
  282. if (list?.Count == 1)
  283. {
  284. return new PropertyAccessor(memberName, list[0]);
  285. }
  286. // try to find explicit method implementations
  287. List<MethodInfo> explicitMethods = null;
  288. foreach (Type iface in type.GetInterfaces())
  289. {
  290. foreach (var imethod in iface.GetMethods())
  291. {
  292. if (EqualsIgnoreCasing(imethod.Name, memberName))
  293. {
  294. explicitMethods ??= new List<MethodInfo>();
  295. explicitMethods.Add(imethod);
  296. }
  297. }
  298. }
  299. if (explicitMethods?.Count > 0)
  300. {
  301. return new MethodAccessor(MethodDescriptor.Build(explicitMethods));
  302. }
  303. // try to find explicit indexer implementations
  304. foreach (var interfaceType in type.GetInterfaces())
  305. {
  306. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  307. {
  308. return accessor;
  309. }
  310. }
  311. if (engine.Options._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  312. {
  313. var matches = new List<MethodInfo>();
  314. foreach (var method in extensionMethods)
  315. {
  316. if (EqualsIgnoreCasing(method.Name, memberName))
  317. {
  318. matches.Add(method);
  319. }
  320. }
  321. if (matches.Count > 0)
  322. {
  323. return new MethodAccessor(MethodDescriptor.Build(matches));
  324. }
  325. }
  326. return ConstantValueAccessor.NullAccessor;
  327. }
  328. private static bool TryFindStringPropertyAccessor(
  329. Type type,
  330. string memberName,
  331. PropertyInfo indexerToTry,
  332. out ReflectionAccessor wrapper)
  333. {
  334. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  335. PropertyInfo property = null;
  336. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  337. {
  338. // only if it's not an indexer, we can do case-ignoring matches
  339. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  340. if (!isStandardIndexer && EqualsIgnoreCasing(p.Name, memberName))
  341. {
  342. property = p;
  343. break;
  344. }
  345. }
  346. if (property != null)
  347. {
  348. wrapper = new PropertyAccessor(memberName, property, indexerToTry);
  349. return true;
  350. }
  351. // look for a field
  352. FieldInfo field = null;
  353. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  354. {
  355. if (EqualsIgnoreCasing(f.Name, memberName))
  356. {
  357. field = f;
  358. break;
  359. }
  360. }
  361. if (field != null)
  362. {
  363. wrapper = new FieldAccessor(field, memberName, indexerToTry);
  364. return true;
  365. }
  366. // if no properties were found then look for a method
  367. List<MethodInfo> methods = null;
  368. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  369. {
  370. if (EqualsIgnoreCasing(m.Name, memberName))
  371. {
  372. methods ??= new List<MethodInfo>();
  373. methods.Add(m);
  374. }
  375. }
  376. if (methods?.Count > 0)
  377. {
  378. wrapper = new MethodAccessor(MethodDescriptor.Build(methods));
  379. return true;
  380. }
  381. wrapper = default;
  382. return false;
  383. }
  384. private static bool EqualsIgnoreCasing(string s1, string s2)
  385. {
  386. if (s1.Length != s2.Length)
  387. {
  388. return false;
  389. }
  390. var equals = false;
  391. if (s1.Length > 0)
  392. {
  393. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  394. }
  395. if (@equals && s1.Length > 1)
  396. {
  397. #if NETSTANDARD2_1
  398. equals = s1.AsSpan(1).SequenceEqual(s2.AsSpan(1));
  399. #else
  400. equals = s1.Substring(1) == s2.Substring(1);
  401. #endif
  402. }
  403. return equals;
  404. }
  405. public override bool Equals(JsValue obj)
  406. {
  407. return Equals(obj as ObjectWrapper);
  408. }
  409. public override bool Equals(object obj)
  410. {
  411. return Equals(obj as ObjectWrapper);
  412. }
  413. public bool Equals(ObjectWrapper other)
  414. {
  415. if (ReferenceEquals(null, other))
  416. {
  417. return false;
  418. }
  419. if (ReferenceEquals(this, other))
  420. {
  421. return true;
  422. }
  423. return Equals(Target, other.Target);
  424. }
  425. public override int GetHashCode()
  426. {
  427. return Target?.GetHashCode() ?? 0;
  428. }
  429. }
  430. }