ObjectWrapper.cs 18 KB

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