ObjectWrapper.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Reflection;
  6. using Jint.Native;
  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.IsArrayLike)
  25. {
  26. // create a forwarder to produce length from Count or Length if one of them is present
  27. var lengthProperty = obj.GetType().GetProperty("Count") ?? obj.GetType().GetProperty("Length");
  28. if (lengthProperty is null)
  29. {
  30. return;
  31. }
  32. var functionInstance = new ClrFunctionInstance(engine, "length", (_, _) => JsNumber.Create((int) lengthProperty.GetValue(obj)));
  33. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  34. SetProperty(KnownKeys.Length, descriptor);
  35. }
  36. }
  37. public object Target { get; }
  38. public override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  39. internal override bool HasOriginalIterator => IsArrayLike;
  40. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexedArray;
  41. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  42. {
  43. // check if we can take shortcuts for empty object, no need to generate properties
  44. if (property is JsString stringKey)
  45. {
  46. var member = stringKey.ToString();
  47. if (_properties is null || !_properties.ContainsKey(member))
  48. {
  49. // can try utilize fast path
  50. var accessor = _engine.Options._TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  51. // CanPut logic
  52. if (!accessor.Writable || !_engine.Options._IsClrWriteAllowed)
  53. {
  54. return false;
  55. }
  56. accessor.SetValue(_engine, Target, value);
  57. return true;
  58. }
  59. }
  60. return SetSlow(property, value);
  61. }
  62. private bool SetSlow(JsValue property, JsValue value)
  63. {
  64. if (!CanPut(property))
  65. {
  66. return false;
  67. }
  68. var ownDesc = GetOwnProperty(property);
  69. if (ownDesc == null)
  70. {
  71. return false;
  72. }
  73. ownDesc.Value = value;
  74. return true;
  75. }
  76. public override JsValue Get(JsValue property, JsValue receiver)
  77. {
  78. if (property.IsInteger() && Target is IList list)
  79. {
  80. var index = (int) ((JsNumber) property)._value;
  81. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  82. }
  83. if (property.IsSymbol() && property != GlobalSymbolRegistry.Iterator)
  84. {
  85. // wrapped objects cannot have symbol properties
  86. return Undefined;
  87. }
  88. if (property is JsString stringKey)
  89. {
  90. var member = stringKey.ToString();
  91. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  92. if (result is not null)
  93. {
  94. return result;
  95. }
  96. if (_properties is null || !_properties.ContainsKey(member))
  97. {
  98. // can try utilize fast path
  99. var accessor = _engine.Options._TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  100. var value = accessor.GetValue(_engine, Target);
  101. if (value is not null)
  102. {
  103. return FromObject(_engine, value);
  104. }
  105. }
  106. }
  107. return base.Get(property, receiver);
  108. }
  109. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  110. {
  111. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  112. }
  113. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  114. {
  115. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  116. {
  117. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  118. }
  119. }
  120. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  121. {
  122. var basePropertyKeys = base.GetOwnPropertyKeys(types);
  123. // prefer object order, add possible other properties after
  124. var processed = basePropertyKeys.Count > 0 ? new HashSet<JsValue>() : null;
  125. var includeStrings = (types & Types.String) != 0;
  126. if (includeStrings && Target is IDictionary<string, object> stringKeyedDictionary) // expando object for instance
  127. {
  128. foreach (var key in stringKeyedDictionary.Keys)
  129. {
  130. var jsString = JsString.Create(key);
  131. processed?.Add(jsString);
  132. yield return jsString;
  133. }
  134. }
  135. else if (includeStrings && Target is IDictionary dictionary)
  136. {
  137. // we take values exposed as dictionary keys only
  138. foreach (var key in dictionary.Keys)
  139. {
  140. if (_engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out var stringKey))
  141. {
  142. var jsString = JsString.Create((string) stringKey);
  143. processed?.Add(jsString);
  144. yield return jsString;
  145. }
  146. }
  147. }
  148. else if (includeStrings)
  149. {
  150. // we take public properties and fields
  151. var type = Target.GetType();
  152. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  153. {
  154. var indexParameters = p.GetIndexParameters();
  155. if (indexParameters.Length == 0)
  156. {
  157. var jsString = JsString.Create(p.Name);
  158. processed?.Add(jsString);
  159. yield return jsString;
  160. }
  161. }
  162. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  163. {
  164. var jsString = JsString.Create(f.Name);
  165. processed?.Add(jsString);
  166. yield return jsString;
  167. }
  168. }
  169. if (processed != null)
  170. {
  171. // we have base keys
  172. for (var i = 0; i < basePropertyKeys.Count; i++)
  173. {
  174. var key = basePropertyKeys[i];
  175. if (processed.Add(key))
  176. {
  177. yield return key;
  178. }
  179. }
  180. }
  181. }
  182. public override PropertyDescriptor GetOwnProperty(JsValue property)
  183. {
  184. if (TryGetProperty(property, out var x))
  185. {
  186. return x;
  187. }
  188. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator)
  189. {
  190. var iteratorFunction = new ClrFunctionInstance(
  191. Engine, "iterator",
  192. (thisObject, arguments) => _engine.Realm.Intrinsics.ArrayIteratorPrototype.Construct(this, intrinsics => intrinsics.IteratorPrototype),
  193. 1,
  194. PropertyFlag.Configurable);
  195. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  196. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  197. return iteratorProperty;
  198. }
  199. var member = property.ToString();
  200. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  201. if (result is not null)
  202. {
  203. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  204. }
  205. var accessor = _engine.Options._TypeResolver.GetAccessor(_engine, Target.GetType(), member);
  206. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target);
  207. SetProperty(member, descriptor);
  208. return descriptor;
  209. }
  210. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  211. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  212. {
  213. // fast path which uses slow search if not found for some reason
  214. ReflectionAccessor Factory()
  215. {
  216. return member switch
  217. {
  218. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  219. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  220. FieldInfo fi => new FieldAccessor(fi),
  221. _ => null
  222. };
  223. }
  224. return engine.Options._TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  225. }
  226. public override bool Equals(JsValue obj)
  227. {
  228. return Equals(obj as ObjectWrapper);
  229. }
  230. public override bool Equals(object obj)
  231. {
  232. return Equals(obj as ObjectWrapper);
  233. }
  234. public bool Equals(ObjectWrapper other)
  235. {
  236. if (ReferenceEquals(null, other))
  237. {
  238. return false;
  239. }
  240. if (ReferenceEquals(this, other))
  241. {
  242. return true;
  243. }
  244. return Equals(Target, other.Target);
  245. }
  246. public override int GetHashCode()
  247. {
  248. return Target?.GetHashCode() ?? 0;
  249. }
  250. }
  251. }