ObjectWrapper.cs 18 KB

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