ObjectWrapper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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, forWrite: true);
  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())
  167. {
  168. if (property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  169. {
  170. var iteratorFunction = new ClrFunctionInstance(
  171. Engine,
  172. "iterator",
  173. Iterator,
  174. 1,
  175. PropertyFlag.Configurable);
  176. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  177. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  178. return iteratorProperty;
  179. }
  180. // not that safe
  181. return PropertyDescriptor.Undefined;
  182. }
  183. var member = property.ToString();
  184. // if type is dictionary, we cannot enumerate anything other than keys
  185. // and we cannot store accessors as dictionary can change dynamically
  186. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  187. if (isDictionary)
  188. {
  189. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  190. {
  191. var flags = PropertyFlag.Enumerable;
  192. if (_engine.Options.Interop.AllowWrite)
  193. {
  194. flags |= PropertyFlag.Configurable;
  195. }
  196. return new PropertyDescriptor(FromObject(_engine, value), flags);
  197. }
  198. }
  199. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  200. if (result is not null)
  201. {
  202. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  203. }
  204. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  205. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
  206. if (!isDictionary && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined))
  207. {
  208. // cache the accessor for faster subsequent accesses
  209. SetProperty(member, descriptor);
  210. }
  211. return descriptor;
  212. }
  213. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  214. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  215. {
  216. // fast path which uses slow search if not found for some reason
  217. ReflectionAccessor? Factory()
  218. {
  219. return member switch
  220. {
  221. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  222. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  223. FieldInfo fi => new FieldAccessor(fi),
  224. _ => null
  225. };
  226. }
  227. return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  228. }
  229. private static JsValue Iterator(JsValue thisObject, JsValue[] arguments)
  230. {
  231. var wrapper = (ObjectWrapper) thisObject;
  232. return wrapper._typeDescriptor.IsDictionary
  233. ? new DictionaryIterator(wrapper._engine, wrapper)
  234. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  235. }
  236. private static JsValue GetLength(JsValue thisObject, JsValue[] arguments)
  237. {
  238. var wrapper = (ObjectWrapper) thisObject;
  239. return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0));
  240. }
  241. internal override ulong GetSmallestIndex(ulong length)
  242. {
  243. return Target is ICollection ? 0 : base.GetSmallestIndex(length);
  244. }
  245. public override bool Equals(JsValue? obj)
  246. {
  247. return Equals(obj as ObjectWrapper);
  248. }
  249. public bool Equals(ObjectWrapper? other)
  250. {
  251. if (ReferenceEquals(null, other))
  252. {
  253. return false;
  254. }
  255. if (ReferenceEquals(this, other))
  256. {
  257. return true;
  258. }
  259. return Equals(Target, other.Target);
  260. }
  261. public override int GetHashCode()
  262. {
  263. return Target?.GetHashCode() ?? 0;
  264. }
  265. private sealed class DictionaryIterator : IteratorInstance
  266. {
  267. private readonly ObjectWrapper _target;
  268. private readonly IEnumerator<JsValue> _enumerator;
  269. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  270. {
  271. _target = target;
  272. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  273. }
  274. public override bool TryIteratorStep(out ObjectInstance nextItem)
  275. {
  276. if (_enumerator.MoveNext())
  277. {
  278. var key = _enumerator.Current;
  279. var value = _target.Get(key);
  280. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine, key, value);
  281. return true;
  282. }
  283. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  284. return false;
  285. }
  286. }
  287. private sealed class EnumerableIterator : IteratorInstance
  288. {
  289. private readonly IEnumerator _enumerator;
  290. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  291. {
  292. _enumerator = target.GetEnumerator();
  293. }
  294. public override void Close(CompletionType completion)
  295. {
  296. (_enumerator as IDisposable)?.Dispose();
  297. base.Close(completion);
  298. }
  299. public override bool TryIteratorStep(out ObjectInstance nextItem)
  300. {
  301. if (_enumerator.MoveNext())
  302. {
  303. var value = _enumerator.Current;
  304. nextItem = IteratorResult.CreateValueIteratorPosition(_engine, FromObject(_engine, value));
  305. return true;
  306. }
  307. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  308. return false;
  309. }
  310. }
  311. }
  312. }