2
0

ObjectWrapper.cs 16 KB

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