ObjectWrapper.cs 15 KB

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