ObjectWrapper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using System;
  2. using System.Collections;
  3. using System.Globalization;
  4. using System.Reflection;
  5. using Jint.Native;
  6. using Jint.Native.Iterator;
  7. using Jint.Native.Object;
  8. using Jint.Native.Symbol;
  9. using Jint.Runtime.Descriptors;
  10. using Jint.Runtime.Interop.Reflection;
  11. namespace Jint.Runtime.Interop
  12. {
  13. /// <summary>
  14. /// Wraps a CLR instance
  15. /// </summary>
  16. public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper, IEquatable<ObjectWrapper>
  17. {
  18. private readonly TypeDescriptor _typeDescriptor;
  19. private readonly Type _clrType;
  20. public ObjectWrapper(Engine engine, object obj, Type? type = null)
  21. : base(engine)
  22. {
  23. Target = obj;
  24. _clrType = ClrType(obj, type);
  25. _typeDescriptor = TypeDescriptor.Get(_clrType);
  26. if (_typeDescriptor.LengthProperty is not null)
  27. {
  28. // create a forwarder to produce length from Count or Length if one of them is present
  29. var functionInstance = new ClrFunctionInstance(engine, "length", GetLength);
  30. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  31. SetProperty(KnownKeys.Length, descriptor);
  32. }
  33. }
  34. public object Target { get; }
  35. public override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  36. internal override bool HasOriginalIterator => IsArrayLike;
  37. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexedArray;
  38. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  39. {
  40. // check if we can take shortcuts for empty object, no need to generate properties
  41. if (property is JsString stringKey)
  42. {
  43. var member = stringKey.ToString();
  44. if (_properties is null || !_properties.ContainsKey(member))
  45. {
  46. // can try utilize fast path
  47. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, _clrType, member, forWrite: true);
  48. if (ReferenceEquals(accessor, ConstantValueAccessor.NullAccessor))
  49. {
  50. // there's no such property, but we can allow extending by calling base
  51. // which will add properties, this allows for example JS class to extend a CLR type
  52. return base.Set(property, value, receiver);
  53. }
  54. // CanPut logic
  55. if (!accessor.Writable || !_engine.Options.Interop.AllowWrite)
  56. {
  57. return false;
  58. }
  59. accessor.SetValue(_engine, Target, value);
  60. return true;
  61. }
  62. }
  63. else if (property is JsSymbol jsSymbol)
  64. {
  65. // symbol addition will never hit any known CLR object properties, so if write is allowed, allow writing symbols too
  66. if (_engine.Options.Interop.AllowWrite)
  67. {
  68. return base.Set(jsSymbol, value, receiver);
  69. }
  70. return false;
  71. }
  72. return SetSlow(property, value);
  73. }
  74. private bool SetSlow(JsValue property, JsValue value)
  75. {
  76. if (!CanPut(property))
  77. {
  78. return false;
  79. }
  80. var ownDesc = GetOwnProperty(property);
  81. ownDesc.Value = value;
  82. return true;
  83. }
  84. public override object ToObject()
  85. {
  86. return Target;
  87. }
  88. public override void RemoveOwnProperty(JsValue property)
  89. {
  90. if (_engine.Options.Interop.AllowWrite && property is JsString jsString)
  91. {
  92. _typeDescriptor.Remove(Target, jsString.ToString());
  93. }
  94. }
  95. public override JsValue Get(JsValue property, JsValue receiver)
  96. {
  97. if (property.IsInteger() && Target is IList list)
  98. {
  99. var index = (int) ((JsNumber) property)._value;
  100. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  101. }
  102. return base.Get(property, receiver);
  103. }
  104. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  105. {
  106. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  107. }
  108. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  109. {
  110. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  111. {
  112. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  113. }
  114. }
  115. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  116. {
  117. // prefer object order, add possible other properties after
  118. var includeStrings = (types & Types.String) != 0;
  119. if (includeStrings && _typeDescriptor.IsStringKeyedGenericDictionary) // expando object for instance
  120. {
  121. var keys = _typeDescriptor.GetKeys(Target);
  122. foreach (var key in keys)
  123. {
  124. var jsString = JsString.Create(key);
  125. yield return jsString;
  126. }
  127. }
  128. else if (includeStrings && Target is IDictionary dictionary)
  129. {
  130. // we take values exposed as dictionary keys only
  131. foreach (var key in dictionary.Keys)
  132. {
  133. object? stringKey = key as string;
  134. if (stringKey is not null
  135. || _engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey))
  136. {
  137. var jsString = JsString.Create((string) stringKey!);
  138. yield return jsString;
  139. }
  140. }
  141. }
  142. else if (includeStrings)
  143. {
  144. // we take public properties and fields
  145. var type = _clrType;
  146. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  147. {
  148. var indexParameters = p.GetIndexParameters();
  149. if (indexParameters.Length == 0)
  150. {
  151. var jsString = JsString.Create(p.Name);
  152. yield return jsString;
  153. }
  154. }
  155. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  156. {
  157. var jsString = JsString.Create(f.Name);
  158. yield return jsString;
  159. }
  160. }
  161. }
  162. public override PropertyDescriptor GetOwnProperty(JsValue property)
  163. {
  164. if (TryGetProperty(property, out var x))
  165. {
  166. return x;
  167. }
  168. // if we have array-like or dictionary or expando, we can provide iterator
  169. if (property.IsSymbol())
  170. {
  171. if (property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  172. {
  173. var iteratorFunction = new ClrFunctionInstance(
  174. Engine,
  175. "iterator",
  176. Iterator,
  177. 1,
  178. PropertyFlag.Configurable);
  179. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  180. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  181. return iteratorProperty;
  182. }
  183. // not that safe
  184. return PropertyDescriptor.Undefined;
  185. }
  186. var member = property.ToString();
  187. // if type is dictionary, we cannot enumerate anything other than keys
  188. // and we cannot store accessors as dictionary can change dynamically
  189. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  190. if (isDictionary)
  191. {
  192. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  193. {
  194. var flags = PropertyFlag.Enumerable;
  195. if (_engine.Options.Interop.AllowWrite)
  196. {
  197. flags |= PropertyFlag.Configurable;
  198. }
  199. return new PropertyDescriptor(FromObject(_engine, value), flags);
  200. }
  201. }
  202. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  203. if (result is not null)
  204. {
  205. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  206. }
  207. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, _clrType, member);
  208. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
  209. if (!isDictionary && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined))
  210. {
  211. // cache the accessor for faster subsequent accesses
  212. SetProperty(member, descriptor);
  213. }
  214. return descriptor;
  215. }
  216. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  217. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  218. {
  219. // fast path which uses slow search if not found for some reason
  220. ReflectionAccessor? Factory()
  221. {
  222. return member switch
  223. {
  224. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  225. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  226. FieldInfo fi => new FieldAccessor(fi),
  227. _ => null
  228. };
  229. }
  230. return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  231. }
  232. public static Type ClrType(object obj, Type? type)
  233. {
  234. if (type is null || type == typeof(object))
  235. {
  236. return obj.GetType();
  237. }
  238. else
  239. {
  240. var underlyingType = Nullable.GetUnderlyingType(type);
  241. if (underlyingType is not null)
  242. {
  243. return underlyingType;
  244. }
  245. else
  246. {
  247. return type;
  248. }
  249. }
  250. }
  251. private static JsValue Iterator(JsValue thisObject, JsValue[] arguments)
  252. {
  253. var wrapper = (ObjectWrapper) thisObject;
  254. return wrapper._typeDescriptor.IsDictionary
  255. ? new DictionaryIterator(wrapper._engine, wrapper)
  256. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  257. }
  258. private static JsValue GetLength(JsValue thisObject, JsValue[] arguments)
  259. {
  260. var wrapper = (ObjectWrapper) thisObject;
  261. return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0));
  262. }
  263. internal override ulong GetSmallestIndex(ulong length)
  264. {
  265. return Target is ICollection ? 0 : base.GetSmallestIndex(length);
  266. }
  267. public override bool Equals(JsValue? obj)
  268. {
  269. return Equals(obj as ObjectWrapper);
  270. }
  271. public bool Equals(ObjectWrapper? other)
  272. {
  273. if (ReferenceEquals(null, other))
  274. {
  275. return false;
  276. }
  277. if (ReferenceEquals(this, other))
  278. {
  279. return true;
  280. }
  281. return Equals(Target, other.Target) && Equals(_clrType, other._clrType);
  282. }
  283. public override int GetHashCode()
  284. {
  285. var hashCode = -1468639730;
  286. hashCode = hashCode * -1521134295 + Target.GetHashCode();
  287. hashCode = hashCode * -1521134295 + _clrType.GetHashCode();
  288. return hashCode;
  289. }
  290. private sealed class DictionaryIterator : IteratorInstance
  291. {
  292. private readonly ObjectWrapper _target;
  293. private readonly IEnumerator<JsValue> _enumerator;
  294. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  295. {
  296. _target = target;
  297. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  298. }
  299. public override bool TryIteratorStep(out ObjectInstance nextItem)
  300. {
  301. if (_enumerator.MoveNext())
  302. {
  303. var key = _enumerator.Current;
  304. var value = _target.Get(key);
  305. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine, key, value);
  306. return true;
  307. }
  308. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  309. return false;
  310. }
  311. }
  312. private sealed class EnumerableIterator : IteratorInstance
  313. {
  314. private readonly IEnumerator _enumerator;
  315. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  316. {
  317. _enumerator = target.GetEnumerator();
  318. }
  319. public override void Close(CompletionType completion)
  320. {
  321. (_enumerator as IDisposable)?.Dispose();
  322. base.Close(completion);
  323. }
  324. public override bool TryIteratorStep(out ObjectInstance nextItem)
  325. {
  326. if (_enumerator.MoveNext())
  327. {
  328. var value = _enumerator.Current;
  329. nextItem = IteratorResult.CreateValueIteratorPosition(_engine, FromObject(_engine, value));
  330. return true;
  331. }
  332. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  333. return false;
  334. }
  335. }
  336. }
  337. }