ObjectWrapper.cs 17 KB

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