ObjectWrapper.cs 13 KB

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