ObjectWrapper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 ClrFunctionInstance(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, forWrite: 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. return base.Get(property, receiver);
  102. }
  103. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  104. {
  105. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  106. }
  107. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  108. {
  109. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  110. {
  111. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  112. }
  113. }
  114. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  115. {
  116. // prefer object order, add possible other properties after
  117. var includeStrings = (types & Types.String) != Types.None;
  118. if (includeStrings && _typeDescriptor.IsStringKeyedGenericDictionary) // expando object for instance
  119. {
  120. var keys = _typeDescriptor.GetKeys(Target);
  121. foreach (var key in keys)
  122. {
  123. var jsString = JsString.Create(key);
  124. yield return jsString;
  125. }
  126. }
  127. else if (includeStrings && Target is IDictionary dictionary)
  128. {
  129. // we take values exposed as dictionary keys only
  130. foreach (var key in dictionary.Keys)
  131. {
  132. object? stringKey = key as string;
  133. if (stringKey is not null
  134. || _engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey))
  135. {
  136. var jsString = JsString.Create((string) stringKey!);
  137. yield return jsString;
  138. }
  139. }
  140. }
  141. else if (includeStrings)
  142. {
  143. // we take public properties and fields
  144. var type = ClrType;
  145. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  146. {
  147. var indexParameters = p.GetIndexParameters();
  148. if (indexParameters.Length == 0)
  149. {
  150. var jsString = JsString.Create(p.Name);
  151. yield return jsString;
  152. }
  153. }
  154. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  155. {
  156. var jsString = JsString.Create(f.Name);
  157. yield return jsString;
  158. }
  159. }
  160. }
  161. public override PropertyDescriptor GetOwnProperty(JsValue property)
  162. {
  163. if (TryGetProperty(property, out var x))
  164. {
  165. return x;
  166. }
  167. // if we have array-like or dictionary or expando, we can provide iterator
  168. if (property.IsSymbol())
  169. {
  170. if (property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  171. {
  172. var iteratorFunction = new ClrFunctionInstance(
  173. Engine,
  174. "iterator",
  175. Iterator,
  176. 1,
  177. PropertyFlag.Configurable);
  178. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  179. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  180. return iteratorProperty;
  181. }
  182. // not that safe
  183. return PropertyDescriptor.Undefined;
  184. }
  185. var member = property.ToString();
  186. // if type is dictionary, we cannot enumerate anything other than keys
  187. // and we cannot store accessors as dictionary can change dynamically
  188. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  189. if (isDictionary)
  190. {
  191. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  192. {
  193. var flags = PropertyFlag.Enumerable;
  194. if (_engine.Options.Interop.AllowWrite)
  195. {
  196. flags |= PropertyFlag.Configurable;
  197. }
  198. return new PropertyDescriptor(FromObject(_engine, value), flags);
  199. }
  200. }
  201. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  202. if (result is not null)
  203. {
  204. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  205. }
  206. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member);
  207. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
  208. if (!isDictionary && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined))
  209. {
  210. // cache the accessor for faster subsequent accesses
  211. SetProperty(member, descriptor);
  212. }
  213. return descriptor;
  214. }
  215. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  216. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  217. {
  218. // fast path which uses slow search if not found for some reason
  219. ReflectionAccessor? Factory()
  220. {
  221. return member switch
  222. {
  223. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  224. MethodBase mb => new MethodAccessor(target.GetType(), member.Name, MethodDescriptor.Build(new[] { mb })),
  225. FieldInfo fi => new FieldAccessor(fi),
  226. _ => null
  227. };
  228. }
  229. return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  230. }
  231. internal static Type GetClrType(object obj, Type? type)
  232. {
  233. if (type is null || type == typeof(object))
  234. {
  235. return obj.GetType();
  236. }
  237. else
  238. {
  239. var underlyingType = Nullable.GetUnderlyingType(type);
  240. if (underlyingType is not null)
  241. {
  242. return underlyingType;
  243. }
  244. else
  245. {
  246. return type;
  247. }
  248. }
  249. }
  250. private static JsValue Iterator(JsValue thisObject, JsValue[] arguments)
  251. {
  252. var wrapper = (ObjectWrapper) thisObject;
  253. return wrapper._typeDescriptor.IsDictionary
  254. ? new DictionaryIterator(wrapper._engine, wrapper)
  255. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  256. }
  257. private static JsValue GetLength(JsValue thisObject, JsValue[] arguments)
  258. {
  259. var wrapper = (ObjectWrapper) thisObject;
  260. return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0));
  261. }
  262. internal override ulong GetSmallestIndex(ulong length)
  263. {
  264. return Target is ICollection ? 0 : base.GetSmallestIndex(length);
  265. }
  266. public override bool Equals(object? obj) => Equals(obj as ObjectWrapper);
  267. public override bool Equals(JsValue? other) => Equals(other as ObjectWrapper);
  268. public bool Equals(ObjectWrapper? other)
  269. {
  270. if (ReferenceEquals(null, other))
  271. {
  272. return false;
  273. }
  274. if (ReferenceEquals(this, other))
  275. {
  276. return true;
  277. }
  278. return Equals(Target, other.Target);
  279. }
  280. public override int GetHashCode() => Target.GetHashCode();
  281. private sealed class DictionaryIterator : IteratorInstance
  282. {
  283. private readonly ObjectWrapper _target;
  284. private readonly IEnumerator<JsValue> _enumerator;
  285. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  286. {
  287. _target = target;
  288. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  289. }
  290. public override bool TryIteratorStep(out ObjectInstance nextItem)
  291. {
  292. if (_enumerator.MoveNext())
  293. {
  294. var key = _enumerator.Current;
  295. var value = _target.Get(key);
  296. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine, key, value);
  297. return true;
  298. }
  299. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  300. return false;
  301. }
  302. }
  303. private sealed class EnumerableIterator : IteratorInstance
  304. {
  305. private readonly IEnumerator _enumerator;
  306. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  307. {
  308. _enumerator = target.GetEnumerator();
  309. }
  310. public override void Close(CompletionType completion)
  311. {
  312. (_enumerator as IDisposable)?.Dispose();
  313. base.Close(completion);
  314. }
  315. public override bool TryIteratorStep(out ObjectInstance nextItem)
  316. {
  317. if (_enumerator.MoveNext())
  318. {
  319. var value = _enumerator.Current;
  320. nextItem = IteratorResult.CreateValueIteratorPosition(_engine, FromObject(_engine, value));
  321. return true;
  322. }
  323. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  324. return false;
  325. }
  326. }
  327. }
  328. }