ObjectWrapper.cs 13 KB

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