ObjectWrapper.cs 18 KB

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