ObjectWrapper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #nullable enable
  2. using System.Collections;
  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. namespace Jint.Runtime.Interop
  12. {
  13. /// <summary>
  14. /// Wraps a CLR instance
  15. /// </summary>
  16. public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper, IEquatable<ObjectWrapper>
  17. {
  18. private readonly TypeDescriptor _typeDescriptor;
  19. public ObjectWrapper(Engine engine, object obj)
  20. : base(engine)
  21. {
  22. Target = obj;
  23. _typeDescriptor = TypeDescriptor.Get(obj.GetType());
  24. if (_typeDescriptor.LengthProperty is not null)
  25. {
  26. // create a forwarder to produce length from Count or Length if one of them is present
  27. var functionInstance = new ClrFunctionInstance(engine, "length", GetLength);
  28. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  29. SetProperty(KnownKeys.Length, descriptor);
  30. }
  31. }
  32. public object Target { get; }
  33. public override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  34. internal override bool HasOriginalIterator => IsArrayLike;
  35. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexedArray;
  36. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  37. {
  38. // check if we can take shortcuts for empty object, no need to generate properties
  39. if (property is JsString stringKey)
  40. {
  41. var member = stringKey.ToString();
  42. if (_properties is null || !_properties.ContainsKey(member))
  43. {
  44. // can try utilize fast path
  45. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  46. if (ReferenceEquals(accessor, ConstantValueAccessor.NullAccessor))
  47. {
  48. // there's no such property, but we can allow extending by calling base
  49. // which will add properties, this allows for example JS class to extend a CLR type
  50. return base.Set(property, value, receiver);
  51. }
  52. // CanPut logic
  53. if (!accessor.Writable || !_engine.Options.Interop.AllowWrite)
  54. {
  55. return false;
  56. }
  57. accessor.SetValue(_engine, Target, value);
  58. return true;
  59. }
  60. }
  61. else if (property is JsSymbol jsSymbol)
  62. {
  63. // symbol addition will never hit any known CLR object properties, so if write is allowed, allow writing symbols too
  64. if (_engine.Options.Interop.AllowWrite)
  65. {
  66. return base.Set(jsSymbol, value, receiver);
  67. }
  68. return false;
  69. }
  70. return SetSlow(property, value);
  71. }
  72. private bool SetSlow(JsValue property, JsValue value)
  73. {
  74. if (!CanPut(property))
  75. {
  76. return false;
  77. }
  78. var ownDesc = GetOwnProperty(property);
  79. ownDesc.Value = value;
  80. return true;
  81. }
  82. public override object ToObject()
  83. {
  84. return Target;
  85. }
  86. public override JsValue Get(JsValue property, JsValue receiver)
  87. {
  88. if (property.IsInteger() && Target is IList list)
  89. {
  90. var index = (int) ((JsNumber) property)._value;
  91. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  92. }
  93. return base.Get(property, receiver);
  94. }
  95. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  96. {
  97. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  98. }
  99. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  100. {
  101. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  102. {
  103. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  104. }
  105. }
  106. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  107. {
  108. // prefer object order, add possible other properties after
  109. var includeStrings = (types & Types.String) != 0;
  110. if (includeStrings && _typeDescriptor.IsStringKeyedGenericDictionary) // expando object for instance
  111. {
  112. var keys = _typeDescriptor.GetKeys(Target);
  113. foreach (var key in keys)
  114. {
  115. var jsString = JsString.Create(key);
  116. yield return jsString;
  117. }
  118. }
  119. else if (includeStrings && Target is IDictionary dictionary)
  120. {
  121. // we take values exposed as dictionary keys only
  122. foreach (var key in dictionary.Keys)
  123. {
  124. object? stringKey = key as string;
  125. if (stringKey is not null
  126. || _engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey))
  127. {
  128. var jsString = JsString.Create((string) stringKey);
  129. yield return jsString;
  130. }
  131. }
  132. }
  133. else if (includeStrings)
  134. {
  135. // we take public properties and fields
  136. var type = Target.GetType();
  137. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  138. {
  139. var indexParameters = p.GetIndexParameters();
  140. if (indexParameters.Length == 0)
  141. {
  142. var jsString = JsString.Create(p.Name);
  143. yield return jsString;
  144. }
  145. }
  146. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  147. {
  148. var jsString = JsString.Create(f.Name);
  149. yield return jsString;
  150. }
  151. }
  152. }
  153. public override PropertyDescriptor GetOwnProperty(JsValue property)
  154. {
  155. if (TryGetProperty(property, out var x))
  156. {
  157. return x;
  158. }
  159. // if we have array-like or dictionary or expando, we can provide iterator
  160. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  161. {
  162. var iteratorFunction = new ClrFunctionInstance(
  163. Engine,
  164. "iterator",
  165. Iterator,
  166. 1,
  167. PropertyFlag.Configurable);
  168. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  169. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  170. return iteratorProperty;
  171. }
  172. var member = property.ToString();
  173. // if type is dictionary, we cannot enumerate anything other than keys
  174. // and we cannot store accessors as dictionary can change dynamically
  175. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  176. if (isDictionary)
  177. {
  178. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  179. {
  180. return new PropertyDescriptor(FromObject(_engine, value), PropertyFlag.OnlyEnumerable);
  181. }
  182. }
  183. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  184. if (result is not null)
  185. {
  186. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  187. }
  188. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  189. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
  190. if (!isDictionary && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined))
  191. {
  192. // cache the accessor for faster subsequent accesses
  193. SetProperty(member, descriptor);
  194. }
  195. return descriptor;
  196. }
  197. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  198. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  199. {
  200. // fast path which uses slow search if not found for some reason
  201. ReflectionAccessor? Factory()
  202. {
  203. return member switch
  204. {
  205. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  206. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  207. FieldInfo fi => new FieldAccessor(fi),
  208. _ => null
  209. };
  210. }
  211. return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  212. }
  213. private static JsValue Iterator(JsValue thisObj, JsValue[] arguments)
  214. {
  215. var wrapper = (ObjectWrapper) thisObj;
  216. return wrapper._typeDescriptor.IsDictionary
  217. ? new DictionaryIterator(wrapper._engine, wrapper)
  218. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  219. }
  220. private static JsValue GetLength(JsValue thisObj, JsValue[] arguments)
  221. {
  222. var wrapper = (ObjectWrapper) thisObj;
  223. return JsNumber.Create((int) wrapper._typeDescriptor.LengthProperty.GetValue(wrapper.Target));
  224. }
  225. internal override ulong GetSmallestIndex(ulong length)
  226. {
  227. return Target is ICollection ? 0 : base.GetSmallestIndex(length);
  228. }
  229. public override bool Equals(JsValue? obj)
  230. {
  231. return Equals(obj as ObjectWrapper);
  232. }
  233. public override bool Equals(object? obj)
  234. {
  235. return Equals(obj as ObjectWrapper);
  236. }
  237. public bool Equals(ObjectWrapper? other)
  238. {
  239. if (ReferenceEquals(null, other))
  240. {
  241. return false;
  242. }
  243. if (ReferenceEquals(this, other))
  244. {
  245. return true;
  246. }
  247. return Equals(Target, other.Target);
  248. }
  249. public override int GetHashCode()
  250. {
  251. return Target?.GetHashCode() ?? 0;
  252. }
  253. private sealed class DictionaryIterator : IteratorInstance
  254. {
  255. private readonly ObjectWrapper _target;
  256. private readonly IEnumerator<JsValue> _enumerator;
  257. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  258. {
  259. _target = target;
  260. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  261. }
  262. public override bool TryIteratorStep(out ObjectInstance nextItem)
  263. {
  264. if (_enumerator.MoveNext())
  265. {
  266. var key = _enumerator.Current;
  267. var value = _target.Get(key);
  268. nextItem = new KeyValueIteratorPosition(_engine, key, value);
  269. return true;
  270. }
  271. nextItem = KeyValueIteratorPosition.Done(_engine);
  272. return false;
  273. }
  274. }
  275. private sealed class EnumerableIterator : IteratorInstance
  276. {
  277. private readonly IEnumerator _enumerator;
  278. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  279. {
  280. _enumerator = target.GetEnumerator();
  281. }
  282. public override bool TryIteratorStep(out ObjectInstance nextItem)
  283. {
  284. if (_enumerator.MoveNext())
  285. {
  286. var value = _enumerator.Current;
  287. nextItem = new ValueIteratorPosition(_engine, FromObject(_engine, value));
  288. return true;
  289. }
  290. nextItem = KeyValueIteratorPosition.Done(_engine);
  291. return false;
  292. }
  293. }
  294. }
  295. }