ObjectWrapper.cs 16 KB

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