ObjectWrapper.cs 13 KB

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