ObjectWrapper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. else if (property is JsSymbol jsSymbol)
  64. {
  65. // symbol addition will never hit any known CLR object properties, so if write is allowed, allow writing symbols too
  66. if (_engine.Options.Interop.AllowWrite)
  67. {
  68. return base.Set(jsSymbol, value, receiver);
  69. }
  70. return false;
  71. }
  72. return SetSlow(property, value);
  73. }
  74. private bool SetSlow(JsValue property, JsValue value)
  75. {
  76. if (!CanPut(property))
  77. {
  78. return false;
  79. }
  80. var ownDesc = GetOwnProperty(property);
  81. if (ownDesc == null)
  82. {
  83. return false;
  84. }
  85. ownDesc.Value = value;
  86. return true;
  87. }
  88. public override object ToObject()
  89. {
  90. return Target;
  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. var basePropertyKeys = base.GetOwnPropertyKeys(types);
  115. // prefer object order, add possible other properties after
  116. var processed = basePropertyKeys.Count > 0 ? new HashSet<JsValue>() : null;
  117. var includeStrings = (types & Types.String) != 0;
  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. processed?.Add(jsString);
  125. yield return jsString;
  126. }
  127. }
  128. else if (includeStrings && Target is IDictionary dictionary)
  129. {
  130. // we take values exposed as dictionary keys only
  131. foreach (var key in dictionary.Keys)
  132. {
  133. object stringKey = key as string;
  134. if (stringKey is not null
  135. || _engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey))
  136. {
  137. var jsString = JsString.Create((string) stringKey);
  138. processed?.Add(jsString);
  139. yield return jsString;
  140. }
  141. }
  142. }
  143. else if (includeStrings)
  144. {
  145. // we take public properties and fields
  146. var type = Target.GetType();
  147. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  148. {
  149. var indexParameters = p.GetIndexParameters();
  150. if (indexParameters.Length == 0)
  151. {
  152. var jsString = JsString.Create(p.Name);
  153. processed?.Add(jsString);
  154. yield return jsString;
  155. }
  156. }
  157. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  158. {
  159. var jsString = JsString.Create(f.Name);
  160. processed?.Add(jsString);
  161. yield return jsString;
  162. }
  163. }
  164. if (processed != null)
  165. {
  166. // we have base keys
  167. for (var i = 0; i < basePropertyKeys.Count; i++)
  168. {
  169. var key = basePropertyKeys[i];
  170. if (processed.Add(key))
  171. {
  172. yield return key;
  173. }
  174. }
  175. }
  176. }
  177. public override PropertyDescriptor GetOwnProperty(JsValue property)
  178. {
  179. if (TryGetProperty(property, out var x))
  180. {
  181. return x;
  182. }
  183. // if we have array-like or dictionary or expando, we can provide iterator
  184. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  185. {
  186. var iteratorFunction = new ClrFunctionInstance(
  187. Engine,
  188. "iterator",
  189. Iterator,
  190. 1,
  191. PropertyFlag.Configurable);
  192. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  193. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  194. return iteratorProperty;
  195. }
  196. var member = property.ToString();
  197. // if type is dictionary, we cannot enumerate anything other than keys
  198. // and we cannot store accessors as dictionary can change dynamically
  199. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  200. if (isDictionary)
  201. {
  202. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  203. {
  204. return new PropertyDescriptor(FromObject(_engine, value), PropertyFlag.OnlyEnumerable);
  205. }
  206. }
  207. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  208. if (result is not null)
  209. {
  210. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  211. }
  212. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  213. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
  214. if (!isDictionary)
  215. {
  216. SetProperty(member, descriptor);
  217. }
  218. return descriptor;
  219. }
  220. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  221. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  222. {
  223. // fast path which uses slow search if not found for some reason
  224. ReflectionAccessor Factory()
  225. {
  226. return member switch
  227. {
  228. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  229. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  230. FieldInfo fi => new FieldAccessor(fi),
  231. _ => null
  232. };
  233. }
  234. return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  235. }
  236. private static JsValue Iterator(JsValue thisObj, JsValue[] arguments)
  237. {
  238. var wrapper = (ObjectWrapper) thisObj;
  239. return wrapper._typeDescriptor.IsDictionary
  240. ? new DictionaryIterator(wrapper._engine, wrapper)
  241. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  242. }
  243. private static JsValue GetLength(JsValue thisObj, JsValue[] arguments)
  244. {
  245. var wrapper = (ObjectWrapper) thisObj;
  246. return JsNumber.Create((int) wrapper._typeDescriptor.LengthProperty.GetValue(wrapper.Target));
  247. }
  248. public override bool Equals(JsValue obj)
  249. {
  250. return Equals(obj as ObjectWrapper);
  251. }
  252. public override bool Equals(object obj)
  253. {
  254. return Equals(obj as ObjectWrapper);
  255. }
  256. public bool Equals(ObjectWrapper other)
  257. {
  258. if (ReferenceEquals(null, other))
  259. {
  260. return false;
  261. }
  262. if (ReferenceEquals(this, other))
  263. {
  264. return true;
  265. }
  266. return Equals(Target, other.Target);
  267. }
  268. public override int GetHashCode()
  269. {
  270. return Target?.GetHashCode() ?? 0;
  271. }
  272. private sealed class DictionaryIterator : IteratorInstance
  273. {
  274. private readonly ObjectWrapper _target;
  275. private readonly IEnumerator<JsValue> _enumerator;
  276. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  277. {
  278. _target = target;
  279. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  280. }
  281. public override bool TryIteratorStep(out ObjectInstance nextItem)
  282. {
  283. if (_enumerator.MoveNext())
  284. {
  285. var key = _enumerator.Current;
  286. var value = _target.Get(key);
  287. nextItem = new KeyValueIteratorPosition(_engine, key, value);
  288. return true;
  289. }
  290. nextItem = KeyValueIteratorPosition.Done(_engine);
  291. return false;
  292. }
  293. }
  294. private sealed class EnumerableIterator : IteratorInstance
  295. {
  296. private readonly IEnumerator _enumerator;
  297. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  298. {
  299. _enumerator = target.GetEnumerator();
  300. }
  301. public override bool TryIteratorStep(out ObjectInstance nextItem)
  302. {
  303. if (_enumerator.MoveNext())
  304. {
  305. var value = _enumerator.Current;
  306. nextItem = new ValueIteratorPosition(_engine, FromObject(_engine, value));
  307. return true;
  308. }
  309. nextItem = KeyValueIteratorPosition.Done(_engine);
  310. return false;
  311. }
  312. }
  313. }
  314. }