ObjectWrapper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. #pragma warning disable IL2067
  11. #pragma warning disable IL2072
  12. #pragma warning disable IL2075
  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(
  22. Engine engine,
  23. object obj,
  24. Type? type = null)
  25. : base(engine)
  26. {
  27. Target = obj;
  28. ClrType = GetClrType(obj, type);
  29. _typeDescriptor = TypeDescriptor.Get(ClrType);
  30. if (_typeDescriptor.LengthProperty is not null)
  31. {
  32. // create a forwarder to produce length from Count or Length if one of them is present
  33. var functionInstance = new ClrFunction(engine, "length", GetLength);
  34. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  35. SetProperty(KnownKeys.Length, descriptor);
  36. }
  37. }
  38. public object Target { get; }
  39. internal Type ClrType { get; }
  40. internal override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  41. internal override bool HasOriginalIterator => IsArrayLike;
  42. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexed;
  43. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  44. {
  45. // check if we can take shortcuts for empty object, no need to generate properties
  46. if (property is JsString stringKey)
  47. {
  48. var member = stringKey.ToString();
  49. if (_properties is null || !_properties.ContainsKey(member))
  50. {
  51. // can try utilize fast path
  52. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member, mustBeReadable: false, mustBeWritable: true);
  53. if (ReferenceEquals(accessor, ConstantValueAccessor.NullAccessor))
  54. {
  55. // there's no such property, but we can allow extending by calling base
  56. // which will add properties, this allows for example JS class to extend a CLR type
  57. return base.Set(property, value, receiver);
  58. }
  59. // CanPut logic
  60. if (!accessor.Writable || !_engine.Options.Interop.AllowWrite)
  61. {
  62. return false;
  63. }
  64. accessor.SetValue(_engine, Target, value);
  65. return true;
  66. }
  67. }
  68. else if (property is JsSymbol jsSymbol)
  69. {
  70. // symbol addition will never hit any known CLR object properties, so if write is allowed, allow writing symbols too
  71. if (_engine.Options.Interop.AllowWrite)
  72. {
  73. return base.Set(jsSymbol, value, receiver);
  74. }
  75. return false;
  76. }
  77. return SetSlow(property, value);
  78. }
  79. private bool SetSlow(JsValue property, JsValue value)
  80. {
  81. if (!CanPut(property))
  82. {
  83. return false;
  84. }
  85. var ownDesc = GetOwnProperty(property);
  86. ownDesc.Value = value;
  87. return true;
  88. }
  89. public override object ToObject()
  90. {
  91. return Target;
  92. }
  93. public override void RemoveOwnProperty(JsValue property)
  94. {
  95. if (_engine.Options.Interop.AllowWrite && property is JsString jsString)
  96. {
  97. _typeDescriptor.Remove(Target, jsString.ToString());
  98. }
  99. }
  100. public override JsValue Get(JsValue property, JsValue receiver)
  101. {
  102. if (property.IsInteger() && Target is IList list)
  103. {
  104. var index = (int) ((JsNumber) property)._value;
  105. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  106. }
  107. var desc = GetOwnProperty(property, mustBeReadable: true, mustBeWritable: false);
  108. if (desc != PropertyDescriptor.Undefined)
  109. {
  110. return UnwrapJsValue(desc, receiver);
  111. }
  112. return Prototype?.Get(property, receiver) ?? Undefined;
  113. }
  114. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.Empty | Types.String | Types.Symbol)
  115. {
  116. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  117. }
  118. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  119. {
  120. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  121. {
  122. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  123. }
  124. }
  125. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  126. {
  127. // prefer object order, add possible other properties after
  128. var includeStrings = (types & Types.String) != Types.Empty;
  129. if (includeStrings && _typeDescriptor.IsStringKeyedGenericDictionary) // expando object for instance
  130. {
  131. var keys = _typeDescriptor.GetKeys(Target);
  132. foreach (var key in keys)
  133. {
  134. var jsString = JsString.Create(key);
  135. yield return jsString;
  136. }
  137. }
  138. else if (includeStrings && Target is IDictionary dictionary)
  139. {
  140. // we take values exposed as dictionary keys only
  141. foreach (var key in dictionary.Keys)
  142. {
  143. object? stringKey = key as string;
  144. if (stringKey is not null
  145. || _engine.TypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey))
  146. {
  147. var jsString = JsString.Create((string) stringKey!);
  148. yield return jsString;
  149. }
  150. }
  151. }
  152. else if (includeStrings)
  153. {
  154. // we take public properties and fields
  155. foreach (var p in ClrType.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  156. {
  157. var indexParameters = p.GetIndexParameters();
  158. if (indexParameters.Length == 0)
  159. {
  160. var jsString = JsString.Create(p.Name);
  161. yield return jsString;
  162. }
  163. }
  164. foreach (var f in ClrType.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  165. {
  166. var jsString = JsString.Create(f.Name);
  167. yield return jsString;
  168. }
  169. }
  170. }
  171. public override PropertyDescriptor GetOwnProperty(JsValue property)
  172. {
  173. // we do not know if we need to read or write
  174. return GetOwnProperty(property, mustBeReadable: false, mustBeWritable: false);
  175. }
  176. private PropertyDescriptor GetOwnProperty(JsValue property, bool mustBeReadable, bool mustBeWritable)
  177. {
  178. if (TryGetProperty(property, out var x))
  179. {
  180. return x;
  181. }
  182. // if we have array-like or dictionary or expando, we can provide iterator
  183. if (property.IsSymbol())
  184. {
  185. if (property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  186. {
  187. var iteratorFunction = new ClrFunction(
  188. Engine,
  189. "iterator",
  190. Iterator,
  191. 1,
  192. PropertyFlag.Configurable);
  193. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  194. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  195. return iteratorProperty;
  196. }
  197. // not that safe
  198. return PropertyDescriptor.Undefined;
  199. }
  200. var member = property.ToString();
  201. // if type is dictionary, we cannot enumerate anything other than keys
  202. // and we cannot store accessors as dictionary can change dynamically
  203. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  204. if (isDictionary)
  205. {
  206. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  207. {
  208. var flags = PropertyFlag.Enumerable;
  209. if (_engine.Options.Interop.AllowWrite)
  210. {
  211. flags |= PropertyFlag.Configurable;
  212. }
  213. return new PropertyDescriptor(FromObject(_engine, value), flags);
  214. }
  215. }
  216. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  217. if (result is not null)
  218. {
  219. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  220. }
  221. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member, mustBeReadable, mustBeWritable);
  222. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
  223. if (!isDictionary
  224. && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined)
  225. && (!mustBeReadable || accessor.Readable)
  226. && (!mustBeWritable || accessor.Writable))
  227. {
  228. // cache the accessor for faster subsequent accesses
  229. SetProperty(member, descriptor);
  230. }
  231. return descriptor;
  232. }
  233. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  234. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  235. {
  236. // fast path which uses slow search if not found for some reason
  237. ReflectionAccessor? Factory()
  238. {
  239. return member switch
  240. {
  241. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  242. MethodBase mb => new MethodAccessor(target.GetType(), member.Name, MethodDescriptor.Build(new[] { mb })),
  243. FieldInfo fi => new FieldAccessor(fi),
  244. _ => null
  245. };
  246. }
  247. var accessor = engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, mustBeReadable: false, mustBeWritable: false, Factory);
  248. return accessor.CreatePropertyDescriptor(engine, target);
  249. }
  250. internal static Type GetClrType(object obj, Type? type)
  251. {
  252. if (type is null || type == typeof(object))
  253. {
  254. return obj.GetType();
  255. }
  256. else
  257. {
  258. var underlyingType = Nullable.GetUnderlyingType(type);
  259. if (underlyingType is not null)
  260. {
  261. return underlyingType;
  262. }
  263. else
  264. {
  265. return type;
  266. }
  267. }
  268. }
  269. private static JsValue Iterator(JsValue thisObject, JsValue[] arguments)
  270. {
  271. var wrapper = (ObjectWrapper) thisObject;
  272. return wrapper._typeDescriptor.IsDictionary
  273. ? new DictionaryIterator(wrapper._engine, wrapper)
  274. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  275. }
  276. private static JsNumber GetLength(JsValue thisObject, JsValue[] arguments)
  277. {
  278. var wrapper = (ObjectWrapper) thisObject;
  279. return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0));
  280. }
  281. internal override ulong GetSmallestIndex(ulong length)
  282. {
  283. return Target is ICollection ? 0 : base.GetSmallestIndex(length);
  284. }
  285. public override bool Equals(object? obj) => Equals(obj as ObjectWrapper);
  286. public override bool Equals(JsValue? other) => Equals(other as ObjectWrapper);
  287. public bool Equals(ObjectWrapper? other)
  288. {
  289. if (ReferenceEquals(null, other))
  290. {
  291. return false;
  292. }
  293. if (ReferenceEquals(this, other))
  294. {
  295. return true;
  296. }
  297. return Equals(Target, other.Target);
  298. }
  299. public override int GetHashCode() => Target.GetHashCode();
  300. private sealed class DictionaryIterator : IteratorInstance
  301. {
  302. private readonly ObjectWrapper _target;
  303. private readonly IEnumerator<JsValue> _enumerator;
  304. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  305. {
  306. _target = target;
  307. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  308. }
  309. public override bool TryIteratorStep(out ObjectInstance nextItem)
  310. {
  311. if (_enumerator.MoveNext())
  312. {
  313. var key = _enumerator.Current;
  314. var value = _target.Get(key);
  315. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine, key, value);
  316. return true;
  317. }
  318. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  319. return false;
  320. }
  321. }
  322. private sealed class EnumerableIterator : IteratorInstance
  323. {
  324. private readonly IEnumerator _enumerator;
  325. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  326. {
  327. _enumerator = target.GetEnumerator();
  328. }
  329. public override void Close(CompletionType completion)
  330. {
  331. (_enumerator as IDisposable)?.Dispose();
  332. base.Close(completion);
  333. }
  334. public override bool TryIteratorStep(out ObjectInstance nextItem)
  335. {
  336. if (_enumerator.MoveNext())
  337. {
  338. var value = _enumerator.Current;
  339. nextItem = IteratorResult.CreateValueIteratorPosition(_engine, FromObject(_engine, value));
  340. return true;
  341. }
  342. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  343. return false;
  344. }
  345. }
  346. }
  347. }