ObjectWrapper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Dynamic;
  5. using System.Globalization;
  6. using System.Reflection;
  7. using System.Threading;
  8. using Jint.Native;
  9. using Jint.Native.Object;
  10. using Jint.Native.Symbol;
  11. using Jint.Runtime.Descriptors;
  12. using Jint.Runtime.Interop.Reflection;
  13. namespace Jint.Runtime.Interop
  14. {
  15. /// <summary>
  16. /// Wraps a CLR instance
  17. /// </summary>
  18. public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper
  19. {
  20. private readonly TypeDescriptor _typeDescriptor;
  21. public ObjectWrapper(Engine engine, object obj)
  22. : base(engine)
  23. {
  24. Target = obj;
  25. _typeDescriptor = TypeDescriptor.Get(obj.GetType());
  26. if (_typeDescriptor.IsArrayLike)
  27. {
  28. // create a forwarder to produce length from Count or Length if one of them is present
  29. var lengthProperty = obj.GetType().GetProperty("Count") ?? obj.GetType().GetProperty("Length");
  30. if (lengthProperty is null)
  31. {
  32. return;
  33. }
  34. var functionInstance = new ClrFunctionInstance(engine, "length", (_, _) => JsNumber.Create((int) lengthProperty.GetValue(obj)));
  35. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  36. SetProperty(KnownKeys.Length, descriptor);
  37. }
  38. }
  39. public object Target { get; }
  40. public override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  41. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexedArray;
  42. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  43. {
  44. // check if we can take shortcuts for empty object, no need to generate properties
  45. if (property is JsString stringKey)
  46. {
  47. var member = stringKey.ToString();
  48. if (_properties is null || !_properties.ContainsKey(member))
  49. {
  50. // can try utilize fast path
  51. var accessor = GetAccessor(_engine, Target.GetType(), member);
  52. // CanPut logic
  53. if (!accessor.Writable || !_engine.Options._IsClrWriteAllowed)
  54. {
  55. return false;
  56. }
  57. accessor.SetValue(_engine, Target, value);
  58. return true;
  59. }
  60. }
  61. return SetSlow(property, value);
  62. }
  63. private bool SetSlow(JsValue property, JsValue value)
  64. {
  65. if (!CanPut(property))
  66. {
  67. return false;
  68. }
  69. var ownDesc = GetOwnProperty(property);
  70. if (ownDesc == null)
  71. {
  72. return false;
  73. }
  74. ownDesc.Value = value;
  75. return true;
  76. }
  77. public override JsValue Get(JsValue property, JsValue receiver)
  78. {
  79. if (property.IsInteger() && Target is IList list)
  80. {
  81. var index = (int) ((JsNumber) property)._value;
  82. return (uint) index < list.Count ? FromObject(_engine, list[index]) : Undefined;
  83. }
  84. if (property.IsSymbol() && property != GlobalSymbolRegistry.Iterator)
  85. {
  86. // wrapped objects cannot have symbol properties
  87. return Undefined;
  88. }
  89. if (property is JsString stringKey)
  90. {
  91. var member = stringKey.ToString();
  92. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  93. if (result is not null)
  94. {
  95. return result;
  96. }
  97. if (_properties is null || !_properties.ContainsKey(member))
  98. {
  99. // can try utilize fast path
  100. var accessor = GetAccessor(_engine, Target.GetType(), member);
  101. var value = accessor.GetValue(_engine, Target);
  102. if (value is not null)
  103. {
  104. return FromObject(_engine, value);
  105. }
  106. }
  107. }
  108. return base.Get(property, receiver);
  109. }
  110. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.None | Types.String | Types.Symbol)
  111. {
  112. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  113. }
  114. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  115. {
  116. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  117. {
  118. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  119. }
  120. }
  121. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  122. {
  123. var basePropertyKeys = base.GetOwnPropertyKeys(types);
  124. // prefer object order, add possible other properties after
  125. var processed = basePropertyKeys.Count > 0 ? new HashSet<JsValue>() : null;
  126. var includeStrings = (types & Types.String) != 0;
  127. if (includeStrings && Target is IDictionary<string, object> stringKeyedDictionary) // expando object for instance
  128. {
  129. foreach (var key in stringKeyedDictionary.Keys)
  130. {
  131. var jsString = JsString.Create(key);
  132. processed?.Add(jsString);
  133. yield return jsString;
  134. }
  135. }
  136. else if (includeStrings && Target is IDictionary dictionary)
  137. {
  138. // we take values exposed as dictionary keys only
  139. foreach (var key in dictionary.Keys)
  140. {
  141. if (_engine.ClrTypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out var stringKey))
  142. {
  143. var jsString = JsString.Create((string) stringKey);
  144. processed?.Add(jsString);
  145. yield return jsString;
  146. }
  147. }
  148. }
  149. else if (includeStrings)
  150. {
  151. // we take public properties and fields
  152. var type = Target.GetType();
  153. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  154. {
  155. var indexParameters = p.GetIndexParameters();
  156. if (indexParameters.Length == 0)
  157. {
  158. var jsString = JsString.Create(p.Name);
  159. processed?.Add(jsString);
  160. yield return jsString;
  161. }
  162. }
  163. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  164. {
  165. var jsString = JsString.Create(f.Name);
  166. processed?.Add(jsString);
  167. yield return jsString;
  168. }
  169. }
  170. if (processed != null)
  171. {
  172. // we have base keys
  173. for (var i = 0; i < basePropertyKeys.Count; i++)
  174. {
  175. var key = basePropertyKeys[i];
  176. if (processed.Add(key))
  177. {
  178. yield return key;
  179. }
  180. }
  181. }
  182. }
  183. public override PropertyDescriptor GetOwnProperty(JsValue property)
  184. {
  185. if (TryGetProperty(property, out var x))
  186. {
  187. return x;
  188. }
  189. if (property.IsSymbol() && property == GlobalSymbolRegistry.Iterator)
  190. {
  191. var iteratorFunction = new ClrFunctionInstance(Engine, "iterator", (thisObject, arguments) => _engine.Iterator.Construct(this), 1, PropertyFlag.Configurable);
  192. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  193. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  194. return iteratorProperty;
  195. }
  196. var member = property.ToString();
  197. var result = Engine.Options._MemberAccessor?.Invoke(Engine, Target, member);
  198. if (result is not null)
  199. {
  200. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  201. }
  202. var accessor = GetAccessor(_engine, Target.GetType(), member);
  203. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target);
  204. SetProperty(member, descriptor);
  205. return descriptor;
  206. }
  207. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  208. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  209. {
  210. // fast path which uses slow search if not found for some reason
  211. ReflectionAccessor Factory()
  212. {
  213. return member switch
  214. {
  215. PropertyInfo pi => new PropertyAccessor(pi.Name, pi),
  216. MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})),
  217. FieldInfo fi => new FieldAccessor(fi),
  218. _ => null
  219. };
  220. }
  221. return GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target);
  222. }
  223. private static ReflectionAccessor GetAccessor(Engine engine, Type type, string member, Func<ReflectionAccessor> accessorFactory = null)
  224. {
  225. var key = new ClrPropertyDescriptorFactoriesKey(type, member);
  226. var factories = Engine.ReflectionAccessors;
  227. if (factories.TryGetValue(key, out var accessor))
  228. {
  229. return accessor;
  230. }
  231. accessor = accessorFactory?.Invoke() ?? ResolvePropertyDescriptorFactory(engine, type, member);
  232. // racy, we don't care, worst case we'll catch up later
  233. Interlocked.CompareExchange(ref Engine.ReflectionAccessors,
  234. new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(factories)
  235. {
  236. [key] = accessor
  237. }, factories);
  238. return accessor;
  239. }
  240. private static ReflectionAccessor ResolvePropertyDescriptorFactory(Engine engine, Type type, string memberName)
  241. {
  242. var isNumber = uint.TryParse(memberName, out _);
  243. // we can always check indexer if there's one, and then fall back to properties if indexer returns null
  244. IndexerAccessor.TryFindIndexer(engine, type, memberName, out var indexerAccessor, out var indexer);
  245. // properties and fields cannot be numbers
  246. if (!isNumber && TryFindStringPropertyAccessor(type, memberName, indexer, out var temp))
  247. {
  248. return temp;
  249. }
  250. if (typeof(DynamicObject).IsAssignableFrom(type))
  251. {
  252. return new DynamicObjectAccessor(type, memberName);
  253. }
  254. // if no methods are found check if target implemented indexing
  255. if (indexerAccessor != null)
  256. {
  257. return indexerAccessor;
  258. }
  259. // try to find a single explicit property implementation
  260. List<PropertyInfo> list = null;
  261. foreach (Type iface in type.GetInterfaces())
  262. {
  263. foreach (var iprop in iface.GetProperties())
  264. {
  265. if (EqualsIgnoreCasing(iprop.Name, memberName))
  266. {
  267. list ??= new List<PropertyInfo>();
  268. list.Add(iprop);
  269. }
  270. }
  271. }
  272. if (list?.Count == 1)
  273. {
  274. return new PropertyAccessor(memberName, list[0]);
  275. }
  276. // try to find explicit method implementations
  277. List<MethodInfo> explicitMethods = null;
  278. foreach (Type iface in type.GetInterfaces())
  279. {
  280. foreach (var imethod in iface.GetMethods())
  281. {
  282. if (EqualsIgnoreCasing(imethod.Name, memberName))
  283. {
  284. explicitMethods ??= new List<MethodInfo>();
  285. explicitMethods.Add(imethod);
  286. }
  287. }
  288. }
  289. if (explicitMethods?.Count > 0)
  290. {
  291. return new MethodAccessor(MethodDescriptor.Build(explicitMethods));
  292. }
  293. // try to find explicit indexer implementations
  294. foreach (var interfaceType in type.GetInterfaces())
  295. {
  296. if (IndexerAccessor.TryFindIndexer(engine, interfaceType, memberName, out var accessor, out _))
  297. {
  298. return accessor;
  299. }
  300. }
  301. if (engine.Options._extensionMethods.TryGetExtensionMethods(type, out var extensionMethods))
  302. {
  303. var matches = new List<MethodInfo>();
  304. foreach (var method in extensionMethods)
  305. {
  306. if (EqualsIgnoreCasing(method.Name, memberName))
  307. {
  308. matches.Add(method);
  309. }
  310. }
  311. if (matches.Count > 0)
  312. {
  313. return new MethodAccessor(MethodDescriptor.Build(matches));
  314. }
  315. }
  316. return ConstantValueAccessor.NullAccessor;
  317. }
  318. private static bool TryFindStringPropertyAccessor(
  319. Type type,
  320. string memberName,
  321. PropertyInfo indexerToTry,
  322. out ReflectionAccessor wrapper)
  323. {
  324. // look for a property, bit be wary of indexers, we don't want indexers which have name "Item" to take precedence
  325. PropertyInfo property = null;
  326. foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  327. {
  328. // only if it's not an indexer, we can do case-ignoring matches
  329. var isStandardIndexer = p.GetIndexParameters().Length == 1 && p.Name == "Item";
  330. if (!isStandardIndexer && EqualsIgnoreCasing(p.Name, memberName))
  331. {
  332. property = p;
  333. break;
  334. }
  335. }
  336. if (property != null)
  337. {
  338. wrapper = new PropertyAccessor(memberName, property, indexerToTry);
  339. return true;
  340. }
  341. // look for a field
  342. FieldInfo field = null;
  343. foreach (var f in type.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  344. {
  345. if (EqualsIgnoreCasing(f.Name, memberName))
  346. {
  347. field = f;
  348. break;
  349. }
  350. }
  351. if (field != null)
  352. {
  353. wrapper = new FieldAccessor(field, memberName, indexerToTry);
  354. return true;
  355. }
  356. // if no properties were found then look for a method
  357. List<MethodInfo> methods = null;
  358. foreach (var m in type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
  359. {
  360. if (EqualsIgnoreCasing(m.Name, memberName))
  361. {
  362. methods ??= new List<MethodInfo>();
  363. methods.Add(m);
  364. }
  365. }
  366. if (methods?.Count > 0)
  367. {
  368. wrapper = new MethodAccessor(MethodDescriptor.Build(methods));
  369. return true;
  370. }
  371. wrapper = default;
  372. return false;
  373. }
  374. private static bool EqualsIgnoreCasing(string s1, string s2)
  375. {
  376. if (s1.Length != s2.Length)
  377. {
  378. return false;
  379. }
  380. var equals = false;
  381. if (s1.Length > 0)
  382. {
  383. equals = char.ToLowerInvariant(s1[0]) == char.ToLowerInvariant(s2[0]);
  384. }
  385. if (@equals && s1.Length > 1)
  386. {
  387. #if NETSTANDARD2_1
  388. equals = s1.AsSpan(1).SequenceEqual(s2.AsSpan(1));
  389. #else
  390. equals = s1.Substring(1) == s2.Substring(1);
  391. #endif
  392. }
  393. return equals;
  394. }
  395. }
  396. }