ObjectWrapper.cs 13 KB

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